content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Car(object): """A car class""" def __init__(self, model, make, color): self.model = model self.make = make self.color = color self.price = None def get_price(self): return self.price def set_price(self, value): self.price = value availableCars = [] def main(): global availableCars #Create a new car obj carObj = Car("Maruti SX4", "2011", "Black") carObj.set_price(950000) # Set price # Add this to available cars availableCars.append(carObj) print('TEST SUCEEDED') if __name__ == '__main__': main()
class Car(object): """A car class""" def __init__(self, model, make, color): self.model = model self.make = make self.color = color self.price = None def get_price(self): return self.price def set_price(self, value): self.price = value available_cars = [] def main(): global availableCars car_obj = car('Maruti SX4', '2011', 'Black') carObj.set_price(950000) availableCars.append(carObj) print('TEST SUCEEDED') if __name__ == '__main__': main()
""" URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/ Problem Statement: ------------------ Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. Example 1: Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5] Example 2: Input: head = [], val = 1 Output: [] Example 3: Input: head = [7,7,7,7], val = 7 Output: [] Constraints: The number of nodes in the list is in the range [0, 104]. 1 <= Node.val <= 50 0 <= val <= 50 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: """Approach 1: Creating new ListNode""" # if head is None: # return head # node = ListNode(-1) # itt = node # while head is not None: # if head.val != val: # itt.next = ListNode(head.val) # itt = itt.next # head = head.next # return node.next """Approach 2: Updating existing Linked List""" node = ListNode(-1) node.next = head head = node while head and head.next: if head.next.val == val: head.next = head.next.next else: head = head.next return node.next head = ListNode(1) head.next = ListNode(6) # head.next.next = ListNode(3) # head.next.next.next = ListNode(6) # head.next.next.next.next = ListNode(5) Solution().removeElements(head=head, val=6)
""" URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/ Problem Statement: ------------------ Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. Example 1: Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5] Example 2: Input: head = [], val = 1 Output: [] Example 3: Input: head = [7,7,7,7], val = 7 Output: [] Constraints: The number of nodes in the list is in the range [0, 104]. 1 <= Node.val <= 50 0 <= val <= 50 """ class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def remove_elements(self, head: ListNode, val: int) -> ListNode: """Approach 1: Creating new ListNode""" 'Approach 2: Updating existing Linked List' node = list_node(-1) node.next = head head = node while head and head.next: if head.next.val == val: head.next = head.next.next else: head = head.next return node.next head = list_node(1) head.next = list_node(6) solution().removeElements(head=head, val=6)
class Solution: def __init__(self): self.ret = [] def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ # dp[i][j] means starting from [i for j ele can be slice dp = [[0 for _ in range(len(s)+1)] for _ in range(len(s)+1)] for j in range(1, len(s)+1): for i in range(len(s)-j+1): if s[i:i+j] in wordDict: dp[i][j] = 1 else: for k in range(i, i+j): if dp[i][k] != 0 and dp[i+k][j-k] != 0: dp[i][j] = 2 if dp[0][len(s)] == 0: return self.ret curr = [] self.dfs(s, curr, 0, dp) return self.ret def dfs(self, s, curr, start, dp): if start == len(s): self.ret.append(" ".join(curr)) return for i in range(1, len(s)-start+1): if dp[start][i] == 1: curr.append(s[start:start+i]) self.dfs(s, curr, start+i, dp) curr.pop() sl = Solution() s = "catsanddog" wordDict = ["cats", "dog", "sand", "and", "cat"] print(sl.wordBreak(s, wordDict))
class Solution: def __init__(self): self.ret = [] def word_break(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)] for j in range(1, len(s) + 1): for i in range(len(s) - j + 1): if s[i:i + j] in wordDict: dp[i][j] = 1 else: for k in range(i, i + j): if dp[i][k] != 0 and dp[i + k][j - k] != 0: dp[i][j] = 2 if dp[0][len(s)] == 0: return self.ret curr = [] self.dfs(s, curr, 0, dp) return self.ret def dfs(self, s, curr, start, dp): if start == len(s): self.ret.append(' '.join(curr)) return for i in range(1, len(s) - start + 1): if dp[start][i] == 1: curr.append(s[start:start + i]) self.dfs(s, curr, start + i, dp) curr.pop() sl = solution() s = 'catsanddog' word_dict = ['cats', 'dog', 'sand', 'and', 'cat'] print(sl.wordBreak(s, wordDict))
password = input() alpha = False upalpha = False digit = False for i in password: if i.isspace(): print("NOPE") break if i.isdigit(): digit = True if i.isalpha(): if i.isupper(): upalpha = True if i.islower(): alpha = True else: if alpha and upalpha and digit: print("OK") else: print("NOPE")
password = input() alpha = False upalpha = False digit = False for i in password: if i.isspace(): print('NOPE') break if i.isdigit(): digit = True if i.isalpha(): if i.isupper(): upalpha = True if i.islower(): alpha = True else: if alpha and upalpha and digit: print('OK') else: print('NOPE')
""" Best Solution Space : O(1) Time : O(n log n) """ class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: A.sort() ans = A[-1] - A[0] for x, y in zip(A, A[1:]): ans = min(ans, max(A[-1]-K, x+K) - min(A[0]+K, y-K)) return ans
""" Best Solution Space : O(1) Time : O(n log n) """ class Solution: def smallest_range_ii(self, A: List[int], K: int) -> int: A.sort() ans = A[-1] - A[0] for (x, y) in zip(A, A[1:]): ans = min(ans, max(A[-1] - K, x + K) - min(A[0] + K, y - K)) return ans
########################### # 6.0002 Problem Set 1b: Space Change # Name: # Collaborators: # Time: # Author: charz, cdenise #================================ # Part B: Golden Eggs #================================ # Problem 1 # Method 1 # def dp_make_weight(egg_weights, target_weight, memo = {}): # """ # Find number of eggs to bring back, using the smallest number of eggs. Assumes there is # an infinite supply of eggs of each weight, and there is always a egg of value 1. # Parameters: # egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk) # target_weight - int, amount of weight we want to find eggs to fit # memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation) # Returns: int, smallest number of eggs needed to make target weight # """ # # TODO: Your code here # # sorted tuple # egg_weights = tuple(sorted(egg_weights, reverse=True)) # # initiate result of zero egg # if egg_weights == () or target_weight == 0: # result = 0 # # explore right branch if first item > target weight # elif egg_weights[0] > target_weight: # result = dp_make_weight(egg_weights[1:],target_weight, memo) # # explore left branch if first item < target weight # else: # next_egg_to_consider = egg_weights[0] # # explore right branch if take next egg # n_eggs_next_taken = dp_make_weight(egg_weights[1:], # target_weight%next_egg_to_consider, # memo) # n_eggs_next_taken += (target_weight//next_egg_to_consider) # # explore left branch if not take any next egg # n_eggs_next_not = dp_make_weight(egg_weights[1:], target_weight, memo) # if target_weight%next_egg_to_consider >= 0: # result = n_eggs_next_taken # else: # result = n_eggs_next_not # return result # Method 2 (dynamic programming) # https://stackoverflow.com/questions/61642912 def dp_make_weight(egg_weights, target_weight, memo={}): # base case target weight < 0 least_taken = float("inf") # base case target weight == 0 if target_weight == 0: return 0 # recall stored key in dict elif target_weight in memo: return memo[target_weight] # recursive case elif target_weight > 0: for weight in egg_weights: sub_result = dp_make_weight(egg_weights, target_weight - weight) least_taken = min(least_taken, sub_result) # add 1 for current egg taken memo[target_weight] = least_taken + 1 print(memo) return least_taken + 1 # EXAMPLE TESTING CODE, feel free to add more if you'd like if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight(egg_weights, n)) print()
def dp_make_weight(egg_weights, target_weight, memo={}): least_taken = float('inf') if target_weight == 0: return 0 elif target_weight in memo: return memo[target_weight] elif target_weight > 0: for weight in egg_weights: sub_result = dp_make_weight(egg_weights, target_weight - weight) least_taken = min(least_taken, sub_result) memo[target_weight] = least_taken + 1 print(memo) return least_taken + 1 if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print('Egg weights = (1, 5, 10, 25)') print('n = 99') print('Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)') print('Actual output:', dp_make_weight(egg_weights, n)) print()
"""Miscellaneous stuff for Coverage.""" def nice_pair(pair): """Make a nice string representation of a pair of numbers. If the numbers are equal, just return the number, otherwise return the pair with a dash between them, indicating the range. """ start, end = pair if start == end: return "%d" % start else: return "%d-%d" % (start, end) def format_lines(statements, lines): """Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14". """ pairs = [] i = 0 j = 0 start = None while i < len(statements) and j < len(lines): if statements[i] == lines[j]: if start == None: start = lines[j] end = lines[j] j += 1 elif start: pairs.append((start, end)) start = None i += 1 if start: pairs.append((start, end)) ret = ', '.join(map(nice_pair, pairs)) return ret def expensive(fn): """A decorator to cache the result of an expensive operation. Only applies to methods with no arguments. """ attr = "_cache_" + fn.__name__ def _wrapped(self): """Inner fn that checks the cache.""" if not hasattr(self, attr): setattr(self, attr, fn(self)) return getattr(self, attr) return _wrapped class CoverageException(Exception): """An exception specific to Coverage.""" pass class NoSource(CoverageException): """Used to indicate we couldn't find the source for a module.""" pass
"""Miscellaneous stuff for Coverage.""" def nice_pair(pair): """Make a nice string representation of a pair of numbers. If the numbers are equal, just return the number, otherwise return the pair with a dash between them, indicating the range. """ (start, end) = pair if start == end: return '%d' % start else: return '%d-%d' % (start, end) def format_lines(statements, lines): """Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14". """ pairs = [] i = 0 j = 0 start = None while i < len(statements) and j < len(lines): if statements[i] == lines[j]: if start == None: start = lines[j] end = lines[j] j += 1 elif start: pairs.append((start, end)) start = None i += 1 if start: pairs.append((start, end)) ret = ', '.join(map(nice_pair, pairs)) return ret def expensive(fn): """A decorator to cache the result of an expensive operation. Only applies to methods with no arguments. """ attr = '_cache_' + fn.__name__ def _wrapped(self): """Inner fn that checks the cache.""" if not hasattr(self, attr): setattr(self, attr, fn(self)) return getattr(self, attr) return _wrapped class Coverageexception(Exception): """An exception specific to Coverage.""" pass class Nosource(CoverageException): """Used to indicate we couldn't find the source for a module.""" pass
# Ideas """ server = dkeras.DataServer() model1.link(model3) model1.postprocess = lambda z: np.float16(z) server = model1 + model2 + model3 server.add(camera1, dest=('m1', 'm2')) server.add_address('192.168.1.42') """
""" server = dkeras.DataServer() model1.link(model3) model1.postprocess = lambda z: np.float16(z) server = model1 + model2 + model3 server.add(camera1, dest=('m1', 'm2')) server.add_address('192.168.1.42') """
#!/usr/bin/env python3 class IndexCreator: def __init__(self): self._index = 0 def generate(self): r = self._index self._index += 1 return r def clear(self): self._index = 0 if __name__ == "__main__": i = IndexCreator() print(i.generate(), i.generate(), i.generate(), i.generate()) i.clear() print(i.generate(), i.generate(), i.generate(), i.generate())
class Indexcreator: def __init__(self): self._index = 0 def generate(self): r = self._index self._index += 1 return r def clear(self): self._index = 0 if __name__ == '__main__': i = index_creator() print(i.generate(), i.generate(), i.generate(), i.generate()) i.clear() print(i.generate(), i.generate(), i.generate(), i.generate())
#Drinklist by Danzibob Credits to him! drink_list = [{ 'name': 'Vesper', 'ingredients': { 'gin': 60, 'vodka': 15.0, 'vermouth': 7.5 }, }, { 'name': 'Bacardi', 'ingredients': { 'whiteRum': 45.0, 'lij': 20, 'grenadine': 10 }, }, { 'name': 'Kryptonite', 'ingredients': { 'vodka': 8.0, 'whiskey': 7.0, 'lej': 6.0, 'oj': 5.0, 'grenadine': 4.0, 'cj': 3.0, 'rum': 2.0, 'vermouth': 1.0 }, }, { 'name': 'Vodka', 'ingredients': { 'vodka': 10.0, }, }, { 'name': 'Whiskey', 'ingredients': { 'whiskey': 10.0, }, }, { 'name': 'Lemon Juice', 'ingredients': { 'lej': 10.0, }, }, { 'name': 'Orange Juice', 'ingredients': { 'oj': 10.0, }, }, { 'name': 'Grenadine', 'ingredients': { 'grenadine': 10.0, }, }, { 'name': 'Cranberry Juice', 'ingredients': { 'cj': 10.0, }, }, { 'name': 'Rum', 'ingredients': { 'rum': 10.0, }, }, { 'name': 'Vermouth', 'ingredients': { 'vermouth': 10.0 }, }, { 'name': 'Negroni', 'ingredients': { 'gin': 30, 'campari': 30, 'vermouth': 30 }, }, { 'name': 'Rose', 'ingredients': { 'cherryBrandy': 20, 'vermouth': 40 }, }, { 'name': 'Old Fashioned', 'ingredients': { 'whiskey': 45.0 }, }, { 'name': 'Tuxedo', 'ingredients': { 'gin': 30, 'vermouth': 30 }, }, { 'name': 'Mojito', 'ingredients': { 'whiteRum': 40, 'lij': 30 }, }, { 'name': "Horse's Neck", 'ingredients': { 'brandy': 40, 'gingerAle': 120 }, }, { 'name': "Planter's Punch", 'ingredients': { 'darkRum': 45.0, 'oj': 35.0, 'pj': 35.0, 'lej': 20, 'grenadine': 10 }, }, { 'name': 'Sea Breeze', 'ingredients': { 'vodka': 40, 'cj': 120, 'gj': 30 }, }, { 'name': 'Pisco Sour', 'ingredients': { 'brandy': 45.0, 'lej': 30, 'grenadine': 20 }, }, { 'name': 'Long Island Iced Tea', 'ingredients': { 'tequila': 15.0, 'vodka': 15.0, 'whiteRum': 15.0, 'tripSec': 15.0, 'gin': 15.0, 'lej': 25.0, 'grenadine': 30.0 }, }, { 'name': 'Clover Club', 'ingredients': { 'gin': 45.0, 'grenadine': 15.0, 'lej': 15.0 }, }, { 'name': 'Angel Face', 'ingredients': { 'gin': 30, 'apricotBrandy': 30, 'appleBrandy': 30 }, }, { 'name': 'Mimosa', 'ingredients': { 'champagne': 75.0, 'oj': 75.0 }, }, { 'name': 'Whiskey Sour', 'ingredients': { 'whiskey': 45.0, 'lej': 30.0, 'grenadine': 15.0 }, }, { 'name': 'Screwdriver', 'ingredients': { 'vodka': 50, 'oj': 100 }, }, { 'name': 'Cuba Libre', 'ingredients': { 'whiteRum': 50, 'cola': 120, 'lij': 10 }, }, { 'name': 'Manhattan', 'ingredients': { 'whiskey': 50, 'vermouth': 20 }, }, { 'name': 'Porto Flip', 'ingredients': { 'brandy': 15.0, 'port': 45.0, 'eggYolk': 10 }, }, { 'name': 'Gin Fizz', 'ingredients': { 'gin': 45.0, 'lej': 30, 'grenadine': 10, 'soda': 80 }, }, { 'name': 'Espresso Martini', 'ingredients': { 'vodka': 50, 'coffeeLiqueur': 10 }, }, { 'name': 'Margarita', 'ingredients': { 'tequila': 35.0, 'tripSec': 20, 'lij': 15.0 }, }, { 'name': 'French 75', 'ingredients': { 'gin': 30, 'lej': 15.0, 'champagne': 60 }, }, { 'name': 'Yellow Bird', 'ingredients': { 'whiteRum': 30, 'galliano': 15.0, 'tripSec': 15.0, 'lij': 15.0 }, }, { 'name': 'Pina Colada', 'ingredients': { 'whiteRum': 30, 'pj': 90, 'coconutMilk': 30 }, }, { 'name': 'Aviation', 'ingredients': { 'gin': 45.0, 'cherryLiqueur': 15.0, 'lej': 15.0 }, }, { 'name': 'Bellini', 'ingredients': { 'prosecco': 100, 'peachPuree': 50 }, }, { 'name': 'Grasshopper', 'ingredients': { 'cremeCacao': 30, 'cream': 30 }, }, { 'name': 'Tequila Sunrise', 'ingredients': { 'tequila': 45.0, 'oj': 90, 'grenadine': 15.0 }, }, { 'name': 'Daiquiri', 'ingredients': { 'whiteRum': 45.0, 'lij': 25.0, 'grenadine': 15.0 }, }, { 'name': 'Rusty Nail', 'ingredients': { 'whiskey': 25.0 }, }, { 'name': 'B52', 'ingredients': { 'coffeeLiqueur': 20, 'baileys': 20, 'tripSec': 20 }, }, { 'name': 'Stinger', 'ingredients': { 'brandy': 50, 'cremeCacao': 20 }, }, { 'name': 'Golden Dream', 'ingredients': { 'galliano': 20, 'tripSec': 20, 'oj': 20, 'cream': 10 }, }, { 'name': 'God Mother', 'ingredients': { 'vodka': 35.0, 'amaretto': 35.0 }, }, { 'name': 'Spritz Veneziano', 'ingredients': { 'prosecco': 60, 'aperol': 40 }, }, { 'name': 'Bramble', 'ingredients': { 'gin': 40, 'lej': 15.0, 'grenadine': 10, 'blackberryLiqueur': 15.0 }, }, { 'name': 'Alexander', 'ingredients': { 'brandy': 30, 'cremeCacao': 30, 'cream': 30 }, }, { 'name': 'Lemon Drop Martini', 'ingredients': { 'vodka': 25.0, 'tripSec': 20, 'lej': 15.0 }, }, { 'name': 'French Martini', 'ingredients': { 'vodka': 45.0, 'raspberryLiqueur': 15.0, 'pj': 15.0 }, }, { 'name': 'Black Russian', 'ingredients': { 'vodka': 50, 'coffeeLiqueur': 20 }, }, { 'name': 'Bloody Mary', 'ingredients': { 'vodka': 45.0, 'tj': 90, 'lej': 15.0 }, }, { 'name': 'Mai-tai', 'ingredients': { 'whiteRum': 40, 'darkRum': 20, 'tripSec': 15.0, 'grenadine': 15.0, 'lij': 10 }, }, { "name": "Madras", "ingredients": { "vodka": 45, "cj": 90, "oj": 30 } }, { "name": "Lemon Drop", "ingredients": { "vodka": 40, "lej": 40, "grenadine": 15 } }, { "name": "Gin Tonic", "ingredients": { "gin": 50, "tonic": 160 } }, { "name": "Cape Cod", "ingredients": { "vodka": 35, "cj": 135 } }, { "name": "Bourbon Squash", "ingredients": { "whisky": 45, "oj": 50, "lej": 30, "grenadine": 20 } }] drink_options = [ { "name": "Gin", "value": "gin" }, { "name": "White Rum", "value": "whiteRum" }, { "name": "Dark Rum", "value": "darkRum" }, { "name": "Coconut Rum", "value": "coconutRum" }, { "name": "Vodka", "value": "vodka" }, { "name": "Tequila", "value": "tequila" }, { "name": "Tonic Water", "value": "tonic" }, { "name": "Coke", "value": "coke" }, { "name": "Orange Juice", "value": "oj" }, { "name": "Margarita Mix", "value": "mmix" }, { "name": "Cranberry Juice", "value": "cj" }, { "name": "Pineapple Juice", "value": "pj" }, { "name": "Apple Juice", "value": "aj" }, { "name": "Grapefruit Juice", "value": "gj" }, { "name": "Tomato Juice", "value": "tj" }, { "name": "Lime Juice", "value": "lij" }, { "name": "Lemon Juice", "value": "lej" }, { "name": "Whiskey", "value": "whiskey" }, { "name": "Triple Sec", "value": "tripSec" }, { "name": "Grenadine", "value": "grenadine" }, { "name": "Vermouth", "value": "vermouth" }, { "name": "Soda", "value": "soda" }, { "name": "Peach Schnapps", "value": "peachSchnapps" }, { "name": "Midori", "value": "midori" }, { "name": "Presecco", "value": "prosecco" }, { "name": "Cherry Brandy", "value": "cherryBrandy" }, { "name": "Apple Brandy", "value": "appleBrandy" }, { "name": "Apricot Brandy", "value": "apricotBrandy" }, { "name": "Brandy (generic)", "value": "brandy" }, { "name": "Champagne", "value": "champagne" }, { "name": "Cola", "value": "cola" }, { "name": "Port", "value": "port" }, { "name": "Coconut Milk", "value": "coconutMilk" }, { "name": "Creme de Cacao", "value": "cremeCacao" }, { "name": "Grenadine", "value": "grenadine" } ] # Check for ingredients that we don 't have a record for if __name__ == "__main__": found = [] drinks = [x["value"] for x in drink_options] for D in drink_list: for I in D["ingredients"]: if I not in drinks and I not in found: found.append(I) print(I)
drink_list = [{'name': 'Vesper', 'ingredients': {'gin': 60, 'vodka': 15.0, 'vermouth': 7.5}}, {'name': 'Bacardi', 'ingredients': {'whiteRum': 45.0, 'lij': 20, 'grenadine': 10}}, {'name': 'Kryptonite', 'ingredients': {'vodka': 8.0, 'whiskey': 7.0, 'lej': 6.0, 'oj': 5.0, 'grenadine': 4.0, 'cj': 3.0, 'rum': 2.0, 'vermouth': 1.0}}, {'name': 'Vodka', 'ingredients': {'vodka': 10.0}}, {'name': 'Whiskey', 'ingredients': {'whiskey': 10.0}}, {'name': 'Lemon Juice', 'ingredients': {'lej': 10.0}}, {'name': 'Orange Juice', 'ingredients': {'oj': 10.0}}, {'name': 'Grenadine', 'ingredients': {'grenadine': 10.0}}, {'name': 'Cranberry Juice', 'ingredients': {'cj': 10.0}}, {'name': 'Rum', 'ingredients': {'rum': 10.0}}, {'name': 'Vermouth', 'ingredients': {'vermouth': 10.0}}, {'name': 'Negroni', 'ingredients': {'gin': 30, 'campari': 30, 'vermouth': 30}}, {'name': 'Rose', 'ingredients': {'cherryBrandy': 20, 'vermouth': 40}}, {'name': 'Old Fashioned', 'ingredients': {'whiskey': 45.0}}, {'name': 'Tuxedo', 'ingredients': {'gin': 30, 'vermouth': 30}}, {'name': 'Mojito', 'ingredients': {'whiteRum': 40, 'lij': 30}}, {'name': "Horse's Neck", 'ingredients': {'brandy': 40, 'gingerAle': 120}}, {'name': "Planter's Punch", 'ingredients': {'darkRum': 45.0, 'oj': 35.0, 'pj': 35.0, 'lej': 20, 'grenadine': 10}}, {'name': 'Sea Breeze', 'ingredients': {'vodka': 40, 'cj': 120, 'gj': 30}}, {'name': 'Pisco Sour', 'ingredients': {'brandy': 45.0, 'lej': 30, 'grenadine': 20}}, {'name': 'Long Island Iced Tea', 'ingredients': {'tequila': 15.0, 'vodka': 15.0, 'whiteRum': 15.0, 'tripSec': 15.0, 'gin': 15.0, 'lej': 25.0, 'grenadine': 30.0}}, {'name': 'Clover Club', 'ingredients': {'gin': 45.0, 'grenadine': 15.0, 'lej': 15.0}}, {'name': 'Angel Face', 'ingredients': {'gin': 30, 'apricotBrandy': 30, 'appleBrandy': 30}}, {'name': 'Mimosa', 'ingredients': {'champagne': 75.0, 'oj': 75.0}}, {'name': 'Whiskey Sour', 'ingredients': {'whiskey': 45.0, 'lej': 30.0, 'grenadine': 15.0}}, {'name': 'Screwdriver', 'ingredients': {'vodka': 50, 'oj': 100}}, {'name': 'Cuba Libre', 'ingredients': {'whiteRum': 50, 'cola': 120, 'lij': 10}}, {'name': 'Manhattan', 'ingredients': {'whiskey': 50, 'vermouth': 20}}, {'name': 'Porto Flip', 'ingredients': {'brandy': 15.0, 'port': 45.0, 'eggYolk': 10}}, {'name': 'Gin Fizz', 'ingredients': {'gin': 45.0, 'lej': 30, 'grenadine': 10, 'soda': 80}}, {'name': 'Espresso Martini', 'ingredients': {'vodka': 50, 'coffeeLiqueur': 10}}, {'name': 'Margarita', 'ingredients': {'tequila': 35.0, 'tripSec': 20, 'lij': 15.0}}, {'name': 'French 75', 'ingredients': {'gin': 30, 'lej': 15.0, 'champagne': 60}}, {'name': 'Yellow Bird', 'ingredients': {'whiteRum': 30, 'galliano': 15.0, 'tripSec': 15.0, 'lij': 15.0}}, {'name': 'Pina Colada', 'ingredients': {'whiteRum': 30, 'pj': 90, 'coconutMilk': 30}}, {'name': 'Aviation', 'ingredients': {'gin': 45.0, 'cherryLiqueur': 15.0, 'lej': 15.0}}, {'name': 'Bellini', 'ingredients': {'prosecco': 100, 'peachPuree': 50}}, {'name': 'Grasshopper', 'ingredients': {'cremeCacao': 30, 'cream': 30}}, {'name': 'Tequila Sunrise', 'ingredients': {'tequila': 45.0, 'oj': 90, 'grenadine': 15.0}}, {'name': 'Daiquiri', 'ingredients': {'whiteRum': 45.0, 'lij': 25.0, 'grenadine': 15.0}}, {'name': 'Rusty Nail', 'ingredients': {'whiskey': 25.0}}, {'name': 'B52', 'ingredients': {'coffeeLiqueur': 20, 'baileys': 20, 'tripSec': 20}}, {'name': 'Stinger', 'ingredients': {'brandy': 50, 'cremeCacao': 20}}, {'name': 'Golden Dream', 'ingredients': {'galliano': 20, 'tripSec': 20, 'oj': 20, 'cream': 10}}, {'name': 'God Mother', 'ingredients': {'vodka': 35.0, 'amaretto': 35.0}}, {'name': 'Spritz Veneziano', 'ingredients': {'prosecco': 60, 'aperol': 40}}, {'name': 'Bramble', 'ingredients': {'gin': 40, 'lej': 15.0, 'grenadine': 10, 'blackberryLiqueur': 15.0}}, {'name': 'Alexander', 'ingredients': {'brandy': 30, 'cremeCacao': 30, 'cream': 30}}, {'name': 'Lemon Drop Martini', 'ingredients': {'vodka': 25.0, 'tripSec': 20, 'lej': 15.0}}, {'name': 'French Martini', 'ingredients': {'vodka': 45.0, 'raspberryLiqueur': 15.0, 'pj': 15.0}}, {'name': 'Black Russian', 'ingredients': {'vodka': 50, 'coffeeLiqueur': 20}}, {'name': 'Bloody Mary', 'ingredients': {'vodka': 45.0, 'tj': 90, 'lej': 15.0}}, {'name': 'Mai-tai', 'ingredients': {'whiteRum': 40, 'darkRum': 20, 'tripSec': 15.0, 'grenadine': 15.0, 'lij': 10}}, {'name': 'Madras', 'ingredients': {'vodka': 45, 'cj': 90, 'oj': 30}}, {'name': 'Lemon Drop', 'ingredients': {'vodka': 40, 'lej': 40, 'grenadine': 15}}, {'name': 'Gin Tonic', 'ingredients': {'gin': 50, 'tonic': 160}}, {'name': 'Cape Cod', 'ingredients': {'vodka': 35, 'cj': 135}}, {'name': 'Bourbon Squash', 'ingredients': {'whisky': 45, 'oj': 50, 'lej': 30, 'grenadine': 20}}] drink_options = [{'name': 'Gin', 'value': 'gin'}, {'name': 'White Rum', 'value': 'whiteRum'}, {'name': 'Dark Rum', 'value': 'darkRum'}, {'name': 'Coconut Rum', 'value': 'coconutRum'}, {'name': 'Vodka', 'value': 'vodka'}, {'name': 'Tequila', 'value': 'tequila'}, {'name': 'Tonic Water', 'value': 'tonic'}, {'name': 'Coke', 'value': 'coke'}, {'name': 'Orange Juice', 'value': 'oj'}, {'name': 'Margarita Mix', 'value': 'mmix'}, {'name': 'Cranberry Juice', 'value': 'cj'}, {'name': 'Pineapple Juice', 'value': 'pj'}, {'name': 'Apple Juice', 'value': 'aj'}, {'name': 'Grapefruit Juice', 'value': 'gj'}, {'name': 'Tomato Juice', 'value': 'tj'}, {'name': 'Lime Juice', 'value': 'lij'}, {'name': 'Lemon Juice', 'value': 'lej'}, {'name': 'Whiskey', 'value': 'whiskey'}, {'name': 'Triple Sec', 'value': 'tripSec'}, {'name': 'Grenadine', 'value': 'grenadine'}, {'name': 'Vermouth', 'value': 'vermouth'}, {'name': 'Soda', 'value': 'soda'}, {'name': 'Peach Schnapps', 'value': 'peachSchnapps'}, {'name': 'Midori', 'value': 'midori'}, {'name': 'Presecco', 'value': 'prosecco'}, {'name': 'Cherry Brandy', 'value': 'cherryBrandy'}, {'name': 'Apple Brandy', 'value': 'appleBrandy'}, {'name': 'Apricot Brandy', 'value': 'apricotBrandy'}, {'name': 'Brandy (generic)', 'value': 'brandy'}, {'name': 'Champagne', 'value': 'champagne'}, {'name': 'Cola', 'value': 'cola'}, {'name': 'Port', 'value': 'port'}, {'name': 'Coconut Milk', 'value': 'coconutMilk'}, {'name': 'Creme de Cacao', 'value': 'cremeCacao'}, {'name': 'Grenadine', 'value': 'grenadine'}] if __name__ == '__main__': found = [] drinks = [x['value'] for x in drink_options] for d in drink_list: for i in D['ingredients']: if I not in drinks and I not in found: found.append(I) print(I)
''' Thanks to "Primo" for the amazing code found in this .py. ''' # legendre symbol (a|m) # note: returns m-1 if a is a non-residue, instead of -1 def legendre(a, m): return pow(a, (m-1) >> 1, m) # strong probable prime def is_sprp(n, b=2): d = n-1 s = 0 while d & 1 == 0: s += 1 d >>= 1 x = pow(b, d, n) if x == 1 or x == n-1: return True for r in range(1, s): x = (x * x) % n if x == 1: return False elif x == n-1: return True return False # lucas probable prime # assumes D = 1 (mod 4), (D|n) = -1 def is_lucas_prp(n, D): P = 1 Q = (1-D) >> 2 # n+1 = 2**r*s where s is odd s = n+1 r = 0 while s&1 == 0: r += 1 s >>= 1 # calculate the bit reversal of (odd) s # e.g. 19 (10011) <=> 25 (11001) t = 0 while s > 0: if s & 1: t += 1 s -= 1 else: t <<= 1 s >>= 1 # use the same bit reversal process to calculate the sth Lucas number # keep track of q = Q**n as we go U = 0 V = 2 q = 1 # mod_inv(2, n) inv_2 = (n+1) >> 1 while t > 0: if t & 1 == 1: # U, V of n+1 U, V = ((U + V) * inv_2) % n, ((D*U + V) * inv_2) % n q = (q * Q) % n t -= 1 else: # U, V of n*2 U, V = (U * V) % n, (V * V - 2 * q) % n q = (q * q) % n t >>= 1 # double s until we have the 2**r*sth Lucas number while r > 0: U, V = (U * V)%n, (V * V - 2 * q)%n q = (q * q)%n r -= 1 # primality check # if n is prime, n divides the n+1st Lucas number, given the assumptions return U == 0 # primes less than 212 small_primes = set([ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113, 127,131,137,139,149,151,157,163,167,173, 179,181,191,193,197,199,211]) # pre-calced sieve of eratosthenes for n = 2, 3, 5, 7 indices = [ 1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113,121,127,131, 137,139,143,149,151,157,163,167,169,173, 179,181,187,191,193,197,199,209] # distances between sieve values offsets = [ 10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2] max_int = 2147483647 # an 'almost certain' primality check def is_prime(n): if n < 212: return n in small_primes for p in small_primes: if n % p == 0: return False # if n is a 32-bit integer, perform full trial division if n <= max_int: i = 211 while i * i < n: for o in offsets: i += o if n % i == 0: return False return True # Baillie-PSW # this is technically a probabalistic test, but there are no known pseudoprimes if not is_sprp(n): return False a = 5 s = 2 while legendre(a, n) != n-1: s = -s a = s-a return is_lucas_prp(n, a) # next prime strictly larger than n def next_prime(n): if n < 2: return 2 # first odd larger than n n = (n + 1) | 1 if n < 212: while True: if n in small_primes: return n n += 2 # find our position in the sieve rotation via binary search x = int(n % 210) s = 0 e = 47 m = 24 while m != e: if indices[m] < x: s = m m = (s + e + 1) >> 1 else: e = m m = (s + e) >> 1 i = int(n + (indices[m] - x)) # adjust offsets offs = offsets[m:]+offsets[:m] while True: for o in offs: if is_prime(i): return i i += o
""" Thanks to "Primo" for the amazing code found in this .py. """ def legendre(a, m): return pow(a, m - 1 >> 1, m) def is_sprp(n, b=2): d = n - 1 s = 0 while d & 1 == 0: s += 1 d >>= 1 x = pow(b, d, n) if x == 1 or x == n - 1: return True for r in range(1, s): x = x * x % n if x == 1: return False elif x == n - 1: return True return False def is_lucas_prp(n, D): p = 1 q = 1 - D >> 2 s = n + 1 r = 0 while s & 1 == 0: r += 1 s >>= 1 t = 0 while s > 0: if s & 1: t += 1 s -= 1 else: t <<= 1 s >>= 1 u = 0 v = 2 q = 1 inv_2 = n + 1 >> 1 while t > 0: if t & 1 == 1: (u, v) = ((U + V) * inv_2 % n, (D * U + V) * inv_2 % n) q = q * Q % n t -= 1 else: (u, v) = (U * V % n, (V * V - 2 * q) % n) q = q * q % n t >>= 1 while r > 0: (u, v) = (U * V % n, (V * V - 2 * q) % n) q = q * q % n r -= 1 return U == 0 small_primes = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211]) indices = [1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 121, 127, 131, 137, 139, 143, 149, 151, 157, 163, 167, 169, 173, 179, 181, 187, 191, 193, 197, 199, 209] offsets = [10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2] max_int = 2147483647 def is_prime(n): if n < 212: return n in small_primes for p in small_primes: if n % p == 0: return False if n <= max_int: i = 211 while i * i < n: for o in offsets: i += o if n % i == 0: return False return True if not is_sprp(n): return False a = 5 s = 2 while legendre(a, n) != n - 1: s = -s a = s - a return is_lucas_prp(n, a) def next_prime(n): if n < 2: return 2 n = n + 1 | 1 if n < 212: while True: if n in small_primes: return n n += 2 x = int(n % 210) s = 0 e = 47 m = 24 while m != e: if indices[m] < x: s = m m = s + e + 1 >> 1 else: e = m m = s + e >> 1 i = int(n + (indices[m] - x)) offs = offsets[m:] + offsets[:m] while True: for o in offs: if is_prime(i): return i i += o
a = "Hello World" b = a[3] c = a[-2] d = a[5::] e = a[:5] print(b) print(c) print(d) print(e)
a = 'Hello World' b = a[3] c = a[-2] d = a[5:] e = a[:5] print(b) print(c) print(d) print(e)
overlapped_classes = ["Alarm clock", "Backpack", "Banana", "Band Aid", "Basket", "Bath towel", "Beer bottle", "Bench", "Bicycle", "Binder (closed)", "Bottle cap", "Bread loaf", "Broom", "Bucket", "Butcher's knife", "Can opener", "Candle", "Cellphone", "Chair", "Clothes hamper", "Combination lock", "Computer mouse", "Desk lamp", "Dishrag or hand towel", "Doormat", "Dress", "Dress shoe (men)", "Drill", "Drinking Cup", "Drying rack for plates", "Envelope", "Fan", "Coffee/French press", "Frying pan", "Hair dryer", "Hammer", "Helmet", "Iron (for clothes)", "Jeans", "Keyboard", "Ladle", "Lampshade", "Laptop (open)", "Lemon", "Letter opener", "Lighter", "Lipstick", "Match", "Measuring cup", "Microwave", "Mixing / Salad Bowl", "Monitor", "Mug", "Nail (fastener)", "Necklace", "Orange", "Padlock", "Paintbrush", "Paper towel", "Pen", "Pill bottle", "Pillow", "Pitcher", "Plastic bag", "Plate", "Plunger", "Pop can", "Portable heater", "Printer", "Remote control", "Ruler", "Running shoe", "Safety pin", "Salt shaker", "Sandal", "Screw", "Shovel", "Skirt", "Sleeping bag", "Soap dispenser", "Sock", "Soup Bowl", "Spatula", "Speaker", "Still Camera", "Strainer", "Stuffed animal", "Suit jacket", "Sunglasses", "Sweater", "Swimming trunks", "T-shirt", "TV", "Teapot", "Tennis racket", "Tie", "Toaster", "Toilet paper roll", "Trash bin", "Tray", "Umbrella", "Vacuum cleaner", "Vase", "Wallet", "Watch", "Water bottle", "Weight (exercise)", "Weight scale", "Wheel", "Whistle", "Wine bottle", "Winter glove", "Wok"]
overlapped_classes = ['Alarm clock', 'Backpack', 'Banana', 'Band Aid', 'Basket', 'Bath towel', 'Beer bottle', 'Bench', 'Bicycle', 'Binder (closed)', 'Bottle cap', 'Bread loaf', 'Broom', 'Bucket', "Butcher's knife", 'Can opener', 'Candle', 'Cellphone', 'Chair', 'Clothes hamper', 'Combination lock', 'Computer mouse', 'Desk lamp', 'Dishrag or hand towel', 'Doormat', 'Dress', 'Dress shoe (men)', 'Drill', 'Drinking Cup', 'Drying rack for plates', 'Envelope', 'Fan', 'Coffee/French press', 'Frying pan', 'Hair dryer', 'Hammer', 'Helmet', 'Iron (for clothes)', 'Jeans', 'Keyboard', 'Ladle', 'Lampshade', 'Laptop (open)', 'Lemon', 'Letter opener', 'Lighter', 'Lipstick', 'Match', 'Measuring cup', 'Microwave', 'Mixing / Salad Bowl', 'Monitor', 'Mug', 'Nail (fastener)', 'Necklace', 'Orange', 'Padlock', 'Paintbrush', 'Paper towel', 'Pen', 'Pill bottle', 'Pillow', 'Pitcher', 'Plastic bag', 'Plate', 'Plunger', 'Pop can', 'Portable heater', 'Printer', 'Remote control', 'Ruler', 'Running shoe', 'Safety pin', 'Salt shaker', 'Sandal', 'Screw', 'Shovel', 'Skirt', 'Sleeping bag', 'Soap dispenser', 'Sock', 'Soup Bowl', 'Spatula', 'Speaker', 'Still Camera', 'Strainer', 'Stuffed animal', 'Suit jacket', 'Sunglasses', 'Sweater', 'Swimming trunks', 'T-shirt', 'TV', 'Teapot', 'Tennis racket', 'Tie', 'Toaster', 'Toilet paper roll', 'Trash bin', 'Tray', 'Umbrella', 'Vacuum cleaner', 'Vase', 'Wallet', 'Watch', 'Water bottle', 'Weight (exercise)', 'Weight scale', 'Wheel', 'Whistle', 'Wine bottle', 'Winter glove', 'Wok']
indexes = range(5) same_indexes = range(0, 5) print("indexes are:") for i in indexes: print(i) print("same_indexes are:") for i in same_indexes: print(i) special_indexes = range(5, 9) print("special_indexes are:") for i in special_indexes: print(i)
indexes = range(5) same_indexes = range(0, 5) print('indexes are:') for i in indexes: print(i) print('same_indexes are:') for i in same_indexes: print(i) special_indexes = range(5, 9) print('special_indexes are:') for i in special_indexes: print(i)
print('\nCalculate the midpoint of a line :') x1 = float(input('The value of x (the first endpoint) ')) y1 = float(input('The value of y (the first endpoint) ')) x2 = float(input('The value of x (the first endpoint) ')) y2 = float(input('The value of y (the first endpoint) ')) x_m_point = (x1 + x2)/2 y_m_point = (y1 + y2)/2 print() print("The midpoint of line is :") print( "The midpoint's x value is: ",x_m_point) print( "The midpoint's y value is: ",y_m_point) print()
print('\nCalculate the midpoint of a line :') x1 = float(input('The value of x (the first endpoint) ')) y1 = float(input('The value of y (the first endpoint) ')) x2 = float(input('The value of x (the first endpoint) ')) y2 = float(input('The value of y (the first endpoint) ')) x_m_point = (x1 + x2) / 2 y_m_point = (y1 + y2) / 2 print() print('The midpoint of line is :') print("The midpoint's x value is: ", x_m_point) print("The midpoint's y value is: ", y_m_point) print()
ts = [ # example tests 14, 16, 23, # small numbers 5, 4, 3, 2, 1, # random bit bigger numbers 10, 20, 31, 32, 33, 46, # perfect squares 25, 36, 49, # random incrementally larger numbers 73, 89, 106, 132, 182, 258, 299, 324, # perfect square 359, # prime 489, 512, 581, 713, 834, 952, 986, 996, 997, # largest prime in range 998, 999, ] for i, n in enumerate(ts): with open('T%02d.in' % i, 'w') as f: f.write('%d\n' % n)
ts = [14, 16, 23, 5, 4, 3, 2, 1, 10, 20, 31, 32, 33, 46, 25, 36, 49, 73, 89, 106, 132, 182, 258, 299, 324, 359, 489, 512, 581, 713, 834, 952, 986, 996, 997, 998, 999] for (i, n) in enumerate(ts): with open('T%02d.in' % i, 'w') as f: f.write('%d\n' % n)
n=int(input()) while n: n-=1 print(pow(*map(int,input().split()),10**9+7))
n = int(input()) while n: n -= 1 print(pow(*map(int, input().split()), 10 ** 9 + 7))
# Wrapper class to make dealing with logs easier class ChannelLog(): __channel = "" __logs = [] unread = False mentioned_in = False # the index of where to start printing the messages __index = 0 def __init__(self, channel, logs): self.__channel = channel self.__logs = list(logs) def get_server(self): return self.__channel.server def get_channel(self): return self.__channel def get_logs(self): return self.__logs def get_name(self): return self.__channel.name def get_server_name(self): return self.__channel.server.name def append(self, message): self.__logs.append(message) def index(self, message): return self.__logs.index(message) def insert(self, i, message): self.__logs.insert(i, message) def len(self): return len(self.__logs) def get_index(self): return self.__index def set_index(self, int): self.__index = int def inc_index(self, int): self.__index += int def dec_index(self, int): self.__index -= int
class Channellog: __channel = '' __logs = [] unread = False mentioned_in = False __index = 0 def __init__(self, channel, logs): self.__channel = channel self.__logs = list(logs) def get_server(self): return self.__channel.server def get_channel(self): return self.__channel def get_logs(self): return self.__logs def get_name(self): return self.__channel.name def get_server_name(self): return self.__channel.server.name def append(self, message): self.__logs.append(message) def index(self, message): return self.__logs.index(message) def insert(self, i, message): self.__logs.insert(i, message) def len(self): return len(self.__logs) def get_index(self): return self.__index def set_index(self, int): self.__index = int def inc_index(self, int): self.__index += int def dec_index(self, int): self.__index -= int
l= int(input("Enter the size of array \n")) a=input("Enter the integer inputs\n").split() c=0 a[0]=int(a[0]) for i in range(1,l): a[i]=int(a[i]) while a[i]<a[i-1]: c+=1 a[i]+=1 print(c)
l = int(input('Enter the size of array \n')) a = input('Enter the integer inputs\n').split() c = 0 a[0] = int(a[0]) for i in range(1, l): a[i] = int(a[i]) while a[i] < a[i - 1]: c += 1 a[i] += 1 print(c)
1 == 2 segfault() class Dupe(object): pass class Dupe(Dupe): pass
1 == 2 segfault() class Dupe(object): pass class Dupe(Dupe): pass
# General Errors NO_ERROR = 0 USER_EXIT = 1 ERR_SUDO_PERMS = 100 ERR_FOUND = 101 ERR_PYTHON_PKG = 154 # Warnings WARN_FILE_PERMS = 115 WARN_LOG_ERRS = 126 WARN_LOG_WARNS = 127 WARN_LARGE_FILES = 151 # Installation Errors ERR_BITS = 102 ERR_OS_VER = 103 ERR_OS = 104 ERR_FINDING_OS = 105 ERR_FREE_SPACE = 106 ERR_PKG_MANAGER = 107 ERR_OMSCONFIG = 108 ERR_OMI = 109 ERR_SCX = 110 ERR_OMS_INSTALL = 111 ERR_OLD_OMS_VER = 112 ERR_GETTING_OMS_VER = 113 ERR_FILE_MISSING = 114 ERR_CERT = 116 ERR_RSA_KEY = 117 ERR_FILE_EMPTY = 118 ERR_INFO_MISSING = 119 ERR_PKG = 152 # Connection Errors ERR_ENDPT = 120 ERR_GUID = 121 ERR_OMS_WONT_RUN = 122 ERR_OMS_STOPPED = 123 ERR_OMS_DISABLED = 124 ERR_FILE_ACCESS = 125 # Heartbeat Errors ERR_HEARTBEAT = 128 ERR_MULTIHOMING = 129 ERR_INTERNET = 130 ERR_QUERIES = 131 # High CPU / Memory Usage Errors ERR_OMICPU = 141 ERR_OMICPU_HOT = 142 ERR_OMICPU_NSSPEM = 143 ERR_OMICPU_NSSPEM_LIKE = 144 ERR_SLAB = 145 ERR_SLAB_BLOATED = 146 ERR_SLAB_NSSSOFTOKN = 147 ERR_SLAB_NSS = 148 ERR_LOGROTATE_SIZE = 149 ERR_LOGROTATE = 150 # Syslog Errors ERR_SYSLOG_WKSPC = 132 ERR_PT = 133 ERR_PORT_MISMATCH = 134 ERR_PORT_SETUP = 135 ERR_SERVICE_CONTROLLER = 136 ERR_SYSLOG = 137 ERR_SERVICE_STATUS = 138 # Custom Log Errors ERR_CL_FILEPATH = 139 ERR_CL_UNIQUENUM = 140 ERR_BACKEND_CONFIG = 153
no_error = 0 user_exit = 1 err_sudo_perms = 100 err_found = 101 err_python_pkg = 154 warn_file_perms = 115 warn_log_errs = 126 warn_log_warns = 127 warn_large_files = 151 err_bits = 102 err_os_ver = 103 err_os = 104 err_finding_os = 105 err_free_space = 106 err_pkg_manager = 107 err_omsconfig = 108 err_omi = 109 err_scx = 110 err_oms_install = 111 err_old_oms_ver = 112 err_getting_oms_ver = 113 err_file_missing = 114 err_cert = 116 err_rsa_key = 117 err_file_empty = 118 err_info_missing = 119 err_pkg = 152 err_endpt = 120 err_guid = 121 err_oms_wont_run = 122 err_oms_stopped = 123 err_oms_disabled = 124 err_file_access = 125 err_heartbeat = 128 err_multihoming = 129 err_internet = 130 err_queries = 131 err_omicpu = 141 err_omicpu_hot = 142 err_omicpu_nsspem = 143 err_omicpu_nsspem_like = 144 err_slab = 145 err_slab_bloated = 146 err_slab_nsssoftokn = 147 err_slab_nss = 148 err_logrotate_size = 149 err_logrotate = 150 err_syslog_wkspc = 132 err_pt = 133 err_port_mismatch = 134 err_port_setup = 135 err_service_controller = 136 err_syslog = 137 err_service_status = 138 err_cl_filepath = 139 err_cl_uniquenum = 140 err_backend_config = 153
"{variable_name:format_description}" print('{a:<10}|{a:^10}|{a:>10}'.format(a='test')) print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test')) person = {"first":"Joran","last":"Beasley"} print("{p[first]} {p[last]}".format(p=person)) data = range(100) print("{d[0]}...{d[99]}".format(d=data)) print("normal:{num:d}".format(num=33)) print("normal:{num:f}".format(num=33)) print("binary:{num:b}".format(num=33)) print("binary:{num:08b}".format(num=33)) print("hex:{num:x}".format(num=33)) print("hex:0x{num:0<4x}".format(num=33)) print("octal:{num:o}".format(num=33)) print("{num:f}".format(num=22/7)) print("${num:0.2f}".format(num=22/7)) print("{num:.2e}".format(num=22/7)) print("{num:.1%}".format(num=22/7)) print("{num:g}".format(num=5.1200001)) variable=27 print(f"{variable}")
"""{variable_name:format_description}""" print('{a:<10}|{a:^10}|{a:>10}'.format(a='test')) print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test')) person = {'first': 'Joran', 'last': 'Beasley'} print('{p[first]} {p[last]}'.format(p=person)) data = range(100) print('{d[0]}...{d[99]}'.format(d=data)) print('normal:{num:d}'.format(num=33)) print('normal:{num:f}'.format(num=33)) print('binary:{num:b}'.format(num=33)) print('binary:{num:08b}'.format(num=33)) print('hex:{num:x}'.format(num=33)) print('hex:0x{num:0<4x}'.format(num=33)) print('octal:{num:o}'.format(num=33)) print('{num:f}'.format(num=22 / 7)) print('${num:0.2f}'.format(num=22 / 7)) print('{num:.2e}'.format(num=22 / 7)) print('{num:.1%}'.format(num=22 / 7)) print('{num:g}'.format(num=5.1200001)) variable = 27 print(f'{variable}')
def solution(A,B,K): count = 0 for i in range(A,B): if(i%K==0): count += 1 #print(count) return count solution(6,11,2)
def solution(A, B, K): count = 0 for i in range(A, B): if i % K == 0: count += 1 return count solution(6, 11, 2)
# -*- coding: utf-8 -*- class Solution: def getLucky(self, s: str, k: int) -> int: result = ''.join(str(ord(c) - ord('a') + 1) for c in s) for _ in range(k): result = sum(int(digit) for digit in str(result)) return result if __name__ == '__main__': solution = Solution() assert 36 == solution.getLucky('iiii', 1) assert 6 == solution.getLucky('leetcode', 2)
class Solution: def get_lucky(self, s: str, k: int) -> int: result = ''.join((str(ord(c) - ord('a') + 1) for c in s)) for _ in range(k): result = sum((int(digit) for digit in str(result))) return result if __name__ == '__main__': solution = solution() assert 36 == solution.getLucky('iiii', 1) assert 6 == solution.getLucky('leetcode', 2)
# -*- coding: utf-8 -*- """ Created on Fri Aug 3 10:38:41 2018 @author: lenovo """ # ============================================================================= # 13. Roman to Integer # Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. # # Symbol Value # I 1 # V 5 # X 10 # L 50 # C 100 # D 500 # M 1000 # # For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. # # Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: # # I can be placed before V (5) and X (10) to make 4 and 9. # X can be placed before L (50) and C (100) to make 40 and 90. # C can be placed before D (500) and M (1000) to make 400 and 900. # # Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. # # Example 1: # # Input: "III" # Output: 3 # # Example 2: # # Input: "IV" # Output: 4 # # Example 3: # # Input: "IX" # Output: 9 # # Example 4: # # Input: "LVIII" # Output: 58 # Explanation: C = 100, L = 50, XXX = 30 and III = 3. # # Example 5: # # Input: "MCMXCIV" # Output: 1994 # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. # ============================================================================= # ============================================================================= # difficulty: easy # acceptance: 49.0% # contributor: LeetCode # ============================================================================= class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ length = len(s) if length == 0: return 0 d1 = {'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900} d2 = {'V':5, 'L':50, 'D':500, 'M':1000} d3 = {'I':1, 'X':10, 'C':100 } result = 0 index = 0 while index < length: # for index, item in enumerate(s): item = s[index] if item in d3: i = index number = 0 while i + 1 < length and s[i + 1] == item: i += 1 j = i + 1 if j < length and s[i:j + 1] in d1: number = d1[s[i:j + 1]] + (j - index - 1) * d3[item] result += number index = j + 1 else: number = (j - index) * d3[item] result += number index = j else: i = index number = 0 while i + 1 < length and s[i + 1] == item: i += 1 j = i + 1 number = (j - index) * d2[item] result += number index = j return result #------------------------------------------------------------------------------ # note: below is the test code test = 'IX' S = Solution() result = S.romanToInt(test) print(result) #------------------------------------------------------------------------------ # note: below is the submission detail # ============================================================================= # Submission Detail # 3999 / 3999 test cases passed. # Status: Accepted # Runtime: 156 ms # beats 15.44% python3 submissions # Submitted: 0 minutes ago # =============================================================================
""" Created on Fri Aug 3 10:38:41 2018 @author: lenovo """ class Solution: def roman_to_int(self, s): """ :type s: str :rtype: int """ length = len(s) if length == 0: return 0 d1 = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900} d2 = {'V': 5, 'L': 50, 'D': 500, 'M': 1000} d3 = {'I': 1, 'X': 10, 'C': 100} result = 0 index = 0 while index < length: item = s[index] if item in d3: i = index number = 0 while i + 1 < length and s[i + 1] == item: i += 1 j = i + 1 if j < length and s[i:j + 1] in d1: number = d1[s[i:j + 1]] + (j - index - 1) * d3[item] result += number index = j + 1 else: number = (j - index) * d3[item] result += number index = j else: i = index number = 0 while i + 1 < length and s[i + 1] == item: i += 1 j = i + 1 number = (j - index) * d2[item] result += number index = j return result test = 'IX' s = solution() result = S.romanToInt(test) print(result)
def calc_average(case): sum = 0 count = int(case[0]) for i in range(1, count + 1): sum += int(case[i]) return sum / count def count_average(case, average): count = 0 count_num = int(case[0]) for i in range(1, count_num + 1): if average < int(case[i]): count += 1 return count count_case = int(input()) cases = list() for i in range(0, count_case): cases.append(list(input().split())) for case in cases: average = calc_average(case) print('%.3f' % round(count_average(case, average) / int(case[0]) * 100, 3) + '%')
def calc_average(case): sum = 0 count = int(case[0]) for i in range(1, count + 1): sum += int(case[i]) return sum / count def count_average(case, average): count = 0 count_num = int(case[0]) for i in range(1, count_num + 1): if average < int(case[i]): count += 1 return count count_case = int(input()) cases = list() for i in range(0, count_case): cases.append(list(input().split())) for case in cases: average = calc_average(case) print('%.3f' % round(count_average(case, average) / int(case[0]) * 100, 3) + '%')
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8 """ class Solution: def generateParenthesis(self, n: int) -> List[str]: ans = [] self.helper(0, 0, "", n, ans) return ans def helper(self, left, right, current, n, ans): if left < right: return if left == n and right == n: ans.append(current) return if left > n or right > n: return new_current = current + "(" self.helper(left + 1, right, new_current, n, ans) new_current = current + ")" self.helper(left, right + 1, new_current, n, ans)
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8 """ class Solution: def generate_parenthesis(self, n: int) -> List[str]: ans = [] self.helper(0, 0, '', n, ans) return ans def helper(self, left, right, current, n, ans): if left < right: return if left == n and right == n: ans.append(current) return if left > n or right > n: return new_current = current + '(' self.helper(left + 1, right, new_current, n, ans) new_current = current + ')' self.helper(left, right + 1, new_current, n, ans)
def decorator(func): def wrapper(): print("Decoring") func() print("Done!") return wrapper @decorator def say_hi(): print("Hi!") if __name__ == "__main__": say_hi()
def decorator(func): def wrapper(): print('Decoring') func() print('Done!') return wrapper @decorator def say_hi(): print('Hi!') if __name__ == '__main__': say_hi()
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ if (n < 3): # Special cases # 0 = 0: # 1 = 1: 1 # 2 = 2: 2, 1 1 return n else: # Fibonaci from here onward # 3 = 3: 1 1 1, 2 1, 1 2 # 4 = 5: 1 1 1 1, 2 1 1, 1 2 1, 1 1 2, 2 2 # 5 = 8: 1 1 1 1 1, 2 1 1 1, 1 2 1 1 , 1 1 2 1, 1 1 1 2, 2 2 1, 1 2 2, 2 1 2 # 6 = 13: 1 1 1 1 1 1, 2 1 1 1 1, 1 2 1 1 1, 1 1 2 1 1, 1 1 1 2 1, 1 1 1 1 2, # Fibonaci pattern spotted as shown above... preprev = 1 # Resume from special cases prev = 2 # Resume from special cases for i in range(n-2): # omit the first two steps temp = preprev preprev = prev # update preprev for next iter prev = prev + temp # update prev for next iter return prev
class Solution: def climb_stairs(self, n): """ :type n: int :rtype: int """ if n < 3: return n else: preprev = 1 prev = 2 for i in range(n - 2): temp = preprev preprev = prev prev = prev + temp return prev
s = pd.Series( data=np.random.randn(NUMBER), index=pd.date_range('2000-01-01', freq='D', periods=NUMBER)) result = s['2000-02-14':'2000-02']
s = pd.Series(data=np.random.randn(NUMBER), index=pd.date_range('2000-01-01', freq='D', periods=NUMBER)) result = s['2000-02-14':'2000-02']
# https://edabit.com/challenge/Yx2a9B57vXRuPevGh # Create a function that takes length and width and finds the perimeter of a rectangle. def find_perimeter(x: int, y: int) -> int: perimeter = (x * 2) + (y * 2) return perimeter print(find_perimeter(20, 10))
def find_perimeter(x: int, y: int) -> int: perimeter = x * 2 + y * 2 return perimeter print(find_perimeter(20, 10))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ return self.iterative(p, q) def recursive(self, p, q): check = self.nodeCheck(p, q) if check == 0: return True elif check == 1: return False return self.recursive(p.left, q.left) and self.recursive(p.right, q.right) def iterative(self, p, q): queue = [(p, q)] while queue: p, q = queue.pop(0) check = self.nodeCheck(p, q) if check % 2 == 1: return False if p: queue.append((p.left, q.left)) queue.append((p.right, q.right)) return True def nodeCheck(self, p, q): if not p and not q: return 0 if not p or not q: return 1 if p.val != q.val: return 1 return 2
class Solution(object): def is_same_tree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ return self.iterative(p, q) def recursive(self, p, q): check = self.nodeCheck(p, q) if check == 0: return True elif check == 1: return False return self.recursive(p.left, q.left) and self.recursive(p.right, q.right) def iterative(self, p, q): queue = [(p, q)] while queue: (p, q) = queue.pop(0) check = self.nodeCheck(p, q) if check % 2 == 1: return False if p: queue.append((p.left, q.left)) queue.append((p.right, q.right)) return True def node_check(self, p, q): if not p and (not q): return 0 if not p or not q: return 1 if p.val != q.val: return 1 return 2
""" Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition Problem Statement: Write code to remove duplicates from unsorted linked list FOLLOW UP : How would you solve this problem if temporary buffer is not allowed. """ def remove_dups(head): # O(n) speed with O(n) space for hash table hash_table = {head.value: True} while head is not None: if head.next_node is not None: if hash_table.get(head.next_node.value, None) is not None: head.next_node = head.next_node.next_node else: hash_table[head.next_node.value] = True head = head.next_node def remove_dups_alternative(head): # O(n^2) speed with O(1) space due to no hash table while head is not None: runner = head while runner is not None: if runner.next_node is not None and runner.next_node.value == head.value: if runner.next_node is None: break else: runner.next_node = runner.next_node.next_node runner = runner.next_node head = head.next_node
""" Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition Problem Statement: Write code to remove duplicates from unsorted linked list FOLLOW UP : How would you solve this problem if temporary buffer is not allowed. """ def remove_dups(head): hash_table = {head.value: True} while head is not None: if head.next_node is not None: if hash_table.get(head.next_node.value, None) is not None: head.next_node = head.next_node.next_node else: hash_table[head.next_node.value] = True head = head.next_node def remove_dups_alternative(head): while head is not None: runner = head while runner is not None: if runner.next_node is not None and runner.next_node.value == head.value: if runner.next_node is None: break else: runner.next_node = runner.next_node.next_node runner = runner.next_node head = head.next_node
# -*- coding: utf-8 -*- # This file is generated from NI Switch Executive API metadata version 21.0.0d1 config = { 'api_version': '21.0.0d1', 'c_function_prefix': 'niSE_', 'close_function': 'CloseSession', 'context_manager_name': { }, 'custom_types': [ ], 'driver_name': 'NI Switch Executive', 'driver_registry': 'Switch Executive', 'extra_errors_used': [ 'InvalidRepeatedCapabilityError' ], 'init_function': 'OpenSession', 'library_info': { 'Linux': { '64bit': { 'name': 'nise', 'type': 'cdll' } }, 'Windows': { '32bit': { 'name': 'nise.dll', 'type': 'windll' }, '64bit': { 'name': 'nise.dll', 'type': 'cdll' } } }, 'metadata_version': '2.0', 'module_name': 'nise', 'repeated_capabilities': [ ], 'session_class_description': 'An NI Switch Executive session', 'session_handle_parameter_name': 'vi', 'use_locking': False }
config = {'api_version': '21.0.0d1', 'c_function_prefix': 'niSE_', 'close_function': 'CloseSession', 'context_manager_name': {}, 'custom_types': [], 'driver_name': 'NI Switch Executive', 'driver_registry': 'Switch Executive', 'extra_errors_used': ['InvalidRepeatedCapabilityError'], 'init_function': 'OpenSession', 'library_info': {'Linux': {'64bit': {'name': 'nise', 'type': 'cdll'}}, 'Windows': {'32bit': {'name': 'nise.dll', 'type': 'windll'}, '64bit': {'name': 'nise.dll', 'type': 'cdll'}}}, 'metadata_version': '2.0', 'module_name': 'nise', 'repeated_capabilities': [], 'session_class_description': 'An NI Switch Executive session', 'session_handle_parameter_name': 'vi', 'use_locking': False}
"""A utility module turning English into machine-readable data.""" def oxford_comma_text_to_list(phrase): """Examples: - 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe'] - 'Black and White' --> ['Black', 'White'] - 'San Francisco and Saint Francis' --> ['San Francisco', 'Saint Francisco'] """ items = [] for subphrase in phrase.split(', '): items.extend( [item.strip() for item in subphrase.split(' and ')]) return items
"""A utility module turning English into machine-readable data.""" def oxford_comma_text_to_list(phrase): """Examples: - 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe'] - 'Black and White' --> ['Black', 'White'] - 'San Francisco and Saint Francis' --> ['San Francisco', 'Saint Francisco'] """ items = [] for subphrase in phrase.split(', '): items.extend([item.strip() for item in subphrase.split(' and ')]) return items
class DomainServiceBase: def __init__(self, repository): self.repository = repository def update(self, obj, updated_data={}): self.repository.update(obj, updated_data) def delete(self, obj): self.repository.delete(obj) def create(self, obj): obj = self.repository.create(obj) return obj def get_all(self, query_params={}, orderby=[], select_related=[]): return self.repository.get_all(query_params, orderby, select_related) def get(self, query_params={}, select_related=[]): return self.repository.get(query_params, select_related)
class Domainservicebase: def __init__(self, repository): self.repository = repository def update(self, obj, updated_data={}): self.repository.update(obj, updated_data) def delete(self, obj): self.repository.delete(obj) def create(self, obj): obj = self.repository.create(obj) return obj def get_all(self, query_params={}, orderby=[], select_related=[]): return self.repository.get_all(query_params, orderby, select_related) def get(self, query_params={}, select_related=[]): return self.repository.get(query_params, select_related)
# score_manager.py #Score Manager ENEMY_SCORE = 300 RUPEE_SCORE = 500 scores = { "ENEMY": ENEMY_SCORE, "RUPEE": RUPEE_SCORE, } my_scores = { "ENEMY": 300, "MONEY": 1000, "LASER": 1000, "HP": 200, "DEFENSE": 100 } def calculate_score(score_type): return my_scores[score_type]
enemy_score = 300 rupee_score = 500 scores = {'ENEMY': ENEMY_SCORE, 'RUPEE': RUPEE_SCORE} my_scores = {'ENEMY': 300, 'MONEY': 1000, 'LASER': 1000, 'HP': 200, 'DEFENSE': 100} def calculate_score(score_type): return my_scores[score_type]
''' Created on Mar 1, 2016 @author: kashefy ''' class Phase: TRAIN = 'Train' TEST = 'Test'
""" Created on Mar 1, 2016 @author: kashefy """ class Phase: train = 'Train' test = 'Test'
class Node: #Initialize node oject def __init__(self, data): self.data = data #assign data self.next = None #declare next as null class LinkedList: #Initialize head def __init__(self): self.head = None #### Insert in the beginning def push(self, content): #Allocate node, Put data new_node = Node(content) #attach head after new_node new_node.next = self.head #set new_node as current head self.head = new_node #### Insert in the middle def insertAfter(self, prev_node, content): if prev_node is None: print("Prev Node invalid") return new_node = Node(content) new_node.next = prev_node.next prev_node.next = new_node #### Insert at last def append(self, content): new_node = Node(content) #If Linkedlist is empty if self.head is None: self.head = new_node return #Else, traverse to last node last = self.head while (last.next): last = last.next #attach new node last.next = new_node ### PRINT LIST def printlist(self): temp = self.head while (temp): print(temp.data) temp = temp.next #### Delete node using key def deleteNode_key(self, key): temp = self.head #for head node if temp is not None: if temp.data == key: self.head = temp.next temp = None return #moving ahead from head node, until key found while(temp is not None): if temp.data == key: break prev = temp temp = temp.next #if not found if temp == None: return #Unlink node prev.next = temp.next temp = None #### Delete node using position def deleteNode_pos(self, pos): if self.head is None: return temp = self.head #to delete head if pos == 0: self.head = temp.next temp = None return #find previous node of the node to be deleted for i in range(pos-1): temp = temp.next if temp is None: break if temp is None: return if temp.next is None: return #store next to next node to be deleted next = temp.next.next #unlink temp.next = None temp.next = next #### Find length def listlength(self): len = 0 if self.head is None: print("Len = ",len) return temp = self.head while temp: len += 1 temp = temp.next print("Len = ", len) #### REVERSE def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev if __name__ == '__main__': list1 = LinkedList() list1.append(6) list1.append(3) list1.push(4) list1.insertAfter(list1.head.next, 1) list1.printlist() print("______") list1.listlength() print("______") list1.deleteNode_key(4) list1.printlist() print("______") list1.reverse() list1.printlist() print("______") list1.deleteNode_pos(1) list1.printlist() print("______")
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def push(self, content): new_node = node(content) new_node.next = self.head self.head = new_node def insert_after(self, prev_node, content): if prev_node is None: print('Prev Node invalid') return new_node = node(content) new_node.next = prev_node.next prev_node.next = new_node def append(self, content): new_node = node(content) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def printlist(self): temp = self.head while temp: print(temp.data) temp = temp.next def delete_node_key(self, key): temp = self.head if temp is not None: if temp.data == key: self.head = temp.next temp = None return while temp is not None: if temp.data == key: break prev = temp temp = temp.next if temp == None: return prev.next = temp.next temp = None def delete_node_pos(self, pos): if self.head is None: return temp = self.head if pos == 0: self.head = temp.next temp = None return for i in range(pos - 1): temp = temp.next if temp is None: break if temp is None: return if temp.next is None: return next = temp.next.next temp.next = None temp.next = next def listlength(self): len = 0 if self.head is None: print('Len = ', len) return temp = self.head while temp: len += 1 temp = temp.next print('Len = ', len) def reverse(self): prev = None current = self.head while current is not None: next = current.next current.next = prev prev = current current = next self.head = prev if __name__ == '__main__': list1 = linked_list() list1.append(6) list1.append(3) list1.push(4) list1.insertAfter(list1.head.next, 1) list1.printlist() print('______') list1.listlength() print('______') list1.deleteNode_key(4) list1.printlist() print('______') list1.reverse() list1.printlist() print('______') list1.deleteNode_pos(1) list1.printlist() print('______')
""" Lab 7 python file """ # print("\n3.1") current_number=-1 while current_number<6: current_number +=1 if (current_number==3 or current_number==6): continue print(current_number) # print("\n3.2") n=int(input("Enter a number:")) factorial=1 while n>=1: factorial=factorial*n n=n-1 print(factorial) # print("\n3.3") n=5 sum=0 total_numbers=n while n>=0: sum=sum+n n=n-1 print(sum) # print("\n3.4") x=3 product=1 while x in range(3,9): product=product*x x=x+1 print(product) # print("\n3.5") x=1 product=1 while x in range(1,9): product=product*x x=x+1 print(product) y=1 divisor=1 while y in range(1,4): divisor=divisor*y y=y+1 print(divisor) final_answer=(product/divisor) print(final_answer) # print("\n3.6") num_list=[12,32,43,35] print(num_list) while num_list: num_list.pop(0) print(num_list)
""" Lab 7 python file """ print('\n3.1') current_number = -1 while current_number < 6: current_number += 1 if current_number == 3 or current_number == 6: continue print(current_number) print('\n3.2') n = int(input('Enter a number:')) factorial = 1 while n >= 1: factorial = factorial * n n = n - 1 print(factorial) print('\n3.3') n = 5 sum = 0 total_numbers = n while n >= 0: sum = sum + n n = n - 1 print(sum) print('\n3.4') x = 3 product = 1 while x in range(3, 9): product = product * x x = x + 1 print(product) print('\n3.5') x = 1 product = 1 while x in range(1, 9): product = product * x x = x + 1 print(product) y = 1 divisor = 1 while y in range(1, 4): divisor = divisor * y y = y + 1 print(divisor) final_answer = product / divisor print(final_answer) print('\n3.6') num_list = [12, 32, 43, 35] print(num_list) while num_list: num_list.pop(0) print(num_list)
class Solution: # @param {character[][]} matrix # @return {integer} def maximalSquare(self, matrix): if not matrix: return 0 max_square = 0 self.visited = [] for line in matrix: row = [] for c in line: row.append(0) self.visited.append(row) self.visited[0] = [int(c) for c in matrix[0]] max_square = max(self.visited[0]) for i, row in enumerate(self.visited): k = int(matrix[i][0]) if k > max_square: max_square = k row[0] = k for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j] == "1": self.visited[i][j] = ( min( self.visited[i - 1][j], self.visited[i][j - 1], self.visited[i - 1][j - 1], ) + 1 ) if self.visited[i][j] > max_square: max_square = self.visited[i][j] return max_square ** 2
class Solution: def maximal_square(self, matrix): if not matrix: return 0 max_square = 0 self.visited = [] for line in matrix: row = [] for c in line: row.append(0) self.visited.append(row) self.visited[0] = [int(c) for c in matrix[0]] max_square = max(self.visited[0]) for (i, row) in enumerate(self.visited): k = int(matrix[i][0]) if k > max_square: max_square = k row[0] = k for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j] == '1': self.visited[i][j] = min(self.visited[i - 1][j], self.visited[i][j - 1], self.visited[i - 1][j - 1]) + 1 if self.visited[i][j] > max_square: max_square = self.visited[i][j] return max_square ** 2
#!/usr/bin/python #------------------------------------------------------------------------------ class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() result = float('inf') # Loop through each index, then use two pointers to close in the rest of the array for i in range(len(nums)-2): l, r = i+1, len(nums)-1 while l < r: # Current sum of the three elements curr_sum = nums[i] + nums[l] + nums[r] # If the difference is smaller, make it the result if abs(target - curr_sum) < abs(target - result): result = curr_sum if curr_sum == target: return curr_sum elif curr_sum < target: l += 1 else: r -= 1 return result #------------------------------------------------------------------------------ #Testing main()
class Solution: def three_sum_closest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() result = float('inf') for i in range(len(nums) - 2): (l, r) = (i + 1, len(nums) - 1) while l < r: curr_sum = nums[i] + nums[l] + nums[r] if abs(target - curr_sum) < abs(target - result): result = curr_sum if curr_sum == target: return curr_sum elif curr_sum < target: l += 1 else: r -= 1 return result main()
#! /usr/bin/python3.7 # soh cah toa def sin(): o = float(input('What is the oppisite?: ')) h = float(input("What is the hypotnuse?: ")) s = o / h print("sin = {}".format(s)) def cos(): a = float(input('What is the ajacent?: ')) h = float(input("What is the hypotnuse?: ")) c = a / h print('cos = {}'.format(c)) def tan(): o = float(input("What is the oppisite?: ")) a = float(input("What is the ajacent?: ")) t = o / a print("tan = {}".format(t)) def main(): userInt = input('What are we solving for (sin cos or tan)?: ').lower() if userInt == 'sin': sin() elif userInt == 'cos': cos() elif userInt == 'tan': tan() else: print('An error has occured please try again') main()
def sin(): o = float(input('What is the oppisite?: ')) h = float(input('What is the hypotnuse?: ')) s = o / h print('sin = {}'.format(s)) def cos(): a = float(input('What is the ajacent?: ')) h = float(input('What is the hypotnuse?: ')) c = a / h print('cos = {}'.format(c)) def tan(): o = float(input('What is the oppisite?: ')) a = float(input('What is the ajacent?: ')) t = o / a print('tan = {}'.format(t)) def main(): user_int = input('What are we solving for (sin cos or tan)?: ').lower() if userInt == 'sin': sin() elif userInt == 'cos': cos() elif userInt == 'tan': tan() else: print('An error has occured please try again') main()
# Scale Settings # For 005.mp4 SCALE_WIDTH = 25 SCALE_HEIGHT = 50 # SCALE_WIDTH = 100 # SCALE_HEIGHT = 100 # Video Settings DETECT_AFTER_N = 50 # NMS Settings NMS_CONFIDENCE = 0.1 NMS_THRESHOLD = 0.1 # Detection Settings DETECTION_CONFIDENCE = 0.9 # Tracker Settings MAX_DISAPPEARED = 50
scale_width = 25 scale_height = 50 detect_after_n = 50 nms_confidence = 0.1 nms_threshold = 0.1 detection_confidence = 0.9 max_disappeared = 50
a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) c=int(input("Enter the third number:")) if a<b in c>a: min=a elif a<b in c>b: min=b else: min=c print(min)
a = int(input('Enter the first number:')) b = int(input('Enter the second number:')) c = int(input('Enter the third number:')) if a < b in c > a: min = a elif a < b in c > b: min = b else: min = c print(min)
class setx: def __init__(self, iterable=[]): self.iterable = set(iterable) self.size = len(self.iterable) def __repr__(self): return f"<{self.__class__.__name__.lower() !a}> {self.iterable}" def add(self, element): if element not in self.iterable: self.iterable.add(element) self.size += 1 print(element, self.iterable) def add_s(self, elements): temp = list(self.iterable) temp.extend(elements) self.iterable = set(temp) self.size = len(self.iterable) def clear(self): self.iterable = setx() self.size = 0 def pop(self): if self.size < 1: raise KeyError( f"Can not pop from empyt {self.__name__.lower()}") self.iterable.pop() self.size -= 1 def get_size(self): return self.size def get_elements(self): return self.iterable def new(self, iterable=[]): # self.iterable = setx(iterable) self.iterable = iterable s = setx(self.iterable) self.size = s.get_size() def check_type(self, other): if type(other) not in [list, set, dict, tuple, setx]: raise TypeError( f"{self.__class__.__name__ !a} requires an iterable") # else: # return f"{type(other)!a}" def difference(self, other): self.check_type(other) difference = set() other = set(other) for element in self.iterable: if element not in other: difference.add(element) return difference def intersection(self, other): self.check_type(other) intersection = set() other = set(other) for element in self.iterable: if element in other: intersection.add(element) return intersection def isdisjoint(self, other): self.check_type(other) other = set(other) if not self.intersection(other): return True return False def issubset(self, other): self.check_type(other) other = list(set(other)) size_of_others = 0 for element in other: if element in self.iterable: size_of_others += 1 if size_of_others == len(other): return True return False def issuperset(self, other): self.check_type(other) other = set(other) for element in self.iterable: if element not in other: return False return True def remove(self, element): if element not in self.iterable: raise KeyError(f"{element!a} not found {self.get()}") temp = list(self.iterable) index = temp.index(element) del temp[index] self.iterable = set(temp) self.size = len(self.iterable) return index def symmetric_difference(self, other): self.check_type(other) other = set(other) intersection = self.intersection(other) symmetric_difference = set() new_set = list(self.iterable) + list(other) new_set = set(new_set) for element in new_set: if element not in intersection: symmetric_difference.add(element) return symmetric_difference def cartesian_product(self, other): # A x B = {(a, b)| a in A, b in B} # |A x B| = |A| x |B| for A, B which are finite self.check_type(other) other = set(other) size_cartesian_product = self.get_size() * len(other) cartesian_product = set() for a in self.iterable: for b in other: cartesian_product.add((a, b)) return cartesian_product, size_cartesian_product def addtoAll(self, e, setobj): for c in setobj: c.append(e) return setobj def power_set(self, temp): """ https://stackoverflow.com/a/58108857/10051170 """ if len(temp) == 0: return [[]] return self.addtoAll(temp[0], self.power_set(temp[1:])) + self.power_set(temp[1:]) # pass # Let A be a finite set, n = |A | and P(A) be the power set of A # P(A) = {X: X is a subset of A}, | P(A) | = 2 ** |A | = 2 ** n # # From the above there'd be n inserts # P(A) may have {{}, {{X}: X in A}, ..., {{x1, x2, x3, ..., xn}: x in A}} # then we'd fill up the ' ... ' # # if n > 2 # there is no repetition as such {x1, x2} is the same as {x2, x1} and so on # we could make use of 3 sets, A, tempA and tempB (where tempA and tempB # are temporary variables) # have two loops # 1 - loop(0, n - 2) # 2 - loop(0, n - 1) # take from tempA, add from A to from tempB # add tempB to the power set and make tempA tempB
class Setx: def __init__(self, iterable=[]): self.iterable = set(iterable) self.size = len(self.iterable) def __repr__(self): return f'<{self.__class__.__name__.lower()!a}> {self.iterable}' def add(self, element): if element not in self.iterable: self.iterable.add(element) self.size += 1 print(element, self.iterable) def add_s(self, elements): temp = list(self.iterable) temp.extend(elements) self.iterable = set(temp) self.size = len(self.iterable) def clear(self): self.iterable = setx() self.size = 0 def pop(self): if self.size < 1: raise key_error(f'Can not pop from empyt {self.__name__.lower()}') self.iterable.pop() self.size -= 1 def get_size(self): return self.size def get_elements(self): return self.iterable def new(self, iterable=[]): self.iterable = iterable s = setx(self.iterable) self.size = s.get_size() def check_type(self, other): if type(other) not in [list, set, dict, tuple, setx]: raise type_error(f'{self.__class__.__name__!a} requires an iterable') def difference(self, other): self.check_type(other) difference = set() other = set(other) for element in self.iterable: if element not in other: difference.add(element) return difference def intersection(self, other): self.check_type(other) intersection = set() other = set(other) for element in self.iterable: if element in other: intersection.add(element) return intersection def isdisjoint(self, other): self.check_type(other) other = set(other) if not self.intersection(other): return True return False def issubset(self, other): self.check_type(other) other = list(set(other)) size_of_others = 0 for element in other: if element in self.iterable: size_of_others += 1 if size_of_others == len(other): return True return False def issuperset(self, other): self.check_type(other) other = set(other) for element in self.iterable: if element not in other: return False return True def remove(self, element): if element not in self.iterable: raise key_error(f'{element!a} not found {self.get()}') temp = list(self.iterable) index = temp.index(element) del temp[index] self.iterable = set(temp) self.size = len(self.iterable) return index def symmetric_difference(self, other): self.check_type(other) other = set(other) intersection = self.intersection(other) symmetric_difference = set() new_set = list(self.iterable) + list(other) new_set = set(new_set) for element in new_set: if element not in intersection: symmetric_difference.add(element) return symmetric_difference def cartesian_product(self, other): self.check_type(other) other = set(other) size_cartesian_product = self.get_size() * len(other) cartesian_product = set() for a in self.iterable: for b in other: cartesian_product.add((a, b)) return (cartesian_product, size_cartesian_product) def addto_all(self, e, setobj): for c in setobj: c.append(e) return setobj def power_set(self, temp): """ https://stackoverflow.com/a/58108857/10051170 """ if len(temp) == 0: return [[]] return self.addtoAll(temp[0], self.power_set(temp[1:])) + self.power_set(temp[1:])
def cycles_until_reseen(bins): configs = set() curr = bins while tuple(curr) not in configs: configs.add(tuple(curr)) min_idx = 0 for i in range(1, len(curr)): if curr[i] > curr[min_idx]: min_idx = i redistribute = curr[min_idx] curr[min_idx] = 0 all_gains = redistribute // len(bins) partial_gain_bins = redistribute % len(bins) for i in range(len(bins)): curr[i] += all_gains if i < partial_gain_bins: curr[(min_idx+i+1) % len(bins)] += 1 return len(configs), curr if __name__ == '__main__': with open('6.txt') as f: bins = [int(i) for i in f.read().split()] num_cycles, last_seen = cycles_until_reseen(bins) print("Part 1: {}".format(num_cycles)) loop_cycles, _ = cycles_until_reseen(last_seen) print("Part 2: {}".format(loop_cycles))
def cycles_until_reseen(bins): configs = set() curr = bins while tuple(curr) not in configs: configs.add(tuple(curr)) min_idx = 0 for i in range(1, len(curr)): if curr[i] > curr[min_idx]: min_idx = i redistribute = curr[min_idx] curr[min_idx] = 0 all_gains = redistribute // len(bins) partial_gain_bins = redistribute % len(bins) for i in range(len(bins)): curr[i] += all_gains if i < partial_gain_bins: curr[(min_idx + i + 1) % len(bins)] += 1 return (len(configs), curr) if __name__ == '__main__': with open('6.txt') as f: bins = [int(i) for i in f.read().split()] (num_cycles, last_seen) = cycles_until_reseen(bins) print('Part 1: {}'.format(num_cycles)) (loop_cycles, _) = cycles_until_reseen(last_seen) print('Part 2: {}'.format(loop_cycles))
n = int(input()) count_2 = 0 count_5 = 0 for i in range(2,n+1): num = i while(1): if num%2 == 0: count_2 += 1 num //= 2 elif num%5 == 0: count_5 += 1 num //= 5 else: break print(min(count_2,count_5))
n = int(input()) count_2 = 0 count_5 = 0 for i in range(2, n + 1): num = i while 1: if num % 2 == 0: count_2 += 1 num //= 2 elif num % 5 == 0: count_5 += 1 num //= 5 else: break print(min(count_2, count_5))
# Copyright 2016-2020 Blue Marble Analytics LLC. All rights reserved. """ **Relevant tables:** +--------------------------------+----------------------------------------------+ |:code:`scenarios` table column |:code:`project_new_potential_scenario_id` | +--------------------------------+----------------------------------------------+ |:code:`scenarios` table feature |N/A | +--------------------------------+----------------------------------------------+ |:code:`subscenario_` table |:code:`subscenarios_project_new_potential` | +--------------------------------+----------------------------------------------+ |:code:`input_` tables |:code:`inputs_project_new_potential` | +--------------------------------+----------------------------------------------+ If the project portfolio includes projects of a 'new' capacity type (:code:`gen_new_bin`, :code:`gen_new_lin`, :code:`stor_new_bin`, or :code:`stor_new_lin`), the user may specify the minimum and maximum cumulative new capacity to be built in each period in the :code:`inputs_project_new_potential` table. For storage project, the minimum and maximum energy capacity may also be specified. All columns are optional and NULL values are interpreted by GridPath as no constraint. Projects that don't either a minimum or maximum cumulative new capacity constraints can be omitted from this table completely. """
""" **Relevant tables:** +--------------------------------+----------------------------------------------+ |:code:`scenarios` table column |:code:`project_new_potential_scenario_id` | +--------------------------------+----------------------------------------------+ |:code:`scenarios` table feature |N/A | +--------------------------------+----------------------------------------------+ |:code:`subscenario_` table |:code:`subscenarios_project_new_potential` | +--------------------------------+----------------------------------------------+ |:code:`input_` tables |:code:`inputs_project_new_potential` | +--------------------------------+----------------------------------------------+ If the project portfolio includes projects of a 'new' capacity type (:code:`gen_new_bin`, :code:`gen_new_lin`, :code:`stor_new_bin`, or :code:`stor_new_lin`), the user may specify the minimum and maximum cumulative new capacity to be built in each period in the :code:`inputs_project_new_potential` table. For storage project, the minimum and maximum energy capacity may also be specified. All columns are optional and NULL values are interpreted by GridPath as no constraint. Projects that don't either a minimum or maximum cumulative new capacity constraints can be omitted from this table completely. """
if 1: N = int(input()) Q = int(input()) queries = [] for i in range(Q): queries.append([int(x) for x in input().split()]) else: N = 100000 queries = [ [2, 1, 2], [4, 1, 2] ] * 10000 queries.append([4, 1, 2]) Q = len(queries) isTransposed = False xs = list(range(N + 1)) ys = list(range(N + 1)) for q in queries: f = q[0] if f == 4: i, j = q[1:] if isTransposed: i, j = j, i print(N * (xs[i] - 1) + ys[j] - 1) elif f == 3: isTransposed = not isTransposed else: i, j = q[1:] if (f == 1) ^ isTransposed: xs[i], xs[j] = xs[j], xs[i] else: ys[i], ys[j] = ys[j], ys[i]
if 1: n = int(input()) q = int(input()) queries = [] for i in range(Q): queries.append([int(x) for x in input().split()]) else: n = 100000 queries = [[2, 1, 2], [4, 1, 2]] * 10000 queries.append([4, 1, 2]) q = len(queries) is_transposed = False xs = list(range(N + 1)) ys = list(range(N + 1)) for q in queries: f = q[0] if f == 4: (i, j) = q[1:] if isTransposed: (i, j) = (j, i) print(N * (xs[i] - 1) + ys[j] - 1) elif f == 3: is_transposed = not isTransposed else: (i, j) = q[1:] if (f == 1) ^ isTransposed: (xs[i], xs[j]) = (xs[j], xs[i]) else: (ys[i], ys[j]) = (ys[j], ys[i])
# Location of the data. reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/' test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/' # Name of the test model data, used to find the climo files. test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison' # An optional, shorter name to be used instead of the test_name. short_test_name = 'beta0.FC5COSP.ne30' # What plotsets to run the diags on. sets = ['lat_lon'] # Name of the folder where the results are stored. results_dir = 'era_tas_land' # Below are more optional arguments. # 'mpl' is to create matplotlib plots, 'vcs' is for vcs plots. backend = 'mpl' # Title of the difference plots. diff_title = 'Model - Obs.' # Save the netcdf files for each of the ref, test, and diff plot. save_netcdf = True
reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/' test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/' test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison' short_test_name = 'beta0.FC5COSP.ne30' sets = ['lat_lon'] results_dir = 'era_tas_land' backend = 'mpl' diff_title = 'Model - Obs.' save_netcdf = True
# # Problem: Given an undirected graph with maximum degree, find a graph coloring using at most D+1 colors. # def color_graph_first_available(graph, colors): """ Solution: For each graph node, assign to it the first color not in the list of neighbor colors. Complexity: (where n is # nodes, d is max degrees) Time: O(n * (d + d+1 + 1)) -> O(n * d) Space: O(g) -> size of graph """ # For every node for node in graph: if node in node.neighbors: raise ValueError('cannot color graph with node loops') # Look at each neighbor and create a set of their colors neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color]) # Look at each color and create a set of available colors not in the neighbor colors set available_colors = [color for color in colors if color not in neighbor_colors] # Take the first available node.color = available_colors[0] def color_graph_first_available_slightly_faster(graph, colors): """ Solution: For each graph node, assign to it the first available color not used by one of its neighbors. Complexity: (where n is # nodes, d is max degrees) Time: O(n * d) Space: O(g) -> size of graph """ for node in graph: if node in node.neighbors: raise ValueError('cannot color graph with node loops') # Look at each neighbor and create a set of their colors neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color]) for color in colors: if color not in neighbor_colors: node.color = color break
def color_graph_first_available(graph, colors): """ Solution: For each graph node, assign to it the first color not in the list of neighbor colors. Complexity: (where n is # nodes, d is max degrees) Time: O(n * (d + d+1 + 1)) -> O(n * d) Space: O(g) -> size of graph """ for node in graph: if node in node.neighbors: raise value_error('cannot color graph with node loops') neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color]) available_colors = [color for color in colors if color not in neighbor_colors] node.color = available_colors[0] def color_graph_first_available_slightly_faster(graph, colors): """ Solution: For each graph node, assign to it the first available color not used by one of its neighbors. Complexity: (where n is # nodes, d is max degrees) Time: O(n * d) Space: O(g) -> size of graph """ for node in graph: if node in node.neighbors: raise value_error('cannot color graph with node loops') neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color]) for color in colors: if color not in neighbor_colors: node.color = color break
file_name=str(input("Input the Filename:")) if(file_name.split('.')[1]=='c'): print('The extension of the file is C') if(file_name.split('.')[1]=='cpp'): print('The extension of the file is C++') if(file_name.split('.')[1]=='java'): print('The extension of the file is Java') if(file_name.split('.')[1]=='py'): print('The extension of the file is python') if(file_name.split('.')[1]=='html'): print('The extension of the file is HTMl')
file_name = str(input('Input the Filename:')) if file_name.split('.')[1] == 'c': print('The extension of the file is C') if file_name.split('.')[1] == 'cpp': print('The extension of the file is C++') if file_name.split('.')[1] == 'java': print('The extension of the file is Java') if file_name.split('.')[1] == 'py': print('The extension of the file is python') if file_name.split('.')[1] == 'html': print('The extension of the file is HTMl')
# # PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:54:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint") chassis, = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-MIB", "chassis") groups, regModule = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-REG", "groups", "regModule") Index, INT32withException, Power, PowerLedStates, IdromBinary16, FaultLedStates, FeatureSet, PresenceLedStates, Presence = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-TC", "Index", "INT32withException", "Power", "PowerLedStates", "IdromBinary16", "FaultLedStates", "FeatureSet", "PresenceLedStates", "Presence") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") Unsigned32, ModuleIdentity, Integer32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ObjectIdentity, Counter64, TimeTicks, Counter32, Bits, iso, IpAddress, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "ModuleIdentity", "Integer32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "ObjectIdentity", "Counter64", "TimeTicks", "Counter32", "Bits", "iso", "IpAddress", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") multiFlexServerDrivesMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 1, 1, 15)) multiFlexServerDrivesMibModule.setRevisions(('2007-08-16 12:00', '2007-07-20 16:45', '2007-06-07 20:30', '2007-06-07 13:30', '2007-05-30 17:00', '2007-04-18 19:05', '2007-04-09 15:45', '2007-04-09 15:30', '2007-03-27 11:30', '2007-03-14 11:30', '2007-03-06 10:30', '2007-02-22 17:00', '2006-12-28 17:30', '2006-12-05 10:30', '2006-11-27 15:30', '2006-11-20 13:30', '2006-11-07 11:30', '2006-10-02 10:24',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setRevisionsDescriptions(('Fixed up minor errors causing some managers grief (ommission or addition of commas in lists) Corrected a few entries that were marked as read-write when they should have been read-only', 'Minor edit to make MIB SMIv2 compliant Dropped driveBackplaneBmcFirmwareVersion as there is no BMC for the drive backplane', 'Added the IdromBinary16 to represent the asset tag, part number, and serial number fields within the IDROM fields.', 'Corrected maximum/nominal IDROM parameters and comments', 'Added enumeration for exceptions Added missing Presence column to sharedDriveTable', 'Moved the trees and chassis nodes around to accomodate the unique power supply characteristics', 'Moved driveBackplane IDROM data to sharedDrives tree from storage tree where it makes more logical sense Relocated both tables after the driveBackplane tree', 'Dropped sDriveAlias', 'Renamed all references of Array to StoragePool', 'Renamed all references of Disk to Drive Dropped redundant sDriveIndex (moved and replaced it with sDriveSlotNumber)', "Changed Mask representation from an Opaque to a DisplayString at the request of the architects such that it now is an ASCII representation of bit string reflecting the presence with the left most 'bit' being bit 1 and max* bits being represented.", 'Renamed MIB file and updated internal relevance to formal product name Multi-Flex Server', 'Corrected sharedDiskStatsTable INDEX to AUGMENTS.', "Updated several object types to reflect changes in the OEM objects. sDiskArrayID Integer32 -> INTEGER sDiskSequenceNumber Integer32 -> INTEGER sDiskDriveType DisplayString -> INTEGER Cleaned up some illegal character usage to make it SMIv2 compliant. Renamed all of the *Transfered to *Transferred Renumbered sharedDiskStatsTable to match OEM's.", 'Removed nolonger supported SATA & SAS drive feature tables Renumbered Stats from { sharedDisks 4 } to { sharedDisks 2 }', 'Replaced sharedDisksStats table index with sDiskIndex to be consistent with the rest of the tables. All tables are indexed by the drive ID', "Consolodated use of Presence datatype and changed 'chassis' to 'chassis'", "Partitioned off and created as it's own module",)) if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setLastUpdated('200708161200Z') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setOrganization('Intel Corporation') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setContactInfo('Brian Kurle Intel Corporation JF5-2-C3 Tel: 503-712-5032 E-Mail: brianx.j.kurle@intel.com') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setDescription('Shared Disks Module of the Multi-Flex Server') maxSharedDrives = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 15), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: maxSharedDrives.setStatus('current') if mibBuilder.loadTexts: maxSharedDrives.setDescription('Maximum number of Shared Drives possible in this chassis') numOfSharedDrives = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 25), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: numOfSharedDrives.setStatus('current') if mibBuilder.loadTexts: numOfSharedDrives.setDescription('The number of Shared Drives in the system') sDrivePresenceMask = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 35), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDrivePresenceMask.setStatus('current') if mibBuilder.loadTexts: sDrivePresenceMask.setDescription("ASCII representation of bit string reflecting the presence of the shared drives with the left most 'bit' being bit 1 and maxSharedDrives bits being represented. Thus, '11001111111111' would express that all the shared drives (of fourteen shared drives) are present with exception of drives 3 & 4") sharedDrives = ObjectIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205)) if mibBuilder.loadTexts: sharedDrives.setStatus('current') if mibBuilder.loadTexts: sharedDrives.setDescription('Container for Shared Drive specific information as well as all components logically contained within.') driveBackplane = ObjectIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1)) if mibBuilder.loadTexts: driveBackplane.setStatus('current') if mibBuilder.loadTexts: driveBackplane.setDescription('IDROM information from the Drive Backplane') driveBackplaneVendor = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneVendor.setStatus('current') if mibBuilder.loadTexts: driveBackplaneVendor.setDescription('Device manufacturer') driveBackplaneMfgDate = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneMfgDate.setStatus('current') if mibBuilder.loadTexts: driveBackplaneMfgDate.setDescription('Manufacture date/time') driveBackplaneDeviceName = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneDeviceName.setStatus('current') if mibBuilder.loadTexts: driveBackplaneDeviceName.setDescription('Device Name') driveBackplanePart = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 4), IdromBinary16()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplanePart.setStatus('current') if mibBuilder.loadTexts: driveBackplanePart.setDescription('Device Part Number') driveBackplaneSerialNo = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 5), IdromBinary16()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneSerialNo.setStatus('current') if mibBuilder.loadTexts: driveBackplaneSerialNo.setDescription('Device Serial Number') driveBackplaneMaximumPower = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 6), Power()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneMaximumPower.setStatus('current') if mibBuilder.loadTexts: driveBackplaneMaximumPower.setDescription('Static maximum power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Maximum power generation/consumption not known or specified') driveBackplaneNominalPower = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 7), Power()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneNominalPower.setStatus('current') if mibBuilder.loadTexts: driveBackplaneNominalPower.setDescription('Static Nominal power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Nominal power generation/consumption not known or specified') driveBackplaneAssetTag = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 8), IdromBinary16()).setMaxAccess("readonly") if mibBuilder.loadTexts: driveBackplaneAssetTag.setStatus('current') if mibBuilder.loadTexts: driveBackplaneAssetTag.setDescription('Asset Tag # of device') sharedDriveTable = MibTable((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2), ) if mibBuilder.loadTexts: sharedDriveTable.setStatus('current') if mibBuilder.loadTexts: sharedDriveTable.setDescription('Each row describes a shared drive in the chassis') sharedDriveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1), ).setIndexNames((0, "INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSlotNumber")) if mibBuilder.loadTexts: sharedDriveEntry.setStatus('current') if mibBuilder.loadTexts: sharedDriveEntry.setDescription('The parameters of a physical drive.') sDriveSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 1), Index()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveSlotNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSlotNumber.setDescription('The slot number on the enclosure where the drive is located (drive ID)') sDrivePresence = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 2), Presence()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDrivePresence.setStatus('current') if mibBuilder.loadTexts: sDrivePresence.setDescription('column used to flag the existence of a particular FRU') sDriveInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveInterface.setStatus('current') if mibBuilder.loadTexts: sDriveInterface.setDescription('The Drive Interface of the physical drive.') sDriveModelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveModelNumber.setStatus('current') if mibBuilder.loadTexts: sDriveModelNumber.setDescription('The Model Number of the physical drive.') sDriveSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveSerialNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSerialNumber.setDescription('The Serial Number of the physical drive.') sDriveFirmwareVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 6), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveFirmwareVersion.setStatus('current') if mibBuilder.loadTexts: sDriveFirmwareVersion.setDescription('The Firmware Version of the physical drive.') sDriveProtocolVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveProtocolVersion.setStatus('current') if mibBuilder.loadTexts: sDriveProtocolVersion.setDescription('The Protocol Version of the physical drive.') sDriveOperationalStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveOperationalStatus.setStatus('current') if mibBuilder.loadTexts: sDriveOperationalStatus.setDescription('The Operational Status of the physical drive.') sDriveCondition = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 9), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveCondition.setStatus('current') if mibBuilder.loadTexts: sDriveCondition.setDescription('The condition of the physical drive, e.g. PFA.') sDriveOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveOperation.setStatus('current') if mibBuilder.loadTexts: sDriveOperation.setDescription('The current operation on the physical drive, e.g. mediapatrolling, migrating.') sDriveConfiguration = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 11), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveConfiguration.setStatus('current') if mibBuilder.loadTexts: sDriveConfiguration.setDescription('The configuration on the physical drive, e.g. array %d seqno %d, or dedicated spare.') sDriveStoragePoolID = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1, 256))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1), ("notavailable", 256)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStoragePoolID.setStatus('current') if mibBuilder.loadTexts: sDriveStoragePoolID.setDescription('The drive array id, if the physical drive is part of a drive array; the spare id, if the drive is a spare.') sDriveSequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveSequenceNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSequenceNumber.setDescription('The sequence number of the drive in the drive array. Valid only when the drive is part of a drive array.') sDriveEnclosureID = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 14), INT32withException()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveEnclosureID.setStatus('current') if mibBuilder.loadTexts: sDriveEnclosureID.setDescription('The id of the enclosure to which the drive is inserted.') sDriveBlockSize = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 15), INT32withException()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveBlockSize.setStatus('current') if mibBuilder.loadTexts: sDriveBlockSize.setDescription(' The Block Size in bytes of the physical drive.') sDrivePhysicalCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 16), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDrivePhysicalCapacity.setStatus('current') if mibBuilder.loadTexts: sDrivePhysicalCapacity.setDescription(' The Physical Size in bytes of the physical drive.') sDriveConfigurableCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 17), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveConfigurableCapacity.setStatus('current') if mibBuilder.loadTexts: sDriveConfigurableCapacity.setDescription(' The Configurable Size in bytes of the physical drive.') sDriveUsedCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 18), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveUsedCapacity.setStatus('current') if mibBuilder.loadTexts: sDriveUsedCapacity.setDescription('The Used Size in bytes of the physical drive.') sDriveType = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1, 1, 4))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1), ("sata", 1), ("sas", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveType.setStatus('current') if mibBuilder.loadTexts: sDriveType.setDescription('The type of the physical drive. e.g. SATA or SAS') sharedDriveStatsTable = MibTable((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3), ) if mibBuilder.loadTexts: sharedDriveStatsTable.setStatus('current') if mibBuilder.loadTexts: sharedDriveStatsTable.setDescription('A table of Physical Drive Statistics (augments sharedDriveTable)') sharedDriveStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1), ) sharedDriveEntry.registerAugmentions(("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sharedDriveStatsEntry")) sharedDriveStatsEntry.setIndexNames(*sharedDriveEntry.getIndexNames()) if mibBuilder.loadTexts: sharedDriveStatsEntry.setStatus('current') if mibBuilder.loadTexts: sharedDriveStatsEntry.setDescription('The statistics of a physical drive since its last reset or statistics rest.') sDriveStatsDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 1), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsDataTransferred.setDescription('The total number of bytes of data transfered to and from the controller.') sDriveStatsReadDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setDescription('The total number of bytes of data transfered from the controller.') sDriveStatsWriteDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setDescription('The total number of bytes of data transfered to the controller.') sDriveStatsNumOfErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setDescription('The total number of errors.') sDriveStatsNumOfNonRWErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setDescription('The total number of non-RW errors.') sDriveStatsNumOfReadErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setDescription('The total number of Read errors.') sDriveStatsNumOfWriteErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setDescription('The total number of Write errors.') sDriveStatsNumOfIORequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setDescription('The total number of IO requests.') sDriveStatsNumOfNonRWRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 9), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setDescription('The total number of non-RW requests.') sDriveStatsNumOfReadRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setDescription('The total number of read requests.') sDriveStatsNumOfWriteRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setDescription('The total number of write requests.') sDriveStatsStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsStartTime.setStatus('current') if mibBuilder.loadTexts: sDriveStatsStartTime.setDescription('The time when the statistics date starts to accumulate since last statistics reset.') sDriveStatsCollectionTime = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 13), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: sDriveStatsCollectionTime.setStatus('current') if mibBuilder.loadTexts: sDriveStatsCollectionTime.setDescription('The time when the statistics data was collected or updated last time.') sDriveGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 2, 2, 15)).setObjects(("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "maxSharedDrives"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "numOfSharedDrives"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePresenceMask"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneVendor"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneMfgDate"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneDeviceName"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplanePart"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneSerialNo"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneMaximumPower"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneNominalPower"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneAssetTag"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSlotNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePresence"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveInterface"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveModelNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSerialNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveFirmwareVersion"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveProtocolVersion"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveOperationalStatus"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveCondition"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveOperation"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveConfiguration"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStoragePoolID"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSequenceNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveEnclosureID"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveBlockSize"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePhysicalCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveConfigurableCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveUsedCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveType"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsReadDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsWriteDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfNonRWErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfReadErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfWriteErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfIORequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfNonRWRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfReadRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfWriteRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsStartTime"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsCollectionTime")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): sDriveGroup = sDriveGroup.setStatus('current') if mibBuilder.loadTexts: sDriveGroup.setDescription('Description.') mibBuilder.exportSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", sharedDriveStatsEntry=sharedDriveStatsEntry, sDriveStoragePoolID=sDriveStoragePoolID, driveBackplanePart=driveBackplanePart, multiFlexServerDrivesMibModule=multiFlexServerDrivesMibModule, driveBackplaneMaximumPower=driveBackplaneMaximumPower, driveBackplaneSerialNo=driveBackplaneSerialNo, driveBackplaneAssetTag=driveBackplaneAssetTag, sDriveStatsNumOfWriteErrors=sDriveStatsNumOfWriteErrors, sDriveUsedCapacity=sDriveUsedCapacity, driveBackplaneNominalPower=driveBackplaneNominalPower, sharedDrives=sharedDrives, sDriveStatsCollectionTime=sDriveStatsCollectionTime, sDriveOperationalStatus=sDriveOperationalStatus, sDrivePresence=sDrivePresence, sDriveInterface=sDriveInterface, sDrivePhysicalCapacity=sDrivePhysicalCapacity, maxSharedDrives=maxSharedDrives, sharedDriveStatsTable=sharedDriveStatsTable, sDriveStatsNumOfReadErrors=sDriveStatsNumOfReadErrors, sDriveType=sDriveType, sDriveStatsNumOfIORequests=sDriveStatsNumOfIORequests, sDriveSerialNumber=sDriveSerialNumber, sDriveGroup=sDriveGroup, sDrivePresenceMask=sDrivePresenceMask, sDriveModelNumber=sDriveModelNumber, driveBackplane=driveBackplane, numOfSharedDrives=numOfSharedDrives, sDriveConfiguration=sDriveConfiguration, sDriveStatsNumOfErrors=sDriveStatsNumOfErrors, driveBackplaneVendor=driveBackplaneVendor, sDriveStatsNumOfNonRWRequests=sDriveStatsNumOfNonRWRequests, sDriveStatsNumOfWriteRequests=sDriveStatsNumOfWriteRequests, sharedDriveEntry=sharedDriveEntry, sDriveBlockSize=sDriveBlockSize, sDriveSlotNumber=sDriveSlotNumber, driveBackplaneMfgDate=driveBackplaneMfgDate, sDriveFirmwareVersion=sDriveFirmwareVersion, sDriveSequenceNumber=sDriveSequenceNumber, driveBackplaneDeviceName=driveBackplaneDeviceName, sDriveConfigurableCapacity=sDriveConfigurableCapacity, sDriveStatsStartTime=sDriveStatsStartTime, sDriveProtocolVersion=sDriveProtocolVersion, sDriveEnclosureID=sDriveEnclosureID, sDriveStatsDataTransferred=sDriveStatsDataTransferred, sDriveStatsWriteDataTransferred=sDriveStatsWriteDataTransferred, sDriveStatsNumOfNonRWErrors=sDriveStatsNumOfNonRWErrors, PYSNMP_MODULE_ID=multiFlexServerDrivesMibModule, sDriveStatsNumOfReadRequests=sDriveStatsNumOfReadRequests, sDriveCondition=sDriveCondition, sDriveOperation=sDriveOperation, sDriveStatsReadDataTransferred=sDriveStatsReadDataTransferred, sharedDriveTable=sharedDriveTable)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint') (chassis,) = mibBuilder.importSymbols('INTELCORPORATION-MULTI-FLEX-SERVER-MIB', 'chassis') (groups, reg_module) = mibBuilder.importSymbols('INTELCORPORATION-MULTI-FLEX-SERVER-REG', 'groups', 'regModule') (index, int32with_exception, power, power_led_states, idrom_binary16, fault_led_states, feature_set, presence_led_states, presence) = mibBuilder.importSymbols('INTELCORPORATION-MULTI-FLEX-SERVER-TC', 'Index', 'INT32withException', 'Power', 'PowerLedStates', 'IdromBinary16', 'FaultLedStates', 'FeatureSet', 'PresenceLedStates', 'Presence') (object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup') (unsigned32, module_identity, integer32, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, object_identity, counter64, time_ticks, counter32, bits, iso, ip_address, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'ModuleIdentity', 'Integer32', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'ObjectIdentity', 'Counter64', 'TimeTicks', 'Counter32', 'Bits', 'iso', 'IpAddress', 'MibIdentifier') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') multi_flex_server_drives_mib_module = module_identity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 1, 1, 15)) multiFlexServerDrivesMibModule.setRevisions(('2007-08-16 12:00', '2007-07-20 16:45', '2007-06-07 20:30', '2007-06-07 13:30', '2007-05-30 17:00', '2007-04-18 19:05', '2007-04-09 15:45', '2007-04-09 15:30', '2007-03-27 11:30', '2007-03-14 11:30', '2007-03-06 10:30', '2007-02-22 17:00', '2006-12-28 17:30', '2006-12-05 10:30', '2006-11-27 15:30', '2006-11-20 13:30', '2006-11-07 11:30', '2006-10-02 10:24')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setRevisionsDescriptions(('Fixed up minor errors causing some managers grief (ommission or addition of commas in lists) Corrected a few entries that were marked as read-write when they should have been read-only', 'Minor edit to make MIB SMIv2 compliant Dropped driveBackplaneBmcFirmwareVersion as there is no BMC for the drive backplane', 'Added the IdromBinary16 to represent the asset tag, part number, and serial number fields within the IDROM fields.', 'Corrected maximum/nominal IDROM parameters and comments', 'Added enumeration for exceptions Added missing Presence column to sharedDriveTable', 'Moved the trees and chassis nodes around to accomodate the unique power supply characteristics', 'Moved driveBackplane IDROM data to sharedDrives tree from storage tree where it makes more logical sense Relocated both tables after the driveBackplane tree', 'Dropped sDriveAlias', 'Renamed all references of Array to StoragePool', 'Renamed all references of Disk to Drive Dropped redundant sDriveIndex (moved and replaced it with sDriveSlotNumber)', "Changed Mask representation from an Opaque to a DisplayString at the request of the architects such that it now is an ASCII representation of bit string reflecting the presence with the left most 'bit' being bit 1 and max* bits being represented.", 'Renamed MIB file and updated internal relevance to formal product name Multi-Flex Server', 'Corrected sharedDiskStatsTable INDEX to AUGMENTS.', "Updated several object types to reflect changes in the OEM objects. sDiskArrayID Integer32 -> INTEGER sDiskSequenceNumber Integer32 -> INTEGER sDiskDriveType DisplayString -> INTEGER Cleaned up some illegal character usage to make it SMIv2 compliant. Renamed all of the *Transfered to *Transferred Renumbered sharedDiskStatsTable to match OEM's.", 'Removed nolonger supported SATA & SAS drive feature tables Renumbered Stats from { sharedDisks 4 } to { sharedDisks 2 }', 'Replaced sharedDisksStats table index with sDiskIndex to be consistent with the rest of the tables. All tables are indexed by the drive ID', "Consolodated use of Presence datatype and changed 'chassis' to 'chassis'", "Partitioned off and created as it's own module")) if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setLastUpdated('200708161200Z') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setOrganization('Intel Corporation') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setContactInfo('Brian Kurle Intel Corporation JF5-2-C3 Tel: 503-712-5032 E-Mail: brianx.j.kurle@intel.com') if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setDescription('Shared Disks Module of the Multi-Flex Server') max_shared_drives = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 15), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: maxSharedDrives.setStatus('current') if mibBuilder.loadTexts: maxSharedDrives.setDescription('Maximum number of Shared Drives possible in this chassis') num_of_shared_drives = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 25), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: numOfSharedDrives.setStatus('current') if mibBuilder.loadTexts: numOfSharedDrives.setDescription('The number of Shared Drives in the system') s_drive_presence_mask = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 35), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDrivePresenceMask.setStatus('current') if mibBuilder.loadTexts: sDrivePresenceMask.setDescription("ASCII representation of bit string reflecting the presence of the shared drives with the left most 'bit' being bit 1 and maxSharedDrives bits being represented. Thus, '11001111111111' would express that all the shared drives (of fourteen shared drives) are present with exception of drives 3 & 4") shared_drives = object_identity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205)) if mibBuilder.loadTexts: sharedDrives.setStatus('current') if mibBuilder.loadTexts: sharedDrives.setDescription('Container for Shared Drive specific information as well as all components logically contained within.') drive_backplane = object_identity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1)) if mibBuilder.loadTexts: driveBackplane.setStatus('current') if mibBuilder.loadTexts: driveBackplane.setDescription('IDROM information from the Drive Backplane') drive_backplane_vendor = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneVendor.setStatus('current') if mibBuilder.loadTexts: driveBackplaneVendor.setDescription('Device manufacturer') drive_backplane_mfg_date = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneMfgDate.setStatus('current') if mibBuilder.loadTexts: driveBackplaneMfgDate.setDescription('Manufacture date/time') drive_backplane_device_name = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneDeviceName.setStatus('current') if mibBuilder.loadTexts: driveBackplaneDeviceName.setDescription('Device Name') drive_backplane_part = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 4), idrom_binary16()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplanePart.setStatus('current') if mibBuilder.loadTexts: driveBackplanePart.setDescription('Device Part Number') drive_backplane_serial_no = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 5), idrom_binary16()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneSerialNo.setStatus('current') if mibBuilder.loadTexts: driveBackplaneSerialNo.setDescription('Device Serial Number') drive_backplane_maximum_power = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 6), power()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneMaximumPower.setStatus('current') if mibBuilder.loadTexts: driveBackplaneMaximumPower.setDescription('Static maximum power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Maximum power generation/consumption not known or specified') drive_backplane_nominal_power = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 7), power()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneNominalPower.setStatus('current') if mibBuilder.loadTexts: driveBackplaneNominalPower.setDescription('Static Nominal power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Nominal power generation/consumption not known or specified') drive_backplane_asset_tag = mib_scalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 8), idrom_binary16()).setMaxAccess('readonly') if mibBuilder.loadTexts: driveBackplaneAssetTag.setStatus('current') if mibBuilder.loadTexts: driveBackplaneAssetTag.setDescription('Asset Tag # of device') shared_drive_table = mib_table((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2)) if mibBuilder.loadTexts: sharedDriveTable.setStatus('current') if mibBuilder.loadTexts: sharedDriveTable.setDescription('Each row describes a shared drive in the chassis') shared_drive_entry = mib_table_row((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1)).setIndexNames((0, 'INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveSlotNumber')) if mibBuilder.loadTexts: sharedDriveEntry.setStatus('current') if mibBuilder.loadTexts: sharedDriveEntry.setDescription('The parameters of a physical drive.') s_drive_slot_number = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 1), index()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveSlotNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSlotNumber.setDescription('The slot number on the enclosure where the drive is located (drive ID)') s_drive_presence = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 2), presence()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDrivePresence.setStatus('current') if mibBuilder.loadTexts: sDrivePresence.setDescription('column used to flag the existence of a particular FRU') s_drive_interface = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveInterface.setStatus('current') if mibBuilder.loadTexts: sDriveInterface.setDescription('The Drive Interface of the physical drive.') s_drive_model_number = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveModelNumber.setStatus('current') if mibBuilder.loadTexts: sDriveModelNumber.setDescription('The Model Number of the physical drive.') s_drive_serial_number = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveSerialNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSerialNumber.setDescription('The Serial Number of the physical drive.') s_drive_firmware_version = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 6), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveFirmwareVersion.setStatus('current') if mibBuilder.loadTexts: sDriveFirmwareVersion.setDescription('The Firmware Version of the physical drive.') s_drive_protocol_version = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 7), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveProtocolVersion.setStatus('current') if mibBuilder.loadTexts: sDriveProtocolVersion.setDescription('The Protocol Version of the physical drive.') s_drive_operational_status = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveOperationalStatus.setStatus('current') if mibBuilder.loadTexts: sDriveOperationalStatus.setDescription('The Operational Status of the physical drive.') s_drive_condition = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 9), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveCondition.setStatus('current') if mibBuilder.loadTexts: sDriveCondition.setDescription('The condition of the physical drive, e.g. PFA.') s_drive_operation = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 10), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveOperation.setStatus('current') if mibBuilder.loadTexts: sDriveOperation.setDescription('The current operation on the physical drive, e.g. mediapatrolling, migrating.') s_drive_configuration = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 11), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveConfiguration.setStatus('current') if mibBuilder.loadTexts: sDriveConfiguration.setDescription('The configuration on the physical drive, e.g. array %d seqno %d, or dedicated spare.') s_drive_storage_pool_id = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(-32, -16, -1, 256))).clone(namedValues=named_values(('notApplicable', -32), ('unknown', -16), ('unavailable', -1), ('notavailable', 256)))).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStoragePoolID.setStatus('current') if mibBuilder.loadTexts: sDriveStoragePoolID.setDescription('The drive array id, if the physical drive is part of a drive array; the spare id, if the drive is a spare.') s_drive_sequence_number = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(-32, -16, -1))).clone(namedValues=named_values(('notApplicable', -32), ('unknown', -16), ('unavailable', -1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveSequenceNumber.setStatus('current') if mibBuilder.loadTexts: sDriveSequenceNumber.setDescription('The sequence number of the drive in the drive array. Valid only when the drive is part of a drive array.') s_drive_enclosure_id = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 14), int32with_exception()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveEnclosureID.setStatus('current') if mibBuilder.loadTexts: sDriveEnclosureID.setDescription('The id of the enclosure to which the drive is inserted.') s_drive_block_size = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 15), int32with_exception()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveBlockSize.setStatus('current') if mibBuilder.loadTexts: sDriveBlockSize.setDescription(' The Block Size in bytes of the physical drive.') s_drive_physical_capacity = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 16), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDrivePhysicalCapacity.setStatus('current') if mibBuilder.loadTexts: sDrivePhysicalCapacity.setDescription(' The Physical Size in bytes of the physical drive.') s_drive_configurable_capacity = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 17), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveConfigurableCapacity.setStatus('current') if mibBuilder.loadTexts: sDriveConfigurableCapacity.setDescription(' The Configurable Size in bytes of the physical drive.') s_drive_used_capacity = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 18), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveUsedCapacity.setStatus('current') if mibBuilder.loadTexts: sDriveUsedCapacity.setDescription('The Used Size in bytes of the physical drive.') s_drive_type = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 19), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(-32, -16, -1, 1, 4))).clone(namedValues=named_values(('notApplicable', -32), ('unknown', -16), ('unavailable', -1), ('sata', 1), ('sas', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveType.setStatus('current') if mibBuilder.loadTexts: sDriveType.setDescription('The type of the physical drive. e.g. SATA or SAS') shared_drive_stats_table = mib_table((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3)) if mibBuilder.loadTexts: sharedDriveStatsTable.setStatus('current') if mibBuilder.loadTexts: sharedDriveStatsTable.setDescription('A table of Physical Drive Statistics (augments sharedDriveTable)') shared_drive_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1)) sharedDriveEntry.registerAugmentions(('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sharedDriveStatsEntry')) sharedDriveStatsEntry.setIndexNames(*sharedDriveEntry.getIndexNames()) if mibBuilder.loadTexts: sharedDriveStatsEntry.setStatus('current') if mibBuilder.loadTexts: sharedDriveStatsEntry.setDescription('The statistics of a physical drive since its last reset or statistics rest.') s_drive_stats_data_transferred = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 1), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsDataTransferred.setDescription('The total number of bytes of data transfered to and from the controller.') s_drive_stats_read_data_transferred = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 2), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setDescription('The total number of bytes of data transfered from the controller.') s_drive_stats_write_data_transferred = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 3), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setStatus('current') if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setDescription('The total number of bytes of data transfered to the controller.') s_drive_stats_num_of_errors = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setDescription('The total number of errors.') s_drive_stats_num_of_non_rw_errors = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setDescription('The total number of non-RW errors.') s_drive_stats_num_of_read_errors = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setDescription('The total number of Read errors.') s_drive_stats_num_of_write_errors = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setDescription('The total number of Write errors.') s_drive_stats_num_of_io_requests = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 8), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setDescription('The total number of IO requests.') s_drive_stats_num_of_non_rw_requests = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 9), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setDescription('The total number of non-RW requests.') s_drive_stats_num_of_read_requests = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 10), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setDescription('The total number of read requests.') s_drive_stats_num_of_write_requests = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 11), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setStatus('current') if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setDescription('The total number of write requests.') s_drive_stats_start_time = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 12), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsStartTime.setStatus('current') if mibBuilder.loadTexts: sDriveStatsStartTime.setDescription('The time when the statistics date starts to accumulate since last statistics reset.') s_drive_stats_collection_time = mib_table_column((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 13), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: sDriveStatsCollectionTime.setStatus('current') if mibBuilder.loadTexts: sDriveStatsCollectionTime.setDescription('The time when the statistics data was collected or updated last time.') s_drive_group = object_group((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 2, 2, 15)).setObjects(('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'maxSharedDrives'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'numOfSharedDrives'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDrivePresenceMask'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneVendor'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneMfgDate'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneDeviceName'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplanePart'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneSerialNo'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneMaximumPower'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneNominalPower'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'driveBackplaneAssetTag'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveSlotNumber'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDrivePresence'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveInterface'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveModelNumber'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveSerialNumber'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveFirmwareVersion'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveProtocolVersion'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveOperationalStatus'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveCondition'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveOperation'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveConfiguration'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStoragePoolID'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveSequenceNumber'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveEnclosureID'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveBlockSize'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDrivePhysicalCapacity'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveConfigurableCapacity'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveUsedCapacity'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveType'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsDataTransferred'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsReadDataTransferred'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsWriteDataTransferred'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfErrors'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfNonRWErrors'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfReadErrors'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfWriteErrors'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfIORequests'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfNonRWRequests'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfReadRequests'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsNumOfWriteRequests'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsStartTime'), ('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', 'sDriveStatsCollectionTime')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): s_drive_group = sDriveGroup.setStatus('current') if mibBuilder.loadTexts: sDriveGroup.setDescription('Description.') mibBuilder.exportSymbols('INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB', sharedDriveStatsEntry=sharedDriveStatsEntry, sDriveStoragePoolID=sDriveStoragePoolID, driveBackplanePart=driveBackplanePart, multiFlexServerDrivesMibModule=multiFlexServerDrivesMibModule, driveBackplaneMaximumPower=driveBackplaneMaximumPower, driveBackplaneSerialNo=driveBackplaneSerialNo, driveBackplaneAssetTag=driveBackplaneAssetTag, sDriveStatsNumOfWriteErrors=sDriveStatsNumOfWriteErrors, sDriveUsedCapacity=sDriveUsedCapacity, driveBackplaneNominalPower=driveBackplaneNominalPower, sharedDrives=sharedDrives, sDriveStatsCollectionTime=sDriveStatsCollectionTime, sDriveOperationalStatus=sDriveOperationalStatus, sDrivePresence=sDrivePresence, sDriveInterface=sDriveInterface, sDrivePhysicalCapacity=sDrivePhysicalCapacity, maxSharedDrives=maxSharedDrives, sharedDriveStatsTable=sharedDriveStatsTable, sDriveStatsNumOfReadErrors=sDriveStatsNumOfReadErrors, sDriveType=sDriveType, sDriveStatsNumOfIORequests=sDriveStatsNumOfIORequests, sDriveSerialNumber=sDriveSerialNumber, sDriveGroup=sDriveGroup, sDrivePresenceMask=sDrivePresenceMask, sDriveModelNumber=sDriveModelNumber, driveBackplane=driveBackplane, numOfSharedDrives=numOfSharedDrives, sDriveConfiguration=sDriveConfiguration, sDriveStatsNumOfErrors=sDriveStatsNumOfErrors, driveBackplaneVendor=driveBackplaneVendor, sDriveStatsNumOfNonRWRequests=sDriveStatsNumOfNonRWRequests, sDriveStatsNumOfWriteRequests=sDriveStatsNumOfWriteRequests, sharedDriveEntry=sharedDriveEntry, sDriveBlockSize=sDriveBlockSize, sDriveSlotNumber=sDriveSlotNumber, driveBackplaneMfgDate=driveBackplaneMfgDate, sDriveFirmwareVersion=sDriveFirmwareVersion, sDriveSequenceNumber=sDriveSequenceNumber, driveBackplaneDeviceName=driveBackplaneDeviceName, sDriveConfigurableCapacity=sDriveConfigurableCapacity, sDriveStatsStartTime=sDriveStatsStartTime, sDriveProtocolVersion=sDriveProtocolVersion, sDriveEnclosureID=sDriveEnclosureID, sDriveStatsDataTransferred=sDriveStatsDataTransferred, sDriveStatsWriteDataTransferred=sDriveStatsWriteDataTransferred, sDriveStatsNumOfNonRWErrors=sDriveStatsNumOfNonRWErrors, PYSNMP_MODULE_ID=multiFlexServerDrivesMibModule, sDriveStatsNumOfReadRequests=sDriveStatsNumOfReadRequests, sDriveCondition=sDriveCondition, sDriveOperation=sDriveOperation, sDriveStatsReadDataTransferred=sDriveStatsReadDataTransferred, sharedDriveTable=sharedDriveTable)
def delUser(cur,con,loginid): try: query = "DELETE FROM USER WHERE Login_id='%s'" % (loginid) #print(query) cur.execute(query) con.commit() print("Deleted from Database") except Exception as e: con.rollback() print("Failed to delete from database") print(">>>>>>>>>>>>>", e) return def delStaff(cur,con): try: row = {} row["Staff_id"] = input("Enter Staff ID to delete: ") row["Login_id"] = "STAFF" + row["Staff_id"] query = "SELECT Department_id FROM WORKS_FOR WHERE Staff_id='%s'" % (row["Staff_id"]) cur.execute(query) row["dep"] = cur.fetchone()['Department_id'] con.commit() query = "UPDATE DEPARTMENT SET No_of_employees=No_of_employees - 1 WHERE Department_id='%s'" % (row["dep"]) cur.execute(query) con.commit() query = "DELETE FROM WORKS_FOR WHERE Staff_id='%s'" % (row["Staff_id"]) #print(query) cur.execute(query) con.commit() query = "DELETE FROM STAFF_SKILLS WHERE Staff_id='%s'" % (row["Staff_id"]) #print(query) cur.execute(query) con.commit() query = "DELETE FROM STAFF WHERE Login_id='%s'" % (row["Login_id"]) #print(query) cur.execute(query) con.commit() delUser(cur,con,row["Login_id"]) except Exception as e: con.rollback() print("Failed to delete from database") print(">>>>>>>>>>>>>", e) return def delDonor(cur,con): try: row = {} row["Donor_id"] = input("Enter Donor ID to delete: ") row["Login_id"] = "DONOR" + row["Donor_id"] query = "DELETE FROM DONOR WHERE Donor_id='%s'" % (row["Donor_id"]) #print(query) cur.execute(query) con.commit() delUser(cur,con,row["Login_id"]) except Exception as e: con.rollback() print("Failed to delete from database") print(">>>>>>>>>>>>>", e) return def delVehi(cur,con): try: row = {} row["Vehicle_id"] = input("Enter Vehicle ID to delete: ") query = "DELETE FROM LOGISTICS WHERE Vehicle_id='%s'" % (row["Vehicle_id"]) #print(query) cur.execute(query) con.commit() except Exception as e: con.rollback() print("Failed to delete from database") print(">>>>>>>>>>>>>", e) return def delDep(cur,con): try: row = {} row["Staff_id"] = input("Enter Staff ID associated: ") name = (input("Name (Fname Lname): ")).split(' ') row["Fname"] = name[0] row["Lname"] = name[1] query = "DELETE FROM DEPENDENT WHERE Staff_id='%s' AND First_name='%s' AND Last_name='%s'" % (row["Staff_id"], row["Fname"], row["Lname"]) #print(query) cur.execute(query) con.commit() except Exception as e: con.rollback() print("Failed to delete from database") print(">>>>>>>>>>>>>", e) return
def del_user(cur, con, loginid): try: query = "DELETE FROM USER WHERE Login_id='%s'" % loginid cur.execute(query) con.commit() print('Deleted from Database') except Exception as e: con.rollback() print('Failed to delete from database') print('>>>>>>>>>>>>>', e) return def del_staff(cur, con): try: row = {} row['Staff_id'] = input('Enter Staff ID to delete: ') row['Login_id'] = 'STAFF' + row['Staff_id'] query = "SELECT Department_id FROM WORKS_FOR WHERE Staff_id='%s'" % row['Staff_id'] cur.execute(query) row['dep'] = cur.fetchone()['Department_id'] con.commit() query = "UPDATE DEPARTMENT SET No_of_employees=No_of_employees - 1 WHERE Department_id='%s'" % row['dep'] cur.execute(query) con.commit() query = "DELETE FROM WORKS_FOR WHERE Staff_id='%s'" % row['Staff_id'] cur.execute(query) con.commit() query = "DELETE FROM STAFF_SKILLS WHERE Staff_id='%s'" % row['Staff_id'] cur.execute(query) con.commit() query = "DELETE FROM STAFF WHERE Login_id='%s'" % row['Login_id'] cur.execute(query) con.commit() del_user(cur, con, row['Login_id']) except Exception as e: con.rollback() print('Failed to delete from database') print('>>>>>>>>>>>>>', e) return def del_donor(cur, con): try: row = {} row['Donor_id'] = input('Enter Donor ID to delete: ') row['Login_id'] = 'DONOR' + row['Donor_id'] query = "DELETE FROM DONOR WHERE Donor_id='%s'" % row['Donor_id'] cur.execute(query) con.commit() del_user(cur, con, row['Login_id']) except Exception as e: con.rollback() print('Failed to delete from database') print('>>>>>>>>>>>>>', e) return def del_vehi(cur, con): try: row = {} row['Vehicle_id'] = input('Enter Vehicle ID to delete: ') query = "DELETE FROM LOGISTICS WHERE Vehicle_id='%s'" % row['Vehicle_id'] cur.execute(query) con.commit() except Exception as e: con.rollback() print('Failed to delete from database') print('>>>>>>>>>>>>>', e) return def del_dep(cur, con): try: row = {} row['Staff_id'] = input('Enter Staff ID associated: ') name = input('Name (Fname Lname): ').split(' ') row['Fname'] = name[0] row['Lname'] = name[1] query = "DELETE FROM DEPENDENT WHERE Staff_id='%s' AND First_name='%s' AND Last_name='%s'" % (row['Staff_id'], row['Fname'], row['Lname']) cur.execute(query) con.commit() except Exception as e: con.rollback() print('Failed to delete from database') print('>>>>>>>>>>>>>', e) return
# program to generate the combinations of n distinct objects taken from the elements of a given list. def combination(n, n_list): if n<=0: yield [] return for i in range(len(n_list)): c_num = n_list[i:i+1] for a_num in combination(n-1, n_list[i+1:]): yield c_num + a_num n_list = [1,2,3,4,5,6,7,8,9] print("Original list:") print(n_list) n = 2 result = combination(n, n_list) print("\nCombinations of",n,"distinct objects:") for e in result: print(e)
def combination(n, n_list): if n <= 0: yield [] return for i in range(len(n_list)): c_num = n_list[i:i + 1] for a_num in combination(n - 1, n_list[i + 1:]): yield (c_num + a_num) n_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print('Original list:') print(n_list) n = 2 result = combination(n, n_list) print('\nCombinations of', n, 'distinct objects:') for e in result: print(e)
def install(job): service = job.service # create user if it doesn't exists username = service.model.dbobj.name password = service.model.data.password email = service.model.data.email provider = service.model.data.provider username = "%s@%s" % (username, provider) if provider else username password = password if not provider else "fakeeeee" g8client = service.producers["g8client"][0] config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key") if not client.api.system.usermanager.userexists(name=username): groups = service.model.data.groups client.api.system.usermanager.create(username=username, password=password, groups=groups, emails=[email], domain='', provider=provider) def processChange(job): service = job.service g8client = service.producers["g8client"][0] config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key") old_args = service.model.data new_args = job.model.args # Process Changing Groups old_groups = set(old_args.groups) new_groups = set(new_args.get('groups', [])) if old_groups != new_groups: username = service.model.dbobj.name provider = old_args.provider username = "%s@%s" % (username, provider) if provider else username # Editing user api requires to send a list contains user's mail emails = [old_args.email] new_groups = list(new_groups) client.api.system.usermanager.editUser(username=username, groups=new_groups, provider=provider, emails=emails) service.model.data.groups = new_groups service.save() def uninstall(job): service = job.service # unauthorize user to all consumed vdc username = service.model.dbobj.name g8client = service.producers["g8client"][0] config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key") provider = service.model.data.provider username = "%s@%s" % (username, provider) if provider else username if client.api.system.usermanager.userexists(name=username): client.api.system.usermanager.delete(username=username)
def install(job): service = job.service username = service.model.dbobj.name password = service.model.data.password email = service.model.data.email provider = service.model.data.provider username = '%s@%s' % (username, provider) if provider else username password = password if not provider else 'fakeeeee' g8client = service.producers['g8client'][0] config_instance = '{}_{}'.format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path='/root/.ssh/ays_repos_key') if not client.api.system.usermanager.userexists(name=username): groups = service.model.data.groups client.api.system.usermanager.create(username=username, password=password, groups=groups, emails=[email], domain='', provider=provider) def process_change(job): service = job.service g8client = service.producers['g8client'][0] config_instance = '{}_{}'.format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path='/root/.ssh/ays_repos_key') old_args = service.model.data new_args = job.model.args old_groups = set(old_args.groups) new_groups = set(new_args.get('groups', [])) if old_groups != new_groups: username = service.model.dbobj.name provider = old_args.provider username = '%s@%s' % (username, provider) if provider else username emails = [old_args.email] new_groups = list(new_groups) client.api.system.usermanager.editUser(username=username, groups=new_groups, provider=provider, emails=emails) service.model.data.groups = new_groups service.save() def uninstall(job): service = job.service username = service.model.dbobj.name g8client = service.producers['g8client'][0] config_instance = '{}_{}'.format(g8client.aysrepo.name, g8client.model.data.instance) client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path='/root/.ssh/ays_repos_key') provider = service.model.data.provider username = '%s@%s' % (username, provider) if provider else username if client.api.system.usermanager.userexists(name=username): client.api.system.usermanager.delete(username=username)
if condition1: ... elif condition2: ... elif condition3: ... elif condition4: ... elif condition5: ... elif condition6: ... else: ...
if condition1: ... elif condition2: ... elif condition3: ... elif condition4: ... elif condition5: ... elif condition6: ... else: ...
MIN_DRIVING_AGE = 18 group = {'tim': 17, 'bob': 18, 'ana': 24} def allowed_driving(name): """Print '{name} is allowed to drive' or '{name} is not allowed to drive' checking the passed in age against the MIN_DRIVING_AGE constant """ is_found = False if name in group: if group[name] >= MIN_DRIVING_AGE: print(name + " is allowed to drive") is_found = True else: print(name + " is not allowed to drive") is_found = True return is_found while True: print("Enter a name: (blank to quit)") name = str.casefold(input()) if name == '': break if not allowed_driving(name): print("Name is not found")
min_driving_age = 18 group = {'tim': 17, 'bob': 18, 'ana': 24} def allowed_driving(name): """Print '{name} is allowed to drive' or '{name} is not allowed to drive' checking the passed in age against the MIN_DRIVING_AGE constant """ is_found = False if name in group: if group[name] >= MIN_DRIVING_AGE: print(name + ' is allowed to drive') is_found = True else: print(name + ' is not allowed to drive') is_found = True return is_found while True: print('Enter a name: (blank to quit)') name = str.casefold(input()) if name == '': break if not allowed_driving(name): print('Name is not found')
# Python - 3.6.0 test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7]) test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11]) test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), [])
test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7]) test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11]) test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), [])
def save_file(contents): with open("path_to_save_the_file.wav", 'wb') as f: f.write(contents) return "path_to_save_the_file.wav"
def save_file(contents): with open('path_to_save_the_file.wav', 'wb') as f: f.write(contents) return 'path_to_save_the_file.wav'
expected_output = { "main": { "chassis": { "ASR1002-X": { "descr": "Cisco ASR1002-X Chassis", "name": "Chassis", "pid": "ASR1002-X", "sn": "FOX1111P1M1", "vid": "V07", } } }, "slot": { "0": { "lc": { "ASR1002-X": { "descr": "Cisco ASR1002-X SPA Interface Processor", "name": "module 0", "pid": "ASR1002-X", "sn": "", "subslot": { "0": { "6XGE-BUILT-IN": { "descr": "6-port Built-in GE SPA", "name": "SPA subslot 0/0", "pid": "6XGE-BUILT-IN", "sn": "", "vid": "", } }, "0 transceiver 0": { "GLC-SX-MMD": { "descr": "GE SX", "name": "subslot 0/0 transceiver 0", "pid": "GLC-SX-MMD", "sn": "AGJ3333R1GC", "vid": "001", } }, "0 transceiver 1": { "GLC-SX-MMD": { "descr": "GE SX", "name": "subslot 0/0 transceiver 1", "pid": "GLC-SX-MMD", "sn": "AGJ1111R1G1", "vid": "001", } }, "0 transceiver 2": { "GLC-SX-MMD": { "descr": "GE SX", "name": "subslot 0/0 transceiver 2", "pid": "GLC-SX-MMD", "sn": "AGJ9999R1FL", "vid": "001", } }, "0 transceiver 3": { "GLC-SX-MMD": { "descr": "GE SX", "name": "subslot 0/0 transceiver 3", "pid": "GLC-SX-MMD", "sn": "AGJ5555RAFM", "vid": "001", } }, }, "vid": "", } } }, "F0": { "lc": { "ASR1002-X": { "descr": "Cisco ASR1002-X Embedded Services Processor", "name": "module F0", "pid": "ASR1002-X", "sn": "", "vid": "", } } }, "P0": { "other": { "ASR1002-PWR-AC": { "descr": "Cisco ASR1002 AC Power Supply", "name": "Power Supply Module 0", "pid": "ASR1002-PWR-AC", "sn": "ABC111111EJ", "vid": "V04", } } }, "P1": { "other": { "ASR1002-PWR-AC": { "descr": "Cisco ASR1002 AC Power Supply", "name": "Power Supply Module 1", "pid": "ASR1002-PWR-AC", "sn": "DCB222222EK", "vid": "V04", } } }, "R0": { "rp": { "ASR1002-X": { "descr": "Cisco ASR1002-X Route Processor", "name": "module R0", "pid": "ASR1002-X", "sn": "JAD333333AQ", "vid": "V07", } } }, }, }
expected_output = {'main': {'chassis': {'ASR1002-X': {'descr': 'Cisco ASR1002-X Chassis', 'name': 'Chassis', 'pid': 'ASR1002-X', 'sn': 'FOX1111P1M1', 'vid': 'V07'}}}, 'slot': {'0': {'lc': {'ASR1002-X': {'descr': 'Cisco ASR1002-X SPA Interface Processor', 'name': 'module 0', 'pid': 'ASR1002-X', 'sn': '', 'subslot': {'0': {'6XGE-BUILT-IN': {'descr': '6-port Built-in GE SPA', 'name': 'SPA subslot 0/0', 'pid': '6XGE-BUILT-IN', 'sn': '', 'vid': ''}}, '0 transceiver 0': {'GLC-SX-MMD': {'descr': 'GE SX', 'name': 'subslot 0/0 transceiver 0', 'pid': 'GLC-SX-MMD', 'sn': 'AGJ3333R1GC', 'vid': '001'}}, '0 transceiver 1': {'GLC-SX-MMD': {'descr': 'GE SX', 'name': 'subslot 0/0 transceiver 1', 'pid': 'GLC-SX-MMD', 'sn': 'AGJ1111R1G1', 'vid': '001'}}, '0 transceiver 2': {'GLC-SX-MMD': {'descr': 'GE SX', 'name': 'subslot 0/0 transceiver 2', 'pid': 'GLC-SX-MMD', 'sn': 'AGJ9999R1FL', 'vid': '001'}}, '0 transceiver 3': {'GLC-SX-MMD': {'descr': 'GE SX', 'name': 'subslot 0/0 transceiver 3', 'pid': 'GLC-SX-MMD', 'sn': 'AGJ5555RAFM', 'vid': '001'}}}, 'vid': ''}}}, 'F0': {'lc': {'ASR1002-X': {'descr': 'Cisco ASR1002-X Embedded Services Processor', 'name': 'module F0', 'pid': 'ASR1002-X', 'sn': '', 'vid': ''}}}, 'P0': {'other': {'ASR1002-PWR-AC': {'descr': 'Cisco ASR1002 AC Power Supply', 'name': 'Power Supply Module 0', 'pid': 'ASR1002-PWR-AC', 'sn': 'ABC111111EJ', 'vid': 'V04'}}}, 'P1': {'other': {'ASR1002-PWR-AC': {'descr': 'Cisco ASR1002 AC Power Supply', 'name': 'Power Supply Module 1', 'pid': 'ASR1002-PWR-AC', 'sn': 'DCB222222EK', 'vid': 'V04'}}}, 'R0': {'rp': {'ASR1002-X': {'descr': 'Cisco ASR1002-X Route Processor', 'name': 'module R0', 'pid': 'ASR1002-X', 'sn': 'JAD333333AQ', 'vid': 'V07'}}}}}
input = """ c(1). c(2). c(3). a(X) | -a(X) :- c(X). minim(X) :- a(X), #min{ D : a(D) } = X. """ output = """ c(1). c(2). c(3). a(X) | -a(X) :- c(X). minim(X) :- a(X), #min{ D : a(D) } = X. """
input = '\nc(1).\nc(2).\nc(3).\n\na(X) | -a(X) :- c(X).\n\nminim(X) :- a(X), #min{ D : a(D) } = X.\n' output = '\nc(1).\nc(2).\nc(3).\n\na(X) | -a(X) :- c(X).\n\nminim(X) :- a(X), #min{ D : a(D) } = X.\n'
A = 1 connection= { A : ['B'], 'B' : ['A', 'B', 'D'], 'C' : ['A'], 'D' : ['E','A'], 'E' : ['B'] } for f in connection: print(connection['B']) print(connection[id])
a = 1 connection = {A: ['B'], 'B': ['A', 'B', 'D'], 'C': ['A'], 'D': ['E', 'A'], 'E': ['B']} for f in connection: print(connection['B']) print(connection[id])
#!/usr/bin/env python #pylint: skip-file # This source code is licensed under the Apache license found in the # LICENSE file in the root directory of this project. class AugmentedTaskDTO(object): def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attributeMap (dict): The key is attribute name and the value is json key in definition. """ self.swaggerTypes = { 'id': 'str', 'progress': 'str', 'version': 'int', 'startTime': 'date-time', 'endTime': 'date-time', 'data': 'str', 'errorCode': 'str', 'serviceType': 'str', 'username': 'str', 'isError': 'bool', 'lastUpdate': 'date-time', 'operationIdList': 'list[str]', 'parentId': 'str', 'rootId': 'str', 'failureReason': 'str' } self.attributeMap = { 'id': 'id', 'progress': 'progress', 'version': 'version', 'startTime': 'startTime', 'endTime': 'endTime', 'data': 'data', 'errorCode': 'errorCode', 'serviceType': 'serviceType', 'username': 'username', 'isError': 'isError', 'lastUpdate': 'lastUpdate', 'operationIdList': 'operationIdList', 'parentId': 'parentId', 'rootId': 'rootId', 'failureReason': 'failureReason' } #id self.id = None # str #progress self.progress = None # str #version self.version = None # int #startTime self.startTime = None # date-time #endTime self.endTime = None # date-time #data self.data = None # str #errorCode self.errorCode = None # str #serviceType self.serviceType = None # str #username self.username = None # str #isError self.isError = None # bool #lastUpdate self.lastUpdate = None # date-time self.operationIdList = None # list[str] #parentId self.parentId = None # str #rootId self.rootId = None # str #failureReason self.failureReason = None # str
class Augmentedtaskdto(object): def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attributeMap (dict): The key is attribute name and the value is json key in definition. """ self.swaggerTypes = {'id': 'str', 'progress': 'str', 'version': 'int', 'startTime': 'date-time', 'endTime': 'date-time', 'data': 'str', 'errorCode': 'str', 'serviceType': 'str', 'username': 'str', 'isError': 'bool', 'lastUpdate': 'date-time', 'operationIdList': 'list[str]', 'parentId': 'str', 'rootId': 'str', 'failureReason': 'str'} self.attributeMap = {'id': 'id', 'progress': 'progress', 'version': 'version', 'startTime': 'startTime', 'endTime': 'endTime', 'data': 'data', 'errorCode': 'errorCode', 'serviceType': 'serviceType', 'username': 'username', 'isError': 'isError', 'lastUpdate': 'lastUpdate', 'operationIdList': 'operationIdList', 'parentId': 'parentId', 'rootId': 'rootId', 'failureReason': 'failureReason'} self.id = None self.progress = None self.version = None self.startTime = None self.endTime = None self.data = None self.errorCode = None self.serviceType = None self.username = None self.isError = None self.lastUpdate = None self.operationIdList = None self.parentId = None self.rootId = None self.failureReason = None
""" EDX_DATABASES = { 'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'}, 'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'}, 'tropic_101x': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'}, 'bioimg_101x': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'}, 'crime_101x': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'}, 'world_101x': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'}, 'write_101x': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'}, 'sense_101x': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'} } """ EDX_DATABASES = { 'think_101x_1T2014': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'}, 'hypers_301x_1T2014': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'}, 'tropic_101x_1T2014': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'}, 'bioimg_101x_1T2014': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'}, 'crime_101x_3T2014': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'}, 'world_101x_3T2014': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'}, 'write_101x_3T2014': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'}, 'sense_101x_3T2014': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'}, }
""" EDX_DATABASES = { 'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'}, 'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'}, 'tropic_101x': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'}, 'bioimg_101x': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'}, 'crime_101x': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'}, 'world_101x': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'}, 'write_101x': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'}, 'sense_101x': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'} } """ edx_databases = {'think_101x_1T2014': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'}, 'hypers_301x_1T2014': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'}, 'tropic_101x_1T2014': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'}, 'bioimg_101x_1T2014': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'}, 'crime_101x_3T2014': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'}, 'world_101x_3T2014': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'}, 'write_101x_3T2014': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'}, 'sense_101x_3T2014': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'}}
def insertion_sort(the_list): """ In-place list sorting method """ i = 1 while i < len(the_list): elem = the_list[i] sorted_iterator = i-1 while elem < the_list[sorted_iterator] and sorted_iterator >= 0: the_list[sorted_iterator+1] = the_list[sorted_iterator] sorted_iterator -= 1 the_list[sorted_iterator + 1] = elem i += 1
def insertion_sort(the_list): """ In-place list sorting method """ i = 1 while i < len(the_list): elem = the_list[i] sorted_iterator = i - 1 while elem < the_list[sorted_iterator] and sorted_iterator >= 0: the_list[sorted_iterator + 1] = the_list[sorted_iterator] sorted_iterator -= 1 the_list[sorted_iterator + 1] = elem i += 1
# emacs: -*- mode: python-mode; py-indent-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- # ex: set sts=2 ts=2 sw=2 et: __all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats']
__all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats']
def f1(x, *args): pass f1(42, 'spam')
def f1(x, *args): pass f1(42, 'spam')
{ 'includes': [ './common.gypi' ], 'target_defaults': { 'defines' : [ 'PNG_PREFIX', 'PNGPREFIX_H', 'PNG_USE_READ_MACROS', ], # 'include_dirs': [ # '<(DEPTH)/third_party/pdfium', # '<(DEPTH)/third_party/pdfium/third_party/freetype/include', # ], 'conditions': [ ['OS=="linux"', { 'conditions': [ ['target_arch=="x64"', { 'defines' : [ '_FX_CPU_=_FX_X64_', ], 'cflags': [ '-fPIC', ], }], ['target_arch=="ia32"', { 'defines' : [ '_FX_CPU_=_FX_X86_', ], }], ], }] ], 'msvs_disabled_warnings': [ 4005, 4018, 4146, 4333, 4345, 4267 ] }, 'targets': [ { 'target_name': 'node_pdfium', 'dependencies' : [ 'fx_lpng', './third_party/pdfium/pdfium.gyp:pdfium' ], 'sources': [ # is like "ls -1 src/*.cc", but gyp does not support direct patterns on # sources '<!@(["python", "tools/getSourceFiles.py", "src", "cc"])' ] }, { 'target_name': 'fx_lpng', 'type': 'static_library', 'dependencies': [ 'third_party/pdfium/pdfium.gyp:fxcodec', ], 'include_dirs': [ 'third_party/pdfium/core/src/fxcodec/fx_zlib/include/', ], 'sources': [ 'third_party/fx_lpng/include/fx_png.h', 'third_party/fx_lpng/src/fx_png.c', 'third_party/fx_lpng/src/fx_pngerror.c', 'third_party/fx_lpng/src/fx_pngget.c', 'third_party/fx_lpng/src/fx_pngmem.c', 'third_party/fx_lpng/src/fx_pngpread.c', 'third_party/fx_lpng/src/fx_pngread.c', 'third_party/fx_lpng/src/fx_pngrio.c', 'third_party/fx_lpng/src/fx_pngrtran.c', 'third_party/fx_lpng/src/fx_pngrutil.c', 'third_party/fx_lpng/src/fx_pngset.c', 'third_party/fx_lpng/src/fx_pngtrans.c', 'third_party/fx_lpng/src/fx_pngwio.c', 'third_party/fx_lpng/src/fx_pngwrite.c', 'third_party/fx_lpng/src/fx_pngwtran.c', 'third_party/fx_lpng/src/fx_pngwutil.c', ] } ] }
{'includes': ['./common.gypi'], 'target_defaults': {'defines': ['PNG_PREFIX', 'PNGPREFIX_H', 'PNG_USE_READ_MACROS'], 'conditions': [['OS=="linux"', {'conditions': [['target_arch=="x64"', {'defines': ['_FX_CPU_=_FX_X64_'], 'cflags': ['-fPIC']}], ['target_arch=="ia32"', {'defines': ['_FX_CPU_=_FX_X86_']}]]}]], 'msvs_disabled_warnings': [4005, 4018, 4146, 4333, 4345, 4267]}, 'targets': [{'target_name': 'node_pdfium', 'dependencies': ['fx_lpng', './third_party/pdfium/pdfium.gyp:pdfium'], 'sources': ['<!@(["python", "tools/getSourceFiles.py", "src", "cc"])']}, {'target_name': 'fx_lpng', 'type': 'static_library', 'dependencies': ['third_party/pdfium/pdfium.gyp:fxcodec'], 'include_dirs': ['third_party/pdfium/core/src/fxcodec/fx_zlib/include/'], 'sources': ['third_party/fx_lpng/include/fx_png.h', 'third_party/fx_lpng/src/fx_png.c', 'third_party/fx_lpng/src/fx_pngerror.c', 'third_party/fx_lpng/src/fx_pngget.c', 'third_party/fx_lpng/src/fx_pngmem.c', 'third_party/fx_lpng/src/fx_pngpread.c', 'third_party/fx_lpng/src/fx_pngread.c', 'third_party/fx_lpng/src/fx_pngrio.c', 'third_party/fx_lpng/src/fx_pngrtran.c', 'third_party/fx_lpng/src/fx_pngrutil.c', 'third_party/fx_lpng/src/fx_pngset.c', 'third_party/fx_lpng/src/fx_pngtrans.c', 'third_party/fx_lpng/src/fx_pngwio.c', 'third_party/fx_lpng/src/fx_pngwrite.c', 'third_party/fx_lpng/src/fx_pngwtran.c', 'third_party/fx_lpng/src/fx_pngwutil.c']}]}
def normalizer(x, norm): if norm == 'l2': norm_val = sum(xi ** 2 for xi in x) ** .5 elif norm == 'l1': norm_val = sum(abs(xi) for xi in x) elif norm == 'max': norm_val = max(abs(xi) for xi in x) return [xi / norm_val for xi in x] def standard_scaler(x, mean_, var_, with_mean, with_std): def scale(x, m, v): if with_mean: x -= m if with_std: x /= v ** .5 return x return [scale(xi, m, v) for xi, m, v in zip(x, mean_, var_)]
def normalizer(x, norm): if norm == 'l2': norm_val = sum((xi ** 2 for xi in x)) ** 0.5 elif norm == 'l1': norm_val = sum((abs(xi) for xi in x)) elif norm == 'max': norm_val = max((abs(xi) for xi in x)) return [xi / norm_val for xi in x] def standard_scaler(x, mean_, var_, with_mean, with_std): def scale(x, m, v): if with_mean: x -= m if with_std: x /= v ** 0.5 return x return [scale(xi, m, v) for (xi, m, v) in zip(x, mean_, var_)]
def pascal_case(text): """Returns text converted to PascalCase""" if text.count('_') == 0: return text s1 = text.split('_') return ''.join([s.lower().capitalize() for s in s1]) def integral_type(member): type = { 'char': 'char', 'signed char': 'sbyte', 'unsigned char': 'byte', 'short': 'short', 'unsigned short': 'ushort', 'int': 'int', 'unsigned int': 'uint', 'long': 'int', 'unsigned long': 'uint', 'long long': 'long', 'unsigned long long': 'ulong', 'float': 'float', 'double': 'double' }[member.type] return type def csharp_type(member, show_length=False): if member.type == 'char' and member.length > 1: return 'string' type = integral_type(member) if member.length > 1: return f'{type}[{member.length if show_length else ""}]' return type def reader_method(member): type = integral_type(member) method = { 'char': 'ReadChar', 'sbyte': 'ReadSByte', 'byte': 'ReadByte', 'short': 'ReadInt16', 'ushort': 'ReadUInt16', 'int': 'ReadInt32', 'uint': 'ReadUInt32', 'long': 'ReadInt64', 'ulong': 'ReadUInt64', 'float': 'ReadSingle', 'double': 'ReadDouble' }[type] return method def lines(text): ls = text.split('\n') if not ls: return [] if ls[0].strip() == '': ls = ls[1:] if not ls: return [] if ls[-1].strip() == '': ls = ls[:-1] return ls def leading_spaces(text): return len(text) - len(text.lstrip()) def remove_miniumum_whitespace(lines): try: minimum_whitespace = min([leading_spaces(l) for l in lines]) return [l[minimum_whitespace:] for l in lines] except ValueError: return [] def xml_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) return '\n'.join([f'/// {l}' for l in ls]) def comment(text): if text.count('\n') == 0: return single_line_comment(text) return multi_line_comment(text) def single_line_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) return '\n'.join([f'// {l}' for l in ls]) def multi_line_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) ls = [f' * {l}' for l in ls] ls.insert(0, '/*') ls.append(' */') return '\n'.join(ls) filters = { 'pascalcase': pascal_case, 'csharptype': csharp_type, 'readermethod': reader_method, 'comment': comment, 'singlelinecomment': single_line_comment, 'multilinecomment': multi_line_comment, 'xmlcomment': xml_comment }
def pascal_case(text): """Returns text converted to PascalCase""" if text.count('_') == 0: return text s1 = text.split('_') return ''.join([s.lower().capitalize() for s in s1]) def integral_type(member): type = {'char': 'char', 'signed char': 'sbyte', 'unsigned char': 'byte', 'short': 'short', 'unsigned short': 'ushort', 'int': 'int', 'unsigned int': 'uint', 'long': 'int', 'unsigned long': 'uint', 'long long': 'long', 'unsigned long long': 'ulong', 'float': 'float', 'double': 'double'}[member.type] return type def csharp_type(member, show_length=False): if member.type == 'char' and member.length > 1: return 'string' type = integral_type(member) if member.length > 1: return f"{type}[{(member.length if show_length else '')}]" return type def reader_method(member): type = integral_type(member) method = {'char': 'ReadChar', 'sbyte': 'ReadSByte', 'byte': 'ReadByte', 'short': 'ReadInt16', 'ushort': 'ReadUInt16', 'int': 'ReadInt32', 'uint': 'ReadUInt32', 'long': 'ReadInt64', 'ulong': 'ReadUInt64', 'float': 'ReadSingle', 'double': 'ReadDouble'}[type] return method def lines(text): ls = text.split('\n') if not ls: return [] if ls[0].strip() == '': ls = ls[1:] if not ls: return [] if ls[-1].strip() == '': ls = ls[:-1] return ls def leading_spaces(text): return len(text) - len(text.lstrip()) def remove_miniumum_whitespace(lines): try: minimum_whitespace = min([leading_spaces(l) for l in lines]) return [l[minimum_whitespace:] for l in lines] except ValueError: return [] def xml_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) return '\n'.join([f'/// {l}' for l in ls]) def comment(text): if text.count('\n') == 0: return single_line_comment(text) return multi_line_comment(text) def single_line_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) return '\n'.join([f'// {l}' for l in ls]) def multi_line_comment(text): ls = lines(text) ls = remove_miniumum_whitespace(ls) ls = [f' * {l}' for l in ls] ls.insert(0, '/*') ls.append(' */') return '\n'.join(ls) filters = {'pascalcase': pascal_case, 'csharptype': csharp_type, 'readermethod': reader_method, 'comment': comment, 'singlelinecomment': single_line_comment, 'multilinecomment': multi_line_comment, 'xmlcomment': xml_comment}
print('Enter any integer: ') n = str(input().strip()) num_places = len(n) for i in range(num_places) : x = num_places - i if x >= 10 : suffix = "Billion " elif x <= 9 and x >= 7 : suffix = "Million " elif x == 6 : suffix = "Hundred " elif x == 5 : suffix = "Thousand " elif x == 4: suffix = "Thousand " elif x == 3 : suffix = "Hundred " else : suffix = "" # the second to last digit will always be the tens, which have special naming if i != num_places - 2 : if n[i] == '1' : # don't make newline print("One " + suffix, end='') elif n[i] == '2' : print("Two " + suffix, end='') elif n[i] == '3' : print("Three " + suffix, end='') elif n[i] == '4': print("Four " + suffix, end='') elif n[i] == '5': print("Five " + suffix, end='') elif n[i] == '6': print("Six " + suffix, end='') elif n[i] == '7': print("Seven " + suffix, end='') elif n[i] == '8': print("Eight " + suffix, end='') elif n[i] == '9': print("Nine " + suffix, end='') else : # if n[i] is 0, print "and" print(" and ", end='') else : if n[i] == '1' : if n[i+1] == '0' : print("Ten ", end='') if n[i+1] == '1' : print("Eleven ", end='') if n[i+1] == '2' : print("Twelve ", end='') else : if n[i+1] == '3' : print("Thir", end='') if n[i+1] == '4' : print("Four", end='') if n[i+1] == '5' : print("Fif", end='') if n[i+1] == '6' : print("Six", end='') if n[i+1] == '7' : print("Seven", end='') if n[i+1] == '8' : print("Eigh", end='') if n[i+1] == '9' : print("Nine", end='') print("teen") break elif n[i] == '2' : print("Twenty ", end='') elif n[i] == '3' : print("Thirty ", end='') elif n[i] == '4': print("Fourty ", end='') elif n[i] == '5': print("Fifty ", end='') elif n[i] == '6': print("Sixty ", end='') elif n[i] == '7': print("Seventy ", end='') elif n[i] == '8': print("Eighty ", end='') elif n[i] == '9': print("Ninety ", end='') else : # if n[i] is 0, print "and" print(" and ", end='')
print('Enter any integer: ') n = str(input().strip()) num_places = len(n) for i in range(num_places): x = num_places - i if x >= 10: suffix = 'Billion ' elif x <= 9 and x >= 7: suffix = 'Million ' elif x == 6: suffix = 'Hundred ' elif x == 5: suffix = 'Thousand ' elif x == 4: suffix = 'Thousand ' elif x == 3: suffix = 'Hundred ' else: suffix = '' if i != num_places - 2: if n[i] == '1': print('One ' + suffix, end='') elif n[i] == '2': print('Two ' + suffix, end='') elif n[i] == '3': print('Three ' + suffix, end='') elif n[i] == '4': print('Four ' + suffix, end='') elif n[i] == '5': print('Five ' + suffix, end='') elif n[i] == '6': print('Six ' + suffix, end='') elif n[i] == '7': print('Seven ' + suffix, end='') elif n[i] == '8': print('Eight ' + suffix, end='') elif n[i] == '9': print('Nine ' + suffix, end='') else: print(' and ', end='') elif n[i] == '1': if n[i + 1] == '0': print('Ten ', end='') if n[i + 1] == '1': print('Eleven ', end='') if n[i + 1] == '2': print('Twelve ', end='') else: if n[i + 1] == '3': print('Thir', end='') if n[i + 1] == '4': print('Four', end='') if n[i + 1] == '5': print('Fif', end='') if n[i + 1] == '6': print('Six', end='') if n[i + 1] == '7': print('Seven', end='') if n[i + 1] == '8': print('Eigh', end='') if n[i + 1] == '9': print('Nine', end='') print('teen') break elif n[i] == '2': print('Twenty ', end='') elif n[i] == '3': print('Thirty ', end='') elif n[i] == '4': print('Fourty ', end='') elif n[i] == '5': print('Fifty ', end='') elif n[i] == '6': print('Sixty ', end='') elif n[i] == '7': print('Seventy ', end='') elif n[i] == '8': print('Eighty ', end='') elif n[i] == '9': print('Ninety ', end='') else: print(' and ', end='')
def search(arr, d, y): for m in range(0, d): if (arr[m] == y): return m; return -1; arr = [4, 8, 26, 30, 13]; p = 30; k = len(arr); result = search(arr, k, p) if (result == -1): print("Element is not present in array") else: print("Element is present at index", result);
def search(arr, d, y): for m in range(0, d): if arr[m] == y: return m return -1 arr = [4, 8, 26, 30, 13] p = 30 k = len(arr) result = search(arr, k, p) if result == -1: print('Element is not present in array') else: print('Element is present at index', result)
# Turns an RPN expression to normal mathematical notation _VARIABLES = { "0": "0", "1": "1", "P": "pi", "a": "x0", "b": "x1", "c": "x2", "d": "x3", "e": "x4", "f": "x5", "g": "x6", "h": "x7", "i": "x8", "j": "x9", "k": "x10", "l": "x11", "m": "x12", "n": "x13", } _OPS_UNARY = { ">": "({}+1)", "<": "({}-1)", "~": "(-{})", "\\": "({})**(-1)", "L": "log({})", "E": "exp({})", "S": "sin({})", "C": "cos({})", "A": "abs({})", "N": "asin({})", "T": "atan({})", "R": "sqrt({})", "O": "(2*({}))", "J": "(2*({})+1)", } _OPS_BINARY = set("+*-/") def RPN_to_eq(expr: str) -> str: stack = [] for i in expr: if i in _VARIABLES: stack.append(_VARIABLES[i]) elif i in _OPS_BINARY: a1 = stack.pop() a2 = stack.pop() stack.append(f"({a2}{i}{a1})") elif i in _OPS_UNARY: a = stack.pop() stack.append(_OPS_UNARY[i].format(a)) return stack[0]
_variables = {'0': '0', '1': '1', 'P': 'pi', 'a': 'x0', 'b': 'x1', 'c': 'x2', 'd': 'x3', 'e': 'x4', 'f': 'x5', 'g': 'x6', 'h': 'x7', 'i': 'x8', 'j': 'x9', 'k': 'x10', 'l': 'x11', 'm': 'x12', 'n': 'x13'} _ops_unary = {'>': '({}+1)', '<': '({}-1)', '~': '(-{})', '\\': '({})**(-1)', 'L': 'log({})', 'E': 'exp({})', 'S': 'sin({})', 'C': 'cos({})', 'A': 'abs({})', 'N': 'asin({})', 'T': 'atan({})', 'R': 'sqrt({})', 'O': '(2*({}))', 'J': '(2*({})+1)'} _ops_binary = set('+*-/') def rpn_to_eq(expr: str) -> str: stack = [] for i in expr: if i in _VARIABLES: stack.append(_VARIABLES[i]) elif i in _OPS_BINARY: a1 = stack.pop() a2 = stack.pop() stack.append(f'({a2}{i}{a1})') elif i in _OPS_UNARY: a = stack.pop() stack.append(_OPS_UNARY[i].format(a)) return stack[0]
#converts the pixel bytes to binary def decToBin(dec): secret_bin = [] for i in dec: secret_bin.append(f'{i:08b}') return secret_bin #gets the last 2 LSB of each byte def get2LSB(secret_bin): last2 = [] for i in secret_bin: for j in i[6:8]: last2.append(j) return last2 def filter2LSB(listdict, last2): piclsb = [] replaceNum = 0 index = 0 #the lower even or odd occurence gets replaced if listdict['0']<2 or listdict['1']<2: replaceNum = 0 listdict['2'] = '01' elif listdict['0'] <= listdict['1']: replaceNum = 0 else: replaceNum = 1 #filters the right matching bits out of the image for i in last2: if int(listdict['2'][index])%2 == replaceNum: piclsb.append(i) index += 1 if index >= len(listdict['2']): index = 0 else: index += 1 if index >= len(listdict['2']): index = 0 return piclsb
def dec_to_bin(dec): secret_bin = [] for i in dec: secret_bin.append(f'{i:08b}') return secret_bin def get2_lsb(secret_bin): last2 = [] for i in secret_bin: for j in i[6:8]: last2.append(j) return last2 def filter2_lsb(listdict, last2): piclsb = [] replace_num = 0 index = 0 if listdict['0'] < 2 or listdict['1'] < 2: replace_num = 0 listdict['2'] = '01' elif listdict['0'] <= listdict['1']: replace_num = 0 else: replace_num = 1 for i in last2: if int(listdict['2'][index]) % 2 == replaceNum: piclsb.append(i) index += 1 if index >= len(listdict['2']): index = 0 else: index += 1 if index >= len(listdict['2']): index = 0 return piclsb
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def buildfarm(): http_archive( name="buildfarm" , build_file="//bazel/deps/buildfarm:build.BUILD" , sha256="de2a18bbe1e6770be0cd54e93630fb1ee7bce937bff708eed16329033fbfe32b" , strip_prefix="bazel-buildfarm-355f816acf3531e9e37d860acf9ebbb89c9041c2" , urls = [ "https://github.com/Unilang/bazel-buildfarm/archive/355f816acf3531e9e37d860acf9ebbb89c9041c2.tar.gz", ], )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def buildfarm(): http_archive(name='buildfarm', build_file='//bazel/deps/buildfarm:build.BUILD', sha256='de2a18bbe1e6770be0cd54e93630fb1ee7bce937bff708eed16329033fbfe32b', strip_prefix='bazel-buildfarm-355f816acf3531e9e37d860acf9ebbb89c9041c2', urls=['https://github.com/Unilang/bazel-buildfarm/archive/355f816acf3531e9e37d860acf9ebbb89c9041c2.tar.gz'])
""" Choose i/o filename here: - a_example - b_should_be_easy - c_no_hurry - d_metropolis - e_high_bonus """ filename = 'b_should_be_easy' # choose input and output file names here ride_pool = [] ride_id = 0 with open(filename + '.in', 'r') as file: args = file.readline().split() for line in file: r = line.split() ride_pool.append((ride_id, (int(r[0]), int(r[1])), (int(r[2]), int(r[3])), int(r[4]), int(r[5]))) ride_id += 1 R = int(args[0]) C = int(args[1]) F = int(args[2]) N = int(args[3]) B = int(args[4]) T = int(args[5]) # RIDE: ((rideID, (startx, starty), (endx, endy), start_time, finish_time) finished_cars_IDs = [] # this will contain all the cars that have no more eligible rides class Car: def __init__(self, id): self.carID = id self.currRide = None self.posx = 0 self.posy = 0 self.ride_dist = 0 # distance till current ride is finished self.pickup_dist = 0 # distance till the pickup spot - (startx, starty) of ride def assignRide(self, Ride): self.currRide = Ride self.ride_dist = manhattanDistance((Ride[1][0], Ride[1][1]), (Ride[2][0], Ride[2][1])) self.pickup_dist = manhattanDistance((self.posx, self.posy), (Ride[1][0], Ride[1][1])) def chooseRideBasedOnStartTime(self, t): # greedily minimize start_time for rides global R, C, ride_pool if self.carID in finished_cars_IDs: return mintimes = float('inf') minride = None finished = True for ride in ride_pool: dt = calculate_start_time((self.posx, self.posy), t, ride) if ride_would_be_in_vain(ride, dt, t): continue finished = False if dt < mintimes: mintimes = dt minride = ride if finished: finished_cars_IDs.append(self.carID) if minride is None: # better pass return ride_pool.remove(minride) self.assignRide(minride) def chooseRideBasedOnMixedScore(self, t): # greedily maximaze the ratio of score / start_time for rides global R, C, ride_pool, B if self.carID in finished_cars_IDs: return maxmixedscore = float('-inf') maxride = None finished = True for ride in ride_pool: mixed_score = calculate_mixed_score((self.posx, self.posy), t, ride) if ride_would_be_in_vain_2(ride, (self.posx, self.posy), t): continue finished = False if mixed_score > maxmixedscore: maxmixedscore = mixed_score maxride = ride if finished: finished_cars_IDs.append(self.carID) if maxride is None: # better pass return ride_pool.remove(maxride) self.assignRide(maxride) def act(self, t): if self.currRide is None: # no rides assigned self.chooseRideBasedOnMixedScore(t) # greedy choice -> we have implemented 2 options if self.currRide is None: # choose returned none -> pass this round return None if self.pickup_dist > 0: # hasn't reached the pickup spot yet self.pickup_dist -= 1 elif self.pickup_dist == 0: # has reached the pickup spot if t < self.currRide[3]: # time to start is not here yet pass # wait elif self.ride_dist > 0: # still working on given ride self.ride_dist -= 1 elif self.ride_dist == 0: res = self.currRide self.currRide = None return res else: print("Unexpected Error") else: print("Unexpected Error") return None def manhattanDistance( xy1, xy2 ): """Returns the Manhattan distance between points xy1 and xy2""" return abs( xy1[0] - xy2[0] ) + abs( xy1[1] - xy2[1] ) def calculate_start_time(pos, t, ride): pickuptime = manhattanDistance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 # journey_time = manhattanDistance(ride[1], ride[2]) return pickuptime + wait_time def calculate_mixed_score(pos, t, ride): pickuptime = manhattanDistance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 journey_time = manhattanDistance(ride[1], ride[2]) completion_time = pickuptime + wait_time + journey_time score = 0 if t + pickuptime <= ride[3]: score += B if t + completion_time < ride[4]: score += journey_time if float(pickuptime + wait_time) != 0: ratio = float(score) / (float(pickuptime + wait_time)) else: ratio = float(score) return ratio def ride_would_be_in_vain(ride, start_time, t): completion_time = start_time + manhattanDistance(ride[1], ride[2]) return t + completion_time >= ride[4] def ride_would_be_in_vain_2(ride, pos, t): # second version of this pickuptime = manhattanDistance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 completion_time = pickuptime + wait_time + manhattanDistance(ride[1], ride[2]) return t + completion_time >= ride[4] def simulation(): global T, F, N, B, R, C car_history = {} # the solution cars = [] for i in range(0, F): cars.append(Car(i)) car_history[i] = [] for t in range(0, T): # print(t) for car in cars: finished_ride = car.act(t) if finished_ride is not None: car_history[car.carID].append(finished_ride[0]) return car_history # main(): car_history = simulation() with open(filename + '.out', 'w') as file: for carID in range(0, F): num_of_rides = len(car_history[carID]) file.write(str(num_of_rides)) for ridenum in range(0, num_of_rides): file.write(' ' + str(car_history[carID][ridenum])) file.write('\n')
""" Choose i/o filename here: - a_example - b_should_be_easy - c_no_hurry - d_metropolis - e_high_bonus """ filename = 'b_should_be_easy' ride_pool = [] ride_id = 0 with open(filename + '.in', 'r') as file: args = file.readline().split() for line in file: r = line.split() ride_pool.append((ride_id, (int(r[0]), int(r[1])), (int(r[2]), int(r[3])), int(r[4]), int(r[5]))) ride_id += 1 r = int(args[0]) c = int(args[1]) f = int(args[2]) n = int(args[3]) b = int(args[4]) t = int(args[5]) finished_cars_i_ds = [] class Car: def __init__(self, id): self.carID = id self.currRide = None self.posx = 0 self.posy = 0 self.ride_dist = 0 self.pickup_dist = 0 def assign_ride(self, Ride): self.currRide = Ride self.ride_dist = manhattan_distance((Ride[1][0], Ride[1][1]), (Ride[2][0], Ride[2][1])) self.pickup_dist = manhattan_distance((self.posx, self.posy), (Ride[1][0], Ride[1][1])) def choose_ride_based_on_start_time(self, t): global R, C, ride_pool if self.carID in finished_cars_IDs: return mintimes = float('inf') minride = None finished = True for ride in ride_pool: dt = calculate_start_time((self.posx, self.posy), t, ride) if ride_would_be_in_vain(ride, dt, t): continue finished = False if dt < mintimes: mintimes = dt minride = ride if finished: finished_cars_IDs.append(self.carID) if minride is None: return ride_pool.remove(minride) self.assignRide(minride) def choose_ride_based_on_mixed_score(self, t): global R, C, ride_pool, B if self.carID in finished_cars_IDs: return maxmixedscore = float('-inf') maxride = None finished = True for ride in ride_pool: mixed_score = calculate_mixed_score((self.posx, self.posy), t, ride) if ride_would_be_in_vain_2(ride, (self.posx, self.posy), t): continue finished = False if mixed_score > maxmixedscore: maxmixedscore = mixed_score maxride = ride if finished: finished_cars_IDs.append(self.carID) if maxride is None: return ride_pool.remove(maxride) self.assignRide(maxride) def act(self, t): if self.currRide is None: self.chooseRideBasedOnMixedScore(t) if self.currRide is None: return None if self.pickup_dist > 0: self.pickup_dist -= 1 elif self.pickup_dist == 0: if t < self.currRide[3]: pass elif self.ride_dist > 0: self.ride_dist -= 1 elif self.ride_dist == 0: res = self.currRide self.currRide = None return res else: print('Unexpected Error') else: print('Unexpected Error') return None def manhattan_distance(xy1, xy2): """Returns the Manhattan distance between points xy1 and xy2""" return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1]) def calculate_start_time(pos, t, ride): pickuptime = manhattan_distance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 return pickuptime + wait_time def calculate_mixed_score(pos, t, ride): pickuptime = manhattan_distance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 journey_time = manhattan_distance(ride[1], ride[2]) completion_time = pickuptime + wait_time + journey_time score = 0 if t + pickuptime <= ride[3]: score += B if t + completion_time < ride[4]: score += journey_time if float(pickuptime + wait_time) != 0: ratio = float(score) / float(pickuptime + wait_time) else: ratio = float(score) return ratio def ride_would_be_in_vain(ride, start_time, t): completion_time = start_time + manhattan_distance(ride[1], ride[2]) return t + completion_time >= ride[4] def ride_would_be_in_vain_2(ride, pos, t): pickuptime = manhattan_distance(pos, ride[1]) wait_time = ride[3] - (t + pickuptime) if wait_time < 0: wait_time = 0 completion_time = pickuptime + wait_time + manhattan_distance(ride[1], ride[2]) return t + completion_time >= ride[4] def simulation(): global T, F, N, B, R, C car_history = {} cars = [] for i in range(0, F): cars.append(car(i)) car_history[i] = [] for t in range(0, T): for car in cars: finished_ride = car.act(t) if finished_ride is not None: car_history[car.carID].append(finished_ride[0]) return car_history car_history = simulation() with open(filename + '.out', 'w') as file: for car_id in range(0, F): num_of_rides = len(car_history[carID]) file.write(str(num_of_rides)) for ridenum in range(0, num_of_rides): file.write(' ' + str(car_history[carID][ridenum])) file.write('\n')
class ReporterInterface(object): def notify_before_console_output(self): pass def notify_after_console_output(self): pass def report_session_start(self, session): pass def report_session_end(self, session): pass def report_file_start(self, filename): pass def report_file_end(self, filename): pass def report_collection_start(self): pass def report_test_collected(self, all_tests, test): pass def report_collection_end(self, collected): pass def report_test_start(self, test): pass def report_test_end(self, test, result): if result.is_success(): self.report_test_success(test, result) elif result.is_skip(): self.report_test_skip(test, result) elif result.is_error(): self.report_test_error(test, result) else: assert result.is_failure() self.report_test_failure(test, result) def report_test_success(self, test, result): pass def report_test_skip(self, test, result): pass def report_test_error(self, test, result): pass def report_test_failure(self, test, result): pass
class Reporterinterface(object): def notify_before_console_output(self): pass def notify_after_console_output(self): pass def report_session_start(self, session): pass def report_session_end(self, session): pass def report_file_start(self, filename): pass def report_file_end(self, filename): pass def report_collection_start(self): pass def report_test_collected(self, all_tests, test): pass def report_collection_end(self, collected): pass def report_test_start(self, test): pass def report_test_end(self, test, result): if result.is_success(): self.report_test_success(test, result) elif result.is_skip(): self.report_test_skip(test, result) elif result.is_error(): self.report_test_error(test, result) else: assert result.is_failure() self.report_test_failure(test, result) def report_test_success(self, test, result): pass def report_test_skip(self, test, result): pass def report_test_error(self, test, result): pass def report_test_failure(self, test, result): pass
def read_as_strings(filename): f = open(filename, "r") res = f.read().split("\n") return res def read_as_ints(filename): f = open(filename, "r") res = map(int, f.read().split("\n")) return list(res)
def read_as_strings(filename): f = open(filename, 'r') res = f.read().split('\n') return res def read_as_ints(filename): f = open(filename, 'r') res = map(int, f.read().split('\n')) return list(res)
n = int(input("Qual o tamanho do vetor?")) x = [int(input()) for x in range(n)] for i in range(0, n, 2): print(x[i])
n = int(input('Qual o tamanho do vetor?')) x = [int(input()) for x in range(n)] for i in range(0, n, 2): print(x[i])
# function for merge sort def merge_sort(arr): if len(arr) > 1: # mid element of array mid = len(arr) // 2 # Dividing the array and calling merge sort on array left = arr[:mid] # into 2 halves right = arr[mid:] # merge sort for array first merge_sort(left) # merge sort for array second merge_sort(right) # merging function merge_array(arr, left, right) def merge_array(arr, left, right): i = j = k = 0 # merging two array left right in sorted order while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 # merging any remaining element while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 # printing array def print_array(arr): for i in range(len(arr)): print(arr[i], end=" ") print() total_element = int(input("Number of element in array ")) arr = [] for i in range(total_element): arr.append(int(input(f"Enter {i}th element "))) print("Input array is ", end="\n") print_array(arr) merge_sort(arr) print("array after sort is: ", end="\n") print_array(arr)
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) merge_array(arr, left, right) def merge_array(arr, left, right): i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 def print_array(arr): for i in range(len(arr)): print(arr[i], end=' ') print() total_element = int(input('Number of element in array ')) arr = [] for i in range(total_element): arr.append(int(input(f'Enter {i}th element '))) print('Input array is ', end='\n') print_array(arr) merge_sort(arr) print('array after sort is: ', end='\n') print_array(arr)
def test_fake_hash(fake_hash): assert fake_hash(b'rainstorms') == b"HASH(brainstorms)"
def test_fake_hash(fake_hash): assert fake_hash(b'rainstorms') == b'HASH(brainstorms)'
"""Constants for Fama RANKS(list of str): taxonomical ranks, top to bottom LOWER_RANKS(dict of str): rank as key, child rank as value ROOT_TAXONOMY_ID (str): taxonomy identifier of root node UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node ENDS (list of str): identifiers of first and second end for paired-end sequences. First end identifier also used for any other sequence types (like single-end reads and proteins) STATUS_CAND (str): status assigned to pre-selected reads STATUS_GOOD (str): status assigned to reads with assigned function STATUS_BAD (str): status assigned to rejected reads """ RANKS = ['norank', 'superkingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'] LOWER_RANKS = {'norank': 'superkingdom', 'superkingdom': 'phylum', 'phylum': 'class', 'class': 'order', 'order': 'family', 'family': 'genus', 'genus': 'species'} ROOT_TAXONOMY_ID = '1' UNKNOWN_TAXONOMY_ID = '0' ENDS = ['pe1', 'pe2'] STATUS_CAND = 'unaccounted' STATUS_GOOD = 'function' STATUS_BAD = 'nofunction'
"""Constants for Fama RANKS(list of str): taxonomical ranks, top to bottom LOWER_RANKS(dict of str): rank as key, child rank as value ROOT_TAXONOMY_ID (str): taxonomy identifier of root node UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node ENDS (list of str): identifiers of first and second end for paired-end sequences. First end identifier also used for any other sequence types (like single-end reads and proteins) STATUS_CAND (str): status assigned to pre-selected reads STATUS_GOOD (str): status assigned to reads with assigned function STATUS_BAD (str): status assigned to rejected reads """ ranks = ['norank', 'superkingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'] lower_ranks = {'norank': 'superkingdom', 'superkingdom': 'phylum', 'phylum': 'class', 'class': 'order', 'order': 'family', 'family': 'genus', 'genus': 'species'} root_taxonomy_id = '1' unknown_taxonomy_id = '0' ends = ['pe1', 'pe2'] status_cand = 'unaccounted' status_good = 'function' status_bad = 'nofunction'
supported_browsers = ( "system_default", "chrome", "chromium", "chromium-browser", "google-chrome", "safari", "firefox", "opera", "mozilla", "netscape", "galeon", "epiphany", "skipstone", "kfmclient", "konqueror", "kfm", "mosaic", "grail", "links", "elinks", "lynx", "w3m", "windows-default", "macosx", ) supported_image_extensions = ( "apng", "avif", "bmp", "gif", "ico", "jpg", "jpeg", "jfif", "pjpeg", "pjp", "png", "svg", "webp", "cur", "tif", "tiff", )
supported_browsers = ('system_default', 'chrome', 'chromium', 'chromium-browser', 'google-chrome', 'safari', 'firefox', 'opera', 'mozilla', 'netscape', 'galeon', 'epiphany', 'skipstone', 'kfmclient', 'konqueror', 'kfm', 'mosaic', 'grail', 'links', 'elinks', 'lynx', 'w3m', 'windows-default', 'macosx') supported_image_extensions = ('apng', 'avif', 'bmp', 'gif', 'ico', 'jpg', 'jpeg', 'jfif', 'pjpeg', 'pjp', 'png', 'svg', 'webp', 'cur', 'tif', 'tiff')
class BasePermission: def __init__(self, user): self.user = user def has_permission(self, action): raise NotImplementedError class AllowAny: def has_permission(self, action): return True class IsAuthenticated(BasePermission): def has_permission(self, action): return self.user.id is not None and self.user.is_authenticated()
class Basepermission: def __init__(self, user): self.user = user def has_permission(self, action): raise NotImplementedError class Allowany: def has_permission(self, action): return True class Isauthenticated(BasePermission): def has_permission(self, action): return self.user.id is not None and self.user.is_authenticated()
# Description: Count number of *.log files in current directory. # Source: placeHolder """ cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of number of log image files in the current directory: ", logCounter);') """ cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of number of log image files in the current directory: ", logCounter);')
""" cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of number of log image files in the current directory: ", logCounter);') """ cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of number of log image files in the current directory: ", logCounter);')
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 06:33:05 2020 @author: ucobiz """ def happy(): print("Happy Bday to you!") def sing(person, age): happy() happy() print("Happy Bday,", person) print("You're already", age, "years old") happy() def main(): sing("Fred", 30) main()
""" Created on Wed Oct 28 06:33:05 2020 @author: ucobiz """ def happy(): print('Happy Bday to you!') def sing(person, age): happy() happy() print('Happy Bday,', person) print("You're already", age, 'years old') happy() def main(): sing('Fred', 30) main()
#counter part of inheritance #inheritance means by this program- a bookself is a book #composition is - class Bookself: def __init__(self, *books): self.books=books def __str__(self): return f"Bookself with {len(self.books)} books." class Book: def __init__(self,name): self.name=name def __str__(self): return f"Book {self.name}" book=Book("Harry potter") book2=Book("Python") shelf=Bookself(book,book2) print(shelf)
class Bookself: def __init__(self, *books): self.books = books def __str__(self): return f'Bookself with {len(self.books)} books.' class Book: def __init__(self, name): self.name = name def __str__(self): return f'Book {self.name}' book = book('Harry potter') book2 = book('Python') shelf = bookself(book, book2) print(shelf)
def fake_get_value_from_db(): return 5 def check_outdated(): total = fake_get_value_from_db() return total > 10 def task_put_more_stuff_in_db(): def put_stuff(): pass return {'actions': [put_stuff], 'uptodate': [check_outdated], }
def fake_get_value_from_db(): return 5 def check_outdated(): total = fake_get_value_from_db() return total > 10 def task_put_more_stuff_in_db(): def put_stuff(): pass return {'actions': [put_stuff], 'uptodate': [check_outdated]}
#!/usr/bin/env python3 def solution(s: str, p: list, q: list) -> list: """ >>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6]) [2, 4, 1] """ response = ['T'] * len(p) for i, s in enumerate(s): for k, (p, q) in enumerate(zip(p, q)): if p <= i <= q and s < response[k]: response[k] = s impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4} return [impact_factor[n] for n in response] def solution(s: str, p: list, q: list) -> list: """ >>> solution('CAGCCTA', [2, 5, 0, 0, 6], [4, 5, 6, 0, 6]) [2, 4, 1, 2, 1] """ counters = { 'A': [0] * len(s), 'C': [0] * len(s), 'G': [0] * len(s), 'T': [0] * len(s) } for i, s in enumerate(s): for count in counters.values(): count[i] = count[i - 1] counters[s][i] += 1 impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4} answers = [] for p, q in zip(p, q): for k, count in counters.items(): if count[q] > count[p if p == 0 else p - 1]: answers.append(impact_factor[k]) break if p == q: answers.append(impact_factor[s[p]]) break else: raise Exception('Unexpected error') return answers
def solution(s: str, p: list, q: list) -> list: """ >>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6]) [2, 4, 1] """ response = ['T'] * len(p) for (i, s) in enumerate(s): for (k, (p, q)) in enumerate(zip(p, q)): if p <= i <= q and s < response[k]: response[k] = s impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4} return [impact_factor[n] for n in response] def solution(s: str, p: list, q: list) -> list: """ >>> solution('CAGCCTA', [2, 5, 0, 0, 6], [4, 5, 6, 0, 6]) [2, 4, 1, 2, 1] """ counters = {'A': [0] * len(s), 'C': [0] * len(s), 'G': [0] * len(s), 'T': [0] * len(s)} for (i, s) in enumerate(s): for count in counters.values(): count[i] = count[i - 1] counters[s][i] += 1 impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4} answers = [] for (p, q) in zip(p, q): for (k, count) in counters.items(): if count[q] > count[p if p == 0 else p - 1]: answers.append(impact_factor[k]) break if p == q: answers.append(impact_factor[s[p]]) break else: raise exception('Unexpected error') return answers
''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ''' def solution(A,target): hash1 = dict() for i in range(len(A)): hash1[A[i]] = i print(hash1) lenght_dict = len(hash1.keys()) print(lenght_dict) count = 0 for key,value in hash1.items(): index1 = hash1[key] key1 = target - key count += 1 if(key1==key): continue else: index2 = hash1.get(key1) if(index2!= None): out_list = [index1,index2] print(out_list) return(out_list) break A = [3,2,4,3] target = 6 solution(A,target)
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ def solution(A, target): hash1 = dict() for i in range(len(A)): hash1[A[i]] = i print(hash1) lenght_dict = len(hash1.keys()) print(lenght_dict) count = 0 for (key, value) in hash1.items(): index1 = hash1[key] key1 = target - key count += 1 if key1 == key: continue else: index2 = hash1.get(key1) if index2 != None: out_list = [index1, index2] print(out_list) return out_list break a = [3, 2, 4, 3] target = 6 solution(A, target)
# coding:utf-8 unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi'] confirmed_users = [] while unconfirmed_users: user = unconfirmed_users.pop() confirmed_users.append(user) print(confirmed_users) print(unconfirmed_users)
unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi'] confirmed_users = [] while unconfirmed_users: user = unconfirmed_users.pop() confirmed_users.append(user) print(confirmed_users) print(unconfirmed_users)
# link: https://leetcode.com/problems/longest-string-chain/ """ Sort the words by word's length. (also can apply bucket sort) For each word, loop on all possible previous word with 1 letter missing. If we have seen this previous word, update the longest chain for the current word. Finally return the longest word chain. """ class Solution(object): def longestStrChain(self, words): """ :type words: List[str] :rtype: int """ words = sorted(words, key = len) dic = {} result = 0 for word in words: dic[word]=1 curr_len = len(word) for i in range(curr_len): new_word = word[:i]+word[i+1:] if new_word in dic and dic[new_word] + 1 > dic[word]: dic[word] = dic[new_word]+1 # print(dic) result = max(result, dic[word]) return result
""" Sort the words by word's length. (also can apply bucket sort) For each word, loop on all possible previous word with 1 letter missing. If we have seen this previous word, update the longest chain for the current word. Finally return the longest word chain. """ class Solution(object): def longest_str_chain(self, words): """ :type words: List[str] :rtype: int """ words = sorted(words, key=len) dic = {} result = 0 for word in words: dic[word] = 1 curr_len = len(word) for i in range(curr_len): new_word = word[:i] + word[i + 1:] if new_word in dic and dic[new_word] + 1 > dic[word]: dic[word] = dic[new_word] + 1 result = max(result, dic[word]) return result
"""typecats""" __version__ = "1.7.0" __author__ = "Peter Gaultney" __author_email__ = "pgaultney@xoi.io"
"""typecats""" __version__ = '1.7.0' __author__ = 'Peter Gaultney' __author_email__ = 'pgaultney@xoi.io'
num = int(input("Enter a number: ")) if ((num % 2 == 0) and (num % 3 == 0) and (num % 5 == 0)): print("Divisible") else: print("Not Divisible")
num = int(input('Enter a number: ')) if num % 2 == 0 and num % 3 == 0 and (num % 5 == 0): print('Divisible') else: print('Not Divisible')
"""Environment Variables to be used inside the CloudConvert-Python-REST-SDK""" CLOUDCONVERT_API_KEY = "API_KEY" """Environment variable defining the Cloud Convert REST API default credentials as Access Token.""" CLOUDCONVERT_SANDBOX = "true" """Environment variable defining if the sandbox API is used instead of the live API"""
"""Environment Variables to be used inside the CloudConvert-Python-REST-SDK""" cloudconvert_api_key = 'API_KEY' 'Environment variable defining the Cloud Convert REST API default\ncredentials as Access Token.' cloudconvert_sandbox = 'true' 'Environment variable defining if the sandbox API is used instead of the live API'
# f[i][j] = f[i - 1][j - 1] where s[i - 1] == p[j - 1] || p[j - 1] == '.' case p[j - 1] != '*' # f[i][j] = f[i][j - 2] or f[i - 1][j] where s[i - 1] == p[j - 2] || p[j - 2] == '.' case p[j - 1] == '*' class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ m = len(s) n = len(p) table = [[False for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 and j == 0: table[i][j] = True continue if j == 0: table[i][j] = False continue if p[j - 1] != '*': if i - 1 >= 0 and (p[j - 1] == '.' or p[j - 1] == s[i- 1]): table[i][j] = table[i - 1][j - 1] else: if j - 2 >= 0: table[i][j] = table[i][j - 2] if i - 1 >= 0 and (p[j - 2] == '.' or p[j - 2] == s[i - 1]): table[i][j] = table[i][j] or table[i - 1][j] return table[m][n]
class Solution(object): def is_match(self, s, p): """ :type s: str :type p: str :rtype: bool """ m = len(s) n = len(p) table = [[False for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 and j == 0: table[i][j] = True continue if j == 0: table[i][j] = False continue if p[j - 1] != '*': if i - 1 >= 0 and (p[j - 1] == '.' or p[j - 1] == s[i - 1]): table[i][j] = table[i - 1][j - 1] elif j - 2 >= 0: table[i][j] = table[i][j - 2] if i - 1 >= 0 and (p[j - 2] == '.' or p[j - 2] == s[i - 1]): table[i][j] = table[i][j] or table[i - 1][j] return table[m][n]
''' Descripttion: version: Author: HuSharp Date: 2021-02-21 22:59:41 LastEditors: HuSharp LastEditTime: 2021-02-21 23:12:36 @Email: 8211180515@csu.edu.cn ''' def countdown_1(k): if k > 0: yield k for i in countdown_1(k-1): yield i def countdown(k): if k > 0: yield k yield from countdown(k-1) else: yield 'Blast off'
""" Descripttion: version: Author: HuSharp Date: 2021-02-21 22:59:41 LastEditors: HuSharp LastEditTime: 2021-02-21 23:12:36 @Email: 8211180515@csu.edu.cn """ def countdown_1(k): if k > 0: yield k for i in countdown_1(k - 1): yield i def countdown(k): if k > 0: yield k yield from countdown(k - 1) else: yield 'Blast off'
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrderBottom(self, root): x = self.solve(root) return list(reversed(x)) def solve(self, root): if root is None: return [] l = self.solve(root.left) r = self.solve(root.right) m = [ (l[i] if i < len(l) else []) + (r[i] if i < len(r) else []) for i in xrange(max(len(l), len(r)))] return [[root.val]] + m
class Solution: def level_order_bottom(self, root): x = self.solve(root) return list(reversed(x)) def solve(self, root): if root is None: return [] l = self.solve(root.left) r = self.solve(root.right) m = [(l[i] if i < len(l) else []) + (r[i] if i < len(r) else []) for i in xrange(max(len(l), len(r)))] return [[root.val]] + m