content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class UndergroundSystem: def __init__(self): self.count = defaultdict(int) self.time = defaultdict(int) self.traveling = dict() def checkIn(self, id: int, stationName: str, t: int) -> None: self.traveling[id] = (stationName, t) def checkOut(self, id: int, stationName: str, t: int) -> None: (prev_station, prev_t) = self.traveling[id] del self.traveling[id] key = (prev_station, stationName) self.count[key] += 1 self.time[key] += (t-prev_t) def getAverageTime(self, startStation: str, endStation: str) -> float: key = (startStation, endStation) return self.time[key] / self.count[key] # Your UndergroundSystem object will be instantiated and called as such: # obj = UndergroundSystem() # obj.checkIn(id,stationName,t) # obj.checkOut(id,stationName,t) # param_3 = obj.getAverageTime(startStation,endStation)
class Undergroundsystem: def __init__(self): self.count = defaultdict(int) self.time = defaultdict(int) self.traveling = dict() def check_in(self, id: int, stationName: str, t: int) -> None: self.traveling[id] = (stationName, t) def check_out(self, id: int, stationName: str, t: int) -> None: (prev_station, prev_t) = self.traveling[id] del self.traveling[id] key = (prev_station, stationName) self.count[key] += 1 self.time[key] += t - prev_t def get_average_time(self, startStation: str, endStation: str) -> float: key = (startStation, endStation) return self.time[key] / self.count[key]
class Patcher(object): """ A dumb class to allow a mock.patch object to be used as a decorator and a context manager Typical usage:: import mock import sys my_mock = Patcher(mock.patch("sys.platform", "win32")) @my_mock def func1(): print(sys.platform) def func2(): with my_mock: print(sys.platform) """ def __init__(self, patcher): self._patcher = patcher def __call__(self, func): return self._patcher(func) def __enter__(self): return self._patcher.__enter__() def __exit__(self, *a, **kw): return self._patcher.__exit__(*a, **kw) class MultiPatcher(object): """ Like Patcher, but applies a list of patchers. """ def __init__(self, patchers): self._patchers = patchers def __call__(self, func): ret = func for patcher in self._patchers: ret = patcher(ret) return ret def __enter__(self): return [patcher.__enter__() for patcher in self._patchers] def __exit__(self, *a, **kw): for patcher in self._patchers: patcher.__exit__(*a, **kw)
class Patcher(object): """ A dumb class to allow a mock.patch object to be used as a decorator and a context manager Typical usage:: import mock import sys my_mock = Patcher(mock.patch("sys.platform", "win32")) @my_mock def func1(): print(sys.platform) def func2(): with my_mock: print(sys.platform) """ def __init__(self, patcher): self._patcher = patcher def __call__(self, func): return self._patcher(func) def __enter__(self): return self._patcher.__enter__() def __exit__(self, *a, **kw): return self._patcher.__exit__(*a, **kw) class Multipatcher(object): """ Like Patcher, but applies a list of patchers. """ def __init__(self, patchers): self._patchers = patchers def __call__(self, func): ret = func for patcher in self._patchers: ret = patcher(ret) return ret def __enter__(self): return [patcher.__enter__() for patcher in self._patchers] def __exit__(self, *a, **kw): for patcher in self._patchers: patcher.__exit__(*a, **kw)
def test_clear_images(client, seeder, app, utils): user_id, admin_unit_id = seeder.setup_base() image_id = seeder.upsert_default_image() url = utils.get_image_url_for_id(image_id) utils.get_ok(url) runner = app.test_cli_runner() result = runner.invoke(args=["cache", "clear-images"]) assert "Done." in result.output
def test_clear_images(client, seeder, app, utils): (user_id, admin_unit_id) = seeder.setup_base() image_id = seeder.upsert_default_image() url = utils.get_image_url_for_id(image_id) utils.get_ok(url) runner = app.test_cli_runner() result = runner.invoke(args=['cache', 'clear-images']) assert 'Done.' in result.output
def binary_slow(n): assert n>=0 bits = [] while n: bits.append('01'[n&1]) n >>= 1 bits.reverse() return ''.join(bits) or '0'
def binary_slow(n): assert n >= 0 bits = [] while n: bits.append('01'[n & 1]) n >>= 1 bits.reverse() return ''.join(bits) or '0'
# Containers for txid sequences start with this string. CONTAINER_PREFIX = 'txids' # Transaction ID sequence nodes start with this string. COUNTER_NODE_PREFIX = 'tx' # ZooKeeper stores the sequence counter as a signed 32-bit integer. MAX_SEQUENCE_COUNTER = 2 ** 31 - 1 # The name of the node used for manually setting a txid offset. OFFSET_NODE = 'txid_offset'
container_prefix = 'txids' counter_node_prefix = 'tx' max_sequence_counter = 2 ** 31 - 1 offset_node = 'txid_offset'
# Solution 1 - recursion # O(log(n)) time / O(log(n)) space def binarySearch1(array, target): return binarySearchHelper1(array, target, 0, len(array) - 1) def binarySearchHelper1(array, target, left, right): if left > right: return -1 middle = (left + right) // 2 potentialMatch = array[middle] if target == potentialMatch: return middle elif target < potentialMatch: return binarySearchHelper1(array, target, left, middle - 1) else: return binarySearchHelper1(array, target, middle + 1, right) # Solution 2 - iteration # O(log(n)) time / O(1) space def binarySearch2(array, target): return binarySearchHelper1(array, target, 0, len(array) - 1) def binarySearchHelper2(array, target, left, right): while left <= right: middle = (left + right) // 2 potentialMatch = array[middle] if target == potentialMatch: return middle elif target < potentialMatch: right = middle - 1 else: left = middle + 1 return -1
def binary_search1(array, target): return binary_search_helper1(array, target, 0, len(array) - 1) def binary_search_helper1(array, target, left, right): if left > right: return -1 middle = (left + right) // 2 potential_match = array[middle] if target == potentialMatch: return middle elif target < potentialMatch: return binary_search_helper1(array, target, left, middle - 1) else: return binary_search_helper1(array, target, middle + 1, right) def binary_search2(array, target): return binary_search_helper1(array, target, 0, len(array) - 1) def binary_search_helper2(array, target, left, right): while left <= right: middle = (left + right) // 2 potential_match = array[middle] if target == potentialMatch: return middle elif target < potentialMatch: right = middle - 1 else: left = middle + 1 return -1
def levenshtein(source: str, target: str) -> int: """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using the Wagner-Fischer algorithm (https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm). These distances are defined recursively, since the distance between two strings is just the cost of adjusting the last one or two characters plus the distance between the prefixes that exclude these characters (e.g. the distance between "tester" and "tested" is 1 + the distance between "teste" and "teste"). The Wagner-Fischer algorithm retains this idea but eliminates redundant computations by storing the distances between various prefixes in a matrix that is filled in iteratively. """ # Create matrix of correct size (this is s_len + 1 * t_len + 1 so that the # empty prefixes "" can also be included). The leftmost column represents # transforming various source prefixes into an empty string, which can # always be done by deleting all characters in the respective prefix, and # the top row represents transforming the empty string into various target # prefixes, which can always be done by inserting every character in the # respective prefix. The ternary used to build the list should ensure that # this row and column are now filled correctly s_range = range(len(source) + 1) t_range = range(len(target) + 1) matrix = [[(i if j == 0 else j) for j in t_range] for i in s_range] # Iterate through rest of matrix, filling it in with Levenshtein # distances for the remaining prefix combinations for i in s_range[1:]: for j in t_range[1:]: # Applies the recursive logic outlined above using the values # stored in the matrix so far. The options for the last pair of # characters are deletion, insertion, and substitution, which # amount to dropping the source character, the target character, # or both and then calculating the distance for the resulting # prefix combo. If the characters at this point are the same, the # situation can be thought of as a free substitution del_dist = matrix[i - 1][j] + 1 ins_dist = matrix[i][j - 1] + 1 sub_trans_cost = 0 if source[i - 1] == target[j - 1] else 1 sub_dist = matrix[i - 1][j - 1] + sub_trans_cost # Choose option that produces smallest distance matrix[i][j] = min(del_dist, ins_dist, sub_dist) # At this point, the matrix is full, and the biggest prefixes are just the # strings themselves, so this is the desired distance return matrix[len(source)][len(target)] def levenshtein_norm(source: str, target: str) -> float: """Calculates the normalized Levenshtein distance between two string arguments. The result will be a float in the range [0.0, 1.0], with 1.0 signifying the biggest possible distance between strings with these lengths """ # Compute Levenshtein distance using helper function. The max is always # just the length of the longer string, so this is used to normalize result # before returning it distance = levenshtein(source, target) return float(distance) / max(len(source), len(target)) # imagin, imogen, imagen, image, imagines, imahine, imoge # list_que, status_list; dark, synthwav, synthese, "fantasy,"; bing # could you embedify these instead of recalculating string distance? or cache def match(source: str, targets: list[str]) -> tuple[float, str]: return sorted(((levenshtein_norm(source, target), target) for target in targets))[0]
def levenshtein(source: str, target: str) -> int: """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using the Wagner-Fischer algorithm (https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm). These distances are defined recursively, since the distance between two strings is just the cost of adjusting the last one or two characters plus the distance between the prefixes that exclude these characters (e.g. the distance between "tester" and "tested" is 1 + the distance between "teste" and "teste"). The Wagner-Fischer algorithm retains this idea but eliminates redundant computations by storing the distances between various prefixes in a matrix that is filled in iteratively. """ s_range = range(len(source) + 1) t_range = range(len(target) + 1) matrix = [[i if j == 0 else j for j in t_range] for i in s_range] for i in s_range[1:]: for j in t_range[1:]: del_dist = matrix[i - 1][j] + 1 ins_dist = matrix[i][j - 1] + 1 sub_trans_cost = 0 if source[i - 1] == target[j - 1] else 1 sub_dist = matrix[i - 1][j - 1] + sub_trans_cost matrix[i][j] = min(del_dist, ins_dist, sub_dist) return matrix[len(source)][len(target)] def levenshtein_norm(source: str, target: str) -> float: """Calculates the normalized Levenshtein distance between two string arguments. The result will be a float in the range [0.0, 1.0], with 1.0 signifying the biggest possible distance between strings with these lengths """ distance = levenshtein(source, target) return float(distance) / max(len(source), len(target)) def match(source: str, targets: list[str]) -> tuple[float, str]: return sorted(((levenshtein_norm(source, target), target) for target in targets))[0]
""" pymatrices Package :- - A Python 3.x Package to implement Matrices and its properties... """ class matrix: """Creates a Matrix using a 2-D list""" def __init__(self, matrix): self.__rows = len(matrix) self.__cols = len(matrix[0]) for rows in matrix: if len(rows) != self.__cols: raise TypeError("Invalid Matrix") if not isinstance(matrix, list): tempMat = list(matrix) else: tempMat = matrix for i in range(len(matrix)): if not isinstance(matrix[i], list): tempMat[i] = list(matrix[i]) self.__mat = tempMat @property def matrix(self): return self.__mat @property def order(self): return (self.__rows, self.__cols) @property def transpose(self): order, res = self.order, [] for i in range(order[1]): temp = [] for j in range(order[0]): temp.append(self.matrix[j][i]) res.append(temp) return matrix(res) @property def primaryDiagonalValues(self): res = [] for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if i == j: res.append(self.matrix[i][j]) return res @property def secondaryDiagonalValues(self): order, res = self.order, [] for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if i+j == (order[0]-1): res.append(self.matrix[i][j]) return res def __repr__(self): neg, minLen, res = False, len(f"{self.matrix[0][0]}"), "" for row in self.matrix: for val in row: if len(f"{val}") > minLen: minLen = len(f"{val}") for row in self.matrix: for val in row: strVal = f"{val}" res += " "*(minLen-len(strVal)) + strVal + " " res += "\n" return res def __add__(self, other): if isinstance(other, matrix): if self.order == other.order: res, temp = [], [] row, col = self.order for i in range(row): for j in range(col): sum_elem = self.matrix[i][j] + other.matrix[i][j] temp.append(sum_elem) res.append(temp) temp = [] return matrix(res) else: raise ValueError("Order of the Matrices must be same") else: raise TypeError(f"can only add matrix (not '{type(other).__name__}') to matrix") def __sub__(self, other): if isinstance(other, matrix): if self.order == other.order: res, temp = [], [] row, col = self.order for i in range(row): for j in range(col): sum_elem = self.matrix[i][j] - other.matrix[i][j] temp.append(sum_elem) res.append(temp) temp = [] return matrix(res) else: raise ValueError("Order of the Matrices must be same") else: raise TypeError(f"can only subtract matrix (not '{type(other).__name__}') from matrix") def __mul__(self, other): assert isinstance(other, (matrix, int, float)), f"Can only multiply either matrix or int or float (not {type(other).__name__}) with matrix" if isinstance(other, matrix): sOrder, oOrder = self.order, other.order if sOrder[1] == oOrder[0]: res = [] T_other = other.transpose tOrder = T_other.order for i in range(sOrder[0]): temp = [] for j in range(tOrder[0]): sum_val = 0 for k in range(tOrder[1]): sum_val += (self.matrix[i][k] * T_other.matrix[j][k]) temp.append(sum_val) res.append(temp) else: raise ValueError("Matrices can't be multiplied.") elif isinstance(other, (int, float)): order, res = self.order, [] for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(self.matrix[row][col]*other) res.append(temp) return matrix(res) def __truediv__(self, other): if isinstance(other, (int, float)): order, res = self.order, [] for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(self.matrix[row][col]/other) res.append(temp) return matrix(res) else: raise ValueError("Matrix can only be divided by a number") def __eq__(self, other): if isinstance(other, matrix): sOrder = self.order if sOrder == other.order: for row in range(sOrder[0]): for col in range(sOrder[1]): if self.matrix[row][col] != other.matrix[row][col]: return False else: return True else: return False else: return False def __neg__(self): order, res = self.order, [] for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(-self.matrix[row][col]) res.append(temp) return matrix(res) def positionOf(self, value): row, col = self.order for i in range(row): for j in range(col): if self.matrix[i][j] == value: return (i+1, j+1) else: raise ValueError(f"There is no Element as {value} in the Matrix.") def minorOfValueAt(self, row, column): row -= 1; column -= 1 mat = [self.matrix[i] for i in range(len(self.matrix)) if i != row] res = [[i[j] for j in range(len(i)) if j!=column] for i in mat] return matrix(res) def valueAt(self, row, column): return self.matrix[row-1][column-1] def adjoint(matrix1): """Returns the adjoint of matrix""" order, mat = matrix1.order, matrix1.matrix if order[0] == 2: return matrix([[mat[1][1], -mat[0][1]], [-mat[1][0], mat[0][0]]]) else: res = [[((-1)**(i+j+2))*(mat[i][j])*(determinant(matrix1.minorOfValueAt(i+1, j+1))) for j in range(order[1])] for i in range(order[0])] return matrix(res) def createByFilling(value, order): """Creates a Matrix of order by Filling it with value""" rows, cols = order[0], order[1] res = [[value for __ in range(cols)] for _ in range(rows)] return matrix(res) def createColumnMatrix(values): """Creates a Column Matrix with values""" return matrix([[i] for i in values]) def createRowMatrix(values): """Creates a Row Matrix with values""" return matrix([[i for i in values]]) def determinant(matrix): """Returns the determinant of matrix""" order = matrix.order if order[0] == order[1]: mat = matrix.matrix if order[0] == 1: return mat[0][0] elif order[0] == 2: return (mat[1][1]*mat[0][0]) - (mat[1][0]*mat[0][1]) else: M11 = mat[0][0]*(determinant(matrix.minorOfValueAt(1, 1))) M12 = mat[0][1]*(determinant(matrix.minorOfValueAt(1, 2))) M13 = mat[0][2]*(determinant(matrix.minorOfValueAt(1, 3))) return M11 + M12 + M13 else: raise ValueError(f"can only find the determinant of square matrix, not '{order[0]}x{order[1]}' matrix.") def eigenvalues(matrix): order = matrix.order S1 = sum(matrix.primaryDiagonalValues) assert order[0] in (1, 2, 3), "Maximum Order is 3x3" if order[0] == 2: S2 = determinant(matrix) a, b, c = (1, -S1, S2) disc = (b**2-4*a*c)**0.5 return ((-b+disc)/2*a, (-b-disc)/2*a) elif order[0] == 3: S2 = determinant(matrix.minorOfValueAt(1, 1))+determinant(matrix.minorOfValueAt(2, 2))+determinant(matrix.minorOfValueAt(3, 3)) S3 = determinant(matrix) a, b, c, d = 1, -S1, S2, -S3 d0 = b**2 - 3*a*c d1 = 2*b**3 - 9*a*b*c + 27*(a**2)*d sqrt = (d1**2 - 4*(d0**3))**0.5 c1 = ((d1+sqrt)/2)**0.33 croot = (-1+3j)/2 try: r1 = (-1/(3*a))*(b+c1+(d0/c1)) r2 = (-1/(3*a))*(b+croot*c1+(d0/croot*c1)) r3 = (-1/(3*a))*(b+(croot**2)*c1+(d0/(croot**2)*c1)) return (r1, r2, r3) except ZeroDivisionError: return ((-b/(3*a)),)*3 def inverse(matrix): """Returns the inverse of matrix""" det = determinant(matrix) if det != 0: return adjoint(matrix)/det else: raise TypeError("Matrix is Singular.") def isDiagonal(matrix): """Returns True if matrix is a 'Diagonal Matrix' else Returns False""" order, mat = matrix.order, matrix.matrix for row in range(order[0]): for col in range(order[1]): if row != col: if mat[row][col] != 0: return False else: return True def I(order): """Returns the Identity Matrix of the given order""" assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'" res = [[0 for _ in range(order)] for __ in range(order)] for i in range(order): for j in range(order): if i==j: res[i][j] = 1 return matrix(res) def O(order): """Returns the Square Null Matrix of the given order""" assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'" res = [[0 for _ in range(order)] for __ in range(order)] return matrix(res) def isIdempotent(matrix): """Returns True if matrix is an 'Idempotent Matrix' else Returns False""" return True if matrix*matrix == matrix else False def isIdentity(matrix): """Returns True if matrix is an 'Identity Matrix' else Returns False""" return True if matrix == I(matrix.order[0]) else False def isNilpotent(matrix): """Returns True if matrix is a 'Nilpotent Matrix' else Returns False""" res = matrix for i in range(1, matrix.order[0]+1): res *= matrix if isNull(res): return True else: return False def isNull(matrix): """Returns True if matrix is a 'Null Matrix' else Returns False""" for i in matrix.matrix: for j in i: if j != 0: return False else: return True def isOrthogonal(matrix): """Returns True if matrix is an 'Orthogonal Matrix' else Returns False""" return True if matrix*matrix.transpose == 0 else False def isScalar(matrix): """Returns True if matrix is a 'Scalar Matrix' else Returns False""" if isDiagonal(matrix): order, val, mat = matrix.order, matrix.matrix[0][0], matrix.matrix for row in range(order[0]): for col in range(order[1]): if row == col: if mat[row][col] != val: return False else: return True else: return False def isSingular(matrix): """Returns True if matrix is a 'Singular Matrix' else Returns False""" return True if determinant(matrix) == 0 else False def isSquare(matrix): """Returns True if matrix is a 'Square Matrix' else Returns False""" order = matrix.order return True if order[0] == order[1] else False def isSymmetric(matrix): """Returns True if matrix is a 'Symmetric Matrix' else Returns False""" return True if matrix == matrix.transpose else False def isSkewSymmetric(matrix): """Returns True if matrix is a 'Skew Symmetric Matrix' else Returns False""" return True if matrix == -matrix.transpose else False
""" pymatrices Package :- - A Python 3.x Package to implement Matrices and its properties... """ class Matrix: """Creates a Matrix using a 2-D list""" def __init__(self, matrix): self.__rows = len(matrix) self.__cols = len(matrix[0]) for rows in matrix: if len(rows) != self.__cols: raise type_error('Invalid Matrix') if not isinstance(matrix, list): temp_mat = list(matrix) else: temp_mat = matrix for i in range(len(matrix)): if not isinstance(matrix[i], list): tempMat[i] = list(matrix[i]) self.__mat = tempMat @property def matrix(self): return self.__mat @property def order(self): return (self.__rows, self.__cols) @property def transpose(self): (order, res) = (self.order, []) for i in range(order[1]): temp = [] for j in range(order[0]): temp.append(self.matrix[j][i]) res.append(temp) return matrix(res) @property def primary_diagonal_values(self): res = [] for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if i == j: res.append(self.matrix[i][j]) return res @property def secondary_diagonal_values(self): (order, res) = (self.order, []) for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if i + j == order[0] - 1: res.append(self.matrix[i][j]) return res def __repr__(self): (neg, min_len, res) = (False, len(f'{self.matrix[0][0]}'), '') for row in self.matrix: for val in row: if len(f'{val}') > minLen: min_len = len(f'{val}') for row in self.matrix: for val in row: str_val = f'{val}' res += ' ' * (minLen - len(strVal)) + strVal + ' ' res += '\n' return res def __add__(self, other): if isinstance(other, matrix): if self.order == other.order: (res, temp) = ([], []) (row, col) = self.order for i in range(row): for j in range(col): sum_elem = self.matrix[i][j] + other.matrix[i][j] temp.append(sum_elem) res.append(temp) temp = [] return matrix(res) else: raise value_error('Order of the Matrices must be same') else: raise type_error(f"can only add matrix (not '{type(other).__name__}') to matrix") def __sub__(self, other): if isinstance(other, matrix): if self.order == other.order: (res, temp) = ([], []) (row, col) = self.order for i in range(row): for j in range(col): sum_elem = self.matrix[i][j] - other.matrix[i][j] temp.append(sum_elem) res.append(temp) temp = [] return matrix(res) else: raise value_error('Order of the Matrices must be same') else: raise type_error(f"can only subtract matrix (not '{type(other).__name__}') from matrix") def __mul__(self, other): assert isinstance(other, (matrix, int, float)), f'Can only multiply either matrix or int or float (not {type(other).__name__}) with matrix' if isinstance(other, matrix): (s_order, o_order) = (self.order, other.order) if sOrder[1] == oOrder[0]: res = [] t_other = other.transpose t_order = T_other.order for i in range(sOrder[0]): temp = [] for j in range(tOrder[0]): sum_val = 0 for k in range(tOrder[1]): sum_val += self.matrix[i][k] * T_other.matrix[j][k] temp.append(sum_val) res.append(temp) else: raise value_error("Matrices can't be multiplied.") elif isinstance(other, (int, float)): (order, res) = (self.order, []) for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(self.matrix[row][col] * other) res.append(temp) return matrix(res) def __truediv__(self, other): if isinstance(other, (int, float)): (order, res) = (self.order, []) for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(self.matrix[row][col] / other) res.append(temp) return matrix(res) else: raise value_error('Matrix can only be divided by a number') def __eq__(self, other): if isinstance(other, matrix): s_order = self.order if sOrder == other.order: for row in range(sOrder[0]): for col in range(sOrder[1]): if self.matrix[row][col] != other.matrix[row][col]: return False else: return True else: return False else: return False def __neg__(self): (order, res) = (self.order, []) for row in range(order[0]): temp = [] for col in range(order[1]): temp.append(-self.matrix[row][col]) res.append(temp) return matrix(res) def position_of(self, value): (row, col) = self.order for i in range(row): for j in range(col): if self.matrix[i][j] == value: return (i + 1, j + 1) else: raise value_error(f'There is no Element as {value} in the Matrix.') def minor_of_value_at(self, row, column): row -= 1 column -= 1 mat = [self.matrix[i] for i in range(len(self.matrix)) if i != row] res = [[i[j] for j in range(len(i)) if j != column] for i in mat] return matrix(res) def value_at(self, row, column): return self.matrix[row - 1][column - 1] def adjoint(matrix1): """Returns the adjoint of matrix""" (order, mat) = (matrix1.order, matrix1.matrix) if order[0] == 2: return matrix([[mat[1][1], -mat[0][1]], [-mat[1][0], mat[0][0]]]) else: res = [[(-1) ** (i + j + 2) * mat[i][j] * determinant(matrix1.minorOfValueAt(i + 1, j + 1)) for j in range(order[1])] for i in range(order[0])] return matrix(res) def create_by_filling(value, order): """Creates a Matrix of order by Filling it with value""" (rows, cols) = (order[0], order[1]) res = [[value for __ in range(cols)] for _ in range(rows)] return matrix(res) def create_column_matrix(values): """Creates a Column Matrix with values""" return matrix([[i] for i in values]) def create_row_matrix(values): """Creates a Row Matrix with values""" return matrix([[i for i in values]]) def determinant(matrix): """Returns the determinant of matrix""" order = matrix.order if order[0] == order[1]: mat = matrix.matrix if order[0] == 1: return mat[0][0] elif order[0] == 2: return mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1] else: m11 = mat[0][0] * determinant(matrix.minorOfValueAt(1, 1)) m12 = mat[0][1] * determinant(matrix.minorOfValueAt(1, 2)) m13 = mat[0][2] * determinant(matrix.minorOfValueAt(1, 3)) return M11 + M12 + M13 else: raise value_error(f"can only find the determinant of square matrix, not '{order[0]}x{order[1]}' matrix.") def eigenvalues(matrix): order = matrix.order s1 = sum(matrix.primaryDiagonalValues) assert order[0] in (1, 2, 3), 'Maximum Order is 3x3' if order[0] == 2: s2 = determinant(matrix) (a, b, c) = (1, -S1, S2) disc = (b ** 2 - 4 * a * c) ** 0.5 return ((-b + disc) / 2 * a, (-b - disc) / 2 * a) elif order[0] == 3: s2 = determinant(matrix.minorOfValueAt(1, 1)) + determinant(matrix.minorOfValueAt(2, 2)) + determinant(matrix.minorOfValueAt(3, 3)) s3 = determinant(matrix) (a, b, c, d) = (1, -S1, S2, -S3) d0 = b ** 2 - 3 * a * c d1 = 2 * b ** 3 - 9 * a * b * c + 27 * a ** 2 * d sqrt = (d1 ** 2 - 4 * d0 ** 3) ** 0.5 c1 = ((d1 + sqrt) / 2) ** 0.33 croot = (-1 + 3j) / 2 try: r1 = -1 / (3 * a) * (b + c1 + d0 / c1) r2 = -1 / (3 * a) * (b + croot * c1 + d0 / croot * c1) r3 = -1 / (3 * a) * (b + croot ** 2 * c1 + d0 / croot ** 2 * c1) return (r1, r2, r3) except ZeroDivisionError: return (-b / (3 * a),) * 3 def inverse(matrix): """Returns the inverse of matrix""" det = determinant(matrix) if det != 0: return adjoint(matrix) / det else: raise type_error('Matrix is Singular.') def is_diagonal(matrix): """Returns True if matrix is a 'Diagonal Matrix' else Returns False""" (order, mat) = (matrix.order, matrix.matrix) for row in range(order[0]): for col in range(order[1]): if row != col: if mat[row][col] != 0: return False else: return True def i(order): """Returns the Identity Matrix of the given order""" assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'" res = [[0 for _ in range(order)] for __ in range(order)] for i in range(order): for j in range(order): if i == j: res[i][j] = 1 return matrix(res) def o(order): """Returns the Square Null Matrix of the given order""" assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'" res = [[0 for _ in range(order)] for __ in range(order)] return matrix(res) def is_idempotent(matrix): """Returns True if matrix is an 'Idempotent Matrix' else Returns False""" return True if matrix * matrix == matrix else False def is_identity(matrix): """Returns True if matrix is an 'Identity Matrix' else Returns False""" return True if matrix == i(matrix.order[0]) else False def is_nilpotent(matrix): """Returns True if matrix is a 'Nilpotent Matrix' else Returns False""" res = matrix for i in range(1, matrix.order[0] + 1): res *= matrix if is_null(res): return True else: return False def is_null(matrix): """Returns True if matrix is a 'Null Matrix' else Returns False""" for i in matrix.matrix: for j in i: if j != 0: return False else: return True def is_orthogonal(matrix): """Returns True if matrix is an 'Orthogonal Matrix' else Returns False""" return True if matrix * matrix.transpose == 0 else False def is_scalar(matrix): """Returns True if matrix is a 'Scalar Matrix' else Returns False""" if is_diagonal(matrix): (order, val, mat) = (matrix.order, matrix.matrix[0][0], matrix.matrix) for row in range(order[0]): for col in range(order[1]): if row == col: if mat[row][col] != val: return False else: return True else: return False def is_singular(matrix): """Returns True if matrix is a 'Singular Matrix' else Returns False""" return True if determinant(matrix) == 0 else False def is_square(matrix): """Returns True if matrix is a 'Square Matrix' else Returns False""" order = matrix.order return True if order[0] == order[1] else False def is_symmetric(matrix): """Returns True if matrix is a 'Symmetric Matrix' else Returns False""" return True if matrix == matrix.transpose else False def is_skew_symmetric(matrix): """Returns True if matrix is a 'Skew Symmetric Matrix' else Returns False""" return True if matrix == -matrix.transpose else False
# Uebungsblatt 2 # Uebung 1 i = 28 f = 28.0 print(i, id(i), type(i)) print(f, id(f), type(f)) # Uebung 2 i = 28.0 f = 28.0 print(i, id(i), type(i)) print(f, id(f), type(f)) # Uebung 3 s = "Hello" s2 = s print(s, id(s), s2, id(s2)) s += " World" print(s, id(s), s2, id(s2)) # Uebung 4 m = ['a', 'b', 'd', 'e', 'f'] print(m, id(m)) m[0]='A' print(m, id(m)) # Uebung 5 m2 = m print(m, id(m), m2, id(m2)) m += 'g' print(m, id(m), m2, id(m2)) # Uebung 6 t = (1, 2, [31, 32], 4) t2 = t print(t, id(t), t2, id(t2)) # t[0] = 'X' # t[2,0] = 'X' # TypeError: 'tuple' object does not support item assignment # Uebung 7 t += 5, print(t, id(t), t2, id(t2)) # Uebung 8 del t # print(t, id(t), t2, id(t2)) # NameError: name 't' is not defined print(t2, id(t2)) del t2 # print(t2, id(t2)) # NameError: name 't2' is not defined # Uebung 9 x = 5 y = '5' # z = x + y # TypeError: unsupported operand type(s) for +: 'int' and 'str'
i = 28 f = 28.0 print(i, id(i), type(i)) print(f, id(f), type(f)) i = 28.0 f = 28.0 print(i, id(i), type(i)) print(f, id(f), type(f)) s = 'Hello' s2 = s print(s, id(s), s2, id(s2)) s += ' World' print(s, id(s), s2, id(s2)) m = ['a', 'b', 'd', 'e', 'f'] print(m, id(m)) m[0] = 'A' print(m, id(m)) m2 = m print(m, id(m), m2, id(m2)) m += 'g' print(m, id(m), m2, id(m2)) t = (1, 2, [31, 32], 4) t2 = t print(t, id(t), t2, id(t2)) t += (5,) print(t, id(t), t2, id(t2)) del t print(t2, id(t2)) del t2 x = 5 y = '5'
n, m = map(int, input().split()) f = list(int(i) for i in input().split()) f.sort() # formula -> f[i+n-1] - f[i] ans = 10**9 for i in range(m-n+1): ans = min(ans, f[i+n-1] - f[i]) print(ans)
(n, m) = map(int, input().split()) f = list((int(i) for i in input().split())) f.sort() ans = 10 ** 9 for i in range(m - n + 1): ans = min(ans, f[i + n - 1] - f[i]) print(ans)
ENDPOINT_PATH = 'foobar' BOOTSTRAP_SERVERS = 'localhost:9092' TOPIC_RAW_REQUESTS = 'test.raw_requests' TOPIC_PARSED_DATA = 'test.parsed_data' USERNAME = None PASSWORD = None SASL_MECHANISM = None SECURITY_PROTOCOL = 'PLAINTEXT' # Use these when trying with FVH servers # SASL_MECHANISM = "PLAIN" # SECURITY_PROTOCOL = "SASL_SSL"
endpoint_path = 'foobar' bootstrap_servers = 'localhost:9092' topic_raw_requests = 'test.raw_requests' topic_parsed_data = 'test.parsed_data' username = None password = None sasl_mechanism = None security_protocol = 'PLAINTEXT'
""" Analyser of the relation. @author: Minchiuan Gao <minchiuan.gao@gmail.com> Build Date: 2015-Nov-25 Wed """ class RelationValue(object): def __init__(self, title, weight, abbr, level): self.title = title self.weight = weight self.abbr = abbr self.level = level class Analyse(object): def __init__(self): self.weigth = {} def caculate_value(self, r1, r2, r3): pass def caculate_weigth(self, person1, peron2): ''' Caculates the weight between person1 and person2 ''' pass def read_data(self): data = open('./data.data', 'r') for line in data.readlines(): row = line.split('\t') relationValue = RelationValue(row[0], row[1], row[2], row[3]) self.weight if __name__ == '__main__': analyse = Analyse() analyse.read_data()
""" Analyser of the relation. @author: Minchiuan Gao <minchiuan.gao@gmail.com> Build Date: 2015-Nov-25 Wed """ class Relationvalue(object): def __init__(self, title, weight, abbr, level): self.title = title self.weight = weight self.abbr = abbr self.level = level class Analyse(object): def __init__(self): self.weigth = {} def caculate_value(self, r1, r2, r3): pass def caculate_weigth(self, person1, peron2): """ Caculates the weight between person1 and person2 """ pass def read_data(self): data = open('./data.data', 'r') for line in data.readlines(): row = line.split('\t') relation_value = relation_value(row[0], row[1], row[2], row[3]) self.weight if __name__ == '__main__': analyse = analyse() analyse.read_data()
# input print('What is my favourite food?') input_guess = input("Guess? ") # response while input_guess != 'electricity': print("Not even close.") input_guess = input("Guess? ") print("You guessed it! Buzzzz")
print('What is my favourite food?') input_guess = input('Guess? ') while input_guess != 'electricity': print('Not even close.') input_guess = input('Guess? ') print('You guessed it! Buzzzz')
# Use enumerate() and other skills to return the count of the number of items in # the list whose value equals its index. def count_match_index(numbers): return len([number for index, number in enumerate(numbers) if index == number]) result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10]) print(result)
def count_match_index(numbers): return len([number for (index, number) in enumerate(numbers) if index == number]) result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10]) print(result)
__title__ = 'elasticsearch-cli' __version__ = '0.0.1' __author__ = 'nevercaution' __license__ = 'Apache v2'
__title__ = 'elasticsearch-cli' __version__ = '0.0.1' __author__ = 'nevercaution' __license__ = 'Apache v2'
## Largest 5 digit number in a series ## 7 kyu ## https://www.codewars.com/kata/51675d17e0c1bed195000001 def solution(digits): biggest = 0 for index in range(len(digits) - 4): if int(digits[index:index+5]) > biggest: biggest = int(digits[index:index+5]) return biggest
def solution(digits): biggest = 0 for index in range(len(digits) - 4): if int(digits[index:index + 5]) > biggest: biggest = int(digits[index:index + 5]) return biggest
""" Quantum Probability =================== """ class QuantumProbability( int, ): def __init__( self, probability: int, ): super().__new__( int, probability, )
""" Quantum Probability =================== """ class Quantumprobability(int): def __init__(self, probability: int): super().__new__(int, probability)
# Databricks notebook source ## Enter your group specific information here... GROUP='group05' # CHANGE TO YOUR GROUP NAME # COMMAND ---------- """ Enter any project wide configuration here... - paths - table names - constants - etc """ # Some configuration of the cluster spark.conf.set("spark.sql.shuffle.partitions", "32") # Configure the size of shuffles the same as core count on your cluster spark.conf.set("spark.sql.adaptive.enabled", "true") # Spark 3.0 AQE - coalescing post-shuffle partitions, converting sort-merge join to broadcast join, and skew join optimization # Mount the S3 class and group specific buckets CLASS_DATA_PATH, GROUP_DATA_PATH = Utils.mount_datasets(GROUP) # create the delta tables base dir in the s3 bucket for your group BASE_DELTA_PATH = Utils.create_delta_dir(GROUP) # Create the metastore for your group and set as the default db GROUP_DBNAME = Utils.create_metastore(GROUP) # class DB Name (bronze data resides here) CLASS_DBNAME = "dscc202_db" # COMMAND ---------- displayHTML(f""" <table border=1> <tr><td><b>Variable Name</b></td><td><b>Value</b></td></tr> <tr><td>CLASS_DATA_PATH</td><td>{CLASS_DATA_PATH}</td></tr> <tr><td>GROUP_DATA_PATH</td><td>{GROUP_DATA_PATH}</td></tr> <tr><td>BASE_DELTA_PATH</td><td>{BASE_DELTA_PATH}</td></tr> <tr><td>GROUP_DBNAME</td><td>{GROUP_DBNAME}</td></tr> <tr><td>CLASS_DBNAME</td><td>{CLASS_DBNAME}</td></tr> </table> """)
group = 'group05' '\nEnter any project wide configuration here...\n- paths\n- table names\n- constants\n- etc\n' spark.conf.set('spark.sql.shuffle.partitions', '32') spark.conf.set('spark.sql.adaptive.enabled', 'true') (class_data_path, group_data_path) = Utils.mount_datasets(GROUP) base_delta_path = Utils.create_delta_dir(GROUP) group_dbname = Utils.create_metastore(GROUP) class_dbname = 'dscc202_db' display_html(f'\n<table border=1>\n<tr><td><b>Variable Name</b></td><td><b>Value</b></td></tr>\n<tr><td>CLASS_DATA_PATH</td><td>{CLASS_DATA_PATH}</td></tr>\n<tr><td>GROUP_DATA_PATH</td><td>{GROUP_DATA_PATH}</td></tr>\n<tr><td>BASE_DELTA_PATH</td><td>{BASE_DELTA_PATH}</td></tr>\n<tr><td>GROUP_DBNAME</td><td>{GROUP_DBNAME}</td></tr>\n<tr><td>CLASS_DBNAME</td><td>{CLASS_DBNAME}</td></tr>\n</table>\n')
""" A simple script. This file shows why we use print. Author: Walker M. White (wmw2) Date: July 31, 2018 """ x = 1+2 # I am a comment x = 3*x print(x)
""" A simple script. This file shows why we use print. Author: Walker M. White (wmw2) Date: July 31, 2018 """ x = 1 + 2 x = 3 * x print(x)
{ "targets": [ { "target_name": "game", "sources": [ "game.cpp" ] } ] }
{'targets': [{'target_name': 'game', 'sources': ['game.cpp']}]}
class Stack: def __init__(self,max_size=4): self.max_size = max_size self.stk = [None]*max_size self.last_pos = -1 def pop(self): if self.last_pos < 0: raise IndexError() temp = self.stk[self.last_pos] self.stk[self.last_pos]=None if self.last_pos >=0: self.last_pos-=1 return temp def push(self,value): if self.last_pos > self.max_size: raise IndexError() if self.last_pos<0: self.last_pos+=1 self.stk[self.last_pos]=value return self.last_pos+=1 self.stk[self.last_pos]=value def top(self): return self.stk[self.last_pos] def test_stack(): stk = Stack() stk.push(1) stk.push(2) stk.push(3) stk.push(4) # print("********************") # stk.push(5) print("********************") print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.pop()) if __name__ == "__main__": test_stack()
class Stack: def __init__(self, max_size=4): self.max_size = max_size self.stk = [None] * max_size self.last_pos = -1 def pop(self): if self.last_pos < 0: raise index_error() temp = self.stk[self.last_pos] self.stk[self.last_pos] = None if self.last_pos >= 0: self.last_pos -= 1 return temp def push(self, value): if self.last_pos > self.max_size: raise index_error() if self.last_pos < 0: self.last_pos += 1 self.stk[self.last_pos] = value return self.last_pos += 1 self.stk[self.last_pos] = value def top(self): return self.stk[self.last_pos] def test_stack(): stk = stack() stk.push(1) stk.push(2) stk.push(3) stk.push(4) print('********************') print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.top()) print(stk.pop()) print(stk.pop()) if __name__ == '__main__': test_stack()
#!/usr/bin/env python3 """Peter Rasmussen, Programming Assignment 1, utils.py This module provides miscellaneous utility functions for this package. """ def compute_factorial(n: int) -> int: """ Compute n-factorial. :param n: Number to compute factorial for :return: n-factorial """ if (not isinstance(n, int)) or (n < 0): raise ValueError("compute_factorial() only accepts non-negative integer values.") factorial = 1 for i in range(1, n + 1): factorial *= i return factorial def n_choose_k(n, m=2) -> int: """ Return number of ways to draw a subset of size m from set of size n. :param n: Set size :param m: Size of each subset :return: Number of ways to draw a subset of size m from set of size n """ integers = (not isinstance(n, int)) or (not isinstance(m, int)) nonnegative = (n >= 0) and (m >= 0) if integers and nonnegative: raise TypeError("The parameters n and m must be non-negative integers.") if m > n: raise ValueError("The parameter m must be less than or equal to n.") return int(compute_factorial(n) / (compute_factorial(m) * compute_factorial(n - m)))
"""Peter Rasmussen, Programming Assignment 1, utils.py This module provides miscellaneous utility functions for this package. """ def compute_factorial(n: int) -> int: """ Compute n-factorial. :param n: Number to compute factorial for :return: n-factorial """ if not isinstance(n, int) or n < 0: raise value_error('compute_factorial() only accepts non-negative integer values.') factorial = 1 for i in range(1, n + 1): factorial *= i return factorial def n_choose_k(n, m=2) -> int: """ Return number of ways to draw a subset of size m from set of size n. :param n: Set size :param m: Size of each subset :return: Number of ways to draw a subset of size m from set of size n """ integers = not isinstance(n, int) or not isinstance(m, int) nonnegative = n >= 0 and m >= 0 if integers and nonnegative: raise type_error('The parameters n and m must be non-negative integers.') if m > n: raise value_error('The parameter m must be less than or equal to n.') return int(compute_factorial(n) / (compute_factorial(m) * compute_factorial(n - m)))
DEFAULT_SERVER_HOST = "localhost" DEFAULT_SERVER_PORT = 11211 DEFAULT_POOL_MINSIZE = 2 DEFAULT_POOL_MAXSIZE = 5 DEFAULT_TIMEOUT = 1 DEFAULT_MAX_KEY_LENGTH = 250 DEFAULT_MAX_VALUE_LENGTH = 1024 * 1024 # 1 megabyte STORED = b"STORED\r\n" NOT_STORED = b"NOT_STORED\r\n" EXISTS = b"EXISTS\r\n" NOT_FOUND = b"NOT_FOUND\r\n" DELETED = b"DELETED\r\n" TOUCHED = b"TOUCHED\r\n" END = b"END\r\n" VERSION = b"VERSION" OK = b"OK\r\n"
default_server_host = 'localhost' default_server_port = 11211 default_pool_minsize = 2 default_pool_maxsize = 5 default_timeout = 1 default_max_key_length = 250 default_max_value_length = 1024 * 1024 stored = b'STORED\r\n' not_stored = b'NOT_STORED\r\n' exists = b'EXISTS\r\n' not_found = b'NOT_FOUND\r\n' deleted = b'DELETED\r\n' touched = b'TOUCHED\r\n' end = b'END\r\n' version = b'VERSION' ok = b'OK\r\n'
def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return int(copy[int((size-1) / 2)]) else: return (int(copy[int((size) / 2)-1]) + int(copy[int(size / 2)])) / 2
def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return int(copy[int((size - 1) / 2)]) else: return (int(copy[int(size / 2) - 1]) + int(copy[int(size / 2)])) / 2
# Python program to calculate C(n, k) # Returns value of Binomial Coefficient # C(n, k) def binomialCoefficient(n, k): # since C(n, k) = C(n, n - k) if(k > n - k): k = n - k # initialize result res = 1 # Calculate value of # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1] for i in range(k): res = res * (n - i) res = res / (i + 1) return res # Driver program to test above function n,k= map(int, input().split()) res = binomialCoefficient(n, k) print("Value of C(% d, % d) is % d" %(n, k, res)) ''' TEST CASES Input = 5 3 Output = Value of C( 5, 3) is 10 Input = 8 1 Output = Value of C( 8, 1) is 8 '''
def binomial_coefficient(n, k): if k > n - k: k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return res (n, k) = map(int, input().split()) res = binomial_coefficient(n, k) print('Value of C(% d, % d) is % d' % (n, k, res)) '\nTEST CASES\n\nInput =\n5 3\nOutput = \nValue of C( 5, 3) is 10\n\nInput =\n8 1\nOutput = \nValue of C( 8, 1) is 8\n\n'
#does array have duplicate entries a=[1,2,3,4,5,1,7] i=1 j=1 for num in a: for ab in range(len(a)): if num==a[i]: print("duplicate found! ",num,"is = a[",i,"]") else: print(num,"is not = a[",i,"]" ) if i>4: break else: i=i+1 i=0
a = [1, 2, 3, 4, 5, 1, 7] i = 1 j = 1 for num in a: for ab in range(len(a)): if num == a[i]: print('duplicate found! ', num, 'is = a[', i, ']') else: print(num, 'is not = a[', i, ']') if i > 4: break else: i = i + 1 i = 0
{ 'name': 'To-Do Kanban board', 'description': 'Kanban board to manage to-do tasks.', 'author': 'Daniel Reis', 'depends': ['todo_ui'], 'data': ['views/todo_view.xml'], }
{'name': 'To-Do Kanban board', 'description': 'Kanban board to manage to-do tasks.', 'author': 'Daniel Reis', 'depends': ['todo_ui'], 'data': ['views/todo_view.xml']}
# play sound file = "HappyBirthday.mp3" print('playing sound using native player') os.system("afplay " + file)
file = 'HappyBirthday.mp3' print('playing sound using native player') os.system('afplay ' + file)
class SkiffKernel(object): """SkiffKernel""" def __init__(self, options=None, **kwargs): super(SkiffKernel, self).__init__() if not options: options = kwargs self._json = options self.__dict__.update(options) def __repr__(self): return '<%s (#%s) %s>' % (self.name, self.id, self.version)
class Skiffkernel(object): """SkiffKernel""" def __init__(self, options=None, **kwargs): super(SkiffKernel, self).__init__() if not options: options = kwargs self._json = options self.__dict__.update(options) def __repr__(self): return '<%s (#%s) %s>' % (self.name, self.id, self.version)
class Solution(object): def splitIntoFibonacci(self, S): """ :type S: str :rtype: List[int] """ Solution.res= [] self.backtrack(0, 0, 0, [],S) return Solution.res def backtrack(self, start, last1, last2, intList, string): for i in range(start,len(string)): cur = int(string[start:i + 1]) if len(string[start:i + 1]) != len(str(cur)): break # if cur > 2147483647: # break if len(intList) == 0: self.backtrack(i + 1, cur, last2, intList + [cur], string) elif len(intList) == 1: self.backtrack(i + 1, last1, cur, intList + [cur], string) else: if cur > last1 + last2: break elif cur == last1 + last2: if i == len(string) - 1: Solution.res = intList + [cur] return else: self.backtrack(i + 1, last2, cur, intList + [cur], string) else: continue s = Solution() print(s.splitIntoFibonacci("123456579"))
class Solution(object): def split_into_fibonacci(self, S): """ :type S: str :rtype: List[int] """ Solution.res = [] self.backtrack(0, 0, 0, [], S) return Solution.res def backtrack(self, start, last1, last2, intList, string): for i in range(start, len(string)): cur = int(string[start:i + 1]) if len(string[start:i + 1]) != len(str(cur)): break if len(intList) == 0: self.backtrack(i + 1, cur, last2, intList + [cur], string) elif len(intList) == 1: self.backtrack(i + 1, last1, cur, intList + [cur], string) elif cur > last1 + last2: break elif cur == last1 + last2: if i == len(string) - 1: Solution.res = intList + [cur] return else: self.backtrack(i + 1, last2, cur, intList + [cur], string) else: continue s = solution() print(s.splitIntoFibonacci('123456579'))
v = 18 _v = 56 def f(): pass def _f(): pass class MyClass(object): pass class _MyClass(object): pass
v = 18 _v = 56 def f(): pass def _f(): pass class Myclass(object): pass class _Myclass(object): pass
def solve_single_lin(opt_x_s): ''' solve one opt_x[s] ''' opt_x_s.solve(solver='MOSEK', verbose = True) return opt_x_s
def solve_single_lin(opt_x_s): """ solve one opt_x[s] """ opt_x_s.solve(solver='MOSEK', verbose=True) return opt_x_s
pkgname = "xsetroot" pkgver = "1.1.2" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] makedepends = [ "xbitmaps", "libxmu-devel", "libxrender-devel", "libxfixes-devel", "libxcursor-devel" ] pkgdesc = "X root window parameter setting utility" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://xorg.freedesktop.org" source = f"$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.bz2" sha256 = "10c442ba23591fb5470cea477a0aa5f679371f4f879c8387a1d9d05637ae417c" def post_install(self): self.install_license("COPYING")
pkgname = 'xsetroot' pkgver = '1.1.2' pkgrel = 0 build_style = 'gnu_configure' hostmakedepends = ['pkgconf'] makedepends = ['xbitmaps', 'libxmu-devel', 'libxrender-devel', 'libxfixes-devel', 'libxcursor-devel'] pkgdesc = 'X root window parameter setting utility' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'https://xorg.freedesktop.org' source = f'$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.bz2' sha256 = '10c442ba23591fb5470cea477a0aa5f679371f4f879c8387a1d9d05637ae417c' def post_install(self): self.install_license('COPYING')
def is_num(in_value): """Checks if a value is a valid number. Parameters ---------- in_value A variable of any type that we want to check is a number. Returns ------- bool True/False depending on whether it was a number. Examples -------- >>> is_num(1) True >>> is_num("Hello") False You can also pass more complex objects, these will all be ''False''. >>> is_num({"hi": "apple"}) False """ try: float(in_value) return True except (ValueError, TypeError): return False
def is_num(in_value): """Checks if a value is a valid number. Parameters ---------- in_value A variable of any type that we want to check is a number. Returns ------- bool True/False depending on whether it was a number. Examples -------- >>> is_num(1) True >>> is_num("Hello") False You can also pass more complex objects, these will all be ''False''. >>> is_num({"hi": "apple"}) False """ try: float(in_value) return True except (ValueError, TypeError): return False
class Item: def __init__(self, block_id, count, damage, data): self.block_id = block_id self.count = count self.damage = damage self.data = data def __str__(self): return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage)
class Item: def __init__(self, block_id, count, damage, data): self.block_id = block_id self.count = count self.damage = damage self.data = data def __str__(self): return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage)
""" 103. Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] a modification from 102 author: gengwg """ # 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 zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] self.preorder(root, 0, res) return res def preorder(self, root, level, res): if root: # create an empty list for new level if len(res) <= level: res.append([]) if level % 2 == 0: # even level, append at the end res[level].append(root.val) else: # at odd level, append to the beginning res[level].insert(0, root.val) self.preorder(root.left, level + 1, res) self.preorder(root.right, level + 1, res)
""" 103. Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] a modification from 102 author: gengwg """ class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzag_level_order(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] self.preorder(root, 0, res) return res def preorder(self, root, level, res): if root: if len(res) <= level: res.append([]) if level % 2 == 0: res[level].append(root.val) else: res[level].insert(0, root.val) self.preorder(root.left, level + 1, res) self.preorder(root.right, level + 1, res)
BAZEL_VERSION_SHA256S = { "0.14.1": "7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376", "0.15.0": "7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b", "0.15.2": "13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241", "0.16.1": "17ab70344645359fd4178002f367885e9019ae7507c9c1ade8220f3628383444", } # This is the map from supported Bazel versions to the Bazel version used to # generate the published toolchain configs that the former should be used with. # This is needed because, in most cases, patch updates in Bazel do not result in # changes in toolchain configs, so we do not publish duplicated toolchain # configs. So, for example, Bazel 0.15.2 should still use published toolchain # configs generated with Bazel 0.15.0. BAZEL_VERSION_TO_CONFIG_VERSION = { "0.14.1": "0.14.1", "0.15.0": "0.15.0", "0.15.2": "0.15.0", "0.16.1": "0.16.1", }
bazel_version_sha256_s = {'0.14.1': '7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376', '0.15.0': '7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b', '0.15.2': '13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241', '0.16.1': '17ab70344645359fd4178002f367885e9019ae7507c9c1ade8220f3628383444'} bazel_version_to_config_version = {'0.14.1': '0.14.1', '0.15.0': '0.15.0', '0.15.2': '0.15.0', '0.16.1': '0.16.1'}
def censor(text, word): bigstring = text.split() print (bigstring) words = "" " ".join(bigstring) return bigstring print (censor("hello hi hey", "hi"))
def censor(text, word): bigstring = text.split() print(bigstring) words = '' ' '.join(bigstring) return bigstring print(censor('hello hi hey', 'hi'))
# -*- coding: utf-8 -*- """ Created on Sun Jul 5 18:30:18 2020 @author: MarcoSilva """ def general_poly (L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """ def f(x): total = 0 fact = len(L) - 1 for num in L: print(num) total += num * x**fact fact -= 1 return total return f
""" Created on Sun Jul 5 18:30:18 2020 @author: MarcoSilva """ def general_poly(L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """ def f(x): total = 0 fact = len(L) - 1 for num in L: print(num) total += num * x ** fact fact -= 1 return total return f
config = { 'api_root': 'https://library.cca.edu/api/v1', 'client_id': 'abcedfg-123445678', 'client_secret': 'abcedfg-123445678', }
config = {'api_root': 'https://library.cca.edu/api/v1', 'client_id': 'abcedfg-123445678', 'client_secret': 'abcedfg-123445678'}
""" Power digit sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ exponent = 1000 def initial_func(exponent): return sum(int(digit) for digit in f'{2 ** exponent}') def improved_func(exponent): pass # 1366 print(initial_func(exponent)) # print(improved_func(exponent))
""" Power digit sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ exponent = 1000 def initial_func(exponent): return sum((int(digit) for digit in f'{2 ** exponent}')) def improved_func(exponent): pass print(initial_func(exponent))
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A(B('Placement portal'),_class="brand", _id="web2py-logo") response.title = request.application.replace('_',' ').title() response.subtitle = '' ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Your Name <you@example.com>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### if auth.has_membership('student_group') and not auth.has_membership('spc_group'): response.menu= [ (T('Home'), False, URL('default', 'index'), []), (T('Apply'), False, URL('s_controller','apply_for'),[] ),(T('Spc'), False,URL('s_controller','spc'),[]) ] elif auth.has_membership('student_group') and auth.has_membership('spc_group'): response.menu= [ (T('Home'), False, URL('default', 'index'), []), (T('Apply'), False, URL('s_controller','apply_for'),[] ),(T('View Student Deatils'), False, URL('s_controller','spc_view'),[] )] elif auth.has_membership('company_group'): response.menu= [ (T('Home'), False, URL('default', 'index'), []), (T('New Posting'), False,URL('c_controller','posting'),[]), (T('View Posting'), False,URL('c_controller','view_posting'),[]) ] elif auth.has_membership('TPO'): response.menu = [ (T('Home'), False, URL('default', 'index'), []), ] else: response.menu = [ (T('Home'), False, URL('default', 'index'), []), (T('Student Register'), False, URL('s_controller', 'reg_s'), []), (T('Company Register'), False, URL('c_controller', 'reg_c'), []) ] DEVELOPMENT_MENU = True if "auth" in locals(): auth.wikimenu()
response.logo = a(b('Placement portal'), _class='brand', _id='web2py-logo') response.title = request.application.replace('_', ' ').title() response.subtitle = '' response.meta.author = 'Your Name <you@example.com>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' response.google_analytics_id = None if auth.has_membership('student_group') and (not auth.has_membership('spc_group')): response.menu = [(t('Home'), False, url('default', 'index'), []), (t('Apply'), False, url('s_controller', 'apply_for'), []), (t('Spc'), False, url('s_controller', 'spc'), [])] elif auth.has_membership('student_group') and auth.has_membership('spc_group'): response.menu = [(t('Home'), False, url('default', 'index'), []), (t('Apply'), False, url('s_controller', 'apply_for'), []), (t('View Student Deatils'), False, url('s_controller', 'spc_view'), [])] elif auth.has_membership('company_group'): response.menu = [(t('Home'), False, url('default', 'index'), []), (t('New Posting'), False, url('c_controller', 'posting'), []), (t('View Posting'), False, url('c_controller', 'view_posting'), [])] elif auth.has_membership('TPO'): response.menu = [(t('Home'), False, url('default', 'index'), [])] else: response.menu = [(t('Home'), False, url('default', 'index'), []), (t('Student Register'), False, url('s_controller', 'reg_s'), []), (t('Company Register'), False, url('c_controller', 'reg_c'), [])] development_menu = True if 'auth' in locals(): auth.wikimenu()
def bubble_sort(elements: list): """Sort the list inplace using bubble sort. Args: -- elements (list): list of elements """ size = len(elements) for i in range(size - 1): # if list is already sorted track it using swapped variable swapped = False for j in range(size - 1 - i): if elements[j] > elements[j + 1]: # swapping tmp = elements[j] elements[j] = elements[j + 1] elements[j + 1] = tmp swapped = True if not swapped: break if __name__ == "__main__": elements = [5, 9, 2, 1, 67, 34, 88, 34] print(f"Before Sorting: {elements}") bubble_sort(elements) print(f"After sorting: {elements} ")
def bubble_sort(elements: list): """Sort the list inplace using bubble sort. Args: -- elements (list): list of elements """ size = len(elements) for i in range(size - 1): swapped = False for j in range(size - 1 - i): if elements[j] > elements[j + 1]: tmp = elements[j] elements[j] = elements[j + 1] elements[j + 1] = tmp swapped = True if not swapped: break if __name__ == '__main__': elements = [5, 9, 2, 1, 67, 34, 88, 34] print(f'Before Sorting: {elements}') bubble_sort(elements) print(f'After sorting: {elements} ')
# game model list base class for all object collections in game class GameModelList(): def __init__( self, game, game_models=[], collidable=False, block_color=None ): self.game = game self.game_models = game_models self.collidable = collidable self.block_color = block_color for model in self.game_models: model.set_collidable(self.collidable) def add_game_model(self, game_model): self.game_models.append(game_model) game_model.set_collidable(self.collidable) def get_game_models(self): return self.game_models def remove_game_model(self, game_model): self.game_models.remove(game_model) def get_block_color(self): return self.block_color def draw(self): for block in self.game_models: block.draw() def update(self): for model in self.game_models: model.update()
class Gamemodellist: def __init__(self, game, game_models=[], collidable=False, block_color=None): self.game = game self.game_models = game_models self.collidable = collidable self.block_color = block_color for model in self.game_models: model.set_collidable(self.collidable) def add_game_model(self, game_model): self.game_models.append(game_model) game_model.set_collidable(self.collidable) def get_game_models(self): return self.game_models def remove_game_model(self, game_model): self.game_models.remove(game_model) def get_block_color(self): return self.block_color def draw(self): for block in self.game_models: block.draw() def update(self): for model in self.game_models: model.update()
# Author: Ian Burke # Module: Emerging Technologies # Date: September, 2017 # Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html # create a function to reverse a string def reverse(): word = input("Enter a string: ") #user enters a string and store it in word word = word[::-1] # slices and reverses the string # Reference: https://stackoverflow.com/questions/931092/reverse-a-string-in-python print(word) reverse() # call function to run
def reverse(): word = input('Enter a string: ') word = word[::-1] print(word) reverse()
# GENERATED VERSION FILE # TIME: Tue Oct 26 14:07:11 2021 __version__ = '0.3.0+dc45206' short_version = '0.3.0'
__version__ = '0.3.0+dc45206' short_version = '0.3.0'
class Cuenta: def __init__(self, nombre, numero, saldo): self.nombre = nombre self.numero= numero self.saldo = saldo def depositar(self, a): self.saldo=self.saldo+a return self.saldo def retirar(self, a): self.saldo=self.saldo-a return self.saldo
class Cuenta: def __init__(self, nombre, numero, saldo): self.nombre = nombre self.numero = numero self.saldo = saldo def depositar(self, a): self.saldo = self.saldo + a return self.saldo def retirar(self, a): self.saldo = self.saldo - a return self.saldo
temp=n=int(input("Enter a number: ")) sum1 = 0 while(n > 0): sum1=sum1+n n=n-1 print(f"natural numbers in series {sum1}+{n}") print(f"The sum of first {temp} natural numbers is: {sum1}")
temp = n = int(input('Enter a number: ')) sum1 = 0 while n > 0: sum1 = sum1 + n n = n - 1 print(f'natural numbers in series {sum1}+{n}') print(f'The sum of first {temp} natural numbers is: {sum1}')
# red_black_node.py class Node: """ A class used to represent a Node in a red-black search tree. Attributes: key: The key is the value the node shall be sorted on. The key can be an integer, float, string, anything capable of being sorted. instances (int): The number of times the key for a node was inserted into the tree. parent (node): The pointer to the parent of the node. left (node): The pointer to the left child node. right (node): The pointer to the right child node. is_red (bool): The color attribute keeps track of whether a node is red or black. """ def __init__(self, key): """ Parameters: key: The key is the value the node shall be sorted on. The key can be an integer, float, string, anything capable of being sorted. """ self.key = key self.instances = 1 self.parent = None self.left = None self.right = None self.is_red = True def recolor(self): """ Switches the color of a Node from red to black or black to red. """ if self.is_red: self.is_red = False else: self.is_red = True def add_instance(self): """ Allows for duplicates in a node by making it "fat" instead of creating more nodes which would defeat the purpose of a self- balancing tree. """ self.instances += 1 def remove_instance(self): """ Allows for removal of a single instance of a key from the search tree rather than pruning an entire node from the tree. """ self.instances -= 1 def delete(self): """ Zeroes out a node for deletion. """ self.key = None self.instances = 0 self.parent = None self.left = None self.right = None self.is_red = False # Null nodes are, by default, black.
class Node: """ A class used to represent a Node in a red-black search tree. Attributes: key: The key is the value the node shall be sorted on. The key can be an integer, float, string, anything capable of being sorted. instances (int): The number of times the key for a node was inserted into the tree. parent (node): The pointer to the parent of the node. left (node): The pointer to the left child node. right (node): The pointer to the right child node. is_red (bool): The color attribute keeps track of whether a node is red or black. """ def __init__(self, key): """ Parameters: key: The key is the value the node shall be sorted on. The key can be an integer, float, string, anything capable of being sorted. """ self.key = key self.instances = 1 self.parent = None self.left = None self.right = None self.is_red = True def recolor(self): """ Switches the color of a Node from red to black or black to red. """ if self.is_red: self.is_red = False else: self.is_red = True def add_instance(self): """ Allows for duplicates in a node by making it "fat" instead of creating more nodes which would defeat the purpose of a self- balancing tree. """ self.instances += 1 def remove_instance(self): """ Allows for removal of a single instance of a key from the search tree rather than pruning an entire node from the tree. """ self.instances -= 1 def delete(self): """ Zeroes out a node for deletion. """ self.key = None self.instances = 0 self.parent = None self.left = None self.right = None self.is_red = False
def get_max_profit(stock_prices): # initialize the lowest_price to the first stock price lowest_price = stock_prices[0] # initialize the max_profit to the # difference between the first and the second stock price max_profit = stock_prices[1] - stock_prices[0] # loop through every price in stock_prices # starting from the second price for index in range(1, len(stock_prices)): # if price minus lowest_price is greater than max_profit if stock_prices[index] - lowest_price > max_profit: # set max_profit to the difference between price and lowest_price max_profit = stock_prices[index] - lowest_price # if price is lower than lowest_price if stock_prices[index] < lowest_price: # set lowest_price to price lowest_price = stock_prices[index] # return max_profit return max_profit
def get_max_profit(stock_prices): lowest_price = stock_prices[0] max_profit = stock_prices[1] - stock_prices[0] for index in range(1, len(stock_prices)): if stock_prices[index] - lowest_price > max_profit: max_profit = stock_prices[index] - lowest_price if stock_prices[index] < lowest_price: lowest_price = stock_prices[index] return max_profit
# Given an integer n, return the number of trailing zeroes in n!. # Example 1: # Input: 3 # Output: 0 # Explanation: 3! = 6, no trailing zero. # Example 2: # Input: 5 # Output: 1 # Explanation: 5! = 120, one trailing zero. class Solution: def trailingZeroes(self, n): """ :type n: int :rtype: int """ x = 5 ans = 0 while n >= x: ans += n // x x *= 5 return ans print(Solution().trailingZeroes(1808548329))
class Solution: def trailing_zeroes(self, n): """ :type n: int :rtype: int """ x = 5 ans = 0 while n >= x: ans += n // x x *= 5 return ans print(solution().trailingZeroes(1808548329))
class EventMongoRepository: database_address = "localhost" def __init__(self): self.client = "Opens a connection with mongo" def add_event(self, event): pass def remove_event(self, event): pass def update_event(self, event): pass
class Eventmongorepository: database_address = 'localhost' def __init__(self): self.client = 'Opens a connection with mongo' def add_event(self, event): pass def remove_event(self, event): pass def update_event(self, event): pass
class SuperList(list): def __len__(self): return 1000 super_list1 = SuperList() print(len(super_list1)) super_list1.append(5) print(super_list1[0]) print(issubclass(list, object))
class Superlist(list): def __len__(self): return 1000 super_list1 = super_list() print(len(super_list1)) super_list1.append(5) print(super_list1[0]) print(issubclass(list, object))
class Finding: def __init__(self, filename, secret_type, secret_value, line_number=None, link=None): self._filename = filename self._secret_type = secret_type self._secret_value = secret_value self._line_number = line_number self._link = link @property def filename(self): return self._filename @property def secret_type(self): return self._secret_type @property def link(self): return self._link @property def line_number(self): return self._line_number def __eq__(self, other): if isinstance(other, Finding): return self.filename == other.filename and \ self.secret_type == other.secret_type and \ self._secret_value == other._secret_value def __hash__(self): return hash((self._filename, self._secret_type, self._secret_value)) def __str__(self): s = "Secret type {} found in {}".format(self._secret_type, self._filename) if self._line_number is not None: s = s + ":{}".format(self._line_number) if self._link is not None: s = s + " ({})".format(self._link) return s def __repr__(self): return "<{}> ({})".format(self._secret_type, self._filename)
class Finding: def __init__(self, filename, secret_type, secret_value, line_number=None, link=None): self._filename = filename self._secret_type = secret_type self._secret_value = secret_value self._line_number = line_number self._link = link @property def filename(self): return self._filename @property def secret_type(self): return self._secret_type @property def link(self): return self._link @property def line_number(self): return self._line_number def __eq__(self, other): if isinstance(other, Finding): return self.filename == other.filename and self.secret_type == other.secret_type and (self._secret_value == other._secret_value) def __hash__(self): return hash((self._filename, self._secret_type, self._secret_value)) def __str__(self): s = 'Secret type {} found in {}'.format(self._secret_type, self._filename) if self._line_number is not None: s = s + ':{}'.format(self._line_number) if self._link is not None: s = s + ' ({})'.format(self._link) return s def __repr__(self): return '<{}> ({})'.format(self._secret_type, self._filename)
PATH_ROOT = "/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/" def read_srx_list(file): srxs = set() with open(file, "r") as fh: next(fh) for line in fh: if line.startswith("SRX"): srxs.add(line.rstrip()) return list(srxs) def read_srr_file(srr_file): srr_data = {} with open(srr_file, "r") as fh: for line in fh: line = line.rstrip() srx, srrs = line.split("\t") srrs = srrs.split(", ") assert srx.startswith("SRX") assert srx not in srr_data for srr in srrs: assert srr.startswith("SRR") assert "," not in srr assert " " not in srr srr_data[srx] = srrs return srr_data def fetch_srr_ids(srx, conn): assert srx.startswith("SRX") first_chunk = srx[3:6] path = PATH_ROOT.format(first_chunk, srx) res = conn.nlst(path) return map(lambda x: x.split("/")[-1], res) def build_srr_list(srxs, conn): srr_data = {} for srx in srx_ids: srrs = fetch_srr_ids(srx, conn) srr_data[srx] = srrs return srr_data
path_root = '/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/' def read_srx_list(file): srxs = set() with open(file, 'r') as fh: next(fh) for line in fh: if line.startswith('SRX'): srxs.add(line.rstrip()) return list(srxs) def read_srr_file(srr_file): srr_data = {} with open(srr_file, 'r') as fh: for line in fh: line = line.rstrip() (srx, srrs) = line.split('\t') srrs = srrs.split(', ') assert srx.startswith('SRX') assert srx not in srr_data for srr in srrs: assert srr.startswith('SRR') assert ',' not in srr assert ' ' not in srr srr_data[srx] = srrs return srr_data def fetch_srr_ids(srx, conn): assert srx.startswith('SRX') first_chunk = srx[3:6] path = PATH_ROOT.format(first_chunk, srx) res = conn.nlst(path) return map(lambda x: x.split('/')[-1], res) def build_srr_list(srxs, conn): srr_data = {} for srx in srx_ids: srrs = fetch_srr_ids(srx, conn) srr_data[srx] = srrs return srr_data
styles = { "alignment": { "color": "black", "linestyle": "-", "linewidth": 1.0, "alpha": 0.2, "label": "raw alignment" }, "despiked": { "color": "blue", "linestyle": "-", "linewidth": 1.4, "alpha": 1.0, "label": "de-spiked alignment" }, "line1": { "color": "black", "linestyle": "-", "linewidth": 1.2, "alpha": 0.3, "label": "line1" }, "line2": { "color": "blue", "linestyle": "-", "linewidth": 1.4, "alpha": 1.0, "label": "line2" }, "line3": { "color": "green", "linestyle": "-", "linewidth": 1.4, "alpha": 1.0, "label": "line3" }, "point1": { "color": "red", "marker": "o", "markersize": 6, "markeredgecolor": "black", "alpha": 1.0, "linestyle": "None", "label": "point1" }, "point2": { "color": "orange", "marker": "o", "markersize": 4, "markeredgecolor": "None", "alpha": 0.5, "linestyle": "None", "label": "point2" }, "point3": { "color": "None", "marker": "o", "markersize": 4, "markeredgecolor": "brown", "alpha": 1.0, "linestyle": "None", "label": "point3" } }
styles = {'alignment': {'color': 'black', 'linestyle': '-', 'linewidth': 1.0, 'alpha': 0.2, 'label': 'raw alignment'}, 'despiked': {'color': 'blue', 'linestyle': '-', 'linewidth': 1.4, 'alpha': 1.0, 'label': 'de-spiked alignment'}, 'line1': {'color': 'black', 'linestyle': '-', 'linewidth': 1.2, 'alpha': 0.3, 'label': 'line1'}, 'line2': {'color': 'blue', 'linestyle': '-', 'linewidth': 1.4, 'alpha': 1.0, 'label': 'line2'}, 'line3': {'color': 'green', 'linestyle': '-', 'linewidth': 1.4, 'alpha': 1.0, 'label': 'line3'}, 'point1': {'color': 'red', 'marker': 'o', 'markersize': 6, 'markeredgecolor': 'black', 'alpha': 1.0, 'linestyle': 'None', 'label': 'point1'}, 'point2': {'color': 'orange', 'marker': 'o', 'markersize': 4, 'markeredgecolor': 'None', 'alpha': 0.5, 'linestyle': 'None', 'label': 'point2'}, 'point3': {'color': 'None', 'marker': 'o', 'markersize': 4, 'markeredgecolor': 'brown', 'alpha': 1.0, 'linestyle': 'None', 'label': 'point3'}}
# -*- coding: utf-8 -*- """ Created on Thu Oct 21 18:24:11 2021 @author: User """ # Objetos, pilas y colas class Rectangulo(): def __init__(self, x, y): self.x = x self.y = y def base(self): return def altura(self): return def area(self): return def desplazar(self, desplazamiento): return def rotar(self, x): return def __str__(self): return f'({self.x}, {self.y})' # Used with `repr()` def __repr__(self): return class Punto(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'({self.x}, {self.y})' # Used with `repr()` def __repr__(self): return f'Punto({self.x}, {self.y})' def __add__(self, b): return Punto(self.x + b.x, self.y + b.y)
""" Created on Thu Oct 21 18:24:11 2021 @author: User """ class Rectangulo: def __init__(self, x, y): self.x = x self.y = y def base(self): return def altura(self): return def area(self): return def desplazar(self, desplazamiento): return def rotar(self, x): return def __str__(self): return f'({self.x}, {self.y})' def __repr__(self): return class Punto: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'({self.x}, {self.y})' def __repr__(self): return f'Punto({self.x}, {self.y})' def __add__(self, b): return punto(self.x + b.x, self.y + b.y)
# encoding: utf-8 # module errno # from (built-in) # by generator 1.147 """ This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value, e.g., on most systems, errno.ENOENT equals the integer 2. The dictionary errno.errorcode maps numeric codes to symbol names, e.g., errno.errorcode[2] could be the string 'ENOENT'. Symbols that are not relevant to the underlying system are not defined. To map error codes to error messages, use the function os.strerror(), e.g. os.strerror(2) could return 'No such file or directory'. """ # no imports # Variables with simple values E2BIG = 7 EACCES = 13 EADDRINUSE = 10048 EADDRNOTAVAIL = 10049 EAFNOSUPPORT = 10047 EAGAIN = 11 EALREADY = 10037 EBADF = 9 EBUSY = 16 ECHILD = 10 ECONNABORTED = 10053 ECONNREFUSED = 10061 ECONNRESET = 10054 EDEADLK = 36 EDEADLOCK = 36 EDESTADDRREQ = 10039 EDOM = 33 EDQUOT = 10069 EEXIST = 17 EFAULT = 14 EFBIG = 27 EHOSTDOWN = 10064 EHOSTUNREACH = 10065 EILSEQ = 42 EINPROGRESS = 10036 EINTR = 4 EINVAL = 22 EIO = 5 EISCONN = 10056 EISDIR = 21 ELOOP = 10062 EMFILE = 24 EMLINK = 31 EMSGSIZE = 10040 ENAMETOOLONG = 38 ENETDOWN = 10050 ENETRESET = 10052 ENETUNREACH = 10051 ENFILE = 23 ENOBUFS = 10055 ENODEV = 19 ENOENT = 2 ENOEXEC = 8 ENOLCK = 39 ENOMEM = 12 ENOPROTOOPT = 10042 ENOSPC = 28 ENOSYS = 40 ENOTCONN = 10057 ENOTDIR = 20 ENOTEMPTY = 41 ENOTSOCK = 10038 ENOTTY = 25 ENXIO = 6 EOPNOTSUPP = 10045 EPERM = 1 EPFNOSUPPORT = 10046 EPIPE = 32 EPROTONOSUPPORT = 10043 EPROTOTYPE = 10041 ERANGE = 34 EREMOTE = 10071 EROFS = 30 ESHUTDOWN = 10058 ESOCKTNOSUPPORT = 10044 ESPIPE = 29 ESRCH = 3 ESTALE = 10070 ETIMEDOUT = 10060 ETOOMANYREFS = 10059 EUSERS = 10068 EWOULDBLOCK = 10035 EXDEV = 18 WSABASEERR = 10000 WSAEACCES = 10013 WSAEADDRINUSE = 10048 WSAEADDRNOTAVAIL = 10049 WSAEAFNOSUPPORT = 10047 WSAEALREADY = 10037 WSAEBADF = 10009 WSAECONNABORTED = 10053 WSAECONNREFUSED = 10061 WSAECONNRESET = 10054 WSAEDESTADDRREQ = 10039 WSAEDISCON = 10101 WSAEDQUOT = 10069 WSAEFAULT = 10014 WSAEHOSTDOWN = 10064 WSAEHOSTUNREACH = 10065 WSAEINPROGRESS = 10036 WSAEINTR = 10004 WSAEINVAL = 10022 WSAEISCONN = 10056 WSAELOOP = 10062 WSAEMFILE = 10024 WSAEMSGSIZE = 10040 WSAENAMETOOLONG = 10063 WSAENETDOWN = 10050 WSAENETRESET = 10052 WSAENETUNREACH = 10051 WSAENOBUFS = 10055 WSAENOPROTOOPT = 10042 WSAENOTCONN = 10057 WSAENOTEMPTY = 10066 WSAENOTSOCK = 10038 WSAEOPNOTSUPP = 10045 WSAEPFNOSUPPORT = 10046 WSAEPROCLIM = 10067 WSAEPROTONOSUPPORT = 10043 WSAEPROTOTYPE = 10041 WSAEREMOTE = 10071 WSAESHUTDOWN = 10058 WSAESOCKTNOSUPPORT = 10044 WSAESTALE = 10070 WSAETIMEDOUT = 10060 WSAETOOMANYREFS = 10059 WSAEUSERS = 10068 WSAEWOULDBLOCK = 10035 WSANOTINITIALISED = 10093 WSASYSNOTREADY = 10091 WSAVERNOTSUPPORTED = 10092 # no functions # no classes # variables with complex values errorcode = { 1: 'EPERM', 2: 'ENOENT', 3: 'ESRCH', 4: 'EINTR', 5: 'EIO', 6: 'ENXIO', 7: 'E2BIG', 8: 'ENOEXEC', 9: 'EBADF', 10: 'ECHILD', 11: 'EAGAIN', 12: 'ENOMEM', 13: 'EACCES', 14: 'EFAULT', 16: 'EBUSY', 17: 'EEXIST', 18: 'EXDEV', 19: 'ENODEV', 20: 'ENOTDIR', 21: 'EISDIR', 22: 'EINVAL', 23: 'ENFILE', 24: 'EMFILE', 25: 'ENOTTY', 27: 'EFBIG', 28: 'ENOSPC', 29: 'ESPIPE', 30: 'EROFS', 31: 'EMLINK', 32: 'EPIPE', 33: 'EDOM', 34: 'ERANGE', 36: 'EDEADLOCK', 38: 'ENAMETOOLONG', 39: 'ENOLCK', 40: 'ENOSYS', 41: 'ENOTEMPTY', 42: 'EILSEQ', 10000: 'WSABASEERR', 10004: 'WSAEINTR', 10009: 'WSAEBADF', 10013: 'WSAEACCES', 10014: 'WSAEFAULT', 10022: 'WSAEINVAL', 10024: 'WSAEMFILE', 10035: 'WSAEWOULDBLOCK', 10036: 'WSAEINPROGRESS', 10037: 'WSAEALREADY', 10038: 'WSAENOTSOCK', 10039: 'WSAEDESTADDRREQ', 10040: 'WSAEMSGSIZE', 10041: 'WSAEPROTOTYPE', 10042: 'WSAENOPROTOOPT', 10043: 'WSAEPROTONOSUPPORT', 10044: 'WSAESOCKTNOSUPPORT', 10045: 'WSAEOPNOTSUPP', 10046: 'WSAEPFNOSUPPORT', 10047: 'WSAEAFNOSUPPORT', 10048: 'WSAEADDRINUSE', 10049: 'WSAEADDRNOTAVAIL', 10050: 'WSAENETDOWN', 10051: 'WSAENETUNREACH', 10052: 'WSAENETRESET', 10053: 'WSAECONNABORTED', 10054: 'WSAECONNRESET', 10055: 'WSAENOBUFS', 10056: 'WSAEISCONN', 10057: 'WSAENOTCONN', 10058: 'WSAESHUTDOWN', 10059: 'WSAETOOMANYREFS', 10060: 'WSAETIMEDOUT', 10061: 'WSAECONNREFUSED', 10062: 'WSAELOOP', 10063: 'WSAENAMETOOLONG', 10064: 'WSAEHOSTDOWN', 10065: 'WSAEHOSTUNREACH', 10066: 'WSAENOTEMPTY', 10067: 'WSAEPROCLIM', 10068: 'WSAEUSERS', 10069: 'WSAEDQUOT', 10070: 'WSAESTALE', 10071: 'WSAEREMOTE', 10091: 'WSASYSNOTREADY', 10092: 'WSAVERNOTSUPPORTED', 10093: 'WSANOTINITIALISED', 10101: 'WSAEDISCON', }
""" This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value, e.g., on most systems, errno.ENOENT equals the integer 2. The dictionary errno.errorcode maps numeric codes to symbol names, e.g., errno.errorcode[2] could be the string 'ENOENT'. Symbols that are not relevant to the underlying system are not defined. To map error codes to error messages, use the function os.strerror(), e.g. os.strerror(2) could return 'No such file or directory'. """ e2_big = 7 eacces = 13 eaddrinuse = 10048 eaddrnotavail = 10049 eafnosupport = 10047 eagain = 11 ealready = 10037 ebadf = 9 ebusy = 16 echild = 10 econnaborted = 10053 econnrefused = 10061 econnreset = 10054 edeadlk = 36 edeadlock = 36 edestaddrreq = 10039 edom = 33 edquot = 10069 eexist = 17 efault = 14 efbig = 27 ehostdown = 10064 ehostunreach = 10065 eilseq = 42 einprogress = 10036 eintr = 4 einval = 22 eio = 5 eisconn = 10056 eisdir = 21 eloop = 10062 emfile = 24 emlink = 31 emsgsize = 10040 enametoolong = 38 enetdown = 10050 enetreset = 10052 enetunreach = 10051 enfile = 23 enobufs = 10055 enodev = 19 enoent = 2 enoexec = 8 enolck = 39 enomem = 12 enoprotoopt = 10042 enospc = 28 enosys = 40 enotconn = 10057 enotdir = 20 enotempty = 41 enotsock = 10038 enotty = 25 enxio = 6 eopnotsupp = 10045 eperm = 1 epfnosupport = 10046 epipe = 32 eprotonosupport = 10043 eprototype = 10041 erange = 34 eremote = 10071 erofs = 30 eshutdown = 10058 esocktnosupport = 10044 espipe = 29 esrch = 3 estale = 10070 etimedout = 10060 etoomanyrefs = 10059 eusers = 10068 ewouldblock = 10035 exdev = 18 wsabaseerr = 10000 wsaeacces = 10013 wsaeaddrinuse = 10048 wsaeaddrnotavail = 10049 wsaeafnosupport = 10047 wsaealready = 10037 wsaebadf = 10009 wsaeconnaborted = 10053 wsaeconnrefused = 10061 wsaeconnreset = 10054 wsaedestaddrreq = 10039 wsaediscon = 10101 wsaedquot = 10069 wsaefault = 10014 wsaehostdown = 10064 wsaehostunreach = 10065 wsaeinprogress = 10036 wsaeintr = 10004 wsaeinval = 10022 wsaeisconn = 10056 wsaeloop = 10062 wsaemfile = 10024 wsaemsgsize = 10040 wsaenametoolong = 10063 wsaenetdown = 10050 wsaenetreset = 10052 wsaenetunreach = 10051 wsaenobufs = 10055 wsaenoprotoopt = 10042 wsaenotconn = 10057 wsaenotempty = 10066 wsaenotsock = 10038 wsaeopnotsupp = 10045 wsaepfnosupport = 10046 wsaeproclim = 10067 wsaeprotonosupport = 10043 wsaeprototype = 10041 wsaeremote = 10071 wsaeshutdown = 10058 wsaesocktnosupport = 10044 wsaestale = 10070 wsaetimedout = 10060 wsaetoomanyrefs = 10059 wsaeusers = 10068 wsaewouldblock = 10035 wsanotinitialised = 10093 wsasysnotready = 10091 wsavernotsupported = 10092 errorcode = {1: 'EPERM', 2: 'ENOENT', 3: 'ESRCH', 4: 'EINTR', 5: 'EIO', 6: 'ENXIO', 7: 'E2BIG', 8: 'ENOEXEC', 9: 'EBADF', 10: 'ECHILD', 11: 'EAGAIN', 12: 'ENOMEM', 13: 'EACCES', 14: 'EFAULT', 16: 'EBUSY', 17: 'EEXIST', 18: 'EXDEV', 19: 'ENODEV', 20: 'ENOTDIR', 21: 'EISDIR', 22: 'EINVAL', 23: 'ENFILE', 24: 'EMFILE', 25: 'ENOTTY', 27: 'EFBIG', 28: 'ENOSPC', 29: 'ESPIPE', 30: 'EROFS', 31: 'EMLINK', 32: 'EPIPE', 33: 'EDOM', 34: 'ERANGE', 36: 'EDEADLOCK', 38: 'ENAMETOOLONG', 39: 'ENOLCK', 40: 'ENOSYS', 41: 'ENOTEMPTY', 42: 'EILSEQ', 10000: 'WSABASEERR', 10004: 'WSAEINTR', 10009: 'WSAEBADF', 10013: 'WSAEACCES', 10014: 'WSAEFAULT', 10022: 'WSAEINVAL', 10024: 'WSAEMFILE', 10035: 'WSAEWOULDBLOCK', 10036: 'WSAEINPROGRESS', 10037: 'WSAEALREADY', 10038: 'WSAENOTSOCK', 10039: 'WSAEDESTADDRREQ', 10040: 'WSAEMSGSIZE', 10041: 'WSAEPROTOTYPE', 10042: 'WSAENOPROTOOPT', 10043: 'WSAEPROTONOSUPPORT', 10044: 'WSAESOCKTNOSUPPORT', 10045: 'WSAEOPNOTSUPP', 10046: 'WSAEPFNOSUPPORT', 10047: 'WSAEAFNOSUPPORT', 10048: 'WSAEADDRINUSE', 10049: 'WSAEADDRNOTAVAIL', 10050: 'WSAENETDOWN', 10051: 'WSAENETUNREACH', 10052: 'WSAENETRESET', 10053: 'WSAECONNABORTED', 10054: 'WSAECONNRESET', 10055: 'WSAENOBUFS', 10056: 'WSAEISCONN', 10057: 'WSAENOTCONN', 10058: 'WSAESHUTDOWN', 10059: 'WSAETOOMANYREFS', 10060: 'WSAETIMEDOUT', 10061: 'WSAECONNREFUSED', 10062: 'WSAELOOP', 10063: 'WSAENAMETOOLONG', 10064: 'WSAEHOSTDOWN', 10065: 'WSAEHOSTUNREACH', 10066: 'WSAENOTEMPTY', 10067: 'WSAEPROCLIM', 10068: 'WSAEUSERS', 10069: 'WSAEDQUOT', 10070: 'WSAESTALE', 10071: 'WSAEREMOTE', 10091: 'WSASYSNOTREADY', 10092: 'WSAVERNOTSUPPORTED', 10093: 'WSANOTINITIALISED', 10101: 'WSAEDISCON'}
''' ''' class Solution: def removeDuplicates(self, nums: List[int]) -> int: length = len(nums) if length <= 2: return length left = 0 cur = 0 while cur < length - 1: sums = 1 while cur < length - 1 and nums[cur] == nums[cur + 1]: sums += 1 cur += 1 for i in range(min(sums, 2)): nums[left] = nums[cur] left += 1 cur += 1 if cur == length - 1: nums[left] = nums[cur] left += 1 #nums = nums[:left + 1] return left
""" """ class Solution: def remove_duplicates(self, nums: List[int]) -> int: length = len(nums) if length <= 2: return length left = 0 cur = 0 while cur < length - 1: sums = 1 while cur < length - 1 and nums[cur] == nums[cur + 1]: sums += 1 cur += 1 for i in range(min(sums, 2)): nums[left] = nums[cur] left += 1 cur += 1 if cur == length - 1: nums[left] = nums[cur] left += 1 return left
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ def make_change(money, coins): if money < 0: return 0 elif money == 0: return 1 elif not coins: return 0 else: return make_change(money - coins[-1], coins) + make_change(money, coins[:-1]) coins = [1, 2, 3] money = 4 make_change(money, coins)
def make_change(money, coins): if money < 0: return 0 elif money == 0: return 1 elif not coins: return 0 else: return make_change(money - coins[-1], coins) + make_change(money, coins[:-1]) coins = [1, 2, 3] money = 4 make_change(money, coins)
_notes_dict_array_hz = { 'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0], 'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'D': [9.177, 18.354, 36.708, 73.416, 146.83, 293.66, 587.33, 1174.7, 2349.3, 4698.6, 9397.3], 'Ef': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1], 'D#': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1], 'E': [10.301, 20.602, 41.203, 82.407, 164.81, 329.63, 659.26, 1318.5, 2637.0, 5274.0, 10548.1], 'F': [10.914, 21.827, 43.654, 87.307, 174.61, 349.23, 698.46, 1396.9, 2793.8, 5587.7, 11175.3], 'F#': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8], 'Gf': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8], 'G': [12.25, 24.5, 48.999, 97.999, 196.0, 392.0, 783.99, 1568.0, 3136.0, 6271.9, 12543.9], 'Af': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9], 'G#': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9], 'A': [13.75, 27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0], 'Bf': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6], 'A#': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6], 'B': [15.434, 30.868, 61.735, 123.47, 246.94, 493.88, 987.77, 1975.5, 3951.1, 7902.1] } midi_note_hz = [8.176, 8.662, 9.177, 9.723, 10.301, 10.914, 11.563, 12.25, 12.979, 13.75, 14.568, 15.434, 16.352, 17.324, 18.354, 19.445, 20.602, 21.827, 23.125, 24.5, 25.957, 27.5, 29.135, 30.868, 32.703, 34.648, 36.708, 38.891, 41.203, 43.654, 46.249, 48.999, 51.913, 55.0, 58.27, 61.735, 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.83, 110.0, 116.54, 123.47, 130.81, 138.59, 146.83, 155.56, 164.81, 174.61, 185.0, 196.0, 207.65, 220.0, 233.08, 246.94, 261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.0, 415.3, 440.0, 466.16, 493.88, 523.25, 554.37, 587.33, 622.25, 659.26, 698.46, 739.99, 783.99, 830.61, 880.0, 932.33, 987.77, 1046.5, 1108.7, 1174.7, 1244.5, 1318.5, 1396.9, 1480.0, 1568.0, 1661.2, 1760.0, 1864.7, 1975.5, 2093.0, 2217.5, 2349.3, 2489.0, 2637.0, 2793.8, 2960.0, 3136.0, 3322.4, 3520.0, 3729.3, 3951.1, 4186.0, 4434.9, 4698.6, 4978.0, 5274.0, 5587.7, 5919.9, 6271.9, 6644.9, 7040.0, 7458.6, 7902.1, 8372.0, 8869.8, 9397.3, 9956.1, 10548.1, 11175.3, 11839.8, 12543.9] def note_freq(note, octave): octave_idx = octave + 1 return _notes_dict_array_hz[note][octave_idx]
_notes_dict_array_hz = {'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0], 'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'D': [9.177, 18.354, 36.708, 73.416, 146.83, 293.66, 587.33, 1174.7, 2349.3, 4698.6, 9397.3], 'Ef': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1], 'D#': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1], 'E': [10.301, 20.602, 41.203, 82.407, 164.81, 329.63, 659.26, 1318.5, 2637.0, 5274.0, 10548.1], 'F': [10.914, 21.827, 43.654, 87.307, 174.61, 349.23, 698.46, 1396.9, 2793.8, 5587.7, 11175.3], 'F#': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8], 'Gf': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8], 'G': [12.25, 24.5, 48.999, 97.999, 196.0, 392.0, 783.99, 1568.0, 3136.0, 6271.9, 12543.9], 'Af': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9], 'G#': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9], 'A': [13.75, 27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0], 'Bf': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6], 'A#': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6], 'B': [15.434, 30.868, 61.735, 123.47, 246.94, 493.88, 987.77, 1975.5, 3951.1, 7902.1]} midi_note_hz = [8.176, 8.662, 9.177, 9.723, 10.301, 10.914, 11.563, 12.25, 12.979, 13.75, 14.568, 15.434, 16.352, 17.324, 18.354, 19.445, 20.602, 21.827, 23.125, 24.5, 25.957, 27.5, 29.135, 30.868, 32.703, 34.648, 36.708, 38.891, 41.203, 43.654, 46.249, 48.999, 51.913, 55.0, 58.27, 61.735, 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.83, 110.0, 116.54, 123.47, 130.81, 138.59, 146.83, 155.56, 164.81, 174.61, 185.0, 196.0, 207.65, 220.0, 233.08, 246.94, 261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.0, 415.3, 440.0, 466.16, 493.88, 523.25, 554.37, 587.33, 622.25, 659.26, 698.46, 739.99, 783.99, 830.61, 880.0, 932.33, 987.77, 1046.5, 1108.7, 1174.7, 1244.5, 1318.5, 1396.9, 1480.0, 1568.0, 1661.2, 1760.0, 1864.7, 1975.5, 2093.0, 2217.5, 2349.3, 2489.0, 2637.0, 2793.8, 2960.0, 3136.0, 3322.4, 3520.0, 3729.3, 3951.1, 4186.0, 4434.9, 4698.6, 4978.0, 5274.0, 5587.7, 5919.9, 6271.9, 6644.9, 7040.0, 7458.6, 7902.1, 8372.0, 8869.8, 9397.3, 9956.1, 10548.1, 11175.3, 11839.8, 12543.9] def note_freq(note, octave): octave_idx = octave + 1 return _notes_dict_array_hz[note][octave_idx]
def funct(l1, l2): s = len(set(l1+l2)) return s for t in range(int(input())): n = int(input()) l = input().split() a = {} for i in l: p = i[1:] if p in a: a[p].append(i[0]) else: a[p] = [i[0]] b = list(a.keys()) s = 0 for i in range(len(a)): for j in range(i+1, len(a)): ans = funct(a[b[i]], a[b[j]]) s += (ans-len(a[b[i]]))*(ans-len(a[b[j]])) print(2*s)
def funct(l1, l2): s = len(set(l1 + l2)) return s for t in range(int(input())): n = int(input()) l = input().split() a = {} for i in l: p = i[1:] if p in a: a[p].append(i[0]) else: a[p] = [i[0]] b = list(a.keys()) s = 0 for i in range(len(a)): for j in range(i + 1, len(a)): ans = funct(a[b[i]], a[b[j]]) s += (ans - len(a[b[i]])) * (ans - len(a[b[j]])) print(2 * s)
"""Created by sgoswami on 8/30/17.""" """Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes.""" # 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 upsideDownBinaryTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root or not root.left: return root new_root = self.upsideDownBinaryTree(root.left) root.left.left = root.right root.left.right = root root.left = None root.right = None return new_root
"""Created by sgoswami on 8/30/17.""" 'Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the \nsame parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into \nleft leaf nodes.' class Solution(object): def upside_down_binary_tree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root or not root.left: return root new_root = self.upsideDownBinaryTree(root.left) root.left.left = root.right root.left.right = root root.left = None root.right = None return new_root
# C100--- python classes class Car(object): """ blueprint for car """ def __init__(self, modelInput, colorInput, companyInput, speed_limitInput): self.color = colorInput self.company = companyInput self.speed_limit = speed_limitInput self.model = modelInput def start(self): print("started") def stop(self): print("stopped") def accelarate(self): print("accelarating...") "accelarator functionality here" def change_gear(self, gear_type): print("gear changed") " gear related functionality here" audi = Car("A6", "red", "audi", 80) print(audi.start())
class Car(object): """ blueprint for car """ def __init__(self, modelInput, colorInput, companyInput, speed_limitInput): self.color = colorInput self.company = companyInput self.speed_limit = speed_limitInput self.model = modelInput def start(self): print('started') def stop(self): print('stopped') def accelarate(self): print('accelarating...') 'accelarator functionality here' def change_gear(self, gear_type): print('gear changed') ' gear related functionality here' audi = car('A6', 'red', 'audi', 80) print(audi.start())
class ConfigSVM: # matrix_size = 1727 # matrix_size = 1219 # matrix_size = 1027 matrix_size = 798 # matrix_size = 3
class Configsvm: matrix_size = 798
print('\033[1;93m-=-\033[m' * 15) print(f'\033[1;31m{"LARGEST AND SMALLEST ON THE LIST":^45}\033[m', ) print('\033[1;93m-=-\033[m' * 15) numbers = list() largest = 0 big_position = list() small_position = list() numbers.append(int(input(f'Type a number for the position {0}: '))) smallest = numbers[0] for i in range(1, 5): numbers.append(int(input(f'Type a number for the position {i}: '))) if numbers[i] > largest: largest = numbers[i] if numbers[i] < smallest: smallest = numbers[i] print('-=-' * 15) print('You entered the valors: ', end='') for n in numbers: print(n, end=' ') for i in range(0, 5): if numbers[i] == largest: big_position.append(i) if numbers[i] == smallest: small_position.append(i) print(f'\nThe largest number entered was: {largest} in the positions ', end='') for n in big_position: print(f'{n}... ', end='') print(f'\nThe smallest number entered was: {smallest} in the positions ', end='') for n in small_position: print(f'{n}... ', end='')
print('\x1b[1;93m-=-\x1b[m' * 15) print(f"\x1b[1;31m{'LARGEST AND SMALLEST ON THE LIST':^45}\x1b[m") print('\x1b[1;93m-=-\x1b[m' * 15) numbers = list() largest = 0 big_position = list() small_position = list() numbers.append(int(input(f'Type a number for the position {0}: '))) smallest = numbers[0] for i in range(1, 5): numbers.append(int(input(f'Type a number for the position {i}: '))) if numbers[i] > largest: largest = numbers[i] if numbers[i] < smallest: smallest = numbers[i] print('-=-' * 15) print('You entered the valors: ', end='') for n in numbers: print(n, end=' ') for i in range(0, 5): if numbers[i] == largest: big_position.append(i) if numbers[i] == smallest: small_position.append(i) print(f'\nThe largest number entered was: {largest} in the positions ', end='') for n in big_position: print(f'{n}... ', end='') print(f'\nThe smallest number entered was: {smallest} in the positions ', end='') for n in small_position: print(f'{n}... ', end='')
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. { 'includes': [ '../build/common.gypi', ], 'conditions': [ ['OS=="ios"', { 'targets': [ { 'target_name': 'rtc_api_objc', 'type': 'static_library', 'dependencies': [ '<(webrtc_root)/base/base.gyp:rtc_base_objc', ], 'sources': [ 'objc/RTCIceServer+Private.h', 'objc/RTCIceServer.h', 'objc/RTCIceServer.mm', ], 'xcode_settings': { 'CLANG_ENABLE_OBJC_ARC': 'YES', 'CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS': 'YES', 'GCC_PREFIX_HEADER': 'objc/WebRTC-Prefix.pch', }, } ], }], # OS=="ios" ], }
{'includes': ['../build/common.gypi'], 'conditions': [['OS=="ios"', {'targets': [{'target_name': 'rtc_api_objc', 'type': 'static_library', 'dependencies': ['<(webrtc_root)/base/base.gyp:rtc_base_objc'], 'sources': ['objc/RTCIceServer+Private.h', 'objc/RTCIceServer.h', 'objc/RTCIceServer.mm'], 'xcode_settings': {'CLANG_ENABLE_OBJC_ARC': 'YES', 'CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS': 'YES', 'GCC_PREFIX_HEADER': 'objc/WebRTC-Prefix.pch'}}]}]]}
getObject = { 'primaryRouter': { 'datacenter': {'id': 1234, 'longName': 'TestDC'}, 'fullyQualifiedDomainName': 'fcr01.TestDC' }, 'id': 1234, 'vlanNumber': 4444, 'firewallInterfaces': None }
get_object = {'primaryRouter': {'datacenter': {'id': 1234, 'longName': 'TestDC'}, 'fullyQualifiedDomainName': 'fcr01.TestDC'}, 'id': 1234, 'vlanNumber': 4444, 'firewallInterfaces': None}
"""Library package info""" author = "linuxdaemon" version_info = (0, 3, 0) version = ".".join(map(str, version_info)) __all__ = ("author", "version_info", "version")
"""Library package info""" author = 'linuxdaemon' version_info = (0, 3, 0) version = '.'.join(map(str, version_info)) __all__ = ('author', 'version_info', 'version')
"""The module has following classes: - Room""" class Room(object): '''Takes name and description of the object and initializes paths.\nProvides methods \n\t go(direction) and,\n\t add_paths(paths)''' def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): return self.paths.update(paths)
"""The module has following classes: - Room""" class Room(object): """Takes name and description of the object and initializes paths. Provides methods go(direction) and, add_paths(paths)""" def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): return self.paths.update(paths)
class Car: def wheels(self): print('Car.wheels') return 4 class Bike(Car): def wheels(self): return 2 class Truck(Car): def wheels(self): print('Truck.wheels: start') super().wheels() print('Truck.wheels: end') return 6 car = Bike() print(car.wheels()) # 2 truck = Truck() print(truck.wheels()) # 6
class Car: def wheels(self): print('Car.wheels') return 4 class Bike(Car): def wheels(self): return 2 class Truck(Car): def wheels(self): print('Truck.wheels: start') super().wheels() print('Truck.wheels: end') return 6 car = bike() print(car.wheels()) truck = truck() print(truck.wheels())
class NodeEndpoint: protocol = '' host = '' port = '' @staticmethod def from_parameters(protocol, host, port): endpoint = NodeEndpoint() endpoint.protocol = protocol endpoint.host = host endpoint.port = port return endpoint @staticmethod def from_json(endpoint_json): return NodeEndpoint.from_parameters( endpoint_json['protocol'], endpoint_json['host'], endpoint_json['port']) def url(self): return '{0}://{1}:{2}/'.format(self.protocol, self.host, self.port)
class Nodeendpoint: protocol = '' host = '' port = '' @staticmethod def from_parameters(protocol, host, port): endpoint = node_endpoint() endpoint.protocol = protocol endpoint.host = host endpoint.port = port return endpoint @staticmethod def from_json(endpoint_json): return NodeEndpoint.from_parameters(endpoint_json['protocol'], endpoint_json['host'], endpoint_json['port']) def url(self): return '{0}://{1}:{2}/'.format(self.protocol, self.host, self.port)
class SchemaConstructionException(Exception): def __init__(self, claz): self.cls = claz class SchemaParseException(Exception): def __init__(self, errors): self.errors = errors class ParseError(object): def __init__(self, path, inner): self.path = path self.inner = inner class CheckFailed(object): def __init__(self, check_fn, failed_value): self.check_fn = check_fn self.failed_value = failed_value
class Schemaconstructionexception(Exception): def __init__(self, claz): self.cls = claz class Schemaparseexception(Exception): def __init__(self, errors): self.errors = errors class Parseerror(object): def __init__(self, path, inner): self.path = path self.inner = inner class Checkfailed(object): def __init__(self, check_fn, failed_value): self.check_fn = check_fn self.failed_value = failed_value
""" Created on Sun Feb 15 01:52:42 2015 @author: Enes Kemal Ergin The Field: Introduction to Complex Numbers (Video 2) """ # complex number = (real part) + (imaginary part) * i ## Pyhton use j for doing complex 1j 1+3j (1+3j) + (10+20j) x = 1+3j (x-1)**2 # (-9+0j) -> -9 x.real # 1.0 x.imag # 3.0 ## Write a procedure solve(a,b,c) to solve ax + b = c def solve(a,b,c): return (c-b)/a solve(10, 5, 30) # We can use the same procedure to calculate complex numbers as well. solve(10+5j, 5, 20) # (1.2-0.6j) # Same procedure works for complex numbers.
""" Created on Sun Feb 15 01:52:42 2015 @author: Enes Kemal Ergin The Field: Introduction to Complex Numbers (Video 2) """ 1j 1 + 3j 1 + 3j + (10 + 20j) x = 1 + 3j (x - 1) ** 2 x.real x.imag def solve(a, b, c): return (c - b) / a solve(10, 5, 30) solve(10 + 5j, 5, 20)
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: modulo = 10 ** 9 + 7 # build tuples of (efficiency, speed) candidates = zip(efficiency, speed) # sort the candidates by their efficiencies candidates = sorted(candidates, key=lambda t:t[0], reverse=True) speed_heap = [] speed_sum, perf = 0, 0 for curr_efficiency, curr_speed in candidates: # maintain a heap for the fastest (k-1) speeds if len(speed_heap) > k-1: speed_sum -= heapq.heappop(speed_heap) heapq.heappush(speed_heap, curr_speed) # calculate the maximum performance with the current member as the least efficient one in the team speed_sum += curr_speed perf = max(perf, speed_sum * curr_efficiency) return perf % modulo
class Solution: def max_performance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: modulo = 10 ** 9 + 7 candidates = zip(efficiency, speed) candidates = sorted(candidates, key=lambda t: t[0], reverse=True) speed_heap = [] (speed_sum, perf) = (0, 0) for (curr_efficiency, curr_speed) in candidates: if len(speed_heap) > k - 1: speed_sum -= heapq.heappop(speed_heap) heapq.heappush(speed_heap, curr_speed) speed_sum += curr_speed perf = max(perf, speed_sum * curr_efficiency) return perf % modulo
"""Helper functions used in various modules.""" def deserialize_thing_id(thing_id): """Convert base36 reddit 'thing id' string into int tuple.""" return tuple(int(x, base=36) for x in thing_id[1:].split("_")) def update_sr_tables(cursor, subreddit): """Update tables of subreddits and subreddit-moderator relationships.""" _, subreddit_id = deserialize_thing_id(subreddit.fullname) # Add subreddits and update subscriber counts cursor.execute( "INSERT OR IGNORE INTO subreddits (id, display_name) VALUES(?,?)", (subreddit_id, str(subreddit)), ) cursor.execute( "UPDATE subreddits SET subscribers = ? " "WHERE id = ?", (subreddit.subscribers, subreddit_id), ) # Refresh listing of subreddits' moderators cursor.execute( "DELETE FROM subreddit_moderator " "WHERE subreddit_id = ?", (subreddit_id,), ) for moderator in subreddit.moderator(): cursor.execute( "INSERT OR IGNORE INTO users (username) " "VALUES(?)", (str(moderator),), ) cursor.execute( "SELECT id FROM users WHERE username = ?", (str(moderator),) ) moderator_id = cursor.fetchone()[0] cursor.execute( "INSERT OR IGNORE INTO subreddit_moderator " "(subreddit_id, moderator_id) VALUES(?,?)", (subreddit_id, moderator_id), )
"""Helper functions used in various modules.""" def deserialize_thing_id(thing_id): """Convert base36 reddit 'thing id' string into int tuple.""" return tuple((int(x, base=36) for x in thing_id[1:].split('_'))) def update_sr_tables(cursor, subreddit): """Update tables of subreddits and subreddit-moderator relationships.""" (_, subreddit_id) = deserialize_thing_id(subreddit.fullname) cursor.execute('INSERT OR IGNORE INTO subreddits (id, display_name) VALUES(?,?)', (subreddit_id, str(subreddit))) cursor.execute('UPDATE subreddits SET subscribers = ? WHERE id = ?', (subreddit.subscribers, subreddit_id)) cursor.execute('DELETE FROM subreddit_moderator WHERE subreddit_id = ?', (subreddit_id,)) for moderator in subreddit.moderator(): cursor.execute('INSERT OR IGNORE INTO users (username) VALUES(?)', (str(moderator),)) cursor.execute('SELECT id FROM users WHERE username = ?', (str(moderator),)) moderator_id = cursor.fetchone()[0] cursor.execute('INSERT OR IGNORE INTO subreddit_moderator (subreddit_id, moderator_id) VALUES(?,?)', (subreddit_id, moderator_id))
"""Test the link to the help docco.""" def test_help_redirect_to_rtd(webapp, f_httpretty): """Test we redirect to read the docs.""" f_httpretty.HTTPretty.allow_net_connect = False response = webapp.get('/help') assert response.status_code == 302 assert response.headers['location'] == 'https://dnstwister.readthedocs.org/en/stable/web.html'
"""Test the link to the help docco.""" def test_help_redirect_to_rtd(webapp, f_httpretty): """Test we redirect to read the docs.""" f_httpretty.HTTPretty.allow_net_connect = False response = webapp.get('/help') assert response.status_code == 302 assert response.headers['location'] == 'https://dnstwister.readthedocs.org/en/stable/web.html'
# Minimum Size Subarray Sum class Solution: def minSubArrayLen(self, target, nums): length = len(nums) Invalid = length + 1 left, right = 0, 0 added = nums[left] if added >= target: return 1 ans = Invalid while True: if left + 1 <= right and added - nums[left] >= target: added -= nums[left] left += 1 ans = min(ans, right - left + 1) continue if right < length - 1: added += nums[right + 1] right += 1 if added >= target: ans = min(ans, right - left + 1) continue # cannot reduct left side, cannot expand to right. # break here break return 0 if ans == Invalid else ans if __name__ == "__main__": sol = Solution() target = 7 nums = [2,3,1,2,4,3] target = 4 nums = [1,4,4] target = 11 nums = [1,1,1,1,1,1,1,1] target = 11 nums = [12] target = 15 nums = [1,2,3,4,5] print(sol.minSubArrayLen(target, nums))
class Solution: def min_sub_array_len(self, target, nums): length = len(nums) invalid = length + 1 (left, right) = (0, 0) added = nums[left] if added >= target: return 1 ans = Invalid while True: if left + 1 <= right and added - nums[left] >= target: added -= nums[left] left += 1 ans = min(ans, right - left + 1) continue if right < length - 1: added += nums[right + 1] right += 1 if added >= target: ans = min(ans, right - left + 1) continue break return 0 if ans == Invalid else ans if __name__ == '__main__': sol = solution() target = 7 nums = [2, 3, 1, 2, 4, 3] target = 4 nums = [1, 4, 4] target = 11 nums = [1, 1, 1, 1, 1, 1, 1, 1] target = 11 nums = [12] target = 15 nums = [1, 2, 3, 4, 5] print(sol.minSubArrayLen(target, nums))
# http://codingbat.com/prob/p165321 def near_ten(num): return (num % 10 <= 2) or (num % 10 >= 8)
def near_ten(num): return num % 10 <= 2 or num % 10 >= 8
class WorkerNode(object): def __init__(self, ip, k8s_name, k8s_is_ready): self.ip = ip self.k8s_name = k8s_name self.k8s_is_ready = k8s_is_ready self.k8s_pod_num = 0 self.vc = None self.to_turn_on = False self.to_turn_off = False class Pod(object): def __init__(self, vc, host_ip, pending): self.vc = vc self.host_ip = host_ip self.pending = pending class VirtualCluster(object): def __init__(self, name, is_full, is_guaranteed): self.name = name self.is_full = is_full self.is_guaranteed = is_guaranteed
class Workernode(object): def __init__(self, ip, k8s_name, k8s_is_ready): self.ip = ip self.k8s_name = k8s_name self.k8s_is_ready = k8s_is_ready self.k8s_pod_num = 0 self.vc = None self.to_turn_on = False self.to_turn_off = False class Pod(object): def __init__(self, vc, host_ip, pending): self.vc = vc self.host_ip = host_ip self.pending = pending class Virtualcluster(object): def __init__(self, name, is_full, is_guaranteed): self.name = name self.is_full = is_full self.is_guaranteed = is_guaranteed
class Solution: def countAndSay(self, n): numb = 1 w = 1 while n > 1: w = Solution.CountSay(numb) numb = w n -= 1 return str(w) def CountSay(no): tnumb = str(no) x = tnumb[0] count = 1 strr = "" for i in range(1, len(tnumb) + 1): if i == len(tnumb): strr += str(count) + str(x) break if tnumb[i] == x: count += 1 else: strr += str(count) + str(x) x = tnumb[i] count = 1 return int(strr)
class Solution: def count_and_say(self, n): numb = 1 w = 1 while n > 1: w = Solution.CountSay(numb) numb = w n -= 1 return str(w) def count_say(no): tnumb = str(no) x = tnumb[0] count = 1 strr = '' for i in range(1, len(tnumb) + 1): if i == len(tnumb): strr += str(count) + str(x) break if tnumb[i] == x: count += 1 else: strr += str(count) + str(x) x = tnumb[i] count = 1 return int(strr)
# domoticz configuration DOMOTICZ_SERVER_IP = "xxx.xxx.x.xxx" DOMOTICZ_SERVER_PORT = "xxxx" DOMOTICZ_USERNAME = "" DOMOTICZ_PASSWORD = "" # sensor dictionary to add own sensors # if you don't want to use the raw voltage option, just write -1 in the VOLTAGE_IDX value field sensors = { 1: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 1, "VOLTAGE_IDX": -1, "UPDATED": False}, 2: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 2, "VOLTAGE_IDX": -1, "UPDATED": False}, 3: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 3, "VOLTAGE_IDX": -1, "UPDATED": False}} # other configuration TEMPERATURE_PREC = 2 # Logfile configuration LOG_FILE_NAME = "loginfo.log" LOG_FILE_SIZE = 16384 # file size in bytes
domoticz_server_ip = 'xxx.xxx.x.xxx' domoticz_server_port = 'xxxx' domoticz_username = '' domoticz_password = '' sensors = {1: {'MAC': 'xx:xx:xx:xx:xx:xx', 'TH_IDX': 1, 'VOLTAGE_IDX': -1, 'UPDATED': False}, 2: {'MAC': 'xx:xx:xx:xx:xx:xx', 'TH_IDX': 2, 'VOLTAGE_IDX': -1, 'UPDATED': False}, 3: {'MAC': 'xx:xx:xx:xx:xx:xx', 'TH_IDX': 3, 'VOLTAGE_IDX': -1, 'UPDATED': False}} temperature_prec = 2 log_file_name = 'loginfo.log' log_file_size = 16384
del_items(0x8009E2A0) SetType(0x8009E2A0, "char StrDate[12]") del_items(0x8009E2AC) SetType(0x8009E2AC, "char StrTime[9]") del_items(0x8009E2B8) SetType(0x8009E2B8, "char *Words[117]") del_items(0x8009E48C) SetType(0x8009E48C, "struct MONTH_DAYS MonDays[12]")
del_items(2148131488) set_type(2148131488, 'char StrDate[12]') del_items(2148131500) set_type(2148131500, 'char StrTime[9]') del_items(2148131512) set_type(2148131512, 'char *Words[117]') del_items(2148131980) set_type(2148131980, 'struct MONTH_DAYS MonDays[12]')
class FunctionLink: def __init__(self, linked_function): self.__linked_function = linked_function @property def linked_function(self): return self.__linked_function
class Functionlink: def __init__(self, linked_function): self.__linked_function = linked_function @property def linked_function(self): return self.__linked_function
workers = 2 timeout = 120 reload = True limit_request_field_size = 0 limit_request_line = 0
workers = 2 timeout = 120 reload = True limit_request_field_size = 0 limit_request_line = 0
GITHUB_TOKENS = ['GH_TOKEN'] GITHUB_URL_FILE = 'rawGitUrls.txt' GITHUB_API_URL = 'https://api.github.com/search/code?q=' GITHUB_API_COMMIT_URL = 'https://api.github.com/repos/' GITHUB_SEARCH_PARAMS = '&sort=indexed&o=desc' GITHUB_BASE_URL = 'https://github.com' GITHUB_MAX_RETRY = 10 XDISCORD_WEBHOOKURL = 'https://discordapp.com/api/webhooks/7XXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXX' XSLACK_WEBHOOKURL = 'https://hooks.slack.com/services/TXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXX' TELEGRAM_CONFIG = { "token": "1437557225:AAHpOqwOZ4Xlap", "chat_id": "Code" }
github_tokens = ['GH_TOKEN'] github_url_file = 'rawGitUrls.txt' github_api_url = 'https://api.github.com/search/code?q=' github_api_commit_url = 'https://api.github.com/repos/' github_search_params = '&sort=indexed&o=desc' github_base_url = 'https://github.com' github_max_retry = 10 xdiscord_webhookurl = 'https://discordapp.com/api/webhooks/7XXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXX' xslack_webhookurl = 'https://hooks.slack.com/services/TXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXX' telegram_config = {'token': '1437557225:AAHpOqwOZ4Xlap', 'chat_id': 'Code'}
class QuickSort(object): "In Place Quick Sort" def __init__(self, arr): self.arr = arr def sort(self, left_i, right_i): if right_i - left_i < 1: return pivot_i = self.partition(left_i, right_i) self.sort(left_i, pivot_i - 1) self.sort(pivot_i + 1, right_i) def partition(self, left_i, right_i): pivot_i = right_i lesser_i = left_i for i in range(left_i, right_i): if arr[i] < arr[pivot_i]: self.swap(i, lesser_i) lesser_i += 1 self.swap(pivot_i, lesser_i) self.print_arr() return lesser_i def swap(self, index_1, index_2): arr[index_1], arr[index_2] = arr[index_2], arr[index_1] def print_arr(self): print(" ".join(list(map(str, arr)))) n = int(input().strip()) arr = list(map(int, input().strip().split(" "))) quicksort = QuickSort(arr) quicksort.sort(0, len(arr) - 1)
class Quicksort(object): """In Place Quick Sort""" def __init__(self, arr): self.arr = arr def sort(self, left_i, right_i): if right_i - left_i < 1: return pivot_i = self.partition(left_i, right_i) self.sort(left_i, pivot_i - 1) self.sort(pivot_i + 1, right_i) def partition(self, left_i, right_i): pivot_i = right_i lesser_i = left_i for i in range(left_i, right_i): if arr[i] < arr[pivot_i]: self.swap(i, lesser_i) lesser_i += 1 self.swap(pivot_i, lesser_i) self.print_arr() return lesser_i def swap(self, index_1, index_2): (arr[index_1], arr[index_2]) = (arr[index_2], arr[index_1]) def print_arr(self): print(' '.join(list(map(str, arr)))) n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) quicksort = quick_sort(arr) quicksort.sort(0, len(arr) - 1)
def validate(instruction) -> bool: """Validates an instruction Parameters ---------- instruction : BaseCommand The instruction to validate Returns ------- bool Valid or not valid """ switch = { # R Type instructions "add": validate_3_rtype, "addu": validate_3_rtype, "and": validate_3_rtype, "nor": validate_3_rtype, "or": validate_3_rtype, "sll": validate_2_itype, "sllv": validate_3_rtype, "slt": validate_3_rtype, "sltu": validate_3_rtype, "sra": validate_2_itype, "srav": validate_3_rtype, "srl": validate_2_itype, "srlv": validate_3_rtype, "sub": validate_3_rtype, "subu": validate_3_rtype, "xor": validate_3_rtype, "div": validate_2_rtype, "divu": validate_2_rtype, "jalr": validate_jalr, "mul": validate_2_rtype, "mult": validate_2_rtype, "madd": validate_2_rtype, "maddu": validate_2_rtype, "msub": validate_2_rtype, "msubu": validate_2_rtype, "move": validate_2_rtype, "not": validate_2_rtype, "teq": validate_2_rtype, "tge": validate_2_rtype, "tgeu": validate_2_rtype, "tlt": validate_2_rtype, "tltu": validate_2_rtype, "tne": validate_2_rtype, "jr": validate_1_rtype, "mfhi": validate_1_rtype, "mflo": validate_1_rtype, "mthi": validate_1_rtype, "mtlo": validate_1_rtype, "syscall": validate_0_rtype, "eret": validate_0_rtype, "nop": validate_0_rtype, # I Type instructions "addi": validate_2_itype, "addiu": validate_2_itype, "andi": validate_2_itype, "beq": validate_2_itype, "bne": validate_2_itype, "ori": validate_2_itype, "slti": validate_2_itype, "sltiu": validate_2_itype, "xori": validate_2_itype, "li": validate_1_itype, "la": validate_optional_2_itype, "bgezal": validate_1_itype, "beqz": validate_1_itype, "bgez": validate_1_itype, "bgtz": validate_1_itype, "blez": validate_1_itype, "bltz": validate_1_itype, "bnez": validate_1_itype, "lui": validate_1_itype, "tgei": validate_1_itype, "teqi": validate_1_itype, "tgeiu": validate_1_itype, "tlti": validate_1_itype, "tltiu": validate_1_itype, "tnei": validate_1_itype, "bge": validate_optional_2_itype, "sw": validate_optional_2_itype, "sc": validate_optional_2_itype, "swl": validate_optional_2_itype, "lw": validate_optional_2_itype, "ll": validate_optional_2_itype, "lb": validate_optional_2_itype, "lbu": validate_optional_2_itype, "lh": validate_optional_2_itype, "lhu": validate_optional_2_itype, "sb": validate_optional_2_itype, "sh": validate_optional_2_itype, # J-Type Instructions "j": validate_jtype, "jal": validate_jtype, } try: func = switch[instruction.command] res = func(instruction) except KeyError: res = True print(f"Validation for {instruction.command} not implemented") except: res = False return res list_of_registers = ( "$zero", "$v0", "$v1", "$a0", "$a1", "$a2", "$a3", "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", "$s0", "$s1", "$s2", "$s3", "$s4", "$s5", "$s6", "$s7", "$t8", "$t9", "$sp", "$ra", ) def validate_jalr(inst): return validate_1_rtype(inst) or validate_2_rtype(inst) def validate_3_rtype(instruction) -> bool: """Validates R-Type instructions with 3 registers Parameters ---------- instruction : R-Type R-types with 3 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is not None check3 = rt is not None if ( rd.name in list_of_registers and rs.name in list_of_registers and rt.name in list_of_registers ): return check1 and check2 and check3 return False def validate_2_rtype(instruction) -> bool: """Validates R-Type instructions with 2 registers Parameters ---------- instruction : R-Type R-types with 2 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is not None check3 = rt is None if rd.name in list_of_registers and rs.name in list_of_registers: return check1 and check2 and check3 return False def validate_1_rtype(instruction) -> bool: """Validates R-Type instructions with 1 registers Parameters ---------- instruction : R-Type R-types with 1 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is None check3 = rt is None if rd.name in list_of_registers: return check1 and check2 and check3 return False def validate_0_rtype(instruction) -> bool: """Validates R-Type instructions with 0 registers Parameters ---------- instruction : R-Type R-types with 0 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is None check2 = rs is None check3 = rt is None return check1 and check2 and check3 def validate_2_itype(instruction) -> bool: """Validates I-Type instructions with 2 registers Parameters ---------- instruction : I-Type I-types with 2 registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register source = instruction.source_register immediate = instruction.immediate check1 = destination is not None check2 = source is not None check3 = immediate is not None if instruction.command in ("beq", "bne", "sll", "srl", "sra") and isinstance( immediate._value, str ): if destination.name in list_of_registers and source.name in list_of_registers: return check1 and check2 and check3 elif ( destination.name in list_of_registers and isinstance(immediate(), int) and source.name in list_of_registers ): return check1 and check2 and check3 return False def validate_optional_2_itype(instruction) -> bool: """Validates I-Type instructions with optional 2 registers Parameters ---------- instruction : I-Type I-types with 2 optional registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register target = instruction.target_register source = instruction.source_register immediate = instruction.immediate check1 = destination is not None check2 = immediate is not None check3 = target is None if destination.name in list_of_registers: if source is not None and source.name in list_of_registers: return check1 and check2 and check3 elif source is None: return check1 and check2 and check3 return False def validate_1_itype(instruction) -> bool: """Validates I-Type instructions with 1 registers Parameters ---------- instruction : I-Type I-types with 1 registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register target = instruction.target_register immediate = instruction.immediate source = instruction.source_register check1 = destination is not None check2 = target is None check3 = immediate is not None check4 = source is None if destination.name in list_of_registers: return check1 and check2 and check3 and check4 return False def validate_jtype(instruction) -> bool: """Validates J-Type instructions Parameters ---------- instruction : J-Type Returns ------- bool [Syntax correct or not] """ address = instruction.address check = address is not None return check
def validate(instruction) -> bool: """Validates an instruction Parameters ---------- instruction : BaseCommand The instruction to validate Returns ------- bool Valid or not valid """ switch = {'add': validate_3_rtype, 'addu': validate_3_rtype, 'and': validate_3_rtype, 'nor': validate_3_rtype, 'or': validate_3_rtype, 'sll': validate_2_itype, 'sllv': validate_3_rtype, 'slt': validate_3_rtype, 'sltu': validate_3_rtype, 'sra': validate_2_itype, 'srav': validate_3_rtype, 'srl': validate_2_itype, 'srlv': validate_3_rtype, 'sub': validate_3_rtype, 'subu': validate_3_rtype, 'xor': validate_3_rtype, 'div': validate_2_rtype, 'divu': validate_2_rtype, 'jalr': validate_jalr, 'mul': validate_2_rtype, 'mult': validate_2_rtype, 'madd': validate_2_rtype, 'maddu': validate_2_rtype, 'msub': validate_2_rtype, 'msubu': validate_2_rtype, 'move': validate_2_rtype, 'not': validate_2_rtype, 'teq': validate_2_rtype, 'tge': validate_2_rtype, 'tgeu': validate_2_rtype, 'tlt': validate_2_rtype, 'tltu': validate_2_rtype, 'tne': validate_2_rtype, 'jr': validate_1_rtype, 'mfhi': validate_1_rtype, 'mflo': validate_1_rtype, 'mthi': validate_1_rtype, 'mtlo': validate_1_rtype, 'syscall': validate_0_rtype, 'eret': validate_0_rtype, 'nop': validate_0_rtype, 'addi': validate_2_itype, 'addiu': validate_2_itype, 'andi': validate_2_itype, 'beq': validate_2_itype, 'bne': validate_2_itype, 'ori': validate_2_itype, 'slti': validate_2_itype, 'sltiu': validate_2_itype, 'xori': validate_2_itype, 'li': validate_1_itype, 'la': validate_optional_2_itype, 'bgezal': validate_1_itype, 'beqz': validate_1_itype, 'bgez': validate_1_itype, 'bgtz': validate_1_itype, 'blez': validate_1_itype, 'bltz': validate_1_itype, 'bnez': validate_1_itype, 'lui': validate_1_itype, 'tgei': validate_1_itype, 'teqi': validate_1_itype, 'tgeiu': validate_1_itype, 'tlti': validate_1_itype, 'tltiu': validate_1_itype, 'tnei': validate_1_itype, 'bge': validate_optional_2_itype, 'sw': validate_optional_2_itype, 'sc': validate_optional_2_itype, 'swl': validate_optional_2_itype, 'lw': validate_optional_2_itype, 'll': validate_optional_2_itype, 'lb': validate_optional_2_itype, 'lbu': validate_optional_2_itype, 'lh': validate_optional_2_itype, 'lhu': validate_optional_2_itype, 'sb': validate_optional_2_itype, 'sh': validate_optional_2_itype, 'j': validate_jtype, 'jal': validate_jtype} try: func = switch[instruction.command] res = func(instruction) except KeyError: res = True print(f'Validation for {instruction.command} not implemented') except: res = False return res list_of_registers = ('$zero', '$v0', '$v1', '$a0', '$a1', '$a2', '$a3', '$t0', '$t1', '$t2', '$t3', '$t4', '$t5', '$t6', '$t7', '$s0', '$s1', '$s2', '$s3', '$s4', '$s5', '$s6', '$s7', '$t8', '$t9', '$sp', '$ra') def validate_jalr(inst): return validate_1_rtype(inst) or validate_2_rtype(inst) def validate_3_rtype(instruction) -> bool: """Validates R-Type instructions with 3 registers Parameters ---------- instruction : R-Type R-types with 3 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is not None check3 = rt is not None if rd.name in list_of_registers and rs.name in list_of_registers and (rt.name in list_of_registers): return check1 and check2 and check3 return False def validate_2_rtype(instruction) -> bool: """Validates R-Type instructions with 2 registers Parameters ---------- instruction : R-Type R-types with 2 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is not None check3 = rt is None if rd.name in list_of_registers and rs.name in list_of_registers: return check1 and check2 and check3 return False def validate_1_rtype(instruction) -> bool: """Validates R-Type instructions with 1 registers Parameters ---------- instruction : R-Type R-types with 1 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is not None check2 = rs is None check3 = rt is None if rd.name in list_of_registers: return check1 and check2 and check3 return False def validate_0_rtype(instruction) -> bool: """Validates R-Type instructions with 0 registers Parameters ---------- instruction : R-Type R-types with 0 registers Returns ------- bool [Syntax correct or not] """ rd = instruction.destination_register rs = instruction.source_register rt = instruction.target_register check1 = rd is None check2 = rs is None check3 = rt is None return check1 and check2 and check3 def validate_2_itype(instruction) -> bool: """Validates I-Type instructions with 2 registers Parameters ---------- instruction : I-Type I-types with 2 registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register source = instruction.source_register immediate = instruction.immediate check1 = destination is not None check2 = source is not None check3 = immediate is not None if instruction.command in ('beq', 'bne', 'sll', 'srl', 'sra') and isinstance(immediate._value, str): if destination.name in list_of_registers and source.name in list_of_registers: return check1 and check2 and check3 elif destination.name in list_of_registers and isinstance(immediate(), int) and (source.name in list_of_registers): return check1 and check2 and check3 return False def validate_optional_2_itype(instruction) -> bool: """Validates I-Type instructions with optional 2 registers Parameters ---------- instruction : I-Type I-types with 2 optional registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register target = instruction.target_register source = instruction.source_register immediate = instruction.immediate check1 = destination is not None check2 = immediate is not None check3 = target is None if destination.name in list_of_registers: if source is not None and source.name in list_of_registers: return check1 and check2 and check3 elif source is None: return check1 and check2 and check3 return False def validate_1_itype(instruction) -> bool: """Validates I-Type instructions with 1 registers Parameters ---------- instruction : I-Type I-types with 1 registers Returns ------- bool [Syntax correct or not] """ destination = instruction.destination_register target = instruction.target_register immediate = instruction.immediate source = instruction.source_register check1 = destination is not None check2 = target is None check3 = immediate is not None check4 = source is None if destination.name in list_of_registers: return check1 and check2 and check3 and check4 return False def validate_jtype(instruction) -> bool: """Validates J-Type instructions Parameters ---------- instruction : J-Type Returns ------- bool [Syntax correct or not] """ address = instruction.address check = address is not None return check
a = [] for i in range(100): a.append(i) if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")
a = [] for i in range(100): a.append(i) if (n := len(a)) > 10: print(f'List is too long ({n} elements, expected <= 10)')
# model initial conditions x = -1 y = 0 z = 0.5 t = 0 # model constants _alpha = 0.3 gamma = 0.01 # gradients palette_relaxing_red = [color(180, 15, 48), color(255, 251, 213)] palette_shahabi = [color(104, 250, 0), color(166, 1, 116)] palette_flare = [color(245, 174, 25), color(241, 40, 16)] palette_rose_colored_lenses = [color(100, 112, 163), color(232, 203, 191)] palette_mean_fruit = [color(247, 193, 158), color(219, 138, 222)] theta = 0 running = True points = [] frame_count = 0 scale_factor = 20.0 scale_factor_step = 0 initial_scale_factor = 20.0 final_scale_factor = 20.0 full_scale_time = 8.5 # in seconds movie_length = 50 # in seconds def setup(): global scale_factor_step size(1200, 1200, P3D) ellipseMode(RADIUS) background(255) smooth() rescaling_frames = (movie_length - full_scale_time)*60 rescaling_fps_frequency = (rescaling_frames * final_scale_factor)/initial_scale_factor scale_factor_step = 1/rescaling_fps_frequency def eval_stroke_color(value,max_value,palette): current_color = lerpColor(palette[1], palette[0], float(value)/max_value) stroke(current_color) #noFill() fill(current_color) def draw(): global x,y,z,t,points,theta,frame_count,scale_factor strokeWeight(1) background(255) #camera positioning camera(40,40,200, 0,0,0, 0.0,1.0,0.0) # incremental resizing of the scene (fading) if frame_count < 60*full_scale_time: scale(initial_scale_factor) else: print("Scale factor: " + str(scale_factor)) print(scale_factor_step) scale_factor -= scale_factor_step scale(scale_factor) # differential equations model dt = 0.02 dx = (y * (z - 1 + x**2) + gamma * x)*dt dy = (x * (3 * z + 1 - x**2) + gamma * y)*dt dz = (-2 * z * (_alpha + x * y))*dt # increment derivatives x += dx y += dy z += dz t += dt p = PVector(x,y,z) points.append(p) theta+=0.05 rotateX(theta/5) rotateY(theta/2) #rotateZ(theta/3) beginShape() for p in points: strokeWeight(max(p.z * 100, 1.0)) eval_stroke_color(p.z * 100,50,palette_flare) vertex(p.x, p.y, p.z) endShape() saveFrame("movie_2/rab_fabri_####.png") frame_count+=1 print(frame_count) if frame_count >= movie_length*60: noLoop() def keyPressed(): global running save("lorentz" + str(random(1000)) + ".png") if running: noLoop() running = False else: loop() running = True print("Saved")
x = -1 y = 0 z = 0.5 t = 0 _alpha = 0.3 gamma = 0.01 palette_relaxing_red = [color(180, 15, 48), color(255, 251, 213)] palette_shahabi = [color(104, 250, 0), color(166, 1, 116)] palette_flare = [color(245, 174, 25), color(241, 40, 16)] palette_rose_colored_lenses = [color(100, 112, 163), color(232, 203, 191)] palette_mean_fruit = [color(247, 193, 158), color(219, 138, 222)] theta = 0 running = True points = [] frame_count = 0 scale_factor = 20.0 scale_factor_step = 0 initial_scale_factor = 20.0 final_scale_factor = 20.0 full_scale_time = 8.5 movie_length = 50 def setup(): global scale_factor_step size(1200, 1200, P3D) ellipse_mode(RADIUS) background(255) smooth() rescaling_frames = (movie_length - full_scale_time) * 60 rescaling_fps_frequency = rescaling_frames * final_scale_factor / initial_scale_factor scale_factor_step = 1 / rescaling_fps_frequency def eval_stroke_color(value, max_value, palette): current_color = lerp_color(palette[1], palette[0], float(value) / max_value) stroke(current_color) fill(current_color) def draw(): global x, y, z, t, points, theta, frame_count, scale_factor stroke_weight(1) background(255) camera(40, 40, 200, 0, 0, 0, 0.0, 1.0, 0.0) if frame_count < 60 * full_scale_time: scale(initial_scale_factor) else: print('Scale factor: ' + str(scale_factor)) print(scale_factor_step) scale_factor -= scale_factor_step scale(scale_factor) dt = 0.02 dx = (y * (z - 1 + x ** 2) + gamma * x) * dt dy = (x * (3 * z + 1 - x ** 2) + gamma * y) * dt dz = -2 * z * (_alpha + x * y) * dt x += dx y += dy z += dz t += dt p = p_vector(x, y, z) points.append(p) theta += 0.05 rotate_x(theta / 5) rotate_y(theta / 2) begin_shape() for p in points: stroke_weight(max(p.z * 100, 1.0)) eval_stroke_color(p.z * 100, 50, palette_flare) vertex(p.x, p.y, p.z) end_shape() save_frame('movie_2/rab_fabri_####.png') frame_count += 1 print(frame_count) if frame_count >= movie_length * 60: no_loop() def key_pressed(): global running save('lorentz' + str(random(1000)) + '.png') if running: no_loop() running = False else: loop() running = True print('Saved')
def get_bid(exchange, symbol, n=1): return 0 def get_bid(exchange, symbol, n=1): return 0
def get_bid(exchange, symbol, n=1): return 0 def get_bid(exchange, symbol, n=1): return 0
def build_tuple_type(*columns): class Tuple(object): __slots__ = columns def __init__(self, d=None, **kw): if d is None: d = kw for k in self.__slots__: setattr(self, k, d.get(k)) def __getitem__(self, k): if k in self.__slots__: return getattr(self, k) def __contains__(self, value): return value in self.__slots__ def __eq__(self, value): for k in self.__slots__: if getattr(self, k) != value[k]: return False return True def __ne__(self, value): for k in self.__slots__: if getattr(self, k) != value[k]: return True return False def __repr__(self): d = self.asdict() return 'WCF ' + d.__repr__() def __hash__(self): return hash(tuple(self.values())) def get(self, k, default=None): if k in self.__slots__: try: return getattr(self, k) except AttributeError: return default def keys(self): return self.__slots__ def items(self): result = [] for k in self.__slots__: result.append((k, getattr(self, k))) return result def values(self): result = [] for k in self.__slots__: result.append(getattr(self, k)) return result def select(self, keys): result = {} for k in keys: if k in self.__slots__: result[k] = getattr(self, k) return result def asdict(self): result = {} for k in self.__slots__: result[k] = getattr(self, k) return result return Tuple
def build_tuple_type(*columns): class Tuple(object): __slots__ = columns def __init__(self, d=None, **kw): if d is None: d = kw for k in self.__slots__: setattr(self, k, d.get(k)) def __getitem__(self, k): if k in self.__slots__: return getattr(self, k) def __contains__(self, value): return value in self.__slots__ def __eq__(self, value): for k in self.__slots__: if getattr(self, k) != value[k]: return False return True def __ne__(self, value): for k in self.__slots__: if getattr(self, k) != value[k]: return True return False def __repr__(self): d = self.asdict() return 'WCF ' + d.__repr__() def __hash__(self): return hash(tuple(self.values())) def get(self, k, default=None): if k in self.__slots__: try: return getattr(self, k) except AttributeError: return default def keys(self): return self.__slots__ def items(self): result = [] for k in self.__slots__: result.append((k, getattr(self, k))) return result def values(self): result = [] for k in self.__slots__: result.append(getattr(self, k)) return result def select(self, keys): result = {} for k in keys: if k in self.__slots__: result[k] = getattr(self, k) return result def asdict(self): result = {} for k in self.__slots__: result[k] = getattr(self, k) return result return Tuple
# ------------------------------------------------------------------------------ # Site Configuration File # ------------------------------------------------------------------------------ theme = "carbon" title = "Holly Demo" tagline = "A blog-engine plugin for Ivy." extensions = ["holly"] holly = { "homepage": { "root_urls": ["@root/blog//", "@root/animalia//"], }, "roots": [ { "root_url": "@root/blog//", }, { "root_url": "@root/animalia//", }, ], }
theme = 'carbon' title = 'Holly Demo' tagline = 'A blog-engine plugin for Ivy.' extensions = ['holly'] holly = {'homepage': {'root_urls': ['@root/blog//', '@root/animalia//']}, 'roots': [{'root_url': '@root/blog//'}, {'root_url': '@root/animalia//'}]}
def Prime_number(n): a = [] for i in range(2,n+1): e1 = n % i if e1 == 0: b.append(e1) if len(a) > 1: print('FALSE') print('This is not a prime number!') elif len(a) == 1: print('TRUE') print('This is a Prime number!') Prime_number(int(input('Please give your number: ')))
def prime_number(n): a = [] for i in range(2, n + 1): e1 = n % i if e1 == 0: b.append(e1) if len(a) > 1: print('FALSE') print('This is not a prime number!') elif len(a) == 1: print('TRUE') print('This is a Prime number!') prime_number(int(input('Please give your number: ')))
class Platform: def __init__(self, designer, debug): self.designer = designer self.debug = debug def generate_wrappers(self): raise Exception("Method not implemented") def create_mem(self, mem_type, name, data_type, size, init): raise Exception("Method not implemented") def create_mem_from(self, mem_type, memory): return self.create_mem(mem_type, memory.name, memory.data_type, memory.size, memory.init) def create_fifo(self): raise Exception("Method not implemented") def add_intrinsic(self, designer, intrinsic): raise Exception("Method not implemented") def get_keys(self): return {}
class Platform: def __init__(self, designer, debug): self.designer = designer self.debug = debug def generate_wrappers(self): raise exception('Method not implemented') def create_mem(self, mem_type, name, data_type, size, init): raise exception('Method not implemented') def create_mem_from(self, mem_type, memory): return self.create_mem(mem_type, memory.name, memory.data_type, memory.size, memory.init) def create_fifo(self): raise exception('Method not implemented') def add_intrinsic(self, designer, intrinsic): raise exception('Method not implemented') def get_keys(self): return {}
# Here I've implemented a method of finding square root of imperfect square # Steps (Pseudocode): visit http://burningmath.blogspot.in/2013/12/finding-square-roots-of-numbers-that.html # Read the steps carefully or you'll not understand the program! # To check is number is a perfect square or not def is_perfect_square(n): if isinstance(n, float): return (False, None) for i in range(n + 1): if i * i == n: return (True, i) return (False, None) # Average def average(*args): hold = list(args) return sum(hold) / len(hold) # Method # Just implementation of steps on above webpage def sqrt_of_imperfect_square(a, certainty=6): is_square = is_perfect_square(a) if is_square[0]: return "{} is a perfect square .It's root is {}.".format(a, is_square[1]) else: a = int(a) tmp = None s1 = max([float(x * x) for x in range(0, a)]) while True: s2 = a / s1 tmp = average(s1, s2) if not (round(tmp * tmp, certainty) == float(a)): s1 = tmp continue else: return tmp return -1 # This condition will normally never occur # Test case = 2613 res = sqrt_of_imperfect_square(case, 9) print("Test case: " + str(case)) print("Root: " + str(res)) print("Root Squared: " + str(res * res))
def is_perfect_square(n): if isinstance(n, float): return (False, None) for i in range(n + 1): if i * i == n: return (True, i) return (False, None) def average(*args): hold = list(args) return sum(hold) / len(hold) def sqrt_of_imperfect_square(a, certainty=6): is_square = is_perfect_square(a) if is_square[0]: return "{} is a perfect square .It's root is {}.".format(a, is_square[1]) else: a = int(a) tmp = None s1 = max([float(x * x) for x in range(0, a)]) while True: s2 = a / s1 tmp = average(s1, s2) if not round(tmp * tmp, certainty) == float(a): s1 = tmp continue else: return tmp return -1 case = 2613 res = sqrt_of_imperfect_square(case, 9) print('Test case: ' + str(case)) print('Root: ' + str(res)) print('Root Squared: ' + str(res * res))
"""Constants that define units""" AUTO = 'auto' METRIC = 'metric' US = 'us' UK = 'uk' CA = 'ca'
"""Constants that define units""" auto = 'auto' metric = 'metric' us = 'us' uk = 'uk' ca = 'ca'
usuario = input("Informe o nome de usuario: ") senha = input("Informe a senha: ") while usuario == senha: print("Usuario deve ser diferente da senha!\n") senha = input("Informe uma nova senha: ") else: print("Dados confirmados")
usuario = input('Informe o nome de usuario: ') senha = input('Informe a senha: ') while usuario == senha: print('Usuario deve ser diferente da senha!\n') senha = input('Informe uma nova senha: ') else: print('Dados confirmados')
""" This is a simple binary search algorithm for python. This is the exact implementation of the pseudocode written in README. """ def binary_search(item_list,item): left_index = 0 right_index = len(item_list)-1 while left_index <= right_index: middle_index = (left_index+right_index) // 2 if item_list[middle_index] < item: left_index=middle_index+1 elif item_list[middle_index] > item: right_index=middle_index-1 else: return middle_index return None #Simple demonstration of the function if __name__=='__main__': print (binary_search([1,3,5,7],3)) print (binary_search([1,2,5,7,97],0))
""" This is a simple binary search algorithm for python. This is the exact implementation of the pseudocode written in README. """ def binary_search(item_list, item): left_index = 0 right_index = len(item_list) - 1 while left_index <= right_index: middle_index = (left_index + right_index) // 2 if item_list[middle_index] < item: left_index = middle_index + 1 elif item_list[middle_index] > item: right_index = middle_index - 1 else: return middle_index return None if __name__ == '__main__': print(binary_search([1, 3, 5, 7], 3)) print(binary_search([1, 2, 5, 7, 97], 0))
# Dependency Inversion Principle (SOLID) # https://www.geeksforgeeks.org/dependecy-inversion-principle-solid/ # SGVP391900 | 12:03 7Mar19 # Mootto - Any higher classes should always depend upon the abstraction of the class # rather than the detail. class Employee(object): def Work(): pass class Manager(): def __init__(self): self.employees=[] def addEmployee(self,a): self.employees.append(a) # self.developers=[] # self.designers=[] # self.testers=[] # def addDeveloper(self, dev): # self.developers.append(dev) # def addDesigners(self, design): # self.designers.append(design) # def addTesters(self, testers): # self.testers.append(testers) class Developer(Employee): def __init__(self): print ("developer added") def Work(): print ("truning coffee into code") class Designer(Employee): def __init__(self): print ("designer added") def Work(): print ("turning lines to wireframes") class Testers(object): def __init__(self): print ("tester added") def Work(): print ("testing everything out there") if __name__ == "__main__": a=Manager() # a.addDeveloper(Developer()) # a.addDesigners(Designer()) a.addEmployee(Developer()) a.addEmployee(Designer())
class Employee(object): def work(): pass class Manager: def __init__(self): self.employees = [] def add_employee(self, a): self.employees.append(a) class Developer(Employee): def __init__(self): print('developer added') def work(): print('truning coffee into code') class Designer(Employee): def __init__(self): print('designer added') def work(): print('turning lines to wireframes') class Testers(object): def __init__(self): print('tester added') def work(): print('testing everything out there') if __name__ == '__main__': a = manager() a.addEmployee(developer()) a.addEmployee(designer())