content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" About this package """ __version__ = '0.1.0' __description__ = 'Python3 client code for ec_golanggrpc' __author__ = 'Paul Hewlett' __author_email__ = 'phewlett76@gmail.com' __license__ = 'MIT'
""" About this package """ __version__ = '0.1.0' __description__ = 'Python3 client code for ec_golanggrpc' __author__ = 'Paul Hewlett' __author_email__ = 'phewlett76@gmail.com' __license__ = 'MIT'
class CrawlerCodeDTO(object): """ Object that contains grouped all data of the code """ def __init__(self, id, libs, comments, variable_names, function_names, class_name, lines_number, code): self.id = id self.libs = libs if len(libs) > 0 else [] self.comments = comments if len(comments) > 0 else [] self.variable_names = variable_names if len(variable_names) > 0 else [] self.function_names = function_names if len(function_names) > 0 else [] self.class_name = class_name if len(class_name) > 0 else [] self.lines_number = lines_number if lines_number else 1 self.score = 0.0 self.code = code
class Crawlercodedto(object): """ Object that contains grouped all data of the code """ def __init__(self, id, libs, comments, variable_names, function_names, class_name, lines_number, code): self.id = id self.libs = libs if len(libs) > 0 else [] self.comments = comments if len(comments) > 0 else [] self.variable_names = variable_names if len(variable_names) > 0 else [] self.function_names = function_names if len(function_names) > 0 else [] self.class_name = class_name if len(class_name) > 0 else [] self.lines_number = lines_number if lines_number else 1 self.score = 0.0 self.code = code
def cls_with_meta(mc, attrs): class _x_(object): __metaclass__ = mc for k, v in attrs.items(): setattr(_x_, k, v) return _x_
def cls_with_meta(mc, attrs): class _X_(object): __metaclass__ = mc for (k, v) in attrs.items(): setattr(_x_, k, v) return _x_
num = int(input('Digite um valor para saber seu fatorial: ')) d = num for c in range(num-1,1,-1): num += (num * c) - num print('Calculando {}! = {}.'.format(d, num))
num = int(input('Digite um valor para saber seu fatorial: ')) d = num for c in range(num - 1, 1, -1): num += num * c - num print('Calculando {}! = {}.'.format(d, num))
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: head = ListNode(0, head) p1, prev, p2 = head, head, head.next while p2: if p2.val < x: if p1 == prev: prev, p2 = p2, p2.next else: p1.next, p2.next, p2, prev.next = p2, p1.next, p2.next, p2.next p1 = p1.next else: prev, p2 = p2, p2.next return head.next
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: head = list_node(0, head) (p1, prev, p2) = (head, head, head.next) while p2: if p2.val < x: if p1 == prev: (prev, p2) = (p2, p2.next) else: (p1.next, p2.next, p2, prev.next) = (p2, p1.next, p2.next, p2.next) p1 = p1.next else: (prev, p2) = (p2, p2.next) return head.next
# # PySNMP MIB module BLUECOAT-HOST-RESOURCES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-HOST-RESOURCES-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:39:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") blueCoatMgmt, = mibBuilder.importSymbols("BLUECOAT-MIB", "blueCoatMgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, Bits, Counter64, TimeTicks, IpAddress, Unsigned32, MibIdentifier, Counter32, ObjectIdentity, ModuleIdentity, Integer32, NotificationType, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Bits", "Counter64", "TimeTicks", "IpAddress", "Unsigned32", "MibIdentifier", "Counter32", "ObjectIdentity", "ModuleIdentity", "Integer32", "NotificationType", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") blueCoatHostResourcesMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 3417, 2, 9)) blueCoatHostResourcesMIB.setRevisions(('2007-04-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setRevisionsDescriptions(('Marked as deprecated.',)) if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setLastUpdated('200704240000Z') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setOrganization('Blue Coat') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setContactInfo('support@bluecoat.com') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setDescription('Internal MIB defines Blue Coat device serial number for Blue Coat Director use.') bchrDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1)) bchrSerial = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: bchrSerial.setStatus('deprecated') if mibBuilder.loadTexts: bchrSerial.setDescription('Serial number of the Blue Coat device.') mibBuilder.exportSymbols("BLUECOAT-HOST-RESOURCES-MIB", bchrDevice=bchrDevice, blueCoatHostResourcesMIB=blueCoatHostResourcesMIB, bchrSerial=bchrSerial, PYSNMP_MODULE_ID=blueCoatHostResourcesMIB)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint') (blue_coat_mgmt,) = mibBuilder.importSymbols('BLUECOAT-MIB', 'blueCoatMgmt') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (iso, bits, counter64, time_ticks, ip_address, unsigned32, mib_identifier, counter32, object_identity, module_identity, integer32, notification_type, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Bits', 'Counter64', 'TimeTicks', 'IpAddress', 'Unsigned32', 'MibIdentifier', 'Counter32', 'ObjectIdentity', 'ModuleIdentity', 'Integer32', 'NotificationType', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') blue_coat_host_resources_mib = module_identity((1, 3, 6, 1, 4, 1, 3417, 2, 9)) blueCoatHostResourcesMIB.setRevisions(('2007-04-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setRevisionsDescriptions(('Marked as deprecated.',)) if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setLastUpdated('200704240000Z') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setOrganization('Blue Coat') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setContactInfo('support@bluecoat.com') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setDescription('Internal MIB defines Blue Coat device serial number for Blue Coat Director use.') bchr_device = mib_identifier((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1)) bchr_serial = mib_scalar((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1, 1), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly') if mibBuilder.loadTexts: bchrSerial.setStatus('deprecated') if mibBuilder.loadTexts: bchrSerial.setDescription('Serial number of the Blue Coat device.') mibBuilder.exportSymbols('BLUECOAT-HOST-RESOURCES-MIB', bchrDevice=bchrDevice, blueCoatHostResourcesMIB=blueCoatHostResourcesMIB, bchrSerial=bchrSerial, PYSNMP_MODULE_ID=blueCoatHostResourcesMIB)
t = {} t["0"] = ["-113", "Marginal"] t["1"] = ["-111", "Marginal"] t["2"] = ["-109", "Marginal"] t["3"] = ["-107", "Marginal"] t["4"] = ["-105", "Marginal"] t["5"] = ["-103", "Marginal"] t["6"] = ["-101", "Marginal"] t["7"] = ["-99", "Marginal"] t["8"] = ["-97", "Marginal"] t["9"] = ["-95", "Marginal"] t["10"] = ["-93", "OK"] t["11"] = ["-91", "OK"] t["12"] = ["-89", "OK"] t["13"] = ["-87", "OK"] t["14"] = ["-85", "OK"] t["15"] = ["-83", "Good"] t["16"] = ["-81", "Good"] t["17"] = ["-79", "Good"] t["18"] = ["-77", "Good"] t["19"] = ["-75", "Good"] t["20"] = ["-73", "Excellent"] t["21"] = ["-71", "Excellent"] t["22"] = ["-69", "Excellent"] t["23"] = ["-67", "Excellent"] t["24"] = ["-65", "Excellent"] t["25"] = ["-63", "Excellent"] t["26"] = ["-61", "Excellent"] t["27"] = ["-59", "Excellent"] t["28"] = ["-57", "Excellent"] t["29"] = ["-55", "Excellent"] t["30"] = ["-53", "Excellent"] t["99"] = ["-53", "Excellent"]
t = {} t['0'] = ['-113', 'Marginal'] t['1'] = ['-111', 'Marginal'] t['2'] = ['-109', 'Marginal'] t['3'] = ['-107', 'Marginal'] t['4'] = ['-105', 'Marginal'] t['5'] = ['-103', 'Marginal'] t['6'] = ['-101', 'Marginal'] t['7'] = ['-99', 'Marginal'] t['8'] = ['-97', 'Marginal'] t['9'] = ['-95', 'Marginal'] t['10'] = ['-93', 'OK'] t['11'] = ['-91', 'OK'] t['12'] = ['-89', 'OK'] t['13'] = ['-87', 'OK'] t['14'] = ['-85', 'OK'] t['15'] = ['-83', 'Good'] t['16'] = ['-81', 'Good'] t['17'] = ['-79', 'Good'] t['18'] = ['-77', 'Good'] t['19'] = ['-75', 'Good'] t['20'] = ['-73', 'Excellent'] t['21'] = ['-71', 'Excellent'] t['22'] = ['-69', 'Excellent'] t['23'] = ['-67', 'Excellent'] t['24'] = ['-65', 'Excellent'] t['25'] = ['-63', 'Excellent'] t['26'] = ['-61', 'Excellent'] t['27'] = ['-59', 'Excellent'] t['28'] = ['-57', 'Excellent'] t['29'] = ['-55', 'Excellent'] t['30'] = ['-53', 'Excellent'] t['99'] = ['-53', 'Excellent']
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =========================================================================== """Precision calculation function of Ubuntu data""" def get_p_at_n_in_m(data, n, m, ind): """Former n recall rate""" pos_score = data[ind][0] curr = data[ind:ind + m] curr = sorted(curr, key=lambda x: x[0], reverse=True) if curr[n - 1][0] <= pos_score: return 1 return 0 def evaluate(file_path): """ Evaluation is done through a score file. :param file_path: Score file path. :return: A tuple of accuracy """ data = [] with open(file_path, 'r') as file: for line in file: line = line.strip() tokens = line.split("\t") if len(tokens) != 2: continue data.append((float(tokens[0]), int(tokens[1]))) # assert len(data) % 10 == 0 p_at_1_in_2 = 0.0 p_at_1_in_10 = 0.0 p_at_2_in_10 = 0.0 p_at_5_in_10 = 0.0 length = int(len(data) / 10) for i in range(0, length): ind = i * 10 assert data[ind][1] == 1 p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind) p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind) p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind) p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind) return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length) def evaluate_m(logits, labels): """ Evaluate through network output. :param logits: Network score. :param labels: Actual label :return: A tuple of accuracy """ data = [] for i in range(len(logits)): data.append((float(logits[i]), int(labels[i]))) # assert len(data) % 10 == 0 p_at_1_in_2 = 0.0 p_at_1_in_10 = 0.0 p_at_2_in_10 = 0.0 p_at_5_in_10 = 0.0 length = int(len(data) / 10) for i in range(0, length): ind = i * 10 assert data[ind][1] == 1 p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind) p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind) p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind) p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind) return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length)
"""Precision calculation function of Ubuntu data""" def get_p_at_n_in_m(data, n, m, ind): """Former n recall rate""" pos_score = data[ind][0] curr = data[ind:ind + m] curr = sorted(curr, key=lambda x: x[0], reverse=True) if curr[n - 1][0] <= pos_score: return 1 return 0 def evaluate(file_path): """ Evaluation is done through a score file. :param file_path: Score file path. :return: A tuple of accuracy """ data = [] with open(file_path, 'r') as file: for line in file: line = line.strip() tokens = line.split('\t') if len(tokens) != 2: continue data.append((float(tokens[0]), int(tokens[1]))) p_at_1_in_2 = 0.0 p_at_1_in_10 = 0.0 p_at_2_in_10 = 0.0 p_at_5_in_10 = 0.0 length = int(len(data) / 10) for i in range(0, length): ind = i * 10 assert data[ind][1] == 1 p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind) p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind) p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind) p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind) return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length) def evaluate_m(logits, labels): """ Evaluate through network output. :param logits: Network score. :param labels: Actual label :return: A tuple of accuracy """ data = [] for i in range(len(logits)): data.append((float(logits[i]), int(labels[i]))) p_at_1_in_2 = 0.0 p_at_1_in_10 = 0.0 p_at_2_in_10 = 0.0 p_at_5_in_10 = 0.0 length = int(len(data) / 10) for i in range(0, length): ind = i * 10 assert data[ind][1] == 1 p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind) p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind) p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind) p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind) return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length)
class Solution: def longestWPI(self, hours: List[int]) -> int: acc = 0 seen = {0 : -1} mx_len = 0 for i, h in enumerate(hours): if h > 8: acc += 1 else: acc -= 1 if acc > 0: mx_len = i + 1 if acc not in seen: seen[acc] = i if (acc - 1) in seen: mx_len = max(mx_len, i - seen[acc - 1]) return mx_len
class Solution: def longest_wpi(self, hours: List[int]) -> int: acc = 0 seen = {0: -1} mx_len = 0 for (i, h) in enumerate(hours): if h > 8: acc += 1 else: acc -= 1 if acc > 0: mx_len = i + 1 if acc not in seen: seen[acc] = i if acc - 1 in seen: mx_len = max(mx_len, i - seen[acc - 1]) return mx_len
#log in process def login(): Username = input("Enter Username : ") if Username == 'betterllama' or NewUsername: Password = input("Enter Password : ") else: print("Username Incorrect") if Password == 'omoshi' or NewPassword: print("Welcome, " + Username) else: print("Password is incorrect") #sign up + log in process def signup(NewUsername = 'default', NewPassword = 'default'): NewUsername = input("Choose a Username : ") NewPassword = input("Choose a Password : ") print("Would you like to log in now?") x = input("Type 'yes' or 'no' : ") if x == 'yes': Username = input("Enter Username : ") if Username == 'betterllama' or NewUsername: Password = input("Enter Password : ") else: print("Username Incorrect") if Password == 'omoshi' or NewPassword: print("Welcome, " + Username) else: print("Password is incorrect") else: print("done") #start sequence def start(): print("Would you like to Login or Sign Up? ") x = input("Type 'login' or 'signup' : ") if x == 'login': login() else: signup() start()
def login(): username = input('Enter Username : ') if Username == 'betterllama' or NewUsername: password = input('Enter Password : ') else: print('Username Incorrect') if Password == 'omoshi' or NewPassword: print('Welcome, ' + Username) else: print('Password is incorrect') def signup(NewUsername='default', NewPassword='default'): new_username = input('Choose a Username : ') new_password = input('Choose a Password : ') print('Would you like to log in now?') x = input("Type 'yes' or 'no' : ") if x == 'yes': username = input('Enter Username : ') if Username == 'betterllama' or NewUsername: password = input('Enter Password : ') else: print('Username Incorrect') if Password == 'omoshi' or NewPassword: print('Welcome, ' + Username) else: print('Password is incorrect') else: print('done') def start(): print('Would you like to Login or Sign Up? ') x = input("Type 'login' or 'signup' : ") if x == 'login': login() else: signup() start()
# -*- coding: utf8 -*- def js_test(): pass
def js_test(): pass
#!/usr/bin/env python # ----------------------------------------------------------------------------- # This example will open a file and read it line by line, process each line, # and write the processed line to standard out. # ----------------------------------------------------------------------------- # Open a file for writing. Use 'a' instead of 'w' to append to the file. outfile = open('jenny.txt', 'w') # Create some data to write to a file. Need some numbers, text and a list num = 867 num2 = 5309 txt = 'Jenny' txt2 = 'Tommy Tutone' list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls'] # The 2.x version of Python formats strings using the method below. The 3.x # version of python uses .format(). The method below will be phased out of # python eventually but I use it here because it is compatible with Python # 2.x, which is the default version of python in Ubuntu and BT5. # # UPDATE: The .format() string formatting method is supported in Python 2.6 # and higher. outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2)) outfile.write('and was covered by:\n') for l in list: outfile.write('%s\n' % (l)) # Close the file because we are done with it. outfile.close()
outfile = open('jenny.txt', 'w') num = 867 num2 = 5309 txt = 'Jenny' txt2 = 'Tommy Tutone' list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls'] outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2)) outfile.write('and was covered by:\n') for l in list: outfile.write('%s\n' % l) outfile.close()
""" 107. Word Break https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160 DFS on dictionary """ class Solution: """ @param: s: A string @param: dict: A dictionary of words dict @return: A boolean """ def wordBreak(self, s, dict): return self.dfs(s, dict, 0) def dfs(self, s, word_lists, index): if index == len(s): return True if index > len(s): return False for word in word_lists: if s[index:].startswith(word): if self.dfs(s, word_lists, index + len(word)): return True return False
""" 107. Word Break https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160 DFS on dictionary """ class Solution: """ @param: s: A string @param: dict: A dictionary of words dict @return: A boolean """ def word_break(self, s, dict): return self.dfs(s, dict, 0) def dfs(self, s, word_lists, index): if index == len(s): return True if index > len(s): return False for word in word_lists: if s[index:].startswith(word): if self.dfs(s, word_lists, index + len(word)): return True return False
# A binary search template """ left, right = 0, len(array) - 1 while left <= right: mid = left + (right - left) // 2 if array[mid] == target: break or return result elif array[mid] < target: left = mid + 1 else: right = mid - 1 """
""" left, right = 0, len(array) - 1 while left <= right: mid = left + (right - left) // 2 if array[mid] == target: break or return result elif array[mid] < target: left = mid + 1 else: right = mid - 1 """
class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 if x < -(2 ** 31) or x > (2 ** 31) - 1: return 0 newNumber = 0 tempNumber = abs(x) while tempNumber > 0: newNumber = (newNumber * 10) + tempNumber % 10 tempNumber = tempNumber // 10 if newNumber < -(2 ** 31) or newNumber > (2 ** 31) - 1: return 0 if x < 0: return -1 * newNumber else: return newNumber
class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 if x < -2 ** 31 or x > 2 ** 31 - 1: return 0 new_number = 0 temp_number = abs(x) while tempNumber > 0: new_number = newNumber * 10 + tempNumber % 10 temp_number = tempNumber // 10 if newNumber < -2 ** 31 or newNumber > 2 ** 31 - 1: return 0 if x < 0: return -1 * newNumber else: return newNumber
good = 0 good_2 = 0 with open("day2.txt") as f: for line in f.readlines(): parts = line.strip().split() print(parts) cmin, cmax = [int(i) for i in parts[0].split('-')] letter = parts[1][0] pwd = parts[2] print(cmin, cmax, letter, pwd) count = pwd.count(letter) if count >= cmin and count <= cmax: good += 1 if (pwd[cmin - 1] == letter or pwd[cmax - 1] == letter) and not (pwd[cmin - 1] == letter and pwd[cmax - 1] == letter): good_2 += 1 print(good, good_2)
good = 0 good_2 = 0 with open('day2.txt') as f: for line in f.readlines(): parts = line.strip().split() print(parts) (cmin, cmax) = [int(i) for i in parts[0].split('-')] letter = parts[1][0] pwd = parts[2] print(cmin, cmax, letter, pwd) count = pwd.count(letter) if count >= cmin and count <= cmax: good += 1 if (pwd[cmin - 1] == letter or pwd[cmax - 1] == letter) and (not (pwd[cmin - 1] == letter and pwd[cmax - 1] == letter)): good_2 += 1 print(good, good_2)
description = 'PUMA multianalyzer device' group = 'lowlevel' includes = ['aliases'] level = False devices = dict( man = device('nicos_mlz.puma.devices.PumaMultiAnalyzer', description = 'PUMA multi analyzer', translations = ['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8', 'ta9', 'ta10', 'ta11'], rotations = ['ra1', 'ra2', 'ra3', 'ra4', 'ra5', 'ra6', 'ra7', 'ra8', 'ra9', 'ra10', 'ra11'], ), muslit_t = device('nicos.devices.generic.Axis', description = 'translation multianalyzer slit', motor = device('nicos.devices.generic.virtual.VirtualMotor', abslimits = (471, 565), unit = 'mm', ), precision = 1, fmtstr = '%.2f', ), ) for i in range(1, 12): devices['ta%d' % i] = device('nicos.devices.generic.Axis', description = 'Translation crystal %d multianalyzer' % i, motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits = (-125.1, 125.1), userlimits = (-125, 125), unit = 'mm', refpos = 0., fmtstr = '%.3f', speed = 5.0, ), precision = 0.01, lowlevel = level, ) devices['ra%d' % i] = device('nicos.devices.generic.Axis', description = 'Rotation crystal %d multianalyzer' % i, motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits = (-60.1, 0.5), userlimits = (-60.05, 0.5), unit = 'deg', refpos = 0.1, fmtstr = '%.3f', speed = 1.0, ), precision = 0.01, lowlevel = level, ) alias_config = { 'theta': {'ra6': 200}, }
description = 'PUMA multianalyzer device' group = 'lowlevel' includes = ['aliases'] level = False devices = dict(man=device('nicos_mlz.puma.devices.PumaMultiAnalyzer', description='PUMA multi analyzer', translations=['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8', 'ta9', 'ta10', 'ta11'], rotations=['ra1', 'ra2', 'ra3', 'ra4', 'ra5', 'ra6', 'ra7', 'ra8', 'ra9', 'ra10', 'ra11']), muslit_t=device('nicos.devices.generic.Axis', description='translation multianalyzer slit', motor=device('nicos.devices.generic.virtual.VirtualMotor', abslimits=(471, 565), unit='mm'), precision=1, fmtstr='%.2f')) for i in range(1, 12): devices['ta%d' % i] = device('nicos.devices.generic.Axis', description='Translation crystal %d multianalyzer' % i, motor=device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits=(-125.1, 125.1), userlimits=(-125, 125), unit='mm', refpos=0.0, fmtstr='%.3f', speed=5.0), precision=0.01, lowlevel=level) devices['ra%d' % i] = device('nicos.devices.generic.Axis', description='Rotation crystal %d multianalyzer' % i, motor=device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits=(-60.1, 0.5), userlimits=(-60.05, 0.5), unit='deg', refpos=0.1, fmtstr='%.3f', speed=1.0), precision=0.01, lowlevel=level) alias_config = {'theta': {'ra6': 200}}
class Solution: def longestPalindrome(self, s: str) -> str: if not s: return None result = '' maxPal = 0 record = [[0] * len(s) for i in range(len(s))] for j in range(len(s)): for i in range(j+1): record[i][j] = ((s[i] == s[j]) and (j-i<=2 or record[i+1][j-1])) if record[i][j] and j-i+1 > maxPal: maxPal = j-i+1 result = s[i:j+1] return result
class Solution: def longest_palindrome(self, s: str) -> str: if not s: return None result = '' max_pal = 0 record = [[0] * len(s) for i in range(len(s))] for j in range(len(s)): for i in range(j + 1): record[i][j] = s[i] == s[j] and (j - i <= 2 or record[i + 1][j - 1]) if record[i][j] and j - i + 1 > maxPal: max_pal = j - i + 1 result = s[i:j + 1] return result
""" entrada nombre-->str-->n horas_trabajadas-->int-->ht precio_hora_normal-->int-->phn horas _extras-->int-->hx #hijos-->int-->hi salidas asignaciones-->str-->asi deducciones-->str-->dd sueldo_neto-->str-->sn """ n=str(input("escriba el nombre del trabador ")) ht=int(input("digite la cantidad de horas trabajadas ")) phn=int(input("digite el precio de la hora normal de trabajo ")) hx = int(input("digite la cantidad de horas extra trabajadas ")) hi=int(input("digite cuantos hijos tiene ")) if (hi==0): ch=0 else: ch=173000 ac=250000 ph=180000 asi=ac+ph+(ch*hi) vhx = ht*0.25 hxt = vhx+ht sb = (ht*phn)+hxt+asi td = ((sb*0.05)+(sb*0.02)+(sb*0.07)) sn = sb-td print(str(n), "tiene un total de " + str(asi), " en asignaciones") print(str(n), "tiene un total de " + str(td), " en deducciones") print(str(n), "tiene un sueldo neto de " + str(sn))
""" entrada nombre-->str-->n horas_trabajadas-->int-->ht precio_hora_normal-->int-->phn horas _extras-->int-->hx #hijos-->int-->hi salidas asignaciones-->str-->asi deducciones-->str-->dd sueldo_neto-->str-->sn """ n = str(input('escriba el nombre del trabador ')) ht = int(input('digite la cantidad de horas trabajadas ')) phn = int(input('digite el precio de la hora normal de trabajo ')) hx = int(input('digite la cantidad de horas extra trabajadas ')) hi = int(input('digite cuantos hijos tiene ')) if hi == 0: ch = 0 else: ch = 173000 ac = 250000 ph = 180000 asi = ac + ph + ch * hi vhx = ht * 0.25 hxt = vhx + ht sb = ht * phn + hxt + asi td = sb * 0.05 + sb * 0.02 + sb * 0.07 sn = sb - td print(str(n), 'tiene un total de ' + str(asi), ' en asignaciones') print(str(n), 'tiene un total de ' + str(td), ' en deducciones') print(str(n), 'tiene un sueldo neto de ' + str(sn))
__author__ = 'Liu' def quadrado_menores(n): return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n] assert [1] == quadrado_menores(1) assert [1, 4] == quadrado_menores(4) assert [1, 4, 9] == quadrado_menores(9) assert [1, 4, 9] == quadrado_menores(11) def soma_quadrados(n): if n > 0: menores = quadrado_menores(n) ultimo = menores[-1] if ultimo == n: return [n] else: lista_escolhida = gerar_solucao(menores, n) while menores: lista_escolhida_2 = gerar_solucao(menores, n) if len(lista_escolhida_2) < len(lista_escolhida): lista_escolhida = lista_escolhida_2 return lista_escolhida return[0] def gerar_solucao(menores, n): ultimo = menores.pop() lista_escolhida = [ultimo] lista_escolhida.extend(soma_quadrados(n - ultimo)) return lista_escolhida assert [0] == soma_quadrados(0) assert [1] == soma_quadrados(1) assert [4] == soma_quadrados(4) assert [9] == soma_quadrados(9) assert [1,1] == soma_quadrados(2) assert [1,1,1] == soma_quadrados(3) assert [4,1] == soma_quadrados(5) assert [4,4,4] == soma_quadrados(12) assert [9, 4] == soma_quadrados(13) assert [9, 4, 1] == soma_quadrados(14) numero = int (input("Adiciona o numero desejada: ")) print(soma_quadrados(numero))
__author__ = 'Liu' def quadrado_menores(n): return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n] assert [1] == quadrado_menores(1) assert [1, 4] == quadrado_menores(4) assert [1, 4, 9] == quadrado_menores(9) assert [1, 4, 9] == quadrado_menores(11) def soma_quadrados(n): if n > 0: menores = quadrado_menores(n) ultimo = menores[-1] if ultimo == n: return [n] else: lista_escolhida = gerar_solucao(menores, n) while menores: lista_escolhida_2 = gerar_solucao(menores, n) if len(lista_escolhida_2) < len(lista_escolhida): lista_escolhida = lista_escolhida_2 return lista_escolhida return [0] def gerar_solucao(menores, n): ultimo = menores.pop() lista_escolhida = [ultimo] lista_escolhida.extend(soma_quadrados(n - ultimo)) return lista_escolhida assert [0] == soma_quadrados(0) assert [1] == soma_quadrados(1) assert [4] == soma_quadrados(4) assert [9] == soma_quadrados(9) assert [1, 1] == soma_quadrados(2) assert [1, 1, 1] == soma_quadrados(3) assert [4, 1] == soma_quadrados(5) assert [4, 4, 4] == soma_quadrados(12) assert [9, 4] == soma_quadrados(13) assert [9, 4, 1] == soma_quadrados(14) numero = int(input('Adiciona o numero desejada: ')) print(soma_quadrados(numero))
try: pass except ImportError: pass if False: pass class GraphQLSchema(object): """Schema Definition A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor. Example: MyAppSchema = GraphQLSchema( query=MyAppQueryRootType, mutation=MyAppMutationRootType, ) Note: If an array of `directives` are provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If `directives` is not provided then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide *additional* directives to these specified directives, you must explicitly declare them. Example: MyAppSchema = GraphQLSchema( ... directives=specified_directives.extend([MyCustomerDirective]), ) """ __slots__ = ("_query", "_mutation", "_subscription", "_type_map", "_directives", "_implementations", "_possible_type_map") def __init__(self, query, mutation=None, subscription=None, directives=None, types=None): assert isinstance(query, GraphQLObjectType), "Schema query must be Object Type but got: {}.".format(query) if mutation: assert isinstance(mutation, GraphQLObjectType), "Schema mutation must be Object Type but got: {}.".format(mutation) if subscription: assert isinstance(subscription, GraphQLObjectType), "Schema subscription must be Object Type but got: {}.".format(subscription) if types: assert isinstance(types, Iterable), "Schema types must be iterable if provided but got: {}.".format(types) self._query = query self._mutation = mutation self._subscription = subscription if directives is None: directives = specified_directives assert all(isinstance(d, GraphQLDirective) for d in directives), "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(directives) self._directives = directives initial_types = list(filter(None, [query, mutation, subscription, IntrospectionSchema])) if types: initial_types += types self._type_map = GraphQLTypeMap(initial_types) def get_query_type(self): return self._query def get_mutation_type(self): return self._mutation def get_subscription_type(self): return self._subscription def get_type_map(self): return self._type_map def get_type(self, name): return self._type_map.get(name) def get_directives(self): return self._directives def get_directive(self, name): for directive in self.get_directives(): if directive.name == name: return directive return None def get_possible_types(self, abstract_type): return self._type_map.get_possible_types(abstract_type) def is_possible_type(self, abstract_type, possible_type): return self._type_map.is_possible_type(abstract_type, possible_type)
try: pass except ImportError: pass if False: pass class Graphqlschema(object): """Schema Definition A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor. Example: MyAppSchema = GraphQLSchema( query=MyAppQueryRootType, mutation=MyAppMutationRootType, ) Note: If an array of `directives` are provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If `directives` is not provided then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide *additional* directives to these specified directives, you must explicitly declare them. Example: MyAppSchema = GraphQLSchema( ... directives=specified_directives.extend([MyCustomerDirective]), ) """ __slots__ = ('_query', '_mutation', '_subscription', '_type_map', '_directives', '_implementations', '_possible_type_map') def __init__(self, query, mutation=None, subscription=None, directives=None, types=None): assert isinstance(query, GraphQLObjectType), 'Schema query must be Object Type but got: {}.'.format(query) if mutation: assert isinstance(mutation, GraphQLObjectType), 'Schema mutation must be Object Type but got: {}.'.format(mutation) if subscription: assert isinstance(subscription, GraphQLObjectType), 'Schema subscription must be Object Type but got: {}.'.format(subscription) if types: assert isinstance(types, Iterable), 'Schema types must be iterable if provided but got: {}.'.format(types) self._query = query self._mutation = mutation self._subscription = subscription if directives is None: directives = specified_directives assert all((isinstance(d, GraphQLDirective) for d in directives)), 'Schema directives must be List[GraphQLDirective] if provided but got: {}.'.format(directives) self._directives = directives initial_types = list(filter(None, [query, mutation, subscription, IntrospectionSchema])) if types: initial_types += types self._type_map = graph_ql_type_map(initial_types) def get_query_type(self): return self._query def get_mutation_type(self): return self._mutation def get_subscription_type(self): return self._subscription def get_type_map(self): return self._type_map def get_type(self, name): return self._type_map.get(name) def get_directives(self): return self._directives def get_directive(self, name): for directive in self.get_directives(): if directive.name == name: return directive return None def get_possible_types(self, abstract_type): return self._type_map.get_possible_types(abstract_type) def is_possible_type(self, abstract_type, possible_type): return self._type_map.is_possible_type(abstract_type, possible_type)
a = 1 if a == 1: print("ok") else: print("no") py_builtins = 1 if py_builtins == 1: print("ok") else: print("no") for py_builtins in range(5): a += py_builtins print(a)
a = 1 if a == 1: print('ok') else: print('no') py_builtins = 1 if py_builtins == 1: print('ok') else: print('no') for py_builtins in range(5): a += py_builtins print(a)
""" html head """ def get_head(content): """ xxx """ return_data = '<head>'+ content +'</head>' return return_data
""" html head """ def get_head(content): """ xxx """ return_data = '<head>' + content + '</head>' return return_data
"""Exceptions for ReSpecTh Parser. .. moduleauthor:: Kyle Niemeyer <kyle.niemeyer@gmail.com> """ class ParseError(Exception): """Base class for errors.""" pass class KeywordError(ParseError): """Raised for errors in keyword parsing.""" def __init__(self, *keywords): self.keywords = keywords def __str__(self): return repr('Error: {}.'.format(self.keywords)) class UndefinedElementError(KeywordError): """Raised for undefined elements.""" def __str__(self): return repr('Error: Element not defined.\n{}'.format(self.keywords)) class MissingElementError(KeywordError): """Raised for missing required elements.""" def __str__(self): return repr('Error: Required element {} is missing.'.format( self.keywords)) class MissingAttributeError(KeywordError): """Raised for missing required attribute.""" def __str__(self): return repr('Error: Required attribute {} of {} is missing.'.format( self.keywords)) class UndefinedKeywordError(KeywordError): """Raised for undefined keywords.""" def __str__(self): return repr('Error: Keyword not defined: {}'.format(self.keywords))
"""Exceptions for ReSpecTh Parser. .. moduleauthor:: Kyle Niemeyer <kyle.niemeyer@gmail.com> """ class Parseerror(Exception): """Base class for errors.""" pass class Keyworderror(ParseError): """Raised for errors in keyword parsing.""" def __init__(self, *keywords): self.keywords = keywords def __str__(self): return repr('Error: {}.'.format(self.keywords)) class Undefinedelementerror(KeywordError): """Raised for undefined elements.""" def __str__(self): return repr('Error: Element not defined.\n{}'.format(self.keywords)) class Missingelementerror(KeywordError): """Raised for missing required elements.""" def __str__(self): return repr('Error: Required element {} is missing.'.format(self.keywords)) class Missingattributeerror(KeywordError): """Raised for missing required attribute.""" def __str__(self): return repr('Error: Required attribute {} of {} is missing.'.format(self.keywords)) class Undefinedkeyworderror(KeywordError): """Raised for undefined keywords.""" def __str__(self): return repr('Error: Keyword not defined: {}'.format(self.keywords))
""" digit factorial chains """ factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] def next_number(n): factorial_sum = 0 while n != 0: factorial_sum += factorial[n % 10] n //= 10 return factorial_sum def chain_len(n): chain = [] while not chain.__contains__(n): chain.append(n) n = next_number(n) return len(chain) if __name__ == '__main__': result = 0 for i in range(1000000): if chain_len(i) == 60: result += 1 print(result)
""" digit factorial chains """ factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] def next_number(n): factorial_sum = 0 while n != 0: factorial_sum += factorial[n % 10] n //= 10 return factorial_sum def chain_len(n): chain = [] while not chain.__contains__(n): chain.append(n) n = next_number(n) return len(chain) if __name__ == '__main__': result = 0 for i in range(1000000): if chain_len(i) == 60: result += 1 print(result)
flag = [""] * 36 flag[0] = chr(0x46) flag[1] = chr(0x4c) flag[2] = chr(0x41) flag[3] = chr(0x47) flag[4] = chr(0x7b) flag[5] = chr(0x35) flag[6] = chr(0x69) flag[7] = chr(0x6d) flag[8] = chr(0x70) flag[9] = chr(0x31) flag[10] = chr(0x65) flag[11] = chr(0x5f) flag[12] = chr(0x52) flag[13] = chr(0x65) flag[14] = chr(0x76) flag[15] = chr(0x65) flag[16] = chr(0x72) flag[17] = chr(0x73) flag[18] = chr(0x31) flag[19] = chr(0x6e) flag[20] = chr(0x67) flag[21] = chr(0x5f) flag[22] = chr(0x34) flag[23] = chr(0x72) flag[24] = chr(0x72) flag[25] = chr(0x61) flag[26] = chr(0x79) flag[27] = chr(0x5f) flag[28] = chr(0x35) flag[29] = chr(0x74) flag[30] = chr(0x72) flag[31] = chr(0x69) flag[32] = chr(0x6e) flag[33] = chr(0x67) flag[34] = chr(0x73) flag[35] = chr(0x7d) print("".join(flag)) # FLAG{5imp1e_Revers1ng_4rray_5trings}
flag = [''] * 36 flag[0] = chr(70) flag[1] = chr(76) flag[2] = chr(65) flag[3] = chr(71) flag[4] = chr(123) flag[5] = chr(53) flag[6] = chr(105) flag[7] = chr(109) flag[8] = chr(112) flag[9] = chr(49) flag[10] = chr(101) flag[11] = chr(95) flag[12] = chr(82) flag[13] = chr(101) flag[14] = chr(118) flag[15] = chr(101) flag[16] = chr(114) flag[17] = chr(115) flag[18] = chr(49) flag[19] = chr(110) flag[20] = chr(103) flag[21] = chr(95) flag[22] = chr(52) flag[23] = chr(114) flag[24] = chr(114) flag[25] = chr(97) flag[26] = chr(121) flag[27] = chr(95) flag[28] = chr(53) flag[29] = chr(116) flag[30] = chr(114) flag[31] = chr(105) flag[32] = chr(110) flag[33] = chr(103) flag[34] = chr(115) flag[35] = chr(125) print(''.join(flag))
def code_function(): #function begin############################################ global code code=""" class {0}_scoreboard extends uvm_scoreboard; //--------------------------------------- // declaring pkt_qu to store the pkt's recived from monitor //--------------------------------------- {0}_seq_item pkt_qu[$]; //--------------------------------------- // sc_{0} //--------------------------------------- bit [7:0] sc_{0} [4]; //--------------------------------------- //port to recive packets from monitor //--------------------------------------- uvm_analysis_imp#({0}_seq_item, {0}_scoreboard) item_collected_export; `uvm_component_utils({0}_scoreboard) //--------------------------------------- // new - constructor //--------------------------------------- function new (string name, uvm_component parent); super.new(name, parent); endfunction : new //--------------------------------------- // build_phase - create port and initialize local {0}ory //--------------------------------------- function void build_phase(uvm_phase phase); super.build_phase(phase); item_collected_export = new("item_collected_export", this); foreach(sc_{0}[i]) sc_{0}[i] = 8'hFF; endfunction: build_phase //--------------------------------------- // write task - recives the pkt from monitor and pushes into queue //--------------------------------------- virtual function void write({0}_seq_item pkt); //pkt.print(); pkt_qu.push_back(pkt); endfunction : write //--------------------------------------- // run_phase - compare's the read data with the expected data(stored in local {0}ory) // local {0}ory will be updated on the write operation. //--------------------------------------- virtual task run_phase(uvm_phase phase); {0}_seq_item {0}_pkt; forever begin wait(pkt_qu.size() > 0); {0}_pkt = pkt_qu.pop_front(); if({0}_pkt.wr_en) begin sc_{0}[{0}_pkt.addr] = {0}_pkt.wdata; `uvm_info(get_type_name(),$sformatf("------ :: WRITE DATA :: ------"),UVM_LOW) `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW) `uvm_info(get_type_name(),$sformatf("Data: %0h",{0}_pkt.wdata),UVM_LOW) `uvm_info(get_type_name(),"------------------------------------",UVM_LOW) end else if({0}_pkt.rd_en) begin if(sc_{0}[{0}_pkt.addr] == {0}_pkt.rdata) begin `uvm_info(get_type_name(),$sformatf("------ :: READ DATA Match :: ------"),UVM_LOW) `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW) `uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW) `uvm_info(get_type_name(),"------------------------------------",UVM_LOW) end else begin `uvm_error(get_type_name(),"------ :: READ DATA MisMatch :: ------") `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW) `uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW) `uvm_info(get_type_name(),"------------------------------------",UVM_LOW) end end end endtask : run_phase endclass : {0}_scoreboard """.format(protocol_name) print(code) #function end############################################ fh=open("protocol.csv","r") for protocol_name in fh: protocol_name=protocol_name.strip("\n") fph=open('{0}_sb.sv'.format(protocol_name),"w") code_function() fph.write(code)
def code_function(): global code code = '\nclass {0}_scoreboard extends uvm_scoreboard;\n \n //---------------------------------------\n // declaring pkt_qu to store the pkt\'s recived from monitor\n //---------------------------------------\n {0}_seq_item pkt_qu[$];\n \n //---------------------------------------\n // sc_{0} \n //---------------------------------------\n bit [7:0] sc_{0} [4];\n\n //---------------------------------------\n //port to recive packets from monitor\n //---------------------------------------\n uvm_analysis_imp#({0}_seq_item, {0}_scoreboard) item_collected_export;\n `uvm_component_utils({0}_scoreboard)\n\n //---------------------------------------\n // new - constructor\n //---------------------------------------\n function new (string name, uvm_component parent);\n super.new(name, parent);\n endfunction : new\n //---------------------------------------\n // build_phase - create port and initialize local {0}ory\n //---------------------------------------\n function void build_phase(uvm_phase phase);\n super.build_phase(phase);\n item_collected_export = new("item_collected_export", this);\n foreach(sc_{0}[i]) sc_{0}[i] = 8\'hFF;\n endfunction: build_phase\n \n //---------------------------------------\n // write task - recives the pkt from monitor and pushes into queue\n //---------------------------------------\n virtual function void write({0}_seq_item pkt);\n //pkt.print();\n pkt_qu.push_back(pkt);\n endfunction : write\n\n //---------------------------------------\n // run_phase - compare\'s the read data with the expected data(stored in local {0}ory)\n // local {0}ory will be updated on the write operation.\n //---------------------------------------\n virtual task run_phase(uvm_phase phase);\n {0}_seq_item {0}_pkt;\n \n forever begin\n wait(pkt_qu.size() > 0);\n {0}_pkt = pkt_qu.pop_front();\n \n if({0}_pkt.wr_en) begin\n sc_{0}[{0}_pkt.addr] = {0}_pkt.wdata;\n `uvm_info(get_type_name(),$sformatf("------ :: WRITE DATA :: ------"),UVM_LOW)\n `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)\n `uvm_info(get_type_name(),$sformatf("Data: %0h",{0}_pkt.wdata),UVM_LOW)\n `uvm_info(get_type_name(),"------------------------------------",UVM_LOW) \n end\n else if({0}_pkt.rd_en) begin\n if(sc_{0}[{0}_pkt.addr] == {0}_pkt.rdata) begin\n `uvm_info(get_type_name(),$sformatf("------ :: READ DATA Match :: ------"),UVM_LOW)\n `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)\n `uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW)\n `uvm_info(get_type_name(),"------------------------------------",UVM_LOW)\n end\n else begin\n `uvm_error(get_type_name(),"------ :: READ DATA MisMatch :: ------")\n `uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)\n `uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW)\n `uvm_info(get_type_name(),"------------------------------------",UVM_LOW)\n end\n end\n end\n endtask : run_phase\nendclass : {0}_scoreboard\n'.format(protocol_name) print(code) fh = open('protocol.csv', 'r') for protocol_name in fh: protocol_name = protocol_name.strip('\n') fph = open('{0}_sb.sv'.format(protocol_name), 'w') code_function() fph.write(code)
uno= Board('/dev/cu.wchusbserial1420') led= Led(13) led.setColor([0.84, 0.34, 0.67]) ledController= ExdTextInputBox(target= led, value="period", size="sm") APP.STACK.add_widget(ledController)
uno = board('/dev/cu.wchusbserial1420') led = led(13) led.setColor([0.84, 0.34, 0.67]) led_controller = exd_text_input_box(target=led, value='period', size='sm') APP.STACK.add_widget(ledController)
a, b = map(int, input().split()) if a + b == 15: print('+') elif a*b == 15: print('*') else: print('x')
(a, b) = map(int, input().split()) if a + b == 15: print('+') elif a * b == 15: print('*') else: print('x')
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: n = len(stoneValue) dp = [[0] * n for _ in range(n)] mx = [[0] * n for _ in range(n)] for i in range(n): mx[i][i] = stoneValue[i] for j in range(1, n): mid = j s = stoneValue[j] rightHalf = 0 for i in range(j - 1, -1, -1): s += stoneValue[i] while (rightHalf + stoneValue[mid]) * 2 <= s: rightHalf += stoneValue[mid] mid -= 1 if rightHalf * 2 == s: dp[i][j] = mx[i][mid] else: dp[i][j] = (0 if mid == i else mx[i][mid - 1]) if mid != j: dp[i][j] = max(dp[i][j], mx[j][mid + 1]) mx[i][j] = max(mx[i][j - 1], dp[i][j] + s) mx[j][i] = max(mx[j][i + 1], dp[i][j] + s) return dp[0][n - 1]
class Solution: def stone_game_v(self, stoneValue: List[int]) -> int: n = len(stoneValue) dp = [[0] * n for _ in range(n)] mx = [[0] * n for _ in range(n)] for i in range(n): mx[i][i] = stoneValue[i] for j in range(1, n): mid = j s = stoneValue[j] right_half = 0 for i in range(j - 1, -1, -1): s += stoneValue[i] while (rightHalf + stoneValue[mid]) * 2 <= s: right_half += stoneValue[mid] mid -= 1 if rightHalf * 2 == s: dp[i][j] = mx[i][mid] else: dp[i][j] = 0 if mid == i else mx[i][mid - 1] if mid != j: dp[i][j] = max(dp[i][j], mx[j][mid + 1]) mx[i][j] = max(mx[i][j - 1], dp[i][j] + s) mx[j][i] = max(mx[j][i + 1], dp[i][j] + s) return dp[0][n - 1]
# %% [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: if not root: return 0 r = self.sumOfLeftLeaves(root.right) if (p := root.left) and not p.left and not p.right: return root.left.val + r return self.sumOfLeftLeaves(root.left) + r
class Solution: def sum_of_left_leaves(self, root: TreeNode) -> int: if not root: return 0 r = self.sumOfLeftLeaves(root.right) if (p := root.left) and (not p.left) and (not p.right): return root.left.val + r return self.sumOfLeftLeaves(root.left) + r
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 row, col = len(matrix), len(matrix[0]) dp = [0] * col ret = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': dp[j] += 1 else: dp[j] = 0 left = [] right = [None] * col stack = [] for idx, val in enumerate(dp): while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: left.append(-1) else: left.append(stack[-1]) stack.append(idx) stack = [] for idx, val in enumerate(dp[::-1]): cidx = col - idx - 1 while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: right[cidx] = col else: right[cidx] = stack[-1] stack.append(cidx) for l, r, v in zip(left, right, dp): ret = max(ret, v * (r - l - 1)) return ret
class Solution: def maximal_rectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 (row, col) = (len(matrix), len(matrix[0])) dp = [0] * col ret = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': dp[j] += 1 else: dp[j] = 0 left = [] right = [None] * col stack = [] for (idx, val) in enumerate(dp): while stack and val <= dp[stack[-1]]: stack.pop() if not stack: left.append(-1) else: left.append(stack[-1]) stack.append(idx) stack = [] for (idx, val) in enumerate(dp[::-1]): cidx = col - idx - 1 while stack and val <= dp[stack[-1]]: stack.pop() if not stack: right[cidx] = col else: right[cidx] = stack[-1] stack.append(cidx) for (l, r, v) in zip(left, right, dp): ret = max(ret, v * (r - l - 1)) return ret
database_name = "Health_Service" user_name = "postgres" password = "zhangheng" port = "5432"
database_name = 'Health_Service' user_name = 'postgres' password = 'zhangheng' port = '5432'
""" Problem Set 5 - Problem 1 - Build the Shift Dictionary and Apply Shift The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action). In the next two questions, you will fill in the methods of the Message class found in ps6.py according to the specifications in the docstrings. In this problem, you will fill in two methods: 1. Fill in the build_shift_dict(self, shift) method of the Message class. Be sure that your dictionary includes both lower and upper case letters, but that the shifted character for a lower case letter and its uppercase version are lower and upper case instances of the same letter. What this means is that if the original letter is "a" and its shifted value is "c", the letter "A" should shift to the letter "C". 2. Fill in the apply_shift(self, shift) method of the Message class. You may find it easier to use build_shift_dict(self, shift). Remember that spaces and punctuation should not be changed by the cipher. """ class Message(object): ### DO NOT MODIFY THIS METHOD ### def __init__(self, text): ''' Initializes a Message object text (string): the message's text a Message object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) ### DO NOT MODIFY THIS METHOD ### def get_message_text(self): ''' Used to safely access self.message_text outside of the class Returns: self.message_text ''' return self.message_text ### DO NOT MODIFY THIS METHOD ### def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class Returns: a COPY of self.valid_words ''' return self.valid_words[:] def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). ''' self.dictionaryResult = {} lowerCase = string.ascii_lowercase upperCase = string.ascii_uppercase for letters in lowerCase: self.dictionaryResult.update({letters : lowerCase[((lowerCase.index(letters) + shift) % 26)]}) for letters in upperCase: self.dictionaryResult.update({letters : upperCase[((upperCase.index(letters) + shift) % 26)]}) return self.dictionaryResult def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' shiftedResult = "" for letters in self.get_message_text(): if letters in self.build_shift_dict(shift): shiftedResult += self.build_shift_dict(shift).get(letters) else: shiftedResult += letters return shiftedResult
""" Problem Set 5 - Problem 1 - Build the Shift Dictionary and Apply Shift The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action). In the next two questions, you will fill in the methods of the Message class found in ps6.py according to the specifications in the docstrings. In this problem, you will fill in two methods: 1. Fill in the build_shift_dict(self, shift) method of the Message class. Be sure that your dictionary includes both lower and upper case letters, but that the shifted character for a lower case letter and its uppercase version are lower and upper case instances of the same letter. What this means is that if the original letter is "a" and its shifted value is "c", the letter "A" should shift to the letter "C". 2. Fill in the apply_shift(self, shift) method of the Message class. You may find it easier to use build_shift_dict(self, shift). Remember that spaces and punctuation should not be changed by the cipher. """ class Message(object): def __init__(self, text): """ Initializes a Message object text (string): the message's text a Message object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words """ self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) def get_message_text(self): """ Used to safely access self.message_text outside of the class Returns: self.message_text """ return self.message_text def get_valid_words(self): """ Used to safely access a copy of self.valid_words outside of the class Returns: a COPY of self.valid_words """ return self.valid_words[:] def build_shift_dict(self, shift): """ Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). """ self.dictionaryResult = {} lower_case = string.ascii_lowercase upper_case = string.ascii_uppercase for letters in lowerCase: self.dictionaryResult.update({letters: lowerCase[(lowerCase.index(letters) + shift) % 26]}) for letters in upperCase: self.dictionaryResult.update({letters: upperCase[(upperCase.index(letters) + shift) % 26]}) return self.dictionaryResult def apply_shift(self, shift): """ Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift """ shifted_result = '' for letters in self.get_message_text(): if letters in self.build_shift_dict(shift): shifted_result += self.build_shift_dict(shift).get(letters) else: shifted_result += letters return shiftedResult
#Exercise 3.2: Rewrite your pay program using try and except so # that yourprogram handles non-numeric input gracefully by # printing a messageand exiting the program. The following # shows two executions of the program: # Enter Hours: 20 # Enter Rate: nine # Error, please enter numeric input # Enter Hours: forty # Error, please enter numeric input hrs = input("Enter Hours: ") try: h = float(hrs) rph = input("Enter Rate: ") try: r = float(rph) if h <= 40: pay = h * r else: overhours = h - 40 norm_pay = 40 * r over_pay = overhours * r * 1.5 pay = norm_pay + over_pay print(pay) except: print("Error, please enter numeric input") except: print("Error, please enter numeric input")
hrs = input('Enter Hours: ') try: h = float(hrs) rph = input('Enter Rate: ') try: r = float(rph) if h <= 40: pay = h * r else: overhours = h - 40 norm_pay = 40 * r over_pay = overhours * r * 1.5 pay = norm_pay + over_pay print(pay) except: print('Error, please enter numeric input') except: print('Error, please enter numeric input')
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # data = dict( # samples_per_gpu=1, # workers_per_gpu=2) # optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
_base_ = ['../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
""" Define custom exceptions """ __all__ = ( 'Track17Exception', 'InvalidCarrierCode', 'DateProcessingError' ) class Track17Exception(Exception): def __init__(self, message: str, code: int = None): self.message = message self.code = code super().__init__() def __str__(self) -> str: if self.code: return f'{self.message} (Code: {self.code})' return self.message class InvalidCarrierCode(Track17Exception): pass class DateProcessingError(Track17Exception): pass
""" Define custom exceptions """ __all__ = ('Track17Exception', 'InvalidCarrierCode', 'DateProcessingError') class Track17Exception(Exception): def __init__(self, message: str, code: int=None): self.message = message self.code = code super().__init__() def __str__(self) -> str: if self.code: return f'{self.message} (Code: {self.code})' return self.message class Invalidcarriercode(Track17Exception): pass class Dateprocessingerror(Track17Exception): pass
""" Ryan Kirkbride - Noodling around: https://www.youtube.com/watch?v=CXrkq7u69vU How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the song, just execute the blocks together (ctrl+enter) from the beginning, so you don't have to go through every variation of each instrument - Enjoy ! :+1: """ Scale.default = Scale.minor Root.default = -4 Clock.bpm = 136 d1 >> play(P["x---o---"],) d1 >> play(P["x---o---"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o---"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o--(-=)"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) d2 >> play(PZip("Vs"," n "),sample=1,) d2 >> play(PZip("Vs"," n "),sample=2,) d2 >> play(PZip("Vs"," n "),sample=2,).every(3,"stutter") d2 >> play(PZip("Vs"," n "),sample=2,).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," n "),sample=2,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) b1 >> dirt(var([0,2,-1,3]),) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,lpf=80,) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,lpf=80,fmod=(0,1),) k1 >> karp() k1 >> karp(oct=6,) k1 >> karp(dur=1/4,oct=6,) k1 >> karp(dur=1/4,oct=var([6,7]),) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1/2,) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32],) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),pan=linvar([-1,1],8),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),pan=linvar([-1,1],8),) + var([0,-1,1,-7]) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",4,pan=[-1,1]) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",4,pan=[-1,1],rate=4) p1 >> blip([0,4,7,9],) p1 >> blip([0,4,7,9],oct=6,) p1 >> blip([0,4,7,9],oct=6,sus=2,) p1 >> blip([0,4,7,9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,7,9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=7,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=1/2,) d3 >> play("[--]") p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=PDur(5,8),) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=PDur(5,8),chop=4) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6),sus=2,dur=PDur(5,8),chop=4) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",0,pan=[-1,1],rate=4) k1.stop() d2.solo() Scale.default = "major" s1 >> swell((0,2,4,const(6)),dur=4,) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,1],8) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,-1],8) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,1],8) Scale.default = Pvar([Scale.major,Scale.minor],16) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,[1,-1]],8) s1.solo() b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=4,lpf=80,fmod=(0,1),) b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=80,fmod=(0,1),) b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,1),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,1),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,0),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,) + [0,4,const(7)] b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,8),bits=0,lpf=0,) + [0,4,const(7)] b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,12),bits=0,lpf=0,) + [0,4,const(7)] d2 >> play(PZip("Vs"," n "),sample=2,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) k2 >> karp([0,7,6,4,2],) k2 >> karp([0,7,6,4,2],sus=2,) k2 >> karp([0,7,6,4,2],sus=2,dur=PDur(5,8),chop=4,) k2 >> karp([0,7,6,4,2],sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2],sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2].layer("mirror"),sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2].layer("mirror"),sus=2,dur=PDur(5,8),chop=4,oct=7,delay=(0,0.25),) k2.solo() b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,12),bits=0,lpf=0,) + [0,4,const(7)] d2 >> play(PZip("Vs"," D "),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," D D"),dur=PDur(5,8),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," i i"),dur=PDur(5,8),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,[1,-1]],8) d3 >> play("[--]") d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,bits=4,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,bits=4,slide=PStep(5,-1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=8,bits=4,slide=PStep(5,-1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sus=1,sample=-1,rate=var([1,4],[28,4]),chop=8,bits=4,slide=PStep(5,-1),) k2.solo() k2.solo(0) p1.stop() Group(k2, s1, d2, d3).only() Group(s1, d3).stop() nextBar(Clock.clear)
""" Ryan Kirkbride - Noodling around: https://www.youtube.com/watch?v=CXrkq7u69vU How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the song, just execute the blocks together (ctrl+enter) from the beginning, so you don't have to go through every variation of each instrument - Enjoy ! :+1: """ Scale.default = Scale.minor Root.default = -4 Clock.bpm = 136 d1 >> play(P['x---o---']) d1 >> play(P['x---o---'].layer('mirror'), pan=(-1, 1)) d1 >> play(P['x--(-[--])o---'].layer('mirror'), pan=(-1, 1)) d1 >> play(P['x--(-[--])o--(-=)'].layer('mirror'), pan=(-1, 1)) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8)) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])) d2 >> play(p_zip('Vs', ' n '), sample=1) d2 >> play(p_zip('Vs', ' n '), sample=2) d2 >> play(p_zip('Vs', ' n '), sample=2).every(3, 'stutter') d2 >> play(p_zip('Vs', ' n '), sample=2).every(3, 'stutter', dur=1) d2 >> play(p_zip('Vs', ' n '), sample=2, hpf=var([0, 4000], [28, 4])).every(3, 'stutter', dur=1) b1 >> dirt(var([0, 2, -1, 3])) b1 >> dirt(var([0, 2, -1, 3]), dur=p_dur(3, 8)) b1 >> dirt(var([0, 2, -1, 3]), dur=p_dur(3, 8), bits=4) b1 >> dirt(var([0, 2, -1, 3]), dur=p_dur(3, 8), bits=4, lpf=80) b1 >> dirt(var([0, 2, -1, 3]), dur=p_dur(3, 8), bits=4, lpf=80, fmod=(0, 1)) k1 >> karp() k1 >> karp(oct=6) k1 >> karp(dur=1 / 4, oct=6) k1 >> karp(dur=1 / 4, oct=var([6, 7])) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1 / 2) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32]) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32] * (1, 2)) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32] * (1, 2), delay=(0, 1 / 8)) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32] * (1, 2), delay=(0, 1 / 8), lpf=linvar([400, 5000], 12)) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32] * (1, 2), delay=(0, 1 / 8), lpf=linvar([400, 5000], 12), pan=linvar([-1, 1], 8)) + var([0, -1, 1, 0]) k1 >> karp(dur=1 / 4, oct=var([6, 7]), sus=1, rate=P[:32] * (1, 2), delay=(0, 1 / 8), lpf=linvar([400, 5000], 12), pan=linvar([-1, 1], 8)) + var([0, -1, 1, -7]) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])).every(5, 'stutter', 4, pan=[-1, 1]) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])).every(5, 'stutter', 4, pan=[-1, 1], rate=4) p1 >> blip([0, 4, 7, 9]) p1 >> blip([0, 4, 7, 9], oct=6) p1 >> blip([0, 4, 7, 9], oct=6, sus=2) p1 >> blip([0, 4, 7, 9], oct=6, sus=2, dur=1 / 2) p1 >> blip([var([0, -1, 1, 0]), 4, 7, 9], oct=6, sus=2, dur=1 / 2) p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=6, sus=2, dur=1 / 2) p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=7, sus=2, dur=1 / 2) p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=(6, 7), sus=2, dur=1 / 2) d3 >> play('[--]') p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=(6, 7), sus=2, dur=p_dur(5, 8)) p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=(6, 7), sus=2, dur=p_dur(5, 8), chop=4) p1 >> blip([var([0, -1, 1, 0]), 4, [7, 10], 9], oct=6, sus=2, dur=p_dur(5, 8), chop=4) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])).every(5, 'stutter', 0, pan=[-1, 1], rate=4) k1.stop() d2.solo() Scale.default = 'major' s1 >> swell((0, 2, 4, const(6)), dur=4) s1 >> swell((0, 2, 4, const(6)), dur=4) + var([0, 1], 8) s1 >> swell((0, 2, 4, const(6)), dur=4) + var([0, -1], 8) s1 >> swell((0, 2, 4, const(6)), dur=4) + var([0, 1], 8) Scale.default = pvar([Scale.major, Scale.minor], 16) s1 >> swell((0, 2, 4, const(6)), dur=4) + var([0, [1, -1]], 8) s1.solo() b1 >> dirt(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=4, lpf=80, fmod=(0, 1)) b1 >> dirt(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=0, lpf=80, fmod=(0, 1)) b1 >> dirt(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=0, lpf=0, fmod=(0, 1)) b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=0, lpf=0, fmod=(0, 1)) b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=0, lpf=0, fmod=(0, 0)) b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(3, 8), bits=0, lpf=0) + [0, 4, const(7)] b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(5, 8), bits=0, lpf=0) + [0, 4, const(7)] b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(5, 12), bits=0, lpf=0) + [0, 4, const(7)] d2 >> play(p_zip('Vs', ' n '), sample=2, hpf=var([0, 4000], [28, 4])).every(3, 'stutter', dur=1) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])) k2 >> karp([0, 7, 6, 4, 2]) k2 >> karp([0, 7, 6, 4, 2], sus=2) k2 >> karp([0, 7, 6, 4, 2], sus=2, dur=p_dur(5, 8), chop=4) k2 >> karp([0, 7, 6, 4, 2], sus=2, dur=p_dur(5, 8), chop=4, oct=7) k2 >> karp(P[var([0, 1], 8), 7, 6, 4, 2], sus=2, dur=p_dur(5, 8), chop=4, oct=7) k2 >> karp(P[var([0, 1], 8), 7, 6, 4, 2].layer('mirror'), sus=2, dur=p_dur(5, 8), chop=4, oct=7) k2 >> karp(P[var([0, 1], 8), 7, 6, 4, 2].layer('mirror'), sus=2, dur=p_dur(5, 8), chop=4, oct=7, delay=(0, 0.25)) k2.solo() b1 >> bass(var([0, [1, -1]], 8), dur=p_dur(5, 12), bits=0, lpf=0) + [0, 4, const(7)] d2 >> play(p_zip('Vs', ' D '), sample=0, hpf=var([0, 4000], [28, 4])).every(3, 'stutter', dur=1) d2 >> play(p_zip('Vs', ' D D'), dur=p_dur(5, 8), sample=0, hpf=var([0, 4000], [28, 4])).every(3, 'stutter', dur=1) d2 >> play(p_zip('Vs', ' i i'), dur=p_dur(5, 8), sample=0, hpf=var([0, 4000], [28, 4])).every(3, 'stutter', dur=1) s1 >> swell((0, 2, 4, const(6)), dur=4) + var([0, [1, -1]], 8) d3 >> play('[--]') d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4])) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4]), chop=32) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4]), chop=32, bits=4) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4]), chop=32, bits=4, slide=p_step(5, -1)) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sample=-1, rate=var([1, 4], [28, 4]), chop=8, bits=4, slide=p_step(5, -1)) d1 >> play(P['x--(-[--])o--o(-=)-'].layer('mirror'), pan=(-1, 1), dur=p_dur(5, 8), sus=1, sample=-1, rate=var([1, 4], [28, 4]), chop=8, bits=4, slide=p_step(5, -1)) k2.solo() k2.solo(0) p1.stop() group(k2, s1, d2, d3).only() group(s1, d3).stop() next_bar(Clock.clear)
HASS_EVENT_RECEIVE = 'HASS_EVENT_RECEIVE' # hass.bus --> hauto.bus HASS_STATE_CHANGED = 'HASS_STATE_CHANGE' # aka hass.EVENT_STATE_CHANGED HASS_ENTITY_CREATE = 'HASS_ENTITY_CREATE' # hass entity is newly created HASS_ENTITY_CHANGE = 'HASS_ENTITY_CHANGE' # hass entity's state changes HASS_ENTITY_UPDATE = 'HASS_ENTITY_UPDATE' # hass entity's state is same, but attributes change HASS_ENTITY_REMOVE = 'HASS_ENTITY_REMOVE' # hass entity is removed
hass_event_receive = 'HASS_EVENT_RECEIVE' hass_state_changed = 'HASS_STATE_CHANGE' hass_entity_create = 'HASS_ENTITY_CREATE' hass_entity_change = 'HASS_ENTITY_CHANGE' hass_entity_update = 'HASS_ENTITY_UPDATE' hass_entity_remove = 'HASS_ENTITY_REMOVE'
N, L = map(int, input().split()) amida = [] for _ in range(L+1): tmp = list(input()) amida.append(tmp) idx = amida[L].index('o') for i in reversed(range(L)): if idx != N*2-2 and amida[i][idx+1] == '-': idx += 2 elif idx != 0 and amida[i][idx-1] == '-': idx -= 2 print(idx//2+1)
(n, l) = map(int, input().split()) amida = [] for _ in range(L + 1): tmp = list(input()) amida.append(tmp) idx = amida[L].index('o') for i in reversed(range(L)): if idx != N * 2 - 2 and amida[i][idx + 1] == '-': idx += 2 elif idx != 0 and amida[i][idx - 1] == '-': idx -= 2 print(idx // 2 + 1)
# LSM6DSO 3D accelerometer and 3D gyroscope seneor micropython drive # ver: 1.0 # License: MIT # Author: shaoziyang (shaoziyang@micropython.org.cn) # v1.0 2019.7 LSM6DSO_CTRL1_XL = const(0x10) LSM6DSO_CTRL2_G = const(0x11) LSM6DSO_CTRL3_C = const(0x12) LSM6DSO_CTRL6_C = const(0x15) LSM6DSO_CTRL8_XL = const(0x17) LSM6DSO_STATUS = const(0x1E) LSM6DSO_OUT_TEMP_L = const(0x20) LSM6DSO_OUTX_L_G = const(0x22) LSM6DSO_OUTY_L_G = const(0x24) LSM6DSO_OUTZ_L_G = const(0x26) LSM6DSO_OUTX_L_A = const(0x28) LSM6DSO_OUTY_L_A = const(0x2A) LSM6DSO_OUTZ_L_A = const(0x2C) LSM6DSO_SCALEA = ('2g', '16g', '4g', '8g') LSM6DSO_SCALEG = ('250', '125', '500', '', '1000', '', '2000') class LSM6DSO(): def __init__(self, i2c, addr = 0x6B): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [[0, 0, 0], [0, 0, 0]] self._power = True self._power_a = 0x10 self._power_g = 0x10 # ODR_XL=1 FS_XL=0 self.setreg(LSM6DSO_CTRL1_XL, 0x10) # ODR_G=1 FS_125=1 self.setreg(LSM6DSO_CTRL2_G, 0x12) # BDU=1 IF_INC=1 self.setreg(LSM6DSO_CTRL3_C, 0x44) self.setreg(LSM6DSO_CTRL8_XL, 0) # scale=2G self._scale_a = 0 self._scale_g = 0 self._scale_a_c = 1 self._scale_g_c = 1 self.scale_a('2g') self.scale_g('125') def int16(self, d): return d if d < 0x8000 else d - 0x10000 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg+1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = (self.rb[0] & mask) | dat self.setreg(reg, self.rb[0]) def ax_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_A)) def ay_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_A)) def az_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_A)) def gx_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_G)) def gy_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_G)) def gz_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_G)) def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * self._scale_a_c) def mdps(self, reg): return round(self.int16(self.get2reg(reg)) * 4.375 * self._scale_g_c) def ax(self): return self.mg(LSM6DSO_OUTX_L_A) def ay(self): return self.mg(LSM6DSO_OUTY_L_A) def az(self): return self.mg(LSM6DSO_OUTZ_L_A) def gx(self): return self.mdps(LSM6DSO_OUTX_L_G) def gy(self): return self.mdps(LSM6DSO_OUTY_L_G) def gz(self): return self.mdps(LSM6DSO_OUTZ_L_G) def get_a(self): self.irq_v[0][0] = self.ax() self.irq_v[0][1] = self.ay() self.irq_v[0][2] = self.az() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx() self.irq_v[1][1] = self.gy() self.irq_v[1][2] = self.gz() return self.irq_v[1] def get(self): self.get_a() self.get_g() return self.irq_v def get_a_raw(self): self.irq_v[0][0] = self.ax_raw() self.irq_v[0][1] = self.ay_raw() self.irq_v[0][2] = self.az_raw() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx_raw() self.irq_v[1][1] = self.gy_raw() self.irq_v[1][2] = self.gz_raw() return self.irq_v[1] def get(self): self.get_a_raw() self.get_g_raw() return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LSM6DSO_OUT_TEMP_L))/256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LSM6DSO_OUT_TEMP_L+1) if self.rb[0] & 0x80: self.rb[0] -= 256 return self.rb[0] + 25 def scale_a(self, dat=None): if dat is None: return LSM6DSO_SCALEA[self._scale_a] else: if type(dat) is str: if not dat in LSM6DSO_SCALEA: return self._scale_a = LSM6DSO_SCALEA.index(dat) self._scale_a_c = int(dat.rstrip('g'))//2 else: return self.r_w_reg(LSM6DSO_CTRL1_XL, self._scale_a<<2, 0xF3) def scale_g(self, dat=None): if (dat is None) or (dat == ''): return LSM6DSO_SCALEG[self._scale_g] else: if type(dat) is str: if not dat in LSM6DSO_SCALEG: return self._scale_g = LSM6DSO_SCALEG.index(dat) self._scale_g_c = int(dat)//125 else: return self.r_w_reg(LSM6DSO_CTRL2_G, self._scale_g<<1, 0xF1) def power(self, on=None): if on is None: return self._power else: self._power = on if on: self.r_w_reg(LSM6DSO_CTRL1_XL, self._power_a, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, self._power_g, 0x0F) else: self._power_a = self.getreg(LSM6DSO_CTRL1_XL) & 0xF0 self._power_g = self.getreg(LSM6DSO_CTRL2_G) & 0xF0 self.r_w_reg(LSM6DSO_CTRL1_XL, 0, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, 0, 0x0F)
lsm6_dso_ctrl1_xl = const(16) lsm6_dso_ctrl2_g = const(17) lsm6_dso_ctrl3_c = const(18) lsm6_dso_ctrl6_c = const(21) lsm6_dso_ctrl8_xl = const(23) lsm6_dso_status = const(30) lsm6_dso_out_temp_l = const(32) lsm6_dso_outx_l_g = const(34) lsm6_dso_outy_l_g = const(36) lsm6_dso_outz_l_g = const(38) lsm6_dso_outx_l_a = const(40) lsm6_dso_outy_l_a = const(42) lsm6_dso_outz_l_a = const(44) lsm6_dso_scalea = ('2g', '16g', '4g', '8g') lsm6_dso_scaleg = ('250', '125', '500', '', '1000', '', '2000') class Lsm6Dso: def __init__(self, i2c, addr=107): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [[0, 0, 0], [0, 0, 0]] self._power = True self._power_a = 16 self._power_g = 16 self.setreg(LSM6DSO_CTRL1_XL, 16) self.setreg(LSM6DSO_CTRL2_G, 18) self.setreg(LSM6DSO_CTRL3_C, 68) self.setreg(LSM6DSO_CTRL8_XL, 0) self._scale_a = 0 self._scale_g = 0 self._scale_a_c = 1 self._scale_g_c = 1 self.scale_a('2g') self.scale_g('125') def int16(self, d): return d if d < 32768 else d - 65536 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg + 1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = self.rb[0] & mask | dat self.setreg(reg, self.rb[0]) def ax_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_A)) def ay_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_A)) def az_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_A)) def gx_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_G)) def gy_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_G)) def gz_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_G)) def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * self._scale_a_c) def mdps(self, reg): return round(self.int16(self.get2reg(reg)) * 4.375 * self._scale_g_c) def ax(self): return self.mg(LSM6DSO_OUTX_L_A) def ay(self): return self.mg(LSM6DSO_OUTY_L_A) def az(self): return self.mg(LSM6DSO_OUTZ_L_A) def gx(self): return self.mdps(LSM6DSO_OUTX_L_G) def gy(self): return self.mdps(LSM6DSO_OUTY_L_G) def gz(self): return self.mdps(LSM6DSO_OUTZ_L_G) def get_a(self): self.irq_v[0][0] = self.ax() self.irq_v[0][1] = self.ay() self.irq_v[0][2] = self.az() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx() self.irq_v[1][1] = self.gy() self.irq_v[1][2] = self.gz() return self.irq_v[1] def get(self): self.get_a() self.get_g() return self.irq_v def get_a_raw(self): self.irq_v[0][0] = self.ax_raw() self.irq_v[0][1] = self.ay_raw() self.irq_v[0][2] = self.az_raw() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx_raw() self.irq_v[1][1] = self.gy_raw() self.irq_v[1][2] = self.gz_raw() return self.irq_v[1] def get(self): self.get_a_raw() self.get_g_raw() return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LSM6DSO_OUT_TEMP_L)) / 256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LSM6DSO_OUT_TEMP_L + 1) if self.rb[0] & 128: self.rb[0] -= 256 return self.rb[0] + 25 def scale_a(self, dat=None): if dat is None: return LSM6DSO_SCALEA[self._scale_a] else: if type(dat) is str: if not dat in LSM6DSO_SCALEA: return self._scale_a = LSM6DSO_SCALEA.index(dat) self._scale_a_c = int(dat.rstrip('g')) // 2 else: return self.r_w_reg(LSM6DSO_CTRL1_XL, self._scale_a << 2, 243) def scale_g(self, dat=None): if dat is None or dat == '': return LSM6DSO_SCALEG[self._scale_g] else: if type(dat) is str: if not dat in LSM6DSO_SCALEG: return self._scale_g = LSM6DSO_SCALEG.index(dat) self._scale_g_c = int(dat) // 125 else: return self.r_w_reg(LSM6DSO_CTRL2_G, self._scale_g << 1, 241) def power(self, on=None): if on is None: return self._power else: self._power = on if on: self.r_w_reg(LSM6DSO_CTRL1_XL, self._power_a, 15) self.r_w_reg(LSM6DSO_CTRL2_G, self._power_g, 15) else: self._power_a = self.getreg(LSM6DSO_CTRL1_XL) & 240 self._power_g = self.getreg(LSM6DSO_CTRL2_G) & 240 self.r_w_reg(LSM6DSO_CTRL1_XL, 0, 15) self.r_w_reg(LSM6DSO_CTRL2_G, 0, 15)
class Solution: def findPeakElement(self, nums: List[int]) -> int: l=0 r=len(nums)-1 while l<r: mid=l+(r-l)//2 if nums[mid]<nums[mid+1]: l=mid+1 else: r=mid return l
class Solution: def find_peak_element(self, nums: List[int]) -> int: l = 0 r = len(nums) - 1 while l < r: mid = l + (r - l) // 2 if nums[mid] < nums[mid + 1]: l = mid + 1 else: r = mid return l
# Refers to `_RAND_INCREASING_TRANSFORMS` in pytorch-image-models rand_increasing_policies = [ dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='SolarizeAdd', magnitude_key='magnitude', magnitude_range=(0, 110)), dict(type='ColorTransform', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Brightness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='horizontal'), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='vertical'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='horizontal'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='vertical') ]
rand_increasing_policies = [dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='SolarizeAdd', magnitude_key='magnitude', magnitude_range=(0, 110)), dict(type='ColorTransform', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Brightness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='horizontal'), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='vertical'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='horizontal'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='vertical')]
def tickets(people): twenty_fives = 0 fifties = 0 for p in people: if p == 25: twenty_fives += 1 if p == 50: if twenty_fives == 0: return 'NO' twenty_fives -= 1 fifties += 1 if p == 100: if fifties >= 1 and twenty_fives >= 1: twenty_fives -= 1 fifties -= 1 elif twenty_fives >= 3: twenty_fives -= 3 else: return 'NO' return 'YES'
def tickets(people): twenty_fives = 0 fifties = 0 for p in people: if p == 25: twenty_fives += 1 if p == 50: if twenty_fives == 0: return 'NO' twenty_fives -= 1 fifties += 1 if p == 100: if fifties >= 1 and twenty_fives >= 1: twenty_fives -= 1 fifties -= 1 elif twenty_fives >= 3: twenty_fives -= 3 else: return 'NO' return 'YES'
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ # Disable DYNAMICBASE for these tests because it implies/doesn't imply # FIXED in certain cases so it complicates the test for FIXED. { 'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_no', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '1', 'RandomizedBaseAddress': '1', } }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_yes', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '2', 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, ] }
{'targets': [{'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_no', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'FixedBaseAddress': '1', 'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_yes', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'FixedBaseAddress': '2', 'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}]}
# Python program to Find Numbers divisible by Another number def main(): x=int(input("Enter the number")) y=int(input("Enter the limit value")) print("The Numbers divisible by",x,"is") for i in range(1,y+1): if i%x==0: print(i) if __name__=='__main__': main()
def main(): x = int(input('Enter the number')) y = int(input('Enter the limit value')) print('The Numbers divisible by', x, 'is') for i in range(1, y + 1): if i % x == 0: print(i) if __name__ == '__main__': main()
class multi(): def insert(self,num): for i in range(1, 11): print(num, "X", i, "=", num * i) d=multi() d.insert(num=int(input('Enter the number')))
class Multi: def insert(self, num): for i in range(1, 11): print(num, 'X', i, '=', num * i) d = multi() d.insert(num=int(input('Enter the number')))
a = 67 b = 1006 c = 1002 """if (a>=b and a>=c): print(a) elif (b>=c and b>=a) : print(b) elif (b>=a and b>=b) : print(c)""" max=a if a>=b: if b>=c: max =a else: if a>=c: max =a else: max = c else: if a>=c: max =b else: if b>=c: max=a else: max=c print(max)
a = 67 b = 1006 c = 1002 'if (a>=b and a>=c):\n print(a)\nelif (b>=c and b>=a) :\n print(b)\nelif (b>=a and b>=b) :\n print(c)' max = a if a >= b: if b >= c: max = a elif a >= c: max = a else: max = c elif a >= c: max = b elif b >= c: max = a else: max = c print(max)
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s)<=1: return True chars=[] for i in range(len(s)): if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '0' and s[i] <= '9' or s[i] >= 'A' and s[i] <= 'Z': chars.append(s[i].lower()) left,right=0,len(chars)-1 while left<=right: if chars[left]!=chars[right]: return False else: left,right=left+1,right-1 return True
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ class Solution(object): def is_palindrome(self, s): """ :type s: str :rtype: bool """ if len(s) <= 1: return True chars = [] for i in range(len(s)): if s[i] >= 'a' and s[i] <= 'z' or (s[i] >= '0' and s[i] <= '9') or (s[i] >= 'A' and s[i] <= 'Z'): chars.append(s[i].lower()) (left, right) = (0, len(chars) - 1) while left <= right: if chars[left] != chars[right]: return False else: (left, right) = (left + 1, right - 1) return True
for value in range(10): print(value) print('All Done!')
for value in range(10): print(value) print('All Done!')
""""" Datos de Entrada N Enteros Positivos = n = int K Enteros Positivos = k = int Datos de Salida Siempre que k sea menor a n Cuando N = K """"" n=int(input("Escriba el primer digito ")) k=int(input("Escriba el primer digito ")) while True: n=0 if(k<n): n=n-1 print(n) elif(n==k): print(k) break # Datos de Salida
""""" Datos de Entrada N Enteros Positivos = n = int K Enteros Positivos = k = int Datos de Salida Siempre que k sea menor a n Cuando N = K """ n = int(input('Escriba el primer digito ')) k = int(input('Escriba el primer digito ')) while True: n = 0 if k < n: n = n - 1 print(n) elif n == k: print(k) break
def shift_letter(char, shifts): if not isinstance(char, chr): raise ValueError('char should be typeof chr') if char == '' or char is None: raise ValueError('char should be typeof chr') if ord(char.upper()) < 65 or ord(char.upper()) > 90: raise ValueError('char should be only a-z Latin alphabet letters') char = char.upper() char = ord(char) + shifts char = char - 90 + 64 if char > 90 else char char = chr(char) return char def cesar(input_string, shifts=13): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(shifts, int) is False or shifts <= 0: raise ValueError( 'shifts should be type of int() and greater then zero') if shifts is True or shifts is False: raise ValueError('shifts cannot be boolean value') chars = list(input_string.upper()) encrypted_string = list() for char in chars: number_in_ascii = ord(char) if number_in_ascii < 65 or number_in_ascii > 90: raise ValueError('Input string should contain only a-z Latin alphabet letters' '(no special signs or numbers!) without white-spaces.') number_in_ascii += shifts if number_in_ascii > 90: number_in_ascii = (number_in_ascii - 90) + 65 char = chr(number_in_ascii) encrypted_string.append(char) return ''.join(encrypted_string) def fence(input_string, fence_height): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(fence_height, int) is False or fence_height < 2: raise ValueError('fence_height should be type of int greater then one') if isinstance(fence_height, bool): raise ValueError('fence_height cannot be typeof bool') fence_levels = list() i = 0 while i < fence_height: fence_levels.append(list()) i += 1 level = 0 go_down = True for sign in input_string: fence_levels[level].append(sign) if go_down: level += 1 else: level -= 1 if level == fence_height - 1: go_down = False if level == 0: go_down = True output_string = '' for lvl in fence_levels: for char in lvl: output_string += char return output_string def gaderypoluki(input_string, key): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(key, str) is False or key is '': raise ValueError('key should be type of str() and not empty or null') input_string = input_string.lower() key = key.lower() i = 2 while i < len(key): if key[i] is not '-': raise ValueError( "Wrong format of key value. Should be like: 'GA-DE-RY-PO-LU-KI'") i += 3 simplified_key = '' for char in key: if char is not '-': simplified_key += char output_string = '' for char in input_string: if char in simplified_key: index = simplified_key.index(char) if index % 2 is 0: index += 1 else: index -= 1 output_string += simplified_key[index] else: output_string += char return output_string def vignere_table(i_row, i_column): table = [[chr(num) for num in range(65, 91, 1)] for c in range(65, 91, 1)] if not isinstance(i_row, int) or not isinstance(i_column, int): raise ValueError('i_row nad i_column should be typeof int') if i_row > 25: raise IndexError('i_rowe is out of range it should be below 26') if i_column > 25: raise IndexError('i_column is out of range it should be below 26') row = 1 while row < len(table): column = 0 while column < len(table[row]): letter = table[row][column] table[row][column] = shift_letter(letter, row) column += 1 row += 1 return table[i_row][i_column] def vignere(input_string, key): if not isinstance(input_string, str): raise ValueError('Input string should be typeof str') if input_string is None or input_string is '': raise ValueError('Input string should be typeof str') input_string = input_string.upper() for c in input_string: if ord(c) < 65 or ord(c) > 90: if c is not ' ': raise ValueError( 'Input string should contain only a-z Latin alphabet letters') key = key.upper() correct_key = [] i = 0 for letter in input_string: if i == len(key): i = 0 if letter == ' ': correct_key.append(letter) else: correct_key.append(key[i]) i += 1 correct_key = ''.join(correct_key) column = 0 row = 0 alphabet = [chr(i) for i in range(65, 91, 1)] output_string = [] i = 0 while i < len(input_string): if input_string[i] == ' ': output_string.append(input_string[i]) else: column = alphabet.index(input_string[i]) row = alphabet.index(correct_key[i]) output_string.append(vignere_table(column, row)) i += 1 output_string = ''.join(output_string) return output_string
def shift_letter(char, shifts): if not isinstance(char, chr): raise value_error('char should be typeof chr') if char == '' or char is None: raise value_error('char should be typeof chr') if ord(char.upper()) < 65 or ord(char.upper()) > 90: raise value_error('char should be only a-z Latin alphabet letters') char = char.upper() char = ord(char) + shifts char = char - 90 + 64 if char > 90 else char char = chr(char) return char def cesar(input_string, shifts=13): if isinstance(input_string, str) is False or input_string is '': raise value_error('input_string should be type of str() and not empty or null') if isinstance(shifts, int) is False or shifts <= 0: raise value_error('shifts should be type of int() and greater then zero') if shifts is True or shifts is False: raise value_error('shifts cannot be boolean value') chars = list(input_string.upper()) encrypted_string = list() for char in chars: number_in_ascii = ord(char) if number_in_ascii < 65 or number_in_ascii > 90: raise value_error('Input string should contain only a-z Latin alphabet letters(no special signs or numbers!) without white-spaces.') number_in_ascii += shifts if number_in_ascii > 90: number_in_ascii = number_in_ascii - 90 + 65 char = chr(number_in_ascii) encrypted_string.append(char) return ''.join(encrypted_string) def fence(input_string, fence_height): if isinstance(input_string, str) is False or input_string is '': raise value_error('input_string should be type of str() and not empty or null') if isinstance(fence_height, int) is False or fence_height < 2: raise value_error('fence_height should be type of int greater then one') if isinstance(fence_height, bool): raise value_error('fence_height cannot be typeof bool') fence_levels = list() i = 0 while i < fence_height: fence_levels.append(list()) i += 1 level = 0 go_down = True for sign in input_string: fence_levels[level].append(sign) if go_down: level += 1 else: level -= 1 if level == fence_height - 1: go_down = False if level == 0: go_down = True output_string = '' for lvl in fence_levels: for char in lvl: output_string += char return output_string def gaderypoluki(input_string, key): if isinstance(input_string, str) is False or input_string is '': raise value_error('input_string should be type of str() and not empty or null') if isinstance(key, str) is False or key is '': raise value_error('key should be type of str() and not empty or null') input_string = input_string.lower() key = key.lower() i = 2 while i < len(key): if key[i] is not '-': raise value_error("Wrong format of key value. Should be like: 'GA-DE-RY-PO-LU-KI'") i += 3 simplified_key = '' for char in key: if char is not '-': simplified_key += char output_string = '' for char in input_string: if char in simplified_key: index = simplified_key.index(char) if index % 2 is 0: index += 1 else: index -= 1 output_string += simplified_key[index] else: output_string += char return output_string def vignere_table(i_row, i_column): table = [[chr(num) for num in range(65, 91, 1)] for c in range(65, 91, 1)] if not isinstance(i_row, int) or not isinstance(i_column, int): raise value_error('i_row nad i_column should be typeof int') if i_row > 25: raise index_error('i_rowe is out of range it should be below 26') if i_column > 25: raise index_error('i_column is out of range it should be below 26') row = 1 while row < len(table): column = 0 while column < len(table[row]): letter = table[row][column] table[row][column] = shift_letter(letter, row) column += 1 row += 1 return table[i_row][i_column] def vignere(input_string, key): if not isinstance(input_string, str): raise value_error('Input string should be typeof str') if input_string is None or input_string is '': raise value_error('Input string should be typeof str') input_string = input_string.upper() for c in input_string: if ord(c) < 65 or ord(c) > 90: if c is not ' ': raise value_error('Input string should contain only a-z Latin alphabet letters') key = key.upper() correct_key = [] i = 0 for letter in input_string: if i == len(key): i = 0 if letter == ' ': correct_key.append(letter) else: correct_key.append(key[i]) i += 1 correct_key = ''.join(correct_key) column = 0 row = 0 alphabet = [chr(i) for i in range(65, 91, 1)] output_string = [] i = 0 while i < len(input_string): if input_string[i] == ' ': output_string.append(input_string[i]) else: column = alphabet.index(input_string[i]) row = alphabet.index(correct_key[i]) output_string.append(vignere_table(column, row)) i += 1 output_string = ''.join(output_string) return output_string
i = 1 while i < 20: print(i) i += 1 i = 1 while i < 100: print(i) i += 1 i = 50 while i < 60: print(i) i += 1 i = 5 while i < 60: print(i) i += 1 i = 1 while i < 6: print(i) if (i == 3): break i += 1 k = 1 while k < 20: print(k) if (k == 20 or k == 16): break k += 1 usr = "" while usr != "q": usr = input("Enter a city, or q t")
i = 1 while i < 20: print(i) i += 1 i = 1 while i < 100: print(i) i += 1 i = 50 while i < 60: print(i) i += 1 i = 5 while i < 60: print(i) i += 1 i = 1 while i < 6: print(i) if i == 3: break i += 1 k = 1 while k < 20: print(k) if k == 20 or k == 16: break k += 1 usr = '' while usr != 'q': usr = input('Enter a city, or q t')
def count_words(message): #return len(message.split()) # words = [] count = 0 activeWord = False for c in message: if c.isspace(): activeWord = False else: if not activeWord: # words.append([]) count += 1 activeWord = True # words[-1].append(c) return count #len(words) def main(): message = "What is your name?" print(message) print(count_words(message)) message = " Howwdy doody? " print(message) print(count_words(message)) if __name__ == '__main__': main()
def count_words(message): count = 0 active_word = False for c in message: if c.isspace(): active_word = False elif not activeWord: count += 1 active_word = True return count def main(): message = 'What is your name?' print(message) print(count_words(message)) message = ' Howwdy doody? ' print(message) print(count_words(message)) if __name__ == '__main__': main()
class BufferFullException(Exception): def __init__(self, msg): self.msg = msg class BufferEmptyException(Exception): def __init__(self, msg): self.msg = msg class CircularBuffer: def __init__(self, capacity): self.list_circulator = list() self.list_circulator.append(','.join(str(capacity))) def read(self): if self.list_circulator == None: return BufferEmptyException("Empty") else: for items in self.list_circulator: return items def write(self, data): pass def overwrite(self, data): pass def clear(self): pass
class Bufferfullexception(Exception): def __init__(self, msg): self.msg = msg class Bufferemptyexception(Exception): def __init__(self, msg): self.msg = msg class Circularbuffer: def __init__(self, capacity): self.list_circulator = list() self.list_circulator.append(','.join(str(capacity))) def read(self): if self.list_circulator == None: return buffer_empty_exception('Empty') else: for items in self.list_circulator: return items def write(self, data): pass def overwrite(self, data): pass def clear(self): pass
DOMAIN = "microsoft_todo" CONF_CLIENT_ID = "client_id" CONF_CLIENT_SECRET = "client_secret" AUTH_CALLBACK_PATH = "/api/microsoft-todo" AUTHORIZATION_BASE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token" SCOPE = ["Tasks.ReadWrite"] AUTH_REQUEST_SCOPE = SCOPE + ["offline_access"] MS_TODO_AUTH_FILE = ".ms_todo_auth.json" ATTR_ACCESS_TOKEN = "access_token" ATTR_REFRESH_TOKEN = "refresh_token" SERVICE_NEW_TASK = "new_task" SUBJECT = "subject" LIST_CONF = "list_conf" LIST_NAME = "list_name" LIST_ID = "list_id" NOTE = "note" DUE_DATE = "due_date" REMINDER_DATE_TIME = "reminder_date_time" ALL_TASKS = "all_tasks"
domain = 'microsoft_todo' conf_client_id = 'client_id' conf_client_secret = 'client_secret' auth_callback_path = '/api/microsoft-todo' authorization_base_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' scope = ['Tasks.ReadWrite'] auth_request_scope = SCOPE + ['offline_access'] ms_todo_auth_file = '.ms_todo_auth.json' attr_access_token = 'access_token' attr_refresh_token = 'refresh_token' service_new_task = 'new_task' subject = 'subject' list_conf = 'list_conf' list_name = 'list_name' list_id = 'list_id' note = 'note' due_date = 'due_date' reminder_date_time = 'reminder_date_time' all_tasks = 'all_tasks'
input = """ c | d. a | b :- c. a :- b. b :- a. """ output = """ {d} {c, a, b} """
input = '\nc | d.\na | b :- c.\na :- b.\nb :- a.\n' output = '\n{d}\n{c, a, b}\n'
def parse_response_from_json(r): response = '' try: response = r.json()['response'] except Exception as ex: response = str(ex) return response
def parse_response_from_json(r): response = '' try: response = r.json()['response'] except Exception as ex: response = str(ex) return response
# [Commerci Republic] Delfino Deleter 2 sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("I was so much faster than you! But you're the sidekick for a reason.") sm.sendNext("C'mon! We can't let them get their buddies. We have to finish this now! I'll be waiting for you at #m865020200#") # Canal 3 sm.sendNext("What are you waiting for, my loyal sidekick?") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("Hold up. I have a really bad feeling about this...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("Don't feel bad. I'm here for you, pal.") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("No, listen. These fishmen seem like they're barely even trying...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("That's only because I'm totally awesome. So they look weak in comparison.") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("But...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("Let's go!") sm.completeQuest(parentID) sm.dispose()
sm.setSpeakerID(9390256) sm.sendNext("I was so much faster than you! But you're the sidekick for a reason.") sm.sendNext("C'mon! We can't let them get their buddies. We have to finish this now! I'll be waiting for you at #m865020200#") sm.sendNext('What are you waiting for, my loyal sidekick?') sm.setPlayerAsSpeaker() sm.sendNext('Hold up. I have a really bad feeling about this...') sm.setSpeakerID(9390256) sm.sendNext("Don't feel bad. I'm here for you, pal.") sm.setPlayerAsSpeaker() sm.sendNext("No, listen. These fishmen seem like they're barely even trying...") sm.setSpeakerID(9390256) sm.sendNext("That's only because I'm totally awesome. So they look weak in comparison.") sm.setPlayerAsSpeaker() sm.sendNext('But...') sm.setSpeakerID(9390256) sm.sendNext("Let's go!") sm.completeQuest(parentID) sm.dispose()
ans=0 n=200 def f(n): fac=[0]*(n+10) fac[0]=1 for i in range(1,n+5): fac[i]=i*fac[i-1] return fac def c(n,m): return fac[n]//fac[n-m]//fac[m] def solve(i,asn,b,other): res=0 if i>b: if other>b+1: return 0 else: t=fac[b+1]//fac[b+1-other] for j in asn: if j: t//=fac[j] return t for j in range(b/i+1): asn[i]=j res+=solve(i+1,asn,b-i*j,other+j) asn[i]=0 return res; fac=f(n) assign = [0]*(n+10) #ans = solve(3,assign,n,0) ans=50 while solve(50,assign,ans,0)<1000000: ans+=1 print(ans)
ans = 0 n = 200 def f(n): fac = [0] * (n + 10) fac[0] = 1 for i in range(1, n + 5): fac[i] = i * fac[i - 1] return fac def c(n, m): return fac[n] // fac[n - m] // fac[m] def solve(i, asn, b, other): res = 0 if i > b: if other > b + 1: return 0 else: t = fac[b + 1] // fac[b + 1 - other] for j in asn: if j: t //= fac[j] return t for j in range(b / i + 1): asn[i] = j res += solve(i + 1, asn, b - i * j, other + j) asn[i] = 0 return res fac = f(n) assign = [0] * (n + 10) ans = 50 while solve(50, assign, ans, 0) < 1000000: ans += 1 print(ans)
a='ala ma kota' print(a) a=u'ala ma kota' print(a) a='ala'+'ma'+'kota' print(a) print(len(a)) if(a[:1]=='a'): print(a[-4]) else: print('No nie za brdzo') print('{0}, {1}, {2}'.format(*'abc')) a = 'Psa' print('%s ma %s' % (a,a))
a = 'ala ma kota' print(a) a = u'ala ma kota' print(a) a = 'ala' + 'ma' + 'kota' print(a) print(len(a)) if a[:1] == 'a': print(a[-4]) else: print('No nie za brdzo') print('{0}, {1}, {2}'.format(*'abc')) a = 'Psa' print('%s ma %s' % (a, a))
class ElectricMotor: """A class used to model an electric motor Assumptions: - linear magnetic circuit (not considering flux dispersions and metal saturation when high currents are applied) - only viscous friction is assumed to be present (not considering Coulomb frictions) - stator is assumed to have a single coil - rotor is assumed to have a single coil Source: - Zaccarian, L. "DC motors: dynamic model and control techniques". Available at: http://homepages.laas.fr/lzaccari/seminars/DCmotors.pdf """ def __init__(self, coil_turns, coil_size, magnetic_permea, solenoid_length, solenoid_area, stator_induc, stator_resist, rotor_induc, rotor_resist, rotor_inertia, viscous_friction, load_torque, stator_current, rotor_current, rotor_speed, rotor_position): self.N = [coil_turns] self.m = [magnetic_permea] self.l = [solenoid_length] self.A = [solenoid_area] self.d = [coil_size] self.K0 = self.m[-1]*self.A[-1]/self.l[-1] self.Kphi = self.l[-1]*self.d[-1]/self.A[-1] self.K = self.Kphi[-1]*self.K0[-1]*self.N[-1] self.Le = [stator_induc] self.Re = [stator_resist] self.Ke = 1/self.Re[-1] # stator gain self.te = self.Le[-1]/self.Re[-1] # stator time constant self.La = [rotor_induc] self.Ra = [rotor_resist] self.Ka = 1/self.Ra[-1] # rotor gain self.ta = self.La[-1]/self.Ra[-1] # rotor time constant self.J = [rotor_inertia] self.F = [viscous_friction] self.Km = 1/self.F[-1] # mechanical gain self.tm = self.J[-1]/self.F[-1] # mechanical time constant self.Tl = [load_torque] # load torque exerted on the motor # state variables self.ie = [stator_current] self.ia = [rotor_current] self.w = [rotor_speed] self.omega = [rotor_position]
class Electricmotor: """A class used to model an electric motor Assumptions: - linear magnetic circuit (not considering flux dispersions and metal saturation when high currents are applied) - only viscous friction is assumed to be present (not considering Coulomb frictions) - stator is assumed to have a single coil - rotor is assumed to have a single coil Source: - Zaccarian, L. "DC motors: dynamic model and control techniques". Available at: http://homepages.laas.fr/lzaccari/seminars/DCmotors.pdf """ def __init__(self, coil_turns, coil_size, magnetic_permea, solenoid_length, solenoid_area, stator_induc, stator_resist, rotor_induc, rotor_resist, rotor_inertia, viscous_friction, load_torque, stator_current, rotor_current, rotor_speed, rotor_position): self.N = [coil_turns] self.m = [magnetic_permea] self.l = [solenoid_length] self.A = [solenoid_area] self.d = [coil_size] self.K0 = self.m[-1] * self.A[-1] / self.l[-1] self.Kphi = self.l[-1] * self.d[-1] / self.A[-1] self.K = self.Kphi[-1] * self.K0[-1] * self.N[-1] self.Le = [stator_induc] self.Re = [stator_resist] self.Ke = 1 / self.Re[-1] self.te = self.Le[-1] / self.Re[-1] self.La = [rotor_induc] self.Ra = [rotor_resist] self.Ka = 1 / self.Ra[-1] self.ta = self.La[-1] / self.Ra[-1] self.J = [rotor_inertia] self.F = [viscous_friction] self.Km = 1 / self.F[-1] self.tm = self.J[-1] / self.F[-1] self.Tl = [load_torque] self.ie = [stator_current] self.ia = [rotor_current] self.w = [rotor_speed] self.omega = [rotor_position]
scan_utility_version = '1.0.11' detect_jar = "/tmp/synopsys-detect.jar" # workflow_script = "/Users/mbrad/working/blackduck-scan-action/blackduck-rapid-scan-to-github.py" # detect_jar = "./synopsys-detect.jar" # workflow_script = "/Users/jcroall/PycharmProjects/blackduck-scan-action/blackduck-rapid-scan-to-github.py" debug = 0 # fix_pr = '' # upgrade_major = '' # comment_on_pr = '' # sarif = "blackduck-sarif.json" # incremental_results = False # upgrade_indirect = False # skip_detect = False bd = None args = None scm_provider = None pkg_files = ['pom.xml', 'package.json', 'npm-shrinkwrap.json', 'package-lock.json', 'Cargo.toml', 'Cargo.lock', 'conanfile.txt', 'environment.yml', 'pubspec.yml', 'pubspec.lock', 'gogradle.lock', 'Gopkg.lock', 'go.mod', 'vendor,json', 'vendor.conf', 'build.gradle', 'rebar.config', 'lerna.json', 'requirements.txt', 'Pipfile', 'Pipfile.lock', 'yarn.lock'] pkg_exts = ['.csproj', '.fsproj', '.vbproj', '.asaproj', '.dcproj', '.shproj', '.ccproj', '.sfproj', '.njsproj', '.vcxproj', '.vcproj', '.xproj', '.pyproj', '.hiveproj', '.pigproj', '.jsproj', '.usqlproj', '.deployproj', '.msbuildproj', '.sqlproj', '.dbproj', '.rproj', '.sln'] # baseline_comp_cache = None bdio_graph = None bdio_projects = None rapid_scan_data = None detected_package_files = None # comment_on_pr_comments = [] tool_rules = [] results = [] fix_pr_data = dict() rscan_items = [] comment_on_pr_header = "Synopsys Black Duck - Vulnerabilities Reported" github_token = '' github_repo = '' github_branch = '' github_ref = '' github_api_url = '' github_sha = '' def printdebug(dstring): if debug > 0: print(dstring)
scan_utility_version = '1.0.11' detect_jar = '/tmp/synopsys-detect.jar' debug = 0 bd = None args = None scm_provider = None pkg_files = ['pom.xml', 'package.json', 'npm-shrinkwrap.json', 'package-lock.json', 'Cargo.toml', 'Cargo.lock', 'conanfile.txt', 'environment.yml', 'pubspec.yml', 'pubspec.lock', 'gogradle.lock', 'Gopkg.lock', 'go.mod', 'vendor,json', 'vendor.conf', 'build.gradle', 'rebar.config', 'lerna.json', 'requirements.txt', 'Pipfile', 'Pipfile.lock', 'yarn.lock'] pkg_exts = ['.csproj', '.fsproj', '.vbproj', '.asaproj', '.dcproj', '.shproj', '.ccproj', '.sfproj', '.njsproj', '.vcxproj', '.vcproj', '.xproj', '.pyproj', '.hiveproj', '.pigproj', '.jsproj', '.usqlproj', '.deployproj', '.msbuildproj', '.sqlproj', '.dbproj', '.rproj', '.sln'] bdio_graph = None bdio_projects = None rapid_scan_data = None detected_package_files = None tool_rules = [] results = [] fix_pr_data = dict() rscan_items = [] comment_on_pr_header = 'Synopsys Black Duck - Vulnerabilities Reported' github_token = '' github_repo = '' github_branch = '' github_ref = '' github_api_url = '' github_sha = '' def printdebug(dstring): if debug > 0: print(dstring)
""" 230. Kth Smallest Element in a BST """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: A = [] res = self.inorder(root, A) return A[k - 1] def inorder(self, root, A): currentNode = root if root: if currentNode.left: self.inorder(currentNode.left, A) print(currentNode.val) A.append(currentNode.val) if currentNode.right: self.inorder(currentNode.right, A) return A
""" 230. Kth Smallest Element in a BST """ class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: a = [] res = self.inorder(root, A) return A[k - 1] def inorder(self, root, A): current_node = root if root: if currentNode.left: self.inorder(currentNode.left, A) print(currentNode.val) A.append(currentNode.val) if currentNode.right: self.inorder(currentNode.right, A) return A
def collateFunction(self, batch): """ Custom collate function to adjust a variable number of low-res images. Args: batch: list of imageset Returns: padded_lr_batch: tensor (B, min_L, W, H), low resolution images alpha_batch: tensor (B, min_L), low resolution indicator (0 if padded view, 1 otherwise) hr_batch: tensor (B, W, H), high resolution images hm_batch: tensor (B, W, H), high resolution status maps isn_batch: list of imageset names """ lr_batch = [] # batch of low-resolution views alpha_batch = [] # batch of indicators (0 if padded view, 1 if genuine view) hr_batch = [] # batch of high-resolution views hm_batch = [] # batch of high-resolution status maps isn_batch = [] # batch of site names train_batch = True for imageset in batch: lrs = imageset['lr'] L, H, W = lrs.shape lr_batch.append(lrs) alpha_batch.append(torch.ones(L)) hr = imageset['hr'] hr_batch.append(hr) hm_batch.append(imageset['hr_map']) isn_batch.append(imageset['name']) padded_lr_batch = lr_batch padded_lr_batch = torch.stack(padded_lr_batch, dim=0) alpha_batch = torch.stack(alpha_batch, dim=0) hr_batch = torch.stack(hr_batch, dim=0) hm_batch = torch.stack(hm_batch, dim=0) # isn_batch = torch.stack(isn_batch, dim=0) # for imageset in batch:# # lrs = imageset['lr'] # L, H, W = lrs.shape # if L >= self.min_L: # pad input to top_k # lr_batch.append(lrs[:self.min_L]) # alpha_batch.append(torch.ones(self.min_L)) # else: # pad = torch.zeros(self.min_L - L, H, W) # lr_batch.append(torch.cat([lrs, pad], dim=0)) # alpha_batch.append(torch.cat([torch.ones(L), torch.zeros(self.min_L - L)], dim=0)) # hr = imageset['hr'] # if train_batch and hr is not None: # hr_batch.append(hr) # else: # train_batch = False # hm_batch.append(imageset['hr_map']) # isn_batch.append(imageset['name']) # padded_lr_batch = torch.stack(lr_batch, dim=0) # alpha_batch = torch.stack(alpha_batch, dim=0) # if train_batch: # hr_batch = torch.stack(hr_batch, dim=0) # hm_batch = torch.stack(hm_batch, dim=0) return padded_lr_batch, alpha_batch, hr_batch, hm_batch, isn_batch
def collate_function(self, batch): """ Custom collate function to adjust a variable number of low-res images. Args: batch: list of imageset Returns: padded_lr_batch: tensor (B, min_L, W, H), low resolution images alpha_batch: tensor (B, min_L), low resolution indicator (0 if padded view, 1 otherwise) hr_batch: tensor (B, W, H), high resolution images hm_batch: tensor (B, W, H), high resolution status maps isn_batch: list of imageset names """ lr_batch = [] alpha_batch = [] hr_batch = [] hm_batch = [] isn_batch = [] train_batch = True for imageset in batch: lrs = imageset['lr'] (l, h, w) = lrs.shape lr_batch.append(lrs) alpha_batch.append(torch.ones(L)) hr = imageset['hr'] hr_batch.append(hr) hm_batch.append(imageset['hr_map']) isn_batch.append(imageset['name']) padded_lr_batch = lr_batch padded_lr_batch = torch.stack(padded_lr_batch, dim=0) alpha_batch = torch.stack(alpha_batch, dim=0) hr_batch = torch.stack(hr_batch, dim=0) hm_batch = torch.stack(hm_batch, dim=0) return (padded_lr_batch, alpha_batch, hr_batch, hm_batch, isn_batch)
destination = input() current_money = 0 while destination != 'End': vacation_money = float(input()) while current_money < vacation_money: work_money = float(input()) current_money += work_money print(f'Going to {destination}!') current_money = 0 destination = input()
destination = input() current_money = 0 while destination != 'End': vacation_money = float(input()) while current_money < vacation_money: work_money = float(input()) current_money += work_money print(f'Going to {destination}!') current_money = 0 destination = input()
"""Internal exception classes.""" class UnsatisfiableConstraint(Exception): """Raise when a specified constraint cannot be satisfied.""" pass class UnsatisfiableType(UnsatisfiableConstraint): """Raised when a type constraint cannot be satisfied.""" pass class TreeConstructionError(Exception): """Raised when a tree cannot be successfully constructed.""" pass
"""Internal exception classes.""" class Unsatisfiableconstraint(Exception): """Raise when a specified constraint cannot be satisfied.""" pass class Unsatisfiabletype(UnsatisfiableConstraint): """Raised when a type constraint cannot be satisfied.""" pass class Treeconstructionerror(Exception): """Raised when a tree cannot be successfully constructed.""" pass
class Book: def __init__(self, title, bookType): self.title = title self.bookType = bookType
class Book: def __init__(self, title, bookType): self.title = title self.bookType = bookType
XK_Aogonek = 0x1a1 XK_breve = 0x1a2 XK_Lstroke = 0x1a3 XK_Lcaron = 0x1a5 XK_Sacute = 0x1a6 XK_Scaron = 0x1a9 XK_Scedilla = 0x1aa XK_Tcaron = 0x1ab XK_Zacute = 0x1ac XK_Zcaron = 0x1ae XK_Zabovedot = 0x1af XK_aogonek = 0x1b1 XK_ogonek = 0x1b2 XK_lstroke = 0x1b3 XK_lcaron = 0x1b5 XK_sacute = 0x1b6 XK_caron = 0x1b7 XK_scaron = 0x1b9 XK_scedilla = 0x1ba XK_tcaron = 0x1bb XK_zacute = 0x1bc XK_doubleacute = 0x1bd XK_zcaron = 0x1be XK_zabovedot = 0x1bf XK_Racute = 0x1c0 XK_Abreve = 0x1c3 XK_Lacute = 0x1c5 XK_Cacute = 0x1c6 XK_Ccaron = 0x1c8 XK_Eogonek = 0x1ca XK_Ecaron = 0x1cc XK_Dcaron = 0x1cf XK_Dstroke = 0x1d0 XK_Nacute = 0x1d1 XK_Ncaron = 0x1d2 XK_Odoubleacute = 0x1d5 XK_Rcaron = 0x1d8 XK_Uring = 0x1d9 XK_Udoubleacute = 0x1db XK_Tcedilla = 0x1de XK_racute = 0x1e0 XK_abreve = 0x1e3 XK_lacute = 0x1e5 XK_cacute = 0x1e6 XK_ccaron = 0x1e8 XK_eogonek = 0x1ea XK_ecaron = 0x1ec XK_dcaron = 0x1ef XK_dstroke = 0x1f0 XK_nacute = 0x1f1 XK_ncaron = 0x1f2 XK_odoubleacute = 0x1f5 XK_udoubleacute = 0x1fb XK_rcaron = 0x1f8 XK_uring = 0x1f9 XK_tcedilla = 0x1fe XK_abovedot = 0x1ff
xk__aogonek = 417 xk_breve = 418 xk__lstroke = 419 xk__lcaron = 421 xk__sacute = 422 xk__scaron = 425 xk__scedilla = 426 xk__tcaron = 427 xk__zacute = 428 xk__zcaron = 430 xk__zabovedot = 431 xk_aogonek = 433 xk_ogonek = 434 xk_lstroke = 435 xk_lcaron = 437 xk_sacute = 438 xk_caron = 439 xk_scaron = 441 xk_scedilla = 442 xk_tcaron = 443 xk_zacute = 444 xk_doubleacute = 445 xk_zcaron = 446 xk_zabovedot = 447 xk__racute = 448 xk__abreve = 451 xk__lacute = 453 xk__cacute = 454 xk__ccaron = 456 xk__eogonek = 458 xk__ecaron = 460 xk__dcaron = 463 xk__dstroke = 464 xk__nacute = 465 xk__ncaron = 466 xk__odoubleacute = 469 xk__rcaron = 472 xk__uring = 473 xk__udoubleacute = 475 xk__tcedilla = 478 xk_racute = 480 xk_abreve = 483 xk_lacute = 485 xk_cacute = 486 xk_ccaron = 488 xk_eogonek = 490 xk_ecaron = 492 xk_dcaron = 495 xk_dstroke = 496 xk_nacute = 497 xk_ncaron = 498 xk_odoubleacute = 501 xk_udoubleacute = 507 xk_rcaron = 504 xk_uring = 505 xk_tcedilla = 510 xk_abovedot = 511
load( "//scala:scala.bzl", "scala_library", ) load( "//scala:scala_cross_version.bzl", _default_scala_version = "default_scala_version", _extract_major_version = "extract_major_version", _scala_mvn_artifact = "scala_mvn_artifact", ) load( "@io_bazel_rules_scala//scala:scala_maven_import_external.bzl", _scala_maven_import_external = "scala_maven_import_external", ) load( "//scala/private:common.bzl", "collect_jars", "create_java_provider", ) load( "//scala_proto/private:scala_proto_default_repositories.bzl", "scala_proto_default_repositories", ) load( "//scala_proto/private:scalapb_aspect.bzl", "scalapb_aspect", "ScalaPBInfo", "merge_scalapb_aspect_info", "ScalaPBAspectInfo", ) def scala_proto_repositories( scala_version = _default_scala_version(), maven_servers = ["http://central.maven.org/maven2"]): return scala_proto_default_repositories(scala_version, maven_servers) """Generate scalapb bindings for a set of proto_library targets. Example: scalapb_proto_library( name = "exampla_proto_scala", deps = ["//src/proto:example_service"] ) Args: name: A unique name for this rule deps: Proto library or java proto library (if with_java is True) targets that this rule depends on Outputs: A scala_library rule that includes the generated scalapb bindings, as well as any library dependencies needed to compile and use these. """ def _scalapb_proto_library_impl(ctx): aspect_info = merge_scalapb_aspect_info( [dep[ScalaPBAspectInfo] for dep in ctx.attr.deps], ) all_java = aspect_info.java_info return [ all_java, ScalaPBInfo(aspect_info = aspect_info), DefaultInfo(files = aspect_info.output_files), ] scalapb_proto_library = rule( implementation = _scalapb_proto_library_impl, attrs = { "deps": attr.label_list(aspects = [scalapb_aspect]) }, provides = [DefaultInfo, ScalaPBInfo, JavaInfo], )
load('//scala:scala.bzl', 'scala_library') load('//scala:scala_cross_version.bzl', _default_scala_version='default_scala_version', _extract_major_version='extract_major_version', _scala_mvn_artifact='scala_mvn_artifact') load('@io_bazel_rules_scala//scala:scala_maven_import_external.bzl', _scala_maven_import_external='scala_maven_import_external') load('//scala/private:common.bzl', 'collect_jars', 'create_java_provider') load('//scala_proto/private:scala_proto_default_repositories.bzl', 'scala_proto_default_repositories') load('//scala_proto/private:scalapb_aspect.bzl', 'scalapb_aspect', 'ScalaPBInfo', 'merge_scalapb_aspect_info', 'ScalaPBAspectInfo') def scala_proto_repositories(scala_version=_default_scala_version(), maven_servers=['http://central.maven.org/maven2']): return scala_proto_default_repositories(scala_version, maven_servers) 'Generate scalapb bindings for a set of proto_library targets.\n\nExample:\n scalapb_proto_library(\n name = "exampla_proto_scala",\n deps = ["//src/proto:example_service"]\n )\n\nArgs:\n name: A unique name for this rule\n deps: Proto library or java proto library (if with_java is True) targets that this rule depends on\n\nOutputs:\n A scala_library rule that includes the generated scalapb bindings, as\n well as any library dependencies needed to compile and use these.\n' def _scalapb_proto_library_impl(ctx): aspect_info = merge_scalapb_aspect_info([dep[ScalaPBAspectInfo] for dep in ctx.attr.deps]) all_java = aspect_info.java_info return [all_java, scala_pb_info(aspect_info=aspect_info), default_info(files=aspect_info.output_files)] scalapb_proto_library = rule(implementation=_scalapb_proto_library_impl, attrs={'deps': attr.label_list(aspects=[scalapb_aspect])}, provides=[DefaultInfo, ScalaPBInfo, JavaInfo])
def EDFB(U): if U>1: return False else: return True def SC_EDF(tasks): U=0 for itask in tasks: U+=(itask['execution']+itask['sslength'])/itask['period'] return EDFB(U)
def edfb(U): if U > 1: return False else: return True def sc_edf(tasks): u = 0 for itask in tasks: u += (itask['execution'] + itask['sslength']) / itask['period'] return edfb(U)
""" Write a Python function that takes a number as an input from the user and computes its factorial. Written by Sudipto Ghosh for the University of Delhi """ def factorial(n): """ Calculates factorial of a number Arguments: n {integer} -- input Returns: factorial {integer} """ assert n >= 0, 'invalid number' if n == 0: return 1 else: return n * factorial(n - 1) def computeFactorial(): """ Takes Argumrnts from the user and computes its factorial """ n = int(input("Enter Number: ")) nFactorial = factorial(n) print("Factorial of", n, "is", nFactorial) def main(): computeFactorial() if __name__ == "__main__": main()
""" Write a Python function that takes a number as an input from the user and computes its factorial. Written by Sudipto Ghosh for the University of Delhi """ def factorial(n): """ Calculates factorial of a number Arguments: n {integer} -- input Returns: factorial {integer} """ assert n >= 0, 'invalid number' if n == 0: return 1 else: return n * factorial(n - 1) def compute_factorial(): """ Takes Argumrnts from the user and computes its factorial """ n = int(input('Enter Number: ')) n_factorial = factorial(n) print('Factorial of', n, 'is', nFactorial) def main(): compute_factorial() if __name__ == '__main__': main()
#buffer = [0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3B, 0x2C, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3B, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x08, 0x01] #buffer = [0xB5, 0x62, 0x06, 0x11, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3E, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3E, 0x24, 0x00, 0x00, 0x16, 0x16, 0x04, 0x00, 0x04, 0xff, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x08, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00] buffer = [0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x06, 0x00] ca = 0 cb = 0 for x in range(2,len(buffer)): ca = 0xff & (ca + buffer[x]) cb = 0xff & (cb + ca) print(hex(ca)) print(hex(cb))
buffer = [181, 98, 5, 1, 2, 0, 6, 0] ca = 0 cb = 0 for x in range(2, len(buffer)): ca = 255 & ca + buffer[x] cb = 255 & cb + ca print(hex(ca)) print(hex(cb))
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: head: The first node of linked list. @return: a tree node """ def sortedListToBST(self, head): # write your code here # base case if not head: return head if not head.next: return TreeNode(head.val) # find middle position of current Linked List slow, fast = head, head.next while fast.next and fast.next.next: slow = slow.next fast = fast.next.next # create TreeNode mid = slow.next slow.next = None root = TreeNode(mid.val) # recursive case root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(mid.next) return root
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: head: The first node of linked list. @return: a tree node """ def sorted_list_to_bst(self, head): if not head: return head if not head.next: return tree_node(head.val) (slow, fast) = (head, head.next) while fast.next and fast.next.next: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None root = tree_node(mid.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(mid.next) return root
ifXTable = '.1.3.6.1.2.1.31.1.1.1' ifName = ifXTable + '.1' ifInMulticastPkts = ifXTable + '.2' ifHCInOctets = ifXTable + '.6' ifHCInUcastPkts = ifXTable + '.7' ifHCInMulticastPkts = ifXTable + '.8' ifHCInBroadcastPkts = ifXTable + '.9' ifHCOutOctets = ifXTable + '.10' ifHCOutUcastPkts = ifXTable + '.11' ifHCOutMulticastPkts = ifXTable + '.12' ifHCOutBroadcastPkts = ifXTable + '.13' ifHighSpeed = ifXTable + '.15' ifAlias = ifXTable + '.18' ifx_table_oids = [ifHCInOctets, ifHCInUcastPkts, ifHCInMulticastPkts, ifHCInBroadcastPkts, ifHCOutOctets, ifHCOutUcastPkts, ifHCOutMulticastPkts, ifHCOutBroadcastPkts, ifHighSpeed, ]
if_x_table = '.1.3.6.1.2.1.31.1.1.1' if_name = ifXTable + '.1' if_in_multicast_pkts = ifXTable + '.2' if_hc_in_octets = ifXTable + '.6' if_hc_in_ucast_pkts = ifXTable + '.7' if_hc_in_multicast_pkts = ifXTable + '.8' if_hc_in_broadcast_pkts = ifXTable + '.9' if_hc_out_octets = ifXTable + '.10' if_hc_out_ucast_pkts = ifXTable + '.11' if_hc_out_multicast_pkts = ifXTable + '.12' if_hc_out_broadcast_pkts = ifXTable + '.13' if_high_speed = ifXTable + '.15' if_alias = ifXTable + '.18' ifx_table_oids = [ifHCInOctets, ifHCInUcastPkts, ifHCInMulticastPkts, ifHCInBroadcastPkts, ifHCOutOctets, ifHCOutUcastPkts, ifHCOutMulticastPkts, ifHCOutBroadcastPkts, ifHighSpeed]
# from django.views.generic.base import View # from rest_framework.views import APIView # from django.conf import settings #!/usr/bin/env python # def func(): # fun_list = [] # for i in range(4): # def foo(x, i=i): # return x*i # fun_list.append(foo) # return fun_list # # # for m in func(): # print(m(2)) class SingleTool(object): __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance def addxnum(self,*args): my_sum = 0 for value in args: my_sum +=value return my_sum t1 = SingleTool() print(t1.addxnum(1,2,3)) print(t1) t2=SingleTool() print(t2) a = [(i-2, i-1, i) for i in range(1, 100) if i % 3 == 0] print(a) print([[x for x in range(1,100)][i:i+3] for i in range(0, 100, 3)])
class Singletool(object): __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance def addxnum(self, *args): my_sum = 0 for value in args: my_sum += value return my_sum t1 = single_tool() print(t1.addxnum(1, 2, 3)) print(t1) t2 = single_tool() print(t2) a = [(i - 2, i - 1, i) for i in range(1, 100) if i % 3 == 0] print(a) print([[x for x in range(1, 100)][i:i + 3] for i in range(0, 100, 3)])
# modifying a list in a function # Start with some designs that need to be printed. unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_models = [] # Simulate printing each design, until none are left. # Move each design to completed_models after printing. while unprinted_designs: current_design = unprinted_designs.pop() print(f"Printing model: {current_design}") completed_models.append(current_design) # Display all completed models print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_models = [] while unprinted_designs: current_design = unprinted_designs.pop() print(f'Printing model: {current_design}') completed_models.append(current_design) print('\nThe following models have been printed:') for completed_model in completed_models: print(completed_model)
def foo(): x = 1 def bar(): nonlocal x baz() print(x) def baz(): nonlocal x x = 2 bar() foo()
def foo(): x = 1 def bar(): nonlocal x baz() print(x) def baz(): nonlocal x x = 2 bar() foo()
"""Constants for the onboarding component.""" DOMAIN = "onboarding" STEP_USER = "user" STEP_CORE_CONFIG = "core_config" STEP_INTEGRATION = "integration" STEP_ANALYTICS = "analytics" STEP_MOB_INTEGRATION = "mob_integration" STEPS = [ STEP_USER, STEP_CORE_CONFIG, STEP_ANALYTICS, STEP_INTEGRATION, STEP_MOB_INTEGRATION, ] DEFAULT_AREAS = ("living_room", "kitchen", "bedroom")
"""Constants for the onboarding component.""" domain = 'onboarding' step_user = 'user' step_core_config = 'core_config' step_integration = 'integration' step_analytics = 'analytics' step_mob_integration = 'mob_integration' steps = [STEP_USER, STEP_CORE_CONFIG, STEP_ANALYTICS, STEP_INTEGRATION, STEP_MOB_INTEGRATION] default_areas = ('living_room', 'kitchen', 'bedroom')
class MovieData: def __init__(self,movie_name,imdb_id,plot,review,facts_table,comments,spans,labels,chat,chat_id): self.movie_name=movie_name self.imdb_id=imdb_id self.plot=plot self.review=review self.facts_table=facts_table self.comments=comments self.spans=spans self.labels=labels self.chat=[] if(chat is not None): self.chat.append(Chat(chat_id,chat)) class Chat: def __init__(self,chat_id,chats): self.chat=[] if(len(chats)%2!=0): le=len(chats)-1 else: le=len(chats) self.chat_id=chat_id self.encoder_chat=[] self.decoder_chat=[] try: for i in range(0, le, 2): if(i>=2): self.encoder_chat.append("<SOS> "+chats[i-2]+" <EOS>"+" <SOS> "+chats[i-1]+" <EOS> "+chats[i]) else: self.encoder_chat.append(chats[i]) self.decoder_chat.append(chats[i + 1]) self.chat.append(self.encoder_chat) self.chat.append(self.decoder_chat) except: print("Error")
class Moviedata: def __init__(self, movie_name, imdb_id, plot, review, facts_table, comments, spans, labels, chat, chat_id): self.movie_name = movie_name self.imdb_id = imdb_id self.plot = plot self.review = review self.facts_table = facts_table self.comments = comments self.spans = spans self.labels = labels self.chat = [] if chat is not None: self.chat.append(chat(chat_id, chat)) class Chat: def __init__(self, chat_id, chats): self.chat = [] if len(chats) % 2 != 0: le = len(chats) - 1 else: le = len(chats) self.chat_id = chat_id self.encoder_chat = [] self.decoder_chat = [] try: for i in range(0, le, 2): if i >= 2: self.encoder_chat.append('<SOS> ' + chats[i - 2] + ' <EOS>' + ' <SOS> ' + chats[i - 1] + ' <EOS> ' + chats[i]) else: self.encoder_chat.append(chats[i]) self.decoder_chat.append(chats[i + 1]) self.chat.append(self.encoder_chat) self.chat.append(self.decoder_chat) except: print('Error')
# Tests: # ifstmt ::= testexpr _ifstmts_jump # _ifstmts_jump ::= c_stmts_opt JUMP_FORWARD COME_FROM if True: b = False
if True: b = False
class Solution: def checkEqualTree(self, root: Optional[TreeNode]) -> bool: if not root: return False seen = set() def dfs(root: Optional[TreeNode]) -> int: if not root: return 0 sum = root.val + dfs(root.left) + dfs(root.right) seen.add(sum) return sum sum = root.val + dfs(root.left) + dfs(root.right) return sum % 2 == 0 and sum // 2 in seen
class Solution: def check_equal_tree(self, root: Optional[TreeNode]) -> bool: if not root: return False seen = set() def dfs(root: Optional[TreeNode]) -> int: if not root: return 0 sum = root.val + dfs(root.left) + dfs(root.right) seen.add(sum) return sum sum = root.val + dfs(root.left) + dfs(root.right) return sum % 2 == 0 and sum // 2 in seen
# color references: # http://rebrickable.com/colors # http://www.bricklink.com/catalogColors.asp rebrickable_color_to_bricklink = { # Solid Colors 15: (1, 'White'), 503: (49, 'Very Light Gray'), 151: (99, 'Very Light Bluish Gray'), 71: (86, 'Light Bluish Gray'), 7: (9, 'Light Gray'), 8: (10, 'Dark Gray'), 72: (85, 'Dark Bluish Gray'), 0: (11, 'Black'), 320: (59, 'Dark Red'), 4: (5, 'Red'), 216: (27, 'Rust'), 12: (25, 'Salmon'), 100: (26, 'Light Salmon'), 335: (58, 'Sand Red'), 70: (88, 'Reddish Brown'), 6: (8, 'Brown'), 308: (120, 'Dark Brown'), 28: (69, 'Dark Tan'), 19: (2, 'Tan'), 78: (90, 'Light Flesh'), 92: (28, 'Flesh'), 84: (150, 'Medium Dark Flesh'), 86: (91, 'Dark Flesh'), 450: (106, 'Fabuland Brown'), 366: (29, 'Earth Orange'), 484: (68, 'Dark Orange'), 25: (4, 'Orange'), 462: (31, 'Medium Orange'), 191: (110, 'Bright Light Orange'), 125: (32, 'Light Orange'), 68: (96, 'Very Light Orange'), 14: (3, 'Yellow'), 226: (103, 'Bright Light Yellow'), 18: (33, 'Light Yellow'), 120: (35, 'Light Lime'), 158: (158, 'Yellowish Green'), 115: (76, 'Medium Lime'), 27: (34, 'Lime'), 326: (155, 'Olive Green'), 288: (80, 'Dark Green'), 2: (6, 'Green'), 10: (36, 'Bright Green'), 74: (37, 'Medium Green'), 17: (38, 'Light Green'), 378: (48, 'Sand Green'), 3: (39, 'Dark Turquoise'), 11: (40, 'Light Turquoise'), 118: (41, 'Aqua'), 323: (152, 'Light Aqua'), 272: (63, 'Dark Blue'), 1: (7, 'Blue'), 321: (153, 'Dark Azure'), 322: (156, 'Medium Azure'), 73: (42, 'Medium Blue'), 313: (72, 'Maersk Blue'), 212: (105, 'Bright Light Blue'), 9: (62, 'Light Blue'), 232: (87, 'Sky Blue'), 379: (55, 'Sand Blue'), 112: (97, 'Blue-Violet'), 23: (109, 'Dark Blue-Violet'), 110: (43, 'Violet'), 1001: (73, 'Medium Violet'), 20: (44, 'Light Violet'), 85: (89, 'Dark Purple'), 22: (24, 'Purple'), 69: (93, 'Light Purple'), 30: (157, 'Medium Lavender'), 31: (154, 'Lavender'), 373: (54, 'Sand Purple'), 26: (71, 'Magenta'), 5: (47, 'Dark Pink'), 351: (94, 'Medium Dark Pink'), 29: (104, 'Bright Pink'), 13: (23, 'Pink'), 77: (56, 'Light Pink'), # Transparent Colors 47: (12, 'Trans-Clear'), 40: (13, 'Trans-Black'), 36: (17, 'Trans-Red'), 57: (18, 'Trans-Neon Orange'), 182: (98, 'Trans-Orange'), 54: (121, 'Trans-Neon Yellow'), 46: (19, 'Trans-Yellow'), 42: (16, 'Trans-Neon Green'), 35: (108, 'Trans-Bright Green'), 34: (20, 'Trans-Green'), 33: (14, 'Trans-Dark Blue'), 143: (74, 'Trans-Medium Blue'), 41: (15, 'Trans-Light Blue'), 43: (113, 'Trans-Very Lt Blue'), 236: (114, 'Trans-Light Purple'), 52: (51, 'Trans-Purple'), 45: (50, 'Trans-Dark Pink'), 230: (107, 'Trans-Pink'), # Chrome Colors 334: (21, 'Chrome Gold'), 383: (22, 'Chrome Silver'), 60: (57, 'Chrome Antique Brass'), 64: (122, 'Chrome Black'), 61: (52, 'Chrome Blue'), 62: (64, 'Chrome Green'), 63: (82, 'Chrome Pink'), # Pearl Colors 183: (83, 'Pearl White'), 150: (119, 'Pearl Very Light Gray'), 135: (66, 'Pearl Light Gray'), 179: (95, 'Flat Silver'), 148: (77, 'Pearl Dark Gray'), 137: (78, 'Metal Blue'), 142: (61, 'Pearl Light Gold'), 297: (115, 'Pearl Gold'), 178: (81, 'Flat Dark Gold'), 134: (84, 'Copper'), # Metallic Colors 80: (67, 'Metallic Silver'), 81: (70, 'Metallic Green'), 82: (65, 'Metallic Gold'), # Milky Colors 79: (60, 'Milky White'), 1000: (159, 'Glow in Dark White'), 21: (46, 'Glow In Dark Opaque'), 294: (118, 'Glow In Dark Trans'), # Glitter Colors 117: (101, 'Glitter Trans-Clear'), 1002: (163, 'Glitter Trans-Neon Green'), 1003: (162, 'Glitter Trans-Light Blue'), 129: (102, 'Glitter Trans-Purple'), 114: (100, 'Glitter Trans-Dark Pink'), # Speckle Colors 132: (111, 'Speckle Black-Silver'), 133: (151, 'Speckle Black-Gold'), 75: (116, 'Speckle Black-Copper'), 76: (117, 'Speckle DBGray-Silver'), # missing: (160, 'Fabuland Orange'), (161, 'Dark Yellow'), Modulex Colors 9999: (-1, '(No Color)'), -1: (-1, 'Unknown'), 89: (-1, 'Royal Blue'), # part bb556 of set 2852725 }
rebrickable_color_to_bricklink = {15: (1, 'White'), 503: (49, 'Very Light Gray'), 151: (99, 'Very Light Bluish Gray'), 71: (86, 'Light Bluish Gray'), 7: (9, 'Light Gray'), 8: (10, 'Dark Gray'), 72: (85, 'Dark Bluish Gray'), 0: (11, 'Black'), 320: (59, 'Dark Red'), 4: (5, 'Red'), 216: (27, 'Rust'), 12: (25, 'Salmon'), 100: (26, 'Light Salmon'), 335: (58, 'Sand Red'), 70: (88, 'Reddish Brown'), 6: (8, 'Brown'), 308: (120, 'Dark Brown'), 28: (69, 'Dark Tan'), 19: (2, 'Tan'), 78: (90, 'Light Flesh'), 92: (28, 'Flesh'), 84: (150, 'Medium Dark Flesh'), 86: (91, 'Dark Flesh'), 450: (106, 'Fabuland Brown'), 366: (29, 'Earth Orange'), 484: (68, 'Dark Orange'), 25: (4, 'Orange'), 462: (31, 'Medium Orange'), 191: (110, 'Bright Light Orange'), 125: (32, 'Light Orange'), 68: (96, 'Very Light Orange'), 14: (3, 'Yellow'), 226: (103, 'Bright Light Yellow'), 18: (33, 'Light Yellow'), 120: (35, 'Light Lime'), 158: (158, 'Yellowish Green'), 115: (76, 'Medium Lime'), 27: (34, 'Lime'), 326: (155, 'Olive Green'), 288: (80, 'Dark Green'), 2: (6, 'Green'), 10: (36, 'Bright Green'), 74: (37, 'Medium Green'), 17: (38, 'Light Green'), 378: (48, 'Sand Green'), 3: (39, 'Dark Turquoise'), 11: (40, 'Light Turquoise'), 118: (41, 'Aqua'), 323: (152, 'Light Aqua'), 272: (63, 'Dark Blue'), 1: (7, 'Blue'), 321: (153, 'Dark Azure'), 322: (156, 'Medium Azure'), 73: (42, 'Medium Blue'), 313: (72, 'Maersk Blue'), 212: (105, 'Bright Light Blue'), 9: (62, 'Light Blue'), 232: (87, 'Sky Blue'), 379: (55, 'Sand Blue'), 112: (97, 'Blue-Violet'), 23: (109, 'Dark Blue-Violet'), 110: (43, 'Violet'), 1001: (73, 'Medium Violet'), 20: (44, 'Light Violet'), 85: (89, 'Dark Purple'), 22: (24, 'Purple'), 69: (93, 'Light Purple'), 30: (157, 'Medium Lavender'), 31: (154, 'Lavender'), 373: (54, 'Sand Purple'), 26: (71, 'Magenta'), 5: (47, 'Dark Pink'), 351: (94, 'Medium Dark Pink'), 29: (104, 'Bright Pink'), 13: (23, 'Pink'), 77: (56, 'Light Pink'), 47: (12, 'Trans-Clear'), 40: (13, 'Trans-Black'), 36: (17, 'Trans-Red'), 57: (18, 'Trans-Neon Orange'), 182: (98, 'Trans-Orange'), 54: (121, 'Trans-Neon Yellow'), 46: (19, 'Trans-Yellow'), 42: (16, 'Trans-Neon Green'), 35: (108, 'Trans-Bright Green'), 34: (20, 'Trans-Green'), 33: (14, 'Trans-Dark Blue'), 143: (74, 'Trans-Medium Blue'), 41: (15, 'Trans-Light Blue'), 43: (113, 'Trans-Very Lt Blue'), 236: (114, 'Trans-Light Purple'), 52: (51, 'Trans-Purple'), 45: (50, 'Trans-Dark Pink'), 230: (107, 'Trans-Pink'), 334: (21, 'Chrome Gold'), 383: (22, 'Chrome Silver'), 60: (57, 'Chrome Antique Brass'), 64: (122, 'Chrome Black'), 61: (52, 'Chrome Blue'), 62: (64, 'Chrome Green'), 63: (82, 'Chrome Pink'), 183: (83, 'Pearl White'), 150: (119, 'Pearl Very Light Gray'), 135: (66, 'Pearl Light Gray'), 179: (95, 'Flat Silver'), 148: (77, 'Pearl Dark Gray'), 137: (78, 'Metal Blue'), 142: (61, 'Pearl Light Gold'), 297: (115, 'Pearl Gold'), 178: (81, 'Flat Dark Gold'), 134: (84, 'Copper'), 80: (67, 'Metallic Silver'), 81: (70, 'Metallic Green'), 82: (65, 'Metallic Gold'), 79: (60, 'Milky White'), 1000: (159, 'Glow in Dark White'), 21: (46, 'Glow In Dark Opaque'), 294: (118, 'Glow In Dark Trans'), 117: (101, 'Glitter Trans-Clear'), 1002: (163, 'Glitter Trans-Neon Green'), 1003: (162, 'Glitter Trans-Light Blue'), 129: (102, 'Glitter Trans-Purple'), 114: (100, 'Glitter Trans-Dark Pink'), 132: (111, 'Speckle Black-Silver'), 133: (151, 'Speckle Black-Gold'), 75: (116, 'Speckle Black-Copper'), 76: (117, 'Speckle DBGray-Silver'), 9999: (-1, '(No Color)'), -1: (-1, 'Unknown'), 89: (-1, 'Royal Blue')}
""" Root-level catalog interface """ class ValidationError(Exception): pass class PrivateArchive(Exception): pass class EntityNotFound(Exception): pass class NoAccessToEntity(Exception): """ Used when the actual entity is not accessible, i.e. when a ref cannot dereference itself """ pass class AbstractQuery(object): """ Not-qute-abstract base class for executing queries Query implementation must provide: - origin (property) - _iface (generator: itype) - _tm (property) a TermManager """ _validated = None ''' Overridde these methods ''' @property def origin(self): return NotImplemented def make_ref(self, entity): raise NotImplementedError def _perform_query(self, itype, attrname, exc, *args, strict=False, **kwargs): raise NotImplementedError ''' Internal workings ''' ''' Can be overridden ''' def _grounded_query(self, origin): """ Pseudo-abstract method used to construct entity references from a query that is anchored to a metaresource. must be overriden by user-facing subclasses if resources beyond self are required to answer the queries (e.g. a catalog). :param origin: :return: """ return self """ Basic "Documentary" interface implementation From JIE submitted: - get(id) - properties(id) - get item(id, item) - get reference(id) - synonyms(id-or-string) provided but not spec'd: - validate - get_uuid """ def validate(self): if self._validated is None: try: self._perform_query('basic', 'validate', ValidationError) self._validated = True except ValidationError: self._validated = False return self._validated def get(self, eid, **kwargs): """ Basic entity retrieval-- should be supported by all implementations :param eid: :param kwargs: :return: """ return self._perform_query('basic', 'get', EntityNotFound, eid, **kwargs) def properties(self, external_ref, **kwargs): """ Get an entity's list of properties :param external_ref: :param kwargs: :return: """ return self._perform_query('basic', 'properties', EntityNotFound, external_ref, **kwargs) def get_item(self, external_ref, item): """ access an entity's dictionary items :param external_ref: :param item: :return: """ ''' if hasattr(external_ref, 'external_ref'): # debounce err_str = external_ref.external_ref else: err_str = external_ref ''' return self._perform_query('basic', 'get_item', EntityNotFound, external_ref, item) def get_uuid(self, external_ref): return self._perform_query('basic', 'get_uuid', EntityNotFound, external_ref) def get_reference(self, external_ref): return self._perform_query('basic', 'get_reference', EntityNotFound, external_ref) def synonyms(self, item, **kwargs): """ Return a list of synonyms for the object -- quantity, flowable, or compartment :param item: :return: list of strings """ return self._perform_query('basic', 'synonyms', EntityNotFound, item, **kwargs)
""" Root-level catalog interface """ class Validationerror(Exception): pass class Privatearchive(Exception): pass class Entitynotfound(Exception): pass class Noaccesstoentity(Exception): """ Used when the actual entity is not accessible, i.e. when a ref cannot dereference itself """ pass class Abstractquery(object): """ Not-qute-abstract base class for executing queries Query implementation must provide: - origin (property) - _iface (generator: itype) - _tm (property) a TermManager """ _validated = None '\n Overridde these methods\n ' @property def origin(self): return NotImplemented def make_ref(self, entity): raise NotImplementedError def _perform_query(self, itype, attrname, exc, *args, strict=False, **kwargs): raise NotImplementedError '\n Internal workings\n ' '\n Can be overridden\n ' def _grounded_query(self, origin): """ Pseudo-abstract method used to construct entity references from a query that is anchored to a metaresource. must be overriden by user-facing subclasses if resources beyond self are required to answer the queries (e.g. a catalog). :param origin: :return: """ return self '\n Basic "Documentary" interface implementation\n From JIE submitted:\n - get(id)\n - properties(id)\n - get item(id, item)\n - get reference(id)\n - synonyms(id-or-string)\n provided but not spec\'d:\n - validate\n - get_uuid\n ' def validate(self): if self._validated is None: try: self._perform_query('basic', 'validate', ValidationError) self._validated = True except ValidationError: self._validated = False return self._validated def get(self, eid, **kwargs): """ Basic entity retrieval-- should be supported by all implementations :param eid: :param kwargs: :return: """ return self._perform_query('basic', 'get', EntityNotFound, eid, **kwargs) def properties(self, external_ref, **kwargs): """ Get an entity's list of properties :param external_ref: :param kwargs: :return: """ return self._perform_query('basic', 'properties', EntityNotFound, external_ref, **kwargs) def get_item(self, external_ref, item): """ access an entity's dictionary items :param external_ref: :param item: :return: """ "\n if hasattr(external_ref, 'external_ref'): # debounce\n err_str = external_ref.external_ref\n else:\n err_str = external_ref\n " return self._perform_query('basic', 'get_item', EntityNotFound, external_ref, item) def get_uuid(self, external_ref): return self._perform_query('basic', 'get_uuid', EntityNotFound, external_ref) def get_reference(self, external_ref): return self._perform_query('basic', 'get_reference', EntityNotFound, external_ref) def synonyms(self, item, **kwargs): """ Return a list of synonyms for the object -- quantity, flowable, or compartment :param item: :return: list of strings """ return self._perform_query('basic', 'synonyms', EntityNotFound, item, **kwargs)
def get_gender(sex='unknown'): if sex == 'm': sex = 'male' elif sex == 'f': sex = 'female' print(sex) get_gender('m') get_gender('f') get_gender()
def get_gender(sex='unknown'): if sex == 'm': sex = 'male' elif sex == 'f': sex = 'female' print(sex) get_gender('m') get_gender('f') get_gender()
description = 'Example Sans2D Pixel Detector Setup with Instrument View' group = 'basic' sysconfig = dict( instrument = 'sans2d', ) devices = dict( sans2d = device('nicos_demo.mantid.devices.instrument.ViewableInstrument', description = 'instrument object', responsible = 'R. Esponsible <r.esponsible@stfc.ac.uk>', instrument = 'sans2d', website = 'http://www.nicos-controls.org', operators = ['ISIS developer team'], facility = 'ISIS demo instruments', idf = 'SANS2D_Definition.xml' ), sample = device('nicos_mlz.sans1.devices.sans1_sample.Sans1Sample', description = 'sample object', ), mot_z = device('nicos.devices.generic.VirtualMotor', description = 'front detector position in the tube', abslimits = (19.281, 23.281), curvalue = 23.281, precision = 3, speed = 1, unit = 'm', fmtstr = '%.3f', ), mot_x = device('nicos.devices.generic.VirtualMotor', description = 'horizontal offset of detector', abslimits = (1.0, 5.0), speed = 0.5, unit = 'm', curvalue = 1.1, ), mot_omega = device('nicos.devices.generic.VirtualMotor', description = 'tilt of detector', abslimits = (-40, 40), speed = 1.5, unit = 'deg', curvalue = 0, fmtstr = '%.1f', ), mantid_move_det = device('nicos_demo.mantid.devices.devices.MantidTranslationDevice', args = {'RelativePosition': False, 'ComponentName': 'front-detector'}, x = 'mot_x', z = 'mot_z', lowlevel = True, ), mantid_rot_det = device('nicos_demo.mantid.devices.devices.MantidRotationDevice', args = {'RelativeRotation': False, 'ComponentName': 'front-detector'}, y = 1, angle = 'mot_omega', lowlevel = True, ), ) startupcode = ''' printinfo("============================================================") printinfo("Welcome to the Sans 2D Instrument View demo setup.") printinfo("============================================================") '''
description = 'Example Sans2D Pixel Detector Setup with Instrument View' group = 'basic' sysconfig = dict(instrument='sans2d') devices = dict(sans2d=device('nicos_demo.mantid.devices.instrument.ViewableInstrument', description='instrument object', responsible='R. Esponsible <r.esponsible@stfc.ac.uk>', instrument='sans2d', website='http://www.nicos-controls.org', operators=['ISIS developer team'], facility='ISIS demo instruments', idf='SANS2D_Definition.xml'), sample=device('nicos_mlz.sans1.devices.sans1_sample.Sans1Sample', description='sample object'), mot_z=device('nicos.devices.generic.VirtualMotor', description='front detector position in the tube', abslimits=(19.281, 23.281), curvalue=23.281, precision=3, speed=1, unit='m', fmtstr='%.3f'), mot_x=device('nicos.devices.generic.VirtualMotor', description='horizontal offset of detector', abslimits=(1.0, 5.0), speed=0.5, unit='m', curvalue=1.1), mot_omega=device('nicos.devices.generic.VirtualMotor', description='tilt of detector', abslimits=(-40, 40), speed=1.5, unit='deg', curvalue=0, fmtstr='%.1f'), mantid_move_det=device('nicos_demo.mantid.devices.devices.MantidTranslationDevice', args={'RelativePosition': False, 'ComponentName': 'front-detector'}, x='mot_x', z='mot_z', lowlevel=True), mantid_rot_det=device('nicos_demo.mantid.devices.devices.MantidRotationDevice', args={'RelativeRotation': False, 'ComponentName': 'front-detector'}, y=1, angle='mot_omega', lowlevel=True)) startupcode = '\nprintinfo("============================================================")\nprintinfo("Welcome to the Sans 2D Instrument View demo setup.")\nprintinfo("============================================================")\n'
class Student: def __init__(self,name="",roll=2): print("para init called") self.name=name self.roll_no=roll def hello(self): print("Hello this is: ",self.name) print("Your roll no. is: ",self.roll_no)
class Student: def __init__(self, name='', roll=2): print('para init called') self.name = name self.roll_no = roll def hello(self): print('Hello this is: ', self.name) print('Your roll no. is: ', self.roll_no)
description = 'pressure filter readout' group = 'lowlevel' devices = dict( # p_in_filter = device('nicos_mlz.sans1.devices.wut.WutValue', # hostname = 'sans1wut-p-diff-fak40.sans1.frm2', # port = '1', # description = 'pressure in front of filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), # p_out_filter = device('nicos_mlz.sans1.devices.wut.WutValue', # hostname = 'sans1wut-p-diff-fak40.sans1.frm2', # port = '2', # description = 'pressure behind of filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), # p_diff_filter = device('nicos_mlz.sans1.devices.wut.WutDiff', # description = 'pressure in front of filter minus pressure behind filter', # dev1 = 'p_in_filter', # dev2 = 'p_out_filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), )
description = 'pressure filter readout' group = 'lowlevel' devices = dict()
#Python doesn't support Generics #you can do it like this in java or C++ or #any other Object Oriented language which supports Generics class AdvancedArithmetic(object): def divisorSum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisorSum(self, n): divisor=[] for i in range(n): x = len([i for i in range(1,n+1) if n % i]) divisor.append(x) res = sum(divisor) return res n = int(input()) my_calculator = Calculator() s = my_calculator.divisorSum(n) print("I implemented: " + type(my_calculator).__bases__[0].__name__) print(s)
class Advancedarithmetic(object): def divisor_sum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisor_sum(self, n): divisor = [] for i in range(n): x = len([i for i in range(1, n + 1) if n % i]) divisor.append(x) res = sum(divisor) return res n = int(input()) my_calculator = calculator() s = my_calculator.divisorSum(n) print('I implemented: ' + type(my_calculator).__bases__[0].__name__) print(s)
class Solution: def solve(self, nums, k): history = [nums[:]] seen = {tuple(nums)} before_cycle = [] cycle = [] while True: nums2 = [0]*8 for i in range(1,7): l = (nums[i-1] if i-1 >= 0 else 0) + (nums[i+1] if i+1 < 8 else 0) nums2[i] = 1 - l%2 nums = nums2 if tuple(nums) in seen: i = history.index(nums) before_cycle = history[:i] cycle = history[i:] break history.append(nums[:]) seen.add(tuple(nums)) return before_cycle[k] if k < len(before_cycle) else cycle[(k-len(before_cycle))%len(cycle)]
class Solution: def solve(self, nums, k): history = [nums[:]] seen = {tuple(nums)} before_cycle = [] cycle = [] while True: nums2 = [0] * 8 for i in range(1, 7): l = (nums[i - 1] if i - 1 >= 0 else 0) + (nums[i + 1] if i + 1 < 8 else 0) nums2[i] = 1 - l % 2 nums = nums2 if tuple(nums) in seen: i = history.index(nums) before_cycle = history[:i] cycle = history[i:] break history.append(nums[:]) seen.add(tuple(nums)) return before_cycle[k] if k < len(before_cycle) else cycle[(k - len(before_cycle)) % len(cycle)]
expected_output = { "Tunnel10": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "17:00:12", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "ipv4": { "1.1.1.3/24": { "ip": "1.1.1.3", "prefix_length": "24" }, }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9980, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "1.1.10.11", "tunnel_protocol": "AURP", "tunnel_receive_bandwidth": 1000000, "tunnel_source_ip": "1.1.10.10", "tunnel_transmit_bandwidth": 10000000, "tunnel_transport_mtu": 1480, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel4": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:02:56", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "192.168.1.100", "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel5": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:01:30", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "7.7.7.8", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "7.7.7.7", "tunnel_source_interface": 'Loopback100', "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel6": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:00:38", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "1.2.3.4", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "UNKNOWN", "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel7": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:00:45", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "9.45.21.231", "tunnel_source_interface": 'GigabitEthernet2', "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" } }
expected_output = {'Tunnel10': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clear': '17:00:12', 'out_broadcast_pkts': 0, 'out_buffer_failure': 0, 'out_buffers_swapped': 0, 'out_collision': 0, 'out_errors': 0, 'out_interface_resets': 0, 'out_multicast_pkts': 0, 'out_octets': 0, 'out_pkts': 0, 'out_underruns': 0, 'out_unknown_protocl_drops': 0, 'rate': {'in_rate': 0, 'in_rate_pkts': 0, 'load_interval': 300, 'out_rate': 0, 'out_rate_pkts': 0}}, 'delay': 50000, 'enabled': True, 'encapsulations': {'encapsulation': 'tunnel'}, 'ipv4': {'1.1.1.3/24': {'ip': '1.1.1.3', 'prefix_length': '24'}}, 'last_input': 'never', 'last_output': 'never', 'line_protocol': 'down', 'mtu': 9980, 'oper_status': 'down', 'output_hang': 'never', 'port_channel': {'port_channel_member': False}, 'queues': {'input_queue_drops': 0, 'input_queue_flushes': 0, 'input_queue_max': 375, 'input_queue_size': 0, 'output_queue_max': 0, 'output_queue_size': 0, 'queue_strategy': 'fifo', 'total_output_drop': 0}, 'reliability': '255/255', 'rxload': '1/255', 'tunnel_destination_ip': '1.1.10.11', 'tunnel_protocol': 'AURP', 'tunnel_receive_bandwidth': 1000000, 'tunnel_source_ip': '1.1.10.10', 'tunnel_transmit_bandwidth': 10000000, 'tunnel_transport_mtu': 1480, 'tunnel_ttl': 255, 'txload': '1/255', 'type': 'Tunnel'}, 'Tunnel4': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clear': '00:02:56', 'out_broadcast_pkts': 0, 'out_buffer_failure': 0, 'out_buffers_swapped': 0, 'out_collision': 0, 'out_errors': 0, 'out_interface_resets': 0, 'out_multicast_pkts': 0, 'out_octets': 0, 'out_pkts': 0, 'out_underruns': 0, 'out_unknown_protocl_drops': 0, 'rate': {'in_rate': 0, 'in_rate_pkts': 0, 'load_interval': 300, 'out_rate': 0, 'out_rate_pkts': 0}}, 'delay': 50000, 'enabled': True, 'encapsulations': {'encapsulation': 'tunnel'}, 'last_input': 'never', 'last_output': 'never', 'line_protocol': 'down', 'mtu': 9976, 'oper_status': 'down', 'output_hang': 'never', 'port_channel': {'port_channel_member': False}, 'queues': {'input_queue_drops': 0, 'input_queue_flushes': 0, 'input_queue_max': 375, 'input_queue_size': 0, 'output_queue_max': 0, 'output_queue_size': 0, 'queue_strategy': 'fifo', 'total_output_drop': 0}, 'reliability': '255/255', 'rxload': '1/255', 'tunnel_protocol': 'GRE/IP', 'tunnel_receive_bandwidth': 8000, 'tunnel_source_ip': '192.168.1.100', 'tunnel_transmit_bandwidth': 8000, 'tunnel_transport_mtu': 1476, 'tunnel_ttl': 255, 'txload': '1/255', 'type': 'Tunnel'}, 'Tunnel5': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clear': '00:01:30', 'out_broadcast_pkts': 0, 'out_buffer_failure': 0, 'out_buffers_swapped': 0, 'out_collision': 0, 'out_errors': 0, 'out_interface_resets': 0, 'out_multicast_pkts': 0, 'out_octets': 0, 'out_pkts': 0, 'out_underruns': 0, 'out_unknown_protocl_drops': 0, 'rate': {'in_rate': 0, 'in_rate_pkts': 0, 'load_interval': 300, 'out_rate': 0, 'out_rate_pkts': 0}}, 'delay': 50000, 'enabled': True, 'encapsulations': {'encapsulation': 'tunnel'}, 'last_input': 'never', 'last_output': 'never', 'line_protocol': 'down', 'mtu': 9976, 'oper_status': 'down', 'output_hang': 'never', 'port_channel': {'port_channel_member': False}, 'queues': {'input_queue_drops': 0, 'input_queue_flushes': 0, 'input_queue_max': 375, 'input_queue_size': 0, 'output_queue_max': 0, 'output_queue_size': 0, 'queue_strategy': 'fifo', 'total_output_drop': 0}, 'reliability': '255/255', 'rxload': '1/255', 'tunnel_destination_ip': '7.7.7.8', 'tunnel_protocol': 'GRE/IP', 'tunnel_receive_bandwidth': 8000, 'tunnel_source_ip': '7.7.7.7', 'tunnel_source_interface': 'Loopback100', 'tunnel_transmit_bandwidth': 8000, 'tunnel_transport_mtu': 1476, 'tunnel_ttl': 255, 'txload': '1/255', 'type': 'Tunnel'}, 'Tunnel6': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clear': '00:00:38', 'out_broadcast_pkts': 0, 'out_buffer_failure': 0, 'out_buffers_swapped': 0, 'out_collision': 0, 'out_errors': 0, 'out_interface_resets': 0, 'out_multicast_pkts': 0, 'out_octets': 0, 'out_pkts': 0, 'out_underruns': 0, 'out_unknown_protocl_drops': 0, 'rate': {'in_rate': 0, 'in_rate_pkts': 0, 'load_interval': 300, 'out_rate': 0, 'out_rate_pkts': 0}}, 'delay': 50000, 'enabled': True, 'encapsulations': {'encapsulation': 'tunnel'}, 'last_input': 'never', 'last_output': 'never', 'line_protocol': 'down', 'mtu': 9976, 'oper_status': 'down', 'output_hang': 'never', 'port_channel': {'port_channel_member': False}, 'queues': {'input_queue_drops': 0, 'input_queue_flushes': 0, 'input_queue_max': 375, 'input_queue_size': 0, 'output_queue_max': 0, 'output_queue_size': 0, 'queue_strategy': 'fifo', 'total_output_drop': 0}, 'reliability': '255/255', 'rxload': '1/255', 'tunnel_destination_ip': '1.2.3.4', 'tunnel_protocol': 'GRE/IP', 'tunnel_receive_bandwidth': 8000, 'tunnel_source_ip': 'UNKNOWN', 'tunnel_transmit_bandwidth': 8000, 'tunnel_transport_mtu': 1476, 'tunnel_ttl': 255, 'txload': '1/255', 'type': 'Tunnel'}, 'Tunnel7': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clear': '00:00:45', 'out_broadcast_pkts': 0, 'out_buffer_failure': 0, 'out_buffers_swapped': 0, 'out_collision': 0, 'out_errors': 0, 'out_interface_resets': 0, 'out_multicast_pkts': 0, 'out_octets': 0, 'out_pkts': 0, 'out_underruns': 0, 'out_unknown_protocl_drops': 0, 'rate': {'in_rate': 0, 'in_rate_pkts': 0, 'load_interval': 300, 'out_rate': 0, 'out_rate_pkts': 0}}, 'delay': 50000, 'enabled': True, 'encapsulations': {'encapsulation': 'tunnel'}, 'last_input': 'never', 'last_output': 'never', 'line_protocol': 'down', 'mtu': 9976, 'oper_status': 'down', 'output_hang': 'never', 'port_channel': {'port_channel_member': False}, 'queues': {'input_queue_drops': 0, 'input_queue_flushes': 0, 'input_queue_max': 375, 'input_queue_size': 0, 'output_queue_max': 0, 'output_queue_size': 0, 'queue_strategy': 'fifo', 'total_output_drop': 0}, 'reliability': '255/255', 'rxload': '1/255', 'tunnel_protocol': 'GRE/IP', 'tunnel_receive_bandwidth': 8000, 'tunnel_source_ip': '9.45.21.231', 'tunnel_source_interface': 'GigabitEthernet2', 'tunnel_transmit_bandwidth': 8000, 'tunnel_transport_mtu': 1476, 'tunnel_ttl': 255, 'txload': '1/255', 'type': 'Tunnel'}}
input = open('input.txt'); length = int(input.readline()); tokens = input.readline().split(' '); input.close(); output = open('output.txt' , 'w'); i = 0; while i < length: j = 0; while (int(tokens[i]) >= int(tokens[j])) & (j < i): j += 1; if j < i: shelf = tokens[i]; k = i; while k > j: tokens[k] = tokens[k - 1]; k -= 1; tokens[j] = shelf; output.write(str(j + 1) + ' '); else: output.write(str(i + 1) + ' '); i += 1; output.write('\n'); for element in tokens: output.write(element + ' '); output.close();
input = open('input.txt') length = int(input.readline()) tokens = input.readline().split(' ') input.close() output = open('output.txt', 'w') i = 0 while i < length: j = 0 while (int(tokens[i]) >= int(tokens[j])) & (j < i): j += 1 if j < i: shelf = tokens[i] k = i while k > j: tokens[k] = tokens[k - 1] k -= 1 tokens[j] = shelf output.write(str(j + 1) + ' ') else: output.write(str(i + 1) + ' ') i += 1 output.write('\n') for element in tokens: output.write(element + ' ') output.close()
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. ''' """ Python Kerberos GSS APIs used by spnego_kerberos_auth.py. It is used as a place holder for kerberos.py which is not available. """ class KrbError(Exception): pass class GSSError(KrbError): pass def authGSSClientInit(service): pass def authGSSClientClean(context): pass def authGSSClientStep(context, challenge): pass def authGSSClientResponse(context): pass
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. """ '\nPython Kerberos GSS APIs used by spnego_kerberos_auth.py.\nIt is used as a place holder for kerberos.py which is not available.\n' class Krberror(Exception): pass class Gsserror(KrbError): pass def auth_gss_client_init(service): pass def auth_gss_client_clean(context): pass def auth_gss_client_step(context, challenge): pass def auth_gss_client_response(context): pass
expected_output = { "ospf-database-information": { "ospf-area-header": {"ospf-area": "192.168.76.0"}, "ospf-database": { "@heading": "Type ID Adv Rtr Seq Age Opt Cksum Len", "advertising-router": "192.168.219.235", "age": "1730", "checksum": "0x1b56", "lsa-id": "10.69.197.1", "lsa-length": "36", "lsa-type": "Network", "options": "0x22", "ospf-network-lsa": { "address-mask": "255.255.255.128", "attached-router": [ "192.168.219.235", "10.69.198.249", "192.168.219.236", ], "ospf-lsa-topology": { "ospf-lsa-topology-link": [ { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "192.168.219.236", "ospf-lsa-topology-link-state": "Bidirectional", }, { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "10.69.198.249", "ospf-lsa-topology-link-state": "Bidirectional", }, { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "192.168.219.235", "ospf-lsa-topology-link-state": "Bidirectional", }, ], "ospf-topology-id": "default", "ospf-topology-name": "default", }, }, "our-entry": True, "sequence-number": "0x80000026", }, } }
expected_output = {'ospf-database-information': {'ospf-area-header': {'ospf-area': '192.168.76.0'}, 'ospf-database': {'@heading': 'Type ID Adv Rtr Seq Age Opt Cksum Len', 'advertising-router': '192.168.219.235', 'age': '1730', 'checksum': '0x1b56', 'lsa-id': '10.69.197.1', 'lsa-length': '36', 'lsa-type': 'Network', 'options': '0x22', 'ospf-network-lsa': {'address-mask': '255.255.255.128', 'attached-router': ['192.168.219.235', '10.69.198.249', '192.168.219.236'], 'ospf-lsa-topology': {'ospf-lsa-topology-link': [{'link-type-name': 'Transit', 'ospf-lsa-topology-link-metric': '0', 'ospf-lsa-topology-link-node-id': '192.168.219.236', 'ospf-lsa-topology-link-state': 'Bidirectional'}, {'link-type-name': 'Transit', 'ospf-lsa-topology-link-metric': '0', 'ospf-lsa-topology-link-node-id': '10.69.198.249', 'ospf-lsa-topology-link-state': 'Bidirectional'}, {'link-type-name': 'Transit', 'ospf-lsa-topology-link-metric': '0', 'ospf-lsa-topology-link-node-id': '192.168.219.235', 'ospf-lsa-topology-link-state': 'Bidirectional'}], 'ospf-topology-id': 'default', 'ospf-topology-name': 'default'}}, 'our-entry': True, 'sequence-number': '0x80000026'}}}
# 1.Why carry is a&b: # If a and b are both 1 at the same digit, it creates one carry. # Because you can only use 0 and 1 in binary, if you add 1+1 together, it will roll that over to the next digit, and the value will be 0 at this digit. # if they are both 0 or only one is 1, it doesn't need to carry. # Use ^ operation between a and b to find the different bit # In my understanding, using ^ operator is kind of adding a and b together (a+b) but ignore the digit that a and b are both 1, # because we already took care of this in step1. class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ INFINITY = 0xffffffff while b & INFINITY != 0: carry = (a & b) << 1 a = a ^ b b = carry # for overflow condition like # -1 # 1 return (a & INFINITY) if b > INFINITY else a sol = Solution() output = sol.getSum(-1, 1) print('Res: ', output)
class Solution(object): def get_sum(self, a, b): """ :type a: int :type b: int :rtype: int """ infinity = 4294967295 while b & INFINITY != 0: carry = (a & b) << 1 a = a ^ b b = carry return a & INFINITY if b > INFINITY else a sol = solution() output = sol.getSum(-1, 1) print('Res: ', output)
while True: h = int(input()) if h == 0: break arr = list() arr.append(h) while h != 1: if h%2 == 0: h = int((0.5)*h) arr.append(h) else: h = 3 * h + 1 arr.append(h) # print(arr) print(max(arr))
while True: h = int(input()) if h == 0: break arr = list() arr.append(h) while h != 1: if h % 2 == 0: h = int(0.5 * h) arr.append(h) else: h = 3 * h + 1 arr.append(h) print(max(arr))
def read_input(): row, col = [int(x) for x in input().split()] arr = [list(input()) for _ in range(row)] return arr def print_output(obj): for i in obj: print(''.join(i)) def test_pos(obj, grid, row, col): for i in range(len(obj)): for j in range(len(obj[0])): if grid[row + i][col + j] != '.' and obj[i][j] != '.': return False return True def place_at_pos(obj, grid, row, col): arr = grid for i in range(len(obj)): for j in range(len(obj[0])): if obj[i][j] != '.': arr[row + i][col + j] = obj[i][j] return arr ob = read_input() gr = read_input() positions = [] for di in range(len(gr) - len(ob) + 1): for dj in range(len(gr[0]) - len(ob[0]) + 1): if test_pos(ob, gr, di, dj): positions.append((di, dj)) print(len(positions)) if len(positions) == 1: display = place_at_pos(ob, gr, positions[0][0], positions[0][1]) print_output(display)
def read_input(): (row, col) = [int(x) for x in input().split()] arr = [list(input()) for _ in range(row)] return arr def print_output(obj): for i in obj: print(''.join(i)) def test_pos(obj, grid, row, col): for i in range(len(obj)): for j in range(len(obj[0])): if grid[row + i][col + j] != '.' and obj[i][j] != '.': return False return True def place_at_pos(obj, grid, row, col): arr = grid for i in range(len(obj)): for j in range(len(obj[0])): if obj[i][j] != '.': arr[row + i][col + j] = obj[i][j] return arr ob = read_input() gr = read_input() positions = [] for di in range(len(gr) - len(ob) + 1): for dj in range(len(gr[0]) - len(ob[0]) + 1): if test_pos(ob, gr, di, dj): positions.append((di, dj)) print(len(positions)) if len(positions) == 1: display = place_at_pos(ob, gr, positions[0][0], positions[0][1]) print_output(display)
# import pytest class TestSingletonMeta: def test___call__(self): # synced assert True class TestSingleton: pass
class Testsingletonmeta: def test___call__(self): assert True class Testsingleton: pass
i = 0 result = 0 while i <= 100: if i % 2 == 0: result += i i += 1 print(result) j = 0 result2 = 0 while j <= 100: result2 += j j += 2 print(result2)
i = 0 result = 0 while i <= 100: if i % 2 == 0: result += i i += 1 print(result) j = 0 result2 = 0 while j <= 100: result2 += j j += 2 print(result2)
# test for PR#112 -- functions should not have __module__ attributes def f(): pass if hasattr(f, '__module__'): print('functions should not have __module__ attributes') # but make sure classes still do have __module__ attributes class F: pass if not hasattr(F, '__module__'): print('classes should still have __module__ attributes')
def f(): pass if hasattr(f, '__module__'): print('functions should not have __module__ attributes') class F: pass if not hasattr(F, '__module__'): print('classes should still have __module__ attributes')