content
stringlengths
7
1.05M
""" [9/10/2014] Challenge #179 [Intermediate] Roguelike - The traveller Game https://www.reddit.com/r/dailyprogrammer/comments/2g1c80/9102014_challenge_179_intermediate_roguelike_the/ #Description: So I was fooling around once with an idea to make a fun Rogue like game. If you do not know what a Rogue Like is check out [Wikipedia Article] (http://en.wikipedia.org/wiki/Roguelike) on what it is about. I got this really weak start at just trying to generate a more graphical approach than ASCII text. If you want to see my attempt. Check out my incomplete project [FORGE] (http://coderd00d.com/Forge/index.html) For this challenge you will have to develop a character moving in a rogue like environment. So the design requirements. * 1 Hero character who moves up/down/left/right in a box map. * Map must have boundary elements to contain it -- Walls/Water/Moutains/Whatever you come up with * Hero does not have to be a person. Could be a spaceship/sea creature/whatever - Just has to move up/down/left/right on a 2-D map * Map has to be 20x20. The boundary are some element which prevents passage like a wall, water or blackholes. Whatever fits your theme. * Your hero has 100 movement points. Each time they move up/down/left/right they lose 1 movement points. When they reach 0 movement points the game ends. * Random elements are generated in the room. Gold. Treasure. Plants. Towns. Caves. Whatever. When the hero reaches that point they score a point. You must have 100 random elements. * At the end of the game when your hero is out of movement. The score is based on how many elements you are able to move to. The higher the score the better. * Hero starts either in a fixed room spot or random spot. I leave it to you to decide. #input: Some keyboard/other method for moving a hero up/down/left/right and way to end the game like Q or Esc or whatever. #output: The 20x20 map with the hero updating if you can with moves. Show how much movement points you have and score. At the end of the game show some final score box. Good luck and have fun. #Example: ASCII Map might look like this. (This is not 20x20 but yours will be 20x20) * % = Wall * $ = Random element * @ = the hero A simple dungeon. %%%%%%%%%% %..$.....% %......$.% %...@....% %....$...% %.$......% %%%%%%%%%% Move: 100 Score: 0 #Creative Challenge: This is a creative challenge. You can use ASCII graphics or bmp graphics or more. You can add more elements to this. But regardless have fun trying to make this challenge work for you. """ def main(): pass if __name__ == "__main__": main()
""" Selection sort. """ def selection_sort(A, unused_0=0, unused_1=1): for j in range(len(A)-1): iMin = j for i in range(j+1, len(A)): if A[i] < A[iMin]: iMin = i if iMin != j: A[j], A[iMin] = A[iMin], A[j]
""" This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or its affiliate. If you do not have an agreement with Totara Learning Solutions LTD, you may not access, use, modify, or distribute this software. Please contact [licensing@totaralearning.com] for more information. @author Amjad Ali <amjad.ali@totaralearning.com> @package ml_recommender """ conf = { # Minimum number of users and items in interactions set for whom to run the recommendation engine in a tenant 'min_data': { 'min_users': 10, 'min_items': 10 }, # The L2 penalty on item features when item features are being used in the model 'item_alpha': 1e-6 } class Config: """ This is a conceptual representation of accessing the configuration elements from the conf object """ def __init__(self): """ The constructor method """ self._config = conf def get_property(self, property_name): """ This method accesses and returns the called item of the `conf` dictionary. The method returns `None` when the provided key does not match with any key of the `conf` dictionary :param property_name: A key from the keys of the `conf` dictionary :type property_name: str :return: An item from the `conf` dictionary whose key was used as input """ value = None if property_name in self._config.keys(): value = self._config[property_name] return value
#!/usr/bin/env python3.7 # -*- coding: utf-8 -*- # Source: https://youtu.be/6oL-0TdVy28 class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(tree.root, "") elif traversal_type == "inorder": return self.inorder_print(tree.root, "") elif traversal_type == "postorder": return self.postorder_print(tree.root, "") def preorder_print(self, start, traversal): """ Preorder traversal. Root -> Left -> Right """ if start: traversal += (str(start.value) + '-') traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self, start, traversal): """ In-order traversal. Left -> Root - Right """ if start: traversal = self.inorder_print(start.left, traversal) traversal += (str(start.value) + '-') traversal = self.inorder_print(start.right, traversal) return traversal def postorder_print(self, start, traversal): """ Post-order traversal. Left -> Right -> Root """ if start: traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) traversal += (str(start.value) + '-') return traversal # Tree representation. # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # Pre-order: 1-2-4-5-3-6-7- # In-order: 4-2-5-1-6-3-7- # Post-order: 2-4-5-3-6-7-1- # It's all DFS Depth First Search # Binary tree setup. tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) print(tree.print_tree('preorder')) print(tree.print_tree('inorder')) print(tree.print_tree('postorder'))
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. def bonus(robot): # a nice bit of goodness from the turtlebot driver by Xuwen Cao and # Morgan Quigley song = ( (76, 16), (76, 16), (72, 8), (76, 16), (79, 32), (67, 32), (72, 24), (67, 24), (64, 24), (69, 16), (71, 16), (70, 8), (69, 16), (79, 16), (76, 16), (72, 8), (74, 16), (71, 24), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 8), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (76, 4), (78, 4), (84, 16), (84, 8), (84, 16), (84, 16), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 16), (70, 4), (72, 4), (75, 16), (69, 4), (71, 4), (74, 16), (67, 4), (69, 4), (72, 16), (67, 8), (67, 16), (60, 24), ) # have to make sure robot is in full mode robot.sci.send([128, 132]) robot.sci.send([140, 1, len(song)]) for note in song: robot.sci.send(note) robot.sci.play_song(1) # From: http://www.harmony-central.com/MIDI/Doc/table2.html MIDI_TABLE = {'rest': 0, 'R': 0, 'pause': 0, 'G1': 31, 'G#1': 32, 'A1': 33, 'A#1': 34, 'B1': 35, 'C2': 36, 'C#2': 37, 'D2': 38, 'D#2': 39, 'E2': 40, 'F2': 41, 'F#2': 42, 'G2': 43, 'G#2': 44, 'A2': 45, 'A#2': 46, 'B2': 47, 'C3': 48, 'C#3': 49, 'D3': 50, 'D#3': 51, 'E3': 52, 'F3': 53, 'F#3': 54, 'G3': 55, 'G#3': 56, 'A3': 57, 'A#3': 58, 'B3': 59, 'C4': 60, 'C#4': 61, 'D4': 62, 'D#4': 63, 'E4': 64, 'F4': 65, 'F#4': 66, 'G4': 67, 'G#4': 68, 'A4': 69, 'A#4': 70, 'B4': 71, 'C5': 72, 'C#5': 73, 'D5': 74, 'D#5': 75, 'E5': 76, 'F5': 77, 'F#5': 78, 'G5': 79, 'G#5': 80, 'A5': 81, 'A#5': 82, 'B5': 83, 'C6': 84, 'C#6': 85, 'D6': 86, 'D#6': 87, 'E6': 88, 'F6': 89, 'F#6': 90, 'G6': 91, 'G#6': 92, 'A6': 93, 'A#6': 94, 'B6': 95, 'C7': 96, 'C#7': 97, 'D7': 98, 'D#7': 99, 'E7': 100, 'F7': 101, 'F#7': 102, 'G7': 103, 'G#7': 104, 'A7': 105, 'A#7': 106, 'B7': 107, 'C8': 108, 'C#8': 109, 'D8': 110, 'D#8': 111, 'E8': 112, 'F8': 113, 'F#8': 114, 'G8': 115, 'G#8': 116, 'A8': 117, 'A#8': 118, 'B8': 119, 'C9': 120, 'C#9': 121, 'D9': 122, 'D#9': 123, 'E9': 124, 'F9': 125, 'F#9': 126, 'G9': 127}
# -*- coding: utf-8 -*- # 高阶函数 # sorted ## 翻转字符串 s = '12345' d = sorted(s, reverse=True) print(''.join(d)) s = '12345' d = s[::-1] print(d) ## 列表元素排序 L = [36, 5, -12, 9, -21] print('列表', L, '排序: ', sorted(L)) ## 按元素的绝对值排序 print('列表', L, '绝对值排序: ', sorted(L, key=abs)) ## 字符串排序 L = ['bob', 'about', 'Zoo', 'Credit'] print('列表', L, '排序: ', sorted(L)) ## 取消大小写 print('列表', L, '取消大小写排序: ', sorted(L, key=str.lower)) ### 练习 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] ### 按名称排序 print(sorted(L, key=lambda x:x[0])) def by_name(t): return t[0] print(sorted(L, key=by_name)) ### 按成绩排序 print(sorted(L, key=lambda x:x[1])) def by_score(t): return t[1] print(sorted(L, key=by_score))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool: if not root: return False return self.isEqualtree(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) def isEqualtree(self, root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return False return self.isEqualtree(root1.left, root2.left) and self.isEqualtree(root1.right, root2.right)
'''Helper to filter sets of data''' class SetFilter: '''Helper class to filter list''' @staticmethod def diff(a_set, b_set): '''Filter by not intersection''' return not set(b_set).intersection(set(a_set)) @staticmethod def exact(a_set, b_set): '''Filter by eq''' return set(a_set) == set(b_set) @staticmethod def subset(a_set, b_set): '''Filter by intersection''' return set(a_set).intersection(set(b_set))
code_begin = """#!/usr/bin/env bash curl""" code_header = """ --header "{header}:{value}" """ code_proxy = " -x {proxy}" code_post = """ --data "{data}" """ code_search = """ | egrep --color " {search_string} |$" """ code_nosearch = """ -v --request {method} {url} {headers} --include"""
# Solution to Exercise #1 # ... env = MultiAgentArena() obs = env.reset() while True: # Compute actions separately for each agent. a1 = dummy_trainer.compute_action(obs["agent1"]) a2 = dummy_trainer.compute_action(obs["agent2"]) # Send the action-dict to the env. obs, rewards, dones, _ = env.step({"agent1": a1, "agent2": a2}) # Get a rendered image from the env. out.clear_output(wait=True) env.render() time.sleep(0.1) if dones["agent1"]: break
#!/usr/bin/env python # -*- coding: utf-8 -*- count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count, end=" ")
def bubble_sort(arr): length = len(arr) for i in range(length): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def main(): random_list = [12, 4, 5, 6, 25, 14, 15] bubble_sort(random_list) print(random_list) if __name__ == "__main__": main()
def bowling_score(frames): frames = [list(r) for r in frames.split(' ')] points = 0 for f in range(0, 8): if frames[f][0] == 'X': points += 10 if frames[f+1][0] == 'X': points += 10 if frames[f+2][0] == 'X': points += 10 else: points += int(frames[f+2][0]) elif frames[f+1][1] == '/': points += 10 else: points += int(frames[f+1][0]) + int(frames[f+1][1]) elif frames[f][1] == '/': points += 10 if frames[f+1][0] == 'X': points += 10 else: points += int(frames[f+1][0]) else: points += int(frames[f][0]) + int(frames[f][1]) if frames[8][0] == 'X': points += 10 if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 else: points += int(frames[9][1]) elif frames[9][1] == '/': points += 10 else: points += int(frames[9][0]) + int(frames[9][1]) elif frames[8][1] == '/': points += 10 if frames[9][0] == 'X': points += 10 else: points += int(frames[9][0]) else: points += int(frames[8][0]) + int(frames[8][1]) if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) elif frames[9][2] == '/': points += 10 else: points += int(frames[9][1]) + int(frames[9][2]) elif frames[9][1] == '/': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) else: points += int(frames[9][0]) + int(frames[9][1]) return points if __name__ == '__main__': print(bowling_score('11 11 11 11 11 11 11 11 11 11')) print(bowling_score('X X X X X X X X X XXX')) print(bowling_score('00 5/ 4/ 53 33 22 4/ 5/ 45 XXX')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 8/8')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 7/2'))
# -*- coding: utf-8 -*- __soap_format = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' 'xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' 'xmlns:ns1="{url}">' '<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '<ns1:{action}>{params}</ns1:{action}>' '</SOAP-ENV:Body>' '</SOAP-ENV:Envelope>' ) __headers = { 'User-Agent': 'BSPlayer/2.x (1022.12362)', 'Content-Type': 'text/xml; charset=utf-8', 'Connection': 'close', } __subdomains = [1, 2, 3, 4, 5, 6, 7, 8, 101, 102, 103, 104, 105, 106, 107, 108, 109] def __get_url(core, service_name): context = core.services[service_name].context if not context.subdomain: time_seconds = core.datetime.now().second context.subdomain = __subdomains[time_seconds % len(__subdomains)] return "http://s%s.api.bsplayer-subtitles.com/v1.php" % context.subdomain def __validate_response(core, service_name, request, response, retry=True): if not retry: return None def get_retry_request(): core.time.sleep(2) request['validate'] = lambda response: __validate_response(core, service_name, request, response, retry=False) return request if response is None: return get_retry_request() if response.status_code != 200: return get_retry_request() response = __parse_response(core, service_name, response.text) if response is None: return None status_code = response.find('result/result') if status_code is None: status_code = response.find('result') if status_code.text != '200' and status_code.text != '402': return get_retry_request() results = response.findall('data/item') if not results: return get_retry_request() if len(results) == 0: return get_retry_request() return None def __get_request(core, service_name, action, params): url = __get_url(core, service_name) headers = __headers.copy() headers['SOAPAction'] = '"%s#%s"' % (url, action) request = { 'method': 'POST', 'url': url, 'data': __soap_format.format(url=url, action=action, params=params), 'headers': headers, 'validate': lambda response: __validate_response(core, service_name, request, response) } return request def __parse_response(core, service_name, response): try: tree = core.ElementTree.fromstring(response.strip()) return tree.find('.//return') except Exception as exc: core.logger.error('%s - %s' % (service_name, exc)) return None def __logout(core, service_name): context = core.services[service_name].context if not context.token: return action = 'logOut' params = '<handle>%s</handle>' % context.token request = __get_request(core, service_name, action, params) def logout(): core.request.execute(core, request) context.token = None thread = core.threading.Thread(target=logout) thread.start() def build_auth_request(core, service_name): action = 'logIn' params = ( '<username></username>' '<password></password>' '<AppID>BSPlayer v2.72</AppID>' ) return __get_request(core, service_name, action, params) def parse_auth_response(core, service_name, response): response = __parse_response(core, service_name, response) if response is None: return if response.find('result').text == '200': token = response.find('data').text core.services[service_name].context.token = token def build_search_requests(core, service_name, meta): token = core.services[service_name].context.token if not token: return [] action = 'searchSubtitles' params = ( '<handle>{token}</handle>' '<movieHash>{filehash}</movieHash>' '<movieSize>{filesize}</movieSize>' '<languageId>{lang_ids}</languageId>' '<imdbId>{imdb_id}</imdbId>' ).format( token=token, filesize=meta.filesize if meta.filesize else '0', filehash=meta.filehash if meta.filehash else '0', lang_ids=','.join(core.utils.get_lang_ids(meta.languages)), imdb_id=meta.imdb_id[2:] ) return [__get_request(core, service_name, action, params)] def parse_search_response(core, service_name, meta, response): __logout(core, service_name) service = core.services[service_name] response = __parse_response(core, service_name, response.text) if response is None: return [] if response.find('result/result').text != '200': return [] results = response.findall('data/item') if not results: return [] lang_ids = core.utils.get_lang_ids(meta.languages) def map_result(result): name = result.find('subName').text lang_id = result.find('subLang').text rating = result.find('subRating').text try: lang = meta.languages[lang_ids.index(lang_id)] except: lang = lang_id return { 'service_name': service_name, 'service': service.display_name, 'lang': lang, 'name': name, 'rating': int(round(float(rating) / 2)) if rating else 0, 'lang_code': core.kodi.xbmc.convertLanguage(lang, core.kodi.xbmc.ISO_639_1), 'sync': 'true' if meta.filehash else 'false', 'impaired': 'false', 'color': 'gold', 'action_args': { 'url': result.find('subDownloadLink').text, 'lang': lang, 'filename': name, 'gzip': True } } return list(map(map_result, results)) def build_download_request(core, service_name, args): request = { 'method': 'GET', 'url': args['url'] } return request
ACCEL_FSR_2G = 0 ACCEL_FSR_4G = 1 ACCEL_FSR_8G = 2 ACCEL_FSR_16G = 3
SUCCESS = 0 FAILURE = 1 # NOTE: click.abort() uses this # for when tests are already running ALREADY_RUNNING = 2
karman_line_earth = 100_000*m // km karman_line_mars = 80_000*m // km karman_line_venus = 250_000*m // km
def extractWLTranslations(item): """ # 'WL Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Chapter Releases' in item['tags'] and ('OSI' in item['tags'] or item['title'].startswith('OSI Chapter')): return buildReleaseMessageWithType(item, 'One Sword to Immortality', vol, chp, frag=frag, postfix=postfix) return False
class Car: def __init__(self, make, petrol_consumption): self.make = make self.petrol_consumption = petrol_consumption def petrol_calculation(self, price = 22.5): return self.petrol_consumption * price ford = Car("ford", 10) money = ford.petrol_calculation() print(money)
# Mouse Move # # November 12, 2018 # By Robin Nash [c,r] = [int(i) for i in input().split(" ") if i != " "] x,y = 0,0 while True: pair = [int(i) for i in input().split(" ") if i != " "] if pair == [0,0]: break x += pair[0] y += pair[1] pair = [x,y] for i in range(2): if pair[i] > [c,r][i]: pair[i] = [c,r][i] if pair[i] < 0: pair[i] = 0 [x,y] = pair print(x,y) #1541983052.0
class Solution: def thirdMax(self, nums: List[int]) -> int: hq = [] for x in nums: if x not in hq: if len(hq) < 3: heapq.heappush(hq, x) else: heapq.heappushpop(hq, x) if len(hq) < 3: return hq[-1] return hq[0]
s = input() k = int(input()) ans = set() for i in range(len(s)): for j in range(1, k+1): ans.add(s[i:i+j]) # print(ans) print(sorted(list(ans))[k-1])
# coding: utf-8 """ Given a string, return a new string where the first and last chars have been exchanged. front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' """ def front_back(str): if len(str) <= 1: return str elif len(str) == 2: return str[-1] + str[0] new_str = '' for i in range(1, len(str)-1): new_str = new_str + str[i] return str[-1] + new_str + str[0]
""" File: copyfile.py Project 7.3 Copies the text from a given input file to a given output file. """ # Take the inputs inName = input("Enter the input file name: ") outName = input("Enter the output file name: ") # Open the input file and read the text inputFile = open(inName, 'r') text = inputFile.read() # Open the output file and write the text outFile = open(outName, 'w') outFile.write(text) outFile.close()
# -*- coding: utf-8 -*- def test_task_run(): print("test task run module") assert 1 == 1
# A program to calculate frequency of array elements class ArrayBasic: def __init__(self, arr, n): self.arr = arr self.n = n def calculate_frequency_hash_map(self): """ [A program to calculate counting frequency of array elements] Time complexity: O(n) Auxiliary space: O(n) Returns: [dict]: [A dict with count] """ hash_map = {} for i in self.arr: hash_map[i] = 1 if hash_map.get(i) == None else hash_map[i] + 1 return hash_map # Driver arr = [10, 20, 20, 10, 10, 20, 5, 20] result = ArrayBasic(arr, len(arr)) print(f"Frequency of array elements is: {result.calculate_frequency_hash_map()}")
n=int(input("Enter the Decimal Number:")) def covbin(n): if(n==0): return 0 else: return (n%2)+(10*covbin(n//2)) print("Binary is=",covbin(n))
""" ssml:sheetViews = ssml:CT_SheetViews Sequence [1..1] ssml:sheetView [1..*] Worksheet View ssml:extLst [0..1] Future Feature Storage Area ssml:sheetView = ssml:CT_SheetView Sequence [1..1] ssml:pane [0..1] View Pane ssml:selection [0..4] Selection ssml:pivotSelection [0..4] PivotTable Selection ssml:extLst [0..1] Future Feature Storage Area ssml:pane = ssml:CT_Pane Attribute xSplit [0..1] xsd:double Horizontal Split Position Default value is "0". ySplit [0..1] xsd:double Vertical Split Position Default value is "0". topLeftCell [0..1] ssml:ST_CellRef Top Left Visible Cell activePane [0..1] ssml:ST_Pane Active Pane Default value is "topLeft". state [0..1] ssml:ST_PaneState Split State Default value is "split". ssml:selection = ssml:CT_Selection Atrribute pane [0..1] ssml:ST_Pane Pane Default value is "topLeft". activeCell [0..1] ssml:ST_CellRef Active Cell Location activeCellId [0..1] xsd:unsignedInt Active Cell Index Default value is "0". sqref [0..1] ssml:ST_Sqref Sequence of References Default value is "A1". ssml:pivotSelection = ssml:CT_PivotSelection Atrribute pane [0..1] ssml:ST_Pane Pane Default value is "topLeft". showHeader [0..1] xsd:boolean Show Header Default value is "false". label [0..1] xsd:boolean Label Default value is "false". data [0..1] xsd:boolean Data Selection Default value is "false". extendable [0..1] xsd:boolean Extendable Default value is "false". count [0..1] xsd:unsignedInt Selection Count Default value is "0". axis [0..1] ssml:ST_Axis Axis dimension [0..1] xsd:unsignedInt Dimension Default value is "0". start [0..1] xsd:unsignedInt Start Default value is "0". min [0..1] xsd:unsignedInt Minimum Default value is "0". max [0..1] xsd:unsignedInt Maximum Default value is "0". activeRow [0..1] xsd:unsignedInt Active Row Default value is "0". activeCol [0..1] xsd:unsignedInt Active Column Default value is "0". previousRow [0..1] xsd:unsignedInt Previous Row Default value is "0". previousCol [0..1] xsd:unsignedInt Previous Column Selection Default value is "0". click [0..1] xsd:unsignedInt Click Count Default value is "0". r:id [0..1] r:ST_RelationshipId Relationship Id """
__all__ = ['descriptor', 'es_transport', 'flushing_buffer', 'line_buffer', 'sqs_transport', 'transport_exceptions', 'transport_result', 'transport_utils']
# GPLv3 License # # Copyright (C) 2020 Ubisoft # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """ This package defines how we send Blender updates to the server, and how we interpret updates we receive to update Blender's data. These functionalities are implemented in the BlenderClient class and in submodules of the package. Submodules with a well defined entity name (camera, collection, light, ...) handle updates for the corresponding data type in Blender. The goal is to replace all this specific code with the submodule data.py, which use the blender_data package to treat updates of Blender's data in a generic way. Specific code will still be required to handle non-Blender clients. As an example, mesh.py add to the MESH message a triangulated, with modifiers applied, of the mesh. This is for non-Blender clients. In the future we want to move these kind of specific processes to a plug-in system. """
def total_centro_custo(D_e): D_return = {} # Pecorre dados de cada pessoa for v in D_e.values(): if v['centro de custo'] not in D_return: D_return[v['centro de custo']] = 0 D_return[v['centro de custo']] += v['valor'] return D_return
""" jupylet/lru.py Copyright (c) 2020, Nir Aides - nir@winpdb.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ SPRITE_TEXTURE_UNIT = 0 SKYBOX_TEXTURE_UNIT = 1 SHADOW_TEXTURE_UNIT = 2 class LRU(object): """Mechanism to allocate least recently used slot in array.""" def __init__(self, min_items, max_items): self.mini = min_items self.step = max_items self.items = {i: [i, i, i, 0] for i in range(min_items, max_items)} def reset(self, min_items, max_items): self.mini = min_items self.step = max_items self.items = {i: [i, i, i, 0] for i in range(min_items, max_items)} def allocate(self, lid=None): """Allocate slot. Args: lid (int): An id that identifies "object" in array. A new id will be generated if None is given. Returns: tuple: A 4-tuple consisting of (step, lid, slot, new) where *step* indicates the lru "timestamp" for this object, *lid* is the allocated object id, *slot* is the array index allocated for the "object", and *new* is 1 if "object" was allocated a new slot or 0 if it remains in the same slot it was before. """ self.step += 1 if lid is None: lid = self.step r = self.items.get(lid) if r is None: lid0, slot = min(self.items.values())[1:3] self.items.pop(lid0) self.items[lid] = [self.step, lid, slot, 0] return self.step, lid, slot, 1 r[0] = self.step return r _MIN_TEXTURES = 3 _MAX_TEXTURES = 16 _lru_textures = LRU(_MIN_TEXTURES, _MAX_TEXTURES) _MAX_MATERIALS = 12 _lru_materials = LRU(0, _MAX_MATERIALS)
"""MicroESP Errors """ __author__ = 'Oleksandr Shepetko' __email__ = 'a@shepetko.com' __license__ = 'MIT' class ESP8266Error(Exception): pass class DeviceNotConnectedError(ESP8266Error): pass class DeviceCodeExecutionError(ESP8266Error): pass
soma = 1 #divisores = 0 num = int(input("Informe um numero")) for c in range(1, num): if num % c == 0: soma = soma + 1 if soma != 2 : print("\033[31mo numero {} não é primo ".format(num)) print("O numero {} é divisivel por {} numeros".format(num, soma)) else: print("\033[32mo numero {} é primo, e tem {} divisores ".format(num, soma))
def print_n(s, n): while n >= 0: print(s) n -= 1
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file 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. PACKAGE_XML_ELEMENT_ORDER = [ "name", "version", "description", "author", "maintainer", "license", "url", "buildtool_depend", "build_depend", "build_export_depend", "depend", "exec_depend", "test_depend", "member_of_group", "doc_depend", "conflict", "replace", "export", ] CMAKE_LISTS_RENAMED_VARIABLES = { "${CATKIN_DEVEL_PREFIX}/": "", "${CATKIN_GLOBAL_BIN_DESTINATION}": "bin", "${CATKIN_GLOBAL_INCLUDE_DESTINATION}": "include", "${CATKIN_GLOBAL_LIB_DESTINATION}": "lib", "${CATKIN_GLOBAL_LIBEXEC_DESTINATION}": "lib", "${CATKIN_GLOBAL_SHARE_DESTINATION}": "share", "${CATKIN_PACKAGE_BIN_DESTINATION}": "bin", "${CATKIN_PACKAGE_INCLUDE_DESTINATION}": "include/${PROJECT_NAME}", "${CATKIN_PACKAGE_LIB_DESTINATION}": "lib", "${CATKIN_PACKAGE_SHARE_DESTINATION}": "share/${PROJECT_NAME}", "CATKIN_ENABLE_TESTING": "BUILD_TESTING" } # Commands that are not used by ROS2 CMAKE_LISTS_DELETED_COMMANDS = [ "catkin_package", "roslaunch_add_file_check" ] # List of ROS packages that have been renamed in ROS 2 RENAMED_ROS_PACKAGES = { "tf": "tf2", "roscpp": "rclcpp", # This shouldn't be here anyways "rospy": "rclpy", # This shouldn't be here anyways "nodelet": "rclcpp", # This shouldn't be here anyways "message_generation": "rosidl_default_generators", # Shouldn't be here "message_runtime": "rosidl_default_runtime", # Shouldn't be here "rosconsole": "ros2_console", # Until ROS 2 replacement exists "rviz": "rviz2", "catkin": "ament_cmake" # Well.. it's not exactly a rename, but good enough } # List of packages that do not need to be found by CMake NO_CMAKE_FIND_PACKAGES = [ "rosidl_default_runtime", # Shouldn't be here "roslaunch", # They're probably trying to do roslaunch file testing "catkin" ] # List of packages that do not need to be found in package.xml NO_PKG_XML_DEPENDS = [ "roslaunch" ] # List of executables that have likely been renamed in ROS 2 RENAMED_ROS_EXECUTABLES = { "rviz": "rviz2" }
class CommandModule: def __init__(self, name, bus, conn, chan, conf): self.name = name self.conf = conf self.chan = chan self.conn = conn self.bus = bus def send(self, msg): self.conn.privmsg(self.chan, msg) def error(self, msg): self.status('error: {}'.format(msg)) def status(self, msg): self.send('[{}] {}'.format(self.name, msg)) def on_message(self, src, content): content = content.strip() words = content.split(' ') if len(words) == 0: return cmd = words[0] if cmd[0] != '!': return cmd = words[0][1:] if hasattr(self, 'cmd_'+cmd): getattr(self, 'cmd_'+cmd)(src, words[1:], content[len(words[0]):].strip(), src) def post(self, msg, *args, **kwargs): self.bus.post(self, msg, args, kwargs) def bus_handle(self, msg, args, kwargs): mname = 'busmsg_' + msg if hasattr(self, mname): getattr(self, mname)(*args, **kwargs)
text = input('Enter a text: ') character = input('Enter a character that you can search in "'+text+'": ') result = text.count(character) print('The character "'+character+'" appears '+str(result)+' times in "'+text+'".')
# # @lc app=leetcode.cn id=55 lang=python3 # # [55] 跳跃游戏 # # https://leetcode-cn.com/problems/jump-game/description/ # # algorithms # Medium (33.65%) # Total Accepted: 12.2K # Total Submissions: 36K # Testcase Example: '[2,3,1,1,4]' # # 给定一个非负整数数组,你最初位于数组的第一个位置。 # # 数组中的每个元素代表你在该位置可以跳跃的最大长度。 # # 判断你是否能够到达最后一个位置。 # # 示例 1: # # 输入: [2,3,1,1,4] # 输出: true # 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。 # # # 示例 2: # # 输入: [3,2,1,0,4] # 输出: false # 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 # # # class Solution: # 1. 分而治之(时间长) # 能否跳到第n个可拆分为 # 能否跳到第n-1个且nums[n-1]>=1 # 能否跳到第n-2个且nums[n-2]>=2 # 能否跳到第i个且nums[i]>=n-i # 能否跳到第1个且nums[1]>=n-1 # 2. 打靶 # 从每个位置依次向前计算打靶的最远位置,直到能够超出数组界限 def canJump(self, nums) -> bool: length = len(nums) if length == 0: return True maxIndex = 0 # 最远打靶距离 for i in range(length): # 循环超过了最远打靶距离,终止 if i > maxIndex: return False curMaxIndex = nums[i] + i if curMaxIndex > maxIndex: maxIndex = curMaxIndex # 判断是否能打到最终点 if maxIndex >= length - 1: return True return False
class BME280: '''Class to mock temp sensor''' def __init__(self): '''Constructor for mock''' def get_temperature(self): '''Temp''' return 20.0
def test_movie_tech_sections(ia): movie = ia.get_movie('0133093', info=['technical']) tech = movie.get('tech', []) assert set(tech.keys()) == set(['sound mix', 'color', 'aspect ratio', 'camera', 'laboratory', 'cinematographic process', 'printed film format', 'negative format', 'runtime', 'film length'])
#!/usr/bin/env python3 #Swimming in the pool excercise def getValue(): try: valueInput = int(input()) except ValueError: print("Wrong type") quit() else: return valueInput def calcResidue(length, coordinate): halfOfLength = length / 2 residue = length - coordinate if residue < halfOfLength: return residue else: return coordinate N = getValue() M = getValue() short = getValue() long = getValue() shortCalculated = short longCalculated = long if M < N: shortCalculated = calcResidue(M, short) else: longCalculated = calcResidue(N, long) if shortCalculated < longCalculated: print(shortCalculated) else: print(longCalculated)
class Robot: def greet(self): print('Hello Viraj') class RobotChild(Robot): def greet(self): print('Hello Scott') # Instantiate RobotChild Class child = RobotChild() # Invoke Greet method from RobotChild class child.greet()
#!/usr/bin/env python3 def welcome(): print("Welcome") def hi(name): print("Hi " + name + "!") welcome() username = input("Who are there? ") hi(name=username) hi(username)
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ for i in xrange(16): a = (n >> i) & 1 b = (n >> (31-i)) & 1 if a: n |= 1 << (31-i) else: n &= ~(1 << (31-i)) if b: n |= 1 << i else: n &= ~(1 << i) return n if __name__ == '__main__': sol = Solution() sol.reverseBits(1)
# -*- coding: utf-8 -*- # words consist of 2 or more alphanumeric characters where there first is not # numeric and not an underscore alphanumeric is defined in the unicode sense. # here is a list of the unicode characters with codepoints 300 and below that # match this pattern: # ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzª²³µ¹º¼½¾ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒ # ÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤ # ĥĦħĨĩĪī ... # includes also all of greek, arabic, etc. TOKEN_PATTERN = r'(?u)\b[^(\W|\d|_)]{1,}\w+\b' ID_PATTERN = r'[a-zA-Z0-9\-_]+' # ids permitted in URL slugs
# preorder: root -> left -> right # inorder: left -> root -> right # we can first pick up root from preorder, then get the left and right subtrees from inorder # Recursion # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: # preorder: root -> left -> right # inorder: left -> root -> right if not inorder: return # if inorder: ind = inorder.index(preorder.pop(0)) root = TreeNode(inorder[ind]) root.left = self.buildTree(preorder, inorder[0:ind]) root.right = self.buildTree(preorder, inorder[ind+1:]) return root # V2 class Solution: def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ def helper(in_left = 0, in_right = len(inorder)): nonlocal pre_idx # if there is no elements to construct subtrees if in_left == in_right: return None # pick up pre_idx element as a root root_val = preorder[pre_idx] root = TreeNode(root_val) # root splits inorder list # into left and right subtrees index = idx_map[root_val] # recursion pre_idx += 1 # build left subtree root.left = helper(in_left, index) # build right subtree root.right = helper(index + 1, in_right) return root # start from first preorder element pre_idx = 0 # build a hashmap value -> its index idx_map = {val:idx for idx, val in enumerate(inorder)} return helper() # V3 class Solution(object): def buildTree(self, preorder, inorder): inorder_map = {val: i for i, val in enumerate(inorder)} return self.dfs_helper(inorder_map, preorder, 0, len(inorder) - 1) def dfs_helper(self, inorder_map, preorder, left, right): if not preorder : return node = preorder.pop(0) root = TreeNode(node) root_index = inorder_map[node] if root_index != left: root.left = self.dfs_helper(inorder_map, preorder, left, root_index - 1) if root_index != right: root.right = self.dfs_helper(inorder_map, preorder, root_index + 1, right) return root # Time: O(N) # Space;O(N)
# Travel club # A group of people are member of a travel club. # The group shares expenses equally but it is not practical to share every expense as they happen, so all expenses are collated (such as taxis, train tickets etc) after the trip # The member cost is shared to within 1% between the group. # Create a programme that computes the net cost from a list of expenses and works out the minimum amount of money that must change hands in order for everybody to have paid the same amount (within 1%). def recursiveInput(msg, until=''): while True: string = input(msg) if string == until: print (f"\033[A{' '*len(msg + string)}\033[A") break yield string def main(): memberNames = [m for m in recursiveInput('Name of group member > ')] print() members = { m: float(input(f"{m}'s money £")) for m in memberNames } print() expenses = [float(e) for e in recursiveInput('Enter cost of an expense > ')] totalCost = sum(expenses) print() # Verifies that the group of people can afford all the expenses if totalCost > sum(members.values()): print("Total cost of expenses is too high, the group of people can't afford to pay for it") return costPerMember = totalCost / len(members) history = [] moneyToChangeHands = 0 for name, money in members.items(): if (missingMoney := costPerMember - money) > 0: moneyToChangeHands += missingMoney history.append(f'£{missingMoney:.02f} has to be given to {name}') if moneyToChangeHands: print(f'A minimum of £{moneyToChangeHands:.02f} must change hands in order for everyone to have paid the same amount (of £{costPerMember:.02f}).') print('\nHistory:') for h in history: print(h) else: print('No money needs to change hands for everyone to have paid the same amount for expenses.') if __name__ == "__main__": main()
classes_names = [ 'book', 'bottle', 'cabinet', 'ceiling', 'chair', 'cone', 'counter', 'dishwasher', 'faucet', 'fire extinguisher', 'floor', 'garbage bin', 'microwave', 'paper towel dispenser', 'paper', 'pot', 'refridgerator', 'stove burner', 'table', 'unknown', 'wall', 'bowl', 'magnet', 'sink', 'air vent', 'box', 'door knob', 'door', 'scissor', 'tape dispenser', 'telephone cord', 'telephone', 'track light', 'cork board', 'cup', 'desk', 'laptop', 'air duct', 'basket', 'camera', 'pipe', 'shelves', 'stacked chairs', 'styrofoam object', 'whiteboard', 'computer', 'keyboard', 'ladder', 'monitor', 'stand', 'bar', 'motion camera', 'projector screen', 'speaker', 'bag', 'clock', 'green screen', 'mantel', 'window', 'ball', 'hole puncher', 'light', 'manilla envelope', 'picture', 'mail shelf', 'printer', 'stapler', 'fax machine', 'folder', 'jar', 'magazine', 'ruler', 'cable modem', 'fan', 'file', 'hand sanitizer', 'paper rack', 'vase', 'air conditioner', 'blinds', 'flower', 'plant', 'sofa', 'stereo', 'books', 'exit sign', 'room divider', 'bookshelf', 'curtain', 'projector', 'modem', 'wire', 'water purifier', 'column', 'hooks', 'hanging hooks', 'pen', 'electrical outlet', 'doll', 'eraser', 'pencil holder', 'water carboy', 'mouse', 'cable rack', 'wire rack', 'flipboard', 'map', 'paper cutter', 'tape', 'thermostat', 'heater', 'circuit breaker box', 'paper towel', 'stamp', 'duster', 'poster case', 'whiteboard marker', 'ethernet jack', 'pillow', 'hair brush', 'makeup brush', 'mirror', 'shower curtain', 'toilet', 'toiletries bag', 'toothbrush holder', 'toothbrush', 'toothpaste', 'platter', 'rug', 'squeeze tube', 'shower cap', 'soap', 'towel rod', 'towel', 'bathtub', 'candle', 'tissue box', 'toilet paper', 'container', 'clothes', 'electric toothbrush', 'floor mat', 'lamp', 'drum', 'flower pot', 'banana', 'candlestick', 'shoe', 'stool', 'urn', 'earplugs', 'mailshelf', 'placemat', 'excercise ball', 'alarm clock', 'bed', 'night stand', 'deoderant', 'headphones', 'headboard', 'basketball hoop', 'foot rest', 'laundry basket', 'sock', 'football', 'mens suit', 'cable box', 'dresser', 'dvd player', 'shaver', 'television', 'contact lens solution bottle', 'drawer', 'remote control', 'cologne', 'stuffed animal', 'lint roller', 'tray', 'lock', 'purse', 'toy bottle', 'crate', 'vasoline', 'gift wrapping roll', 'wall decoration', 'hookah', 'radio', 'bicycle', 'pen box', 'mask', 'shorts', 'hat', 'hockey glove', 'hockey stick', 'vuvuzela', 'dvd', 'chessboard', 'suitcase', 'calculator', 'flashcard', 'staple remover', 'umbrella', 'bench', 'yoga mat', 'backpack', 'cd', 'sign', 'hangers', 'notebook', 'hanger', 'security camera', 'folders', 'clothing hanger', 'stairs', 'glass rack', 'saucer', 'tag', 'dolly', 'machine', 'trolly', 'shopping baskets', 'gate', 'bookrack', 'blackboard', 'coffee bag', 'coffee packet', 'hot water heater', 'muffins', 'napkin dispenser', 'plaque', 'plastic tub', 'plate', 'coffee machine', 'napkin holder', 'radiator', 'coffee grinder', 'oven', 'plant pot', 'scarf', 'spice rack', 'stove', 'tea kettle', 'napkin', 'bag of chips', 'bread', 'cutting board', 'dish brush', 'serving spoon', 'sponge', 'toaster', 'cooking pan', 'kitchen items', 'ladel', 'spatula', 'spice stand', 'trivet', 'knife rack', 'knife', 'baking dish', 'dish scrubber', 'drying rack', 'vessel', 'kichen towel', 'tin foil', 'kitchen utensil', 'utensil', 'blender', 'garbage bag', 'sink protector', 'box of ziplock bags', 'spice bottle', 'pitcher', 'pizza box', 'toaster oven', 'step stool', 'vegetable peeler', 'washing machine', 'can opener', 'can of food', 'paper towel holder', 'spoon stand', 'spoon', 'wooden kitchen utensils', 'bag of flour', 'fruit', 'sheet of metal', 'waffle maker', 'cake', 'cell phone', 'tv stand', 'tablecloth', 'wine glass', 'sculpture', 'wall stand', 'iphone', 'coke bottle', 'piano', 'wine rack', 'guitar', 'light switch', 'shirts in hanger', 'router', 'glass pot', 'cart', 'vacuum cleaner', 'bin', 'coins', 'hand sculpture', 'ipod', 'jersey', 'blanket', 'ironing board', 'pen stand', 'mens tie', 'glass baking dish', 'utensils', 'frying pan', 'shopping cart', 'plastic bowl', 'wooden container', 'onion', 'potato', 'jacket', 'dvds', 'surge protector', 'tumbler', 'broom', 'can', 'crock pot', 'person', 'salt shaker', 'wine bottle', 'apple', 'eye glasses', 'menorah', 'bicycle helmet', 'fire alarm', 'water fountain', 'humidifier', 'necklace', 'chandelier', 'barrel', 'chest', 'decanter', 'wooden utensils', 'globe', 'sheets', 'fork', 'napkin ring', 'gift wrapping', 'bed sheets', 'spot light', 'lighting track', 'cannister', 'coffee table', 'mortar and pestle', 'stack of plates', 'ottoman', 'server', 'salt container', 'utensil container', 'phone jack', 'switchbox', 'casserole dish', 'oven handle', 'whisk', 'dish cover', 'electric mixer', 'decorative platter', 'drawer handle', 'fireplace', 'stroller', 'bookend', 'table runner', 'typewriter', 'ashtray', 'key', 'suit jacket', 'range hood', 'cleaning wipes', 'six pack of beer', 'decorative plate', 'watch', 'balloon', 'ipad', 'coaster', 'whiteboard eraser', 'toy', 'toys basket', 'toy truck', 'classroom board', 'chart stand', 'picture of fish', 'plastic box', 'pencil', 'carton', 'walkie talkie', 'binder', 'coat hanger', 'filing shelves', 'plastic crate', 'plastic rack', 'plastic tray', 'flag', 'poster board', 'lunch bag', 'board', 'leg of a girl', 'file holder', 'chart', 'glass pane', 'cardboard tube', 'bassinet', 'toy car', 'toy shelf', 'toy bin', 'toys shelf', 'educational display', 'placard', 'soft toy group', 'soft toy', 'toy cube', 'toy cylinder', 'toy rectangle', 'toy triangle', 'bucket', 'chalkboard', 'game table', 'storage shelvesbooks', 'toy cuboid', 'toy tree', 'wooden toy', 'toy box', 'toy phone', 'toy sink', 'toyhouse', 'notecards', 'toy trucks', 'wall hand sanitizer dispenser', 'cap stand', 'music stereo', 'toys rack', 'display board', 'lid of jar', 'stacked bins boxes', 'stacked plastic racks', 'storage rack', 'roll of paper towels', 'cables', 'power surge', 'cardboard sheet', 'banister', 'show piece', 'pepper shaker', 'kitchen island', 'excercise equipment', 'treadmill', 'ornamental plant', 'piano bench', 'sheet music', 'grandfather clock', 'iron grill', 'pen holder', 'toy doll', 'globe stand', 'telescope', 'magazine holder', 'file container', 'paper holder', 'flower box', 'pyramid', 'desk mat', 'cordless phone', 'desk drawer', 'envelope', 'window frame', 'id card', 'file stand', 'paper weight', 'toy plane', 'money', 'papers', 'comforter', 'crib', 'doll house', 'toy chair', 'toy sofa', 'plastic chair', 'toy house', 'child carrier', 'cloth bag', 'cradle', 'baby chair', 'chart roll', 'toys box', 'railing', 'clothing dryer', 'clothing washer', 'laundry detergent jug', 'clothing detergent', 'bottle of soap', 'box of paper', 'trolley', 'hand sanitizer dispenser', 'soap holder', 'water dispenser', 'photo', 'water cooler', 'foosball table', 'crayon', 'hoola hoop', 'horse toy', 'plastic toy container', 'pool table', 'game system', 'pool sticks', 'console system', 'video game', 'pool ball', 'trampoline', 'tricycle', 'wii', 'furniture', 'alarm', 'toy table', 'ornamental item', 'copper vessel', 'stick', 'car', 'mezuza', 'toy cash register', 'lid', 'paper bundle', 'business cards', 'clipboard', 'flatbed scanner', 'paper tray', 'mouse pad', 'display case', 'tree sculpture', 'basketball', 'fiberglass case', 'framed certificate', 'cordless telephone', 'shofar', 'trophy', 'cleaner', 'cloth drying stand', 'electric box', 'furnace', 'piece of wood', 'wooden pillar', 'drying stand', 'cane', 'clothing drying rack', 'iron box', 'excercise machine', 'sheet', 'rope', 'sticks', 'wooden planks', 'toilet plunger', 'bar of soap', 'toilet bowl brush', 'light bulb', 'drain', 'faucet handle', 'nailclipper', 'shaving cream', 'rolled carpet', 'clothing iron', 'window cover', 'charger and wire', 'quilt', 'mattress', 'hair dryer', 'stones', 'pepper grinder', 'cat cage', 'dish rack', 'curtain rod', 'calendar', 'head phones', 'cd disc', 'head phone', 'usb drive', 'water heater', 'pan', 'tuna cans', 'baby gate', 'spoon sets', 'cans of cat food', 'cat', 'flower basket', 'fruit platter', 'grapefruit', 'kiwi', 'hand blender', 'knobs', 'vessels', 'cell phone charger', 'wire basket', 'tub of tupperware', 'candelabra', 'litter box', 'shovel', 'cat bed', 'door way', 'belt', 'surge protect', 'glass', 'console controller', 'shoe rack', 'door frame', 'computer disk', 'briefcase', 'mail tray', 'file pad', 'letter stand', 'plastic cup of coffee', 'glass box', 'ping pong ball', 'ping pong racket', 'ping pong table', 'tennis racket', 'ping pong racquet', 'xbox', 'electric toothbrush base', 'toilet brush', 'toiletries', 'razor', 'bottle of contact lens solution', 'contact lens case', 'cream', 'glass container', 'container of skin cream', 'soap dish', 'scale', 'soap stand', 'cactus', 'door window reflection', 'ceramic frog', 'incense candle', 'storage space', 'door lock', 'toilet paper holder', 'tissue', 'personal care liquid', 'shower head', 'shower knob', 'knob', 'cream tube', 'perfume box', 'perfume', 'back scrubber', 'door facing trimreflection', 'doorreflection', 'light switchreflection', 'medicine tube', 'wallet', 'soap tray', 'door curtain', 'shower pipe', 'face wash cream', 'flashlight', 'shower base', 'window shelf', 'shower hose', 'toothpaste holder', 'soap box', 'incense holder', 'conch shell', 'roll of toilet paper', 'shower tube', 'bottle of listerine', 'bottle of hand wash liquid', 'tea pot', 'lazy susan', 'avocado', 'fruit stand', 'fruitplate', 'oil container', 'package of water', 'bottle of liquid', 'door way arch', 'jug', 'bulb', 'bagel', 'bag of bagels', 'banana peel', 'bag of oreo', 'flask', 'collander', 'brick', 'torch', 'dog bowl', 'wooden plank', 'eggs', 'grill', 'dog', 'chimney', 'dog cage', 'orange plastic cap', 'glass set', 'vessel set', 'mellon', 'aluminium foil', 'orange', 'peach', 'tea coaster', 'butterfly sculpture', 'corkscrew', 'heating tray', 'food processor', 'corn', 'squash', 'watermellon', 'vegetables', 'celery', 'glass dish', 'hot dogs', 'plastic dish', 'vegetable', 'sticker', 'chapstick', 'sifter', 'fruit basket', 'glove', 'measuring cup', 'water filter', 'wine accessory', 'dishes', 'file box', 'ornamental pot', 'dog toy', 'salt and pepper', 'electrical kettle', 'kitchen container plastic', 'pineapple', 'suger jar', 'steamer', 'charger', 'mug holder', 'orange juicer', 'juicer', 'bag of hot dog buns', 'hamburger bun', 'mug hanger', 'bottle of ketchup', 'toy kitchen', 'food wrapped on a tray', 'kitchen utensils', 'oven mitt', 'bottle of comet', 'wooden utensil', 'decorative dish', 'handle', 'label', 'flask set', 'cooking pot cover', 'tupperware', 'garlic', 'tissue roll', 'lemon', 'wine', 'decorative bottle', 'wire tray', 'tea cannister', 'clothing hamper', 'guitar case', 'wardrobe', 'boomerang', 'button', 'karate belts', 'medal', 'window seat', 'window box', 'necklace holder', 'beeper', 'webcam', 'fish tank', 'luggage', 'life jacket', 'shoelace', 'pen cup', 'eyeball plastic ball', 'toy pyramid', 'model boat', 'certificate', 'puppy toy', 'wire board', 'quill', 'canister', 'toy boat', 'antenna', 'bean bag', 'lint comb', 'travel bag', 'wall divider', 'toy chest', 'headband', 'luggage rack', 'bunk bed', 'lego', 'yarmulka', 'package of bedroom sheets', 'bedding package', 'comb', 'dollar bill', 'pig', 'storage bin', 'storage chest', 'slide', 'playpen', 'electronic drumset', 'ipod dock', 'microphone', 'music keyboard', 'music stand', 'microphone stand', 'album', 'kinect', 'inkwell', 'baseball', 'decorative bowl', 'book holder', 'toy horse', 'desser', 'toy apple', 'toy dog', 'scenary', 'drawer knob', 'shoe hanger', 'tent', 'figurine', 'soccer ball', 'hand weight', 'magic 8ball', 'bottle of perfume', 'sleeping bag', 'decoration item', 'envelopes', 'trinket', 'hand fan', 'sculpture of the chrysler building', 'sculpture of the eiffel tower', 'sculpture of the empire state building', 'jeans', 'garage door', 'case', 'rags', 'decorative item', 'toy stroller', 'shelf frame', 'cat house', 'can of beer', 'dog bed', 'lamp shade', 'bracelet', 'reflection of window shutters', 'decorative egg', 'indoor fountain', 'photo album', 'decorative candle', 'walkietalkie', 'serving dish', 'floor trim', 'mini display platform', 'american flag', 'vhs tapes', 'throw', 'newspapers', 'mantle', 'package of bottled water', 'serving platter', 'display platter', 'centerpiece', 'tea box', 'gold piece', 'wreathe', 'lectern', 'hammer', 'matchbox', 'pepper', 'yellow pepper', 'duck', 'eggplant', 'glass ware', 'sewing machine', 'rolled up rug', 'doily', 'coffee pot', 'torah', ]
# -*- coding: utf-8 -*- class CoinPair: """ 币对处理类 """ @classmethod def coin_pair_with(cls, cp_str, sep='/'): comps = cp_str.split(sep) if len(comps) < 2: return None return CoinPair(comps[0], comps[1]) def __init__(self, trade_coin='', base_coin='', custom_min_cost=None): self.trade_coin = trade_coin.upper() self.base_coin = base_coin.upper() self.custom_min_cost = custom_min_cost # 自定义最小下单金额 def formatted(self, sep='/'): """获取格式化的币对 Parameters ---------- sep : str, optional 分割符, by default '/' """ return "{}{}{}".format(self.trade_coin, sep, self.base_coin) @property def estimated_value_of_base_coin(self): """ 以粗略的价格估算本位币价格 """ base_coin = self.base_coin.upper() if base_coin in ['USDT', 'USD']: return 1 if base_coin in ['ETH']: return 200 if base_coin in ['BTC']: return 9000 # default return 1 class ContractCoinPair(CoinPair): sep = None """合约币对""" @classmethod def coin_pair_with(cls, cp_str, sep='/'): comps = cp_str.split(sep, cp_str.count(sep)) def safe_list_get(l, idx, default=None): try: return l[idx] except IndexError: return default if len(comps) < 2: return None cp = ContractCoinPair(comps[0], comps[1], safe_list_get(comps, 2)) cp.sep = sep return cp def __init__(self, trade_coin='', base_coin='', tail_str='', custom_min_cost=None): super().__init__(trade_coin, base_coin, custom_min_cost) self.tail = tail_str.upper() if tail_str is not None else None def formatted(self, sep=None): """获取格式化的币对 Parameters ---------- sep : str, optional 分割符, by default '/' """ sep = sep if sep is not None else self.sep if self.sep is not None else '/' base_str = "{}{}{}".format(self.trade_coin, sep, self.base_coin) if self.tail is not None: base_str = "{}{}{}".format(base_str, sep, self.tail) return base_str
''' Return the nth Fibonacci number F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 ''' def Fibonacci(n): ''' return nth fibonacci number to reduce O(n), we invoke recursion only once during one call (Fn-1, Fn-2) ''' if n <= 1: return (n,0) else: (a,b) = Fibonacci(n-1) return (a+b,a) #print(Fibonacci(9)[0]) ''' sum the elements of a sequence recursively ''' def linear_sum(data): if len(data) == 0 : return 0 else: return data[len(data)-1]+linear_sum(data[0:len(data)-1]) # a = [4,3,6,2,8,9,3,2,8,5,1,7,2,8,3,7] # print(linear_sum(a)) # b = [4,3,6,2,8] # print(linear_sum(b)) ''' reverse a sequence with recursion ''' def reverse_seq(sequence,start,stop): if len(sequence[start:stop]) != 1: print(start,stop) sequence[stop-1],sequence[start] = sequence[start],sequence[stop-1] reverse_seq(sequence,start+1,stop-1) return sequence # a = [1,2,3,4,5] # print(reverse_seq(a,start= 0,stop = len(a))) ''' computing powers x**n = x * x**(n-1) ''' def compute_powers(x,n): if n == 0 : return 1 else: x = x * compute_powers(x,n-1) return x print(compute_powers(2,5))
thisdict = { "brand":"Ford", "model":"Mustang", "year":1964 } for x in thisdict.values(): print(x)
# Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths # of all of them are known. The bars can be put one on the top of the other if their lengths are the same. # Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the # best way possible. # We are given a list of integers (1<= N <= 1000) — the lengths of the bars. All the lengths are natural # numbers not exceeding 1000. Find the height of the largest tower and their total number. Remember that # Vasya should use all the bars. def partition(T, p, r): pivot = T[r] i = p - 1 for j in range(p, r): if T[j] <= pivot: i += 1 T[i], T[j] = T[j], T[i] T[i + 1], T[r] = T[r], T[i + 1] return i + 1 def quicksort(T, p, r): while p < r: q = partition(T, p, r) if q - p <= r - q: quicksort(T, p, q - 1) p = q + 1 else: quicksort(T, q, r) r = q - 1 def towers(T): quicksort(T, 0, len(T) - 1) previous = T[0] count = 1 max_height = actual_height = 1 for i in range(1, len(T)): if T[i] == previous: actual_height += 1 max_height = max(max_height, actual_height) else: previous = T[i] actual_height = 1 count += 1 return (max_height, count) T = [1, 8, 2, 3, 9, 3, 15, 15, 3] print(towers(T))
name = "ada lovelace" print(name.title()) print(name.upper()) print(name.lower())
#!/usr/bin/env python """ Class definition to store attributes of micro architectural events This module provides definitions for the following events 1. generic core - events programmable in general purpose pmu registers 2. fixed core - events colleted by fixed pmu registers 3. offcore - counters for offcore requests and responses Author: Manikandan Dhamodharan, Morgan Stanley """ class GenericCoreEvent(object): """Generic PMU Core Event""" eventType = 'GenericCore' def __init__(self): self.eventType = GenericCoreEvent.eventType self.name = None self.eventSelect = None self.unitMask = None self.counterMask = None self.invert = None self.briefDescription = None self.description = None self._validSmtPmc = None self._validPmc = None self.msrIndex = None self.msrValue = None self.anyThread = None self.edgeDetect = None self.pebs = None self.takenAlone = None self.dataLA = None self.l1HitIndication = None self.errata = None self.isOffCore = False @property def validPmc(self): """returns a set of programmable pmc registers""" return self._validPmc if self._validPmc else self._validSmtPmc def unInitialized(self): """Checks if all required attribues are initialized""" return ( self.name is None or self.eventSelect is None or self.unitMask is None or self.counterMask is None or self.invert is None or self.briefDescription is None or self.description is None or self.validPmc is None or self.msrIndex is None or self.msrValue is None or self.anyThread is None or self.edgeDetect is None or self.pebs is None ) def rawValue(self): """Returns a raw bit mask for this event""" val = self.eventSelect | (self.unitMask << 8) val |= self.edgeDetect << 18 val |= self.anyThread << 21 val |= self.counterMask << 24 val |= self.invert << 23 return val def canUse(self, counterIndex): """ Checks if this pmu event can be programmed at given register index :param counterIndex: Index of the register to check """ return counterIndex in self.validPmc # pylint: disable=unsupported-membership-test def isConstrained(self): """Checks if this event imposes, any constraints on programmable registers""" return len(self.validPmc) < 8 def __repr__(self): """Returns string representation of this generic core event""" counterMaskRepr = ' [CMask-{}]'.format(self.counterMask) if self.counterMask else '' return '{:60s} [0x{:08X}] - {}{}'.format(self.name, self.rawValue(), self.briefDescription, counterMaskRepr) def __eq__(self, other): return self.__dict__ == other.__dict__ class FixedCoreEvent(GenericCoreEvent): """Fixed PMU Core Event""" eventType = 'FixedCore' def __init__(self): GenericCoreEvent.__init__(self) self.eventType = FixedCoreEvent.eventType def __repr__(self): eventName = '{} (FixedCtr {})'.format(self.name, self.validPmc) return '{:60s} [FixedCtr-{}] - {}'.format(eventName, self.validPmc, self.briefDescription) class OffCoreEvent(GenericCoreEvent): """ Offcore events need to program two general purpose counter with with request and response event select codes in addition to two request/response msr registers. The event select in this case will be an array instead of a scalar value """ eventType = 'OffCore' eventSelects = [int('B7', 16), int('BB', 16)] def __init__(self): GenericCoreEvent.__init__(self) self.eventType = OffCoreEvent.eventType self.isOffCore = True def __repr__(self): """str representation of a PMUGpEvent""" return '{:60s} [0x{:02X},0x{:02X}|0x{:02X}] - {}'.format( self.name, self.eventSelect[0], self.eventSelect[1] if len(self.eventSelect) > 1 else 0, # pylint: disable=unsubscriptable-object self.unitMask, self.briefDescription ) class UnCoreEvent(object): """Offcore PMU Core Event""" eventType = 'UnCore' def __init__(self): self.eventType = UnCoreEvent.eventType
""" Functions for working with, checking and converting numbers. All numbers are stored within the computer as the positive equivalent. They may be interpreted as negative. """ def number_to_bitstring(number, bit_width=8): """ Convert a number to an equivalent bitstring of the given width. Raises: ValueError: If number doesn't fit in the bit width. """ if not number_is_within_bit_limit(number, bit_width=bit_width): raise ValueError( "{number} will not fit in {num_bits} bits.".format( number=number, num_bits=bit_width ) ) number = get_positive_equivalent(number) return "{number:0{bit_width}b}".format( number=number, bit_width=bit_width ) def number_is_within_bit_limit(number, bit_width=8): """ Check if a number can be stored in the number of bits given. Negative numbers are stored in 2's compliment binary. Args: number (int): The number to check. bit_width (int, optional): The number of bits available. Returns: bool: True if within limits, False if not. """ min_val = (2**bit_width / 2) * -1 max_val = 2**bit_width - 1 return min_val <= number <= max_val def get_positive_equivalent(number): """ Read the 2's compliment equivalent of this number as positive. With a 3 bit number, the positive equivalent of -2 is 5. E.g.:: -4 4 100 -3 5 101 -2 6 110 -1 7 111 0 0 000 1 1 001 2 2 010 3 3 011 Args: number (int): The number to convert to a positive quivalent Returns: int: The positive equivalent of the number. """ ret = number if number < 0: ret = number + 256 return ret def bitstring_to_number(bitstring): """ Convert a bitstring to a number. E.g. ``10110101`` gives 181. Args: bitstring (str): String of ``1``\ s and ``0``\ s. Returns: int: The equivalent integer. """ return int(bitstring, 2) def bitstring_to_hex_string(bitstring, zero_pad_width=2): """ Convert a bitstring to a hex number. Args: bitstring (str): String of ``1``\ s and ``0``\ s. zero_pad_width (int) (optional): How many zeroes to pad the returned hex value with. """ return "{num:0{zero_pad_width}X}".format( num=int(bitstring, 2), zero_pad_width=zero_pad_width )
def has_style(tag): return tag.has_attr('style') def has_class(tag): return tag.has_attr('class') def clean(soup): if soup.name == 'br' or soup.name == 'img' or soup.name == 'p' or soup.name == 'div': return try: ll = 0 for j in soup.strings: ll += len(j.replace('\n', '')) if ll == 0: soup.decompose() else: for child in soup.children: clean(child) except Exception as e: pass def dfs(soup, v): if soup.name == 'a' or soup.name == 'br': return try: lt = len(soup.get_text()) ls = len(str(soup)) a = soup.find_all('a') at = 0 for j in a: at += len(j.get_text()) lvt = lt - at v.append((soup, lt / ls * lvt)) for child in soup.children: dfs(child, v) except Exception as e: pass def extract(soup, text_only = True, remove_img = True): filt = ['script', 'noscript', 'style', 'embed', 'label', 'form', 'input', 'iframe', 'head', 'meta', 'link', 'object', 'aside', 'channel'] if remove_img: filt.append('img') for ff in filt: for i in soup.find_all(ff): i.decompose() for tag in soup.find_all(has_style): del tag['style'] for tag in soup.find_all(has_class): del tag['class'] clean(soup) LVT = len(soup.get_text()) for i in soup.find_all('a'): LVT -= len(i.get_text()) v = [] dfs(soup, v) mij = 0 for i in range(len(v)): if v[i][1] > v[mij][1]: mij = i if text_only: res = v[mij][0].get_text() else: res = str(v[mij][0]) return res, v[mij][1] / LVT
# # PySNMP MIB module HIRSCHMANN-PIM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIRSCHMANN-PIM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:12 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, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") hmPlatform4Multicast, = mibBuilder.importSymbols("HIRSCHMANN-MULTICAST-MIB", "hmPlatform4Multicast") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ipMRouteNextHopGroup, ipMRouteSourceMask, ipMRouteNextHopIfIndex, ipMRouteNextHopAddress, ipMRouteNextHopSourceMask, ipMRouteGroup, ipMRouteNextHopSource, ipMRouteSource = mibBuilder.importSymbols("IPMROUTE-STD-MIB", "ipMRouteNextHopGroup", "ipMRouteSourceMask", "ipMRouteNextHopIfIndex", "ipMRouteNextHopAddress", "ipMRouteNextHopSourceMask", "ipMRouteGroup", "ipMRouteNextHopSource", "ipMRouteSource") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") Gauge32, IpAddress, iso, Unsigned32, Bits, ModuleIdentity, ObjectIdentity, Integer32, TimeTicks, MibIdentifier, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "IpAddress", "iso", "Unsigned32", "Bits", "ModuleIdentity", "ObjectIdentity", "Integer32", "TimeTicks", "MibIdentifier", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Counter64") TruthValue, TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "TextualConvention", "RowStatus", "DisplayString") hmPIMMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 15, 4, 99)) hmPIMMIB.setRevisions(('2006-02-06 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hmPIMMIB.setRevisionsDescriptions(('Initial version, published as RFC 2934.',)) if mibBuilder.loadTexts: hmPIMMIB.setLastUpdated('200602061200Z') if mibBuilder.loadTexts: hmPIMMIB.setOrganization('Hirschmann Automation and Control GmbH') if mibBuilder.loadTexts: hmPIMMIB.setContactInfo('Customer Support Postal: Hirschmann Automation and Control GmbH Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Tel: +49 7127 14 1981 Web: http://www.hicomcenter.com/ E-Mail: hicomcenter@hirschmann.com') if mibBuilder.loadTexts: hmPIMMIB.setDescription('The Hirschmann Private Platform4 PIM MIB definitions for Platform devices.') hmPIMMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1)) hmPIMTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 0)) hmPIM = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1)) hmPIMJoinPruneInterval = MibScalar((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 1), Integer32()).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hmPIMJoinPruneInterval.setStatus('current') if mibBuilder.loadTexts: hmPIMJoinPruneInterval.setDescription('The default interval at which periodic PIM-SM Join/Prune messages are to be sent.') hmPIMInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2), ) if mibBuilder.loadTexts: hmPIMInterfaceTable.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceTable.setDescription("The (conceptual) table listing the router's PIM interfaces. IGMP and PIM are enabled on all interfaces listed in this table.") hmPIMInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMInterfaceIfIndex")) if mibBuilder.loadTexts: hmPIMInterfaceEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceEntry.setDescription('An entry (conceptual row) in the hmPIMInterfaceTable.') hmPIMInterfaceIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hmPIMInterfaceIfIndex.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceIfIndex.setDescription('The ifIndex value of this PIM interface.') hmPIMInterfaceAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMInterfaceAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceAddress.setDescription('The IP address of the PIM interface.') hmPIMInterfaceNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMInterfaceNetMask.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceNetMask.setDescription('The network mask for the IP address of the PIM interface.') hmPIMInterfaceMode = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dense", 1), ("sparse", 2), ("sparseDense", 3))).clone('dense')).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMInterfaceMode.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceMode.setDescription('The configured mode of this PIM interface. A value of sparseDense is only valid for PIMv1.') hmPIMInterfaceDR = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 5), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMInterfaceDR.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceDR.setDescription('The Designated Router on this PIM interface. For point-to- point interfaces, this object has the value 0.0.0.0.') hmPIMInterfaceHelloInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 6), Integer32().clone(30)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMInterfaceHelloInterval.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceHelloInterval.setDescription('The frequency at which PIM Hello messages are transmitted on this interface.') hmPIMInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMInterfaceStatus.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceStatus.setDescription('The status of this entry. Creating the entry enables PIM on the interface; destroying the entry disables PIM on the interface.') hmPIMInterfaceJoinPruneInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 8), Integer32()).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMInterfaceJoinPruneInterval.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceJoinPruneInterval.setDescription('The frequency at which PIM Join/Prune messages are transmitted on this PIM interface. The default value of this object is the hmPIMJoinPruneInterval.') hmPIMInterfaceCBSRPreference = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMInterfaceCBSRPreference.setStatus('current') if mibBuilder.loadTexts: hmPIMInterfaceCBSRPreference.setDescription('The preference value for the local interface as a candidate bootstrap router. The value of -1 is used to indicate that the local interface is not a candidate BSR interface.') hmPIMNeighborTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3), ) if mibBuilder.loadTexts: hmPIMNeighborTable.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborTable.setDescription("The (conceptual) table listing the router's PIM neighbors.") hmPIMNeighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMNeighborAddress")) if mibBuilder.loadTexts: hmPIMNeighborEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborEntry.setDescription('An entry (conceptual row) in the hmPIMNeighborTable.') hmPIMNeighborAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1, 1), IpAddress()) if mibBuilder.loadTexts: hmPIMNeighborAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborAddress.setDescription('The IP address of the PIM neighbor for which this entry contains information.') hmPIMNeighborIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1, 2), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMNeighborIfIndex.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborIfIndex.setDescription('The value of ifIndex for the interface used to reach this PIM neighbor.') hmPIMNeighborUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMNeighborUpTime.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborUpTime.setDescription('The time since this PIM neighbor (last) became a neighbor of the local router.') hmPIMNeighborExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1, 4), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMNeighborExpiryTime.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborExpiryTime.setDescription('The minimum time remaining before this PIM neighbor will be aged out.') hmPIMNeighborMode = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("dense", 1), ("sparse", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMNeighborMode.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMNeighborMode.setDescription('The active PIM mode of this neighbor. This object is deprecated for PIMv2 routers since all neighbors on the interface must be either dense or sparse as determined by the protocol running on the interface.') hmPIMIpMRouteTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4), ) if mibBuilder.loadTexts: hmPIMIpMRouteTable.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteTable.setDescription('The (conceptual) table listing PIM-specific information on a subset of the rows of the ipMRouteTable defined in the IP Multicast MIB.') hmPIMIpMRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteGroup"), (0, "IPMROUTE-STD-MIB", "ipMRouteSource"), (0, "IPMROUTE-STD-MIB", "ipMRouteSourceMask")) if mibBuilder.loadTexts: hmPIMIpMRouteEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteEntry.setDescription('An entry (conceptual row) in the hmPIMIpMRouteTable. There is one entry per entry in the ipMRouteTable whose incoming interface is running PIM.') hmPIMIpMRouteUpstreamAssertTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1, 1), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteUpstreamAssertTimer.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteUpstreamAssertTimer.setDescription('The time remaining before the router changes its upstream neighbor back to its RPF neighbor. This timer is called the Assert timer in the PIM Sparse and Dense mode specification. A value of 0 indicates that no Assert has changed the upstream neighbor away from the RPF neighbor.') hmPIMIpMRouteAssertMetric = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteAssertMetric.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteAssertMetric.setDescription('The metric advertised by the assert winner on the upstream interface, or 0 if no such assert is in received.') hmPIMIpMRouteAssertMetricPref = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteAssertMetricPref.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteAssertMetricPref.setDescription('The preference advertised by the assert winner on the upstream interface, or 0 if no such assert is in effect.') hmPIMIpMRouteAssertRPTBit = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1, 4), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteAssertRPTBit.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteAssertRPTBit.setDescription('The value of the RPT-bit advertised by the assert winner on the upstream interface, or false if no such assert is in effect.') hmPIMIpMRouteFlags = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 4, 1, 5), Bits().clone(namedValues=NamedValues(("rpt", 0), ("spt", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteFlags.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteFlags.setDescription('This object describes PIM-specific flags related to a multicast state entry. See the PIM Sparse Mode specification for the meaning of the RPT and SPT bits.') hmPIMIpMRouteNextHopTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 7), ) if mibBuilder.loadTexts: hmPIMIpMRouteNextHopTable.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteNextHopTable.setDescription('The (conceptual) table listing PIM-specific information on a subset of the rows of the ipMRouteNextHopTable defined in the IP Multicast MIB.') hmPIMIpMRouteNextHopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 7, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteNextHopGroup"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopSource"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopSourceMask"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopIfIndex"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopAddress")) if mibBuilder.loadTexts: hmPIMIpMRouteNextHopEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteNextHopEntry.setDescription('An entry (conceptual row) in the hmPIMIpMRouteNextHopTable. There is one entry per entry in the ipMRouteNextHopTable whose interface is running PIM and whose ipMRouteNextHopState is pruned(1).') hmPIMIpMRouteNextHopPruneReason = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("prune", 2), ("assert", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMIpMRouteNextHopPruneReason.setStatus('current') if mibBuilder.loadTexts: hmPIMIpMRouteNextHopPruneReason.setDescription('This object indicates why the downstream interface was pruned, whether in response to a PIM prune message or due to PIM Assert processing.') hmPIMRPTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5), ) if mibBuilder.loadTexts: hmPIMRPTable.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPTable.setDescription('The (conceptual) table listing PIM version 1 information for the Rendezvous Points (RPs) for IP multicast groups. This table is deprecated since its function is replaced by the hmPIMRPSetTable for PIM version 2.') hmPIMRPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMRPGroupAddress"), (0, "HIRSCHMANN-PIM-MIB", "hmPIMRPAddress")) if mibBuilder.loadTexts: hmPIMRPEntry.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPEntry.setDescription('An entry (conceptual row) in the hmPIMRPTable. There is one entry per RP address for each IP multicast group.') hmPIMRPGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 1), IpAddress()) if mibBuilder.loadTexts: hmPIMRPGroupAddress.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPGroupAddress.setDescription('The IP multicast group address for which this entry contains information about an RP.') hmPIMRPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 2), IpAddress()) if mibBuilder.loadTexts: hmPIMRPAddress.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPAddress.setDescription('The unicast address of the RP.') hmPIMRPState = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMRPState.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPState.setDescription('The state of the RP.') hmPIMRPStateTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 4), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMRPStateTimer.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPStateTimer.setDescription('The minimum time remaining before the next state change. When hmPIMRPState is up, this is the minimum time which must expire until it can be declared down. When hmPIMRPState is down, this is the time until it will be declared up (in order to retry).') hmPIMRPLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMRPLastChange.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPLastChange.setDescription('The value of sysUpTime at the time when the corresponding instance of hmPIMRPState last changed its value.') hmPIMRPRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 5, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMRPRowStatus.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMRPRowStatus.setDescription('The status of this row, by which new entries may be created, or old entries deleted from this table.') hmPIMRPSetTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6), ) if mibBuilder.loadTexts: hmPIMRPSetTable.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetTable.setDescription('The (conceptual) table listing PIM information for candidate Rendezvous Points (RPs) for IP multicast groups. When the local router is the BSR, this information is obtained from received Candidate-RP-Advertisements. When the local router is not the BSR, this information is obtained from received RP-Set messages.') hmPIMRPSetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMRPSetComponent"), (0, "HIRSCHMANN-PIM-MIB", "hmPIMRPSetGroupAddress"), (0, "HIRSCHMANN-PIM-MIB", "hmPIMRPSetGroupMask"), (0, "HIRSCHMANN-PIM-MIB", "hmPIMRPSetAddress")) if mibBuilder.loadTexts: hmPIMRPSetEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetEntry.setDescription('An entry (conceptual row) in the hmPIMRPSetTable.') hmPIMRPSetGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 1), IpAddress()) if mibBuilder.loadTexts: hmPIMRPSetGroupAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetGroupAddress.setDescription('The IP multicast group address which, when combined with hmPIMRPSetGroupMask, gives the group prefix for which this entry contains information about the Candidate-RP.') hmPIMRPSetGroupMask = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 2), IpAddress()) if mibBuilder.loadTexts: hmPIMRPSetGroupMask.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetGroupMask.setDescription('The multicast group address mask which, when combined with hmPIMRPSetGroupAddress, gives the group prefix for which this entry contains information about the Candidate-RP.') hmPIMRPSetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 3), IpAddress()) if mibBuilder.loadTexts: hmPIMRPSetAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetAddress.setDescription('The IP address of the Candidate-RP.') hmPIMRPSetHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMRPSetHoldTime.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetHoldTime.setDescription('The holdtime of a Candidate-RP. If the local router is not the BSR, this value is 0.') hmPIMRPSetExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMRPSetExpiryTime.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetExpiryTime.setDescription('The minimum time remaining before the Candidate-RP will be declared down. If the local router is not the BSR, this value is 0.') hmPIMRPSetComponent = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))) if mibBuilder.loadTexts: hmPIMRPSetComponent.setStatus('current') if mibBuilder.loadTexts: hmPIMRPSetComponent.setDescription(' A number uniquely identifying the component. Each protocol instance connected to a separate domain should have a different index value.') hmPIMCandidateRPTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11), ) if mibBuilder.loadTexts: hmPIMCandidateRPTable.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPTable.setDescription('The (conceptual) table listing the IP multicast groups for which the local router is to advertise itself as a Candidate-RP when the value of hmPIMComponentCRPHoldTime is non-zero. If this table is empty, then the local router will advertise itself as a Candidate-RP for all groups (providing the value of hmPIMComponentCRPHoldTime is non- zero).') hmPIMCandidateRPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMCandidateRPGroupAddress"), (0, "HIRSCHMANN-PIM-MIB", "hmPIMCandidateRPGroupMask")) if mibBuilder.loadTexts: hmPIMCandidateRPEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPEntry.setDescription('An entry (conceptual row) in the hmPIMCandidateRPTable.') hmPIMCandidateRPGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11, 1, 1), IpAddress()) if mibBuilder.loadTexts: hmPIMCandidateRPGroupAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPGroupAddress.setDescription('The IP multicast group address which, when combined with hmPIMCandidateRPGroupMask, identifies a group prefix for which the local router will advertise itself as a Candidate-RP.') hmPIMCandidateRPGroupMask = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11, 1, 2), IpAddress()) if mibBuilder.loadTexts: hmPIMCandidateRPGroupMask.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPGroupMask.setDescription('The multicast group address mask which, when combined with hmPIMCandidateRPGroupMask, identifies a group prefix for which the local router will advertise itself as a Candidate-RP.') hmPIMCandidateRPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11, 1, 3), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMCandidateRPAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPAddress.setDescription('The (unicast) address of the interface which will be advertised as a Candidate-RP.') hmPIMCandidateRPRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 11, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMCandidateRPRowStatus.setStatus('current') if mibBuilder.loadTexts: hmPIMCandidateRPRowStatus.setDescription('The status of this row, by which new entries may be created, or old entries deleted from this table.') hmPIMComponentTable = MibTable((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12), ) if mibBuilder.loadTexts: hmPIMComponentTable.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentTable.setDescription('The (conceptual) table containing objects specific to a PIM domain. One row exists for each domain to which the router is connected. A PIM-SM domain is defined as an area of the network over which Bootstrap messages are forwarded. Typically, a PIM-SM router will be a member of exactly one domain. This table also supports, however, routers which may form a border between two PIM-SM domains and do not forward Bootstrap messages between them.') hmPIMComponentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1), ).setIndexNames((0, "HIRSCHMANN-PIM-MIB", "hmPIMComponentIndex")) if mibBuilder.loadTexts: hmPIMComponentEntry.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentEntry.setDescription('An entry (conceptual row) in the hmPIMComponentTable.') hmPIMComponentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))) if mibBuilder.loadTexts: hmPIMComponentIndex.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentIndex.setDescription('A number uniquely identifying the component. Each protocol instance connected to a separate domain should have a different index value. Routers that only support membership in a single PIM-SM domain should use a hmPIMComponentIndex value of 1.') hmPIMComponentBSRAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMComponentBSRAddress.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentBSRAddress.setDescription('The IP address of the bootstrap router (BSR) for the local PIM region.') hmPIMComponentBSRExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: hmPIMComponentBSRExpiryTime.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentBSRExpiryTime.setDescription('The minimum time remaining before the bootstrap router in the local domain will be declared down. For candidate BSRs, this is the time until the component sends an RP-Set message. For other routers, this is the time until it may accept an RP-Set message from a lower candidate BSR.') hmPIMComponentCRPHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMComponentCRPHoldTime.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentCRPHoldTime.setDescription('The holdtime of the component when it is a candidate RP in the local domain. The value of 0 is used to indicate that the local system is not a Candidate-RP.') hmPIMComponentStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 1, 12, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hmPIMComponentStatus.setStatus('current') if mibBuilder.loadTexts: hmPIMComponentStatus.setDescription('The status of this entry. Creating the entry creates another protocol instance; destroying the entry disables a protocol instance.') hmPIMNeighborLoss = NotificationType((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 1, 0, 1)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMNeighborIfIndex")) if mibBuilder.loadTexts: hmPIMNeighborLoss.setStatus('current') if mibBuilder.loadTexts: hmPIMNeighborLoss.setDescription('A hmPIMNeighborLoss trap signifies the loss of an adjacency with a neighbor. This trap should be generated when the neighbor timer expires, and the router has no other neighbors on the same interface with a lower IP address than itself.') hmPIMMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2)) hmPIMMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 1)) hmPIMMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2)) hmPIMV1MIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 1, 1)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMV1MIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMV1MIBCompliance = hmPIMV1MIBCompliance.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMV1MIBCompliance.setDescription('The compliance statement for routers running PIMv1 and implementing the PIM MIB.') hmPIMSparseV2MIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 1, 2)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMV2MIBGroup"), ("HIRSCHMANN-PIM-MIB", "hmPIMV2CandidateRPMIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMSparseV2MIBCompliance = hmPIMSparseV2MIBCompliance.setStatus('current') if mibBuilder.loadTexts: hmPIMSparseV2MIBCompliance.setDescription('The compliance statement for routers running PIM Sparse Mode and implementing the PIM MIB.') hmPIMDenseV2MIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 1, 3)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMDenseV2MIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMDenseV2MIBCompliance = hmPIMDenseV2MIBCompliance.setStatus('current') if mibBuilder.loadTexts: hmPIMDenseV2MIBCompliance.setDescription('The compliance statement for routers running PIM Dense Mode and implementing the PIM MIB.') hmPIMNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 1)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMNeighborLoss")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMNotificationGroup = hmPIMNotificationGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMNotificationGroup.setDescription('A collection of notifications for signaling important PIM events.') hmPIMV2MIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 2)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMJoinPruneInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborIfIndex"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborUpTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborExpiryTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceAddress"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceNetMask"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceDR"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceHelloInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceStatus"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceJoinPruneInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceCBSRPreference"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceMode"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPSetHoldTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPSetExpiryTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMComponentBSRAddress"), ("HIRSCHMANN-PIM-MIB", "hmPIMComponentBSRExpiryTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMComponentCRPHoldTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMComponentStatus"), ("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteFlags"), ("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteUpstreamAssertTimer")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMV2MIBGroup = hmPIMV2MIBGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMV2MIBGroup.setDescription('A collection of objects to support management of PIM Sparse Mode (version 2) routers.') hmPIMDenseV2MIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 5)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMNeighborIfIndex"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborUpTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborExpiryTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceAddress"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceNetMask"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceDR"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceHelloInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceStatus"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceMode")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMDenseV2MIBGroup = hmPIMDenseV2MIBGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMDenseV2MIBGroup.setDescription('A collection of objects to support management of PIM Dense Mode (version 2) routers.') hmPIMV2CandidateRPMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 3)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMCandidateRPAddress"), ("HIRSCHMANN-PIM-MIB", "hmPIMCandidateRPRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMV2CandidateRPMIBGroup = hmPIMV2CandidateRPMIBGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMV2CandidateRPMIBGroup.setDescription('A collection of objects to support configuration of which groups a router is to advertise itself as a Candidate-RP.') hmPIMV1MIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 4)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMJoinPruneInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborIfIndex"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborUpTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborExpiryTime"), ("HIRSCHMANN-PIM-MIB", "hmPIMNeighborMode"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceAddress"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceNetMask"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceJoinPruneInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceStatus"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceMode"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceDR"), ("HIRSCHMANN-PIM-MIB", "hmPIMInterfaceHelloInterval"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPState"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPStateTimer"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPLastChange"), ("HIRSCHMANN-PIM-MIB", "hmPIMRPRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMV1MIBGroup = hmPIMV1MIBGroup.setStatus('deprecated') if mibBuilder.loadTexts: hmPIMV1MIBGroup.setDescription('A collection of objects to support management of PIM (version 1) routers.') hmPIMNextHopGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 6)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteNextHopPruneReason")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMNextHopGroup = hmPIMNextHopGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMNextHopGroup.setDescription('A collection of optional objects to provide per-next hop information for diagnostic purposes. Supporting this group may add a large number of instances to a tree walk, but the information in this group can be extremely useful in tracking down multicast connectivity problems.') hmPIMAssertGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 248, 15, 4, 99, 2, 2, 7)).setObjects(("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteAssertMetric"), ("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteAssertMetricPref"), ("HIRSCHMANN-PIM-MIB", "hmPIMIpMRouteAssertRPTBit")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hmPIMAssertGroup = hmPIMAssertGroup.setStatus('current') if mibBuilder.loadTexts: hmPIMAssertGroup.setDescription('A collection of optional objects to provide extra information about the assert election process. There is no protocol reason to keep such information, but some implementations may already keep this information and make it available. These objects can also be very useful in debugging connectivity or duplicate packet problems, especially if the assert winner does not support the PIM and IP Multicast MIBs.') mibBuilder.exportSymbols("HIRSCHMANN-PIM-MIB", hmPIMComponentEntry=hmPIMComponentEntry, hmPIMInterfaceHelloInterval=hmPIMInterfaceHelloInterval, hmPIMCandidateRPTable=hmPIMCandidateRPTable, hmPIMIpMRouteNextHopTable=hmPIMIpMRouteNextHopTable, hmPIMMIBObjects=hmPIMMIBObjects, hmPIMIpMRouteAssertMetricPref=hmPIMIpMRouteAssertMetricPref, hmPIMIpMRouteTable=hmPIMIpMRouteTable, hmPIMDenseV2MIBGroup=hmPIMDenseV2MIBGroup, hmPIMCandidateRPEntry=hmPIMCandidateRPEntry, hmPIMJoinPruneInterval=hmPIMJoinPruneInterval, hmPIMMIBCompliances=hmPIMMIBCompliances, hmPIMCandidateRPAddress=hmPIMCandidateRPAddress, hmPIMComponentBSRExpiryTime=hmPIMComponentBSRExpiryTime, hmPIMMIB=hmPIMMIB, hmPIMIpMRouteAssertRPTBit=hmPIMIpMRouteAssertRPTBit, hmPIMComponentCRPHoldTime=hmPIMComponentCRPHoldTime, hmPIMRPLastChange=hmPIMRPLastChange, hmPIMComponentTable=hmPIMComponentTable, hmPIMNeighborIfIndex=hmPIMNeighborIfIndex, hmPIMRPSetTable=hmPIMRPSetTable, hmPIMComponentStatus=hmPIMComponentStatus, PYSNMP_MODULE_ID=hmPIMMIB, hmPIMMIBConformance=hmPIMMIBConformance, hmPIMRPStateTimer=hmPIMRPStateTimer, hmPIMNeighborTable=hmPIMNeighborTable, hmPIMNextHopGroup=hmPIMNextHopGroup, hmPIMAssertGroup=hmPIMAssertGroup, hmPIMNeighborMode=hmPIMNeighborMode, hmPIMInterfaceTable=hmPIMInterfaceTable, hmPIMRPSetAddress=hmPIMRPSetAddress, hmPIMInterfaceMode=hmPIMInterfaceMode, hmPIMSparseV2MIBCompliance=hmPIMSparseV2MIBCompliance, hmPIMRPGroupAddress=hmPIMRPGroupAddress, hmPIMCandidateRPRowStatus=hmPIMCandidateRPRowStatus, hmPIMRPSetHoldTime=hmPIMRPSetHoldTime, hmPIMRPTable=hmPIMRPTable, hmPIMIpMRouteAssertMetric=hmPIMIpMRouteAssertMetric, hmPIMMIBGroups=hmPIMMIBGroups, hmPIMInterfaceNetMask=hmPIMInterfaceNetMask, hmPIMRPSetEntry=hmPIMRPSetEntry, hmPIMInterfaceDR=hmPIMInterfaceDR, hmPIMInterfaceAddress=hmPIMInterfaceAddress, hmPIMIpMRouteEntry=hmPIMIpMRouteEntry, hmPIMV2CandidateRPMIBGroup=hmPIMV2CandidateRPMIBGroup, hmPIMNeighborEntry=hmPIMNeighborEntry, hmPIMRPSetGroupMask=hmPIMRPSetGroupMask, hmPIMTraps=hmPIMTraps, hmPIMIpMRouteUpstreamAssertTimer=hmPIMIpMRouteUpstreamAssertTimer, hmPIMInterfaceStatus=hmPIMInterfaceStatus, hmPIMRPAddress=hmPIMRPAddress, hmPIMInterfaceIfIndex=hmPIMInterfaceIfIndex, hmPIMRPEntry=hmPIMRPEntry, hmPIMNeighborUpTime=hmPIMNeighborUpTime, hmPIMNeighborLoss=hmPIMNeighborLoss, hmPIMInterfaceEntry=hmPIMInterfaceEntry, hmPIMNeighborAddress=hmPIMNeighborAddress, hmPIMCandidateRPGroupAddress=hmPIMCandidateRPGroupAddress, hmPIMRPRowStatus=hmPIMRPRowStatus, hmPIMDenseV2MIBCompliance=hmPIMDenseV2MIBCompliance, hmPIMNotificationGroup=hmPIMNotificationGroup, hmPIMIpMRouteNextHopPruneReason=hmPIMIpMRouteNextHopPruneReason, hmPIMCandidateRPGroupMask=hmPIMCandidateRPGroupMask, hmPIMComponentBSRAddress=hmPIMComponentBSRAddress, hmPIMRPSetComponent=hmPIMRPSetComponent, hmPIMV2MIBGroup=hmPIMV2MIBGroup, hmPIMV1MIBGroup=hmPIMV1MIBGroup, hmPIMInterfaceCBSRPreference=hmPIMInterfaceCBSRPreference, hmPIMRPSetGroupAddress=hmPIMRPSetGroupAddress, hmPIMComponentIndex=hmPIMComponentIndex, hmPIMInterfaceJoinPruneInterval=hmPIMInterfaceJoinPruneInterval, hmPIMNeighborExpiryTime=hmPIMNeighborExpiryTime, hmPIMRPSetExpiryTime=hmPIMRPSetExpiryTime, hmPIMV1MIBCompliance=hmPIMV1MIBCompliance, hmPIM=hmPIM, hmPIMIpMRouteFlags=hmPIMIpMRouteFlags, hmPIMRPState=hmPIMRPState, hmPIMIpMRouteNextHopEntry=hmPIMIpMRouteNextHopEntry)
""" [Question.py] @description: a set of functions which helps with asking console questions. """ def ask(question): print(question) answer = input("Response: ") return answer def ask_bool_positive_safe(question): answer = input(question + " ") return (answer.lower() == "true") or \ (answer.lower() == "t") or \ (answer.lower() == "yes") or \ (answer.lower() == "y") or \ (answer == "1") def bool_negative_safe_question(question): answer = input(question + " ") return (answer.lower() == "false") or \ (answer.lower() == "f") or \ (answer.lower() == "no") or \ (answer.lower() == "n") or \ (answer == "0") def ask_type(question, ans_type, loop=True): """ Used to ask and assert that the response to the question will be an integer :param question: what to ask :return: the result, of type specified """ answer = ask(question) if loop: # Loops until the user while loop: try: ans_type(answer) loop = False except: print("Please enter an", ans_type, "answer.") answer = ask(question) else: try: ans_type(answer) except: print("Error. The answer was not an " + str(ans_type) + ".") return int(answer) def ask_int(question, loop=True): return ask_type(question=question, ans_type=int, loop=loop) def ask_float(question, loop=True): return ask_type(question=question, ans_type=float, loop=loop)
# 1. Write a function called int_return that takes an integer as input and returns the same integer. user_input = input("Enter a number") def int_return(val): return int(val) int_return(user_input) # 2. Write a function called add that takes any number as its input and returns that sum with 2 added. user_input = input("Enter a number:") def add(val): sum_val = int(val) + 2 return sum_val add(user_input) # 3. Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given, and returns that new string. user_input = input("Enter a Sentence:") def change(val): nice = "Nice to meet you!" final = val + nice return final change(user_input) # 4. Write a function, accum, that takes a list of integers as input and returns the sum of those integers. intList = [1,2,3,5,15,62] def accum (numList): sumInt = 0 for num in numList: sumInt = sumInt + num return sumInt accum(intList) # 5. Write a function, length, that takes in a list as the input. If the length of the list is greater than or equal to 5, return “Longer than 5”. # If the length is less than 5, return “Less than 5”. intList = [1,2,3,5,15,62] def length (numList): count = 0 for num in numList: count = count + 1 if count >= 5: return "Longer than 5" else: return "Less than 5" length(intList) # 6. You will need to write two functions for this problem. The first function, divide that takes in any number and returns that same number divided # by 2. The second function called sum should take any number, divide it by 2, and add 6. It should return this new number. You should call the divide # function within the sum function. Do not worry about decimals. def divide(num): return num / 2 def sum(num): return (num / 2) + 6 sum(divide(10))
load( "@d2l_rules_csharp//csharp:defs.bzl", "csharp_register_toolchains", "csharp_repositories", "import_nuget_package", ) def selenium_register_dotnet(): csharp_register_toolchains() csharp_repositories() native.register_toolchains("//third_party/dotnet/ilmerge:all") import_nuget_package( name = "json.net", file = "third_party/dotnet/nuget/packages/newtonsoft.json.12.0.2.nupkg", sha256 = "056eec5d3d8b2a93f7ca5b026d34d9d5fe8c835b11e322faf1a2551da25c4e70", ) import_nuget_package( name = "moq", file = "third_party/dotnet/nuget/packages/moq.4.12.0.nupkg", sha256 = "339bbb71107e137a753a89c6b74adb5d9072f0916cf8f19f48b30ae29c41f434", ) import_nuget_package( name = "benderproxy", file = "third_party/dotnet/nuget/packages/benderproxy.1.0.0.nupkg", sha256 = "fd536dc97eb71268392173e7c4c0699795a31f6843470134ee068ade1be4b57d", ) import_nuget_package( name = "castle.core", file = "third_party/dotnet/nuget/packages/castle.core.4.4.0.nupkg", sha256 = "ee12c10079c1f9daebdb2538c37a34e5e317d800f2feb5cddd744f067d5dec66", ) import_nuget_package( name = "nunit", file = "third_party/dotnet/nuget/packages/nunit.3.12.0.nupkg" #sha256 = "056eec5d3d8b2a93f7ca5b026d34d9d5fe8c835b11e322faf1a2551da25c4e70", ) #import_nuget_package( # name = "system.threading.tasks.extensions", # package = "system.threading.tasks.extensions", # version = "4.5.1", #) #import_nuget_package( # name = "nunit", # package = "nunit", # version = "3.12.0", #)
wifi_ssid = "" wifi_password = "" mqtt_username = "" mqtt_password = "" mqtt_address = "" mqtt_port = 8883
# NOTE: \a is the delimiter for chat pages # Quest ids can be found in Quests.py SCRIPT = ''' ID reward_100 SHOW laffMeter LERP_POS laffMeter 0 0 0 1 LERP_SCALE laffMeter 0.2 0.2 0.2 1 WAIT 1.5 ADD_LAFFMETER 1 WAIT 1 LERP_POS laffMeter -1.18 0 -0.87 1 LERP_SCALE laffMeter 0.075 0.075 0.075 1 WAIT 1 FINISH_QUEST_MOVIE # TUTORIAL ID tutorial_mickey LOAD_SFX soundRun "phase_3.5/audio/sfx/AV_footstep_runloop.ogg" LOAD_CC_DIALOGUE mickeyTutorialDialogue_1 "phase_3/audio/dial/CC_%s_tutorial02.ogg" LOAD_CC_DIALOGUE mickeyTutorialDialogue_2 "phase_3.5/audio/dial/CC_tom_tutorial_%s01.ogg" LOAD_CC_DIALOGUE mickeyTutorialDialogue_3a "phase_3/audio/dial/CC_%s_tutorial03.ogg" LOAD_CC_DIALOGUE mickeyTutorialDialogue_3b "phase_3/audio/dial/CC_%s_tutorial05.ogg" LOAD_DIALOGUE mickeyTutorialDialogue_4 "phase_3.5/audio/dial/CC_tom_tutorial_mickey02.ogg" LOCK_LOCALTOON REPARENTTO camera render POSHPRSCALE camera 11 7 3 52 0 0 1 1 1 LOAD_CLASSIC_CHAR classicChar REPARENTTO classicChar render POS classicChar 0 0 0 HPR classicChar 0 0 0 POS localToon 0 0 0 HPR localToon 0 0 0 WAIT 2 PLAY_SFX soundRun 1 LOOP_ANIM classicChar "run" LOOP_ANIM localToon "run" LERP_POS localToon -1.8 14.4 0 2 LERP_POS classicChar 0 17 0 2 WAIT 2 #LERP_HPR localToon -110 0 0 0.5 LERP_HPR localToon -70 0 0 0.5 LERP_HPR classicChar -120 0 0 0.5 WAIT 0.5 STOP_SFX soundRun LOOP_ANIM localToon "neutral" PLAY_ANIM classicChar "left-point-start" 1 WAIT 1.63 LOOP_ANIM classicChar "left-point" CC_CHAT_CONFIRM classicChar "QuestScriptTutorial%s_1" mickeyTutorialDialogue_1 PLAY_ANIM classicChar "left-point-start" -1.5 WAIT 1.0867 LOOP_ANIM classicChar "neutral" CC_CHAT_TO_CONFIRM npc classicChar "QuestScriptTutorial%s_2" "CFSpeech" mickeyTutorialDialogue_2 PLAY_ANIM classicChar "right-point-start" 1 WAIT 1.0867 LOOP_ANIM classicChar "right-point" CC_CHAT_CONFIRM classicChar "QuestScriptTutorial%s_3" mickeyTutorialDialogue_3a mickeyTutorialDialogue_3b PLAY_SFX soundRun 1 LOOP_ANIM classicChar "run" LERP_HPR classicChar -180 0 0 0.5 WAIT 0.5 LERP_POS classicChar 0 0 0 2 WAIT 2 STOP_SFX soundRun REPARENTTO classicChar hidden UNLOAD_CHAR classicChar #CHAT npc QuestScriptTutorialMickey_4 mickeyTutorialDialogue_4 REPARENTTO camera localToon POS localToon 1.6 9.8 0 HPR localToon 14 0 0 FREE_LOCALTOON LOCAL_CHAT_PERSIST npc QuestScriptTutorialMickey_4 mickeyTutorialDialogue_4 ID quest_assign_101 CLEAR_CHAT npc LOAD squirt1 "phase_3.5/models/gui/tutorial_gui" "squirt1" LOAD squirt2 "phase_3.5/models/gui/tutorial_gui" "squirt2" LOAD toonBuilding "phase_3.5/models/gui/tutorial_gui" "toon_buildings" LOAD cogBuilding "phase_3.5/models/gui/tutorial_gui" "suit_buildings" LOAD cogs "phase_3.5/models/gui/tutorial_gui" "suits" LOAD tart "phase_3.5/models/props/tart" LOAD flower "phase_3.5/models/props/squirting-flower" LOAD_DIALOGUE tomDialogue_01 "phase_3.5/audio/dial/CC_tom_tutorial_questscript01.ogg" LOAD_DIALOGUE tomDialogue_02 "phase_3.5/audio/dial/CC_tom_tutorial_questscript03.ogg" LOAD_DIALOGUE tomDialogue_03 "phase_3.5/audio/dial/CC_tom_tutorial_questscript04.ogg" LOAD_DIALOGUE tomDialogue_04 "phase_3.5/audio/dial/CC_tom_tutorial_questscript05.ogg" LOAD_DIALOGUE tomDialogue_05 "phase_3.5/audio/dial/CC_tom_tutorial_questscript06.ogg" LOAD_DIALOGUE tomDialogue_06 "phase_3.5/audio/dial/CC_tom_tutorial_questscript07.ogg" LOAD_DIALOGUE tomDialogue_07 "phase_3.5/audio/dial/CC_tom_tutorial_questscript08.ogg" LOAD_DIALOGUE tomDialogue_08 "phase_3.5/audio/dial/CC_tom_tutorial_questscript09.ogg" LOAD_DIALOGUE tomDialogue_09 "phase_3.5/audio/dial/CC_tom_tutorial_questscript10.ogg" LOAD_DIALOGUE tomDialogue_10 "phase_3.5/audio/dial/CC_tom_tutorial_questscript11.ogg" LOAD_DIALOGUE tomDialogue_11 "phase_3.5/audio/dial/CC_tom_tutorial_questscript12.ogg" LOAD_DIALOGUE tomDialogue_12 "phase_3.5/audio/dial/CC_tom_tutorial_questscript13.ogg" LOAD_DIALOGUE tomDialogue_13 "phase_3.5/audio/dial/CC_tom_tutorial_questscript14.ogg" LOAD_DIALOGUE tomDialogue_14 "phase_3.5/audio/dial/CC_tom_tutorial_questscript16.ogg" POSHPRSCALE cogs -1.05 7 0 0 0 0 1 1 1 POSHPRSCALE toonBuilding -1.05 7 0 0 0 0 1 1 1 POSHPRSCALE cogBuilding -1.05 7 0 0 0 0 1 1 1 POSHPRSCALE squirt1 -1.05 7 0 0 0 0 1 1 1 POSHPRSCALE squirt2 -1.05 7 0 0 0 0 1 1 1 REPARENTTO camera npc POS camera -2.2 5.2 3.3 HPR camera 215 5 0 WRTREPARENTTO camera localToon PLAY_ANIM npc "right-hand-start" 1 WAIT 1 REPARENTTO cogs aspect2d LERP_SCALE cogs 1 1 1 0.5 WAIT 1.0833 LOOP_ANIM npc "right-hand" 1 FUNCTION npc "angryEyes" FUNCTION npc "blinkEyes" LOCAL_CHAT_CONFIRM npc QuestScript101_1 "CFSpeech" tomDialogue_01 LOCAL_CHAT_CONFIRM npc QuestScript101_2 "CFSpeech" tomDialogue_02 REPARENTTO cogs hidden REPARENTTO toonBuilding camera LOCAL_CHAT_CONFIRM npc QuestScript101_3 "CFSpeech" tomDialogue_03 REPARENTTO toonBuilding hidden REPARENTTO cogBuilding camera FUNCTION npc "sadEyes" FUNCTION npc "blinkEyes" LOCAL_CHAT_CONFIRM npc QuestScript101_4 "CFSpeech" tomDialogue_04 REPARENTTO cogBuilding hidden REPARENTTO squirt1 camera FUNCTION npc "normalEyes" FUNCTION npc "blinkEyes" LOCAL_CHAT_CONFIRM npc QuestScript101_5 "CFSpeech" tomDialogue_05 REPARENTTO squirt1 hidden REPARENTTO squirt2 camera LOCAL_CHAT_CONFIRM npc QuestScript101_6 "CFSpeech" tomDialogue_06 PLAY_ANIM npc 'right-hand-start' -1.8 LERP_SCALE squirt2 1 1 0.01 0.5 WAIT 0.5 REPARENTTO squirt2 hidden WAIT 0.6574 LOOP_ANIM npc 'neutral' 1 LOCAL_CHAT_CONFIRM npc QuestScript101_7 "CFSpeech" tomDialogue_07 # Make it look like the client has no inventory. Since the toon.dc # specifies that the user really does have 1 of each item, we will # just put on a show for the client of not having any items then # handing them out. SET_INVENTORY 4 0 0 SET_INVENTORY 5 0 0 REPARENTTO inventory camera SHOW inventory SET_INVENTORY_DETAIL -1 POSHPRSCALE inventory -0.77 7.42 1.11 0 0 0 0.01 0.01 0.01 SET_INVENTORY_YPOS 4 0 -0.1 SET_INVENTORY_YPOS 5 0 -0.1 LERP_SCALE inventory 3 0.01 3 1 WAIT 1 REPARENTTO flower npc "**/1000/**/def_joint_right_hold" POSHPRSCALE flower 0.10 -0.14 0.20 180.00 287.10 168.69 0.70 0.70 0.70 PLAY_ANIM npc 'right-hand-start' 1.8 WAIT 1.1574 LOOP_ANIM npc 'right-hand' 1.1 WAIT 0.8 WRTREPARENTTO flower camera LERP_POSHPRSCALE flower -1.75 4.77 0.00 30.00 180.00 16.39 0.75 0.75 0.75 0.589 WAIT 1.094 LERP_POSHPRSCALE flower -1.76 7.42 -0.63 179.96 -89.9 -153.43 0.12 0.12 0.12 1 PLAY_ANIM npc 'right-hand-start' -1.5 WAIT 1 ADD_INVENTORY 5 0 1 POSHPRSCALE inventory -0.77 7.42 1.11 0 0 0 3 0.01 3 REPARENTTO flower hidden REPARENTTO tart npc "**/1000/**/def_joint_right_hold" POSHPRSCALE tart 0.19 0.02 0.00 0.00 0.00 349.38 0.34 0.34 0.34 PLAY_ANIM npc 'right-hand-start' 1.8 WAIT 1.1574 LOOP_ANIM npc 'right-hand' 1.1 WAIT 0.8 WRTREPARENTTO tart camera LERP_POSHPRSCALE tart -1.37 4.56 0 329.53 39.81 346.76 0.6 0.6 0.6 0.589 WAIT 1.094 LERP_POSHPRSCALE tart -1.66 7.42 -0.36 0 30 30 0.12 0.12 0.12 1.0 PLAY_ANIM npc 'right-hand-start' -1.5 WAIT 1 ADD_INVENTORY 4 0 1 POSHPRSCALE inventory -0.77 7.42 1.11 0 0 0 3 0.01 3 REPARENTTO tart hidden #PLAY_ANIM npc 'neutral' 1 #WAIT 2.0833 PLAY_ANIM npc 'right-hand-start' 1 WAIT 1.0 HIDE inventory REPARENTTO inventory hidden SET_INVENTORY_YPOS 4 0 0 SET_INVENTORY_YPOS 5 0 0 SET_INVENTORY_DETAIL 0 POSHPRSCALE inventory 0 0 0 0 0 0 1 1 1 OBSCURE_LAFFMETER 0 SHOW laffMeter POS laffMeter 0 0 0 SCALE laffMeter 0.075 0.075 0.075 LERP_POS laffMeter 1.7 0 0.87 1 LERP_SCALE laffMeter 0.2 0.2 0.2 0.6 WAIT 1.0833 LOOP_ANIM npc "right-hand" LOCAL_CHAT_CONFIRM npc QuestScript101_8 "CFSpeech" tomDialogue_08 LOCAL_CHAT_CONFIRM npc QuestScript101_9 "CFSpeech" tomDialogue_09 FUNCTION npc "sadEyes" FUNCTION npc "blinkEyes" LAFFMETER 15 15 WAIT 0.1 LAFFMETER 14 15 WAIT 0.1 LAFFMETER 13 15 WAIT 0.1 LAFFMETER 12 15 WAIT 0.1 LAFFMETER 11 15 WAIT 0.1 LAFFMETER 10 15 WAIT 0.1 LAFFMETER 9 15 WAIT 0.1 LAFFMETER 8 15 WAIT 0.1 LAFFMETER 7 15 WAIT 0.1 LAFFMETER 6 15 WAIT 0.1 LAFFMETER 5 15 WAIT 0.1 LAFFMETER 4 15 WAIT 0.1 LAFFMETER 3 15 WAIT 0.1 LAFFMETER 2 15 WAIT 0.1 LAFFMETER 1 15 WAIT 0.1 LAFFMETER 0 15 LOCAL_CHAT_CONFIRM npc QuestScript101_10 "CFSpeech" tomDialogue_10 FUNCTION npc "normalEyes" FUNCTION npc "blinkEyes" LAFFMETER 15 15 WAIT 0.5 LERP_POS laffMeter 0.15 0.15 0.15 1 LERP_SCALE laffMeter 0.085 0.085 0.085 0.6 PLAY_ANIM npc "right-hand-start" -2 WAIT 1.0625 LOOP_ANIM npc "neutral" WAIT 0.5 LERP_HPR npc -50 0 0 0.5 FUNCTION npc "surpriseEyes" FUNCTION npc "showSurpriseMuzzle" PLAY_ANIM npc "right-point-start" 1.5 WAIT 0.6944 LOOP_ANIM npc "right-point" LOCAL_CHAT_CONFIRM npc QuestScript101_11 "CFSpeech" tomDialogue_11 LOCAL_CHAT_CONFIRM npc QuestScript101_12 "CFSpeech" tomDialogue_12 PLAY_ANIM npc "right-point-start" -1 LERP_HPR npc -0.068 0 0 0.75 WAIT 1.0417 FUNCTION npc "angryEyes" FUNCTION npc "blinkEyes" FUNCTION npc "hideSurpriseMuzzle" LOOP_ANIM npc "neutral" FUNCTION localToon "questPage.showQuestsOnscreenTutorial" LOCAL_CHAT_CONFIRM npc QuestScript101_13 "CFSpeech" tomDialogue_13 FUNCTION localToon "questPage.hideQuestsOnscreenTutorial" LOCAL_CHAT_CONFIRM npc QuestScript101_14 1 "CFSpeech" tomDialogue_14 FUNCTION npc "normalEyes" FUNCTION npc "blinkEyes" # Cleanup UPON_TIMEOUT FUNCTION tart "removeNode" UPON_TIMEOUT FUNCTION flower "removeNode" UPON_TIMEOUT FUNCTION cogs "removeNode" UPON_TIMEOUT FUNCTION toonBuilding "removeNode" UPON_TIMEOUT FUNCTION cogBuilding "removeNode" UPON_TIMEOUT FUNCTION squirt1 "removeNode" UPON_TIMEOUT FUNCTION squirt2 "removeNode" UPON_TIMEOUT LOOP_ANIM npc "neutral" UPON_TIMEOUT HIDE inventory UPON_TIMEOUT SET_INVENTORY_DETAIL 0 UPON_TIMEOUT SHOW laffMeter UPON_TIMEOUT POS laffMeter 0.15 0.15 0.15 UPON_TIMEOUT SCALE laffMeter 0.085 0.085 0.085 UPON_TIMEOUT POSHPRSCALE inventory 0 0 0 0 0 0 1 1 1 POS localToon 0.776 14.6 0 HPR localToon 47.5 0 0 FINISH_QUEST_MOVIE # TUTORIAL HQ HARRY ID quest_incomplete_110 DEBUG "quest assign 110" LOAD_DIALOGUE harryDialogue_01 "phase_3.5/audio/dial/CC_harry_tutorial_questscript01.ogg" LOAD_DIALOGUE harryDialogue_02 "phase_3.5/audio/dial/CC_harry_tutorial_questscript02.ogg" LOAD_DIALOGUE harryDialogue_03 "phase_3.5/audio/dial/CC_harry_tutorial_questscript03.ogg" LOAD_DIALOGUE harryDialogue_04 "phase_3.5/audio/dial/CC_harry_tutorial_questscript04.ogg" LOAD_DIALOGUE harryDialogue_05 "phase_3.5/audio/dial/CC_harry_tutorial_questscript05.ogg" LOAD_DIALOGUE harryDialogue_06 "phase_3.5/audio/dial/CC_harry_tutorial_questscript06.ogg" LOAD_DIALOGUE harryDialogue_07 "phase_3.5/audio/dial/CC_harry_tutorial_questscript07.ogg" LOAD_DIALOGUE harryDialogue_08 "phase_3.5/audio/dial/CC_harry_tutorial_questscript08.ogg" LOAD_DIALOGUE harryDialogue_09 "phase_3.5/audio/dial/CC_harry_tutorial_questscript09.ogg" LOAD_DIALOGUE harryDialogue_10 "phase_3.5/audio/dial/CC_harry_tutorial_questscript10.ogg" LOAD_DIALOGUE harryDialogue_11 "phase_3.5/audio/dial/CC_harry_tutorial_questscript11.ogg" SET_MUSIC_VOLUME 0.4 activityMusic 0.5 0.7 LOCAL_CHAT_CONFIRM npc QuestScript110_1 harryDialogue_01 OBSCURE_BOOK 0 SHOW bookOpenButton LOCAL_CHAT_CONFIRM npc QuestScript110_2 harryDialogue_02 # ARROWS_ON 0.92 -0.89 0 1.22 -0.64 90 ARROWS_ON 1.364477 -0.89 0 1.664477 -0.64 90 LOCAL_CHAT_PERSIST npc QuestScript110_3 harryDialogue_03 WAIT_EVENT "enterStickerBook" ARROWS_OFF SHOW_BOOK HIDE bookPrevArrow HIDE bookNextArrow CLEAR_CHAT npc WAIT 0.5 TOON_HEAD npc -0.2 -0.45 1 LOCAL_CHAT_CONFIRM npc QuestScript110_4 harryDialogue_04 ARROWS_ON 0.85 -0.75 -90 0.85 -0.75 -90 SHOW bookNextArrow LOCAL_CHAT_PERSIST npc QuestScript110_5 harryDialogue_05 WAIT_EVENT "stickerBookPageChange-4" HIDE bookPrevArrow HIDE bookNextArrow ARROWS_OFF CLEAR_CHAT npc WAIT 0.5 LOCAL_CHAT_CONFIRM npc QuestScript110_6 harryDialogue_06 ARROWS_ON 0.85 -0.75 -90 0.85 -0.75 -90 SHOW bookNextArrow LOCAL_CHAT_PERSIST npc QuestScript110_7 harryDialogue_07 WAIT_EVENT "stickerBookPageChange-5" HIDE bookNextArrow HIDE bookPrevArrow ARROWS_OFF CLEAR_CHAT npc LOCAL_CHAT_CONFIRM npc QuestScript110_8 harryDialogue_08 LOCAL_CHAT_CONFIRM npc QuestScript110_9 harryDialogue_09 LOCAL_CHAT_PERSIST npc QuestScript110_10 harryDialogue_10 ENABLE_CLOSE_BOOK ARROWS_ON 1.364477 -0.89 0 1.664477 -0.64 90 WAIT_EVENT "exitStickerBook" ARROWS_OFF TOON_HEAD npc 0 0 0 HIDE_BOOK HIDE bookOpenButton LOCAL_CHAT_CONFIRM npc QuestScript110_11 1 harryDialogue_11 SET_MUSIC_VOLUME 0.7 activityMusic 1.0 0.4 # Lots of cleanup UPON_TIMEOUT DEBUG "testing upon death" UPON_TIMEOUT OBSCURE_BOOK 0 UPON_TIMEOUT ARROWS_OFF UPON_TIMEOUT HIDE_BOOK UPON_TIMEOUT COLOR_SCALE bookOpenButton 1 1 1 1 UPON_TIMEOUT TOON_HEAD npc 0 0 0 UPON_TIMEOUT SHOW bookOpenButton FINISH_QUEST_MOVIE # TUTORIAL FLIPPY ID tutorial_blocker LOAD_DIALOGUE blockerDialogue_01 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker01.ogg" LOAD_DIALOGUE blockerDialogue_02 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker02.ogg" LOAD_DIALOGUE blockerDialogue_03 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker03.ogg" LOAD_DIALOGUE blockerDialogue_04 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker04.ogg" LOAD_DIALOGUE blockerDialogue_05a "phase_3.5/audio/dial/CC_flippy_tutorial_blocker05.ogg" LOAD_DIALOGUE blockerDialogue_05b "phase_3.5/audio/dial/CC_flippy_tutorial_blocker06.ogg" LOAD_DIALOGUE blockerDialogue_06 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker07.ogg" LOAD_DIALOGUE blockerDialogue_07 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker08.ogg" LOAD_DIALOGUE blockerDialogue_08 "phase_3.5/audio/dial/CC_flippy_tutorial_blocker09.ogg" HIDE localToon REPARENTTO camera npc FUNCTION npc "stopLookAround" #POS camera 0.0 6.0 4.0 #HPR camera 180.0 0.0 0.0 LERP_POSHPR camera 0.0 6.0 4.0 180.0 0.0 0.0 0.5 SET_MUSIC_VOLUME 0.4 music 0.5 0.8 LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_1 blockerDialogue_01 WAIT 0.8 LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_2 blockerDialogue_02 WAIT 0.8 #POS camera -5.0 -9.0 6.0 #HPR camera -25.0 -10.0 0.0 LERP_POSHPR camera -5.0 -9.0 6.0 -25.0 -10.0 0.0 0.5 POS localToon 203.8 18.64 -0.475 HPR localToon -90.0 0.0 0.0 SHOW localToon LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_3 blockerDialogue_03 OBSCURE_CHAT 1 0 0 SHOW chatScButton WAIT 0.6 ARROWS_ON -1.3644 0.91 180 -1.5644 0.74 -90 LOCAL_CHAT_PERSIST npc QuestScriptTutorialBlocker_4 blockerDialogue_04 WAIT_EVENT "enterSpeedChat" ARROWS_OFF BLACK_CAT_LISTEN 1 WAIT_EVENT "SCChatEvent" BLACK_CAT_LISTEN 0 WAIT 0.5 CLEAR_CHAT localToon REPARENTTO camera localToon LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_5 "CFSpeech" blockerDialogue_05a blockerDialogue_05b LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_6 "CFSpeech" blockerDialogue_06 OBSCURE_CHAT 0 0 0 SHOW chatNormalButton WAIT 0.6 LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_7 "CFSpeech" blockerDialogue_07 LOCAL_CHAT_CONFIRM npc QuestScriptTutorialBlocker_8 1 "CFSpeech" blockerDialogue_08 SET_MUSIC_VOLUME 0.8 music 1.0 0.4 LOOP_ANIM npc "walk" LERP_HPR npc 270 0 0 0.5 WAIT 0.5 LOOP_ANIM npc "run" LERP_POS npc 217.4 18.81 -0.475 0.75 LERP_HPR npc 240 0 0 0.75 WAIT 0.75 LERP_POS npc 222.4 15.0 -0.475 0.35 LERP_HPR npc 180 0 0 0.35 WAIT 0.35 LERP_POS npc 222.4 5.0 -0.475 0.75 WAIT 0.75 REPARENTTO npc hidden FREE_LOCALTOON UPON_TIMEOUT ARROWS_OFF UPON_TIMEOUT OBSCURE_CHAT 0 0 0 UPON_TIMEOUT REPARENTTO camera localToon FINISH_QUEST_MOVIE ID quest_incomplete_120 CHAT_CONFIRM npc QuestScript120_1 # ANIM CHAT_CONFIRM npc QuestScript120_2 1 FINISH_QUEST_MOVIE ID quest_assign_121 CHAT_CONFIRM npc QuestScript121_1 1 FINISH_QUEST_MOVIE ID quest_assign_130 CHAT_CONFIRM npc QuestScript130_1 1 FINISH_QUEST_MOVIE ID quest_assign_131 CHAT_CONFIRM npc QuestScript131_1 1 FINISH_QUEST_MOVIE ID quest_assign_140 CHAT_CONFIRM npc QuestScript140_1 1 FINISH_QUEST_MOVIE ID quest_assign_141 CHAT_CONFIRM npc QuestScript141_1 1 FINISH_QUEST_MOVIE # TUTORIAL COG ID quest_incomplete_145 CHAT_CONFIRM npc QuestScript145_1 1 LOAD frame "phase_4/models/gui/tfa_images" "FrameBlankA" LOAD tunnel "phase_4/models/gui/tfa_images" "tunnelSignA" POSHPRSCALE tunnel 0 0 0 0 0 0 0.8 0.8 0.8 REPARENTTO tunnel frame POSHPRSCALE frame 0 0 0 0 0 0 0.1 0.1 0.1 REPARENTTO frame aspect2d LERP_SCALE frame 1.0 1.0 1.0 1.0 WAIT 3.0 LERP_SCALE frame 0.1 0.1 0.1 0.5 WAIT 0.5 REPARENTTO frame hidden CHAT_CONFIRM npc QuestScript145_2 1 UPON_TIMEOUT FUNCTION frame "removeNode" FINISH_QUEST_MOVIE # TUTORIAL FRIENDS ID quest_incomplete_150 CHAT_CONFIRM npc QuestScript150_1 ARROWS_ON 1.65 0.51 -120 1.65 0.51 -120 SHOW_FRIENDS_LIST CHAT_CONFIRM npc QuestScript150_2 ARROWS_OFF HIDE_FRIENDS_LIST CHAT_CONFIRM npc QuestScript150_3 HIDE bFriendsList CHAT_CONFIRM npc QuestScript150_4 1 UPON_TIMEOUT HIDE_FRIENDS_LIST UPON_TIMEOUT ARROWS_OFF FINISH_QUEST_MOVIE # First Task: Assign Visit to Jester Chester ID quest_assign_600 PLAY_ANIM npc "wave" 1 CHAT npc QuestScript600_1 LOAD_IMAGE logo "phase_3/maps/toontown-logo.png" REPARENTTO logo aspect2d POSHPRSCALE logo -0.4 7 0 0 0 0 0 0 0 LERP_SCALE logo 0.4 0.2 0.2 0.5 WAIT 2.5 LOOP_ANIM npc "neutral" LERP_SCALE logo 0 0 0 0.5 WAIT 0.5 FUNCTION logo "destroy" CLEAR_CHAT npc CHAT_CONFIRM npc QuestScript600_2 CHAT_CONFIRM npc QuestScript600_3 CHAT_CONFIRM npc QuestScript600_4 CHAT_CONFIRM npc QuestScript600_5 PLAY_ANIM npc "wave" 1 CHAT_CONFIRM npc QuestScript600_6 LOOP_ANIM npc "neutral" FINISH_QUEST_MOVIE # Loopys Balls ID quest_assign_10301 POSE_ANIM npc "wave" 20 CHAT_CONFIRM npc QuestScript10301_1 POSE_ANIM npc "neutral" 1 CHAT_CONFIRM npc QuestScript10301_2 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_3 POSE_ANIM npc "think" 40 CHAT_CONFIRM npc QuestScript10301_4 POSE_ANIM npc "conked" 20 CHAT_CONFIRM npc QuestScript10301_5 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_6 POSE_ANIM npc "think" 40 CHAT_CONFIRM npc QuestScript10301_7 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_8 LOOP_ANIM npc "neutral" FINISH_QUEST_MOVIE # Loopys Balls ID quest_incomplete_10301 POSE_ANIM npc "wave" 20 CHAT_CONFIRM npc QuestScript10301_1 POSE_ANIM npc "neutral" 1 CHAT_CONFIRM npc QuestScript10301_2 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_3 POSE_ANIM npc "think" 40 CHAT_CONFIRM npc QuestScript10301_4 POSE_ANIM npc "conked" 20 CHAT_CONFIRM npc QuestScript10301_5 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_6 POSE_ANIM npc "think" 40 CHAT_CONFIRM npc QuestScript10301_7 POSE_ANIM npc "shrug" 25 CHAT_CONFIRM npc QuestScript10301_8 LOOP_ANIM npc "neutral" FINISH_QUEST_MOVIE '''
# https://leetcode.com/submissions/detail/109225225/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return stack = [] while(head): stack.append(head) head = head.next #New head head = stack.pop() head.next = None final_head = head while len(stack)>0: head.next = stack.pop() head = head.next head.next = None return final_head
class Word(): """docstring for Word""" def __init__(self, text: str, start_time: float, end_time: float): assert isinstance(text, str), "text should be string." assert isinstance(start_time, float) and isinstance(end_time, float), "Start time and end time should be float values." self.text = text self.start_time = start_time self.end_time = end_time def __str__(self): return "Word(text='{}', start_time={}s, end_time={}s)".format(self.text, self.start_time, self.end_time) def __len__(self): return self.end_time - self.start_time
while True: valores = input().split() n = int(valores[0]) d = a = int(valores[1]) e = b = int(valores[2]) if n == 0 and a == 0 and b == 0: break while e != 0: d, e = e, d % e c = (a * b) // d a_l = len(range(a, n + 1, a)) b_l = len(range(b, n + 1, b)) c_l = len(range(c, n + 1, c)) print(a_l + b_l - c_l)
def convert_to_string(idx_list, form_manager): w_list = [] for i in range(len(idx_list)): w_list.append(form_manager.get_idx_symbol(int(idx_list[i]))) return " ".join(w_list) def is_all_same(c1, c2, form_manager): all_same = False if len(c1) == len(c2): all_same = True for j in range(len(c1)): if c1[j] != c2[j]: all_same = False break return all_same def compute_accuracy(candidate_list, reference_list, form_manager): if len(candidate_list) != len(reference_list): print( "candidate list has length {}, reference list has length {}\n".format( len(candidate_list), len(reference_list) ) ) len_min = min(len(candidate_list), len(reference_list)) c = 0 for i in range(len_min): if is_all_same(candidate_list[i], reference_list[i], form_manager): c = c + 1 else: pass return c / float(len_min) def compute_tree_accuracy(candidate_list_, reference_list_, form_manager): candidate_list = [] for i in range(len(candidate_list_)): candidate_list.append(candidate_list_[i]) reference_list = [] for i in range(len(reference_list_)): reference_list.append(reference_list_[i]) return compute_accuracy(candidate_list, reference_list, form_manager)
def test_geoadd(judge_command): judge_command( 'GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"', { "command": "GEOADD", "key": "Sicily", "longitude": "15.087269", "latitude": "37.502669", "member": '"Catania"', }, ) def test_georadiusbymember(judge_command): judge_command( "GEORADIUSBYMEMBER Sicily Agrigento 100 km", { "command": "GEORADIUSBYMEMBER", "key": "Sicily", "member": "Agrigento", "float": "100", "distunit": "km", }, ) def test_georadius(judge_command): judge_command( "GEORADIUS Sicily 15 37 200 km WITHDIST WITHCOORD ", { "command": "GEORADIUS", "key": "Sicily", "longitude": "15", "latitude": "37", "float": "200", "distunit": "km", "geochoice": "WITHCOORD", }, )
""" Common utilities/lib for use by multiple services """ subscription_types = ['policy_eval', 'tag_update', 'vuln_update', 'repo_update', 'analysis_update'] resource_types = ['registries', 'users', 'images', 'policies', 'evaluations', 'subscriptions', 'archive'] bucket_types = ["analysis_data", "policy_bundles", "policy_evaluations", "query_data", "vulnerability_scan", "image_content_data", "manifest_data"] super_users = ['admin', 'anchore-system'] image_content_types = ['os', 'files', 'npm', 'gem', 'python', 'java'] image_metadata_types = ['manifest', 'docker_history', 'dockerfile'] image_vulnerability_types = ['os', 'non-os'] os_package_types = ['rpm', 'dpkg', 'APKG'] nonos_package_types = ['java', 'python', 'npm', 'gem', 'maven', 'js']
""" Dexter Legaspi Class: CS 521 - Summer 2 Date: 08/03/2021 Homework Problem # 5.6.3 Description of Problem: A program that highlights the use of proper exception handling. """ EXPECTED_INPUTS = 4 # validate input and the result loop while True: user_input = input('Please enter {} numbers delimited by space: ' .format(EXPECTED_INPUTS)).split() if len(user_input) != EXPECTED_INPUTS: print(f'We need {EXPECTED_INPUTS} numbers. Please try again.') else: try: numbers = [float(t) for t in user_input] num_result = (numbers[0] * numbers[1] + numbers[2]) / numbers[3] except ValueError as err: print(f'Input error; {err}. Please try again.') except ZeroDivisionError: print('Division by zero error encountered. Please try again.') else: # at this point the inputs are valid and calculation # does not cause division by zero, so we break out of the loop break # print the result print('({:,} * {:,} + {:,}) / {:,} = {:,}' .format(numbers[0], numbers[1], numbers[2], numbers[3], num_result))
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. PYTHON_VERSION_COMPATIBILITY = 'PY2+3' DEPS = [ 'recipe_engine/cipd', 'recipe_engine/commit_position', 'recipe_engine/context', 'recipe_engine/file', 'recipe_engine/golang', 'recipe_engine/json', 'recipe_engine/nodejs', 'recipe_engine/path', 'recipe_engine/raw_io', 'recipe_engine/step', 'depot_tools/depot_tools', 'depot_tools/git', 'depot_tools/git_cl', ]
class Cup(object): def __init__(self, name): self.name = name self.price = 0 class MyClass: pass def myfunc(): pass if __name__ == '__main__': cup1 = Cup('aaa') cup2 = Cup('bbb') # get attribute of object print(getattr(cup1, 'name')) print(getattr(cup2, 'name')) try: name = getattr(cup1, 'country') except Exception as e: print('occured getattr except:' + str(e)) # check attribute print(hasattr(cup2, 'new_name')) print(getattr(cup2, 'new_name', 'default')) # set attribute setattr(cup2, 'new_name', 'default') print(hasattr(cup2, 'new_name'), end='\n\n') # access class attribute obj = MyClass() print(obj.__class__.__name__) print(myfunc.__name__)
# set, himpunan: super_hero = {'superman','ironman','hulk','flash'} print(super_hero) print('1=====================') super_hero.add('gundala') super_hero.add('121') print(super_hero) print('2=====================') super_hero.add('hulk') print(super_hero) print(sorted(super_hero)) print('3=====================') ganjil = {1,3,5,7,9} genap = {2,4,6,8,10} prima = {2,3,5,7} print(ganjil.union(genap)) print(ganjil.intersection(prima))
# Python carefully avoids evaluating bools more than once in a variety of situations. # Eg: # In the statement # if a or b: # it doesn't simply compute (a or b) and then evaluate the result to decide whether to # jump. If a is true it jumps directly to the body of the if statement. # We can confirm that this behaviour is correct in python code. # A Bool that raises an exception if evaluated twice! class ExplodingBool(): def __init__(self, value): self.value = value self.booled = False def __bool__(self): assert not self.booled self.booled = True return self.value y = (ExplodingBool(False) and False and True and False) print(y) if (ExplodingBool(True) or False or True or False): pass assert ExplodingBool(True) or False while ExplodingBool(False) and False: pass # if ExplodingBool(False) and False and True and False: # pass
def firstZero(arr, low, high): if (high >= low): # Check if mid element is first 0 mid = low + int((high - low) / 2) if (( mid == 0 or arr[mid-1] == 1) and arr[mid] == 0): return mid # If mid element is not 0 if (arr[mid] == 1): return firstZero(arr, (mid + 1), high) # If mid element is 0, but not first 0 else: return firstZero(arr, low, (mid - 1)) return -1 # A wrapper over recursive # function firstZero() def countZeroes(arr, n): # Find index of first zero in given array first = firstZero(arr, 0, n - 1) # If 0 is not present at all, return 0 if (first == -1): return 0 return (n - first) # Driver Code arr = [1, 1, 1, 0, 0, 0, 0, 0] n = len(arr) print("Count of zeroes is", countZeroes(arr, n))
#Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. sal = float(input('Digite o valor do seu Salário: R$')) aum = sal * 0.15 print('Seu salario teve aumento de 15% equivalentes a R${:.2f}. Portanto seu salário atual é R${:.2f}'.format(aum, sal + aum))
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # # Const Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.ui.dialogs class CommonFilePickerElementIds(object): """ Const Class These constants are used to specify common controls of a FilePicker dialog. **since** OOo 1.1.2 See Also: `API CommonFilePickerElementIds <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1ui_1_1dialogs_1_1CommonFilePickerElementIds.html>`_ """ __ooo_ns__: str = 'com.sun.star.ui.dialogs' __ooo_full_ns__: str = 'com.sun.star.ui.dialogs.CommonFilePickerElementIds' __ooo_type_name__: str = 'const' PUSHBUTTON_OK = 1 """ The control id of the OK button. """ PUSHBUTTON_CANCEL = 2 """ The control id of the Cancel button. """ LISTBOX_FILTER = 3 """ The filter listbox of a FilePicker dialog. """ CONTROL_FILEVIEW = 4 """ Is used to refer to the file view of the file picker. This view shows the list of all files/folders in the currently selected folder. """ EDIT_FILEURL = 5 """ Is used to refer to the edit line where a file or path can be entered by the user. """ LISTBOX_FILTER_LABEL = 6 """ The label of the filter listbox of a FilePicker dialog. **since** OOo 1.1.2 """ EDIT_FILEURL_LABEL = 7 """ The label of the file name listbox of a FilePicker dialog. **since** OOo 1.1.2 """ __all__ = ['CommonFilePickerElementIds']
SYMBOL_JSON = { "rb":{"sylbom":"RB0","name":"螺纹钢","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, "ag":{"sylbom":"AG0","name":"白银","contractSize":"15","exchangeName":"上期所","exchangeCode":"SHFE"}, "au":{"sylbom":"AU0","name":"黄金","contractSize":"1000","exchangeName":"上期所","exchangeCode":"SHFE"}, "cu":{"sylbom":"CU0","name":"沪铜","contractSize":"5","exchangeName":"上期所","exchangeCode":"SHFE"}, "al":{"sylbom":"AL0","name":"沪铝","contractSize":"5","exchangeName":"上期所","exchangeCode":"SHFE"}, "zn":{"sylbom":"ZN0","name":"沪锌","contractSize":"5","exchangeName":"上期所","exchangeCode":"SHFE"}, "pb":{"sylbom":"PB0","name":"沪铅","contractSize":"5","exchangeName":"上期所","exchangeCode":"SHFE"}, "ru":{"sylbom":"RU0","name":"橡胶","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, "fu":{"sylbom":"FU0","name":"燃油","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, "sc":{"sylbom":"SC0","name":"原油","contractSize":"1000","exchangeName":"上期所","exchangeCode":"SHFE"}, "bu":{"sylbom":"BU0","name":"沥青","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, "hc":{"sylbom":"HC0","name":"热轧卷板","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, "sn":{"sylbom":"SN0","name":"沪锡","contractSize":"1","exchangeName":"上期所","exchangeCode":"SHFE"}, "ni":{"sylbom":"NI0","name":"沪镍","contractSize":"1","exchangeName":"上期所","exchangeCode":"SHFE"}, "sp":{"sylbom":"SP0","name":"纸浆","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, # "nr":{"sylbom":"NR0","name":"20号胶","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, ## 该品种新浪取不到数据 # "ss":{"sylbom":"SS0","name":"不锈钢","contractSize":"5","exchangeName":"上期所","exchangeCode":"SHFE"}, ## 该品种新浪取不到数据 "wr":{"sylbom":"WR0","name":"线材","contractSize":"10","exchangeName":"上期所","exchangeCode":"SHFE"}, ## 上期所 "a":{"sylbom":"A0","name":"大豆一","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 豆一 "b":{"sylbom":"B0","name":"大豆二","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 豆一 "m":{"sylbom":"M0","name":"豆粕","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, "y":{"sylbom":"Y0","name":"豆油","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, "j":{"sylbom":"J0","name":"焦炭","contractSize":"60","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, "c":{"sylbom":"C0","name":"玉米","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, "l":{"sylbom":"L0","name":"聚乙烯","contractSize":"5","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 就是塑料?对,代码一致的 "pp":{"sylbom":"PP0","name":"聚丙烯","contractSize":"5","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 就是塑料?对,代码一致的 "fb":{"sylbom":"FB0","name":"纤维板","contractSize":"500","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 就是塑料?对,代码一致的 "p":{"sylbom":"P0","name":"棕油","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ## 就是棕榈油?对的,代码一致 "v":{"sylbom":"V0","name":"PVC","contractSize":"5","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "i":{"sylbom":"I0","name":"铁矿石","contractSize":"100","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "jd":{"sylbom":"JD0","name":"鸡蛋","contractSize":"100","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "bb":{"sylbom":"BB0","name":"胶合板","contractSize":"500","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "jm":{"sylbom":"JM0","name":"焦煤","contractSize":"60","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "cs":{"sylbom":"CS0","name":"玉米淀粉","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "eg":{"sylbom":"EG0","name":"乙二醇","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 # "rr":{"sylbom":"RR0","name":"粳米","contractSize":"10","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 # "eb":{"sylbom":"EB0","name":"苯乙烯","contractSize":"5","exchangeName":"大连商品交易所","exchangeCode":"DCE"}, ### 对的,代码v,又叫聚氯乙烯 "rs":{"sylbom":"RS0","name":"菜籽","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 油菜籽-郑商所 "rn":{"sylbom":"RM0","name":"菜粕","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "fg":{"sylbom":"FG0","name":"玻璃","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "cf":{"sylbom":"CF0","name":"棉花","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ##"ws":{"sylbom":"WS0","name":"强麦","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 代码不一样呢和天勤的对比 待确定,郑商所代码与天勤是一致的 # "er":{"sylbom":"ER0","name":"籼稻","contractSize":"20"}, ## ???郑商所-早籼稻:RI,郑商所-晚籼稻:LR,就是没用ER # "me":{"sylbom":"ME0","name":"甲醇","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 郑商所是MA,没有me呢 ## "ro":{"sylbom":"RO0","name":"菜油","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 代码不一样呢和天勤的对比 "ta":{"sylbom":"TA0","name":"甲酸","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 就是PTA??是的 "oi":{"sylbom":"OI0","name":"菜油","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "zc":{"sylbom":"ZC0","name":"动力煤","contractSize":"100","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "wh":{"sylbom":"WH0","name":"强麦","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "jr":{"sylbom":"JR0","name":"粳稻","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "sr":{"sylbom":"SR0","name":"白糖","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "ri":{"sylbom":"RI0","name":"早籼稻","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "lr":{"sylbom":"LR0","name":"晚籼稻","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "ma":{"sylbom":"MA0","name":"甲醇","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "sf":{"sylbom":"SF0","name":"硅铁","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "sm":{"sylbom":"SM0","name":"锰硅","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "cy":{"sylbom":"CY0","name":"棉纱","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "ap":{"sylbom":"AP0","name":"鲜苹果","contractSize":"10","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, "cj":{"sylbom":"CJ0","name":"红枣","contractSize":"5","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, # "ur":{"sylbom":"UR0","name":"尿素","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, # "sa":{"sylbom":"SA0","name":"纯碱","contractSize":"20","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, # "pm":{"sylbom":"PM0","name":"普麦","contractSize":"50","exchangeName":"郑州商品交易所","exchangeCode":"CZCE"}, ## 新浪没有该项数据 } INDEX_JSON={ "AGRI-OIL":{"name":"农产品-油脂油料","content":{"a":"大豆一","y":"豆油","m":"豆粕","oi":"菜油","p":"棕油","rn":"菜粕","rs":"油菜籽"}}, "AGRI-CANDY":{"name":"农产品-棉花糖","content":{"cf":"棉花","sr":"糖"}}, "AGRI-OTHERS":{"name":"农产品-其他农产品","content":{"c":"玉米","jd":"鸡蛋","cs":"玉米淀粉","ri":"早籼稻","lr":"晚籼稻","wh":"强麦","jr":"粳稻","ap":"苹果","cy":"棉纱"}}, "METAL-NOBLE":{"name":"金属-贵金属","content":{"au":"黄金","ag":"白银"}}, "METAL-COLOR":{"name":"金属-有色金属","content":{"cu":"铜","al":"铝","pb":"铅","zn":"锌","ni":"镍","sn":"锡"}}, "METAL-BLACK":{"name":"金属-黑色系","content":{"rb":"螺纹钢","i":"铁矿石","sm":"锰硅","hc":"热轧卷板","wr":"线材","sf":"硅铁"}}, "ENERGY-COAL":{"name":"能化-煤炭","content":{"zc":"动力煤","j":"焦炭","jm":"焦煤"}}, "ENERGY-OTHERS":{"name":"能化-其他能化","content":{"ru":"天然橡胶","sc":"原油","l":"聚乙烯","ta":"PTA","pp":"聚丙烯","fg":"玻璃","bu":"沥青","v":"PVC","ma":"甲醇","fu":"燃油"}}, "INDUSTRY-ESTATE":{"name":"工业品-黑色产业","content":{"rb":"螺纹钢","i":"铁矿石","jm":"焦煤","j":"焦炭","hc":"热轧卷板","wr":"线材","sm":"锰硅","sf":"硅铁"}}, "INDUSTRY-MATERAIL":{"name":"工业品-黑色原材料","content":{"i":"铁矿石","jm":"焦煤","j":"焦炭","sf":"硅铁","sm":"锰硅"}}, "INDUSTRY-BUILDING":{"name":"工业品-建材","content":{"fg":"玻璃","rb":"螺纹钢","v":"PVC","bb":"胶合板","fb":"纤维板"}}, } def ts(): print("xxx")
"""Package pyang.transforms: transform plugins for YANG. Modules: * edit: YANG edit transform plugin """
# augmented vertex class Vertex: def __init__(self, element, location): self.element = element self.location = location def getElement(self): return self.element def setElement(self, element): self.element = element def getLocation(self): return self.location def setLocation(self, location): self.location = location def isIndeterminate(self): return False def toString(self): return str(self.location)
def get_node_info(file): nodes = set() df = [line.strip().split() for line in open('input/%s.txt' % file).readlines() if line.startswith('/dev')] for nodeinfo in df: # Filesystem Size Used Avail Use% # /dev/grid/node-x0-y0 92T 68T 24T 73% _, x, y = nodeinfo[0].split('-') size = int(nodeinfo[1][:-1]) used = int(nodeinfo[2][:-1]) node = (int(x[1:]), int(y[1:]), size, used) nodes.add(node) return nodes def get_pair_count(nodes): pair_count = 0 for a in nodes: ax, ay, _, au = a if au == 0: continue for b in nodes: bx, by, bs, bu = b if bx == ax and by == ay: continue if au <= (bs-bu): pair_count += 1 return pair_count def make_grid(nodes, reg): max_x = max([n[0] for n in nodes]) max_y = max([n[1] for n in nodes]) grid = [[None for x in range(max_x + 1)]for y in range(max_y + 1)] walls = [] empty = (0,0) for node in nodes: x, y, _, u = node if u == 0: char = '0' empty = (x,y) elif u > reg: char = '#' walls.append((x,y)) else: char = '.' grid[y][x] = char grid[0][max_x] = 'D' return grid, max_x, empty, walls def swap(a,b,grid): new = copy_grid(grid) ax, ay = a bx, by = b node_a = grid[ay][ax] node_b = grid[by][bx] new[by][bx] = node_a new[ay][ax] = node_b return new def copy_grid(grid): return [[x for x in y] for y in grid] def find_empty(grid): for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == '0': return (x,y) def find_data(grid): for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == 'D': return (x,y) def print_grid(grid): for row in grid: print(' '.join(row)) print() def solve(input, reg): nodes = get_node_info(input) print("Part 1:", get_pair_count(nodes)) grid, max_x, empty, walls = make_grid(nodes, reg) goal = (0,0) data = (max_x, 0) wall_edge = min([w[0] for w in walls if w[1] < empty[1]]) step_count = 0 # move to left of wall old_empty = empty while empty[0] >= wall_edge: empty = (empty[0] - 1, empty[1]) step_count += 1 grid = swap(old_empty, empty, grid) # go up to top row old_empty = empty while empty[1] != 0: empty = (empty[0], empty[1] - 1) step_count += 1 grid = swap(old_empty, empty, grid) # move next to data old_empty = empty while empty[0] != data[0] - 1: empty = (empty[0] + 1, empty[1]) step_count += 1 grid = swap(old_empty, empty, grid) # swap data, move empty around to left, repeat while data != goal: grid = swap(empty, data, grid) empty = find_empty(grid) data = find_data(grid) step_count += 1 if data != goal: # down 1, left 2, up 1 old_empty = empty empty = (empty[0], empty[1] + 1) grid = swap(empty, old_empty, grid) step_count += 1 old_empty = empty empty = (empty[0]-2, empty[1]) grid = swap(empty, old_empty, grid) step_count += 2 old_empty = empty empty = (empty[0], empty[1] - 1) grid = swap(empty, old_empty, grid) step_count += 1 print("Part 2:", step_count) solve('day22', 100)
""" 04 - Escreva um programa que declare um inteiro, inicialize-o com 0, e incremente de 1000 em 1000, imprimindo o seu valor na tela, até que seu valor seja 100000(cem mil). """ numero = 0 while numero <= 100000: print(numero, end=' ') numero += 1000
class Problem: initial_state = [None, None, None, None, None, None, None, None] row = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] col = [0,1,2,3,4,5,6,7] def check_if_attacked(self, state): # returns True if attacked try: index = state.index(None) - 1 except ValueError: index = 7 if index == 0: return False for i in range(0,index): if (state[i][0] == state[index][0]) or (state[i][1] == state[index][1]): return True #row and column attack check if abs(ord(state[i][0]) - ord(state[index][0])) == abs(int(state[i][1]) - int(state[index][1])): return True #diagonal attack detect return False def actions(self, state): all_actions = [] #find the first (leftmost) None position try: index = state.index(None) # returns the first index on None or raises ValueError in None is not found except ValueError: return [state] for i in range(0,8): next_state = state[:] next_state[index] = Problem.row[index] + str(i) if not self.check_if_attacked(next_state): all_actions.append(next_state) return all_actions def result(self, state, action): return action def goal_test(self, state): try: state.index(None) return False except ValueError: return True def step_cost(self, par_state=None, action=None, child_state=None): return 0 class Node: def __init__(self, state, parent, action, path_cost): self.state = state self.parent = parent self.action = action self.path_cost = path_cost def child_node(problem, parent, action): state = problem.result(parent.state, action) path_cost = parent.path_cost + problem.step_cost(parent.state, action) return Node(state, parent, action, path_cost) def compare(node): return node.path_cost class Frontier: def __init__(self): self.p_queue = [] def is_empty(self): return len(self.p_queue) == 0 def insert(self, node): self.p_queue.append(node) self.p_queue = sorted(self.p_queue, key=compare, reverse=True) def pop(self): return self.p_queue.pop() def contains_state(self, state): for node in self.p_queue[:]: if node.state == state: return True return False def replace_if_higher_path_cost_with_same_state(self,node): for i in range(len(self.p_queue)): if self.p_queue[i].state == node.state: if self.p_queue[i].path_cost > node.path_cost: self.p_queue[i] = node def uniform_cost_search(problem): node = Node(problem.initial_state.copy(),None, None, 0) frontier = Frontier() frontier.insert(node) explored = [] n=1 while True: if frontier.is_empty(): return "failure" node = frontier.pop() #print("popped from frontier") if problem.goal_test(node.state): print (str(n) +" "+ str(node.state)) paint(node.state) n = n+1 explored.append(node.state) for action in problem.actions(node.state): #print(action) child = child_node(problem, node, action) if (child.state not in explored) and (not frontier.contains_state(child.state)): frontier.insert(child) #print('inserted in frontier') else: frontier.replace_if_higher_path_cost_with_same_state(child) def paint(state): print(" _ _ _ _ _ _ _ _ ") for i in range(7,-1,-1): prnt_str = str(i) for j in range(0,8): prnt_str = prnt_str + "|" if int(state[j][1]) == i : prnt_str = prnt_str + "Q" else: prnt_str = prnt_str + " " prnt_str = prnt_str + "|" print(prnt_str) #print(" - - - - - - - - ") print(" a b c d e f g h ") problem = Problem() uniform_cost_search(problem)
#soma dos pares #mostre a soma apenas daqueles que forem pares.Se o valor digitado for impar,desconsidere-o. soma = 0 cont = 0 for c in range(1, 7): num = int(input('Digite o {} valor: '.format(c))) if num % 2 == 0: soma += num cont += 1 print('Você informou {} números e a soma foi {}'.format(cont, soma))
# Easy # https://leetcode.com/problems/climbing-stairs/ class Solution: # Time complexity : O(n) # Space complexity: O(1) # Fibonacci sequence def climbStairs(self, n: int) -> int: a, b = 1, 2 for _ in range(1, n): a, b = b, a + b return a
""" Author: Clinton Wang, E-mail: `clintonjwang@gmail.com`, Github: `https://github.com/clintonjwang/lipiodol` """ class Config: def __init__(self): self.proj_dims = [64,64,32] self.world_dims = [32,64,64] #self.aug_factor = 100 self.npy_dir = r"D:\CBCT\Train\NPYs" self.nii_dir = r"D:\CBCT\Train\NIFTIs" self.dcm_dir = r"D:\CBCT\Train\DICOMs" self.train_dir = r"D:\CBCT\Train" self.model_dir = r"D:\CBCT\Models"
file = {'amy':5, 'bob':8, 'candy':6, 'doby':9, 'john':0} print("Amy's number is:" +'\n\t' + str(file['amy']) +'.') print("\nBob's number is:" +'\n\t' + str(file['bob']) +'.')
print('trace | Start.') # 配列アクセスは遅い気がするので、match構文で書こうぜ☆(^~^) enums = ['Sq11', 'Sq12', 'Sq13', 'Sq14', 'Sq15', 'Sq16', 'Sq17', 'Sq18', 'Sq19', 'Sq21', 'Sq22', 'Sq23', 'Sq24', 'Sq25', 'Sq26', 'Sq27', 'Sq28', 'Sq29', 'Sq31', 'Sq32', 'Sq33', 'Sq34', 'Sq35', 'Sq36', 'Sq37', 'Sq38', 'Sq39', 'Sq41', 'Sq42', 'Sq43', 'Sq44', 'Sq45', 'Sq46', 'Sq47', 'Sq48', 'Sq49', 'Sq51', 'Sq52', 'Sq53', 'Sq54', 'Sq55', 'Sq56', 'Sq57', 'Sq58', 'Sq59', 'Sq61', 'Sq62', 'Sq63', 'Sq64', 'Sq65', 'Sq66', 'Sq67', 'Sq68', 'Sq69', 'Sq71', 'Sq72', 'Sq73', 'Sq74', 'Sq75', 'Sq76', 'Sq77', 'Sq78', 'Sq79', 'Sq81', 'Sq82', 'Sq83', 'Sq84', 'Sq85', 'Sq86', 'Sq87', 'Sq88', 'Sq89', 'Sq91', 'Sq92', 'Sq93', 'Sq94', 'Sq95', 'Sq96', 'Sq97', 'Sq98', 'Sq99', ] print('impl SquareType {') print( ' pub fn to_unified_address(&self, turn: Phase) -> UnifiedAddress {') print(' use crate::cosmic::toy_box::SquareType::*;') print(' if turn == Phase::First {') print(' match self {') i = 0 for file in range(1, 10): for rank in range(1, 10): print( f' {enums[i]} => UnifiedAddress::Sq{file}{rank}_1,') i += 1 print(' }') print(' } else {') print(' match self {') i = 0 for file in range(1, 10): for rank in range(1, 10): print( f' {enums[i]} => UnifiedAddress::Sq{file}{rank}_2,') i += 1 print(' }') print(' }') print(' }') print('}') print('trace | Finished.')
class Solution: def myAtoi(self, str): if len(str) == 0: return 0 res = 0 max_int = 2147483647 min_int = -2147483648 for i in range(0, len(str)): c = str[i] if c != ' ': break s = str[i:] pos = False if s[0] == '-': pos = False s = s[1:] elif s[0] == '+': pos = True s = s[1:] else: pos = True s = s for c in s: if c >= '0' and c <= '9': res = res*10 + int(c) else: break if not pos: res = -res if res > max_int: res = max_int if res < min_int: res = min_int return res a = Solution() r = a.myAtoi("") print(r) r = a.myAtoi(" ab") print(r) r = a.myAtoi(" -123") print(r)
class Config: def __init__(self): self.basename = 'delta_video' self.directory = '/home/eleanor/Documents/gcamp_analysis_files_temp/171019-06-bottom-experiment/data' self.topics = ['/multi_tracker/1/delta_video',] self.record_length_hours = 1
## -*- coding: utf-8 -*- ## ## Sage Doctest File ## #**************************************# #* Generated from PreTeXt source *# #* on 2017-08-24T11:43:34-07:00 *# #* *# #* http://mathbook.pugetsound.edu *# #* *# #**************************************# ## """ Please contact Rob Beezer (beezer@ups.edu) with any test failures here that need to be changed as a result of changes accepted into Sage. You may edit/change this file in any sensible way, so that development work may procede. Your changes may later be replaced by the authors of "Abstract Algebra: Theory and Applications" when the text is updated, and a replacement of this file is proposed for review. """ ## ## To execute doctests in these files, run ## $ $SAGE_ROOT/sage -t <directory-of-these-files> ## or ## $ $SAGE_ROOT/sage -t <a-single-file> ## ## Replace -t by "-tp n" for parallel testing, ## "-tp 0" will use a sensible number of threads ## ## See: http://www.sagemath.org/doc/developer/doctesting.html ## or run $ $SAGE_ROOT/sage --advanced for brief help ## ## Generated at 2017-08-24T11:43:34-07:00 ## From "Abstract Algebra" ## At commit 26d3cac0b4047f4b8d6f737542be455606e2c4b4 ## ## Section 6.5 Sage ## r""" ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = SymmetricGroup(3) sage: a = G("(1,2)") sage: H = G.subgroup([a]) sage: rc = G.cosets(H, side='right'); rc [[(), (1,2)], [(2,3), (1,3,2)], [(1,2,3), (1,3)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: lc = G.cosets(H, side='left'); lc [[(), (1,2)], [(2,3), (1,2,3)], [(1,3,2), (1,3)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = SymmetricGroup(3) sage: b = G("(1,2,3)") sage: H = G.subgroup([b]) sage: rc = G.cosets(H, side='right'); rc [[(), (1,2,3), (1,3,2)], [(2,3), (1,3), (1,2)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: lc = G.cosets(H, side='left'); lc [[(), (1,2,3), (1,3,2)], [(2,3), (1,2), (1,3)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: rc == lc False ~~~~~~~~~~~~~~~~~~~~~~ :: sage: rc_sorted = sorted([sorted(coset) for coset in rc]) sage: rc_sorted [[(), (1,2,3), (1,3,2)], [(2,3), (1,2), (1,3)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: lc_sorted = sorted([sorted(coset) for coset in lc]) sage: lc_sorted [[(), (1,2,3), (1,3,2)], [(2,3), (1,2), (1,3)]] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: rc_sorted == lc_sorted True ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = SymmetricGroup(3) sage: sg = G.subgroups(); sg [Subgroup generated by [()] of (Symmetric group of order 3! as a permutation group), Subgroup generated by [(2,3)] of (Symmetric group of order 3! as a permutation group), Subgroup generated by [(1,2)] of (Symmetric group of order 3! as a permutation group), Subgroup generated by [(1,3)] of (Symmetric group of order 3! as a permutation group), Subgroup generated by [(1,2,3)] of (Symmetric group of order 3! as a permutation group), Subgroup generated by [(2,3), (1,2,3)] of (Symmetric group of order 3! as a permutation group)] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: H = sg[4]; H Subgroup generated by [(1,2,3)] of (Symmetric group of order 3! as a permutation group) ~~~~~~~~~~~~~~~~~~~~~~ :: sage: H.order() 3 ~~~~~~~~~~~~~~~~~~~~~~ :: sage: H.list() [(), (1,3,2), (1,2,3)] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: H.is_cyclic() True ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = AlternatingGroup(4) sage: sg = G.subgroups() sage: [H.order() for H in sg] [1, 2, 2, 2, 3, 3, 3, 3, 4, 12] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = SymmetricGroup(4) sage: sg = G.subgroups() sage: [H.order() for H in sg] [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 8, 12, 24] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: len(sg) 30 ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = CyclicPermutationGroup(20) sage: [H.order() for H in G.subgroups()] [1, 2, 4, 5, 10, 20] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: G = CyclicPermutationGroup(19) sage: [H.order() for H in G.subgroups()] [1, 19] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: n = 8 sage: G = CyclicPermutationGroup(n) sage: [H.order() for H in G.subgroups()] [1, 2, 4, 8] ~~~~~~~~~~~~~~~~~~~~~~ :: sage: euler_phi(345) 176 ~~~~~~~~~~~~~~~~~~~~~~ :: sage: m = random_prime(10000) sage: n = random_prime(10000) sage: m, n, euler_phi(m*n) == euler_phi(m)*euler_phi(n) # random (5881, 1277, True) """
class Memory: def __init__(self, size): self.mem = bytearray(size) self.bin_size = 0 def read8(self, addr): val = self.mem[addr] #if addr > self.bin_size: # print(f'Read {val:02x} at {addr}') return val def write8(self, addr, val): self.mem[addr] = val def write_bin(self, addr, data): self.mem[addr: addr+len(data)] = data self.bin_size = addr + len(data) def __len__(self): return len(self.mem) class MemoryMap: def __init__(self, mems): self.mems = mems def resolve_addr(self, addr): for start, m in self.mems: if start <= addr < start + len(m): return m, start raise IndexError(f'Access to unmapped memory {addr:x}') def read8(self, addr): mem, start = self.resolve_addr(addr) val = mem.read8(addr - start) #print(f'Read {val:x} at {addr}') return val def write8(self, addr, val): #print(f'Write {val:x} at {addr}') mem, start = self.resolve_addr(addr) mem.write8(addr - start, val)
__author__ = 'Jeffrey Seifried' __description__ = 'A library for forecasting sun positions' __email__ = 'jeffrey.seifried@gmail.com' __program__ = 'analemma' __url__ = 'http://github.com/jeffseif/{}'.format(__program__) __version__ = '1.0.0' __year__ = '2020'
""" MIT License Copyright (c) 2021 FelipeSavazi 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. """ class Formattings: def normal(self): return f'\033[0m' def bold(self, texto): return f'\033[01m{texto}\033[0m' def disable(self, texto): return f'\033[02m{texto}\033[0m' def underline(self, texto): return f'\033[04m{texto}\033[0m' def reverse(self, texto): return f'\033[07m{texto}\033[0m' def strikethrough(self, texto): return f'\033[09m{texto}\033[0m' def invisible(self, texto): return f'\033[08m{texto}\033[0m'
''' Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example 1: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun". Example 2: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). Note: The length of both lists will be in the range of [1, 1000]. The length of strings in both lists will be in the range of [1, 30]. The index is starting from 0 to the list length minus 1. No duplicates in both lists. ''' class Solution(object): def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ if len(list1) < len(list2): return self.findRestaurant(list2, list1) key_to_idx = {} for i in xrange(len(list2)): key_to_idx[list2[i]] = i res = [] idx_sum = float('inf') for i in xrange(len(list1)): if list1[i] in key_to_idx: tmp = i + key_to_idx[list1[i]] if tmp < idx_sum: res = [list1[i]] idx_sum = tmp elif tmp == idx_sum: res.append(list1[i]) return res
# -*- coding: utf-8 -*- """ Procurement A module to handle Procurement Currently handles Suppliers Planned Procurements Purchase Orders (POs) @ToDo: Extend to Purchase Requests (PRs) """ if not settings.has_module(c): raise HTTP(404, body="Module disabled: %s" % c) # ----------------------------------------------------------------------------- def index(): """ Module's Home Page """ return s3db.cms_index(c) # ----------------------------------------------------------------------------- def order(): """ RESTful CRUD controller """ return s3_rest_controller(rheader = s3db.proc_rheader, hide_filter = True, ) # ----------------------------------------------------------------------------- #def order_item(): # """ RESTful CRUD controller """ # return s3_rest_controller() # ----------------------------------------------------------------------------- def plan(): """ RESTful CRUD controller """ return s3_rest_controller(rheader = s3db.proc_rheader, hide_filter = True, ) # ----------------------------------------------------------------------------- def supplier(): """ RESTful CRUD controller """ return s3_rest_controller("org", "organisation") # END =========================================================================
# flake8: noqa # https://github.com/trezor/python-mnemonic/blob/master/vectors.json trezor_vectors = { "english": [ { "id": 0, "entropy": "00000000000000000000000000000000", "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "salt": "TREZOR", "binary": "00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 0000000", "checksum": "0011", "seed": "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04", "root": { "private_key": "cbedc75b0d6412c85c79bc13875112ef912fd1e756631b5a00330866f22ff184", "public_key": "02f632717d78bf73e74aa8461e2e782532abae4eed5110241025afb59ebfd3d2fd", "xpub": "xpub661MyMwAqRbcGB88KaFbLGiYAat55APKhtWg4uYMkXAmfuSTbq2QYsn9sKJCj1YqZPafsboef4h4YbXXhNhPwMbkHTpkf3zLhx7HvFw1NDy", "xpriv": "xprv9s21ZrQH143K3h3fDYiay8mocZ3afhfULfb5GX8kCBdno77K4HiA15Tg23wpbeF1pLfs1c5SPmYHrEpTuuRhxMwvKDwqdKiGJS9XFKzUsAF", "parent_fingerprint": "00", "fingerprint": "b4e3f5ed", "depth": 0, "index": 0, "chain_code": "a3fa8c983223306de0f0f65e74ebb1e98aba751633bf91d5fb56529aa5c132c1" }, "derived_node": { "path": "m/7'/13'/8'/65'/6/44/16/18'/7", "public_key": "026381791f9bf7ec99538a408d61c911737a30488c78004feb34a73295776c2f17", "private_key": "b4749323ef65b3898c8cf3f9978fa437c9113a3a91b26320a1047032ab9eaf47", "xpub": "xpub6Qo94BJ44WgahcCbte4pYt2UU5AGBrkt4PyKWzG3KA9AR1EbERqbTo69Wtc4cXnB2DiuFcxwEDRNdQh1GXwF1jqHrwZS3KRS6X7eaceREJd", "xpriv": "xprvABonefmAE98HV888ncXpBk5jv3KmnQ32hB3iibrRkpcBYCuSgtXLuzmffeBwvMLcouHL2WdJEZiiXJDB6cMDKytYPy37Em7BNCytyBhJd5A", "parent_fingerprint": "fc4ca6e2", "fingerprint": "264f90ed", "depth": 9, "index": 7, "chain_code": "3c063c0a452d20fba1b1cc476a886def7096116dd0cb8400d90f6f55507bcca6" } } ] } # generated with: https://iancoleman.io/bip39/#english test_vectors = { "english": [ { "id": 0, "entropy": "a4e3fc4c0161698a22707cfbf30f7f83", "mnemonic": "pilot cable basic actress bird shallow mean auto winner observe that all", "salt": None, "binary": "10100100111 00011111111 00010011000 00000010110 00010110100 11000101000 10001001110 00001111100 11111011111 10011000011 11011111111 0000011", "checksum": "0011", "seed": "af44c7ad86ba0a5f46d4c1e785c846db14e0f3d62b69c2ab7efa012a9c9155c024975d6897e36fe9e9e6f0bde55fdf325ff308914ed1b316da0f755f9dd7347d", "root": { "private_key": "c6796958d07afe0af1ba9a11da2b7a22d6226b4ff7ff5324c7c876cfc1ea0f1c", "public_key": "029cfe11e5f33a2601083ff5e29d9b7f134f5edc6b7636674a7286ecf6d23804df", "xpub": "xpub661MyMwAqRbcFXwuU8c1uEfmER2GW8A7XfaR9Cw41RCGr1xmr4WaLdU9cGPvcJXaaNYLFuu9bMimhKmGgaFja9BxcBAo98Eim1UuUu1dXAn", "xpriv": "xprv9s21ZrQH143K33sSN751Y6j2gPBn6fSGASepLpXST5fHyDddJXCKnq9fm1gRmHk4CPPcEF9gBmJvPBf74ExYM6Ybe6zwA7HfX8dQkRFY9S4", "parent_fingerprint": "00", "fingerprint": "f3ac0f3f", "depth": 0, "index": 0, "chain_code": "6399431d3f454a4acbe0f1cbb2d9a392a43dbea34e7fea952bdda675adde6e6e" }, "derived_node": { "path": "m/55'/16'/34'/20/19'/97/21'/88'", "public_key": "039b8a22c4fb43cb4b52596fc2050357dd9771950d6b6881c6e4b2e78e1943f51d", "private_key": "258dc521c0581a788a2f08fd64be0f4d29c0c7384031960e6b6986526bcb039f", "xpub": "xpub6NjKMZDHrzmR8m4poa48Xzj3qeS32QQBbfXffSK5N4F6SLE35fFrBT9qECJ77LMic44hNnWTR86qVjE8r4DsMSNVztB1vyoYNvhzrg91zXV", "xpriv": "xprvA9jxx3gQ2dD7vGzMhYX8ArnKHcbYcwgLESc4s3uToii7ZXttY7wbdeqMNtRdhhepm7cEKKparnDqeigAPgj7KTj7Gw5ZGUKCRBYbkd3sdGo", "parent_fingerprint": "e33b22ce", "fingerprint": "93195471", "depth": 8, "index": 2147483736, "chain_code": "18eb1b59d8a529c9fdbfbce7f6cb03cc9b1bd80b2fc5abee1944b32a32c136f8" } }, { "id": 1, "entropy": "8cfc94f3846c43fa893b4950155de2369772c91e", "mnemonic": "mind tool diagram angle service wool ceiling hard exotic priority joy honey jaguar goose kit", "salt": None, "binary": "10001100111 11100100101 00111100111 00001000110 11000100001 11111101010 00100100111 01101001001 01010000000 10101010111 01111000100 01101101001 01110111001 01100100100 011110", "checksum": "10111", "seed": "82555df2fd8c76fca417c83fc7ed0552a0310299eed41d3a45cf49e1ac056e21126e64d988052b9dbc0e04bd6b3580c51ab6a4ec5a62c5dba2039bd372e7d137", "root": { "private_key": "9fee59092ebbedc782277cf75bc85f9db0ea559818eb20de865c4897eb2144f4", "public_key": "0357ffdd29d20d72d2061c154353835b9cd34016d6f63755a04d70a7033e2919b3", "xpub": "xpub661MyMwAqRbcFyPp6zb6ZPcsuqVkvUm2Y61Gn7cRrkp2xxCD8ot9tgJQDKG6R6DWopMQrVoUhMChoCZcS4PKSFFx5AoNPAGFizikrRVTmpn", "xpriv": "xprv9s21ZrQH143K3VKLzy46CFg9MofGX23BAs5fyjCpJRH469s4bGZuLsyvN2qGCAYoJYmHyT6XVVkhm7DHGyHSyYPintmfgxYrwKHzCgCthir", "parent_fingerprint": "00", "fingerprint": "94db54c0", "depth": 0, "index": 0, "chain_code": "8faa80cab7372c9e12e2f54a445e434b5d2cb310bc92d7e304b914360a89278a" }, "derived_node": { "path": "m/96'/2'/10/81'/60'/90'", "public_key": "0229d3838c6703a16aa9e7f8604dd308f36980ca891783f9e46dcc8d0a7c7da5ed", "private_key": "6f7ae238af855eb9e0cee63333a4c05ef4c24a54a6951dcdf298ea13c85e2050", "xpub": "xpub6JuoVny9rzjMruCwjgP66H9bLt97ow3jgg6Sjt5Eny85LQKoQzA6E9xhmFcVoQR2PoYnTTDMcXnyo1MZPHeW4PFBxaN6VitafnfA3csorkr", "xpriv": "xprvA5vT6HSG2dB4eR8Uder5j9CrnrJdQUKtKTAqwVfdEdb6TbzesSqqgMeDv17Qa6M5jxRcbhDTTfzzBxuJqMURrsXnRXNJUwkRsqNmTHEs6Qx", "parent_fingerprint": "db9f3893", "fingerprint": "11b20e3d", "depth": 6, "index": 2147483738, "chain_code": "91f4c0395a78095692132cb1f632834ab821c373057ccdb5637f7f9f34837fdd" } }, { "id": 2, "entropy": "15bf57143a38579300d9f4cbd65adaebe01398fbeb8f44f0", "mnemonic": "between wide shallow inner lyrics sister address direct slim ready repeat style abuse small use impose eager liberty", "salt": None, "binary": "00010101101 11111010101 11000101000 01110100011 10000101011 11001001100 00000011011 00111110100 11001011110 10110010110 10110110101 11010111110 00000001001 11001100011 11101111101 01110001111 01000100111 10000", "checksum": "000111", "seed": "db6b9728bce174c1c14976415cfe06d63509e127f38ba265cf672315b5ed15953828f0fe5e9922654c07d3284f7ac11f814b564e87f94210d3bcc153ec6f698b", "root": { "private_key": "3a4014ab104dc69ba3820e3c1e9740998dfdd0b912f1f83268c639bac5fa64f0", "public_key": "03230ac7166adf9664a911a4d4785a60e79e983f950b99fe9dc228dd1438c0aa36", "xpub": "xpub661MyMwAqRbcFtZZGjnmsUKVffkBYUraocCexn2maSi1keXzdsaam5fwHRrwFaLNe1dCjqQQMgcGSQfaiD5BFuDbvy3cdkWrq3939hHHns9", "xpriv": "xprv9s21ZrQH143K3QV6AiFmWLNm7duh928jSPH4APdA27B2srCr6LGLDHMTS94eTRRBfnoLErXZEXbkAHpybohWnb4tp8sv3cSK7nJKtpcwJ4U", "parent_fingerprint": "00", "fingerprint": "b46fe1d0", "depth": 0, "index": 0, "chain_code": "874c576e48fdc3ebf6f0822b4d18498d0a545d6684dfd683ef215fd0273870e8" }, "derived_node": { "path": "m/87/19/76/25'/96'", "public_key": "03540f45d9145cd5c9bdbf67b674df050255ac19380b0b6f3cc57dff99e17b836a", "private_key": "c3c055a5154dafa361e82d585393d82a8bf3f82cbe96f7c4e2e758de7ac90a0e", "xpub": "xpub6FwAvDCcTWuqD2hVZHoi3WhtWZbf2XBeo36HRFwCLLk85DxzvHau5dmx8o7VKsdrv98yigghdX6PkgeGvoe4LZ39Hoex2ZhGtJ53W4Tdnmn", "xpriv": "xprvA2wpWhfid9MXzYd2TGGhgNm9xXmAd4ToRpAgcsXan1D9CRdrNkGeXqTUHWzAimdLSuZCMCqMhu545mtYP4mj13q5RWDbuyBHBbwMeaPcAyU", "parent_fingerprint": "46ae4850", "fingerprint": "94d1cc4b", "depth": 5, "index": 2147483744, "chain_code": "309cff07ed70166ebe30ec31ee7a4c261fa9dfa6bdae249d498a84f4d224d472" } }, { "id": 3, "entropy": "a05a7afb69e2cd81c838a7d1ad4132d06bef59042b0388512881b61a", "mnemonic": "park stable salute stable coast science can belt spider head erosion patch same prosper awful gather marriage matter call history pluck", "salt": None, "binary": "10100000010 11010011110 10111110110 11010011110 00101100110 11000000111 00100000111 00010100111 11010001101 01101010000 01001100101 10100000110 10111110111 10101100100 00010000101 01100000011 10001000010 10001001010 00100000011 01101100001 1010", "checksum": "0110101", "seed": "1929655fd266457fc620dd471f424b8351999338c837db07ec362dab19f11dbb2c2aff18d0a063a9d91239f81181d0fcebe327c37803b45012a8163fe3b716b6", "root": { "private_key": "a01b94f79e8c29ee63b8c27e40ef63f1cfe8f4cac870d0de5d20e889b1d8a13a", "public_key": "031225fa5e457da949ab1021931887131c7a53c06df0fce4d6a3dd5819aa5776e0", "xpub": "xpub661MyMwAqRbcFJsyHbfuQsjnh3qjSfXkxkEXa5JHoSbyU7UNoiXU3FXfcKUbdFqC5cyxexpUAYPZP6K9AU9C4FjfuiX743buQgF5k7BwUND", "xpriv": "xprv9s21ZrQH143K2poWBa8u3jo4921F3CoubXJvmgtgF74zbK9EGBDDVTDBm3acAnd1cvowkj1pvi7PK3Ab6XrwYfJPWmQtCp5kor3tbqkreJ6", "parent_fingerprint": "00", "fingerprint": "056dd4ec", "depth": 0, "index": 0, "chain_code": "4cf7eb64f359de9cdb7f2c05baf3267a2f1f96e1fc68333c60e92ff3dbbf0b78" }, "derived_node": { "path": "m/85'/15/76", "public_key": "02029099fda4c09fa365c85cf785fb790270125bc0d9a584e1707ca2d85209eab2", "private_key": "921255b836b8215d67d18949b217f3b3edf77cc0d185d37ff85da85d6ca0657e", "xpub": "xpub6CnpKCiJ2WSFtjfzoreA69jdgCrLK2vVrzEhvJHHEDjREWLU2SYKwVkMVML9Gt22pMY2aa4RdEXedECPgyoegRy76vaPNpj8QzFwAxeRKmn", "xpriv": "xprv9yoTuhBQC8sxgFbXhq79j1nu8B1quaCeVmK77usfftCSMi1KUuE5PhRse7PaX8uh8stKfMGjNGN6ZiXVXBL54daSjmLvEe57u3m8mbGvHGv", "parent_fingerprint": "9aedbb6f", "fingerprint": "6ad6b30a", "depth": 3, "index": 76, "chain_code": "ec33efe03c9ad429a6e2cba47cdbc396ae2bded480c628f760396794e6f52729" } }, { "id": 4, "entropy": "39281ecca67d16aa629115340d8ad4923bd49ec2d6f17669fce458087ee89a92", "mnemonic": "decrease domain rebel erupt sphere festival medal cargo cross hobby release caught run exhaust area taste island exit decorate quote margin inmate heart frog", "salt": None, "binary": "00111001001 01000000111 10110011001 01001100111 11010001011 01010101001 10001010010 00100010101 00110100000 01101100010 10110101001 00100100011 10111101010 01001111011 00001011010 11011110001 01110110011 01001111111 00111001000 10110000000 10000111111 01110100010 01101010010 010", "checksum": "11101001", "seed": "c11b0ff978d88c0ae9f7c349733bbd1b7baf2237663e3064a4c62bc4f5a578e4fb14fc43c38f85bfe83a15790397d7a301df5233d7d520cd2cc974cd33ae47b2", "root": { "private_key": "36f0fcac8ff8e73506ae26aa1db732918e0db5c5635330eaed951e12eacedf3e", "public_key": "02800f0237e39dce74f506c508985d4d71f8020342d7dfe781ca5cfb73e63eb43e", "xpub": "xpub661MyMwAqRbcGYp55aa3wf9WqTuPGdFnwyhFBALErewiMiBkeDrXsZ6qDbUbawSiHVgqvqobbNdosLY7aJgsNVv4DtwPAWKEjgCaSEjvdBg", "xpriv": "xprv9s21ZrQH143K44jbyZ33aXCnHS4tsAXwakmeNmvdJKQjUurc6gYHKknMNKtdTiC7jPbnEBmTWDEJ4HpxobatUpEKQgrshDpv8R1NrCkdWyT", "parent_fingerprint": "00", "fingerprint": "ea6be3d5", "depth": 0, "index": 0, "chain_code": "c989c416cf4c4e3d3708c25893ab6c01bcb9893e153929ab9204eb374ab76a63" }, "derived_node": { "path": "m/51'", "public_key": "028f08404abc652f3170f471591cab170f153a0772adf69d33116212f9219537cc", "private_key": "e74f8cedbafd94797fd0d21ecb06ccac46721602ccb8a0fe86cdb54335d03691", "xpub": "xpub69cS8waJoeNVm5qKbGi2eyspJLHgP1zyZWgFJt2knTHGUhF45C8tthWzJ5cJTKQA77UvXkKvpdGh49ewZhDyQD2vFcSyTz3qjvstaxjPd4F", "xpriv": "xprv9vd5jS3QyGpCYbkrVFB2Hqw5kJTByZH8CHkeWVd9E7kHbtuuXepeLuCWSqFQy8o3iwPrPyw5trAwCpW9HvecxQkCNBeHUHmXiAu9mUWDviW", "parent_fingerprint": "ea6be3d5", "fingerprint": "97f01095", "depth": 1, "index": 2147483699, "chain_code": "bfad5d31ac996363d635dad2304f9582e81ddd7cc8249c3cd5b327706103cb6e" } }, ] } public_path_mnemonic = "decrease domain rebel erupt sphere festival medal cargo cross hobby release caught run exhaust area taste island exit decorate quote margin inmate heart frog" public_path = [ 'xpub661MyMwAqRbcGYp55aa3wf9WqTuPGdFnwyhFBALErewiMiBkeDrXsZ6qDbUbawSiHVgqvqobbNdosLY7aJgsNVv4DtwPAWKEjgCaSEjvdBg', 'xpub69cS8waATyqVK5tryNLyKKHMHzieRM4AQdG5aR9VSe29cJp4EyTrMDLHUi198chSiY86Dh1V57UPCdwSsNUPDKjhSeXvZ3ejvW76pRGFpQe', 'xpub6AB84inF91Uf26fue9dETg5rkNhDwEsWN2kpB7vJWHHuakuMeKPL7onruexAnWhLkEMv7Rjq2aA1z8h6iz4XX6tfRaiuZY83TQi4MR29UCN']
# -*- coding: utf-8 -*- # Copyright 2011 Fanficdownloader team # # 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. # ## Just to shut up the appengine warning about "You are using the ## default Django version (0.96). The default Django version will ## change in an App Engine release in the near future. Please call ## use_library() to explicitly select a Django version. For more ## information see ## http://code.google.com/appengine/docs/python/tools/libraries.html#Django" pass
class Mapper(object): """ A base clap from which to ineherit in order to create a keyboard mapper. """ def __init__(self): self.base_map = None self.alt_map = None self.map = None def create_map(self): self.map = dict(zip(self.base_map, self.alt_map)) def map_key(self, key): if key not in self.map.keys(): return key return self.map[key] class DvorakMapper(Mapper): """ Maps a qwerty key to its dvorak equivalent. """ def __init__(self): super(DvorakMapper, self).__init__() self.base_map = '`1234567890-=QWERTYUIOP[]ASDFGHJKL;\'ZXCVBNM,./' self.alt_map = '`1234567890[]\',.PYFGCRL/=AOEUIDHTNS-;QJKXBMWVZ' super(DvorakMapper, self).create_map()
""" A package with everything you need to build a simple neural network """ # todo - add unit tests