content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Copyright 2021 Google LLC # # 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. def capital_checker(dicti): correct_ans = {"New York": "Albany", "California": "Sacramento", "New Mexico": "Santa Fe", "Florida": "Tallahassee", "Michigan": "Lansing"} return_dict = {} for keys,values in dicti.items(): if values.lower() != correct_ans[keys].lower(): return_dict[keys] = "Incorrect" else: return_dict[keys] = "Correct" return return_dict
def capital_checker(dicti): correct_ans = {'New York': 'Albany', 'California': 'Sacramento', 'New Mexico': 'Santa Fe', 'Florida': 'Tallahassee', 'Michigan': 'Lansing'} return_dict = {} for (keys, values) in dicti.items(): if values.lower() != correct_ans[keys].lower(): return_dict[keys] = 'Incorrect' else: return_dict[keys] = 'Correct' return return_dict
TEST_OCF_ACCOUNTS = ( 'sanjay', # an old, sorried account with kerberos princ 'alec', # an old, sorried account with no kerberos princ 'guser', # an account specifically made for testing 'nonexist', # this account does not exist ) TESTER_CALNET_UIDS = ( 872544, # daradib 1034192, # ckuehl 869331, # tzhu 1031366, # mattmcal 1099131, # dkessler 1101587, # jvperrin 1511731, # ethanhs 1623751, # cooperc 1619256, # jaw ) # comma separated tuples of CalLink OIDs and student group names TEST_GROUP_ACCOUNTS = ( (91740, 'The Testing Group'), # needs to have a real OID, so boo (46187, 'Open Computing Facility'), # good old ocf (46692, 'Awesome Group of Awesome'), # boo another real OID (92029, 'eXperimental Computing Facility'), # our sister org )
test_ocf_accounts = ('sanjay', 'alec', 'guser', 'nonexist') tester_calnet_uids = (872544, 1034192, 869331, 1031366, 1099131, 1101587, 1511731, 1623751, 1619256) test_group_accounts = ((91740, 'The Testing Group'), (46187, 'Open Computing Facility'), (46692, 'Awesome Group of Awesome'), (92029, 'eXperimental Computing Facility'))
class NotFoundError(Exception): def __init__(self, url): super().__init__(url) self.type = "notfound" class NoTitleError(Exception): def __init__(self, url): super().__init__(url) self.type = "notitle" class ErrorPageError(Exception): def __init__(self, url): super().__init__(url) self.type = "errorpage" class HomepageRedirectError(Exception): def __init__(self, url): super().__init__(url) self.type = "homepageredir" class FetchError(Exception): def __init__(self, url, info={}): super().__init__(url) self.type = "fetcherror" self.info = info class UnknownError(Exception): def __init__(self, url): super().__init__(url) self.type = "unknown"
class Notfounderror(Exception): def __init__(self, url): super().__init__(url) self.type = 'notfound' class Notitleerror(Exception): def __init__(self, url): super().__init__(url) self.type = 'notitle' class Errorpageerror(Exception): def __init__(self, url): super().__init__(url) self.type = 'errorpage' class Homepageredirecterror(Exception): def __init__(self, url): super().__init__(url) self.type = 'homepageredir' class Fetcherror(Exception): def __init__(self, url, info={}): super().__init__(url) self.type = 'fetcherror' self.info = info class Unknownerror(Exception): def __init__(self, url): super().__init__(url) self.type = 'unknown'
init_info = input().split(" ") sapce_width = int(init_info[0]) space_length = int(init_info[1]) space_gun = int(init_info[2]) gun_x = [] gun_y = [] for each_input in range(space_gun): init_gun = input().split() gun_x.append(int(init_gun[0])) gun_y.append(int(init_gun[1])) new_width = sapce_width - len(set((gun_x))) new_length = space_length - len(set((gun_y))) print((new_width * new_length) % 25621) # Passed
init_info = input().split(' ') sapce_width = int(init_info[0]) space_length = int(init_info[1]) space_gun = int(init_info[2]) gun_x = [] gun_y = [] for each_input in range(space_gun): init_gun = input().split() gun_x.append(int(init_gun[0])) gun_y.append(int(init_gun[1])) new_width = sapce_width - len(set(gun_x)) new_length = space_length - len(set(gun_y)) print(new_width * new_length % 25621)
# Create a calculator function # The function should accept three parameters: # first_number: a numeric value for the math operation # second_number: a numeric value for the math operation # operation: the word 'add' or 'subtract' # the function should return the result of the two numbers added or subtracted # based on the value passed in for the operator def calcutate(first, second, operation): if operation.lower() == 'add': result = first + second elif operation.lower() == 'substract': result = first - second else: result = 'Operation, not supported' return result first = float(input('Enter first number: ')) second = float(input('Enter second number: ')) operation = input('Enter operation type (add or substract): ') print(calcutate(first, second, operation)) # # Test your function with the values 6,4, add # Should return 10 # # Test your function with the values 6,4, subtract # Should return 2 # # BONUS: Test your function with the values 6, 4 and divide # Have your function return an error message when invalid values are received
def calcutate(first, second, operation): if operation.lower() == 'add': result = first + second elif operation.lower() == 'substract': result = first - second else: result = 'Operation, not supported' return result first = float(input('Enter first number: ')) second = float(input('Enter second number: ')) operation = input('Enter operation type (add or substract): ') print(calcutate(first, second, operation))
''' We can pass multiple arguments to the .order_by() method to order by multiple columns. In fact, we can also sort in ascending or descending order for each individual column. Each column in the .order_by() method is fully sorted from left to right. This means that the first column is completely sorted, and then within each matching group of values in the first column, it's sorted by the next column in the .order_by() method. This process is repeated until all the columns in the .order_by() are sorted. ''' # Build a query to select state and age: stmt stmt = select([census.columns.state, census.columns.age]) # Append order by to ascend by state and descend by age stmt = stmt.order_by(census.columns.state, desc(census.columns.age)) # Execute the statement and store all the records: results results = connection.execute(stmt).fetchall() # Print the first 20 results print(results[:20])
""" We can pass multiple arguments to the .order_by() method to order by multiple columns. In fact, we can also sort in ascending or descending order for each individual column. Each column in the .order_by() method is fully sorted from left to right. This means that the first column is completely sorted, and then within each matching group of values in the first column, it's sorted by the next column in the .order_by() method. This process is repeated until all the columns in the .order_by() are sorted. """ stmt = select([census.columns.state, census.columns.age]) stmt = stmt.order_by(census.columns.state, desc(census.columns.age)) results = connection.execute(stmt).fetchall() print(results[:20])
#!/usr/bin/env python3 #################################################################################### # # # Program purpose: Finds the difference between the largest and the smallest # # integer which are created by numbers from 0 to 9. The # # number that can be rearranged shall start with 0 as in # # 00135668. # # Program Author : Happi Yvan <[email protected]> # # Creation Date : September 22, 2019 # # # #################################################################################### def read_data(mess: str): valid = False data = 0 while not valid: try: temp_data = list(input(mess).strip()) if len(temp_data) != 8: raise ValueError("Number must be 8-digit long") else: for x in range(len(temp_data)): if not f"{temp_data[x]}".isdigit(): raise ValueError(f"'{temp_data[x]}' is not an integer") data = temp_data valid = True except ValueError as ve: print(f"[ERROR]: {ve}") return data if __name__ == "__main__": main_data = read_data("Enter an integer created by 8 numbers from 0 to 9: ") largest = ''.join(sorted(main_data, reverse=True)) smallest = ''.join(sorted(main_data)) print(f"Difference between the largest {largest} and smallest {smallest}:" f" {int(''.join(largest)) - int(''.join(smallest))}")
def read_data(mess: str): valid = False data = 0 while not valid: try: temp_data = list(input(mess).strip()) if len(temp_data) != 8: raise value_error('Number must be 8-digit long') else: for x in range(len(temp_data)): if not f'{temp_data[x]}'.isdigit(): raise value_error(f"'{temp_data[x]}' is not an integer") data = temp_data valid = True except ValueError as ve: print(f'[ERROR]: {ve}') return data if __name__ == '__main__': main_data = read_data('Enter an integer created by 8 numbers from 0 to 9: ') largest = ''.join(sorted(main_data, reverse=True)) smallest = ''.join(sorted(main_data)) print(f"Difference between the largest {largest} and smallest {smallest}: {int(''.join(largest)) - int(''.join(smallest))}")
class AuthenticationError(Exception): pass class MarketClosedError(Exception): pass class MarketEmptyError(Exception): pass
class Authenticationerror(Exception): pass class Marketclosederror(Exception): pass class Marketemptyerror(Exception): pass
# coding=utf-8 # @Time : 2021/3/26 10:34 # @Auto : zzf-jeff class GlobalSetting(): label_path = './coco.names' model_path = './weights/yolov5x-simpler.engine' # model_path = './weights/yolov5s.pt' output_path = './output' img_path = './test_imgs' conf_thresh = 0.3 iou_thresh = 0.45 anchors = [ [[10, 13], [16, 30], [33, 23]], [[30, 61], [62, 45], [59, 119]], [[116, 90], [156, 198], [373, 326]], ] opt = GlobalSetting()
class Globalsetting: label_path = './coco.names' model_path = './weights/yolov5x-simpler.engine' output_path = './output' img_path = './test_imgs' conf_thresh = 0.3 iou_thresh = 0.45 anchors = [[[10, 13], [16, 30], [33, 23]], [[30, 61], [62, 45], [59, 119]], [[116, 90], [156, 198], [373, 326]]] opt = global_setting()
def test_trading_fee(position): entry_price = 100000000000000000000 # 100 current_price = 150000000000000000000 # 150 notional = 10000000000000000000 # 10 debt = 2000000000000000000 # 2 liquidated = False trading_fee_rate = 750000000000000 oi = int((notional / entry_price) * 1000000000000000000) # 0.1 fraction = 1000000000000000000 # 1 cap_payoff = 5000000000000000000 # 5 # check trading fee is notional * fee_rate is_long = True # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 11250000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate is_long = False # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 3750000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate when 0 price change is_long = True current_price = entry_price # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate when 0 price change is_long = False current_price = entry_price # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_entry_not_equal_to_mid(position): mid_price = 100000000000000000000 # 100 current_price = 150000000000000000000 # 150 notional = 10000000000000000000 # 10 debt = 2000000000000000000 # 2 liquidated = False trading_fee_rate = 750000000000000 oi = int((notional / mid_price) * 1000000000000000000) # 0.1 fraction = 1000000000000000000 # 1 cap_payoff = 5000000000000000000 # 5 # check trading fee is notional * fee_rate is_long = True entry_price = 101000000000000000000 # 101 # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 11175000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate is_long = False entry_price = 99000000000000000000 # 99 # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 3675000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate when 0 price change is_long = True entry_price = 101000000000000000000 # 101 current_price = entry_price # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate when 0 price change is_long = False entry_price = 99000000000000000000 # 99 current_price = entry_price # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_fraction_less_than_one(position): entry_price = 100000000000000000000 # 100 current_price = 150000000000000000000 # 150 notional = 10000000000000000000 # 10 debt = 2000000000000000000 # 2 liquidated = False trading_fee_rate = 750000000000000 oi = int((notional / entry_price) * 1000000000000000000) # 0.1 fraction = 250000000000000000 # 0.25 cap_payoff = 5000000000000000000 # 5 # check trading fee is notional * fee_rate is_long = True # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 2812500000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual # check trading fee is notional * fee_rate is_long = False # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 937500000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_payoff_greater_than_cap(position): entry_price = 100000000000000000000 # 100 current_price = 800000000000000000000 # 800 notional = 10000000000000000000 # 10 debt = 2000000000000000000 # 2 liquidated = False trading_fee_rate = 750000000000000 oi = int((notional / entry_price) * 1000000000000000000) # 0.1 fraction = 1000000000000000000 # 1 cap_payoff = 5000000000000000000 # 5 # check trading fee is notional * fee_rate is_long = True # NOTE: mid_ratio tests in test_entry_price.py mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 45000000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual
def test_trading_fee(position): entry_price = 100000000000000000000 current_price = 150000000000000000000 notional = 10000000000000000000 debt = 2000000000000000000 liquidated = False trading_fee_rate = 750000000000000 oi = int(notional / entry_price * 1000000000000000000) fraction = 1000000000000000000 cap_payoff = 5000000000000000000 is_long = True mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 11250000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = False mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 3750000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = True current_price = entry_price mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = False current_price = entry_price mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_entry_not_equal_to_mid(position): mid_price = 100000000000000000000 current_price = 150000000000000000000 notional = 10000000000000000000 debt = 2000000000000000000 liquidated = False trading_fee_rate = 750000000000000 oi = int(notional / mid_price * 1000000000000000000) fraction = 1000000000000000000 cap_payoff = 5000000000000000000 is_long = True entry_price = 101000000000000000000 mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 11175000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = False entry_price = 99000000000000000000 mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 3675000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = True entry_price = 101000000000000000000 current_price = entry_price mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = False entry_price = 99000000000000000000 current_price = entry_price mid_ratio = position.calcEntryToMidRatio(entry_price, mid_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 7500000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_fraction_less_than_one(position): entry_price = 100000000000000000000 current_price = 150000000000000000000 notional = 10000000000000000000 debt = 2000000000000000000 liquidated = False trading_fee_rate = 750000000000000 oi = int(notional / entry_price * 1000000000000000000) fraction = 250000000000000000 cap_payoff = 5000000000000000000 is_long = True mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 2812500000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual is_long = False mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 937500000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual def test_trading_fee_when_payoff_greater_than_cap(position): entry_price = 100000000000000000000 current_price = 800000000000000000000 notional = 10000000000000000000 debt = 2000000000000000000 liquidated = False trading_fee_rate = 750000000000000 oi = int(notional / entry_price * 1000000000000000000) fraction = 1000000000000000000 cap_payoff = 5000000000000000000 is_long = True mid_ratio = position.calcEntryToMidRatio(entry_price, entry_price) pos = (notional, debt, mid_ratio, is_long, liquidated, oi) expect = 45000000000000000 actual = position.tradingFee(pos, fraction, oi, oi, current_price, cap_payoff, trading_fee_rate) assert expect == actual
# 9th Solutions #-------------------------- n = int(input()) d = {} for i in range(n): x = input().split() d[x[0]] = x[1] while True: try: name = input() if name in d: print(name, '=', d[name], sep='') else: print('Not found') except: break
n = int(input()) d = {} for i in range(n): x = input().split() d[x[0]] = x[1] while True: try: name = input() if name in d: print(name, '=', d[name], sep='') else: print('Not found') except: break
def define_targets(rules): rules.cc_test( name = "test", srcs = ["impl/CUDATest.cpp"], deps = [ "@com_google_googletest//:gtest_main", "//c10/cuda", ], target_compatible_with = rules.requires_cuda_enabled(), )
def define_targets(rules): rules.cc_test(name='test', srcs=['impl/CUDATest.cpp'], deps=['@com_google_googletest//:gtest_main', '//c10/cuda'], target_compatible_with=rules.requires_cuda_enabled())
def vogal(c): if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' or c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U': return True else: return False
def vogal(c): if c == 'a' or c == 'e' or c == 'i' or (c == 'o') or (c == 'u') or (c == 'A') or (c == 'E') or (c == 'I') or (c == 'O') or (c == 'U'): return True else: return False
# Copyright 2021 Variscite LTD # SPDX-License-Identifier: BSD-3-Clause __version__ = "1.0.0"
__version__ = '1.0.0'
# dfs def walk_parents(vertex): return sum( (walk_parents(parent) for parent in vertex.parents), [] ) + [vertex] def walk_children(vertex): return sum( (walk_children(child) for child in vertex.children), [] ) + [vertex]
def walk_parents(vertex): return sum((walk_parents(parent) for parent in vertex.parents), []) + [vertex] def walk_children(vertex): return sum((walk_children(child) for child in vertex.children), []) + [vertex]
# list1 = [i for i in range(5, 16)] # print(list1) # list1 = [i for i in range(0, 11)] # for i in range(11): # if i > 0: # print(list1[i-1] * list1[i]) # list1 = [i * j for i in range(1, 10) for j in range(1, 10)] # print(list1) str1 = str(input()) strArray = list(str1) newList = [] for i in strArray: if i > "e": del i else: newList.append(i) print(*newList)
str1 = str(input()) str_array = list(str1) new_list = [] for i in strArray: if i > 'e': del i else: newList.append(i) print(*newList)
# Flask settings DEBUG = False # Flask-restplus settings RESTPLUS_MASK_SWAGGER = False SWAGGER_UI_DOC_EXPANSION = 'none' # Application settings # API metadata API_TITLE = 'MAX Image Colorizer' API_DESC = 'Adds color to black and white images.' API_VERSION = '1.1.0' ERR_MSG = 'Invalid file type/extension. Please provide a valid image (supported formats: JPEG, PNG).' # default model MODEL_NAME = API_TITLE MODEL_ID = MODEL_NAME.replace(' ', '-').lower() DEFAULT_MODEL_PATH = 'assets/pix2pix-bw-to-color' MODEL_LICENSE = 'MIT'
debug = False restplus_mask_swagger = False swagger_ui_doc_expansion = 'none' api_title = 'MAX Image Colorizer' api_desc = 'Adds color to black and white images.' api_version = '1.1.0' err_msg = 'Invalid file type/extension. Please provide a valid image (supported formats: JPEG, PNG).' model_name = API_TITLE model_id = MODEL_NAME.replace(' ', '-').lower() default_model_path = 'assets/pix2pix-bw-to-color' model_license = 'MIT'
minx = 20 maxx = 30 miny = -10 maxy = -5 minx = 25 maxx = 67 miny = -260 maxy = -200 def simulate(vx, vy): x = 0 y = 0 highest = 0 while y > miny: x += vx y += vy if vx > 0: vx -= 1 elif vx < 0: vx += 1 vy -= 1 if vy == 0: highest = y if x >= minx and x <= maxx and y >= miny and y <= maxy: return highest return -1 result = 0 num = 0 for x in range(1, maxx + 1): for y in range(miny, 500): v = simulate(x, y) if v >= 0: num += 1 if v > result: result = v print(f"{result}") print(f"{num}")
minx = 20 maxx = 30 miny = -10 maxy = -5 minx = 25 maxx = 67 miny = -260 maxy = -200 def simulate(vx, vy): x = 0 y = 0 highest = 0 while y > miny: x += vx y += vy if vx > 0: vx -= 1 elif vx < 0: vx += 1 vy -= 1 if vy == 0: highest = y if x >= minx and x <= maxx and (y >= miny) and (y <= maxy): return highest return -1 result = 0 num = 0 for x in range(1, maxx + 1): for y in range(miny, 500): v = simulate(x, y) if v >= 0: num += 1 if v > result: result = v print(f'{result}') print(f'{num}')
def file_to_list(filename): lines = [] fin = open(filename, "rt", encoding="utf-8") lines = fin.readlines() fin.close() return lines def print_table(lines): template = { "1": "+" + "-" * 11 + "+" + "-" * 11 + "+" + "-" * 8 + "+", "2": "| {:<10.9}| {:<10.9}| {:<7.6}|", } print(template["1"]) print(template["2"].format("Last", "First", "Salary")) print(template["1"]) for line in lines: field = line.rstrip().split(",") print(template["2"].format(field[0], field[1], field[2])) print(template["1"]) def main(): lines = file_to_list("../data/42.txt") print_table(lines) main()
def file_to_list(filename): lines = [] fin = open(filename, 'rt', encoding='utf-8') lines = fin.readlines() fin.close() return lines def print_table(lines): template = {'1': '+' + '-' * 11 + '+' + '-' * 11 + '+' + '-' * 8 + '+', '2': '| {:<10.9}| {:<10.9}| {:<7.6}|'} print(template['1']) print(template['2'].format('Last', 'First', 'Salary')) print(template['1']) for line in lines: field = line.rstrip().split(',') print(template['2'].format(field[0], field[1], field[2])) print(template['1']) def main(): lines = file_to_list('../data/42.txt') print_table(lines) main()
a = int(input()) b = int(input()) c = int(input()) a_odd = a % 2 b_odd = b % 2 c_odd = c % 2 a_even = not (a % 2) b_even = not (b % 2) c_even = not (c % 2) if (a_odd or b_odd or c_odd) and (a_even or b_even or c_even): print("YES") else: print("NO")
a = int(input()) b = int(input()) c = int(input()) a_odd = a % 2 b_odd = b % 2 c_odd = c % 2 a_even = not a % 2 b_even = not b % 2 c_even = not c % 2 if (a_odd or b_odd or c_odd) and (a_even or b_even or c_even): print('YES') else: print('NO')
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def closestValue(self, root: TreeNode, target: float) -> int: if root == None: return float('inf') diff = target - root.val if diff > 0: sub_closest = self.closestValue(root.right, target) elif diff < 0: sub_closest = self.closestValue(root.left, target) else: return root.val if abs(root.val - target) > abs(sub_closest - target): return sub_closest else: return root.val
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def closest_value(self, root: TreeNode, target: float) -> int: if root == None: return float('inf') diff = target - root.val if diff > 0: sub_closest = self.closestValue(root.right, target) elif diff < 0: sub_closest = self.closestValue(root.left, target) else: return root.val if abs(root.val - target) > abs(sub_closest - target): return sub_closest else: return root.val
command = '/opt/django/smegurus-django/env/bin/gunicorn' pythonpath = '/opt/django/smegurus-django/smegurus' bind = '127.0.0.1:8001' workers = 3
command = '/opt/django/smegurus-django/env/bin/gunicorn' pythonpath = '/opt/django/smegurus-django/smegurus' bind = '127.0.0.1:8001' workers = 3
language_compiler_param = \ { "java": "-encoding UTF-8 -d -cp ." }
language_compiler_param = {'java': '-encoding UTF-8 -d -cp .'}
aTuple = ("Orange", [10, 20, 30], (5, 15, 25)) print(aTuple[1][1])
a_tuple = ('Orange', [10, 20, 30], (5, 15, 25)) print(aTuple[1][1])
__all__ = [ "sorter", "ioputter", "handler", "timer", "simple", "process", "HarnessChartProcessing", "KomaxTaskProcessing", "KomaxCore", "HarnessProcessing" ]
__all__ = ['sorter', 'ioputter', 'handler', 'timer', 'simple', 'process', 'HarnessChartProcessing', 'KomaxTaskProcessing', 'KomaxCore', 'HarnessProcessing']
_base_ = "base.py" fold = 1 percent = 1 data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( ann_file="data/coco/annotations/semi_supervised/instances_train2017.${fold}@${percent}.json", img_prefix="data/coco/train2017/", ), ) work_dir = "work_dirs/${cfg_name}/${percent}/${fold}" log_config = dict( interval=50, hooks=[ dict(type="TextLoggerHook"), dict( type="WandbLoggerHook", init_kwargs=dict( project="pre_release", name="${cfg_name}", config=dict( fold="${fold}", percent="${percent}", work_dirs="${work_dir}", total_step="${runner.max_iters}", ), ), by_epoch=False, ), ], )
_base_ = 'base.py' fold = 1 percent = 1 data = dict(samples_per_gpu=1, workers_per_gpu=1, train=dict(ann_file='data/coco/annotations/semi_supervised/instances_train2017.${fold}@${percent}.json', img_prefix='data/coco/train2017/')) work_dir = 'work_dirs/${cfg_name}/${percent}/${fold}' log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook'), dict(type='WandbLoggerHook', init_kwargs=dict(project='pre_release', name='${cfg_name}', config=dict(fold='${fold}', percent='${percent}', work_dirs='${work_dir}', total_step='${runner.max_iters}')), by_epoch=False)])
class GumballMonitor: def __init__(self, machine): self.machine = machine def report(self): try: print(f'Gumball Machine: {self.machine.get_location()}') print(f'Current inventory: {self.machine.get_count()} gumballs') except Exception as e: print(e)
class Gumballmonitor: def __init__(self, machine): self.machine = machine def report(self): try: print(f'Gumball Machine: {self.machine.get_location()}') print(f'Current inventory: {self.machine.get_count()} gumballs') except Exception as e: print(e)
################### Error URLs ##################### # For imageGen.py not_enough_info = 'http://i.imgur.com/2BZk32a.jpg' improperly_formatted_tag = 'http://i.imgur.com/HvFX82m.jpg' # For memeAPI.py meme_not_supported = 'http://i.imgur.com/6VoMZqm.jpg' couldnt_create_meme = 'http://i.imgur.com/bkW1HEV.jpg' too_many_lines = 'http://i.imgur.com/fGkrbGe.jpg' too_few_lines = 'http://i.imgur.com/aLYiN7V.jpg' # For gifAPI.py no_search_params = 'http://i.imgur.com/60KAAPv.jpg' no_suitable_gif = 'http://i.imgur.com/gH3bPTs.jpg'
not_enough_info = 'http://i.imgur.com/2BZk32a.jpg' improperly_formatted_tag = 'http://i.imgur.com/HvFX82m.jpg' meme_not_supported = 'http://i.imgur.com/6VoMZqm.jpg' couldnt_create_meme = 'http://i.imgur.com/bkW1HEV.jpg' too_many_lines = 'http://i.imgur.com/fGkrbGe.jpg' too_few_lines = 'http://i.imgur.com/aLYiN7V.jpg' no_search_params = 'http://i.imgur.com/60KAAPv.jpg' no_suitable_gif = 'http://i.imgur.com/gH3bPTs.jpg'
# # PySNMP MIB module CENTILLION-FILTERS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CENTILLION-FILTERS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:47:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint") StatusIndicator, sysConfig = mibBuilder.importSymbols("CENTILLION-ROOT-MIB", "StatusIndicator", "sysConfig") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") TimeTicks, Counter32, MibIdentifier, Gauge32, ObjectIdentity, Unsigned32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, IpAddress, Integer32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter32", "MibIdentifier", "Gauge32", "ObjectIdentity", "Unsigned32", "NotificationType", "iso", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "IpAddress", "Integer32", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") class GeneralFilterName(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(8, 8) fixedLength = 8 class NetbiosFilterName(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(16, 16) fixedLength = 16 class NetbiosFilterAction(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("discard", 1), ("forward", 2)) filterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11)) filterGroupTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1), ) if mibBuilder.loadTexts: filterGroupTable.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupTable.setDescription('Filter Group Table. Entries are added into the group by specifying values for all objects with the exception of the filterGroupMonitorDests and filterGroupAdditionalDests objects. Entries are deleted simply by specifying the appropriate filterGroupStatus value.') filterGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1), ).setIndexNames((0, "CENTILLION-FILTERS-MIB", "filterGroupName"), (0, "CENTILLION-FILTERS-MIB", "filterGroupIndex")) if mibBuilder.loadTexts: filterGroupEntry.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') filterGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 1), GeneralFilterName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupName.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupName.setDescription('A user-defined unique ASCII string identifying the filter group.') filterGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupIndex.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupIndex.setDescription('The index of the filter entry within the filter group. Any filter group entry is uniquely identifable by the group nam and index.') filterGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 3), StatusIndicator()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupStatus.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupStatus.setDescription('The status of this filter group entry. Entries may be deleted by setting this object to invalid(2).') filterGroupMatch = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("lt", 1), ("eq", 2), ("le", 3), ("gt", 4), ("ne", 5), ("ge", 6)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupMatch.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupMatch.setDescription('The match condition for the filter. Match conditions are in the form of the usual logical operators.') filterGroupType = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("macFilter", 1), ("llcFilter", 2), ("vlanFilter", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupType.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupType.setDescription("The type of filter. MAC filters are defined from the start of the MAC frame. LLC filters are defined from the start of the LLC header (after RIF). VLAN filters operate on a packet's VLAN classification parameters. For a valid VLAN filter, filterGroupOffset be set to 0, and filterGroupValue must contain exactly four bytes of VLAN filter data as shown below: Octet 1 Defines the user priority match criteria for VLAN filter. Valid values are 0x01 through 0xFF. Each bit in the octet corresponds to one of the eight available user priority level as defined by the 802.1Q draft specification. The least significant bit represents priority zero, and the most significant bit represents priority seven. Octet 2 Defines the Canonical Format Indicator (CFI) match criteria for VLAN filter. Possible values are 0x00, 0x01 and 0xFF. The value 0xFF indicates the switch should ignore CFI value when filtering. Octet 3 and 4 Define 12-bit VLAN ID match criteria for VLAN filter. Valid values are 0x001 through 0xFFF.") filterGroupOffset = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupOffset.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupOffset.setDescription('The byte offset from the beginning of the header to the value to filter.') filterGroupValue = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupValue.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupValue.setDescription('The filter value field. The value is specified as a hexadecimal string up to 12 bytes.') filterGroupForward = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("normClear", 1), ("alt", 2), ("add", 3), ("addAlt", 4), ("norm", 5), ("normAlt", 6), ("normAdd", 7), ("normAddAlt", 8), ("drop", 9)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupForward.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupForward.setDescription('The forwarding rule for the filter. Forward to normal indicates that the frame should be forwarded as usual.') filterGroupNextIfMatch = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupNextIfMatch.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupNextIfMatch.setDescription('The next filter entry as referenced by the filter index to apply if the filter match succeeds. An entry of 0 indicates that filtering ends for the packet. An entry whose value is larger than the number of filters in the group indicates that the next filter entry to apply is the next filter group (if any) enabled on the port.') filterGroupNextIfFail = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupNextIfFail.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupNextIfFail.setDescription('The next filter entry as referenced by the filter index to apply if the filter match fails. An entry of 0 indicates that filtering ends for the packet. An entry whose value is larger than the number of filters in the group indicates that the next filter entry to apply is the next filter group (if any) enabled on the port.') filterGroupAdditionalDests = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupAdditionalDests.setStatus('deprecated') if mibBuilder.loadTexts: filterGroupAdditionalDests.setDescription('This will be replaced by filterGroupAdditionalDestions. A list of up to 256 pairs of additional cards and ports to send packets matching this filter. Each unsigned int8 is formatted as follows: the high-order 4 bits represent the card number, the low order 4 bits are the port number.') filterGroupMonitorDests = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 12), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupMonitorDests.setStatus('deprecated') if mibBuilder.loadTexts: filterGroupMonitorDests.setDescription('This will be replaced by filterGroupAlternateDestination. A pair of the monitoring card and port to send packets matching this filter. Each unsigned int8 is formatted as follows: the high-order 4 bits represent the card number, the low order 4 bits are the port number.') filterGroupAdditionalDestinations = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupAdditionalDestinations.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupAdditionalDestinations.setDescription('For 24 ports support. This is to replace filterGroupAdditionalDests. Setting either filterGroupAdditionalDests or filterGroupAlternateDestination is enough. And if both are set, the one set later will be in effect. Make sure that even number of octets are given. A list of up to 256 pairs of additional cards and ports to send packets matching this filter. Each pair of octets is formatted as follows: the high-order octet represent the card number, the low order octet is the port number.') filterGroupAlternateDestination = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 2))).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterGroupAlternateDestination.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupAlternateDestination.setDescription('For 24 ports support. This is to replace filterGroupMonitorDests. Setting either filterGroupMonitorDests filterGroupAlternateDestination is enough. And if both are set, the one set later will be in effect. Make sure that even number of octets are given. A pair of the monitoring card and port to send packets matching this filter. Each pair of octets is formatted as follows: the high-order byte represent the card number, the low order byte is the port number.') filterPortTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2), ) if mibBuilder.loadTexts: filterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: filterPortTable.setDescription('Input Filter Port Table.') filterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1), ).setIndexNames((0, "CENTILLION-FILTERS-MIB", "filterPortCardNumber"), (0, "CENTILLION-FILTERS-MIB", "filterPortPortNumber"), (0, "CENTILLION-FILTERS-MIB", "filterPortIndex")) if mibBuilder.loadTexts: filterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: filterPortEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') filterPortCardNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: filterPortCardNumber.setDescription('The card number to which the filters apply.') filterPortPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: filterPortPortNumber.setDescription('The port number to which the filters apply.') filterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: filterPortIndex.setDescription('A unique value for each filter group within the port.') filterPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 4), StatusIndicator()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: filterPortStatus.setDescription('The status of this filter port entry. Entries may be deleted by setting this object to invalid(2).') filterPortGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 5), GeneralFilterName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: filterPortGroupName.setStatus('mandatory') if mibBuilder.loadTexts: filterPortGroupName.setDescription('The filter port group name.') netbiosFilterPortTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3), ) if mibBuilder.loadTexts: netbiosFilterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortTable.setDescription('The NetBIOS name filter table indexed by card and port numbers. ') netbiosFilterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1), ).setIndexNames((0, "CENTILLION-FILTERS-MIB", "netbiosFilterPortCardNumber"), (0, "CENTILLION-FILTERS-MIB", "netbiosFilterPortPortNumber"), (0, "CENTILLION-FILTERS-MIB", "netbiosFilterPortIndex")) if mibBuilder.loadTexts: netbiosFilterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortEntry.setDescription('An entry in the NetBios filter port table. Table entries are indexed by the card, port and PortIndex as assigned by the system.') netbiosFilterPortCardNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortCardNumber.setDescription('The card number to which the filters apply.') netbiosFilterPortPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortPortNumber.setDescription('The port number to which the filters apply.') netbiosFilterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortIndex.setDescription('A unique value for each filter group within the port.') netbiosFilterPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 4), StatusIndicator()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortStatus.setDescription('The status of this NetBIOS filter entry. Entries may be deleted by setting this object to invalid(2).') netbiosFilterPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 5), NetbiosFilterName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortName.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortName.setDescription('The NetBIOS name to match for filtering. The name will be blank padded.') netbiosFilterPortAction = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 6), NetbiosFilterAction()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterPortAction.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortAction.setDescription('The action to take upon matching the name filter.') netbiosFilterRingTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4), ) if mibBuilder.loadTexts: netbiosFilterRingTable.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingTable.setDescription('The NetBIOS name filter table indexed by ring number.') netbiosFilterRingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1), ).setIndexNames((0, "CENTILLION-FILTERS-MIB", "netbiosFilterRingNumber"), (0, "CENTILLION-FILTERS-MIB", "netbiosFilterRingIndex")) if mibBuilder.loadTexts: netbiosFilterRingEntry.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingEntry.setDescription('An entry in the NetBios filter port table. Table entries are indexed by ring number and PortIndex as assigned by the system.') netbiosFilterRingNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterRingNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingNumber.setDescription('The ring number to which the filters apply.') netbiosFilterRingIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterRingIndex.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingIndex.setDescription('A unique value for each filter group within the port.') netbiosFilterRingStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 3), StatusIndicator()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterRingStatus.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingStatus.setDescription('The status of this NetBIOS filter entry. Entries may be deleted by setting this object to invalid(2).') netbiosFilterRingName = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 4), NetbiosFilterName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterRingName.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingName.setDescription('The NetBIOS name to match for filtering. The name will be blank padded.') netbiosFilterRingAction = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 5), NetbiosFilterAction()).setMaxAccess("readwrite") if mibBuilder.loadTexts: netbiosFilterRingAction.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingAction.setDescription('The action to take upon matching the name filter.') outputFilterPortTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5), ) if mibBuilder.loadTexts: outputFilterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortTable.setDescription('Output Filter Port Table.') outputFilterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1), ).setIndexNames((0, "CENTILLION-FILTERS-MIB", "outputFilterPortCardNumber"), (0, "CENTILLION-FILTERS-MIB", "outputFilterPortPortNumber"), (0, "CENTILLION-FILTERS-MIB", "outputFilterPortIndex")) if mibBuilder.loadTexts: outputFilterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') outputFilterPortCardNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: outputFilterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortCardNumber.setDescription('The card number to which the filters apply.') outputFilterPortPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: outputFilterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortPortNumber.setDescription('The port number to which the filters apply.') outputFilterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: outputFilterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortIndex.setDescription('A unique value for each filter group within the port.') outputFilterPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 4), StatusIndicator()).setMaxAccess("readwrite") if mibBuilder.loadTexts: outputFilterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortStatus.setDescription('The status of this filter port entry. Entries may be deleted by setting this object to invalid(2).') outputFilterPortGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 5), GeneralFilterName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: outputFilterPortGroupName.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortGroupName.setDescription('The filter port group name.') mibBuilder.exportSymbols("CENTILLION-FILTERS-MIB", netbiosFilterPortName=netbiosFilterPortName, filterGroupValue=filterGroupValue, netbiosFilterRingName=netbiosFilterRingName, filterGroupOffset=filterGroupOffset, netbiosFilterPortCardNumber=netbiosFilterPortCardNumber, NetbiosFilterName=NetbiosFilterName, netbiosFilterRingTable=netbiosFilterRingTable, netbiosFilterPortPortNumber=netbiosFilterPortPortNumber, outputFilterPortIndex=outputFilterPortIndex, filterGroupForward=filterGroupForward, outputFilterPortPortNumber=outputFilterPortPortNumber, filterGroupName=filterGroupName, filterGroupNextIfMatch=filterGroupNextIfMatch, filterGroupAdditionalDests=filterGroupAdditionalDests, netbiosFilterPortAction=netbiosFilterPortAction, outputFilterPortTable=outputFilterPortTable, netbiosFilterRingIndex=netbiosFilterRingIndex, outputFilterPortEntry=outputFilterPortEntry, netbiosFilterPortIndex=netbiosFilterPortIndex, outputFilterPortCardNumber=outputFilterPortCardNumber, netbiosFilterRingNumber=netbiosFilterRingNumber, filterPortStatus=filterPortStatus, netbiosFilterRingAction=netbiosFilterRingAction, filterGroup=filterGroup, netbiosFilterPortStatus=netbiosFilterPortStatus, filterGroupIndex=filterGroupIndex, netbiosFilterPortTable=netbiosFilterPortTable, filterPortEntry=filterPortEntry, filterGroupTable=filterGroupTable, filterPortTable=filterPortTable, filterGroupMatch=filterGroupMatch, GeneralFilterName=GeneralFilterName, netbiosFilterPortEntry=netbiosFilterPortEntry, netbiosFilterRingStatus=netbiosFilterRingStatus, outputFilterPortGroupName=outputFilterPortGroupName, filterGroupType=filterGroupType, filterGroupMonitorDests=filterGroupMonitorDests, filterPortCardNumber=filterPortCardNumber, filterGroupStatus=filterGroupStatus, filterGroupAlternateDestination=filterGroupAlternateDestination, filterPortGroupName=filterPortGroupName, filterPortPortNumber=filterPortPortNumber, filterGroupEntry=filterGroupEntry, outputFilterPortStatus=outputFilterPortStatus, filterGroupAdditionalDestinations=filterGroupAdditionalDestinations, netbiosFilterRingEntry=netbiosFilterRingEntry, filterPortIndex=filterPortIndex, filterGroupNextIfFail=filterGroupNextIfFail, NetbiosFilterAction=NetbiosFilterAction)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint') (status_indicator, sys_config) = mibBuilder.importSymbols('CENTILLION-ROOT-MIB', 'StatusIndicator', 'sysConfig') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (time_ticks, counter32, mib_identifier, gauge32, object_identity, unsigned32, notification_type, iso, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, ip_address, integer32, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Counter32', 'MibIdentifier', 'Gauge32', 'ObjectIdentity', 'Unsigned32', 'NotificationType', 'iso', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'IpAddress', 'Integer32', 'Bits') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') class Generalfiltername(DisplayString): subtype_spec = DisplayString.subtypeSpec + value_size_constraint(8, 8) fixed_length = 8 class Netbiosfiltername(DisplayString): subtype_spec = DisplayString.subtypeSpec + value_size_constraint(16, 16) fixed_length = 16 class Netbiosfilteraction(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('discard', 1), ('forward', 2)) filter_group = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11)) filter_group_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1)) if mibBuilder.loadTexts: filterGroupTable.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupTable.setDescription('Filter Group Table. Entries are added into the group by specifying values for all objects with the exception of the filterGroupMonitorDests and filterGroupAdditionalDests objects. Entries are deleted simply by specifying the appropriate filterGroupStatus value.') filter_group_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1)).setIndexNames((0, 'CENTILLION-FILTERS-MIB', 'filterGroupName'), (0, 'CENTILLION-FILTERS-MIB', 'filterGroupIndex')) if mibBuilder.loadTexts: filterGroupEntry.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') filter_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 1), general_filter_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupName.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupName.setDescription('A user-defined unique ASCII string identifying the filter group.') filter_group_index = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupIndex.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupIndex.setDescription('The index of the filter entry within the filter group. Any filter group entry is uniquely identifable by the group nam and index.') filter_group_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 3), status_indicator()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupStatus.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupStatus.setDescription('The status of this filter group entry. Entries may be deleted by setting this object to invalid(2).') filter_group_match = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('lt', 1), ('eq', 2), ('le', 3), ('gt', 4), ('ne', 5), ('ge', 6)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupMatch.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupMatch.setDescription('The match condition for the filter. Match conditions are in the form of the usual logical operators.') filter_group_type = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('macFilter', 1), ('llcFilter', 2), ('vlanFilter', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupType.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupType.setDescription("The type of filter. MAC filters are defined from the start of the MAC frame. LLC filters are defined from the start of the LLC header (after RIF). VLAN filters operate on a packet's VLAN classification parameters. For a valid VLAN filter, filterGroupOffset be set to 0, and filterGroupValue must contain exactly four bytes of VLAN filter data as shown below: Octet 1 Defines the user priority match criteria for VLAN filter. Valid values are 0x01 through 0xFF. Each bit in the octet corresponds to one of the eight available user priority level as defined by the 802.1Q draft specification. The least significant bit represents priority zero, and the most significant bit represents priority seven. Octet 2 Defines the Canonical Format Indicator (CFI) match criteria for VLAN filter. Possible values are 0x00, 0x01 and 0xFF. The value 0xFF indicates the switch should ignore CFI value when filtering. Octet 3 and 4 Define 12-bit VLAN ID match criteria for VLAN filter. Valid values are 0x001 through 0xFFF.") filter_group_offset = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 6), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupOffset.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupOffset.setDescription('The byte offset from the beginning of the header to the value to filter.') filter_group_value = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(1, 12))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupValue.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupValue.setDescription('The filter value field. The value is specified as a hexadecimal string up to 12 bytes.') filter_group_forward = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('normClear', 1), ('alt', 2), ('add', 3), ('addAlt', 4), ('norm', 5), ('normAlt', 6), ('normAdd', 7), ('normAddAlt', 8), ('drop', 9)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupForward.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupForward.setDescription('The forwarding rule for the filter. Forward to normal indicates that the frame should be forwarded as usual.') filter_group_next_if_match = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 9), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupNextIfMatch.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupNextIfMatch.setDescription('The next filter entry as referenced by the filter index to apply if the filter match succeeds. An entry of 0 indicates that filtering ends for the packet. An entry whose value is larger than the number of filters in the group indicates that the next filter entry to apply is the next filter group (if any) enabled on the port.') filter_group_next_if_fail = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 10), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupNextIfFail.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupNextIfFail.setDescription('The next filter entry as referenced by the filter index to apply if the filter match fails. An entry of 0 indicates that filtering ends for the packet. An entry whose value is larger than the number of filters in the group indicates that the next filter entry to apply is the next filter group (if any) enabled on the port.') filter_group_additional_dests = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 11), octet_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupAdditionalDests.setStatus('deprecated') if mibBuilder.loadTexts: filterGroupAdditionalDests.setDescription('This will be replaced by filterGroupAdditionalDestions. A list of up to 256 pairs of additional cards and ports to send packets matching this filter. Each unsigned int8 is formatted as follows: the high-order 4 bits represent the card number, the low order 4 bits are the port number.') filter_group_monitor_dests = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 12), octet_string().subtype(subtypeSpec=value_size_constraint(0, 1))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupMonitorDests.setStatus('deprecated') if mibBuilder.loadTexts: filterGroupMonitorDests.setDescription('This will be replaced by filterGroupAlternateDestination. A pair of the monitoring card and port to send packets matching this filter. Each unsigned int8 is formatted as follows: the high-order 4 bits represent the card number, the low order 4 bits are the port number.') filter_group_additional_destinations = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 13), octet_string().subtype(subtypeSpec=value_size_constraint(0, 512))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupAdditionalDestinations.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupAdditionalDestinations.setDescription('For 24 ports support. This is to replace filterGroupAdditionalDests. Setting either filterGroupAdditionalDests or filterGroupAlternateDestination is enough. And if both are set, the one set later will be in effect. Make sure that even number of octets are given. A list of up to 256 pairs of additional cards and ports to send packets matching this filter. Each pair of octets is formatted as follows: the high-order octet represent the card number, the low order octet is the port number.') filter_group_alternate_destination = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 1, 1, 14), octet_string().subtype(subtypeSpec=value_size_constraint(0, 2))).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterGroupAlternateDestination.setStatus('mandatory') if mibBuilder.loadTexts: filterGroupAlternateDestination.setDescription('For 24 ports support. This is to replace filterGroupMonitorDests. Setting either filterGroupMonitorDests filterGroupAlternateDestination is enough. And if both are set, the one set later will be in effect. Make sure that even number of octets are given. A pair of the monitoring card and port to send packets matching this filter. Each pair of octets is formatted as follows: the high-order byte represent the card number, the low order byte is the port number.') filter_port_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2)) if mibBuilder.loadTexts: filterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: filterPortTable.setDescription('Input Filter Port Table.') filter_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1)).setIndexNames((0, 'CENTILLION-FILTERS-MIB', 'filterPortCardNumber'), (0, 'CENTILLION-FILTERS-MIB', 'filterPortPortNumber'), (0, 'CENTILLION-FILTERS-MIB', 'filterPortIndex')) if mibBuilder.loadTexts: filterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: filterPortEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') filter_port_card_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: filterPortCardNumber.setDescription('The card number to which the filters apply.') filter_port_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: filterPortPortNumber.setDescription('The port number to which the filters apply.') filter_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 3), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: filterPortIndex.setDescription('A unique value for each filter group within the port.') filter_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 4), status_indicator()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: filterPortStatus.setDescription('The status of this filter port entry. Entries may be deleted by setting this object to invalid(2).') filter_port_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 2, 1, 5), general_filter_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: filterPortGroupName.setStatus('mandatory') if mibBuilder.loadTexts: filterPortGroupName.setDescription('The filter port group name.') netbios_filter_port_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3)) if mibBuilder.loadTexts: netbiosFilterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortTable.setDescription('The NetBIOS name filter table indexed by card and port numbers. ') netbios_filter_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1)).setIndexNames((0, 'CENTILLION-FILTERS-MIB', 'netbiosFilterPortCardNumber'), (0, 'CENTILLION-FILTERS-MIB', 'netbiosFilterPortPortNumber'), (0, 'CENTILLION-FILTERS-MIB', 'netbiosFilterPortIndex')) if mibBuilder.loadTexts: netbiosFilterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortEntry.setDescription('An entry in the NetBios filter port table. Table entries are indexed by the card, port and PortIndex as assigned by the system.') netbios_filter_port_card_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortCardNumber.setDescription('The card number to which the filters apply.') netbios_filter_port_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortPortNumber.setDescription('The port number to which the filters apply.') netbios_filter_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 3), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortIndex.setDescription('A unique value for each filter group within the port.') netbios_filter_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 4), status_indicator()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortStatus.setDescription('The status of this NetBIOS filter entry. Entries may be deleted by setting this object to invalid(2).') netbios_filter_port_name = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 5), netbios_filter_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortName.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortName.setDescription('The NetBIOS name to match for filtering. The name will be blank padded.') netbios_filter_port_action = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 3, 1, 6), netbios_filter_action()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterPortAction.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterPortAction.setDescription('The action to take upon matching the name filter.') netbios_filter_ring_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4)) if mibBuilder.loadTexts: netbiosFilterRingTable.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingTable.setDescription('The NetBIOS name filter table indexed by ring number.') netbios_filter_ring_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1)).setIndexNames((0, 'CENTILLION-FILTERS-MIB', 'netbiosFilterRingNumber'), (0, 'CENTILLION-FILTERS-MIB', 'netbiosFilterRingIndex')) if mibBuilder.loadTexts: netbiosFilterRingEntry.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingEntry.setDescription('An entry in the NetBios filter port table. Table entries are indexed by ring number and PortIndex as assigned by the system.') netbios_filter_ring_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterRingNumber.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingNumber.setDescription('The ring number to which the filters apply.') netbios_filter_ring_index = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterRingIndex.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingIndex.setDescription('A unique value for each filter group within the port.') netbios_filter_ring_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 3), status_indicator()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterRingStatus.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingStatus.setDescription('The status of this NetBIOS filter entry. Entries may be deleted by setting this object to invalid(2).') netbios_filter_ring_name = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 4), netbios_filter_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterRingName.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingName.setDescription('The NetBIOS name to match for filtering. The name will be blank padded.') netbios_filter_ring_action = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 4, 1, 5), netbios_filter_action()).setMaxAccess('readwrite') if mibBuilder.loadTexts: netbiosFilterRingAction.setStatus('mandatory') if mibBuilder.loadTexts: netbiosFilterRingAction.setDescription('The action to take upon matching the name filter.') output_filter_port_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5)) if mibBuilder.loadTexts: outputFilterPortTable.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortTable.setDescription('Output Filter Port Table.') output_filter_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1)).setIndexNames((0, 'CENTILLION-FILTERS-MIB', 'outputFilterPortCardNumber'), (0, 'CENTILLION-FILTERS-MIB', 'outputFilterPortPortNumber'), (0, 'CENTILLION-FILTERS-MIB', 'outputFilterPortIndex')) if mibBuilder.loadTexts: outputFilterPortEntry.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortEntry.setDescription('An entry in the filter group table. Table entries are indexed by the unique user-defined group name, and the filter entry index as assigned by the system.') output_filter_port_card_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: outputFilterPortCardNumber.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortCardNumber.setDescription('The card number to which the filters apply.') output_filter_port_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: outputFilterPortPortNumber.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortPortNumber.setDescription('The port number to which the filters apply.') output_filter_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 3), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: outputFilterPortIndex.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortIndex.setDescription('A unique value for each filter group within the port.') output_filter_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 4), status_indicator()).setMaxAccess('readwrite') if mibBuilder.loadTexts: outputFilterPortStatus.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortStatus.setDescription('The status of this filter port entry. Entries may be deleted by setting this object to invalid(2).') output_filter_port_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 2, 11, 5, 1, 5), general_filter_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: outputFilterPortGroupName.setStatus('mandatory') if mibBuilder.loadTexts: outputFilterPortGroupName.setDescription('The filter port group name.') mibBuilder.exportSymbols('CENTILLION-FILTERS-MIB', netbiosFilterPortName=netbiosFilterPortName, filterGroupValue=filterGroupValue, netbiosFilterRingName=netbiosFilterRingName, filterGroupOffset=filterGroupOffset, netbiosFilterPortCardNumber=netbiosFilterPortCardNumber, NetbiosFilterName=NetbiosFilterName, netbiosFilterRingTable=netbiosFilterRingTable, netbiosFilterPortPortNumber=netbiosFilterPortPortNumber, outputFilterPortIndex=outputFilterPortIndex, filterGroupForward=filterGroupForward, outputFilterPortPortNumber=outputFilterPortPortNumber, filterGroupName=filterGroupName, filterGroupNextIfMatch=filterGroupNextIfMatch, filterGroupAdditionalDests=filterGroupAdditionalDests, netbiosFilterPortAction=netbiosFilterPortAction, outputFilterPortTable=outputFilterPortTable, netbiosFilterRingIndex=netbiosFilterRingIndex, outputFilterPortEntry=outputFilterPortEntry, netbiosFilterPortIndex=netbiosFilterPortIndex, outputFilterPortCardNumber=outputFilterPortCardNumber, netbiosFilterRingNumber=netbiosFilterRingNumber, filterPortStatus=filterPortStatus, netbiosFilterRingAction=netbiosFilterRingAction, filterGroup=filterGroup, netbiosFilterPortStatus=netbiosFilterPortStatus, filterGroupIndex=filterGroupIndex, netbiosFilterPortTable=netbiosFilterPortTable, filterPortEntry=filterPortEntry, filterGroupTable=filterGroupTable, filterPortTable=filterPortTable, filterGroupMatch=filterGroupMatch, GeneralFilterName=GeneralFilterName, netbiosFilterPortEntry=netbiosFilterPortEntry, netbiosFilterRingStatus=netbiosFilterRingStatus, outputFilterPortGroupName=outputFilterPortGroupName, filterGroupType=filterGroupType, filterGroupMonitorDests=filterGroupMonitorDests, filterPortCardNumber=filterPortCardNumber, filterGroupStatus=filterGroupStatus, filterGroupAlternateDestination=filterGroupAlternateDestination, filterPortGroupName=filterPortGroupName, filterPortPortNumber=filterPortPortNumber, filterGroupEntry=filterGroupEntry, outputFilterPortStatus=outputFilterPortStatus, filterGroupAdditionalDestinations=filterGroupAdditionalDestinations, netbiosFilterRingEntry=netbiosFilterRingEntry, filterPortIndex=filterPortIndex, filterGroupNextIfFail=filterGroupNextIfFail, NetbiosFilterAction=NetbiosFilterAction)
def ask_user_for_weeknum(): weeknum = 0 while weeknum not in range(1,23): try: weeknum = int(input('Please enter the number of the week that we\'re in:')) if weeknum in range(1,23): break else: print('You did not enter a valid week number') #weeknum = int(input('Please enter the number of the week that we\'re in:')) except ValueError or UnboundLocalError: print('You did not enter a valid week number') print() weeknum = str(weeknum) if len(weeknum) == 1: weeknum = '0'+weeknum #print(weeknum) return weeknum #ask_user_for_weeknum()
def ask_user_for_weeknum(): weeknum = 0 while weeknum not in range(1, 23): try: weeknum = int(input("Please enter the number of the week that we're in:")) if weeknum in range(1, 23): break else: print('You did not enter a valid week number') except ValueError or UnboundLocalError: print('You did not enter a valid week number') print() weeknum = str(weeknum) if len(weeknum) == 1: weeknum = '0' + weeknum return weeknum
message = input() new_message = '' index = 0 current_text = '' multiplier = '' while index < len(message): if message[index].isdigit(): multiplier += message[index] if index+1 < len(message): if message[index+1].isdigit(): multiplier += message[index+1] index += 1 multiplier = int(multiplier) new_message += current_text * multiplier index += 1 multiplier = '' current_text = '' continue current_text += message[index].upper() index += 1 print(f"Unique symbols used: {len(set(new_message))}") print(new_message)
message = input() new_message = '' index = 0 current_text = '' multiplier = '' while index < len(message): if message[index].isdigit(): multiplier += message[index] if index + 1 < len(message): if message[index + 1].isdigit(): multiplier += message[index + 1] index += 1 multiplier = int(multiplier) new_message += current_text * multiplier index += 1 multiplier = '' current_text = '' continue current_text += message[index].upper() index += 1 print(f'Unique symbols used: {len(set(new_message))}') print(new_message)
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_mongodb_mongodb_driver_reactivestreams", artifact = "org.mongodb:mongodb-driver-reactivestreams:1.11.0", jar_sha256 = "ae3d5eb3c51a0c286f43fe7ab0c52e3e0b385766f1b4dd82e06df1e617770764", srcjar_sha256 = "f3eb497f44ffc040d048c205d813c84846a3fc550a656110b1888a38797af77b", deps = [ "@org_mongodb_mongodb_driver_async", "@org_reactivestreams_reactive_streams" ], )
load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external') def dependencies(): import_external(name='org_mongodb_mongodb_driver_reactivestreams', artifact='org.mongodb:mongodb-driver-reactivestreams:1.11.0', jar_sha256='ae3d5eb3c51a0c286f43fe7ab0c52e3e0b385766f1b4dd82e06df1e617770764', srcjar_sha256='f3eb497f44ffc040d048c205d813c84846a3fc550a656110b1888a38797af77b', deps=['@org_mongodb_mongodb_driver_async', '@org_reactivestreams_reactive_streams'])
def delete_date_symbols(date,dateFormat): if(dateFormat == 'YYYY-MM-DD HH:MM:SS'): year = date[0:4] month = date[5:7] day = date[8:10] hours = date[11:13] minutes = date[14:16] seconds = date[17:19] formattedDate=year+month+day+hours+minutes+seconds return formattedDate else: return 'pass a date formatted as YYYY-MM-DD HH:MM:SS'
def delete_date_symbols(date, dateFormat): if dateFormat == 'YYYY-MM-DD HH:MM:SS': year = date[0:4] month = date[5:7] day = date[8:10] hours = date[11:13] minutes = date[14:16] seconds = date[17:19] formatted_date = year + month + day + hours + minutes + seconds return formattedDate else: return 'pass a date formatted as YYYY-MM-DD HH:MM:SS'
class Solution: def countAndSay(self, n: int) -> str: if n == 1: return "1" prev = "1" for i in range(1, n): res = "" val = prev[0] count = 1 for i in range(1, len(prev)): if prev[i] == val: count += 1 else: res += str(count) + val val = prev[i] count =1 res += str(count) + val prev = res return res
class Solution: def count_and_say(self, n: int) -> str: if n == 1: return '1' prev = '1' for i in range(1, n): res = '' val = prev[0] count = 1 for i in range(1, len(prev)): if prev[i] == val: count += 1 else: res += str(count) + val val = prev[i] count = 1 res += str(count) + val prev = res return res
# # @lc app=leetcode id=771 lang=python3 # # [771] Jewels and Stones # # @lc code=start class Solution: def numJewelsInStones(self, J: str, S: str) -> int: jewels = set(J) number_jewels = 0 for char in S: if char in jewels: number_jewels += 1 return number_jewels # return (1 if char in jewels else 0 for char in jewels) # oneline solution # @lc code=end
class Solution: def num_jewels_in_stones(self, J: str, S: str) -> int: jewels = set(J) number_jewels = 0 for char in S: if char in jewels: number_jewels += 1 return number_jewels
#Odd numbers for number in range(1,21,2): print(number)
for number in range(1, 21, 2): print(number)
# Copyright (C) 2019 The Android Open Source Project # # 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. # Noop function used to override rules we don't want to support in standalone. def _noop_override(**kwargs): pass PERFETTO_CONFIG = struct( # This is used to refer to deps within perfetto's BUILD files. # In standalone and bazel-based embedders use '//', because perfetto has its # own repository, and //xxx would be relative to @perfetto//xxx. # In Google internal builds, instead, this is set to //third_party/perfetto, # because perfetto doesn't have its own repository there. root = "//", # These variables map dependencies to perfetto third-party projects. This is # to allow perfetto embedders (e.g. gapid) and google internal builds to # override paths and target names to their own third_party. deps = struct( # Target exposing the build config header. It should be a valid # cc_library dependency as it will become a dependency of every # perfetto_cc_library target. It needs to expose a # "perfetto_build_flags.h" file that can be included via: # #include "perfetto_build_flags.h". build_config = ["//:build_config_hdr"], zlib = ["@perfetto_dep_zlib//:zlib"], jsoncpp = ["@perfetto_dep_jsoncpp//:jsoncpp"], linenoise = ["@perfetto_dep_linenoise//:linenoise"], sqlite = ["@perfetto_dep_sqlite//:sqlite"], sqlite_ext_percentile = ["@perfetto_dep_sqlite_src//:percentile_ext"], protoc = ["@com_google_protobuf//:protoc"], protoc_lib = ["@com_google_protobuf//:protoc_lib"], protobuf_lite = ["@com_google_protobuf//:protobuf_lite"], protobuf_full = ["@com_google_protobuf//:protobuf"], ), # This struct allows embedders to customize the cc_opts for Perfetto # 3rd party dependencies. They only have an effect if the dependencies are # initialized with the Perfetto build files (i.e. via perfetto_deps()). deps_copts = struct( zlib = [], jsoncpp = [], linenoise = [], sqlite = [], ), # Allow Bazel embedders to change the visibility of "public" targets. # This variable has been introduced to limit the change to Bazel and avoid # making the targets fully public in the google internal tree. public_visibility = [ "//visibility:public", ], # Allow Bazel embedders to change the visibility of the proto targets. # This variable has been introduced to limit the change to Bazel and avoid # making the targets public in the google internal tree. proto_library_visibility = "//visibility:private", # This struct allows the embedder to customize copts and other args passed # to rules like cc_binary. Prefixed rules (e.g. perfetto_cc_binary) will # look into this struct before falling back on native.cc_binary(). # This field is completely optional, the embedder can omit the whole # |rule_overrides| or invidivual keys. They are assigned to None or noop # actions here just for documentation purposes. rule_overrides = struct( cc_binary = None, cc_library = None, cc_proto_library = None, # Supporting java rules pulls in the JDK and generally is not something # we need for most embedders. java_proto_library = _noop_override, java_lite_proto_library = _noop_override, proto_library = None, py_binary = None, # We only need this for internal binaries. No other embeedder should # care about this. gensignature_internal_only = None, ), )
def _noop_override(**kwargs): pass perfetto_config = struct(root='//', deps=struct(build_config=['//:build_config_hdr'], zlib=['@perfetto_dep_zlib//:zlib'], jsoncpp=['@perfetto_dep_jsoncpp//:jsoncpp'], linenoise=['@perfetto_dep_linenoise//:linenoise'], sqlite=['@perfetto_dep_sqlite//:sqlite'], sqlite_ext_percentile=['@perfetto_dep_sqlite_src//:percentile_ext'], protoc=['@com_google_protobuf//:protoc'], protoc_lib=['@com_google_protobuf//:protoc_lib'], protobuf_lite=['@com_google_protobuf//:protobuf_lite'], protobuf_full=['@com_google_protobuf//:protobuf']), deps_copts=struct(zlib=[], jsoncpp=[], linenoise=[], sqlite=[]), public_visibility=['//visibility:public'], proto_library_visibility='//visibility:private', rule_overrides=struct(cc_binary=None, cc_library=None, cc_proto_library=None, java_proto_library=_noop_override, java_lite_proto_library=_noop_override, proto_library=None, py_binary=None, gensignature_internal_only=None))
load("@npm//@bazel/typescript:index.bzl", "ts_library") def ng_ts_library(**kwargs): ts_library( compiler = "//libraries/angular-tools:tsc_wrapped_with_angular", supports_workers = True, use_angular_plugin = True, **kwargs )
load('@npm//@bazel/typescript:index.bzl', 'ts_library') def ng_ts_library(**kwargs): ts_library(compiler='//libraries/angular-tools:tsc_wrapped_with_angular', supports_workers=True, use_angular_plugin=True, **kwargs)
def comb(n, k): if n - k < k: k = n - k if k == 0: return 1 a = 1 b = 1 for i in range(k): a *= n - i b *= i + 1 return a // b N, P = map(int, input().split()) A = list(map(int, input().split())) odds = sum(a % 2 for a in A) evens = len(A) - odds print(sum(comb(odds, i) for i in range(P, odds + 1, 2)) * (2 ** evens))
def comb(n, k): if n - k < k: k = n - k if k == 0: return 1 a = 1 b = 1 for i in range(k): a *= n - i b *= i + 1 return a // b (n, p) = map(int, input().split()) a = list(map(int, input().split())) odds = sum((a % 2 for a in A)) evens = len(A) - odds print(sum((comb(odds, i) for i in range(P, odds + 1, 2))) * 2 ** evens)
class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: if k == 0: return [] win = sorted(nums[:k]) ans = [] for i in range(k, len(nums) + 1): median = (win[k // 2] + win[(k - 1) // 2]) / 2.0 ans.append(median) if i == len(nums): break # get the index of the nums[i-k] and then delete it, then insort nums[i] index = bisect.bisect_left(win, nums[i - k]) win.pop(index) bisect.insort_left(win, nums[i]) return ans
class Solution: def median_sliding_window(self, nums: List[int], k: int) -> List[float]: if k == 0: return [] win = sorted(nums[:k]) ans = [] for i in range(k, len(nums) + 1): median = (win[k // 2] + win[(k - 1) // 2]) / 2.0 ans.append(median) if i == len(nums): break index = bisect.bisect_left(win, nums[i - k]) win.pop(index) bisect.insort_left(win, nums[i]) return ans
# https://codeforces.com/problemset/problem/230/A s, n = [int(x) for x in input().split()] dragons = [] new_dragons = [] for _ in range(n): x, y = [int(x) for x in input().split()] dragons.append([x, y]) dragons.sort() for row in range(n - 1): current_row = dragons[row] next_row = dragons[row + 1] if current_row[0] == next_row[0]: if current_row[1] < next_row[1]: dragons[row], dragons[row + 1] = dragons[row + 1], dragons[row] else: continue # print(dragons) bool_var = True for row in dragons: if s > row[0]: s += row[1] else: print('NO') bool_var = False break if bool_var: print('YES')
(s, n) = [int(x) for x in input().split()] dragons = [] new_dragons = [] for _ in range(n): (x, y) = [int(x) for x in input().split()] dragons.append([x, y]) dragons.sort() for row in range(n - 1): current_row = dragons[row] next_row = dragons[row + 1] if current_row[0] == next_row[0]: if current_row[1] < next_row[1]: (dragons[row], dragons[row + 1]) = (dragons[row + 1], dragons[row]) else: continue bool_var = True for row in dragons: if s > row[0]: s += row[1] else: print('NO') bool_var = False break if bool_var: print('YES')
# # PySNMP MIB module NMS-EPON-ONU-RESET (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-EPON-ONU-RESET # Produced by pysmi-0.3.4 at Mon Apr 29 20:12:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint") nmsEPONGroup, = mibBuilder.importSymbols("NMS-SMI", "nmsEPONGroup") PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Bits, NotificationType, IpAddress, Integer32, Gauge32, ModuleIdentity, Unsigned32, iso, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, TimeTicks, Counter64, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "NotificationType", "IpAddress", "Integer32", "Gauge32", "ModuleIdentity", "Unsigned32", "iso", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "TimeTicks", "Counter64", "ObjectIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") nmsEponOnuReset = MibIdentifier((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25)) nmsEponOnuResetTable = MibTable((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1), ) if mibBuilder.loadTexts: nmsEponOnuResetTable.setStatus('mandatory') nmsEponOnuResetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1), ).setIndexNames((0, "NMS-EPON-ONU-RESET", "onuLlid")) if mibBuilder.loadTexts: nmsEponOnuResetEntry.setStatus('mandatory') onuLlid = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: onuLlid.setStatus('mandatory') onuReset = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no_action", 0), ("reset", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: onuReset.setStatus('mandatory') mibBuilder.exportSymbols("NMS-EPON-ONU-RESET", nmsEponOnuResetEntry=nmsEponOnuResetEntry, onuLlid=onuLlid, nmsEponOnuResetTable=nmsEponOnuResetTable, nmsEponOnuReset=nmsEponOnuReset, onuReset=onuReset)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint') (nms_epon_group,) = mibBuilder.importSymbols('NMS-SMI', 'nmsEPONGroup') (port_list,) = mibBuilder.importSymbols('Q-BRIDGE-MIB', 'PortList') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (bits, notification_type, ip_address, integer32, gauge32, module_identity, unsigned32, iso, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, time_ticks, counter64, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'NotificationType', 'IpAddress', 'Integer32', 'Gauge32', 'ModuleIdentity', 'Unsigned32', 'iso', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'TimeTicks', 'Counter64', 'ObjectIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') nms_epon_onu_reset = mib_identifier((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25)) nms_epon_onu_reset_table = mib_table((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1)) if mibBuilder.loadTexts: nmsEponOnuResetTable.setStatus('mandatory') nms_epon_onu_reset_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1)).setIndexNames((0, 'NMS-EPON-ONU-RESET', 'onuLlid')) if mibBuilder.loadTexts: nmsEponOnuResetEntry.setStatus('mandatory') onu_llid = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: onuLlid.setStatus('mandatory') onu_reset = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 25, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('no_action', 0), ('reset', 1)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: onuReset.setStatus('mandatory') mibBuilder.exportSymbols('NMS-EPON-ONU-RESET', nmsEponOnuResetEntry=nmsEponOnuResetEntry, onuLlid=onuLlid, nmsEponOnuResetTable=nmsEponOnuResetTable, nmsEponOnuReset=nmsEponOnuReset, onuReset=onuReset)
def centuryFromYear(year): remainer = year % 100 if remainer == 0: return year/100 else: return int(year/100)+1
def century_from_year(year): remainer = year % 100 if remainer == 0: return year / 100 else: return int(year / 100) + 1
#Christine Logan #9/10/2017 #CS 3240 #Lab 3: Pre-lab #hello.py def greeting(msg): print(msg) def salutation(msg): print(msg) if __name__ == "__main__": greeting("hello") salutation("goodbye")
def greeting(msg): print(msg) def salutation(msg): print(msg) if __name__ == '__main__': greeting('hello') salutation('goodbye')
# TODO: to be deleted class FieldMock: def __init__(self): self.find = lambda _: FieldMock() self.skip = lambda _: FieldMock() self.limit = lambda _: FieldMock() class BeaconMock: def __init__(self): self.datasets = FieldMock() class DBMock: def __init__(self): self.beacon = BeaconMock() client = DBMock()
class Fieldmock: def __init__(self): self.find = lambda _: field_mock() self.skip = lambda _: field_mock() self.limit = lambda _: field_mock() class Beaconmock: def __init__(self): self.datasets = field_mock() class Dbmock: def __init__(self): self.beacon = beacon_mock() client = db_mock()
class SecurityKeyError(Exception): def __init__(self, message): super().__init__(message) class ListenError(Exception): def __init__(self, message): super().__init__(message) class ChildError(Exception): def __init__(self, message): super().__init__(message)
class Securitykeyerror(Exception): def __init__(self, message): super().__init__(message) class Listenerror(Exception): def __init__(self, message): super().__init__(message) class Childerror(Exception): def __init__(self, message): super().__init__(message)
def main(): single_digit = 36 teens = 70 second_digit = 46 hundred = 7 nd = 3 thousand = 11 a = single_digit * (10 * 19) a += second_digit * 10 * 10 a += teens * 10 a += hundred * 900 a += nd * 891 a += thousand print(a) main()
def main(): single_digit = 36 teens = 70 second_digit = 46 hundred = 7 nd = 3 thousand = 11 a = single_digit * (10 * 19) a += second_digit * 10 * 10 a += teens * 10 a += hundred * 900 a += nd * 891 a += thousand print(a) main()
class CreditCard: def __init__(self, cc_number, expiration, security_code): self.cc_number = cc_number self.expiration = expiration self.security_code = security_code class Charge: def __init__(self, success, error=''): self.success = success self.error = error
class Creditcard: def __init__(self, cc_number, expiration, security_code): self.cc_number = cc_number self.expiration = expiration self.security_code = security_code class Charge: def __init__(self, success, error=''): self.success = success self.error = error
{ 'targets': [ { 'target_name': 'xxhash', 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', }, 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 }, }, 'sources': [ 'lib/binding/xxhash_binding.cc', 'deps/lz4/lib/xxhash.h', 'deps/lz4/lib/xxhash.c', ], 'include_dirs': [ '<!(node -p "require(\'node-addon-api\').include_dir")', ], 'cflags': [ '-O3' ], }, { 'target_name': 'lz4', 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', }, 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 }, }, 'sources': [ 'lib/binding/lz4_binding.cc', 'deps/lz4/lib/lz4.h', 'deps/lz4/lib/lz4.c', 'deps/lz4/lib/lz4hc.h', 'deps/lz4/lib/lz4hc.c', ], 'include_dirs': [ '<!(node -p "require(\'node-addon-api\').include_dir")', ], 'cflags': [ '-O3' ], }, ], }
{'targets': [{'target_name': 'xxhash', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7'}, 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'sources': ['lib/binding/xxhash_binding.cc', 'deps/lz4/lib/xxhash.h', 'deps/lz4/lib/xxhash.c'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'cflags': ['-O3']}, {'target_name': 'lz4', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7'}, 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'sources': ['lib/binding/lz4_binding.cc', 'deps/lz4/lib/lz4.h', 'deps/lz4/lib/lz4.c', 'deps/lz4/lib/lz4hc.h', 'deps/lz4/lib/lz4hc.c'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'cflags': ['-O3']}]}
class Solution: def canCross(self, stones): memo, stones, target = {}, set(stones), stones[-1] def dfs(unit, last): if unit == target: return True if (unit, last) not in memo: memo[(unit, last)] = any(dfs(unit + move, move) for move in (last - 1, last, last + 1) if move and unit + move in stones) return memo[(unit, last)] return dfs(1, 1) if 1 in stones else False
class Solution: def can_cross(self, stones): (memo, stones, target) = ({}, set(stones), stones[-1]) def dfs(unit, last): if unit == target: return True if (unit, last) not in memo: memo[unit, last] = any((dfs(unit + move, move) for move in (last - 1, last, last + 1) if move and unit + move in stones)) return memo[unit, last] return dfs(1, 1) if 1 in stones else False
path2file = sys.argv[1] file = open(path2file, 'r') while True: line = file.readline() if not line: break stroka = unicode(line, 'utf-8') type('f', KeyModifier.CTRL) sleep(1) paste(stroka) sleep(1) type(Key.ENTER) sleep(1) break exit(0)
path2file = sys.argv[1] file = open(path2file, 'r') while True: line = file.readline() if not line: break stroka = unicode(line, 'utf-8') type('f', KeyModifier.CTRL) sleep(1) paste(stroka) sleep(1) type(Key.ENTER) sleep(1) break exit(0)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longestSubstring = 0 start = -1 end = 0 characterSet = set() stringLength = len(s) while start < stringLength and end < stringLength: currentChar = s[end] if currentChar in characterSet: start += 1 characterToRemove = s[start] characterSet.remove(characterToRemove) longestSubstring = max(longestSubstring, end - start) else: characterSet.add(currentChar) longestSubstring = max(longestSubstring, end - start) end += 1 return longestSubstring
class Solution: def length_of_longest_substring(self, s: str) -> int: longest_substring = 0 start = -1 end = 0 character_set = set() string_length = len(s) while start < stringLength and end < stringLength: current_char = s[end] if currentChar in characterSet: start += 1 character_to_remove = s[start] characterSet.remove(characterToRemove) longest_substring = max(longestSubstring, end - start) else: characterSet.add(currentChar) longest_substring = max(longestSubstring, end - start) end += 1 return longestSubstring
def Swap(a,b): temp = a a=b b=temp lst = [a,b] return lst
def swap(a, b): temp = a a = b b = temp lst = [a, b] return lst
# 5 # 5 3 # 1 5 2 6 1 # 1 6 # 6 # 3 2 # 1 2 3 # 4 3 # 3 1 2 3 # 10 3 # 1 2 3 4 5 6 7 8 9 10 i = int(input()) l = [] for j in range(i): k = list(map(int,(input().split(' ')))) il = list(map(int,input().split(' '))) if k[1] in il and len(il)==1: l.append('yes') elif k[1] in il[1:] and len(il) % 2 == 1: l.append('yes') elif k[1] in il[1:-1] and len(il) % 2 == 0: l.append('yes') else: l.append('no') for t in l: print(t)
i = int(input()) l = [] for j in range(i): k = list(map(int, input().split(' '))) il = list(map(int, input().split(' '))) if k[1] in il and len(il) == 1: l.append('yes') elif k[1] in il[1:] and len(il) % 2 == 1: l.append('yes') elif k[1] in il[1:-1] and len(il) % 2 == 0: l.append('yes') else: l.append('no') for t in l: print(t)
class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: now = points[0] ans = 0 for point in points[1:]: ans += max(abs(now[0] - point[0]), abs(now[1] - point[1])) now = point return ans
class Solution: def min_time_to_visit_all_points(self, points: List[List[int]]) -> int: now = points[0] ans = 0 for point in points[1:]: ans += max(abs(now[0] - point[0]), abs(now[1] - point[1])) now = point return ans
# Write a Python class which has two methods get_String and print_String.... # get_String accept a string from the user and print_String print the string in upper case. class IOString(): def __init__(self): self.str1 = "" def get_String(self): self.str1 = input() def print_String(self): print(self.str1.upper()) str1 = IOString() str1.get_String() str1.print_String()
class Iostring: def __init__(self): self.str1 = '' def get__string(self): self.str1 = input() def print__string(self): print(self.str1.upper()) str1 = io_string() str1.get_String() str1.print_String()
##################### ### Base classes. ### ##################### class room: repr = "room" m_description = "You are in a simple room." def __init__(self, contents=[]): self.contents = contents def __str__(self): s = "" for object in self.contents: s += " " + str(object) return self.m_description + s def __repr__(self): return self.repr ###################### ### Child classes. ### ###################### class blue_room(room): repr = "b. room" m_description = "You are in a blue room." class red_room(room): repr = "r. room" m_description = "You are in a red room." class green_room(room): repr = "g. room" m_description = "You are in a green room." class final_room(room): repr = "goal" m_description = "You found the hidden room!"
class Room: repr = 'room' m_description = 'You are in a simple room.' def __init__(self, contents=[]): self.contents = contents def __str__(self): s = '' for object in self.contents: s += ' ' + str(object) return self.m_description + s def __repr__(self): return self.repr class Blue_Room(room): repr = 'b. room' m_description = 'You are in a blue room.' class Red_Room(room): repr = 'r. room' m_description = 'You are in a red room.' class Green_Room(room): repr = 'g. room' m_description = 'You are in a green room.' class Final_Room(room): repr = 'goal' m_description = 'You found the hidden room!'
# Source # ====== # https://www.hackerrank.com/contests/projecteuler/challenges/euler008 # # Problem # ======= # Find the greatest product of K consecutive digits in the N digit number. # # Input Format # ============ # First line contains T that denotes the number of test cases. # First line of each test case will contain two integers N & K. # Second line of each test case will contain a N digit integer. # # Constraints # ============ # 1 <= T <= 100 # 1<= K <= 7 # K <= N <= 1000 # # Output Format # ============= # Print the required answer for each test case. def product(num_subset): p = 1 for i in num_subset: p *= i return p t = int(input().strip()) for _ in range(t): n,k = input().strip().split(' ') n,k = [int(n),int(k)] num = input().strip() p = [] for i in range(n-k): num_subset = [int(x) for x in list(num[i:k+i])] p.append(product(num_subset)) print(max(p))
def product(num_subset): p = 1 for i in num_subset: p *= i return p t = int(input().strip()) for _ in range(t): (n, k) = input().strip().split(' ') (n, k) = [int(n), int(k)] num = input().strip() p = [] for i in range(n - k): num_subset = [int(x) for x in list(num[i:k + i])] p.append(product(num_subset)) print(max(p))
# __version__ is for deploying with seed. # VERSION is to keep the rest of the app DRY. __version__ = '0.1.18' VERSION = __version__
__version__ = '0.1.18' version = __version__
class Vehicle(object): def __init__(self, vehicle_id, company, location): self.vehicle_id = vehicle_id self.company = company self.location = location # def __str__(self): # return str( P["id":+str(self.id) + " company: " + str(self.company)+ # str(self.location)+ " location "] ")
class Vehicle(object): def __init__(self, vehicle_id, company, location): self.vehicle_id = vehicle_id self.company = company self.location = location
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? ''' def largest_prime_factor(n): f = 2 while f**2 <= n: while n % f == 0: n //= f f += 1 return max(f-1, n) print(largest_prime_factor(600851475143))
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ def largest_prime_factor(n): f = 2 while f ** 2 <= n: while n % f == 0: n //= f f += 1 return max(f - 1, n) print(largest_prime_factor(600851475143))
def selectionSort(alist): for fillslot in range (len(alist)-1, 0, -1): positionofMax = 0; for location in range(1,fillslot+1): if alist[location] > alist[positionofMax]: positionofMax = location temp = alist[fillslot] alist[fillslot] = alist[positionofMax] alist[positionofMax] = temp a = [54,26,93,17,77,31,44,55,20] selectionSort(a) print (a)
def selection_sort(alist): for fillslot in range(len(alist) - 1, 0, -1): positionof_max = 0 for location in range(1, fillslot + 1): if alist[location] > alist[positionofMax]: positionof_max = location temp = alist[fillslot] alist[fillslot] = alist[positionofMax] alist[positionofMax] = temp a = [54, 26, 93, 17, 77, 31, 44, 55, 20] selection_sort(a) print(a)
#!/usr/bin/env python a = 1000000000 for i in xrange(1000000): a += 1e-6 a -= 1000000000 print(a)
a = 1000000000 for i in xrange(1000000): a += 1e-06 a -= 1000000000 print(a)
class EnviadorDeSpam(): def __init__(self, sessao, enviador): self.sessao = sessao self.enviador = enviador def enviar_emails(self, remetente, assunto, corpo): for usuario in self.sessao.listar(): self.enviador.enviar( remetente, usuario.email, assunto, corpo )
class Enviadordespam: def __init__(self, sessao, enviador): self.sessao = sessao self.enviador = enviador def enviar_emails(self, remetente, assunto, corpo): for usuario in self.sessao.listar(): self.enviador.enviar(remetente, usuario.email, assunto, corpo)
class DDAE_Hyperparams: drop_rate = 0.5 n_units = 1024 activation = 'lrelu' final_act = 'linear' f_bin = 257 class CBHG_Hyperparams: #### Modules #### drop_rate = 0.0 normalization_mode = 'layer_norm' activation = 'lrelu' final_act = 'linear' f_bin = 257 ## CBHG encoder banks_filter = 64 n_banks = 8 n_resblocks = 3 resblocks_filter = 512 down_sample = [512] n_highway = 4 gru_size = 256 class UNET_Hyperparams: drop_rate = 0.0 normalization_mode = 'batch_norm' activation = 'lrelu' final_act = 'linear' f_bin = 257 enc_layers = [32,64,64,128,128,256,256,512,512,1024] dec_layers = [1024,512,512,256,256,128,128,64,64,32] class Hyperparams: is_variable_length = False #### Signal Processing #### n_fft = 512 hop_length = 256 n_mels = 80 # Number of Mel banks to generate f_bin = n_fft//2 + 1 ppg_dim = 96 feature_type = 'logmag' # logmag lps nfeature_mode = 'None' # mean_std minmax cfeature_mode = 'None' # mean_std minmax # num_layers = [1024,512,256,128,256,512] # bigCNN num_layers = [2048,1024,512,256,128,256,512] # bigCNN2 normalization_mode = 'None' activation = 'lrelu' final_act = 'relu' n_units = 1024 pretrain = True pretrain_path = "/mnt/Data/user_vol_2/user_neillu/DNS_Challenge_timit/models/20200516_timit_broad_confusion_triphone_newts/model-1000000" SAVEITER = 20000 # is_trimming = True # sr = 16000 # Sample rate. # n_fft = 1024 # fft points (samples) # frame_shift = 0.0125 # seconds # frame_length = 0.05 # seconds # hop_length = int(sr*frame_shift) # samples. # win_length = int(sr*frame_length) # samples. # power = 1.2 # Exponent for amplifying the predicted magnitude # n_iter = 200 # Number of inversion iterations # preemphasis = .97 # or None max_db = 100 ref_db = 20
class Ddae_Hyperparams: drop_rate = 0.5 n_units = 1024 activation = 'lrelu' final_act = 'linear' f_bin = 257 class Cbhg_Hyperparams: drop_rate = 0.0 normalization_mode = 'layer_norm' activation = 'lrelu' final_act = 'linear' f_bin = 257 banks_filter = 64 n_banks = 8 n_resblocks = 3 resblocks_filter = 512 down_sample = [512] n_highway = 4 gru_size = 256 class Unet_Hyperparams: drop_rate = 0.0 normalization_mode = 'batch_norm' activation = 'lrelu' final_act = 'linear' f_bin = 257 enc_layers = [32, 64, 64, 128, 128, 256, 256, 512, 512, 1024] dec_layers = [1024, 512, 512, 256, 256, 128, 128, 64, 64, 32] class Hyperparams: is_variable_length = False n_fft = 512 hop_length = 256 n_mels = 80 f_bin = n_fft // 2 + 1 ppg_dim = 96 feature_type = 'logmag' nfeature_mode = 'None' cfeature_mode = 'None' num_layers = [2048, 1024, 512, 256, 128, 256, 512] normalization_mode = 'None' activation = 'lrelu' final_act = 'relu' n_units = 1024 pretrain = True pretrain_path = '/mnt/Data/user_vol_2/user_neillu/DNS_Challenge_timit/models/20200516_timit_broad_confusion_triphone_newts/model-1000000' saveiter = 20000 max_db = 100 ref_db = 20
SIZE_BOARD = 10 # Tipo de navios na forma "tipo": tamanho TYPES_OF_SHIPS = { "1": 5, "2": 4, "3": 3, "4": 2 }
size_board = 10 types_of_ships = {'1': 5, '2': 4, '3': 3, '4': 2}
x = input("input a letter : ") if x == "a" or x == "i" or x == "u" or x == "e" or x == "o": print("This is a vowel!") elif x == "y": print("Sometimes y is a vowel and sometimes y is a consonant") else: print("This is a consonant!")
x = input('input a letter : ') if x == 'a' or x == 'i' or x == 'u' or (x == 'e') or (x == 'o'): print('This is a vowel!') elif x == 'y': print('Sometimes y is a vowel and sometimes y is a consonant') else: print('This is a consonant!')
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: max_count = 0 count = 0 for i in nums: if i == 1: count += 1 else: count = 0 max_count = max(max_count, count) return max_count
class Solution: def find_max_consecutive_ones(self, nums: List[int]) -> int: max_count = 0 count = 0 for i in nums: if i == 1: count += 1 else: count = 0 max_count = max(max_count, count) return max_count
# This file declares all the constants for used in this app MAIN_URL = 'https://api.github.com/repos/' ONE_DAY = 1
main_url = 'https://api.github.com/repos/' one_day = 1
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: l, h = 1, n while l <= h: m = l + (h - l) // 2 if guess(m) < 0: h = m - 1 elif guess(m) > 0: l = m + 1 else: return m return -1
class Solution: def guess_number(self, n: int) -> int: (l, h) = (1, n) while l <= h: m = l + (h - l) // 2 if guess(m) < 0: h = m - 1 elif guess(m) > 0: l = m + 1 else: return m return -1
def make_shirt(text, size = 'large'): print('You can buy a ' + size + ' size t-shirt with written ' + text + ' written on it.') make_shirt(text = 'yepa')
def make_shirt(text, size='large'): print('You can buy a ' + size + ' size t-shirt with written ' + text + ' written on it.') make_shirt(text='yepa')
########################################################### # This module is used to centralise messages # used by the self service bot. # ########################################################### class ErrorMessages: BOT_ABORT_ERROR = "Aborting Self Service Bot" BOT_INIT_ERROR = "ERROR reported during initialisation of SelfServiceBot" DYNAMODB_SCAN_ERROR = "ERROR reported by DynamoDB" GENERAL_ERROR = "The bot encountered an error." MISSING_PARAM_ERROR = "Required parameter not provided" MISSING_SKILLS_OBJ_ERROR = "Sills object not provided"
class Errormessages: bot_abort_error = 'Aborting Self Service Bot' bot_init_error = 'ERROR reported during initialisation of SelfServiceBot' dynamodb_scan_error = 'ERROR reported by DynamoDB' general_error = 'The bot encountered an error.' missing_param_error = 'Required parameter not provided' missing_skills_obj_error = 'Sills object not provided'
class Solution: def maxChunksToSorted(self, arr): intervals = {} for i in range(len(arr)): if i < arr[i]: minVal, maxVal = i, arr[i] else: minVal, maxVal = arr[i], i if minVal in intervals: if maxVal > intervals[ minVal ]: intervals[ minVal ] = maxVal else: intervals[ minVal ] = maxVal sortedKeys = sorted(intervals.keys()) if len(sortedKeys) == 1: return 1 else: bgnNum = sortedKeys[0] endNum = intervals[ sortedKeys[0] ] outCount = 0 for i in range(1, len(sortedKeys)): if endNum < sortedKeys[i]: endNum = intervals[ sortedKeys[i] ] outCount += 1 else: endNum = max(endNum, intervals[ sortedKeys[i] ]) outCount += 1 return outCount
class Solution: def max_chunks_to_sorted(self, arr): intervals = {} for i in range(len(arr)): if i < arr[i]: (min_val, max_val) = (i, arr[i]) else: (min_val, max_val) = (arr[i], i) if minVal in intervals: if maxVal > intervals[minVal]: intervals[minVal] = maxVal else: intervals[minVal] = maxVal sorted_keys = sorted(intervals.keys()) if len(sortedKeys) == 1: return 1 else: bgn_num = sortedKeys[0] end_num = intervals[sortedKeys[0]] out_count = 0 for i in range(1, len(sortedKeys)): if endNum < sortedKeys[i]: end_num = intervals[sortedKeys[i]] out_count += 1 else: end_num = max(endNum, intervals[sortedKeys[i]]) out_count += 1 return outCount
def bubble_sort(alist): for i in range(len(alist)-1, 0, -1): for j in range(i): if alist[j] > alist[j+1]: temp = alist[j] alist[j] = alist[j+1] alist[j+1] = temp return alist list_to_sort = [147, -16, 18, 91, 44, 1, 8, 54, 31, 18] bubble_sort(list_to_sort) print(list_to_sort)
def bubble_sort(alist): for i in range(len(alist) - 1, 0, -1): for j in range(i): if alist[j] > alist[j + 1]: temp = alist[j] alist[j] = alist[j + 1] alist[j + 1] = temp return alist list_to_sort = [147, -16, 18, 91, 44, 1, 8, 54, 31, 18] bubble_sort(list_to_sort) print(list_to_sort)
class MenuItem(): def __init__(self, itemID, itemName, itemPrice): self.itemID = itemID self.itemName = itemName self.itemPrice = itemPrice self.itemMods = list() def getItemID(self): return self.itemID def setItemID(self, itemID): self.itemID = self.itemID def getItemName(self): return self.itemName def setItemName(self, name): self.itemName = self.itemName def getItemPrice(self): return self.itemPrice def setItemPrice(self, itemPrice): self.itemPrice = itemPrice def getItemMods(self): return self.itemMods def setItemMods(self, index, val): self.itemMods[index] = val def __str__(self): return self.itemName
class Menuitem: def __init__(self, itemID, itemName, itemPrice): self.itemID = itemID self.itemName = itemName self.itemPrice = itemPrice self.itemMods = list() def get_item_id(self): return self.itemID def set_item_id(self, itemID): self.itemID = self.itemID def get_item_name(self): return self.itemName def set_item_name(self, name): self.itemName = self.itemName def get_item_price(self): return self.itemPrice def set_item_price(self, itemPrice): self.itemPrice = itemPrice def get_item_mods(self): return self.itemMods def set_item_mods(self, index, val): self.itemMods[index] = val def __str__(self): return self.itemName
def find_highest_number(numbers): highest_number = 0 for num in numbers: if num > highest_number: highest_number = num return highest_number
def find_highest_number(numbers): highest_number = 0 for num in numbers: if num > highest_number: highest_number = num return highest_number
# [17CE023] Bhishm Daslaniya ''' Algorithm! --> Build a list of tuples such that the string "aaabbc" can be squashed down to [("a", 3), ("b", 2), ("c", 1)] --> Add to answer all combinations of substrings from these tuples which would represent palindromes which have all same letters --> traverse this list to specifically find the second case mentioned in probelm ''' def substrCount(n, s): l = [] count = 0 current = None for i in range(n): if s[i] == current: count += 1 else: if current is not None: l.append((current, count)) current = s[i] count = 1 l.append((current, count)) # print(l) ans = 0 for i in l: ans += (i[1] * (i[1] + 1)) // 2 for i in range(1, len(l) - 1): if l[i - 1][0] == l[i + 1][0] and l[i][1] == 1: ans += min(l[i - 1][1], l[i + 1][1]) return ans if __name__ == '__main__': n = int(input()) s = input() result = substrCount(n,s) print(result)
""" Algorithm! --> Build a list of tuples such that the string "aaabbc" can be squashed down to [("a", 3), ("b", 2), ("c", 1)] --> Add to answer all combinations of substrings from these tuples which would represent palindromes which have all same letters --> traverse this list to specifically find the second case mentioned in probelm """ def substr_count(n, s): l = [] count = 0 current = None for i in range(n): if s[i] == current: count += 1 else: if current is not None: l.append((current, count)) current = s[i] count = 1 l.append((current, count)) ans = 0 for i in l: ans += i[1] * (i[1] + 1) // 2 for i in range(1, len(l) - 1): if l[i - 1][0] == l[i + 1][0] and l[i][1] == 1: ans += min(l[i - 1][1], l[i + 1][1]) return ans if __name__ == '__main__': n = int(input()) s = input() result = substr_count(n, s) print(result)
# Copyright 2019 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. config_type='sweetberry' revs = [5] inas = [ ('sweetberry', '0x40:3', 'pp975_io', 7.7, 0.100, 'j2', True), # R111 ('sweetberry', '0x40:1', 'pp850_prim_core', 7.7, 0.100, 'j2', True), # R164 ('sweetberry', '0x40:2', 'pp3300_dsw', 3.3, 0.010, 'j2', True), # R513 ('sweetberry', '0x40:0', 'pp3300_a', 7.7, 0.010, 'j2', True), # R144 ('sweetberry', '0x41:3', 'pp1800_a', 7.7, 0.100, 'j2', True), # R141 ('sweetberry', '0x41:1', 'pp1800_u', 7.7, 0.100, 'j2', True), # R161 ('sweetberry', '0x41:2', 'pp1200_vddq', 7.7, 0.100, 'j2', True), # R162 ('sweetberry', '0x41:0', 'pp1000_a', 7.7, 0.100, 'j2', True), # R163 ('sweetberry', '0x42:3', 'pp3300_dx_wlan', 3.3, 0.010, 'j2', True), # R645 ('sweetberry', '0x42:1', 'pp3300_dx_edp', 3.3, 0.010, 'j2', True), # F1 ('sweetberry', '0x42:2', 'vbat', 7.7, 0.010, 'j2', True), # R226 ('sweetberry', '0x42:0', 'ppvar_vcc', 1.0, 0.002, 'j4', True), # L13 ('sweetberry', '0x43:3', 'ppvar_sa', 1.0, 0.005, 'j4', True), # L12 ('sweetberry', '0x43:1', 'ppvar_gt', 1.0, 0.002, 'j4', True), # L31 ('sweetberry', '0x43:2', 'ppvar_bl', 7.7, 0.050, 'j2', True), # U89 ]
config_type = 'sweetberry' revs = [5] inas = [('sweetberry', '0x40:3', 'pp975_io', 7.7, 0.1, 'j2', True), ('sweetberry', '0x40:1', 'pp850_prim_core', 7.7, 0.1, 'j2', True), ('sweetberry', '0x40:2', 'pp3300_dsw', 3.3, 0.01, 'j2', True), ('sweetberry', '0x40:0', 'pp3300_a', 7.7, 0.01, 'j2', True), ('sweetberry', '0x41:3', 'pp1800_a', 7.7, 0.1, 'j2', True), ('sweetberry', '0x41:1', 'pp1800_u', 7.7, 0.1, 'j2', True), ('sweetberry', '0x41:2', 'pp1200_vddq', 7.7, 0.1, 'j2', True), ('sweetberry', '0x41:0', 'pp1000_a', 7.7, 0.1, 'j2', True), ('sweetberry', '0x42:3', 'pp3300_dx_wlan', 3.3, 0.01, 'j2', True), ('sweetberry', '0x42:1', 'pp3300_dx_edp', 3.3, 0.01, 'j2', True), ('sweetberry', '0x42:2', 'vbat', 7.7, 0.01, 'j2', True), ('sweetberry', '0x42:0', 'ppvar_vcc', 1.0, 0.002, 'j4', True), ('sweetberry', '0x43:3', 'ppvar_sa', 1.0, 0.005, 'j4', True), ('sweetberry', '0x43:1', 'ppvar_gt', 1.0, 0.002, 'j4', True), ('sweetberry', '0x43:2', 'ppvar_bl', 7.7, 0.05, 'j2', True)]
# fastq handling class fastqIter: " A simple file iterator that returns 4 lines for fast fastq iteration. " def __init__(self, handle): self.inf = handle def __iter__(self): return self def next(self): lines = {'id': self.inf.readline().strip(), 'seq': self.inf.readline().strip(), '+': self.inf.readline().strip(), 'qual': self.inf.readline().strip()} assert(len(lines['seq']) == len(lines['qual'])) if lines['id'] == '' or lines['seq'] == '' or lines['+'] == '' or lines['qual'] == '': raise StopIteration else: return lines @staticmethod def parse(handle): return fastqIter(handle) def close(self): self.inf.close() def writeFastq(handle, fq): handle.write(fq['id'] + '\n') handle.write(fq['seq'] + '\n') handle.write(fq['+'] + '\n') handle.write(fq['qual'] + '\n')
class Fastqiter: """ A simple file iterator that returns 4 lines for fast fastq iteration. """ def __init__(self, handle): self.inf = handle def __iter__(self): return self def next(self): lines = {'id': self.inf.readline().strip(), 'seq': self.inf.readline().strip(), '+': self.inf.readline().strip(), 'qual': self.inf.readline().strip()} assert len(lines['seq']) == len(lines['qual']) if lines['id'] == '' or lines['seq'] == '' or lines['+'] == '' or (lines['qual'] == ''): raise StopIteration else: return lines @staticmethod def parse(handle): return fastq_iter(handle) def close(self): self.inf.close() def write_fastq(handle, fq): handle.write(fq['id'] + '\n') handle.write(fq['seq'] + '\n') handle.write(fq['+'] + '\n') handle.write(fq['qual'] + '\n')
vowels = ['a' , 'o' , 'u' , 'e' , 'i' , 'A' , 'O' , 'U' , 'E' , 'I'] string = input() result = [s for s in string if s not in vowels] print(''.join(result))
vowels = ['a', 'o', 'u', 'e', 'i', 'A', 'O', 'U', 'E', 'I'] string = input() result = [s for s in string if s not in vowels] print(''.join(result))
# Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. # Every eight bits in the binary string represents one character on the ASCII table. # Examples: # csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" # 01101100 -> 108 -> "l" # 01100001 -> 97 -> "a" # 01101101 -> 109 -> "m" # 01100010 -> 98 -> "b" # 01100100 -> 100 -> "d" # 01100001 -> 97 -> "a" # csBinaryToASCII("") -> "" # Notes: # The input string will always be a valid binary string. # Characters can be in the range from "00000000" to "11111111" (inclusive). # In the case of an empty input string, your function should return an empty string. # [execution time limit] 4 seconds (py3) # [input] string binary # [output] string def csBinaryToASCII(binary): binary_letters = [] letters = "" if binary == "": return "" for index in range(0, len(binary), 8): binary_letters.append(binary[index : index + 8]) print(binary_letters) for string in binary_letters: binary_int = v = chr(int(string, 2)) print(binary_int) letters += binary_int return letters
def cs_binary_to_ascii(binary): binary_letters = [] letters = '' if binary == '': return '' for index in range(0, len(binary), 8): binary_letters.append(binary[index:index + 8]) print(binary_letters) for string in binary_letters: binary_int = v = chr(int(string, 2)) print(binary_int) letters += binary_int return letters
# 5/1/2020 # Elliott Gorman # ITSW 1359 # VINES - STACK ABSTRACT DATA TYPE class Stack(): def __init__(self): self.stack = [] #set stack size to -1 so when first object is pushed # its reference is correct at 0 self.size = -1 def push(self, object): self.stack.append(object) self.size += 1 def pop(self): if (self.isEmpty()): raise EmptyStackException('The Stack is already Empty.') else: removedElement = self.stack.pop(self.size) self.size -= 1 return removedElement def peek(self): if (not self.isEmpty()): return self.stack[self.size] def isEmpty(self): return self.size == -1 def clear(self): self.stack.clear() #set size back to -1 self.size = -1
class Stack: def __init__(self): self.stack = [] self.size = -1 def push(self, object): self.stack.append(object) self.size += 1 def pop(self): if self.isEmpty(): raise empty_stack_exception('The Stack is already Empty.') else: removed_element = self.stack.pop(self.size) self.size -= 1 return removedElement def peek(self): if not self.isEmpty(): return self.stack[self.size] def is_empty(self): return self.size == -1 def clear(self): self.stack.clear() self.size = -1
# Motor MOTOR_LEFT_FORWARD = 20 MOTOR_LEFT_BACK = 21 MOTOR_RIGHT_FORWARD = 19 MOTOR_RIGHT_BACK = 26 MOTOR_LEFT_PWM = 16 MOTOR_RIGHT_PWM = 13 # Track Sensors TRACK_LEFT_1 = 3 TRACK_LEFT_2 = 5 TRACK_RIGHT_1 = 4 TRACK_RIGHT_2 = 18 # Button BUTTON = 8 BUZZER = 8 # Servos FAN = 2 SEARCHLIGHT_SERVO = 23 CAMERA_SERVO_H = 11 CAMERA_SERVO_V = 9 # Lights LED_R = 22 LED_G = 27 LED_B = 24 # UltraSonic Sensor ULTRASONIC_ECHO = 0 ULTRASONIC_TRIGGER = 1 # Infrared Sensors INFRARED_LEFT = 12 INFRARED_RIGHT = 17 # Light Sensors LIGHT_LEFT = 7 LIGHT_RIGHT = 6
motor_left_forward = 20 motor_left_back = 21 motor_right_forward = 19 motor_right_back = 26 motor_left_pwm = 16 motor_right_pwm = 13 track_left_1 = 3 track_left_2 = 5 track_right_1 = 4 track_right_2 = 18 button = 8 buzzer = 8 fan = 2 searchlight_servo = 23 camera_servo_h = 11 camera_servo_v = 9 led_r = 22 led_g = 27 led_b = 24 ultrasonic_echo = 0 ultrasonic_trigger = 1 infrared_left = 12 infrared_right = 17 light_left = 7 light_right = 6
# Selection Sort # Time Complexity: O(n^2) # A Implementation of a Selection Sort Algorithm Through a Function. def selection_sort(nums): # This value of i corresponds to each value that will be sorted. for i in range(len(nums)): # We assume that the first item of the unsorted numbers is the smallest lowest_value_index = i # This loop iterates over the unsorted items for j in range(i + 1, len(nums)): if nums[j] < nums[lowest_value_index]: lowest_value_index = j # Swap values of the lowest unsorted element with the first unsorted element nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i] # Example 1: [12, 8, 3, 20, 11] # We Prepare a List of Values to Test Our Algorithm. random_list_of_nums = [12, 8, 3, 20, 11] selection_sort(random_list_of_nums) # Expected Result: [3,8,11,12,20] print(random_list_of_nums) # Example 2: [9,12,1,4,5,7,8] random_list_of_nums = [9, 12, 1, 4, 5, 7, 8] selection_sort(random_list_of_nums) # Expected Result: [1, 4, 5, 7, 8, 9, 12] print(random_list_of_nums)
def selection_sort(nums): for i in range(len(nums)): lowest_value_index = i for j in range(i + 1, len(nums)): if nums[j] < nums[lowest_value_index]: lowest_value_index = j (nums[i], nums[lowest_value_index]) = (nums[lowest_value_index], nums[i]) random_list_of_nums = [12, 8, 3, 20, 11] selection_sort(random_list_of_nums) print(random_list_of_nums) random_list_of_nums = [9, 12, 1, 4, 5, 7, 8] selection_sort(random_list_of_nums) print(random_list_of_nums)
# Solution to problem 7 # #Student: Niamh O'Leary# #ID: G00376339# #Date: 10/03/2019# #Write a program that takes a positive floating point number as input and outputs an approximation of its square root# #Note: for the problem please use number 14.5. num = 14.5 num_sqrt = num ** 0.5 #calulates the square root# print("The square root of %0.3f is %0.3f"%(num, num_sqrt)) #prints the original number and its square root# # For method and refernces please see accompying README file in GITHUB repository #
num = 14.5 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f' % (num, num_sqrt))
class Categories: def __init__(self, category_name, money_allocated, index_inside_list): self.category_name = category_name self.money_allocated = money_allocated self.index_inside_list = index_inside_list
class Categories: def __init__(self, category_name, money_allocated, index_inside_list): self.category_name = category_name self.money_allocated = money_allocated self.index_inside_list = index_inside_list
class Solution: def fib(self, N: int) -> int: self.seen = {} self.seen[0] = 0 self.seen[1] = 1 return self.dfs(N) def dfs(self, n): if n in self.seen: return self.seen[n] self.seen[n] = self.dfs(n - 1) + self.dfs(n - 2) return self.seen[n]
class Solution: def fib(self, N: int) -> int: self.seen = {} self.seen[0] = 0 self.seen[1] = 1 return self.dfs(N) def dfs(self, n): if n in self.seen: return self.seen[n] self.seen[n] = self.dfs(n - 1) + self.dfs(n - 2) return self.seen[n]
# Program to find whether given input string has balanced brackets or not def isBalanced(s): a=[] for i in range(len(s)): if s[i]=='{' or s[i]=='[' or s[i]=='(': a.append(s[i]) if s[i]=='}': if len(a)==0: return "NO" else: if a[-1]=='{': a.pop() else: break if s[i]==']': if len(a)==0: return "NO" else: if a[-1]=='[': a.pop() else: break if s[i]==')': if len(a)==0: return "NO" else: if a[-1]=='(': a.pop() else: break if len(a)==0: return "YES" else: return "NO" inp = input('Enter your query string: ') #sample input: {)[](}]}]}))}(())( print(isBalanced(inp))
def is_balanced(s): a = [] for i in range(len(s)): if s[i] == '{' or s[i] == '[' or s[i] == '(': a.append(s[i]) if s[i] == '}': if len(a) == 0: return 'NO' elif a[-1] == '{': a.pop() else: break if s[i] == ']': if len(a) == 0: return 'NO' elif a[-1] == '[': a.pop() else: break if s[i] == ')': if len(a) == 0: return 'NO' elif a[-1] == '(': a.pop() else: break if len(a) == 0: return 'YES' else: return 'NO' inp = input('Enter your query string: ') print(is_balanced(inp))
#Requests stress Pod resources for a given period of time to simulate load #deploymentLabel is the Deployment that the request is beings sent to #cpuCost is the number of threads that the request will use on a pod #execTime is how long the request will use those resource for before completing class Request: def __init__(self, INFOLIST): self.label = INFOLIST[0] self.deploymentLabel = INFOLIST[1] self.execTime = int(INFOLIST[2])
class Request: def __init__(self, INFOLIST): self.label = INFOLIST[0] self.deploymentLabel = INFOLIST[1] self.execTime = int(INFOLIST[2])
# Constants and functions for Marsaglia bits ingestion # constants FILE_BASE = '/media/alxfed/toca/bits.' FILE_NUMBER_MIN = 1 FILE_NUMBER_MAX = 60 # pseudo-constants FILE_EXTENSION = [str(i).zfill(2) for i in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1)] # starts with 0 element and ends with 59, that's why the dance in the function # pseudo-function def file_name(n=1): if n in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX+1): # +1 because... return FILE_BASE + FILE_EXTENSION[n-1] # -1 because... else: raise ValueError('There is no such file in Marsaglia set of bits')
file_base = '/media/alxfed/toca/bits.' file_number_min = 1 file_number_max = 60 file_extension = [str(i).zfill(2) for i in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1)] def file_name(n=1): if n in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1): return FILE_BASE + FILE_EXTENSION[n - 1] else: raise value_error('There is no such file in Marsaglia set of bits')
def organise(records): # { user: {shop -> {day -> counter}}} res = {} for person, shop, day in records: if person and shop and (0 < day < 8): if person not in res: res[person] = {} if shop not in res[person]: res[person][shop] = {} if day not in res[person][shop]: res[person][shop][day] = 0 res[person][shop][day] += 1 return res assert(organise([]) == {}) assert(organise([('Tom', '', 5), ('Tom', 'Aldi', 4)]) == {'Tom': {'Aldi': {4: 1}}}) assert(organise([('Tom', 'Aldi', 5), ('Tom', 'Aldi', 5)]) == {'Tom': {'Aldi': {5: 2}}}) assert(organise([('Tom', 'Aldi', 1), ('Tom', 'Migros', 4), ('Jack', 'Aldi', 5)]) == {'Jack': {'Aldi': {5: 1}}, 'Tom': {'Aldi': {1: 1}, 'Migros': {4: 1}}})
def organise(records): res = {} for (person, shop, day) in records: if person and shop and (0 < day < 8): if person not in res: res[person] = {} if shop not in res[person]: res[person][shop] = {} if day not in res[person][shop]: res[person][shop][day] = 0 res[person][shop][day] += 1 return res assert organise([]) == {} assert organise([('Tom', '', 5), ('Tom', 'Aldi', 4)]) == {'Tom': {'Aldi': {4: 1}}} assert organise([('Tom', 'Aldi', 5), ('Tom', 'Aldi', 5)]) == {'Tom': {'Aldi': {5: 2}}} assert organise([('Tom', 'Aldi', 1), ('Tom', 'Migros', 4), ('Jack', 'Aldi', 5)]) == {'Jack': {'Aldi': {5: 1}}, 'Tom': {'Aldi': {1: 1}, 'Migros': {4: 1}}}
''' Convenience wrappers to make using the conf system as easy and seamless as possible ''' def integrate(hub, imports, override=None, cli=None, roots=None, home_root=None, loader='json'): ''' Load the conf sub and run the integrate sequence. ''' hub.pop.sub.add('pop.mods.conf') hub.conf.integrate.load(imports, override, cli=cli, roots=roots, home_root=home_root, loader=loader)
""" Convenience wrappers to make using the conf system as easy and seamless as possible """ def integrate(hub, imports, override=None, cli=None, roots=None, home_root=None, loader='json'): """ Load the conf sub and run the integrate sequence. """ hub.pop.sub.add('pop.mods.conf') hub.conf.integrate.load(imports, override, cli=cli, roots=roots, home_root=home_root, loader=loader)
#!/usr/bin/env python # create pipeline # reader = vtk.vtkDataSetReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/RectGrid2.vtk") reader.Update() # here to force exact extent elev = vtk.vtkElevationFilter() elev.SetInputConnection(reader.GetOutputPort()) elev.Update() outline = vtk.vtkRectilinearGridOutlineFilter() outline.SetInputData(elev.GetRectilinearGridOutput()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineMapper.SetNumberOfPieces(2) outlineMapper.SetPiece(1) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(black) # Graphics stuff # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddActor(outlineActor) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) cam1 = ren1.GetActiveCamera() cam1.SetClippingRange(3.76213,10.712) cam1.SetFocalPoint(-0.0842503,-0.136905,0.610234) cam1.SetPosition(2.53813,2.2678,-5.22172) cam1.SetViewUp(-0.241047,0.930635,0.275343) iren.Initialize() # render the image # # prevent the tk window from showing up then start the event loop # --- end of script --
reader = vtk.vtkDataSetReader() reader.SetFileName('' + str(VTK_DATA_ROOT) + '/Data/RectGrid2.vtk') reader.Update() elev = vtk.vtkElevationFilter() elev.SetInputConnection(reader.GetOutputPort()) elev.Update() outline = vtk.vtkRectilinearGridOutlineFilter() outline.SetInputData(elev.GetRectilinearGridOutput()) outline_mapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineMapper.SetNumberOfPieces(2) outlineMapper.SetPiece(1) outline_actor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(black) ren1 = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.AddActor(outlineActor) ren1.SetBackground(1, 1, 1) renWin.SetSize(400, 400) cam1 = ren1.GetActiveCamera() cam1.SetClippingRange(3.76213, 10.712) cam1.SetFocalPoint(-0.0842503, -0.136905, 0.610234) cam1.SetPosition(2.53813, 2.2678, -5.22172) cam1.SetViewUp(-0.241047, 0.930635, 0.275343) iren.Initialize()
# Find the 10001st prime using the Sieve of Eratosthenes def sieve(n): sieve = [True] * (n + 1) sieve[0] = sieve[1] = False for i in range(2, (n + 1)): if sieve[i]: for j in range(i*i, (n + 1), i): sieve[j] = False return sieve prime_sieve = sieve(400000); primes = [] for idx, val in enumerate(prime_sieve): if val: primes.append(idx) print(primes[10000])
def sieve(n): sieve = [True] * (n + 1) sieve[0] = sieve[1] = False for i in range(2, n + 1): if sieve[i]: for j in range(i * i, n + 1, i): sieve[j] = False return sieve prime_sieve = sieve(400000) primes = [] for (idx, val) in enumerate(prime_sieve): if val: primes.append(idx) print(primes[10000])
class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to prit the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data), temp = temp.next def detectLoop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: print ("Found Loop") return print ("Not Found Loop") # Driver program for testing llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(10) # Create a loop for testing llist.head.next.next.next.next = llist.head llist.detectLoop()
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def push(self, new_data): new_node = node(new_data) new_node.next = self.head self.head = new_node def print_list(self): temp = self.head while temp: (print(temp.data),) temp = temp.next def detect_loop(self): slow_p = self.head fast_p = self.head while slow_p and fast_p and fast_p.next: slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: print('Found Loop') return print('Not Found Loop') llist = linked_list() llist.push(20) llist.push(4) llist.push(15) llist.push(10) llist.head.next.next.next.next = llist.head llist.detectLoop()
def bubble(alist): for first in range(len(alist)-1,0,-1): for sec in range(first): if alist[sec] > alist[sec+1]: tmp = alist[sec+1] alist[sec+1] = alist[sec] alist[sec] = tmp def test_bubble(): alist = [1,7,2,5,9,12,5] bubble(alist) assert alist[0] == 1 assert alist[1] == 2 assert alist[6] == 12 assert alist[5] == 9 def short_bubble(alist): exchange = True first = len(alist) - 1 while first > 0 and exchange: exchange = False for sec in range(first): if alist[sec] > alist[sec+1]: exchange = True tmp = alist[sec+1] alist[sec+1] = alist[sec] alist[sec] = tmp first -= 1 def test_short_bubble(): alist = [1,4,5,2,19,3,7] short_bubble(alist) assert alist[0] == 1 assert alist[1] == 2 assert alist[6] == 19 assert alist[5] == 7
def bubble(alist): for first in range(len(alist) - 1, 0, -1): for sec in range(first): if alist[sec] > alist[sec + 1]: tmp = alist[sec + 1] alist[sec + 1] = alist[sec] alist[sec] = tmp def test_bubble(): alist = [1, 7, 2, 5, 9, 12, 5] bubble(alist) assert alist[0] == 1 assert alist[1] == 2 assert alist[6] == 12 assert alist[5] == 9 def short_bubble(alist): exchange = True first = len(alist) - 1 while first > 0 and exchange: exchange = False for sec in range(first): if alist[sec] > alist[sec + 1]: exchange = True tmp = alist[sec + 1] alist[sec + 1] = alist[sec] alist[sec] = tmp first -= 1 def test_short_bubble(): alist = [1, 4, 5, 2, 19, 3, 7] short_bubble(alist) assert alist[0] == 1 assert alist[1] == 2 assert alist[6] == 19 assert alist[5] == 7
# # PySNMP MIB module TPLINK-ETHERNETOAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-ETHERNETOAM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:17:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, Gauge32, IpAddress, MibIdentifier, Integer32, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Counter64, TimeTicks, iso, Counter32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Gauge32", "IpAddress", "MibIdentifier", "Integer32", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Counter64", "TimeTicks", "iso", "Counter32", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt") tplinkEthernetOam = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 60)) tplinkEthernetOam.setRevisions(('2015-07-06 10:30',)) if mibBuilder.loadTexts: tplinkEthernetOam.setLastUpdated('201507061030Z') if mibBuilder.loadTexts: tplinkEthernetOam.setOrganization('TPLINK') tplinkEthernetOamMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1)) tplinkEthernetOamMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 2)) ethernetOamBasicConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 1)) ethernetOamLinkMonConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 2)) ethernetOamRfiConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 3)) ethernetOamRmtLbConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 4)) ethernetOamDiscoveryInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 5)) ethernetOamStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 6)) ethernetOamEventLog = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 7)) mibBuilder.exportSymbols("TPLINK-ETHERNETOAM-MIB", ethernetOamBasicConfig=ethernetOamBasicConfig, ethernetOamStatistics=ethernetOamStatistics, ethernetOamDiscoveryInfo=ethernetOamDiscoveryInfo, ethernetOamLinkMonConfig=ethernetOamLinkMonConfig, ethernetOamRfiConfig=ethernetOamRfiConfig, ethernetOamEventLog=ethernetOamEventLog, tplinkEthernetOamMIBObjects=tplinkEthernetOamMIBObjects, PYSNMP_MODULE_ID=tplinkEthernetOam, ethernetOamRmtLbConfig=ethernetOamRmtLbConfig, tplinkEthernetOamMIBNotifications=tplinkEthernetOamMIBNotifications, tplinkEthernetOam=tplinkEthernetOam)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (module_identity, gauge32, ip_address, mib_identifier, integer32, bits, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, counter64, time_ticks, iso, counter32, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'Gauge32', 'IpAddress', 'MibIdentifier', 'Integer32', 'Bits', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Counter64', 'TimeTicks', 'iso', 'Counter32', 'Unsigned32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (tplink_mgmt,) = mibBuilder.importSymbols('TPLINK-MIB', 'tplinkMgmt') tplink_ethernet_oam = module_identity((1, 3, 6, 1, 4, 1, 11863, 6, 60)) tplinkEthernetOam.setRevisions(('2015-07-06 10:30',)) if mibBuilder.loadTexts: tplinkEthernetOam.setLastUpdated('201507061030Z') if mibBuilder.loadTexts: tplinkEthernetOam.setOrganization('TPLINK') tplink_ethernet_oam_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1)) tplink_ethernet_oam_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 2)) ethernet_oam_basic_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 1)) ethernet_oam_link_mon_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 2)) ethernet_oam_rfi_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 3)) ethernet_oam_rmt_lb_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 4)) ethernet_oam_discovery_info = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 5)) ethernet_oam_statistics = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 6)) ethernet_oam_event_log = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 60, 1, 7)) mibBuilder.exportSymbols('TPLINK-ETHERNETOAM-MIB', ethernetOamBasicConfig=ethernetOamBasicConfig, ethernetOamStatistics=ethernetOamStatistics, ethernetOamDiscoveryInfo=ethernetOamDiscoveryInfo, ethernetOamLinkMonConfig=ethernetOamLinkMonConfig, ethernetOamRfiConfig=ethernetOamRfiConfig, ethernetOamEventLog=ethernetOamEventLog, tplinkEthernetOamMIBObjects=tplinkEthernetOamMIBObjects, PYSNMP_MODULE_ID=tplinkEthernetOam, ethernetOamRmtLbConfig=ethernetOamRmtLbConfig, tplinkEthernetOamMIBNotifications=tplinkEthernetOamMIBNotifications, tplinkEthernetOam=tplinkEthernetOam)
class ParticleInstanceModifier: axis = None object = None particle_system_index = None position = None random_position = None show_alive = None show_dead = None show_unborn = None use_children = None use_normal = None use_path = None use_preserve_shape = None use_size = None
class Particleinstancemodifier: axis = None object = None particle_system_index = None position = None random_position = None show_alive = None show_dead = None show_unborn = None use_children = None use_normal = None use_path = None use_preserve_shape = None use_size = None
def FlagsForFile(filename, **kwargs): return { 'flags': ['-x', 'c++', '-std=c++14', '-Wall', '-Wextra', '-Werror' ,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/include' ,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/atlmfc/include' ,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/VS/include' ,'-I','C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/ucrt' ,'-I','C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/um' ,'-I','C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/shared' ,'-I','C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/winrt' ,'-I','C:/Program Files (x86)/Windows Kits/NETFXSDK/4.6.1/Include/um'] }
def flags_for_file(filename, **kwargs): return {'flags': ['-x', 'c++', '-std=c++14', '-Wall', '-Wextra', '-Werror', '-I', 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/include', '-I', 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/atlmfc/include', '-I', 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/VS/include', '-I', 'C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/ucrt', '-I', 'C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/um', '-I', 'C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/shared', '-I', 'C:/Program Files (x86)/Windows Kits/10/Include/10.0.16299.0/winrt', '-I', 'C:/Program Files (x86)/Windows Kits/NETFXSDK/4.6.1/Include/um']}
n = int(input('Digite um valor para calcular seu fatorial: ')) f = 1 print(f'Calculando {n}! = ', end =' ') for i in range(1, n+1): print(f'{n}', end = ' ') print(' x ' if n > 1 else ' = ', end = ' ') f *= i n -= 1 print(f)
n = int(input('Digite um valor para calcular seu fatorial: ')) f = 1 print(f'Calculando {n}! = ', end=' ') for i in range(1, n + 1): print(f'{n}', end=' ') print(' x ' if n > 1 else ' = ', end=' ') f *= i n -= 1 print(f)