content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def test_opendota_api_type(heroes): # Ensure data returned by fetch_hero_stats() is a list assert isinstance(heroes, list) def test_opendota_api_count(heroes, N_HEROES): # Ensure all heroes are included assert len(heroes) == N_HEROES def test_opendota_api_contents(heroes, N_HEROES): # Verify that all elements in heroes list are dicts assert all(isinstance(hero, dict) for hero in heroes)
def test_opendota_api_type(heroes): assert isinstance(heroes, list) def test_opendota_api_count(heroes, N_HEROES): assert len(heroes) == N_HEROES def test_opendota_api_contents(heroes, N_HEROES): assert all((isinstance(hero, dict) for hero in heroes))
class ParserException(Exception): """ Base exception for the email parser. """ pass class ParseEmailException(ParserException): """ Raised when the parser can't create a email.message.Message object of the raw string or bytes. """ pass class MessageIDNotExistException(ParserException): """ Raised when a message not contain a message-id """ pass class DefectMessageException(ParserException): """ Raised when the recieved message is defect. """ pass
class Parserexception(Exception): """ Base exception for the email parser. """ pass class Parseemailexception(ParserException): """ Raised when the parser can't create a email.message.Message object of the raw string or bytes. """ pass class Messageidnotexistexception(ParserException): """ Raised when a message not contain a message-id """ pass class Defectmessageexception(ParserException): """ Raised when the recieved message is defect. """ pass
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ # Runtime: 12 ms # Memory: 13.5 MB pascal = [] for r in range(1, numRows + 1): row = [] for c in range(r): if c == 0 or c == r - 1: row.append(1) else: last_row = pascal[-1] row.append(last_row[c - 1] + last_row[c]) pascal.append(row) return pascal
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ pascal = [] for r in range(1, numRows + 1): row = [] for c in range(r): if c == 0 or c == r - 1: row.append(1) else: last_row = pascal[-1] row.append(last_row[c - 1] + last_row[c]) pascal.append(row) return pascal
class Solution: def lastRemaining(self, n): """ :type n: int :rtype: int """ def helper(n,i): if n == 1: return 1 if i: return 2 * helper(n//2,0) elif n % 2 == 1: return 2 * helper(n//2,1) else: return 2 * helper(n//2,1) - 1 return helper(n,1) a = Solution() print(a.lastRemaining(100000000))
class Solution: def last_remaining(self, n): """ :type n: int :rtype: int """ def helper(n, i): if n == 1: return 1 if i: return 2 * helper(n // 2, 0) elif n % 2 == 1: return 2 * helper(n // 2, 1) else: return 2 * helper(n // 2, 1) - 1 return helper(n, 1) a = solution() print(a.lastRemaining(100000000))
''' From: LeetCode - 141. Linked List Cycle Level: Easy Source: https://leetcode.com/problems/linked-list-cycle/description/ Status: AC Solution: Using Hash Table ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head is None: return False p = head.next m = {head} while p is not None: if p in m: return True m.add(p) p = p.next return False # times o(n) # space o(n) ''' Most Optimal Answer: Two Pointers def hasCycle(self, head): try: normalSpeed = head x2Speed = head.next while normalSpeed is not x2Speed: normalSpeed = normalSpeed.next x2Speed = x2Speed.next.next print('normal: {}, x2Speed: {}'.format(normalSpeed.val, x2Speed.val)) return True except: return False # times o(n) # space o(1) '''
""" From: LeetCode - 141. Linked List Cycle Level: Easy Source: https://leetcode.com/problems/linked-list-cycle/description/ Status: AC Solution: Using Hash Table """ class Solution(object): def has_cycle(self, head): """ :type head: ListNode :rtype: bool """ if head is None: return False p = head.next m = {head} while p is not None: if p in m: return True m.add(p) p = p.next return False "\nMost Optimal Answer: Two Pointers\ndef hasCycle(self, head):\n try:\n normalSpeed = head\n x2Speed = head.next\n while normalSpeed is not x2Speed:\n normalSpeed = normalSpeed.next\n x2Speed = x2Speed.next.next\n print('normal: {}, x2Speed: {}'.format(normalSpeed.val, x2Speed.val))\n return True\n except:\n return False\n\n# times o(n)\n# space o(1)\n"
""" Journals module of Spire library and API version. """ SPIRE_JOURNALS_VERSION = "0.1.1"
""" Journals module of Spire library and API version. """ spire_journals_version = '0.1.1'
class Structure(object): _fields = () def __init__(self, *args): if len(_fields) != len(args): raise TypeError(f"Expected {len(_fields)} arguments.") for name, value in zip(self._fields, args): setattr(self, name, value) if __name__ == '__main__': class Shares(Structure): _fields = ('name', 'share', 'price') class Point(Structure): _fields = ('x', 'y') class Circle(Structure): _fields = ('radius')
class Structure(object): _fields = () def __init__(self, *args): if len(_fields) != len(args): raise type_error(f'Expected {len(_fields)} arguments.') for (name, value) in zip(self._fields, args): setattr(self, name, value) if __name__ == '__main__': class Shares(Structure): _fields = ('name', 'share', 'price') class Point(Structure): _fields = ('x', 'y') class Circle(Structure): _fields = 'radius'
#!/usr/bin/env python #-*- coding: utf-8 -*- ID = 'ID' TOKEN = 'TOKEN' SUB_DOMAIN = 'xsy' DOMAIN = 'admxj.pw'
id = 'ID' token = 'TOKEN' sub_domain = 'xsy' domain = 'admxj.pw'
''' this program translates any integer base to decimal. examples for testing: assert checkio("101", 2) == 5, "Binary" assert checkio("111112", 3) == 365, "Ternary" assert checkio("200", 4) == 32, "Quaternary" assert checkio("101", 5) == 26, "5 base" assert checkio("25", 6) == 17, "Heximal/Senary" assert checkio("112", 8) == 74, "Octal assert checkio("AB", 10) == -1, "B > A > 10" assert checkio("10000", 12) == 20736, "duodecimal" assert checkio("AF", 16) == 175, "Hex" assert checkio("20", 20) == 40, "Vigesimal" assert checkio("D0", 20) == 260, "Vigesimal" assert checkio("100", 20) == 400, "Vigesimal" assert checkio("Z", 36) == 35, "Hexatrigesimal" ''' def checkio(str_number, radix): myList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; # initialise first digit letter = str_number[0].lower(); faktor = myList.index(letter); # digit cannot be greater than base if faktor >= radix: return -1 # only one digit if len(str_number) == 1: return faktor; # only two digits if len(str_number) == 2: letter = str_number[0].lower(); faktor = myList.index(letter); if faktor > radix: return -1 result = faktor * radix; letter = str_number[1].lower(); faktor = myList.index(letter); if faktor > radix: return -1 result += faktor; return result # all other cases result = faktor; for elem in range(1, len(str_number)): letter = str_number[elem].lower(); faktor = myList.index(letter); # check that digit is not greater than base if faktor > radix: return -1 result *= radix; result += faktor; return result; #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("AF", 16) == 175, "Hex" assert checkio("101", 2) == 5, "Bin" assert checkio("101", 5) == 26, "5 base" assert checkio("Z", 36) == 35, "Z base" assert checkio("AB", 10) == -1, "B > A > 10"
""" this program translates any integer base to decimal. examples for testing: assert checkio("101", 2) == 5, "Binary" assert checkio("111112", 3) == 365, "Ternary" assert checkio("200", 4) == 32, "Quaternary" assert checkio("101", 5) == 26, "5 base" assert checkio("25", 6) == 17, "Heximal/Senary" assert checkio("112", 8) == 74, "Octal assert checkio("AB", 10) == -1, "B > A > 10" assert checkio("10000", 12) == 20736, "duodecimal" assert checkio("AF", 16) == 175, "Hex" assert checkio("20", 20) == 40, "Vigesimal" assert checkio("D0", 20) == 260, "Vigesimal" assert checkio("100", 20) == 400, "Vigesimal" assert checkio("Z", 36) == 35, "Hexatrigesimal" """ def checkio(str_number, radix): my_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter = str_number[0].lower() faktor = myList.index(letter) if faktor >= radix: return -1 if len(str_number) == 1: return faktor if len(str_number) == 2: letter = str_number[0].lower() faktor = myList.index(letter) if faktor > radix: return -1 result = faktor * radix letter = str_number[1].lower() faktor = myList.index(letter) if faktor > radix: return -1 result += faktor return result result = faktor for elem in range(1, len(str_number)): letter = str_number[elem].lower() faktor = myList.index(letter) if faktor > radix: return -1 result *= radix result += faktor return result if __name__ == '__main__': assert checkio('AF', 16) == 175, 'Hex' assert checkio('101', 2) == 5, 'Bin' assert checkio('101', 5) == 26, '5 base' assert checkio('Z', 36) == 35, 'Z base' assert checkio('AB', 10) == -1, 'B > A > 10'
classes = [ { 'name': 'science-1', 'subjects': [ { 'name': 'Math', 'taughtBy': 'Turing', 'duration': 60 }, { 'name': 'English', 'taughtBy': 'Adele', 'duration': 60 }, { 'name': 'Sports', 'taughtBy': 'Dinho', 'duration': 60 }, { 'name': 'Science', 'taughtBy': 'Harish', 'duration': 60 } ], }, { 'name': 'science-2', 'subjects': [ { 'name': 'Math', 'taughtBy': 'Harish', 'duration': 60 }, { 'name': 'English', 'taughtBy': 'Freddie', 'duration': 60 }, { 'name': 'Music', 'taughtBy': 'Freddie', 'duration': 60 }, { 'name': 'Science', 'taughtBy': 'Harish', 'duration': 60 } ] }, { 'name': 'biology', 'subjects': [ { 'name': 'Botany', 'taughtBy': 'Dalton', 'duration': 60 }, { 'name': 'Zoology', 'taughtBy': 'Dalton', 'duration': 60 } ] }, { 'name': 'politics', 'subjects': [ { 'name': 'Political Administration', 'taughtBy': 'Trump', 'duration': 60 }, { 'name': 'Business Administration', 'taughtBy': 'Trump', 'duration': 60 }, { 'name': 'Foreign Affairs', 'taughtBy': 'Trump', 'duration': 60 } ] }, { 'name': 'politics-2', 'subjects': [ { 'name': 'Foreign Affairs', 'taughtBy': 'Swaraj', 'duration': 60 } ] }, { 'name': 'philosophy', 'subjects': [ { 'name': 'Philosophy', 'taughtBy': 'Socrates', 'duration': 60 }, { 'name': 'Moral Science', 'taughtBy': 'Socrates', 'duration': 60 } ] }, ]
classes = [{'name': 'science-1', 'subjects': [{'name': 'Math', 'taughtBy': 'Turing', 'duration': 60}, {'name': 'English', 'taughtBy': 'Adele', 'duration': 60}, {'name': 'Sports', 'taughtBy': 'Dinho', 'duration': 60}, {'name': 'Science', 'taughtBy': 'Harish', 'duration': 60}]}, {'name': 'science-2', 'subjects': [{'name': 'Math', 'taughtBy': 'Harish', 'duration': 60}, {'name': 'English', 'taughtBy': 'Freddie', 'duration': 60}, {'name': 'Music', 'taughtBy': 'Freddie', 'duration': 60}, {'name': 'Science', 'taughtBy': 'Harish', 'duration': 60}]}, {'name': 'biology', 'subjects': [{'name': 'Botany', 'taughtBy': 'Dalton', 'duration': 60}, {'name': 'Zoology', 'taughtBy': 'Dalton', 'duration': 60}]}, {'name': 'politics', 'subjects': [{'name': 'Political Administration', 'taughtBy': 'Trump', 'duration': 60}, {'name': 'Business Administration', 'taughtBy': 'Trump', 'duration': 60}, {'name': 'Foreign Affairs', 'taughtBy': 'Trump', 'duration': 60}]}, {'name': 'politics-2', 'subjects': [{'name': 'Foreign Affairs', 'taughtBy': 'Swaraj', 'duration': 60}]}, {'name': 'philosophy', 'subjects': [{'name': 'Philosophy', 'taughtBy': 'Socrates', 'duration': 60}, {'name': 'Moral Science', 'taughtBy': 'Socrates', 'duration': 60}]}]
""" snek.tests Package: Unit & integration tests for Snek. """ #------------------------------------------------------------------------------- # Constants #------------------------------------------------------------------------------- MOCKS_FOLDER = './tests/mocks'
""" snek.tests Package: Unit & integration tests for Snek. """ mocks_folder = './tests/mocks'
cont = 0 lista = [] while cont < 20: x = input() lista.append(x) cont += 1 cont2 = 0 valor = -1 while cont2 < 20: print("N[" + str(cont2) + "] = " + str(lista[valor])) valor -= 1 cont2 += 1
cont = 0 lista = [] while cont < 20: x = input() lista.append(x) cont += 1 cont2 = 0 valor = -1 while cont2 < 20: print('N[' + str(cont2) + '] = ' + str(lista[valor])) valor -= 1 cont2 += 1
class Solution: def isRobotBounded(self, instructions: str) -> bool: x, y, dx, dy = 0, 0, 0, 1 for it in instructions: if it == 'L': dx, dy = -dy, dx elif it == 'R': dx, dy = dy, -dx else: x = x + dx y = y + dy return (x, y) == (0, 0) or (dx, dy) != (0, 1)
class Solution: def is_robot_bounded(self, instructions: str) -> bool: (x, y, dx, dy) = (0, 0, 0, 1) for it in instructions: if it == 'L': (dx, dy) = (-dy, dx) elif it == 'R': (dx, dy) = (dy, -dx) else: x = x + dx y = y + dy return (x, y) == (0, 0) or (dx, dy) != (0, 1)
### TODO use the details of your database connection REGION = 'eu-west-2' DBPORT = 1433 DBUSERNAME = 'admin' # the name of the database user you created in step 2 DBNAME = 'EventDatabase' # the name of the database your database user is granted access to DBENDPOINT = 'eventdatabase.cu9s0xzhp0zw.eu-west-2.rds.amazonaws.com' # DBPASSWORD = 'Eventpassword' #config file containing credentials for RDS MySQL instance db_username = "admin" db_password = "Eventpassword" db_name = "event_shema"
region = 'eu-west-2' dbport = 1433 dbusername = 'admin' dbname = 'EventDatabase' dbendpoint = 'eventdatabase.cu9s0xzhp0zw.eu-west-2.rds.amazonaws.com' dbpassword = 'Eventpassword' db_username = 'admin' db_password = 'Eventpassword' db_name = 'event_shema'
MAILBOX_MOVIE_CLEAR = 2 MAILBOX_MOVIE_EMPTY = 3 MAILBOX_MOVIE_WAITING = 4 MAILBOX_MOVIE_READY = 5 MAILBOX_MOVIE_NOT_OWNER = 6 MAILBOX_MOVIE_EXIT = 7
mailbox_movie_clear = 2 mailbox_movie_empty = 3 mailbox_movie_waiting = 4 mailbox_movie_ready = 5 mailbox_movie_not_owner = 6 mailbox_movie_exit = 7
# Copyright (c) 2013 by pytest_pyramid authors and contributors # # This module is part of pytest_pyramid and is released under # the MIT License (MIT): http://opensource.org/licenses/MIT """pytest_pyramid main module.""" __version__ = "1.0.1" # pragma: no cover
"""pytest_pyramid main module.""" __version__ = '1.0.1'
answer = int(input("How many times do you want to play? ")) for i in range(0,answer): person1 = input("What is the first name? ") person2 = input("What is the second name? ") if person1 > person2: print(person1) print("has won") elif person1 == person2: print("friendship") print("has won") else: print(person2) print("has won")
answer = int(input('How many times do you want to play? ')) for i in range(0, answer): person1 = input('What is the first name? ') person2 = input('What is the second name? ') if person1 > person2: print(person1) print('has won') elif person1 == person2: print('friendship') print('has won') else: print(person2) print('has won')
__all__ = ['strip_comments'] def strip_comments(contents): """Strips the comments from coq code in contents. The strings in contents are only preserved if there are no comment-like tokens inside of strings. Stripping should be successful and correct, regardless of whether or not there are comment-like tokens in strings. The behavior of this method is undefined if there are any notations which change the meaning of '(*', '*)', or '"'. Note that we take some extra care to leave *) untouched when it does not terminate a comment. """ contents = contents.replace('(*', ' (* ').replace('*)', ' *) ') tokens = contents.split(' ') rtn = [] is_string = False comment_level = 0 for token in tokens: do_append = (comment_level == 0) if is_string: if token.count('"') % 2 == 1: # there are an odd number of '"' characters, indicating that we've ended the string is_string = False elif token.count('"') % 2 == 1: # there are an odd number of '"' characters, so we're starting a string is_string = True elif token == '(*': comment_level += 1 do_append = False elif comment_level > 0 and token == '*)': comment_level -= 1 if do_append: rtn.append(token) return ' '.join(rtn).replace(' (* ', '(*').replace(' *) ', '*)').strip('\n\t ')
__all__ = ['strip_comments'] def strip_comments(contents): """Strips the comments from coq code in contents. The strings in contents are only preserved if there are no comment-like tokens inside of strings. Stripping should be successful and correct, regardless of whether or not there are comment-like tokens in strings. The behavior of this method is undefined if there are any notations which change the meaning of '(*', '*)', or '"'. Note that we take some extra care to leave *) untouched when it does not terminate a comment. """ contents = contents.replace('(*', ' (* ').replace('*)', ' *) ') tokens = contents.split(' ') rtn = [] is_string = False comment_level = 0 for token in tokens: do_append = comment_level == 0 if is_string: if token.count('"') % 2 == 1: is_string = False elif token.count('"') % 2 == 1: is_string = True elif token == '(*': comment_level += 1 do_append = False elif comment_level > 0 and token == '*)': comment_level -= 1 if do_append: rtn.append(token) return ' '.join(rtn).replace(' (* ', '(*').replace(' *) ', '*)').strip('\n\t ')
"""This file contains macros to be called during WORKSPACE evaluation. For historic reasons, pip_repositories() is defined in //python:pip.bzl. """ def py_repositories(): """Pull in dependencies needed to use the core Python rules.""" # At the moment this is a placeholder hook, in that it does not actually # pull in any dependencies. Users should still call this function to make # it less likely that they need to update their WORKSPACE files, in case # this function is changed in the future. pass
"""This file contains macros to be called during WORKSPACE evaluation. For historic reasons, pip_repositories() is defined in //python:pip.bzl. """ def py_repositories(): """Pull in dependencies needed to use the core Python rules.""" pass
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( X , Y , m , n ) : LCSuff = [ [ 0 for k in range ( n + 1 ) ] for l in range ( m + 1 ) ] result = 0 for i in range ( m + 1 ) : for j in range ( n + 1 ) : if ( i == 0 or j == 0 ) : LCSuff [ i ] [ j ] = 0 elif ( X [ i - 1 ] == Y [ j - 1 ] ) : LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 result = max ( result , LCSuff [ i ] [ j ] ) else : LCSuff [ i ] [ j ] = 0 return result #TOFILL if __name__ == '__main__': param = [ (['A', 'D', 'E', 'E', 'L', 'L', 'T', 'r', 'x'],['D', 'F', 'H', 'O', 'g', 'o', 'u', 'v', 'w'],4,4,), (['9', '3', '4', '8', '7', '6', '3', '8', '3', '3', '5', '3', '5', '4', '2', '5', '5', '3', '6', '2', '1', '7', '4', '2', '7', '3', '2', '1', '3', '7', '6', '5', '0', '6', '3', '8', '5', '1', '7', '9', '2', '7'],['5', '5', '3', '7', '8', '0', '9', '8', '5', '8', '5', '1', '4', '4', '0', '2', '9', '2', '3', '1', '1', '3', '6', '1', '2', '0', '5', '4', '3', '7', '5', '5', '8', '1', '1', '4', '8', '1', '7', '5', '5', '4'],41,37,), (['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],35,29,), (['W', 'X', 'P', 'u', 's', 'k', 'O', 'y', 'Q', 'i', 't', 'z', 'F', 'f', 's', 'N', 'K', 'm', 'I', 'M', 'g', 'e', 'E', 'P', 'b', 'Y', 'c', 'O', ' ', 'G', 'F', 'x'],['e', 'R', 'P', 'W', 'd', 'a', 'A', 'j', 'H', 'v', 'T', 'w', 'x', 'I', 'd', 'o', 'z', 'K', 'B', 'M', 'J', 'L', 'a', ' ', 'T', 'L', 'V', 't', 'M', 'U', 'z', 'R'],31,18,), (['0', '1', '2', '4', '5', '7', '7', '7', '8', '8', '9', '9', '9'],['0', '0', '2', '2', '2', '3', '4', '6', '6', '7', '8', '9', '9'],12,8,), (['0', '0', '1'],['0', '0', '1'],1,1,), (['A', 'C', 'F', 'G', 'G', 'H', 'I', 'K', 'K', 'N', 'O', 'Q', 'R', 'V', 'V', 'W', 'Y', 'a', 'a', 'c', 'd', 'k', 'k', 'm', 'o', 'p', 't', 'u', 'y', 'y', 'y', 'z'],[' ', ' ', 'B', 'C', 'C', 'C', 'D', 'E', 'I', 'J', 'M', 'N', 'P', 'T', 'U', 'U', 'V', 'V', 'W', 'W', 'Y', 'b', 'c', 'e', 'i', 'o', 'p', 'r', 't', 'y', 'y', 'z'],21,23,), (['0', '0', '0', '2', '8', '3', '5', '1', '0', '7', '7', '9', '9', '4', '8', '9', '5'],['8', '5', '8', '7', '1', '4', '0', '2', '2', '7', '2', '4', '0', '8', '3', '8', '7'],13,12,), (['0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1'],9,9,), (['B', 'o', 'R', 'k', 'Y', 'M', 'g', 'b', 'h', 'A', 'i', 'X', 'p', 'i', 'j', 'f', 'V', 'n', 'd', 'P', 'T', 'U', 'f', 'G', 'M', 'W', 'g', 'a', 'C', 'E', 'v', 'C', ' '],['F', 'h', 'G', 'H', 'Q', 'Q', 'K', 'g', 'k', 'u', 'l', 'c', 'c', 'o', 'n', 'G', 'i', 'Z', 'd', 'b', 'c', 'b', 'v', 't', 'S', 't', 'P', 'A', 'K', 'g', 'G', 'i', 'm'],19,32,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(X, Y, m, n): lc_suff = [[0 for k in range(n + 1)] for l in range(m + 1)] result = 0 for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: LCSuff[i][j] = 0 elif X[i - 1] == Y[j - 1]: LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 result = max(result, LCSuff[i][j]) else: LCSuff[i][j] = 0 return result if __name__ == '__main__': param = [(['A', 'D', 'E', 'E', 'L', 'L', 'T', 'r', 'x'], ['D', 'F', 'H', 'O', 'g', 'o', 'u', 'v', 'w'], 4, 4), (['9', '3', '4', '8', '7', '6', '3', '8', '3', '3', '5', '3', '5', '4', '2', '5', '5', '3', '6', '2', '1', '7', '4', '2', '7', '3', '2', '1', '3', '7', '6', '5', '0', '6', '3', '8', '5', '1', '7', '9', '2', '7'], ['5', '5', '3', '7', '8', '0', '9', '8', '5', '8', '5', '1', '4', '4', '0', '2', '9', '2', '3', '1', '1', '3', '6', '1', '2', '0', '5', '4', '3', '7', '5', '5', '8', '1', '1', '4', '8', '1', '7', '5', '5', '4'], 41, 37), (['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], 35, 29), (['W', 'X', 'P', 'u', 's', 'k', 'O', 'y', 'Q', 'i', 't', 'z', 'F', 'f', 's', 'N', 'K', 'm', 'I', 'M', 'g', 'e', 'E', 'P', 'b', 'Y', 'c', 'O', ' ', 'G', 'F', 'x'], ['e', 'R', 'P', 'W', 'd', 'a', 'A', 'j', 'H', 'v', 'T', 'w', 'x', 'I', 'd', 'o', 'z', 'K', 'B', 'M', 'J', 'L', 'a', ' ', 'T', 'L', 'V', 't', 'M', 'U', 'z', 'R'], 31, 18), (['0', '1', '2', '4', '5', '7', '7', '7', '8', '8', '9', '9', '9'], ['0', '0', '2', '2', '2', '3', '4', '6', '6', '7', '8', '9', '9'], 12, 8), (['0', '0', '1'], ['0', '0', '1'], 1, 1), (['A', 'C', 'F', 'G', 'G', 'H', 'I', 'K', 'K', 'N', 'O', 'Q', 'R', 'V', 'V', 'W', 'Y', 'a', 'a', 'c', 'd', 'k', 'k', 'm', 'o', 'p', 't', 'u', 'y', 'y', 'y', 'z'], [' ', ' ', 'B', 'C', 'C', 'C', 'D', 'E', 'I', 'J', 'M', 'N', 'P', 'T', 'U', 'U', 'V', 'V', 'W', 'W', 'Y', 'b', 'c', 'e', 'i', 'o', 'p', 'r', 't', 'y', 'y', 'z'], 21, 23), (['0', '0', '0', '2', '8', '3', '5', '1', '0', '7', '7', '9', '9', '4', '8', '9', '5'], ['8', '5', '8', '7', '1', '4', '0', '2', '2', '7', '2', '4', '0', '8', '3', '8', '7'], 13, 12), (['0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1'], ['0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1'], 9, 9), (['B', 'o', 'R', 'k', 'Y', 'M', 'g', 'b', 'h', 'A', 'i', 'X', 'p', 'i', 'j', 'f', 'V', 'n', 'd', 'P', 'T', 'U', 'f', 'G', 'M', 'W', 'g', 'a', 'C', 'E', 'v', 'C', ' '], ['F', 'h', 'G', 'H', 'Q', 'Q', 'K', 'g', 'k', 'u', 'l', 'c', 'c', 'o', 'n', 'G', 'i', 'Z', 'd', 'b', 'c', 'b', 'v', 't', 'S', 't', 'P', 'A', 'K', 'g', 'G', 'i', 'm'], 19, 32)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
#Simple declaration of Funtion '''def say_hello(): print('hello') say_hello() ''' def greeting(name): print(f'Hello {name}') greeting('raj')
"""def say_hello(): print('hello') say_hello() """ def greeting(name): print(f'Hello {name}') greeting('raj')
def for_hyphen(): for row in range(3): for col in range(3): if row==1: print("*",end=" ") else: print(" ",end=" ") print() def while_hyphen(): row=0 while row<3: col=0 while col<3: if row==1: print("*",end=" ") else: print(" ",end=" ") col+=1 row+=1 print()
def for_hyphen(): for row in range(3): for col in range(3): if row == 1: print('*', end=' ') else: print(' ', end=' ') print() def while_hyphen(): row = 0 while row < 3: col = 0 while col < 3: if row == 1: print('*', end=' ') else: print(' ', end=' ') col += 1 row += 1 print()
class EmptyGraphHelper(object): @staticmethod def get_help_message(): return f""" We are deeply sorry but unfortunately the result graph is empty. Please try the following steps to fix the problem - \t1. Try running again with other / no filters \t2. Make sure to run 'edr lineage generate' command first \t3. Join our slack channel here - https://bit.ly/slack-elementary, we promise to help and be nice! """
class Emptygraphhelper(object): @staticmethod def get_help_message(): return f"\n We are deeply sorry but unfortunately the result graph is empty.\n Please try the following steps to fix the problem - \n \t1. Try running again with other / no filters\n \t2. Make sure to run 'edr lineage generate' command first\n \t3. Join our slack channel here - https://bit.ly/slack-elementary, we promise to help and be nice! \n "
def tabuada(numero): for i in range(1, 11): print(f'{i} x {numero} = {i * numero}') tabuada(int(input()))
def tabuada(numero): for i in range(1, 11): print(f'{i} x {numero} = {i * numero}') tabuada(int(input()))
class RadarSensor: angle = None axis = None distance = None property = None
class Radarsensor: angle = None axis = None distance = None property = None
# 838. Push Dominoes # There are N dominoes in a line, and we place each domino vertically upright. # In the beginning, we simultaneously push some of the dominoes either to the left or to the right. # After each second, each domino that is falling to the left pushes the adjacent domino on the left. # Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. # When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. # For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. # Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed. # Return a string representing the final state. # Example 1: # Input: ".L.R...LR..L.." # Output: "LL.RR.LLRRLL.." # Example 2: # Input: "RR.L" # Output: "RR.L" # Explanation: The first domino expends no additional force on the second domino. # Note: # 0 <= N <= 10^5 # String dominoes contains only 'L', 'R' and '.' class Solution(object): def pushDominoes(self, dominoes): """ :type dominoes: str :rtype: str """ # sol 1: # use DP # time O(n) space O(n) # runtime: 553ms dp = [0]*len(dominoes) # distance from current index to L/R. lst = list(dominoes) n = len(lst) leftDist, rightDist = None, None for i, val in enumerate(dominoes): # right if val == 'R': rightDist = 0 elif val == 'L': rightDist = None elif rightDist != None: rightDist += 1 lst[i] = 'R' dp[i] = rightDist for i in range(n-1, -1, -1): if dominoes[i] == 'L': leftDist = 0 elif dominoes[i] == 'R': leftDist = None elif leftDist != None: leftDist += 1 if leftDist < dp[i] or lst[i]=='.': lst[i] = 'L' elif leftDist == dp[i]: lst[i] = '.' return ''.join(lst)
class Solution(object): def push_dominoes(self, dominoes): """ :type dominoes: str :rtype: str """ dp = [0] * len(dominoes) lst = list(dominoes) n = len(lst) (left_dist, right_dist) = (None, None) for (i, val) in enumerate(dominoes): if val == 'R': right_dist = 0 elif val == 'L': right_dist = None elif rightDist != None: right_dist += 1 lst[i] = 'R' dp[i] = rightDist for i in range(n - 1, -1, -1): if dominoes[i] == 'L': left_dist = 0 elif dominoes[i] == 'R': left_dist = None elif leftDist != None: left_dist += 1 if leftDist < dp[i] or lst[i] == '.': lst[i] = 'L' elif leftDist == dp[i]: lst[i] = '.' return ''.join(lst)
#!/usr/bin/env python3 class Course: '''Course superclass for any course''' def __init__(self, dept, num, name='', units=4, prereq=set(), restr=set(), coclass=None): self.dept, self.num, self.name = dept, num, name self.units = units self.prereq, self.restr = prereq, restr if coclass: self.coclass = coclass else: self.coclass = 'No co-classes required' def __repr__(self): return self.dept+' '+self.num def get_info(self): return self.__repr__()+': '+self.name\ +'\nPrerequisites: '+', '.join(self.prereq)\ + '\nCoclasses: '+self.coclass class GE(Course): '''GE class''' def __init__(self, dept, num, name='', units=4, prereq=set(), restr=set(), coclass=None, section=set()): self.section = section super.__init__(dept, num, name, units, prereq, restr, coclass)
class Course: """Course superclass for any course""" def __init__(self, dept, num, name='', units=4, prereq=set(), restr=set(), coclass=None): (self.dept, self.num, self.name) = (dept, num, name) self.units = units (self.prereq, self.restr) = (prereq, restr) if coclass: self.coclass = coclass else: self.coclass = 'No co-classes required' def __repr__(self): return self.dept + ' ' + self.num def get_info(self): return self.__repr__() + ': ' + self.name + '\nPrerequisites: ' + ', '.join(self.prereq) + '\nCoclasses: ' + self.coclass class Ge(Course): """GE class""" def __init__(self, dept, num, name='', units=4, prereq=set(), restr=set(), coclass=None, section=set()): self.section = section super.__init__(dept, num, name, units, prereq, restr, coclass)
"""Ecosystem exception.""" class QiskitEcosystemException(Exception): """Exceptions for qiskit ecosystem."""
"""Ecosystem exception.""" class Qiskitecosystemexception(Exception): """Exceptions for qiskit ecosystem."""
# LIS2DW12 3-axis motion seneor micropython drive # ver: 1.0 # License: MIT # Author: shaoziyang (shaoziyang@micropython.org.cn) # v1.0 2019.7 LIS2DW12_CTRL1 = const(0x20) LIS2DW12_CTRL2 = const(0x21) LIS2DW12_CTRL3 = const(0x22) LIS2DW12_CTRL6 = const(0x25) LIS2DW12_STATUS = const(0x27) LIS2DW12_OUT_T_L = const(0x0D) LIS2DW12_OUT_X_L = const(0x28) LIS2DW12_OUT_Y_L = const(0x2A) LIS2DW12_OUT_Z_L = const(0x2C) LIS2DW12_SCALE = ('2g', '4g', '8g', '16g') class LIS2DW12(): def __init__(self, i2c, addr = 0x19): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [0, 0, 0] self._power = 0x20 # ODR=5 MODE=0 LP=1 self.setreg(LIS2DW12_CTRL1, 0x51) # BDU=1 self.setreg(LIS2DW12_CTRL2, 0x0C) # SLP_MODE_SEL=1 self.setreg(LIS2DW12_CTRL3, 0x02) # scale=2G self._scale = 0 self.scale(self._scale) self.oneshot_mode(False) def int16(self, d): return d if d < 0x8000 else d - 0x10000 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg+1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = (self.rb[0] & mask) | dat self.setreg(reg, self.rb[0]) def oneshot_mode(self, oneshot=None): if oneshot is None: return self.oneshot else: self.oneshot = oneshot d = 8 if oneshot else 0 self.r_w_reg(LIS2DW12_CTRL1, d, 0xF3) def ONE_SHOT(self): if self.oneshot: self.r_w_reg(LIS2DW12_CTRL3, 1, 0xFE) while 1: if (self.getreg(LIS2DW12_CTRL3) & 0x01) == 0: return def x_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_X_L))>>2 def y_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_Y_L))>>2 def z_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_Z_L))>>2 def get_raw(self): self.ONE_SHOT() self.irq_v[0] = self.int16(self.get2reg(LIS2DW12_OUT_X_L))>>2 self.irq_v[1] = self.int16(self.get2reg(LIS2DW12_OUT_Y_L))>>2 self.irq_v[2] = self.int16(self.get2reg(LIS2DW12_OUT_Z_L))>>2 return self.irq_v def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * (1 << self._scale)) def x(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_X_L) def y(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_Y_L) def z(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_Z_L) def get(self): self.ONE_SHOT() self.irq_v[0] = self.mg(LIS2DW12_OUT_X_L) self.irq_v[1] = self.mg(LIS2DW12_OUT_Y_L) self.irq_v[2] = self.mg(LIS2DW12_OUT_Z_L) return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LIS2DW12_OUT_T_L))/256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LIS2DW12_OUT_T_L+1) if self.rb[0] & 0x80: self.rb[0] -= 256 return self.rb[0] + 25 def scale(self, dat=None): if dat is None: return LIS2DW12_SCALE[self._scale] else: if type(dat) is str: if not dat in LIS2DW12_SCALE: return self._scale = LIS2DW12_SCALE.index(dat) else: return self.r_w_reg(LIS2DW12_CTRL6, self._scale<<4, 0xCF) def power(self, on=None): if on is None: return self._power > 0 else: if on: self.r_w_reg(LIS2DW12_CTRL1, self._power, 0x0F) self._power = 0 else: self._power = self.getreg(LIS2DW12_CTRL1) & 0xF0 self.r_w_reg(LIS2DW12_CTRL1, 0, 0x0F)
lis2_dw12_ctrl1 = const(32) lis2_dw12_ctrl2 = const(33) lis2_dw12_ctrl3 = const(34) lis2_dw12_ctrl6 = const(37) lis2_dw12_status = const(39) lis2_dw12_out_t_l = const(13) lis2_dw12_out_x_l = const(40) lis2_dw12_out_y_l = const(42) lis2_dw12_out_z_l = const(44) lis2_dw12_scale = ('2g', '4g', '8g', '16g') class Lis2Dw12: def __init__(self, i2c, addr=25): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [0, 0, 0] self._power = 32 self.setreg(LIS2DW12_CTRL1, 81) self.setreg(LIS2DW12_CTRL2, 12) self.setreg(LIS2DW12_CTRL3, 2) self._scale = 0 self.scale(self._scale) self.oneshot_mode(False) def int16(self, d): return d if d < 32768 else d - 65536 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg + 1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = self.rb[0] & mask | dat self.setreg(reg, self.rb[0]) def oneshot_mode(self, oneshot=None): if oneshot is None: return self.oneshot else: self.oneshot = oneshot d = 8 if oneshot else 0 self.r_w_reg(LIS2DW12_CTRL1, d, 243) def one_shot(self): if self.oneshot: self.r_w_reg(LIS2DW12_CTRL3, 1, 254) while 1: if self.getreg(LIS2DW12_CTRL3) & 1 == 0: return def x_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_X_L)) >> 2 def y_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_Y_L)) >> 2 def z_raw(self): self.ONE_SHOT() return self.int16(self.get2reg(LIS2DW12_OUT_Z_L)) >> 2 def get_raw(self): self.ONE_SHOT() self.irq_v[0] = self.int16(self.get2reg(LIS2DW12_OUT_X_L)) >> 2 self.irq_v[1] = self.int16(self.get2reg(LIS2DW12_OUT_Y_L)) >> 2 self.irq_v[2] = self.int16(self.get2reg(LIS2DW12_OUT_Z_L)) >> 2 return self.irq_v def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * (1 << self._scale)) def x(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_X_L) def y(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_Y_L) def z(self): self.ONE_SHOT() return self.mg(LIS2DW12_OUT_Z_L) def get(self): self.ONE_SHOT() self.irq_v[0] = self.mg(LIS2DW12_OUT_X_L) self.irq_v[1] = self.mg(LIS2DW12_OUT_Y_L) self.irq_v[2] = self.mg(LIS2DW12_OUT_Z_L) return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LIS2DW12_OUT_T_L)) / 256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LIS2DW12_OUT_T_L + 1) if self.rb[0] & 128: self.rb[0] -= 256 return self.rb[0] + 25 def scale(self, dat=None): if dat is None: return LIS2DW12_SCALE[self._scale] else: if type(dat) is str: if not dat in LIS2DW12_SCALE: return self._scale = LIS2DW12_SCALE.index(dat) else: return self.r_w_reg(LIS2DW12_CTRL6, self._scale << 4, 207) def power(self, on=None): if on is None: return self._power > 0 elif on: self.r_w_reg(LIS2DW12_CTRL1, self._power, 15) self._power = 0 else: self._power = self.getreg(LIS2DW12_CTRL1) & 240 self.r_w_reg(LIS2DW12_CTRL1, 0, 15)
recomputation_vm_memory = 2048 haskell_vm_memory = 4096 recomputation_vm_cpus = 2 vagrantfile_templates_dict = { "python": "python/python.vagrantfile", "node_js": "nodejs/nodejs.vagrantfile", "cpp": "cpp/cpp.vagrantfile", "c++": "cpp/cpp.vagrantfile", "c": "cpp/cpp.vagrantfile", "haskell": "haskell/haskell.vagrantfile", "go": "go/go.vagrantfile" } languages_version_dict = { "python": "2.7", "node_js": "0.10" } languages_install_dict = { "python": ["pip install -r requirements.txt"], "node_js": ["npm install"], "cpp": ["chmod +x configure", "./configure", "make", "sudo make install"], "c++": ["chmod +x configure", "./configure", "make", "sudo make install"], "c": ["chmod +x configure", "./configure", "make", "sudo make install"], "haskell": ["$VAGRANT_USER 'cabal configure'", "$VAGRANT_USER 'cabal install'"] } boxes_install_scripts = { "gecode": ["echo \"export LD_LIBRARY_PATH=/home/vagrant/gecode\" >> /home/vagrant/.bashrc", "source /home/vagrant/.bashrc"], "Idris-dev": ["$VAGRANT_USER 'sudo cabal configure'", "$VAGRANT_USER 'sudo cabal install'"] } ignore_test_scripts = ["Idris-dev"]
recomputation_vm_memory = 2048 haskell_vm_memory = 4096 recomputation_vm_cpus = 2 vagrantfile_templates_dict = {'python': 'python/python.vagrantfile', 'node_js': 'nodejs/nodejs.vagrantfile', 'cpp': 'cpp/cpp.vagrantfile', 'c++': 'cpp/cpp.vagrantfile', 'c': 'cpp/cpp.vagrantfile', 'haskell': 'haskell/haskell.vagrantfile', 'go': 'go/go.vagrantfile'} languages_version_dict = {'python': '2.7', 'node_js': '0.10'} languages_install_dict = {'python': ['pip install -r requirements.txt'], 'node_js': ['npm install'], 'cpp': ['chmod +x configure', './configure', 'make', 'sudo make install'], 'c++': ['chmod +x configure', './configure', 'make', 'sudo make install'], 'c': ['chmod +x configure', './configure', 'make', 'sudo make install'], 'haskell': ["$VAGRANT_USER 'cabal configure'", "$VAGRANT_USER 'cabal install'"]} boxes_install_scripts = {'gecode': ['echo "export LD_LIBRARY_PATH=/home/vagrant/gecode" >> /home/vagrant/.bashrc', 'source /home/vagrant/.bashrc'], 'Idris-dev': ["$VAGRANT_USER 'sudo cabal configure'", "$VAGRANT_USER 'sudo cabal install'"]} ignore_test_scripts = ['Idris-dev']
def pay(hours,rate) : return hours * rate hours = float(input('Enter Hours:')) rate = float(input('Enter Rate:')) print(pay(hours,rate))
def pay(hours, rate): return hours * rate hours = float(input('Enter Hours:')) rate = float(input('Enter Rate:')) print(pay(hours, rate))
{ "targets": [ { "target_name": "mynanojs", "sources": [ "./src/mynanojs.c", "./src/utility.c", "./src/mybitcoinjs.c" ], "include_dirs":[ "./include", "./include/sodium" ], "libraries": [ "../lib/libnanocrypto1.a", "../lib/libsodium.a" ], } ] }
{'targets': [{'target_name': 'mynanojs', 'sources': ['./src/mynanojs.c', './src/utility.c', './src/mybitcoinjs.c'], 'include_dirs': ['./include', './include/sodium'], 'libraries': ['../lib/libnanocrypto1.a', '../lib/libsodium.a']}]}
#!/usr/bin/python # -*- coding: utf-8 -*- def add(x, y): """Add two numbers together and return the result""" return x + y def subtract(x, y): """Subtract x from y and return result""" return y - x
def add(x, y): """Add two numbers together and return the result""" return x + y def subtract(x, y): """Subtract x from y and return result""" return y - x
input00 = open("input/input00.txt", "r") input01 = open("input/input01.txt", "r") input00_list = input00.read().splitlines() input01_list = input01.read().splitlines() count_elements = int(input00_list[0]) dictionary = {} for i in range(count_elements): str_elements = input00_list[i+1].split() dictionary[str_elements[0]] = [str_elements[1], str_elements[2], str_elements[3]] average = sum(map(int, dictionary[input00_list[count_elements + 1]])) / len(input00_list) print(average) # query_scores = student_marks[query_name] # print("{0:.2f}".format(sum(query_scores) / len(query_scores)))
input00 = open('input/input00.txt', 'r') input01 = open('input/input01.txt', 'r') input00_list = input00.read().splitlines() input01_list = input01.read().splitlines() count_elements = int(input00_list[0]) dictionary = {} for i in range(count_elements): str_elements = input00_list[i + 1].split() dictionary[str_elements[0]] = [str_elements[1], str_elements[2], str_elements[3]] average = sum(map(int, dictionary[input00_list[count_elements + 1]])) / len(input00_list) print(average)
{ "variables": { "library%": "shared_library", "mikmod_dir%": "../libmikmod" }, "target_defaults": { "include_dirs": [ "include", "<(mikmod_dir)/include" ], "defines": [ "HAVE_CONFIG_H" ], "cflags": [ "-Wall", "-finline-functions", "-funroll-loops", "-ffast-math" ], "target_conditions": [ ["OS == 'win'", { "defines": [ "WIN32" ] }], ["OS != 'win'", { "defines": [ "unix" ] }], ["_type == 'shared_library' and OS == 'win'", { "defines": [ "DLL_EXPORTS" ] }], ["_type == 'shared_library' and OS == 'linux'", { "cflags": [ "-fPIC" ] }] ], "default_configuration": "Release", "configurations": { "Debug": { "defines": [ "MIKMOD_DEBUG" ], "cflags": [ "-g3", "-Werror" ], "msvs_settings": { "VCCLCompilerTool": { "RuntimeLibrary": 3 } } }, "Release": { "cflags": [ "-g", "-O2" ], "msvs_settings": { "VCCLCompilerTool": { "RuntimeLibrary": 2 } } } } }, "targets": [ { "target_name": "mikmod", "type": "<(library)", "product_dir": "../../System", "sources": [ "<(mikmod_dir)/drivers/drv_nos.c", "<(mikmod_dir)/drivers/drv_raw.c", "<(mikmod_dir)/drivers/drv_stdout.c", "<(mikmod_dir)/drivers/drv_wav.c", "<(mikmod_dir)/loaders/load_669.c", "<(mikmod_dir)/loaders/load_amf.c", "<(mikmod_dir)/loaders/load_asy.c", "<(mikmod_dir)/loaders/load_dsm.c", "<(mikmod_dir)/loaders/load_far.c", "<(mikmod_dir)/loaders/load_gdm.c", "<(mikmod_dir)/loaders/load_gt2.c", "<(mikmod_dir)/loaders/load_it.c", "<(mikmod_dir)/loaders/load_imf.c", "<(mikmod_dir)/loaders/load_m15.c", "<(mikmod_dir)/loaders/load_med.c", "<(mikmod_dir)/loaders/load_mod.c", "<(mikmod_dir)/loaders/load_mtm.c", "<(mikmod_dir)/loaders/load_okt.c", "<(mikmod_dir)/loaders/load_s3m.c", "<(mikmod_dir)/loaders/load_stm.c", "<(mikmod_dir)/loaders/load_stx.c", "<(mikmod_dir)/loaders/load_ult.c", "<(mikmod_dir)/loaders/load_uni.c", "<(mikmod_dir)/loaders/load_xm.c", "<(mikmod_dir)/mmio/mmalloc.c", "<(mikmod_dir)/mmio/mmerror.c", "<(mikmod_dir)/mmio/mmio.c", "<(mikmod_dir)/playercode/mdriver.c", "<(mikmod_dir)/playercode/mdreg.c", "<(mikmod_dir)/playercode/mdulaw.c", "<(mikmod_dir)/playercode/mloader.c", "<(mikmod_dir)/playercode/mlreg.c", "<(mikmod_dir)/playercode/mlutil.c", "<(mikmod_dir)/playercode/mplayer.c", "<(mikmod_dir)/playercode/munitrk.c", "<(mikmod_dir)/playercode/mwav.c", "<(mikmod_dir)/playercode/npertab.c", "<(mikmod_dir)/playercode/sloader.c", "<(mikmod_dir)/playercode/virtch.c", "<(mikmod_dir)/playercode/virtch2.c", "<(mikmod_dir)/playercode/virtch_common.c" ], "all_dependent_settings": { "include_dirs": [ "include", "<(mikmod_dir)/include" ] }, "conditions": [ ["OS != 'win'", { "libraries": [ "-lm" ] }] ] } ] }
{'variables': {'library%': 'shared_library', 'mikmod_dir%': '../libmikmod'}, 'target_defaults': {'include_dirs': ['include', '<(mikmod_dir)/include'], 'defines': ['HAVE_CONFIG_H'], 'cflags': ['-Wall', '-finline-functions', '-funroll-loops', '-ffast-math'], 'target_conditions': [["OS == 'win'", {'defines': ['WIN32']}], ["OS != 'win'", {'defines': ['unix']}], ["_type == 'shared_library' and OS == 'win'", {'defines': ['DLL_EXPORTS']}], ["_type == 'shared_library' and OS == 'linux'", {'cflags': ['-fPIC']}]], 'default_configuration': 'Release', 'configurations': {'Debug': {'defines': ['MIKMOD_DEBUG'], 'cflags': ['-g3', '-Werror'], 'msvs_settings': {'VCCLCompilerTool': {'RuntimeLibrary': 3}}}, 'Release': {'cflags': ['-g', '-O2'], 'msvs_settings': {'VCCLCompilerTool': {'RuntimeLibrary': 2}}}}}, 'targets': [{'target_name': 'mikmod', 'type': '<(library)', 'product_dir': '../../System', 'sources': ['<(mikmod_dir)/drivers/drv_nos.c', '<(mikmod_dir)/drivers/drv_raw.c', '<(mikmod_dir)/drivers/drv_stdout.c', '<(mikmod_dir)/drivers/drv_wav.c', '<(mikmod_dir)/loaders/load_669.c', '<(mikmod_dir)/loaders/load_amf.c', '<(mikmod_dir)/loaders/load_asy.c', '<(mikmod_dir)/loaders/load_dsm.c', '<(mikmod_dir)/loaders/load_far.c', '<(mikmod_dir)/loaders/load_gdm.c', '<(mikmod_dir)/loaders/load_gt2.c', '<(mikmod_dir)/loaders/load_it.c', '<(mikmod_dir)/loaders/load_imf.c', '<(mikmod_dir)/loaders/load_m15.c', '<(mikmod_dir)/loaders/load_med.c', '<(mikmod_dir)/loaders/load_mod.c', '<(mikmod_dir)/loaders/load_mtm.c', '<(mikmod_dir)/loaders/load_okt.c', '<(mikmod_dir)/loaders/load_s3m.c', '<(mikmod_dir)/loaders/load_stm.c', '<(mikmod_dir)/loaders/load_stx.c', '<(mikmod_dir)/loaders/load_ult.c', '<(mikmod_dir)/loaders/load_uni.c', '<(mikmod_dir)/loaders/load_xm.c', '<(mikmod_dir)/mmio/mmalloc.c', '<(mikmod_dir)/mmio/mmerror.c', '<(mikmod_dir)/mmio/mmio.c', '<(mikmod_dir)/playercode/mdriver.c', '<(mikmod_dir)/playercode/mdreg.c', '<(mikmod_dir)/playercode/mdulaw.c', '<(mikmod_dir)/playercode/mloader.c', '<(mikmod_dir)/playercode/mlreg.c', '<(mikmod_dir)/playercode/mlutil.c', '<(mikmod_dir)/playercode/mplayer.c', '<(mikmod_dir)/playercode/munitrk.c', '<(mikmod_dir)/playercode/mwav.c', '<(mikmod_dir)/playercode/npertab.c', '<(mikmod_dir)/playercode/sloader.c', '<(mikmod_dir)/playercode/virtch.c', '<(mikmod_dir)/playercode/virtch2.c', '<(mikmod_dir)/playercode/virtch_common.c'], 'all_dependent_settings': {'include_dirs': ['include', '<(mikmod_dir)/include']}, 'conditions': [["OS != 'win'", {'libraries': ['-lm']}]]}]}
## # Copyright (c) 2006-2016 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## def parsetoken(text, delimiters=" \t"): if not text: return "", "" if text[0] == '"': return parsequoted(text, delimiters) else: for pos, c in enumerate(text): if c in delimiters: token = text[0:pos] break else: return text, "" return token, lstripdelimiters(text[pos:], delimiters) def parsequoted(text, delimiters=" \t"): assert(text) assert(text[0] == '"') pos = 1 while True: next_pos = text.find('"', pos) if next_pos == -1: return text[1:].replace("\\\\", "\\").replace("\\\"", "\""), "" if text[next_pos - 1] == '\\': pos = next_pos + 1 else: return ( text[1:next_pos].replace("\\\\", "\\").replace("\\\"", "\""), lstripdelimiters(text[next_pos + 1:], delimiters) ) def lstripdelimiters(text, delimiters): for pos, c in enumerate(text): if c not in delimiters: return text[pos:] else: return "" def parseStatusLine(status): status = status.strip() # Must have 'HTTP/1.1' version at start if status[0:9] != "HTTP/1.1 ": return 0 # Must have three digits followed by nothing or one space if not status[9:12].isdigit() or (len(status) > 12 and status[12] != " "): return 0 # Read in the status code return int(status[9:12])
def parsetoken(text, delimiters=' \t'): if not text: return ('', '') if text[0] == '"': return parsequoted(text, delimiters) else: for (pos, c) in enumerate(text): if c in delimiters: token = text[0:pos] break else: return (text, '') return (token, lstripdelimiters(text[pos:], delimiters)) def parsequoted(text, delimiters=' \t'): assert text assert text[0] == '"' pos = 1 while True: next_pos = text.find('"', pos) if next_pos == -1: return (text[1:].replace('\\\\', '\\').replace('\\"', '"'), '') if text[next_pos - 1] == '\\': pos = next_pos + 1 else: return (text[1:next_pos].replace('\\\\', '\\').replace('\\"', '"'), lstripdelimiters(text[next_pos + 1:], delimiters)) def lstripdelimiters(text, delimiters): for (pos, c) in enumerate(text): if c not in delimiters: return text[pos:] else: return '' def parse_status_line(status): status = status.strip() if status[0:9] != 'HTTP/1.1 ': return 0 if not status[9:12].isdigit() or (len(status) > 12 and status[12] != ' '): return 0 return int(status[9:12])
units=int(input("Enter the number of units you used: ")) if(units>=0 and units <= 50): amount = units * 0.50 elif(units <= 150): amount = units * 0.75 elif(units <= 250): amount = units * 1.25 else: amount = units * 1.50 surcharge = amount * 17/100 ebill = amount + surcharge print("Electricity Bill = Rs.",ebill)
units = int(input('Enter the number of units you used: ')) if units >= 0 and units <= 50: amount = units * 0.5 elif units <= 150: amount = units * 0.75 elif units <= 250: amount = units * 1.25 else: amount = units * 1.5 surcharge = amount * 17 / 100 ebill = amount + surcharge print('Electricity Bill = Rs.', ebill)
class matching_matrix_proportion(): def __init__(self, sol, n, * args, **kwargs): self.rows = {i : {int(j):1} for i, j in enumerate(sol)} self.n = n self.k = len(Counter(sol)) self.update_A = {} self.maximums = np.zeros(self.k) self.where = np.zeros(self.k) def merge_rows(self, i_1, i_2, k): if i_1 >= self.n: i_1 = self.update_A.pop(i_1) if i_2 >= self.n: i_2 = self.update_A.pop(i_2) if (len(self.rows[i_1]) >= len(self.rows[i_2]) and i_1 >= self.n and i_2 >= self.n): i_1 , i_2 = i_2, i_1 self.update_A[k + self.n] = i_2 r1, r2 = self.rows.pop(i_1), self.rows[i_2] # If the maximum is moving then update it's location if i_1 in self.where: self.where[np.where(self.where == i_1)] = i_2 for elem in r1: if elem not in r2: r2[elem] = r1[elem] else: value_1 = r1[elem] value_2 = r2[elem] value_new = value_1 + value_2 r2[elem] = value_new if value_new > self.maximums[elem]: self.maximums[elem] = value_new self.where[elem] = i_2 self.rows[i_2] = r2 def to_dense(self): m = len(self.rows) n = self.k M = np.zeros((m, n)) for i, row in enumerate(self.rows): for j, col in self.rows[row].items(): M[i, j] = self.rows[row][j] return(M)
class Matching_Matrix_Proportion: def __init__(self, sol, n, *args, **kwargs): self.rows = {i: {int(j): 1} for (i, j) in enumerate(sol)} self.n = n self.k = len(counter(sol)) self.update_A = {} self.maximums = np.zeros(self.k) self.where = np.zeros(self.k) def merge_rows(self, i_1, i_2, k): if i_1 >= self.n: i_1 = self.update_A.pop(i_1) if i_2 >= self.n: i_2 = self.update_A.pop(i_2) if len(self.rows[i_1]) >= len(self.rows[i_2]) and i_1 >= self.n and (i_2 >= self.n): (i_1, i_2) = (i_2, i_1) self.update_A[k + self.n] = i_2 (r1, r2) = (self.rows.pop(i_1), self.rows[i_2]) if i_1 in self.where: self.where[np.where(self.where == i_1)] = i_2 for elem in r1: if elem not in r2: r2[elem] = r1[elem] else: value_1 = r1[elem] value_2 = r2[elem] value_new = value_1 + value_2 r2[elem] = value_new if value_new > self.maximums[elem]: self.maximums[elem] = value_new self.where[elem] = i_2 self.rows[i_2] = r2 def to_dense(self): m = len(self.rows) n = self.k m = np.zeros((m, n)) for (i, row) in enumerate(self.rows): for (j, col) in self.rows[row].items(): M[i, j] = self.rows[row][j] return M
class Solution: def findNumbers(self, nums: List[int]) -> int: ans = 0 if(len(nums) == 0): return 0 for i in nums: if(len(str(i))%2 == 0): ans+=1; return ans
class Solution: def find_numbers(self, nums: List[int]) -> int: ans = 0 if len(nums) == 0: return 0 for i in nums: if len(str(i)) % 2 == 0: ans += 1 return ans
""" This file contains all the biological constants of Chlamy CCM. -------------------------------------------------------------- """ # ============================================================= # # + Define relevant length scale, time scale, and conc. scale Lnth = 3.14 * pow(10, -6) # Typical length scale; same as the chloroplast radius Time = Lnth * Lnth / pow(10, -9) # Characteristic time for small molecules to diffuse over the # chloroplast assuming diffusion constant ~ 1E-9 m^2/s Conc = 0.001 # Typical concentration 1 mM # ============================================================= # # ============================================================= # # + Passive transport: permeability of different species k_h2co3 = 3 * pow(10, -5) / (Lnth / Time) # permeability of membrane to H2CO3, m/s k_hco3 = 5 * pow(10, -8) / (Lnth / Time) # permeability of membrane to HCO3-, m/s # ============================================================= # # ============================================================= # # + pH and pKa [o] pKa1 = 3.4 # 1st pKa of H2CO3 pH_tub = 6.0 # tubule pH pH_cyt = 7.1 # cytosolic pH pH_chlor = 8.0 # stromal pH pK_eff = 6.1 # effective pKa of CO2 <--> HCO3- conversion # + pH dependent partition factors # The fraction of HCO3- is f / (1+f), and # the fraction of H2CO3 is 1 / (1+f) in a given compartment f_cyt = pow(10, -pKa1 + pH_cyt) f_chlor = pow(10, -pKa1 + pH_chlor) f_tub = pow(10, -pKa1 + pH_tub) # ============================================================= # # ============================================================= # # + Diffusion constant D_c = 1.88 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of CO2 in water, m^2/s D_h = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of HCO3- in water, m^2/s D_h2co3 = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of H2CO3 in water, m^2/s (UPDATE) # for the sum of HCO3- + H2CO3 in each compartment D_h_chlor = f_chlor / (1 + f_chlor) * D_h + 1 / (1 + f_chlor) * D_h2co3 D_h_tub = f_tub / (1 + f_tub) * D_h + 1 / (1 + f_tub) * D_h2co3 # ============================================================= # # ============================================================= # # + Geometry factors R_chlor = 3.14 * pow(10, -6) / Lnth # radius of Chlamy chloroplast R_pyr = 0.3 * R_chlor # radius of Chlamy pyrenoid N_tub = 40 # number of thylkaoid tubules rin = 0.4 * pow(10, -6) / Lnth # radius of the tubule meshwork a_tub = 0.05 * pow(10, -6) / Lnth # cylindrical radius of the thylakoid tubules fv_in = N_tub / 4 * (a_tub / rin)**2 # volume fraction # for plant thylakoid geometry (!) # (optional, assuming a meshwork structure of thylakoids # throughout the chloroplast) fv_plant = 0.35 a_plant = 0.25 * pow(10, -6) / Lnth # ============================================================= # # ============================================================= # # + Rubsico reaction kinetics C_rub = 0.005 # conc. of Rubisco active sites, M kcat = 3.0 # kcat(turnover number) of Rubisco, s^-1 Km_c = 3.0 * pow(10, -5) / Conc # concentration of CO2 that half-maximizes rate of Rubisco Km_o = 15.0 * pow(10, -5) / Conc # concentration of O2 that half-maximizes rate of Rubisco O = 0.00023 / Conc # concentration of O2 in the pyrenoid Vmax = (kcat * C_rub) / (Conc / Time) # maximum velocity of Rubisco carboxylation Km_eff = Km_c * (1 + O / Km_o) # effective Km of Rubisco for CO2 # ============================================================= # # ============================================================= # # + Carbonic anhydrase kinetics v_sp = 0.036 / (1 / Time) # velocity of spontaneous interconversion #kmax_C = 1E4 / (1 / Time) #kmax_H_tub = kmax_C * pow(10, pK_eff - pH_tub) #kmax_H_chlor = kmax_C_lcib * pow(10, pK_eff - pH_chlor) Km_CO2 = 0.005 / Conc # estimates of Km for carbonic anhydrases Km_HCO3 = 0.005 / Conc # ============================================================= # #Km_active_chlor = 0.005 / Conc #Km_active_tub = 0.005 / Conc
""" This file contains all the biological constants of Chlamy CCM. -------------------------------------------------------------- """ lnth = 3.14 * pow(10, -6) time = Lnth * Lnth / pow(10, -9) conc = 0.001 k_h2co3 = 3 * pow(10, -5) / (Lnth / Time) k_hco3 = 5 * pow(10, -8) / (Lnth / Time) p_ka1 = 3.4 p_h_tub = 6.0 p_h_cyt = 7.1 p_h_chlor = 8.0 p_k_eff = 6.1 f_cyt = pow(10, -pKa1 + pH_cyt) f_chlor = pow(10, -pKa1 + pH_chlor) f_tub = pow(10, -pKa1 + pH_tub) d_c = 1.88 * pow(10, -9) / (Lnth * Lnth / Time) d_h = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) d_h2co3 = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) d_h_chlor = f_chlor / (1 + f_chlor) * D_h + 1 / (1 + f_chlor) * D_h2co3 d_h_tub = f_tub / (1 + f_tub) * D_h + 1 / (1 + f_tub) * D_h2co3 r_chlor = 3.14 * pow(10, -6) / Lnth r_pyr = 0.3 * R_chlor n_tub = 40 rin = 0.4 * pow(10, -6) / Lnth a_tub = 0.05 * pow(10, -6) / Lnth fv_in = N_tub / 4 * (a_tub / rin) ** 2 fv_plant = 0.35 a_plant = 0.25 * pow(10, -6) / Lnth c_rub = 0.005 kcat = 3.0 km_c = 3.0 * pow(10, -5) / Conc km_o = 15.0 * pow(10, -5) / Conc o = 0.00023 / Conc vmax = kcat * C_rub / (Conc / Time) km_eff = Km_c * (1 + O / Km_o) v_sp = 0.036 / (1 / Time) km_co2 = 0.005 / Conc km_hco3 = 0.005 / Conc
#! /usr/bin/env python """ RASPA file format and default parameters. """ GENERIC_PSEUDO_ATOMS_HEADER = [ ['# of pseudo atoms'], ['29'], ['#type ', 'print ', 'as ', 'chem ', 'oxidation ', 'mass ', 'charge ', 'polarization ', 'B-factor radii ', 'connectivity ', 'anisotropic ', 'anisotropic-type ', 'tinker-type '] ] GENERIC_PSEUDO_ATOMS = [ ['He ' ,'yes' ,'He' ,'He' ,'0' ,'4.002602' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.0 ' ,'0' ,'0' ,'relative' ,'0'], ['CH4_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'16.04246' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['CH3_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'15.03452' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['CH2_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'14.02658' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['CH_sp3 ' ,'yes' ,'C ' ,'C ' ,'0' ,'13.01864' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['C_sp3 ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['H_h2 ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.468 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['H_com ' ,'no ' ,'H ' ,'H ' ,'0' ,'0.0 ' ,'-0.936 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['C_co2 ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.70 ' ,'0.0' ,'1.0' ,'0.720' ,'0' ,'0' ,'relative' ,'0'], ['O_co2 ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.35 ' ,'0.0' ,'1.0' ,'0.68 ' ,'0' ,'0' ,'relative' ,'0'], ['O_o2 ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.112 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['O_com ' ,'no ' ,'O ' ,'- ' ,'0' ,'0.0 ' ,' 0.224 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['N_n2 ' ,'yes' ,'N ' ,'N ' ,'0' ,'14.00674' ,'-0.4048' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['N_com ' ,'no ' ,'N ' ,'- ' ,'0' ,'0.0 ' ,' 0.8096' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['Ar ' ,'yes' ,'Ar' ,'Ar' ,'0' ,'39.948 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'], ['Ow ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'0.5 ' ,'2' ,'0' ,'relative' ,'0'], ['Hw ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.241 ' ,'0.0' ,'1.0' ,'1.00 ' ,'1' ,'0' ,'relative' ,'0'], ['Lw ' ,'no ' ,'L ' ,'H ' ,'0' ,'0.0 ' ,'-0.241 ' ,'0.0' ,'1.0' ,'1.00 ' ,'1' ,'0' ,'relative' ,'0'], ['C_benz ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,'-0.095 ' ,'0.0' ,'1.0' ,'0.70 ' ,'0' ,'0' ,'relative' ,'0'], ['H_benz ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.095 ' ,'0.0' ,'1.0' ,'0.320' ,'0' ,'0' ,'relative' ,'0'], ['N_dmf ' ,'yes' ,'N ' ,'N ' ,'0' ,'14.00674' ,'-0.57 ' ,'0.0' ,'1.0' ,'0.50 ' ,'0' ,'0' ,'relative' ,'0'], ['Co_dmf ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.45 ' ,'0.0' ,'1.0' ,'0.52 ' ,'0' ,'0' ,'relative' ,'0'], ['Cm_dmf ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.28 ' ,'0.0' ,'1.0' ,'0.52 ' ,'0' ,'0' ,'relative' ,'0'], ['O_dmf ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.50 ' ,'0.0' ,'1.0' ,'0.78 ' ,'0' ,'0' ,'relative' ,'0'], ['H_dmf ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.06 ' ,'0.0' ,'1.0' ,'0.22 ' ,'0' ,'0' ,'relative' ,'0'], ['Na ' ,'yes' ,'Na' ,'Na' ,'0' ,'22.98977' ,' 1.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['Cl ' ,'yes' ,'Cl' ,'Cl' ,'0' ,'35.453 ' ,'-1.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['Kr ' ,'yes' ,'Kr' ,'Kr' ,'0' ,'83.798 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ['Xe ' ,'yes' ,'Xe' ,'Xe' ,'0' ,'131.293 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'], ] GENERIC_FF_MIXING_HEADER = [ ['# general rule for shifted vs truncated '], ['shifted '], ['# general rule tailcorrections '], ['no '], ['# number of defined interactions '], ['55 '], ['# type interaction, parameters. IMPORTANT: define shortest matches first, so that more specific ones overwrites these '], ] GENERIC_FF_MIXING = [ ['He ' , 'lennard-jones' ,'10.9 ' ,'2.64 '], ['CH4_sp3 ' , 'lennard-jones' ,'158.5 ' ,'3.72 '], ['CH3_sp3 ' , 'lennard-jones' ,'108.0 ' ,'3.76 '], ['CH2_sp3 ' , 'lennard-jones' ,'56.0 ' ,'3.96 '], ['CH_sp3 ' , 'lennard-jones' ,'17.0 ' ,'4.67 '], ['C_sp3 ' , 'lennard-jones' ,' 0.8 ' ,'6.38 '], ['H_com ' , 'lennard-jones' ,'36.7 ' ,'2.958 '], ['H_h2 ' , 'none ' ,' ' ,' '], ['O_co2 ' , 'lennard-jones' ,'79.0 ' ,'3.05 '], ['C_co2 ' , 'lennard-jones' ,'27.0 ' ,'2.80 '], ['C_benz ' , 'lennard-jones' ,'30.70 ' ,'3.60 '], ['H_benz ' , 'lennard-jones' ,'25.45 ' ,'2.36 '], ['N_n2 ' , 'lennard-jones' ,'36.0 ' ,'3.31 '], ['N_com ' , 'none ' ,' ' ,' '], ['Ow ' , 'lennard-jones' ,'89.633' ,'3.097 '], ['N_dmf ' , 'lennard-jones' ,'80.0 ' ,'3.2 '], ['Co_dmf ' , 'lennard-jones' ,'50.0 ' ,'3.7 '], ['Cm_dmf ' , 'lennard-jones' ,'80.0 ' ,'3.8 '], ['O_dmf ' , 'lennard-jones' ,'100.0 ' ,'2.96 '], ['H_dmf ' , 'lennard-jones' ,'8.0 ' ,'2.2 '], ['Ar ' , 'lennard-jones' ,'119.8 ' ,'3.34 '], ['Kr ' , 'lennard-jones' ,'166.4 ' ,'3.636 '], ['Xe ' , 'lennard-jones' ,'221.0 ' ,'4.1 '], ] GENERIC_FF_MIXING_FOOTER = [ ['# general mixing rule for Lennard-Jones '], ['Lorentz-Berthelot '], ]
""" RASPA file format and default parameters. """ generic_pseudo_atoms_header = [['# of pseudo atoms'], ['29'], ['#type ', 'print ', 'as ', 'chem ', 'oxidation ', 'mass ', 'charge ', 'polarization ', 'B-factor radii ', 'connectivity ', 'anisotropic ', 'anisotropic-type ', 'tinker-type ']] generic_pseudo_atoms = [['He ', 'yes', 'He', 'He', '0', '4.002602', ' 0.0 ', '0.0', '1.0', '1.0 ', '0', '0', 'relative', '0'], ['CH4_sp3', 'yes', 'C ', 'C ', '0', '16.04246', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['CH3_sp3', 'yes', 'C ', 'C ', '0', '15.03452', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['CH2_sp3', 'yes', 'C ', 'C ', '0', '14.02658', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['CH_sp3 ', 'yes', 'C ', 'C ', '0', '13.01864', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['C_sp3 ', 'yes', 'C ', 'C ', '0', '12.0 ', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['H_h2 ', 'yes', 'H ', 'H ', '0', '1.00794 ', ' 0.468 ', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['H_com ', 'no ', 'H ', 'H ', '0', '0.0 ', '-0.936 ', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['C_co2 ', 'yes', 'C ', 'C ', '0', '12.0 ', ' 0.70 ', '0.0', '1.0', '0.720', '0', '0', 'relative', '0'], ['O_co2 ', 'yes', 'O ', 'O ', '0', '15.9994 ', '-0.35 ', '0.0', '1.0', '0.68 ', '0', '0', 'relative', '0'], ['O_o2 ', 'yes', 'O ', 'O ', '0', '15.9994 ', '-0.112 ', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['O_com ', 'no ', 'O ', '- ', '0', '0.0 ', ' 0.224 ', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['N_n2 ', 'yes', 'N ', 'N ', '0', '14.00674', '-0.4048', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['N_com ', 'no ', 'N ', '- ', '0', '0.0 ', ' 0.8096', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['Ar ', 'yes', 'Ar', 'Ar', '0', '39.948 ', ' 0.0 ', '0.0', '1.0', '0.7 ', '0', '0', 'relative', '0'], ['Ow ', 'yes', 'O ', 'O ', '0', '15.9994 ', ' 0.0 ', '0.0', '1.0', '0.5 ', '2', '0', 'relative', '0'], ['Hw ', 'yes', 'H ', 'H ', '0', '1.00794 ', ' 0.241 ', '0.0', '1.0', '1.00 ', '1', '0', 'relative', '0'], ['Lw ', 'no ', 'L ', 'H ', '0', '0.0 ', '-0.241 ', '0.0', '1.0', '1.00 ', '1', '0', 'relative', '0'], ['C_benz ', 'yes', 'C ', 'C ', '0', '12.0 ', '-0.095 ', '0.0', '1.0', '0.70 ', '0', '0', 'relative', '0'], ['H_benz ', 'yes', 'H ', 'H ', '0', '1.00794 ', ' 0.095 ', '0.0', '1.0', '0.320', '0', '0', 'relative', '0'], ['N_dmf ', 'yes', 'N ', 'N ', '0', '14.00674', '-0.57 ', '0.0', '1.0', '0.50 ', '0', '0', 'relative', '0'], ['Co_dmf ', 'yes', 'C ', 'C ', '0', '12.0 ', ' 0.45 ', '0.0', '1.0', '0.52 ', '0', '0', 'relative', '0'], ['Cm_dmf ', 'yes', 'C ', 'C ', '0', '12.0 ', ' 0.28 ', '0.0', '1.0', '0.52 ', '0', '0', 'relative', '0'], ['O_dmf ', 'yes', 'O ', 'O ', '0', '15.9994 ', '-0.50 ', '0.0', '1.0', '0.78 ', '0', '0', 'relative', '0'], ['H_dmf ', 'yes', 'H ', 'H ', '0', '1.00794 ', ' 0.06 ', '0.0', '1.0', '0.22 ', '0', '0', 'relative', '0'], ['Na ', 'yes', 'Na', 'Na', '0', '22.98977', ' 1.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['Cl ', 'yes', 'Cl', 'Cl', '0', '35.453 ', '-1.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['Kr ', 'yes', 'Kr', 'Kr', '0', '83.798 ', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0'], ['Xe ', 'yes', 'Xe', 'Xe', '0', '131.293 ', ' 0.0 ', '0.0', '1.0', '1.00 ', '0', '0', 'relative', '0']] generic_ff_mixing_header = [['# general rule for shifted vs truncated '], ['shifted '], ['# general rule tailcorrections '], ['no '], ['# number of defined interactions '], ['55 '], ['# type interaction, parameters. IMPORTANT: define shortest matches first, so that more specific ones overwrites these ']] generic_ff_mixing = [['He ', 'lennard-jones', '10.9 ', '2.64 '], ['CH4_sp3 ', 'lennard-jones', '158.5 ', '3.72 '], ['CH3_sp3 ', 'lennard-jones', '108.0 ', '3.76 '], ['CH2_sp3 ', 'lennard-jones', '56.0 ', '3.96 '], ['CH_sp3 ', 'lennard-jones', '17.0 ', '4.67 '], ['C_sp3 ', 'lennard-jones', ' 0.8 ', '6.38 '], ['H_com ', 'lennard-jones', '36.7 ', '2.958 '], ['H_h2 ', 'none ', ' ', ' '], ['O_co2 ', 'lennard-jones', '79.0 ', '3.05 '], ['C_co2 ', 'lennard-jones', '27.0 ', '2.80 '], ['C_benz ', 'lennard-jones', '30.70 ', '3.60 '], ['H_benz ', 'lennard-jones', '25.45 ', '2.36 '], ['N_n2 ', 'lennard-jones', '36.0 ', '3.31 '], ['N_com ', 'none ', ' ', ' '], ['Ow ', 'lennard-jones', '89.633', '3.097 '], ['N_dmf ', 'lennard-jones', '80.0 ', '3.2 '], ['Co_dmf ', 'lennard-jones', '50.0 ', '3.7 '], ['Cm_dmf ', 'lennard-jones', '80.0 ', '3.8 '], ['O_dmf ', 'lennard-jones', '100.0 ', '2.96 '], ['H_dmf ', 'lennard-jones', '8.0 ', '2.2 '], ['Ar ', 'lennard-jones', '119.8 ', '3.34 '], ['Kr ', 'lennard-jones', '166.4 ', '3.636 '], ['Xe ', 'lennard-jones', '221.0 ', '4.1 ']] generic_ff_mixing_footer = [['# general mixing rule for Lennard-Jones '], ['Lorentz-Berthelot ']]
class Store: def __init__(self): self.store_item = [] def __str__(self): if self.store_item == []: return 'No items' return '\n'.join(map(str,self.store_item)) def add_item(self,item): self.store_item.append(item) def count(self): return len(self.store_item) def filter(self, q_object): store_obj = Store() for items in self.store_item: field_name = q_object.field if q_object.operation == 'EQ' and getattr(items,field_name) == q_object.value: store_obj.add_item(items) elif q_object.operation == 'GT' and getattr(items,field_name) > q_object.value: store_obj.add_item(items) elif q_object.operation == 'GTE' and getattr(items,field_name) >= q_object.value: store_obj.add_item(items) elif q_object.operation == 'LT' and getattr(items,field_name) < q_object.value: store_obj.add_item(items) elif q_object.operation == 'LTE' and getattr(items,field_name) <= q_object.value: store_obj.add_item(items) elif (q_object.operation == 'CONTAINS' or q_object.operation == 'STARTS_WITH' or q_object.operation== 'ENDS_WITH') and q_object.value in getattr(items,field_name): store_obj.add_item(items) elif q_object.operation == 'IN' and getattr(items,field_name) in q_object.value: store_obj.add_item(items) return store_obj def exclude(self, q_object): exclude_obj = Store() include_obj = self.filter(q_object) for items in self.store_item: if items not in include_obj.store_item: exclude_obj.add_item(items) return exclude_obj class Item: def __init__(self, name=None, price=0, category=None): self._name = name self._price = price self._category = category #raise error for value if price <= 0: raise ValueError('Invalid value for price, got {}'.format(price)) @property def name(self): return self._name @property def price(self): return self._price @property def category(self): return self._category def __str__(self): return f'{self._name}@{self._price}-{self._category}' class Query: valid_op = ['IN','EQ','GT','GTE','LT','LTE','STARTS_WITH','ENDS_WITH','CONTAINS'] def __init__(self, field=None, operation=None, value=None): self.field = field self.operation = operation self.value = value if operation not in Query.valid_op: raise ValueError('Invalid value for operation, got {}'.format(operation)) def __str__(self): return f"{self.field} {self.operation} {self.value}"
class Store: def __init__(self): self.store_item = [] def __str__(self): if self.store_item == []: return 'No items' return '\n'.join(map(str, self.store_item)) def add_item(self, item): self.store_item.append(item) def count(self): return len(self.store_item) def filter(self, q_object): store_obj = store() for items in self.store_item: field_name = q_object.field if q_object.operation == 'EQ' and getattr(items, field_name) == q_object.value: store_obj.add_item(items) elif q_object.operation == 'GT' and getattr(items, field_name) > q_object.value: store_obj.add_item(items) elif q_object.operation == 'GTE' and getattr(items, field_name) >= q_object.value: store_obj.add_item(items) elif q_object.operation == 'LT' and getattr(items, field_name) < q_object.value: store_obj.add_item(items) elif q_object.operation == 'LTE' and getattr(items, field_name) <= q_object.value: store_obj.add_item(items) elif (q_object.operation == 'CONTAINS' or q_object.operation == 'STARTS_WITH' or q_object.operation == 'ENDS_WITH') and q_object.value in getattr(items, field_name): store_obj.add_item(items) elif q_object.operation == 'IN' and getattr(items, field_name) in q_object.value: store_obj.add_item(items) return store_obj def exclude(self, q_object): exclude_obj = store() include_obj = self.filter(q_object) for items in self.store_item: if items not in include_obj.store_item: exclude_obj.add_item(items) return exclude_obj class Item: def __init__(self, name=None, price=0, category=None): self._name = name self._price = price self._category = category if price <= 0: raise value_error('Invalid value for price, got {}'.format(price)) @property def name(self): return self._name @property def price(self): return self._price @property def category(self): return self._category def __str__(self): return f'{self._name}@{self._price}-{self._category}' class Query: valid_op = ['IN', 'EQ', 'GT', 'GTE', 'LT', 'LTE', 'STARTS_WITH', 'ENDS_WITH', 'CONTAINS'] def __init__(self, field=None, operation=None, value=None): self.field = field self.operation = operation self.value = value if operation not in Query.valid_op: raise value_error('Invalid value for operation, got {}'.format(operation)) def __str__(self): return f'{self.field} {self.operation} {self.value}'
def add(x, y): """Sum two numbers""" return x + y def subtract(x, y): """Subtract two numbers""" return x - y
def add(x, y): """Sum two numbers""" return x + y def subtract(x, y): """Subtract two numbers""" return x - y
""" # Why we use for else condition ? # For checking the specific number or checking the condition is true # if the condition is false we just print single line in else condition. """ # To check whether the given number is divisible by 5 then print the number # if it's not then print "Given is not divisible by 5" nums = [34, 53, 32, 20, 39] for num in nums: if num % 5 == 0: print(num) break # If condition is True it's break the loop # print else part, after the condition is false else: print("Given number is not divisible by 5")
""" # Why we use for else condition ? # For checking the specific number or checking the condition is true # if the condition is false we just print single line in else condition. """ nums = [34, 53, 32, 20, 39] for num in nums: if num % 5 == 0: print(num) break else: print('Given number is not divisible by 5')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 22 10:26:43 2018 @author: francisco """ #1) if 6 > 7: print("Yep") # Answer: Blank # Since 6 is not greater than 7, it doesn't print anything and it doesn't have any # more conditionals to evalutate. #2) if 6 > 7: print("Yep") else: print("Nope") #Answer: Nope #Same as previous exercise, only this time we have an else statement. So the else statement gets executed. #3) var = 'Panda' if var == "panda": print("Cute!") elif var == "Panda": print("Regal!") else: print("Ugly...") #Answer: Regal! # Strings in Python are case sensitive, the first condition compares 'Panda' with # 'panda', thus they're not the same, so we pass on to the next conditional # this one compares 'Panda' with 'Panda' and they're the same so the code inside # is executed #4) temp = 120 if temp > 85: print("Hot") elif temp > 100: print("REALLY HOT!") elif temp > 60: print("Comfortable") else: print("Cold") #Answer: Hot # Conditionals are evaluated in order, in this case the first conditions says # if temp is greater than 85, since it is the conditional ends and the rest # isn't evaluated. That's why it prints hot and not REALLY HOT! #5) temp = 50 if temp > 85: print("Hot") elif temp > 100: print("REALLY HOT!") elif temp > 60: print("Comfortable") else: print("Cold") # The value of temp is 50 and the 3 conditions compares if temp is greater than # 85, 100 and 60, 50 is not greater than any of them so each condition returns # false so the code inside the else statement is the one that gets executed
""" Created on Tue May 22 10:26:43 2018 @author: francisco """ if 6 > 7: print('Yep') if 6 > 7: print('Yep') else: print('Nope') var = 'Panda' if var == 'panda': print('Cute!') elif var == 'Panda': print('Regal!') else: print('Ugly...') temp = 120 if temp > 85: print('Hot') elif temp > 100: print('REALLY HOT!') elif temp > 60: print('Comfortable') else: print('Cold') temp = 50 if temp > 85: print('Hot') elif temp > 100: print('REALLY HOT!') elif temp > 60: print('Comfortable') else: print('Cold')
class A: def __init__(self, *, kw_only, optional_kw_only=None): pass class B(A): def __init__(self, *, kw_only): super().__init__(kw_only=kw_only)
class A: def __init__(self, *, kw_only, optional_kw_only=None): pass class B(A): def __init__(self, *, kw_only): super().__init__(kw_only=kw_only)
''' Problem description: Given an array of unsorted integers, find the smallest positive integer not in the array. ''' def find_smallest_missing_pos_int_sort(array): ''' runtime: O(nlogn) space : O(1) - this depends on the sort but python's list.sort() performs an in-place sort This sort-based solution is slow but requires no additional space, given the right sorting algorithm. ''' array.sort() n = len(array) # move to index of first positive integer; if none exist, return 1 index_of_first_pos = 0 for index_of_first_pos in xrange(n): if array[index_of_first_pos] > 0: break current_pos_int = 1 for i in xrange(index_of_first_pos, n): if array[i] != current_pos_int: return current_pos_int current_pos_int += 1 return current_pos_int def find_smallest_missing_pos_int_set(array): ''' runtime: O(n) space : O(n) This set-based solution is fast and readable but requires linear additional space. ''' as_set = set(array) n = len(array) for x in xrange(1, n + 1): if x not in as_set: return x return n + 1 def find_smallest_missing_pos_int_optimal(array): ''' runtime: O(n) space : O(1) This in-place swap solution runs in linear time and requires constant space. Aside from some constant-factor performance optimizations, this is the optimal solution. ''' n = len(array) def in_bounds(value): return 1 <= value <= n # swap integers within 1 to n into their respective cells # all other values (x < 1, x > n, and repeats) end up in the remaining empty cells for i in xrange(n): while in_bounds(array[i]) and array[i] != i + 1 and array[array[i] - 1] != array[i]: swap_cell = array[i] - 1 array[i], array[swap_cell] = array[swap_cell], array[i] for i in xrange(n): if array[i] != i + 1: return i + 1 return n + 1
""" Problem description: Given an array of unsorted integers, find the smallest positive integer not in the array. """ def find_smallest_missing_pos_int_sort(array): """ runtime: O(nlogn) space : O(1) - this depends on the sort but python's list.sort() performs an in-place sort This sort-based solution is slow but requires no additional space, given the right sorting algorithm. """ array.sort() n = len(array) index_of_first_pos = 0 for index_of_first_pos in xrange(n): if array[index_of_first_pos] > 0: break current_pos_int = 1 for i in xrange(index_of_first_pos, n): if array[i] != current_pos_int: return current_pos_int current_pos_int += 1 return current_pos_int def find_smallest_missing_pos_int_set(array): """ runtime: O(n) space : O(n) This set-based solution is fast and readable but requires linear additional space. """ as_set = set(array) n = len(array) for x in xrange(1, n + 1): if x not in as_set: return x return n + 1 def find_smallest_missing_pos_int_optimal(array): """ runtime: O(n) space : O(1) This in-place swap solution runs in linear time and requires constant space. Aside from some constant-factor performance optimizations, this is the optimal solution. """ n = len(array) def in_bounds(value): return 1 <= value <= n for i in xrange(n): while in_bounds(array[i]) and array[i] != i + 1 and (array[array[i] - 1] != array[i]): swap_cell = array[i] - 1 (array[i], array[swap_cell]) = (array[swap_cell], array[i]) for i in xrange(n): if array[i] != i + 1: return i + 1 return n + 1
class Crawler: def __init__(self, root): self._root = root def crawl(self): pass def crawl_into(self): pass
class Crawler: def __init__(self, root): self._root = root def crawl(self): pass def crawl_into(self): pass
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def buildbuddy_deps(): maybe( http_archive, name = "rules_cc", sha256 = "b6f34b3261ec02f85dbc5a8bdc9414ce548e1f5f67e000d7069571799cb88b25", strip_prefix = "rules_cc-726dd8157557f1456b3656e26ab21a1646653405", urls = ["https://github.com/bazelbuild/rules_cc/archive/726dd8157557f1456b3656e26ab21a1646653405.tar.gz"], )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe') def buildbuddy_deps(): maybe(http_archive, name='rules_cc', sha256='b6f34b3261ec02f85dbc5a8bdc9414ce548e1f5f67e000d7069571799cb88b25', strip_prefix='rules_cc-726dd8157557f1456b3656e26ab21a1646653405', urls=['https://github.com/bazelbuild/rules_cc/archive/726dd8157557f1456b3656e26ab21a1646653405.tar.gz'])
def TP(target, prediction): """ True positives. :param target: target value :param prediction: prediction value :return: """ return (target.float() * prediction.float().round()).sum() def TN(target, prediction): """ True negatives. :param target: target value :param prediction: prediction value :return: """ return ((target == 0).float() * (prediction.float().round() == 0).float()).sum() def FP(target, prediction): """ False positives. :param target: target value :param prediction: prediction value :return: """ return ((target == 0).float() * prediction.float().round()).sum() def FN(target, prediction): """ False negatives. :param target: target value :param prediction: prediction value :return: """ return (target.float() * (prediction.float().round() == 0).float()).sum() def TPR(target, prediction, eps=1e-7): """ True positive rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = TP(target, prediction) fn = FN(target, prediction) s = tp + fn + eps return tp / s def TNR(target, prediction, eps=1e-7): """ True negative rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tn = TN(target, prediction) fp = FP(target, prediction) s = (tn + fp + eps) assert (s > 0) return tn / s def FPR(target, prediction, eps=1e-7): """ False positive rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ fp = FP(target, prediction) tn = TN(target, prediction) s = fp + tn + eps assert (s > 0) return fp / s def FNR(target, prediction, eps=1e-7): """ False negative rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ fn = FN(target, prediction) tp = TP(target, prediction) s = fn + tp + eps assert (s > 0) return fn / s def ACC(target, prediction, eps=1e-7): """ Accuracy metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = TP(target, prediction) tn = TN(target, prediction) p = target.sum().float() n = (target == 0).sum().float() s = p + n + eps assert (s > 0) return (tp + tn) / s def BACC(target, prediction, eps=1e-7): """ Balanced accuracy metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = TP(target, prediction) tn = TN(target, prediction) p = target.sum().float() n = (target == 0).sum().float() s = (p + eps) + tn / (n + eps) assert (s > 0) return 0.5 * (tp / s) def precision(target, prediction, eps=1e-7): """ Precision metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = TP(target, prediction) fp = FP(target, prediction) s = (tp + fp + eps) assert (s > 0) return tp / s def recall(target, prediction, eps=1e-7): """ Recall metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = TP(target, prediction) fn = FN(target, prediction) s = (tp + fn + eps) assert (s > 0) return tp / s def f1_score(target, prediction, eps=1e-7): """ F1-score metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ precision_ = precision(target, prediction) recall_ = recall(target, prediction) n = (precision_ * recall_) s = (precision_ + recall_ + eps) assert (s > 0) return 2 * (n / s)
def tp(target, prediction): """ True positives. :param target: target value :param prediction: prediction value :return: """ return (target.float() * prediction.float().round()).sum() def tn(target, prediction): """ True negatives. :param target: target value :param prediction: prediction value :return: """ return ((target == 0).float() * (prediction.float().round() == 0).float()).sum() def fp(target, prediction): """ False positives. :param target: target value :param prediction: prediction value :return: """ return ((target == 0).float() * prediction.float().round()).sum() def fn(target, prediction): """ False negatives. :param target: target value :param prediction: prediction value :return: """ return (target.float() * (prediction.float().round() == 0).float()).sum() def tpr(target, prediction, eps=1e-07): """ True positive rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = tp(target, prediction) fn = fn(target, prediction) s = tp + fn + eps return tp / s def tnr(target, prediction, eps=1e-07): """ True negative rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tn = tn(target, prediction) fp = fp(target, prediction) s = tn + fp + eps assert s > 0 return tn / s def fpr(target, prediction, eps=1e-07): """ False positive rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ fp = fp(target, prediction) tn = tn(target, prediction) s = fp + tn + eps assert s > 0 return fp / s def fnr(target, prediction, eps=1e-07): """ False negative rate metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ fn = fn(target, prediction) tp = tp(target, prediction) s = fn + tp + eps assert s > 0 return fn / s def acc(target, prediction, eps=1e-07): """ Accuracy metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = tp(target, prediction) tn = tn(target, prediction) p = target.sum().float() n = (target == 0).sum().float() s = p + n + eps assert s > 0 return (tp + tn) / s def bacc(target, prediction, eps=1e-07): """ Balanced accuracy metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = tp(target, prediction) tn = tn(target, prediction) p = target.sum().float() n = (target == 0).sum().float() s = p + eps + tn / (n + eps) assert s > 0 return 0.5 * (tp / s) def precision(target, prediction, eps=1e-07): """ Precision metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = tp(target, prediction) fp = fp(target, prediction) s = tp + fp + eps assert s > 0 return tp / s def recall(target, prediction, eps=1e-07): """ Recall metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ tp = tp(target, prediction) fn = fn(target, prediction) s = tp + fn + eps assert s > 0 return tp / s def f1_score(target, prediction, eps=1e-07): """ F1-score metric. :param target: target value :param prediction: prediction value :param eps: epsilon to avoid zero division :return: """ precision_ = precision(target, prediction) recall_ = recall(target, prediction) n = precision_ * recall_ s = precision_ + recall_ + eps assert s > 0 return 2 * (n / s)
# The @npm packages at the root node_modules are used by integration tests # with `file:../../node_modules/foobar` references NPM_PACKAGE_ARCHIVES = [ "@angular/animations-12", "@angular/common-12", "@angular/core-12", "@angular/forms-12", "@angular/platform-browser-12", "@angular/platform-browser-dynamic-12", "@angular/platform-server-12", "@angular/router-12", "@babel/core", "@rollup/plugin-babel", "@rollup/plugin-node-resolve", "@rollup/plugin-commonjs", "check-side-effects", "core-js", "google-closure-compiler", "jasmine", "typescript", "rxjs", "systemjs", "tsickle", "tslib", "protractor", "terser", "rollup", "rollup-plugin-sourcemaps", "@angular/cli", "@angular-devkit/build-angular", "@bazel/bazelisk", "@types/jasmine", "@types/jasminewd2", "@types/node", ] def npm_package_archive_label(package_name): return package_name.replace("/", "_").replace("@", "") + "_archive" def npm_package_archives(): """Function to generate pkg_tar definitions for WORKSPACE yarn_install manual_build_file_contents""" npm_packages_to_archive = NPM_PACKAGE_ARCHIVES result = """load("@rules_pkg//:pkg.bzl", "pkg_tar") """ for name in npm_packages_to_archive: label_name = npm_package_archive_label(name) last_segment_name = name.split("/")[-1] result += """pkg_tar( name = "{label_name}", srcs = ["//{name}:{last_segment_name}__all_files"], extension = "tar.gz", strip_prefix = "/external/npm/node_modules/{name}", # should not be built unless it is a dependency of another rule tags = ["manual"], ) """.format(name = name, label_name = label_name, last_segment_name = last_segment_name) return result
npm_package_archives = ['@angular/animations-12', '@angular/common-12', '@angular/core-12', '@angular/forms-12', '@angular/platform-browser-12', '@angular/platform-browser-dynamic-12', '@angular/platform-server-12', '@angular/router-12', '@babel/core', '@rollup/plugin-babel', '@rollup/plugin-node-resolve', '@rollup/plugin-commonjs', 'check-side-effects', 'core-js', 'google-closure-compiler', 'jasmine', 'typescript', 'rxjs', 'systemjs', 'tsickle', 'tslib', 'protractor', 'terser', 'rollup', 'rollup-plugin-sourcemaps', '@angular/cli', '@angular-devkit/build-angular', '@bazel/bazelisk', '@types/jasmine', '@types/jasminewd2', '@types/node'] def npm_package_archive_label(package_name): return package_name.replace('/', '_').replace('@', '') + '_archive' def npm_package_archives(): """Function to generate pkg_tar definitions for WORKSPACE yarn_install manual_build_file_contents""" npm_packages_to_archive = NPM_PACKAGE_ARCHIVES result = 'load("@rules_pkg//:pkg.bzl", "pkg_tar")\n' for name in npm_packages_to_archive: label_name = npm_package_archive_label(name) last_segment_name = name.split('/')[-1] result += 'pkg_tar(\n name = "{label_name}",\n srcs = ["//{name}:{last_segment_name}__all_files"],\n extension = "tar.gz",\n strip_prefix = "/external/npm/node_modules/{name}",\n # should not be built unless it is a dependency of another rule\n tags = ["manual"],\n)\n'.format(name=name, label_name=label_name, last_segment_name=last_segment_name) return result
# Copyright (C) 2016 Benoit Myard <myardbenoit@gmail.com> # Released under the terms of the BSD license. class BaseRemoteStorage(object): def __init__(self, config, root): self.config = config self.root = root def __enter__(self): raise NotImplementedError def __exit__(self, *args): pass def push(self, filename): raise NotImplementedError def pull(self, path): raise NotImplementedError
class Baseremotestorage(object): def __init__(self, config, root): self.config = config self.root = root def __enter__(self): raise NotImplementedError def __exit__(self, *args): pass def push(self, filename): raise NotImplementedError def pull(self, path): raise NotImplementedError
get_f = float(input("Enter temperature in Fahrenheit: ")) convert_c = (get_f - 32) * 5/9 print(f"{get_f} in Fahrenheit is equal to {convert_c} in Celsius")
get_f = float(input('Enter temperature in Fahrenheit: ')) convert_c = (get_f - 32) * 5 / 9 print(f'{get_f} in Fahrenheit is equal to {convert_c} in Celsius')
#!/usr/bin/env python # coding: utf-8 # # Exercise 1. Regex and Parsing challenges : # ### writer : Faranak Alikhah 1954128 # ### 14.Regex Substitution : # In[ ]: for _ in range(int(input())): line = input() while '&&'in line or '||'in line: line = line.replace("&&", "and").replace("||", "or") print(line) # #
for _ in range(int(input())): line = input() while '&&' in line or '||' in line: line = line.replace('&&', 'and').replace('||', 'or') print(line)
def is_valid_story_or_comment(form_data): parent = form_data.get('parent') title = bool(form_data.get('title')) url = bool(form_data.get('url')) text = bool(form_data.get('text')) if parent: if title or url: return (False, 'Invalid fields for a comment') if not text: return (False, 'Comment field is missing') else: if not title: return (False, 'Missing title field') if text and url: return (False, 'Please enter either URL or text, but not both') return (True, 'success')
def is_valid_story_or_comment(form_data): parent = form_data.get('parent') title = bool(form_data.get('title')) url = bool(form_data.get('url')) text = bool(form_data.get('text')) if parent: if title or url: return (False, 'Invalid fields for a comment') if not text: return (False, 'Comment field is missing') else: if not title: return (False, 'Missing title field') if text and url: return (False, 'Please enter either URL or text, but not both') return (True, 'success')
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, values = []): self.head = None for value in values: self.append(value) def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def search(self, value): if self.head is None: return False node = self.head while node: if node.value == value: return True node = node.next return False def delete(self, value): if self.head is None: return if self.head.value == value: self.head = self.head.next return node = self.head while node.next: if node.next.value == value: node.next = node.next.next return node = node.next def pop(self): if self.head is None: return None node = self.head self.head = self.head.next return node.value def to_list(self): out = [] node = self.head while node is not None: out.append(node.value) node = node.next return out # Test Case linked_list = LinkedList([5, 7, -1, 0.9, 71]) print("Linked List tests:") print (" Initialization: " + "Pass" if (linked_list.to_list() == [5, 7, -1, 0.9, 71]) else "Fail") linked_list.delete(-1) print (" Delete: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71]) else "Fail") print (" Search: " + "Pass" if (linked_list.search(0.9)) else "Fail") print (" Search: " + "Pass" if (not linked_list.search(55)) else "Fail") linked_list.append(91) print (" Append: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71, 91]) else "Fail") print (" Pop: " + "Pass" if (linked_list.pop() == 5) else "Fail")
class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: def __init__(self, values=[]): self.head = None for value in values: self.append(value) def append(self, value): if self.head is None: self.head = node(value) return node = self.head while node.next: node = node.next node.next = node(value) def search(self, value): if self.head is None: return False node = self.head while node: if node.value == value: return True node = node.next return False def delete(self, value): if self.head is None: return if self.head.value == value: self.head = self.head.next return node = self.head while node.next: if node.next.value == value: node.next = node.next.next return node = node.next def pop(self): if self.head is None: return None node = self.head self.head = self.head.next return node.value def to_list(self): out = [] node = self.head while node is not None: out.append(node.value) node = node.next return out linked_list = linked_list([5, 7, -1, 0.9, 71]) print('Linked List tests:') print(' Initialization: ' + 'Pass' if linked_list.to_list() == [5, 7, -1, 0.9, 71] else 'Fail') linked_list.delete(-1) print(' Delete: ' + 'Pass' if linked_list.to_list() == [5, 7, 0.9, 71] else 'Fail') print(' Search: ' + 'Pass' if linked_list.search(0.9) else 'Fail') print(' Search: ' + 'Pass' if not linked_list.search(55) else 'Fail') linked_list.append(91) print(' Append: ' + 'Pass' if linked_list.to_list() == [5, 7, 0.9, 71, 91] else 'Fail') print(' Pop: ' + 'Pass' if linked_list.pop() == 5 else 'Fail')
""" A Symbol in a pushdown automaton """ class Symbol: """ A Symbol in a pushdown automaton Parameters ---------- value : any The value of the state """ def __init__(self, value): self._value = value def __hash__(self): return hash(str(self._value)) @property def value(self): """ Returns the value of the symbol Returns ---------- value: The value any """ return self._value def __eq__(self, other): if isinstance(other, Symbol): return self._value == other.value return False def __repr__(self): return "Symbol(" + str(self._value) + ")"
""" A Symbol in a pushdown automaton """ class Symbol: """ A Symbol in a pushdown automaton Parameters ---------- value : any The value of the state """ def __init__(self, value): self._value = value def __hash__(self): return hash(str(self._value)) @property def value(self): """ Returns the value of the symbol Returns ---------- value: The value any """ return self._value def __eq__(self, other): if isinstance(other, Symbol): return self._value == other.value return False def __repr__(self): return 'Symbol(' + str(self._value) + ')'
loss_fns = ['retrain_regu_mas', 'retrain_regu_mine', 'retrain_regu_minen', 'retrain_regu_fisher', 'retrain_regu_fishern',\ 'retrain', 'retrain_regu', 'retrain_regu_selfless']#'retrain_regu_mine3', 'cnn' model_log_map = {'fishern': 'EWCN', 'mine': 'Arms', 'minen': 'ArmsN', 'regu': 'RetrainRegu', \ 'fisher': 'EWC', 'mas': 'MAS', 'selfless': 'Selfless', 'retrain':'Retrain'}
loss_fns = ['retrain_regu_mas', 'retrain_regu_mine', 'retrain_regu_minen', 'retrain_regu_fisher', 'retrain_regu_fishern', 'retrain', 'retrain_regu', 'retrain_regu_selfless'] model_log_map = {'fishern': 'EWCN', 'mine': 'Arms', 'minen': 'ArmsN', 'regu': 'RetrainRegu', 'fisher': 'EWC', 'mas': 'MAS', 'selfless': 'Selfless', 'retrain': 'Retrain'}
def digit_to_text(digit): if digit == 1: return "one" elif digit == 2: return "two" elif digit == 3: return "three" elif digit == 4: return "four" elif digit == 5: return "five" elif digit == 6: return "six" elif digit == 7: return "seven" elif digit == 8: return "eight" elif digit == 9: return "nine" else: return None def teen_to_text(digit): if digit == 1: return "ten" elif digit == 11: return "eleven" elif digit == 12: return "twelve" elif digit == 13: return "thirteen" elif digit == 14: return "fourteen" elif digit == 15: return "fifteen" elif digit == 16: return "sixteen" elif digit == 17: return "seventeen" elif digit == 18: return "eighteen" elif digit == 19: return "nineteen" else: return None def convert_to_text(num): text = "" hundreds = num // 100 tens = num // 10 if hundreds: text += digit_to_text(hundreds) + " hundred" if tens: if tens == 1: if num > 100: real_ten = real_ten - (hundreds * 100) else: real_ten = num text += teen_to_text(real_ten) return text print(convert_to_text(1)) print(convert_to_text(11)) print(convert_to_text(16)) print(convert_to_text(22))
def digit_to_text(digit): if digit == 1: return 'one' elif digit == 2: return 'two' elif digit == 3: return 'three' elif digit == 4: return 'four' elif digit == 5: return 'five' elif digit == 6: return 'six' elif digit == 7: return 'seven' elif digit == 8: return 'eight' elif digit == 9: return 'nine' else: return None def teen_to_text(digit): if digit == 1: return 'ten' elif digit == 11: return 'eleven' elif digit == 12: return 'twelve' elif digit == 13: return 'thirteen' elif digit == 14: return 'fourteen' elif digit == 15: return 'fifteen' elif digit == 16: return 'sixteen' elif digit == 17: return 'seventeen' elif digit == 18: return 'eighteen' elif digit == 19: return 'nineteen' else: return None def convert_to_text(num): text = '' hundreds = num // 100 tens = num // 10 if hundreds: text += digit_to_text(hundreds) + ' hundred' if tens: if tens == 1: if num > 100: real_ten = real_ten - hundreds * 100 else: real_ten = num text += teen_to_text(real_ten) return text print(convert_to_text(1)) print(convert_to_text(11)) print(convert_to_text(16)) print(convert_to_text(22))
def get_schema(): return { 'type': 'object', 'properties': { 'aftale_id': {'type': 'string'}, 'state': {'type': 'string'}, 'gateway_fejlkode': {'type': 'string'} }, 'required': ['aftale_id', 'gateway_fejlkode'] }
def get_schema(): return {'type': 'object', 'properties': {'aftale_id': {'type': 'string'}, 'state': {'type': 'string'}, 'gateway_fejlkode': {'type': 'string'}}, 'required': ['aftale_id', 'gateway_fejlkode']}
w = h = 600 s = 40 off = s/4 shift = 3 x = y = 0 newPage(w, h) strokeWidth(2) stroke(.5) while (y * s) < h: while (x *s) < w: fill(0) if x % 2 == 0 else fill(1) rect(off + x * s, y * s, s, s) x += 1 if y % 3 == 0: off *= -1 off += s/4 x = 0 y += 1 saveImage('imgs/cafe_wall.png')
w = h = 600 s = 40 off = s / 4 shift = 3 x = y = 0 new_page(w, h) stroke_width(2) stroke(0.5) while y * s < h: while x * s < w: fill(0) if x % 2 == 0 else fill(1) rect(off + x * s, y * s, s, s) x += 1 if y % 3 == 0: off *= -1 off += s / 4 x = 0 y += 1 save_image('imgs/cafe_wall.png')
""" Caesar Cipher Encryptor: Given a non-empty string of lowercase letters and a non-negative integer representing a key, write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet, where k is the key. Note that letters should "wrap" around the alphabet; in other words, the letter z shifted by one returns the letter a. https://www.algoexpert.io/questions/Caesar%20Cipher%20Encryptor """ # O(n) time | O(n) space def caesarCipherEncryptor(string, key): characters = list(string) # Calculate where to move the character for idx, char in enumerate(characters): char_unicode = ord(char) + key # make sure key is < ord('z') else subtract 26 while char_unicode > ord('z'): char_unicode -= 26 # replace moved character in our characters characters[idx] = chr(char_unicode) return "".join(characters) # O(n) time | O(n) space def caesarCipherEncryptor1(string, key): newLetters = [] newKey = key % 26 # handle large numbers for letter in string: newLetters.append(getNewLetter(letter, newKey)) return "".join(newLetters) def getNewLetter(letter, key): newLetterCode = ord(letter) + key # # return within alphabet return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122) """ For each character in the string calculate where to move it # convert characters/string into array for better runtime 1. Iterate through each character 2. Calculate where to move the character - get it's unicode value: ord(char) - add/move it by the key: ord(char) + key - make sure key is < ord('z') else subtract 26 - to return it withoin the alphabet - convert back to char chr(result from above) 3. replace character in our characters 4. convert characters to string and return """ print(caesarCipherEncryptor("abcxyz", 1)) print(caesarCipherEncryptor("abcxyz", 100))
""" Caesar Cipher Encryptor: Given a non-empty string of lowercase letters and a non-negative integer representing a key, write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet, where k is the key. Note that letters should "wrap" around the alphabet; in other words, the letter z shifted by one returns the letter a. https://www.algoexpert.io/questions/Caesar%20Cipher%20Encryptor """ def caesar_cipher_encryptor(string, key): characters = list(string) for (idx, char) in enumerate(characters): char_unicode = ord(char) + key while char_unicode > ord('z'): char_unicode -= 26 characters[idx] = chr(char_unicode) return ''.join(characters) def caesar_cipher_encryptor1(string, key): new_letters = [] new_key = key % 26 for letter in string: newLetters.append(get_new_letter(letter, newKey)) return ''.join(newLetters) def get_new_letter(letter, key): new_letter_code = ord(letter) + key return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122) "\nFor each character in the string calculate where to move it\n\n# convert characters/string into array for better runtime\n1. Iterate through each character\n2. Calculate where to move the character\n - get it's unicode value: ord(char)\n - add/move it by the key: ord(char) + key\n - make sure key is < ord('z') else subtract 26 - to return it withoin the alphabet\n - convert back to char chr(result from above) \n3. replace character in our characters\n4. convert characters to string and return \n\n" print(caesar_cipher_encryptor('abcxyz', 1)) print(caesar_cipher_encryptor('abcxyz', 100))
class Solution: def recoverTree(self, root): def inorder(node): if node.left: yield from inorder(node.left) yield node if node.right: yield from inorder(node.right) swap1 = swap2 = smaller = None for node in inorder(root): if smaller and smaller.val > node.val: if not swap1: swap1 = smaller swap2 = node smaller = node if swap1: swap1.val, swap2.val = swap2.val, swap1.val
class Solution: def recover_tree(self, root): def inorder(node): if node.left: yield from inorder(node.left) yield node if node.right: yield from inorder(node.right) swap1 = swap2 = smaller = None for node in inorder(root): if smaller and smaller.val > node.val: if not swap1: swap1 = smaller swap2 = node smaller = node if swap1: (swap1.val, swap2.val) = (swap2.val, swap1.val)
''' 80. Remove Duplicates from Sorted Array II Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. ''' class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ # TODO pass class Solution2: def removeDuplicates(self, nums): ''' Incredible solution from https://leetcode.com/stefanpochmann ''' i = 0 AT_MOST = 2 for num in nums: if i<AT_MOST or num > nums[i-AT_MOST]: nums[i]=num i+=1 print(nums) return i if __name__ == "__main__": s = Solution() t1 = [1,1,1,2,2,3] assert s.removeDuplicates(t1)==5 t2 = [0,0,1,1,1,1,2,3,3] assert s.removeDuplicates(t2)==7 t3 = [1,1,2,3,4,5,5,5,5,5,5,5,5] assert s.removeDuplicates(t3)==7
""" 80. Remove Duplicates from Sorted Array II Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ class Solution: def remove_duplicates(self, nums): """ :type nums: List[int] :rtype: int """ pass class Solution2: def remove_duplicates(self, nums): """ Incredible solution from https://leetcode.com/stefanpochmann """ i = 0 at_most = 2 for num in nums: if i < AT_MOST or num > nums[i - AT_MOST]: nums[i] = num i += 1 print(nums) return i if __name__ == '__main__': s = solution() t1 = [1, 1, 1, 2, 2, 3] assert s.removeDuplicates(t1) == 5 t2 = [0, 0, 1, 1, 1, 1, 2, 3, 3] assert s.removeDuplicates(t2) == 7 t3 = [1, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5] assert s.removeDuplicates(t3) == 7
expected_output = { "dhcp_guard_policy_config":{ "policy_name":"pol1", "trusted_port":True, "device_role":"dhcp server", "max_preference":255, "min_preference":0, "access_list":"acl2", "prefix_list":"abc", "targets":{ "vlan 2":{ "target":"vlan 2", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 3":{ "target":"vlan 3", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 4":{ "target":"vlan 4", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 5":{ "target":"vlan 5", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 6":{ "target":"vlan 6", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 7":{ "target":"vlan 7", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 8":{ "target":"vlan 8", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 9":{ "target":"vlan 9", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" }, "vlan 10":{ "target":"vlan 10", "type":"VLAN", "feature":"DHCP Guard", "target_range":"vlan all" } } } }
expected_output = {'dhcp_guard_policy_config': {'policy_name': 'pol1', 'trusted_port': True, 'device_role': 'dhcp server', 'max_preference': 255, 'min_preference': 0, 'access_list': 'acl2', 'prefix_list': 'abc', 'targets': {'vlan 2': {'target': 'vlan 2', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 3': {'target': 'vlan 3', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 4': {'target': 'vlan 4', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 5': {'target': 'vlan 5', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 6': {'target': 'vlan 6', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 7': {'target': 'vlan 7', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 8': {'target': 'vlan 8', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 9': {'target': 'vlan 9', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}, 'vlan 10': {'target': 'vlan 10', 'type': 'VLAN', 'feature': 'DHCP Guard', 'target_range': 'vlan all'}}}}
class Person: Y = "You are young." T = "You are a teenager." O = "You are old." age = int(0) def __init__(self, initialAge): if initialAge < 0: print('Age is not valid, setting age to 0.') else: self.age = initialAge def amIOld(self): if self.age < 13: print(self.Y) elif self.age < 18: print(self.T) else: print(self.O) def yearPasses(self): self.age += 1
class Person: y = 'You are young.' t = 'You are a teenager.' o = 'You are old.' age = int(0) def __init__(self, initialAge): if initialAge < 0: print('Age is not valid, setting age to 0.') else: self.age = initialAge def am_i_old(self): if self.age < 13: print(self.Y) elif self.age < 18: print(self.T) else: print(self.O) def year_passes(self): self.age += 1
""" Stuff """ class Sequence(object): def __init__(self, *_seq): self.seq = tuple(_seq) pass;
""" Stuff """ class Sequence(object): def __init__(self, *_seq): self.seq = tuple(_seq) pass
# Improved Position Calculation # objectposncalc.py (improved) print("This program calculates an object's final position.") do_calculation = True while(do_calculation): # Get information about the object from the user while (True): try: initial_position = float(input("\nEnter the object's initial position: ")) except ValueError: print("The value you entered is invalid. Only numerical values are valid."); else: break while (True): try: initial_velocity = float(input("Enter the object's initial velocity: ")) except ValueError: print("The value you entered is invalid. Only numerical values are valid."); else: break while (True): try: acceleration = float(input("Enter the object's acceleration: ")) except ValueError: print("The value you entered is invalid. Only numerical values are valid."); else: break while (True): try: time_elapsed = float(input("Enter the time that has elapsed: ")) if (time_elapsed < 0): print("Negative times are not allowed.") continue except ValueError: print("The value you entered is invalid. Only numerical values are valid."); else: break # Calculate the final position final_position = initial_position + initial_velocity * time_elapsed + 0.5 * acceleration * time_elapsed ** 2 # Output final position print("\nThe object's final position is", final_position) # Check if the user wants to perform another calculation another_calculation = input("\nDo you want to perform another calculation? (y/n): ") if (another_calculation != "y"): do_calculation = False
print("This program calculates an object's final position.") do_calculation = True while do_calculation: while True: try: initial_position = float(input("\nEnter the object's initial position: ")) except ValueError: print('The value you entered is invalid. Only numerical values are valid.') else: break while True: try: initial_velocity = float(input("Enter the object's initial velocity: ")) except ValueError: print('The value you entered is invalid. Only numerical values are valid.') else: break while True: try: acceleration = float(input("Enter the object's acceleration: ")) except ValueError: print('The value you entered is invalid. Only numerical values are valid.') else: break while True: try: time_elapsed = float(input('Enter the time that has elapsed: ')) if time_elapsed < 0: print('Negative times are not allowed.') continue except ValueError: print('The value you entered is invalid. Only numerical values are valid.') else: break final_position = initial_position + initial_velocity * time_elapsed + 0.5 * acceleration * time_elapsed ** 2 print("\nThe object's final position is", final_position) another_calculation = input('\nDo you want to perform another calculation? (y/n): ') if another_calculation != 'y': do_calculation = False
CELL_DIM = 46 NEXT_CELL_DISTANCE = 66 NEXT_ROW_DISTANCE_V = 57 NEXT_ROW_DISTANCE_H = 33 INITIAL_V = 44 INITIAL_H = 230
cell_dim = 46 next_cell_distance = 66 next_row_distance_v = 57 next_row_distance_h = 33 initial_v = 44 initial_h = 230
""" In Central_Phila.gdb Use an UpdateCursor to update any Parks 'ADDRESS' records ending in PWY or BLD to PKWY or BLVD """ # Import modules # Set variables # Execute operation
""" In Central_Phila.gdb Use an UpdateCursor to update any Parks 'ADDRESS' records ending in PWY or BLD to PKWY or BLVD """
class ConfigFileNotFoundError(Exception): """Denotes failing to find configuration file.""" def __init__(self, message, locations, *args): self.message = message self.locations = ", ".join(str(l) for l in locations) super(ConfigFileNotFoundError, self).__init__(message, locations, *args) def __str__(self): return "Config File {0} Not Found in {1}".format( self.message, self.locations) class RemoteConfigError(Exception): """Denotes encountering an error while trying to pull the configuration from the remote provider. """ def __init__(self, message, *args): self.message = message super(RemoteConfigError, self).__init__(message, *args) def __str__(self): return "Remote Configuration Error {0}".format(self.message) class UnsupportedConfigError(Exception): """Denotes encountering an unsupported configuration file type.""" def __init__(self, message, *args): self.message = message super(UnsupportedConfigError, self).__init__(message, *args) def __str__(self): return "Unsupported Config Type {0}".format(self.message) class UnsupportedRemoteProviderError(Exception): """Denotes encountering an unsupported remote provider. Currently only etcd, consul and zookeeper are supported. """ def __init__(self, message, *args): self.message = message super(UnsupportedRemoteProviderError, self).__init__(message, *args) def __str__(self): return "Unsupported Remote Provider Type {0}".format(self.message)
class Configfilenotfounderror(Exception): """Denotes failing to find configuration file.""" def __init__(self, message, locations, *args): self.message = message self.locations = ', '.join((str(l) for l in locations)) super(ConfigFileNotFoundError, self).__init__(message, locations, *args) def __str__(self): return 'Config File {0} Not Found in {1}'.format(self.message, self.locations) class Remoteconfigerror(Exception): """Denotes encountering an error while trying to pull the configuration from the remote provider. """ def __init__(self, message, *args): self.message = message super(RemoteConfigError, self).__init__(message, *args) def __str__(self): return 'Remote Configuration Error {0}'.format(self.message) class Unsupportedconfigerror(Exception): """Denotes encountering an unsupported configuration file type.""" def __init__(self, message, *args): self.message = message super(UnsupportedConfigError, self).__init__(message, *args) def __str__(self): return 'Unsupported Config Type {0}'.format(self.message) class Unsupportedremoteprovidererror(Exception): """Denotes encountering an unsupported remote provider. Currently only etcd, consul and zookeeper are supported. """ def __init__(self, message, *args): self.message = message super(UnsupportedRemoteProviderError, self).__init__(message, *args) def __str__(self): return 'Unsupported Remote Provider Type {0}'.format(self.message)
class Node: def __init__(self, value, adj): self.value = value self.adj = adj self.visited = False def dfs(graph): for source in graph: source.visited = True dfs_node(source) def dfs_node(node): print(node.value) for e in node.adj: if not e.visited: e.visited = True dfs_node(e)
class Node: def __init__(self, value, adj): self.value = value self.adj = adj self.visited = False def dfs(graph): for source in graph: source.visited = True dfs_node(source) def dfs_node(node): print(node.value) for e in node.adj: if not e.visited: e.visited = True dfs_node(e)
class Cuenta(): def __init__(self, nombre, saldo): self.nombre=nombre self.saldo=saldo def get_ingreso(self): ingresos=self.saldo + 100 return ingresos def get_reintegro(self): reintegro=self.saldo-300 return reintegro def get_transferencia(self): dinero_tranferido=300 impuestos=10 transferencia=self.saldo-300-10 return transferencia
class Cuenta: def __init__(self, nombre, saldo): self.nombre = nombre self.saldo = saldo def get_ingreso(self): ingresos = self.saldo + 100 return ingresos def get_reintegro(self): reintegro = self.saldo - 300 return reintegro def get_transferencia(self): dinero_tranferido = 300 impuestos = 10 transferencia = self.saldo - 300 - 10 return transferencia
class MessageDispatcher: def __init__(self): self._bacteria = [] self.message_uid = 1 def broadcast(self, message): message.uid = self.message_uid #print('-- {} Broad casting for agent# {}'.format(message.uid, message.sender.uid)) self.message_uid += 1 for bacterium in self._bacteria: if bacterium is not message.sender: bacterium.receive(message) def register(self, bacterium): self._bacteria.append(bacterium) def unregister(self, bacterium): self._bacteria.remove(bacterium) class Message: def __init__(self, sender):#, points, points_info):# position_of, x, y): self.sender = sender #self.uid = 0 #self.position_of = position_of #self.x = x #self.y = y #self.points = points #self.points_info = points_info
class Messagedispatcher: def __init__(self): self._bacteria = [] self.message_uid = 1 def broadcast(self, message): message.uid = self.message_uid self.message_uid += 1 for bacterium in self._bacteria: if bacterium is not message.sender: bacterium.receive(message) def register(self, bacterium): self._bacteria.append(bacterium) def unregister(self, bacterium): self._bacteria.remove(bacterium) class Message: def __init__(self, sender): self.sender = sender
#!/usr/local/bin/python3 class Cpu(): def __init__(self, components): self.components = [ tuple([int(x) for x in component.strip().split("/")]) for component in components ] self.validBridges = self.__generateValidBridges(0, self.components) def __generateValidBridges(self, port, components, bridge=None): if not bridge: bridge = [] validBridges = [] matchingComponents = [ x for x in components if (x[0] == port or x[1] == port) ] if len(matchingComponents) != 0: for component in matchingComponents: newbridge = bridge + [tuple(component)] validBridges.append(newbridge) if component[0] != port: newport = component[0] else: newport = component[1] remainingComponents = [ m for m in components if m not in [component] ] validBridges += self.__generateValidBridges(newport, remainingComponents, newbridge) return validBridges def __calcStrength(self, bridge): return sum([item for sublist in bridge for item in sublist]) def findStrongest(self, bridges): return max([ self.__calcStrength(bridge) for bridge in bridges ]) def findLongest(self): longest = [self.validBridges[0]] for bridge in self.validBridges: if len(bridge) > len(longest[0]): longest = [bridge] elif len(bridge) == len(longest[0]): longest.append(bridge) return longest with open("./input.txt") as f: INPUT = f.readlines() bridge = Cpu(INPUT) print("Star 1: %i" % bridge.findStrongest(bridge.validBridges)) print("Star 2: %i" % bridge.findStrongest(bridge.findLongest())) #print("Star 2: %i" % tubes.steps)
class Cpu: def __init__(self, components): self.components = [tuple([int(x) for x in component.strip().split('/')]) for component in components] self.validBridges = self.__generateValidBridges(0, self.components) def __generate_valid_bridges(self, port, components, bridge=None): if not bridge: bridge = [] valid_bridges = [] matching_components = [x for x in components if x[0] == port or x[1] == port] if len(matchingComponents) != 0: for component in matchingComponents: newbridge = bridge + [tuple(component)] validBridges.append(newbridge) if component[0] != port: newport = component[0] else: newport = component[1] remaining_components = [m for m in components if m not in [component]] valid_bridges += self.__generateValidBridges(newport, remainingComponents, newbridge) return validBridges def __calc_strength(self, bridge): return sum([item for sublist in bridge for item in sublist]) def find_strongest(self, bridges): return max([self.__calcStrength(bridge) for bridge in bridges]) def find_longest(self): longest = [self.validBridges[0]] for bridge in self.validBridges: if len(bridge) > len(longest[0]): longest = [bridge] elif len(bridge) == len(longest[0]): longest.append(bridge) return longest with open('./input.txt') as f: input = f.readlines() bridge = cpu(INPUT) print('Star 1: %i' % bridge.findStrongest(bridge.validBridges)) print('Star 2: %i' % bridge.findStrongest(bridge.findLongest()))
def create_log_file(fname, optimization_method, directions, nodes, step, method_dd, method_ds_db, method_d2s_db2, method_jacobian, method_hessian, e_dd, e_ds_db, ex_d2s_db2, ey_d2s_db2, e_jacobian, ex_hessian, ey_hessian): format1 = "# {:71}: {}\n" format2 = "# {:71}: {:25}| e : {:10}\n" format3 = "# {:71}: {:25}| e : {:10}| ey : {:10}\n" # Clear file open(fname, 'w').close() f = open(fname, "a") f.write(format1.format("Method of Optimization", optimization_method)) f.write(format1.format("Directions of Optimization", directions)) f.write(format1.format("Number of Nodes", nodes)) if optimization_method == "Steepest Decent": f.write(format1.format("Step", step)) if (optimization_method == "Newton" and method_hessian == "dd-av") or method_jacobian == "direct": if method_dd == "finite differences": f.write(format2.format("Method of first derivatives of Velocity and Pressure Calculation", method_dd, str(e_dd))) else: f.write(format1.format("Method of first derivatives of Velocity and Pressure Calculation", method_dd)) if method_jacobian != "finite differences" and method_hessian != "finite differences": if method_ds_db == "finite differences": f.write(format2.format("Method of first derivatives of Cross-Section Area Calculation", method_ds_db, str(e_ds_db))) else: f.write(format1.format("Method of first derivatives of Cross-Section Area Calculation", method_ds_db)) if optimization_method == "Newton" and method_hessian == "dd-av": if method_d2s_db2 == "finite differences": f.write(format3.format("Method of second derivatives of Cross-Secion Area Calculation", method_d2s_db2, str(ex_d2s_db2), str(ey_d2s_db2))) else: f.write(format1.format("Method of second derivatives of Cross-Secion Area Calculation", method_d2s_db2)) if method_jacobian == "finite differences": f.write(format2.format("Method of Jacobian Calculation", method_jacobian, str(e_jacobian))) else: f.write(format1.format("Method of Jacobian Calculation", method_jacobian)) if optimization_method == "Newton": if method_hessian == "finite differences": f.write(format3.format("Method of Hessian Calculation", method_hessian, str(ex_hessian), str(ey_hessian))) else: f.write(format1.format("Method of Hessian Calculation", method_hessian)) f.write("\n") f.close() def write_log_file_headers(fname, num_of_cp, directions): x = ["X" + str(i) for i in range(num_of_cp)] y = ["Y" + str(i) for i in range(num_of_cp)] for i in range(num_of_cp - 2): if directions == 1: y[i + 1] += " (b" + str(i) + ")" else: x[i + 1] += " (b" + str(i) + ")" y[i + 1] += " (b" + str(i + num_of_cp - 2) + ")" f = open(fname, "a") f.write("# {:25}{:25}{:25}{:25}".format("Cycle of Optimization", "Time Units of Cycle", "Total Time Units", "F Objective") + str(num_of_cp * "{:25}").format(*x) + str(num_of_cp * "{:25}").format(*y) + "\n\n") f.close() def write_optimization_cycle_data(fname, cycle, time_units, total_time_units, f_objective, cp): f = open(fname, "a") f.write(" {:25}{:25}{:25}{:25}".format(str(cycle), str(time_units), str(total_time_units), str(f_objective)) + str(len(cp) * "{:25}").format(*[str(cp[i, 0].real) for i in range(len(cp))]) + str(len(cp) * "{:25}").format(*[str(cp[i, 1].real) for i in range(len(cp))]) + "\n") f.close()
def create_log_file(fname, optimization_method, directions, nodes, step, method_dd, method_ds_db, method_d2s_db2, method_jacobian, method_hessian, e_dd, e_ds_db, ex_d2s_db2, ey_d2s_db2, e_jacobian, ex_hessian, ey_hessian): format1 = '# {:71}: {}\n' format2 = '# {:71}: {:25}| e : {:10}\n' format3 = '# {:71}: {:25}| e : {:10}| ey : {:10}\n' open(fname, 'w').close() f = open(fname, 'a') f.write(format1.format('Method of Optimization', optimization_method)) f.write(format1.format('Directions of Optimization', directions)) f.write(format1.format('Number of Nodes', nodes)) if optimization_method == 'Steepest Decent': f.write(format1.format('Step', step)) if optimization_method == 'Newton' and method_hessian == 'dd-av' or method_jacobian == 'direct': if method_dd == 'finite differences': f.write(format2.format('Method of first derivatives of Velocity and Pressure Calculation', method_dd, str(e_dd))) else: f.write(format1.format('Method of first derivatives of Velocity and Pressure Calculation', method_dd)) if method_jacobian != 'finite differences' and method_hessian != 'finite differences': if method_ds_db == 'finite differences': f.write(format2.format('Method of first derivatives of Cross-Section Area Calculation', method_ds_db, str(e_ds_db))) else: f.write(format1.format('Method of first derivatives of Cross-Section Area Calculation', method_ds_db)) if optimization_method == 'Newton' and method_hessian == 'dd-av': if method_d2s_db2 == 'finite differences': f.write(format3.format('Method of second derivatives of Cross-Secion Area Calculation', method_d2s_db2, str(ex_d2s_db2), str(ey_d2s_db2))) else: f.write(format1.format('Method of second derivatives of Cross-Secion Area Calculation', method_d2s_db2)) if method_jacobian == 'finite differences': f.write(format2.format('Method of Jacobian Calculation', method_jacobian, str(e_jacobian))) else: f.write(format1.format('Method of Jacobian Calculation', method_jacobian)) if optimization_method == 'Newton': if method_hessian == 'finite differences': f.write(format3.format('Method of Hessian Calculation', method_hessian, str(ex_hessian), str(ey_hessian))) else: f.write(format1.format('Method of Hessian Calculation', method_hessian)) f.write('\n') f.close() def write_log_file_headers(fname, num_of_cp, directions): x = ['X' + str(i) for i in range(num_of_cp)] y = ['Y' + str(i) for i in range(num_of_cp)] for i in range(num_of_cp - 2): if directions == 1: y[i + 1] += ' (b' + str(i) + ')' else: x[i + 1] += ' (b' + str(i) + ')' y[i + 1] += ' (b' + str(i + num_of_cp - 2) + ')' f = open(fname, 'a') f.write('# {:25}{:25}{:25}{:25}'.format('Cycle of Optimization', 'Time Units of Cycle', 'Total Time Units', 'F Objective') + str(num_of_cp * '{:25}').format(*x) + str(num_of_cp * '{:25}').format(*y) + '\n\n') f.close() def write_optimization_cycle_data(fname, cycle, time_units, total_time_units, f_objective, cp): f = open(fname, 'a') f.write(' {:25}{:25}{:25}{:25}'.format(str(cycle), str(time_units), str(total_time_units), str(f_objective)) + str(len(cp) * '{:25}').format(*[str(cp[i, 0].real) for i in range(len(cp))]) + str(len(cp) * '{:25}').format(*[str(cp[i, 1].real) for i in range(len(cp))]) + '\n') f.close()
class Node: def __init__(self, element): self.item = element self.next_link = None class QueueLL: def __init__(self): self.head = None def is_empty(self): if self.head is None: print("Error! The queue is empty!") return True else: return False def print_queue(self): if not QueueLL.is_empty(self): node = self.head while node is not None: print(node.item) node = node.next_link def search_item(self, element): if not QueueLL.is_empty(self): node = self.head while node is not None: if node.item == element: print("Found") return True node = node.next_link print("Not found") return False def enqueue(self, element): new_node = Node(element) node = self.head if node is None: self.head = new_node else: while node.next_link is not None: node = node.next_link node.next_link = new_node def dequeue(self): node = self.head if not QueueLL.is_empty(self): self.head = node.next_link print(node.item) return node.item
class Node: def __init__(self, element): self.item = element self.next_link = None class Queuell: def __init__(self): self.head = None def is_empty(self): if self.head is None: print('Error! The queue is empty!') return True else: return False def print_queue(self): if not QueueLL.is_empty(self): node = self.head while node is not None: print(node.item) node = node.next_link def search_item(self, element): if not QueueLL.is_empty(self): node = self.head while node is not None: if node.item == element: print('Found') return True node = node.next_link print('Not found') return False def enqueue(self, element): new_node = node(element) node = self.head if node is None: self.head = new_node else: while node.next_link is not None: node = node.next_link node.next_link = new_node def dequeue(self): node = self.head if not QueueLL.is_empty(self): self.head = node.next_link print(node.item) return node.item
def simulateSeats(seats): #output seats new_seats = [] # seat_n # seat_ne # seat_e # seat_se # seat_s # seat_sw # seat_w # seat_nw for i, seat_row in enumerate(seats): for j, seat in enumerate(seats[i]): print(" i : " + str(i) + " j : "+ str(j) + " seat : " + seat) return 0 #maybe need helper function to get adjacent? f = open("day11test.txt","r") seats = f.read().splitlines() print(simulateSeats(seats)) #to track when it stops changing, just keep a tab when it changes
def simulate_seats(seats): new_seats = [] for (i, seat_row) in enumerate(seats): for (j, seat) in enumerate(seats[i]): print(' i : ' + str(i) + ' j : ' + str(j) + ' seat : ' + seat) return 0 f = open('day11test.txt', 'r') seats = f.read().splitlines() print(simulate_seats(seats))
# General system information system_information = { "SERVICE": "wecken_api", "ENVIRONMENT": "development", "BUILD": "dev_build", } # Database settings database = { "CONNECTION_STRING": "", "LOCAL_DB_NAME": "mongo-wecken-dev-db" } # user settings user = { "profile": { "max_length": 500 } }
system_information = {'SERVICE': 'wecken_api', 'ENVIRONMENT': 'development', 'BUILD': 'dev_build'} database = {'CONNECTION_STRING': '', 'LOCAL_DB_NAME': 'mongo-wecken-dev-db'} user = {'profile': {'max_length': 500}}
#string my_var1="hello students" myvar1="hello \t students" print(my_var1) print(myvar1) print("class \t hello \t studennts") #innt my_var2=20 print("number is",my_var2, "msg ",my_var1) #float my_var3=20.123456789123456789 print(my_var3) #complex my_var4=23j print(my_var4) #list my_var5=[1,20,"hello","world"] print(my_var5) #tuple my_var6=(1,20,"hello","tuple","world") print(my_var6) #dict my_var7={ "name":"gaurav", "age":20, "marks":80.234 } print(my_var7) #range my_var8=range(0,10) print(my_var8) #bool my_var9=True print(my_var9) #set my_var10={"student1","student2",3,3} print(my_var10) #to know about ddata type use type(<variable>)
my_var1 = 'hello students' myvar1 = 'hello \t students' print(my_var1) print(myvar1) print('class \t hello \t studennts') my_var2 = 20 print('number is', my_var2, 'msg ', my_var1) my_var3 = 20.123456789123455 print(my_var3) my_var4 = 23j print(my_var4) my_var5 = [1, 20, 'hello', 'world'] print(my_var5) my_var6 = (1, 20, 'hello', 'tuple', 'world') print(my_var6) my_var7 = {'name': 'gaurav', 'age': 20, 'marks': 80.234} print(my_var7) my_var8 = range(0, 10) print(my_var8) my_var9 = True print(my_var9) my_var10 = {'student1', 'student2', 3, 3} print(my_var10)
# # PySNMP MIB module CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:26:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") snmpAgentInfo_Utilities_ces, = mibBuilder.importSymbols("CONTIVITY-INFO-V1-MIB", "snmpAgentInfo-Utilities-ces") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, MibIdentifier, TimeTicks, Integer32, Gauge32, ModuleIdentity, Unsigned32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Counter64, IpAddress, ObjectIdentity, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibIdentifier", "TimeTicks", "Integer32", "Gauge32", "ModuleIdentity", "Unsigned32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Counter64", "IpAddress", "ObjectIdentity", "iso") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") snmpAgentInfo_Utilities_TrapAck_ces = ModuleIdentity((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2)).setLabel("snmpAgentInfo-Utilities-TrapAck-ces") if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setLastUpdated('0604062230Z') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setOrganization('Nortel') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setContactInfo('support@nortel.com Postal: Nortel 600 Technology Park Drive Billerica, MA 01821 Tel: +1 978 670 8888 E-Mail: support@nortel.com') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setDescription('Contivity Trap Acknowledgment MIB') trapAck_RevInfo_ces = MibIdentifier((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1)).setLabel("trapAck-RevInfo-ces") trapAck_RevDate_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 1), DisplayString()).setLabel("trapAck-RevDate-ces").setMaxAccess("readonly") if mibBuilder.loadTexts: trapAck_RevDate_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_RevDate_ces.setDescription('This value should match the LAST-UPDATED value in the MIB if this section of the mib was modified.') trapAck_Rev_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 2), Integer32()).setLabel("trapAck-Rev-ces").setMaxAccess("readonly") if mibBuilder.loadTexts: trapAck_Rev_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_Rev_ces.setDescription('This is an integer that is increment for each change in the implementation of the MIB since the LAST-UPDATED date/time.') trapAck_ServerRev_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 3), DisplayString()).setLabel("trapAck-ServerRev-ces").setMaxAccess("readonly") if mibBuilder.loadTexts: trapAck_ServerRev_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_ServerRev_ces.setDescription('This is the lowest major and minor version numbers for the server image that this mib implementation is compatible with. Usage: if a customer develops an application that utilizes this mib in server version V4_00. By checking this value they can tell how far back this implementation is available. ') trapSeverity_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 2), Integer32()).setLabel("trapSeverity-ces") if mibBuilder.loadTexts: trapSeverity_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapSeverity_ces.setDescription('') trapDescription_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 3), Integer32()).setLabel("trapDescription-ces") if mibBuilder.loadTexts: trapDescription_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapDescription_ces.setDescription('') trapSysUpTime_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 4), Integer32()).setLabel("trapSysUpTime-ces") if mibBuilder.loadTexts: trapSysUpTime_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapSysUpTime_ces.setDescription('') trapOID_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 5), ObjectIdentifier()).setLabel("trapOID-ces") if mibBuilder.loadTexts: trapOID_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapOID_ces.setDescription('') trapAckTable_ces = MibTable((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6), ).setLabel("trapAckTable-ces") if mibBuilder.loadTexts: trapAckTable_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAckTable_ces.setDescription('') trapAckEntry_ces = MibTableRow((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6, 1), ).setLabel("trapAckEntry-ces").setIndexNames((0, "CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB", "trapSeverity-ces"), (0, "CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB", "trapDescription-ces"), (0, "CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB", "trapSysUpTime-ces"), (0, "CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB", "trapOID-ces")) if mibBuilder.loadTexts: trapAckEntry_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAckEntry_ces.setDescription('') trapAcknowledgement_ces = MibScalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6, 1, 1), Integer32()).setLabel("trapAcknowledgement-ces").setMaxAccess("readonly") if mibBuilder.loadTexts: trapAcknowledgement_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAcknowledgement_ces.setDescription('Possible Values: -1 the trap could not be acknowledged. -2 the trap OID was not found. 1 the trap acknowledgement was successful.') mibBuilder.exportSymbols("CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB", trapOID_ces=trapOID_ces, trapAckTable_ces=trapAckTable_ces, trapAckEntry_ces=trapAckEntry_ces, trapAck_RevDate_ces=trapAck_RevDate_ces, PYSNMP_MODULE_ID=snmpAgentInfo_Utilities_TrapAck_ces, trapDescription_ces=trapDescription_ces, trapAck_RevInfo_ces=trapAck_RevInfo_ces, snmpAgentInfo_Utilities_TrapAck_ces=snmpAgentInfo_Utilities_TrapAck_ces, trapAck_Rev_ces=trapAck_Rev_ces, trapAck_ServerRev_ces=trapAck_ServerRev_ces, trapSeverity_ces=trapSeverity_ces, trapSysUpTime_ces=trapSysUpTime_ces, trapAcknowledgement_ces=trapAcknowledgement_ces)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion') (snmp_agent_info__utilities_ces,) = mibBuilder.importSymbols('CONTIVITY-INFO-V1-MIB', 'snmpAgentInfo-Utilities-ces') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (bits, mib_identifier, time_ticks, integer32, gauge32, module_identity, unsigned32, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, counter64, ip_address, object_identity, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'MibIdentifier', 'TimeTicks', 'Integer32', 'Gauge32', 'ModuleIdentity', 'Unsigned32', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Counter64', 'IpAddress', 'ObjectIdentity', 'iso') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') snmp_agent_info__utilities__trap_ack_ces = module_identity((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2)).setLabel('snmpAgentInfo-Utilities-TrapAck-ces') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setLastUpdated('0604062230Z') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setOrganization('Nortel') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setContactInfo('support@nortel.com Postal: Nortel 600 Technology Park Drive Billerica, MA 01821 Tel: +1 978 670 8888 E-Mail: support@nortel.com') if mibBuilder.loadTexts: snmpAgentInfo_Utilities_TrapAck_ces.setDescription('Contivity Trap Acknowledgment MIB') trap_ack__rev_info_ces = mib_identifier((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1)).setLabel('trapAck-RevInfo-ces') trap_ack__rev_date_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 1), display_string()).setLabel('trapAck-RevDate-ces').setMaxAccess('readonly') if mibBuilder.loadTexts: trapAck_RevDate_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_RevDate_ces.setDescription('This value should match the LAST-UPDATED value in the MIB if this section of the mib was modified.') trap_ack__rev_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 2), integer32()).setLabel('trapAck-Rev-ces').setMaxAccess('readonly') if mibBuilder.loadTexts: trapAck_Rev_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_Rev_ces.setDescription('This is an integer that is increment for each change in the implementation of the MIB since the LAST-UPDATED date/time.') trap_ack__server_rev_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 1, 3), display_string()).setLabel('trapAck-ServerRev-ces').setMaxAccess('readonly') if mibBuilder.loadTexts: trapAck_ServerRev_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAck_ServerRev_ces.setDescription('This is the lowest major and minor version numbers for the server image that this mib implementation is compatible with. Usage: if a customer develops an application that utilizes this mib in server version V4_00. By checking this value they can tell how far back this implementation is available. ') trap_severity_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 2), integer32()).setLabel('trapSeverity-ces') if mibBuilder.loadTexts: trapSeverity_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapSeverity_ces.setDescription('') trap_description_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 3), integer32()).setLabel('trapDescription-ces') if mibBuilder.loadTexts: trapDescription_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapDescription_ces.setDescription('') trap_sys_up_time_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 4), integer32()).setLabel('trapSysUpTime-ces') if mibBuilder.loadTexts: trapSysUpTime_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapSysUpTime_ces.setDescription('') trap_oid_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 5), object_identifier()).setLabel('trapOID-ces') if mibBuilder.loadTexts: trapOID_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapOID_ces.setDescription('') trap_ack_table_ces = mib_table((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6)).setLabel('trapAckTable-ces') if mibBuilder.loadTexts: trapAckTable_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAckTable_ces.setDescription('') trap_ack_entry_ces = mib_table_row((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6, 1)).setLabel('trapAckEntry-ces').setIndexNames((0, 'CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB', 'trapSeverity-ces'), (0, 'CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB', 'trapDescription-ces'), (0, 'CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB', 'trapSysUpTime-ces'), (0, 'CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB', 'trapOID-ces')) if mibBuilder.loadTexts: trapAckEntry_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAckEntry_ces.setDescription('') trap_acknowledgement_ces = mib_scalar((1, 3, 6, 1, 4, 1, 2505, 1, 15, 1, 2, 6, 1, 1), integer32()).setLabel('trapAcknowledgement-ces').setMaxAccess('readonly') if mibBuilder.loadTexts: trapAcknowledgement_ces.setStatus('mandatory') if mibBuilder.loadTexts: trapAcknowledgement_ces.setDescription('Possible Values: -1 the trap could not be acknowledged. -2 the trap OID was not found. 1 the trap acknowledgement was successful.') mibBuilder.exportSymbols('CONTIVITY-TRAP-ACKNOWLEDGMENT-MIB', trapOID_ces=trapOID_ces, trapAckTable_ces=trapAckTable_ces, trapAckEntry_ces=trapAckEntry_ces, trapAck_RevDate_ces=trapAck_RevDate_ces, PYSNMP_MODULE_ID=snmpAgentInfo_Utilities_TrapAck_ces, trapDescription_ces=trapDescription_ces, trapAck_RevInfo_ces=trapAck_RevInfo_ces, snmpAgentInfo_Utilities_TrapAck_ces=snmpAgentInfo_Utilities_TrapAck_ces, trapAck_Rev_ces=trapAck_Rev_ces, trapAck_ServerRev_ces=trapAck_ServerRev_ces, trapSeverity_ces=trapSeverity_ces, trapSysUpTime_ces=trapSysUpTime_ces, trapAcknowledgement_ces=trapAcknowledgement_ces)
filename = "classes.csv" filout = "classescleaned.csv" with open(filename) as filein: with open(filout,"w") as fileo: for line in filein.readlines(): lineSplit = line.split(",") # if len(lineSplit)>1: # print(lineSplit[2]) # try: # int(lineSplit[2][1:-1]) # if len(lineSplit)==16: # fileo.write(line) # except: # print("nice") while len(lineSplit)!=15: lineSplit[1] = lineSplit[0]+lineSplit[1] lineSplit = lineSplit[1:] fileo.write(",".join(lineSplit))
filename = 'classes.csv' filout = 'classescleaned.csv' with open(filename) as filein: with open(filout, 'w') as fileo: for line in filein.readlines(): line_split = line.split(',') while len(lineSplit) != 15: lineSplit[1] = lineSplit[0] + lineSplit[1] line_split = lineSplit[1:] fileo.write(','.join(lineSplit))
# def multiply(a, b): # if b == 0: # return 0 # if b == 1: # return a # return a + multiply(a, b - 1) def multiply(a, b): if a < 0 and b < 0: return multiply(-a, -b) elif a < 0 or b < 0: return -multiply(abs(a), abs(b)) elif b == 0: return 0 elif b == 1: return a else: return a + multiply(a, b - 1) print(multiply(-5, 6))
def multiply(a, b): if a < 0 and b < 0: return multiply(-a, -b) elif a < 0 or b < 0: return -multiply(abs(a), abs(b)) elif b == 0: return 0 elif b == 1: return a else: return a + multiply(a, b - 1) print(multiply(-5, 6))
class GrocyPicnicProduct(): grocy_id = "" grocy_name = "" grocy_img_id = "" grocy_weight = "" grocy_id_stock = "" picnic_id = "" def __init__(self, picnic_id: str, grocy_id: str, grocy_name: str, grocy_img_id: str, grocy_weight: str, grocy_id_stock: str): self.picnic_id = picnic_id self.grocy_id = grocy_id self.grocy_name = grocy_name self.grocy_img_id = grocy_img_id self.grocy_weight = grocy_weight self.grocy_id_stock = grocy_id_stock def __repr__(self): return """ grocy_id: """+self.grocy_id+""" grocy_name: """+self.grocy_name+""" grocy_img_id: """+self.grocy_img_id+""" grocy_weight: """+self.grocy_weight+""" grocy_id_stock: """+self.grocy_id_stock+""" picnic_id: """+self.picnic_id+""" """
class Grocypicnicproduct: grocy_id = '' grocy_name = '' grocy_img_id = '' grocy_weight = '' grocy_id_stock = '' picnic_id = '' def __init__(self, picnic_id: str, grocy_id: str, grocy_name: str, grocy_img_id: str, grocy_weight: str, grocy_id_stock: str): self.picnic_id = picnic_id self.grocy_id = grocy_id self.grocy_name = grocy_name self.grocy_img_id = grocy_img_id self.grocy_weight = grocy_weight self.grocy_id_stock = grocy_id_stock def __repr__(self): return '\n grocy_id: ' + self.grocy_id + '\n grocy_name: ' + self.grocy_name + '\n grocy_img_id: ' + self.grocy_img_id + '\n grocy_weight: ' + self.grocy_weight + '\n grocy_id_stock: ' + self.grocy_id_stock + '\n picnic_id: ' + self.picnic_id + '\n '
def checkDigestionWithTwoEnzymes(splitdic, probebindingsites, keyfeatures): keylist2 = []; newSplitDic = {}; keylistTwoEnzymes = []; keydict = {}; banddic = {} for key in splitdic: keylist2.append(key) for i in range(len(keylist2)): for j in range(i+1, len(keylist2)): bandsTwoEnzymes = splitdic[keylist2[i]]+splitdic[keylist2[j]] keylistTwoEnzymes.append(keylist2[i]+"+"+keylist2[j]) bandsTwoEnzymes.sort() newSplitDic.update({keylist2[i]+"+"+keylist2[j]: bandsTwoEnzymes}) for k in range(len(keylistTwoEnzymes)): surroundingBands = [] for m in range(len(keyfeatures)): smallerBands = []; biggerBands = [] twoEnzymes = newSplitDic[keylistTwoEnzymes[k]] for v in range(len(twoEnzymes)): if int(twoEnzymes[v]) < int(probebindingsites[keyfeatures[m]][0]): smallerBands.append(twoEnzymes[v]) if int(twoEnzymes[v]) > int(probebindingsites[keyfeatures[m]][1]): biggerBands.append(twoEnzymes[v]) if smallerBands and biggerBands: surroundingBands.append([smallerBands[-1], biggerBands[0]]) else: surroundingBands.append([]) banddic.update({keylistTwoEnzymes[k]: surroundingBands}) for n in range(len(keylistTwoEnzymes)): keylist3 = [] for q in range(len(keyfeatures)): bandsTwoEnzymes = banddic[keylistTwoEnzymes[n]] if bandsTwoEnzymes and bandsTwoEnzymes[q] and bandsTwoEnzymes[q][1] - bandsTwoEnzymes[q][0] not in keylist3: keylist3.append(bandsTwoEnzymes[q][1] - bandsTwoEnzymes[q][0]) keylist3.sort(reverse=True) keydict.update({keylistTwoEnzymes[n]: keylist3}) return keylistTwoEnzymes, keydict, newSplitDic
def check_digestion_with_two_enzymes(splitdic, probebindingsites, keyfeatures): keylist2 = [] new_split_dic = {} keylist_two_enzymes = [] keydict = {} banddic = {} for key in splitdic: keylist2.append(key) for i in range(len(keylist2)): for j in range(i + 1, len(keylist2)): bands_two_enzymes = splitdic[keylist2[i]] + splitdic[keylist2[j]] keylistTwoEnzymes.append(keylist2[i] + '+' + keylist2[j]) bandsTwoEnzymes.sort() newSplitDic.update({keylist2[i] + '+' + keylist2[j]: bandsTwoEnzymes}) for k in range(len(keylistTwoEnzymes)): surrounding_bands = [] for m in range(len(keyfeatures)): smaller_bands = [] bigger_bands = [] two_enzymes = newSplitDic[keylistTwoEnzymes[k]] for v in range(len(twoEnzymes)): if int(twoEnzymes[v]) < int(probebindingsites[keyfeatures[m]][0]): smallerBands.append(twoEnzymes[v]) if int(twoEnzymes[v]) > int(probebindingsites[keyfeatures[m]][1]): biggerBands.append(twoEnzymes[v]) if smallerBands and biggerBands: surroundingBands.append([smallerBands[-1], biggerBands[0]]) else: surroundingBands.append([]) banddic.update({keylistTwoEnzymes[k]: surroundingBands}) for n in range(len(keylistTwoEnzymes)): keylist3 = [] for q in range(len(keyfeatures)): bands_two_enzymes = banddic[keylistTwoEnzymes[n]] if bandsTwoEnzymes and bandsTwoEnzymes[q] and (bandsTwoEnzymes[q][1] - bandsTwoEnzymes[q][0] not in keylist3): keylist3.append(bandsTwoEnzymes[q][1] - bandsTwoEnzymes[q][0]) keylist3.sort(reverse=True) keydict.update({keylistTwoEnzymes[n]: keylist3}) return (keylistTwoEnzymes, keydict, newSplitDic)
@bot.command(name='roll') async def roll(ctx, roll_type="action", number=1, placeholder="d", sides=20, modifier=0): # broken if number <= 0 or number > 10: await ctx.send("Please enter a number of dice between 1 and 10.") return if sides < 1: await ctx.send("Please enter a valid number of dice sides.") return response = "" if sides != 20: for i in range(0, number): response += f"Your roll: {random.randint(1, sides)}\n\n" else: for i in range(0, number): mod_int = int(modifier) raw_roll = random.randint(1,sides) modified_roll = raw_roll if raw_roll != 1 and raw_roll != 20: modified_roll += mod_int if modified_roll > 20: modified_roll = 20 if modified_roll < 1: modified_roll = 1 response += f"Your roll: {raw_roll}\n Modified roll: {raw_roll} + {mod_int} = {modified_roll}\n" else: response += f"Your roll: Natural {raw_roll}\n" if roll_type.lower() == "action": response += outcome_tables.action_outcomes(modified_roll)+"\n\n" elif roll_type.lower() == "combat": response += outcome_tables.combat_outcomes(modified_roll)+"\n\n" elif roll_type.lower() == "item": response += outcome_tables.item_outcomes(modified_roll)+"\n\n" else: response += ("Invalid roll type" + raw_roll) + modified_roll await ctx.send(response) # This works but it is missing all the new commands @bot.command(name='commands') async def commands(ctx): #deprecated inforandt = "```$randtrait``` to get a random trait from our list,\n" infofind = "```$find \"Name of trait in quotes\" ``` to find a trait in the list and have me define it, \n" infoins = "```$insert \"Name of trait in quotes\" \"Definition of trait in quotes\"``` to insert a new trait and definition in our traits file," infodel = "```$delete \"Name of trait in quotes\" ``` to delete a trait if it is in our traits file,\n" infogimme = "```$gimme``` to get the file of traits in chat, \n" infochar = "``` $charactertraits``` to get a list of traits to choose from and one which you are stuck with,\n" inforoll = "``` $roll [type \"action\"\"combat\"\"item\"] [number of dice to roll] [\"d\"][sides of dice] [modifier]``` to roll for an outcome of the three types, and how many dice you want to roll. Defaults to action roll of 1d20 with modifier 0." message = f'Type {inforandt}{infofind}{infoins}{infodel}{infogimme}{infochar}{inforoll}' await ctx.send(message)
@bot.command(name='roll') async def roll(ctx, roll_type='action', number=1, placeholder='d', sides=20, modifier=0): if number <= 0 or number > 10: await ctx.send('Please enter a number of dice between 1 and 10.') return if sides < 1: await ctx.send('Please enter a valid number of dice sides.') return response = '' if sides != 20: for i in range(0, number): response += f'Your roll: {random.randint(1, sides)}\n\n' else: for i in range(0, number): mod_int = int(modifier) raw_roll = random.randint(1, sides) modified_roll = raw_roll if raw_roll != 1 and raw_roll != 20: modified_roll += mod_int if modified_roll > 20: modified_roll = 20 if modified_roll < 1: modified_roll = 1 response += f'Your roll: {raw_roll}\n Modified roll: {raw_roll} + {mod_int} = {modified_roll}\n' else: response += f'Your roll: Natural {raw_roll}\n' if roll_type.lower() == 'action': response += outcome_tables.action_outcomes(modified_roll) + '\n\n' elif roll_type.lower() == 'combat': response += outcome_tables.combat_outcomes(modified_roll) + '\n\n' elif roll_type.lower() == 'item': response += outcome_tables.item_outcomes(modified_roll) + '\n\n' else: response += 'Invalid roll type' + raw_roll + modified_roll await ctx.send(response) @bot.command(name='commands') async def commands(ctx): inforandt = '```$randtrait``` to get a random trait from our list,\n' infofind = '```$find "Name of trait in quotes" ``` to find a trait in the list and have me define it, \n' infoins = '```$insert "Name of trait in quotes" "Definition of trait in quotes"``` to insert a new trait and definition in our traits file,' infodel = '```$delete "Name of trait in quotes" ``` to delete a trait if it is in our traits file,\n' infogimme = '```$gimme``` to get the file of traits in chat, \n' infochar = '``` $charactertraits``` to get a list of traits to choose from and one which you are stuck with,\n' inforoll = '``` $roll [type "action""combat""item"] [number of dice to roll] ["d"][sides of dice] [modifier]``` to roll for an outcome of the three types, and how many dice you want to roll. Defaults to action roll of 1d20 with modifier 0.' message = f'Type {inforandt}{infofind}{infoins}{infodel}{infogimme}{infochar}{inforoll}' await ctx.send(message)
# ---------------------------- defining functions ---------------------------- # def f(x, z): return z def s(x, z): return -alpha * x # ---------------------- system parameters and constants --------------------- # g = 9.8 # gravitational acceleration | m/s^2 mu = 0.6 # kinetic friction coefficient m = 0.5 # mass of the rod | kg l = 1.5 # length between centres of the disks | m alpha = 2 * g * mu / l # --------------------------- ODE solvers variable --------------------------- # h = 0.005 # increment tEnd = 20 # end of simulation | s numberOfSteps = int(tEnd / h) # number of steps xInitial = 0.1 # initial height of water relative to base | m | added a small change relative to the centre zInitial = 0 # initial velocity through the hole | m/s
def f(x, z): return z def s(x, z): return -alpha * x g = 9.8 mu = 0.6 m = 0.5 l = 1.5 alpha = 2 * g * mu / l h = 0.005 t_end = 20 number_of_steps = int(tEnd / h) x_initial = 0.1 z_initial = 0
class DataTable: """A DataTable is an object used to define the domain and data for a DiscreteField. Attributes ---------- dataWidth: int An Int specifying the width of the data. Valid widths are 1, 6, 21, corresponding to scalar data, orientations and 4D tensors. name: str A String specifying the index. instanceName: str A String specifying the instance name. domain: int A tuple of Ints specifying the domain node, element or integration point identifiers. table: float A tuple of Floats specifying the data within the domain. Notes ----- This object can be accessed by: .. code-block:: python import field mdb.models[name].discreteFields[name].data[i] """ # An Int specifying the width of the data. Valid widths are 1, 6, 21, corresponding to # scalar data, orientations and 4D tensors. dataWidth: int = None # A String specifying the index. name: str = '' # A String specifying the instance name. instanceName: str = '' # A tuple of Ints specifying the domain node, element or integration point identifiers. domain: int = None # A tuple of Floats specifying the data within the domain. table: float = None
class Datatable: """A DataTable is an object used to define the domain and data for a DiscreteField. Attributes ---------- dataWidth: int An Int specifying the width of the data. Valid widths are 1, 6, 21, corresponding to scalar data, orientations and 4D tensors. name: str A String specifying the index. instanceName: str A String specifying the instance name. domain: int A tuple of Ints specifying the domain node, element or integration point identifiers. table: float A tuple of Floats specifying the data within the domain. Notes ----- This object can be accessed by: .. code-block:: python import field mdb.models[name].discreteFields[name].data[i] """ data_width: int = None name: str = '' instance_name: str = '' domain: int = None table: float = None
def max_number(n): sorting ="".join(sorted(str(n), reverse = True)) s =int(sorting) return s def max_number2(n): return int(''.join(sorted(str(n), reverse=True)))
def max_number(n): sorting = ''.join(sorted(str(n), reverse=True)) s = int(sorting) return s def max_number2(n): return int(''.join(sorted(str(n), reverse=True)))
""" 1389. Create Target Array in the Given Order Given two arrays of integers nums and index. Your task is to create target array under the following rules: * Initially target array is empty. * From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. * Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. Example: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] """ # Runtime: 36ms class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: arr = [] # Check if len(nums) == len(index) if len(nums) == len(index): for i in range(len(nums)): arr.insert(index[i], nums[i]) return arr
""" 1389. Create Target Array in the Given Order Given two arrays of integers nums and index. Your task is to create target array under the following rules: * Initially target array is empty. * From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. * Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. Example: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] """ class Solution: def create_target_array(self, nums: List[int], index: List[int]) -> List[int]: arr = [] if len(nums) == len(index): for i in range(len(nums)): arr.insert(index[i], nums[i]) return arr
for i in range(1,101): print(i,"(",end="") if i % 2 == 0: print(2,",",end="") if i % 3 == 0: print(3,",",end="") if i % 5 == 0: print(5,",",end="") print(")")
for i in range(1, 101): print(i, '(', end='') if i % 2 == 0: print(2, ',', end='') if i % 3 == 0: print(3, ',', end='') if i % 5 == 0: print(5, ',', end='') print(')')
class ProcessingNode: def execute(self, processor, img): raise NotImplementedError() def dependencies(self, processor): return []
class Processingnode: def execute(self, processor, img): raise not_implemented_error() def dependencies(self, processor): return []
# # PySNMP MIB module SIP-UA-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SIP-UA-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:28:20 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( OctetString, ObjectIdentifier, Integer, ) = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection") ( applIndex, ) = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "applIndex") ( sipMIB, ) = mibBuilder.importSymbols("SIP-MIB-SMI", "sipMIB") ( ModuleCompliance, NotificationGroup, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ( MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ObjectIdentity, Counter64, iso, ModuleIdentity, NotificationType, Gauge32, IpAddress, TimeTicks, Unsigned32, Counter32, ) = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ObjectIdentity", "Counter64", "iso", "ModuleIdentity", "NotificationType", "Gauge32", "IpAddress", "TimeTicks", "Unsigned32", "Counter32") ( DisplayString, TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") sipUAMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 9998, 3)) if mibBuilder.loadTexts: sipUAMIB.setLastUpdated('200007080000Z') if mibBuilder.loadTexts: sipUAMIB.setOrganization('IETF SIP Working Group, SIP MIB Team') if mibBuilder.loadTexts: sipUAMIB.setContactInfo('SIP MIB Team email: sip-mib@egroups.com \n\n Co-editor Kevin Lingle \n Cisco Systems, Inc. \n postal: 7025 Kit Creek Road \n P.O. Box 14987 \n Research Triangle Park, NC 27709 \n USA \n email: klingle@cisco.com \n phone: +1-919-392-2029 \n\n Co-editor Joon Maeng \n VTEL Corporation \n postal: 108 Wild Basin Rd. \n Austin, TX 78746 \n USA \n email: joon_maeng@vtel.com \n phone: +1-512-437-4567 \n\n Co-editor Dave Walker \n SS8 Networks, Inc. \n postal: 80 Hines Road \n Kanata, ON K2K 2T8 \n Canada \n email: drwalker@ss8networks.com \n phone: +1 613 592 2100') if mibBuilder.loadTexts: sipUAMIB.setDescription('Initial version of Session Initiation Protocol (SIP) \n User Agent (UA) MIB module. \n\n SIP is an application-layer signalling protocol for \n creating, modifying and terminating multimedia \n sessions with one or more participants. These sessions \n include Internet multimedia conferences and Internet \n telephone calls. SIP is defined in RFC 2543 (March \n 1999). \n\n A User Agent is an application that contains both a \n User Agent Client (UAC) and a User Agent Server (UAS). \n A UAC is an application that initiates a SIP request. \n A UAS is an application that contacts the user when a \n SIP request is received and that returns a response on \n behalf of the user. The response accepts, rejects, or \n redirects the request.') sipUACfg = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 1)) sipUACfgTimer = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1)) sipUACfgRetry = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2)) sipUAStats = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 2)) sipUAStatsRetry = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1)) sipUACfgTimerTable = MibTable((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1), ) if mibBuilder.loadTexts: sipUACfgTimerTable.setDescription('This table contains timer configuration objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sipUACfgTimerEntry = MibTableRow((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: sipUACfgTimerEntry.setDescription('A row of timer configuration.') sipUACfgTimerTrying = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100,1000))).setUnits('milliseconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgTimerTrying.setDescription('This object specifies the time a user agent will wait to \n receive a provisional response to an INVITE before \n resending the INVITE.') sipUACfgTimerProv = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60000,300000))).setUnits('milliseconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgTimerProv.setDescription('This object specifies the time a user agent will wait to \n receive a final response to an INVITE before canceling the \n transaction.') sipUACfgTimerAck = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100,1000))).setUnits('milliseconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgTimerAck.setDescription('This object specifies the time a user agent will wait to \n receive an ACK confirmation indicating that a session is \n established.') sipUACfgTimerDisconnect = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100,1000))).setUnits('milliseconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgTimerDisconnect.setDescription('This object specifies the time a user agent will wait to \n receive a BYE confirmation indicating that a session is \n disconnected.') sipUACfgTimerReRegister = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,2147483647))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgTimerReRegister.setDescription('This object specifies how long the user agent wishes its \n registrations to be valid.') sipUACfgRetryTable = MibTable((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1), ) if mibBuilder.loadTexts: sipUACfgRetryTable.setDescription('This table contains retry configuration objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sipUACfgRetryEntry = MibTableRow((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: sipUACfgRetryEntry.setDescription('A row of retry configuration.') sipUACfgRetryInvite = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgRetryInvite.setDescription('This object will specify the number of times a user agent \n will retry sending an INVITE request.') sipUACfgRetryBye = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgRetryBye.setDescription('This object will specify the number of times a user agent \n will retry sending a BYE request.') sipUACfgRetryCancel = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgRetryCancel.setDescription('This object will specify the number of times a user agent \n will retry sending a CANCEL request.') sipUACfgRetryRegister = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgRetryRegister.setDescription('This object will specify the number of times a user agent \n will retry sending a REGISTER request.') sipUACfgRetryResponse = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sipUACfgRetryResponse.setDescription('This object will specify the number of times a user agent \n will retry sending a Response and expecting an ACK.') sipUAStatsRetryTable = MibTable((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1), ) if mibBuilder.loadTexts: sipUAStatsRetryTable.setDescription('This table contains retry statistics objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sipUAStatsRetryEntry = MibTableRow((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: sipUAStatsRetryEntry.setDescription('A row of retry statistics.') sipStatsRetryInvites = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sipStatsRetryInvites.setDescription("This object reflects the total number of INVITE retries \n that have been sent by the user agent. If the number of \n 'first attempt' INVITES is of interest, subtract the value \n of this object from sipStatsTrafficInviteOut.") sipStatsRetryByes = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sipStatsRetryByes.setDescription('This object reflects the total number of BYE retries that \n have been sent by the user agent.') sipStatsRetryCancels = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sipStatsRetryCancels.setDescription('This object reflects the total number of CANCEL retries \n that have been sent by the user agent.') sipStatsRetryRegisters = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sipStatsRetryRegisters.setDescription('This object reflects the total number of REGISTER retries \n that have been sent by the user agent.') sipStatsRetryResponses = MibTableColumn((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sipStatsRetryResponses.setDescription('This object reflects the total number of Response (while \n expecting an ACK) retries that have been sent by the user \n agent.') sipUAMIBNotif = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 3)) sipUAMIBConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 4)) sipUAMIBCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 4, 1)) sipUAMIBGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2)) sipUACompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 9998, 3, 4, 1, 1)).setObjects(*(("SIP-UA-MIB", "sipUAConfigGroup"), ("SIP-UA-MIB", "sipUAStatsGroup"),)) if mibBuilder.loadTexts: sipUACompliance.setDescription('The compliance statement for SIP entities.') sipUAConfigGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2, 1)).setObjects(*(("SIP-UA-MIB", "sipUACfgTimerTrying"), ("SIP-UA-MIB", "sipUACfgTimerProv"), ("SIP-UA-MIB", "sipUACfgTimerAck"), ("SIP-UA-MIB", "sipUACfgTimerDisconnect"), ("SIP-UA-MIB", "sipUACfgTimerReRegister"), ("SIP-UA-MIB", "sipUACfgRetryInvite"), ("SIP-UA-MIB", "sipUACfgRetryBye"), ("SIP-UA-MIB", "sipUACfgRetryCancel"), ("SIP-UA-MIB", "sipUACfgRetryRegister"), ("SIP-UA-MIB", "sipUACfgRetryResponse"),)) if mibBuilder.loadTexts: sipUAConfigGroup.setDescription('A collection of objects providing configuration for \n SIP User Agents.') sipUAStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2, 2)).setObjects(*(("SIP-UA-MIB", "sipStatsRetryInvites"), ("SIP-UA-MIB", "sipStatsRetryByes"), ("SIP-UA-MIB", "sipStatsRetryCancels"), ("SIP-UA-MIB", "sipStatsRetryRegisters"), ("SIP-UA-MIB", "sipStatsRetryResponses"),)) if mibBuilder.loadTexts: sipUAStatsGroup.setDescription('A collection of objects providing statistics for \n SIP User Agents.') mibBuilder.exportSymbols("SIP-UA-MIB", PYSNMP_MODULE_ID=sipUAMIB, sipStatsRetryInvites=sipStatsRetryInvites, sipUACfgTimerTrying=sipUACfgTimerTrying, sipUACfgTimerAck=sipUACfgTimerAck, sipUAMIBNotif=sipUAMIBNotif, sipUACfgRetryEntry=sipUACfgRetryEntry, sipUACfgRetryCancel=sipUACfgRetryCancel, sipUAMIBCompliances=sipUAMIBCompliances, sipUAMIBGroups=sipUAMIBGroups, sipStatsRetryRegisters=sipStatsRetryRegisters, sipUAStatsRetryTable=sipUAStatsRetryTable, sipUAMIB=sipUAMIB, sipUACfgTimerDisconnect=sipUACfgTimerDisconnect, sipStatsRetryCancels=sipStatsRetryCancels, sipStatsRetryResponses=sipStatsRetryResponses, sipUACfgRetryBye=sipUACfgRetryBye, sipUAStatsRetry=sipUAStatsRetry, sipUACfgTimer=sipUACfgTimer, sipUACfgTimerProv=sipUACfgTimerProv, sipUACfgTimerEntry=sipUACfgTimerEntry, sipUAStatsRetryEntry=sipUAStatsRetryEntry, sipUACfg=sipUACfg, sipUACfgRetryInvite=sipUACfgRetryInvite, sipUACfgRetryRegister=sipUACfgRetryRegister, sipUAStatsGroup=sipUAStatsGroup, sipUACfgTimerReRegister=sipUACfgTimerReRegister, sipUACfgRetryResponse=sipUACfgRetryResponse, sipUAConfigGroup=sipUAConfigGroup, sipUACfgRetryTable=sipUACfgRetryTable, sipUAMIBConformance=sipUAMIBConformance, sipUACompliance=sipUACompliance, sipUACfgRetry=sipUACfgRetry, sipStatsRetryByes=sipStatsRetryByes, sipUAStats=sipUAStats, sipUACfgTimerTable=sipUACfgTimerTable)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection') (appl_index,) = mibBuilder.importSymbols('NETWORK-SERVICES-MIB', 'applIndex') (sip_mib,) = mibBuilder.importSymbols('SIP-MIB-SMI', 'sipMIB') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (mib_identifier, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, object_identity, counter64, iso, module_identity, notification_type, gauge32, ip_address, time_ticks, unsigned32, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'ObjectIdentity', 'Counter64', 'iso', 'ModuleIdentity', 'NotificationType', 'Gauge32', 'IpAddress', 'TimeTicks', 'Unsigned32', 'Counter32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') sip_uamib = module_identity((1, 3, 6, 1, 2, 1, 9998, 3)) if mibBuilder.loadTexts: sipUAMIB.setLastUpdated('200007080000Z') if mibBuilder.loadTexts: sipUAMIB.setOrganization('IETF SIP Working Group, SIP MIB Team') if mibBuilder.loadTexts: sipUAMIB.setContactInfo('SIP MIB Team email: sip-mib@egroups.com \n\n Co-editor Kevin Lingle \n Cisco Systems, Inc. \n postal: 7025 Kit Creek Road \n P.O. Box 14987 \n Research Triangle Park, NC 27709 \n USA \n email: klingle@cisco.com \n phone: +1-919-392-2029 \n\n Co-editor Joon Maeng \n VTEL Corporation \n postal: 108 Wild Basin Rd. \n Austin, TX 78746 \n USA \n email: joon_maeng@vtel.com \n phone: +1-512-437-4567 \n\n Co-editor Dave Walker \n SS8 Networks, Inc. \n postal: 80 Hines Road \n Kanata, ON K2K 2T8 \n Canada \n email: drwalker@ss8networks.com \n phone: +1 613 592 2100') if mibBuilder.loadTexts: sipUAMIB.setDescription('Initial version of Session Initiation Protocol (SIP) \n User Agent (UA) MIB module. \n\n SIP is an application-layer signalling protocol for \n creating, modifying and terminating multimedia \n sessions with one or more participants. These sessions \n include Internet multimedia conferences and Internet \n telephone calls. SIP is defined in RFC 2543 (March \n 1999). \n\n A User Agent is an application that contains both a \n User Agent Client (UAC) and a User Agent Server (UAS). \n A UAC is an application that initiates a SIP request. \n A UAS is an application that contacts the user when a \n SIP request is received and that returns a response on \n behalf of the user. The response accepts, rejects, or \n redirects the request.') sip_ua_cfg = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 1)) sip_ua_cfg_timer = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1)) sip_ua_cfg_retry = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2)) sip_ua_stats = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 2)) sip_ua_stats_retry = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1)) sip_ua_cfg_timer_table = mib_table((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1)) if mibBuilder.loadTexts: sipUACfgTimerTable.setDescription('This table contains timer configuration objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sip_ua_cfg_timer_entry = mib_table_row((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: sipUACfgTimerEntry.setDescription('A row of timer configuration.') sip_ua_cfg_timer_trying = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(100, 1000))).setUnits('milliseconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgTimerTrying.setDescription('This object specifies the time a user agent will wait to \n receive a provisional response to an INVITE before \n resending the INVITE.') sip_ua_cfg_timer_prov = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(60000, 300000))).setUnits('milliseconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgTimerProv.setDescription('This object specifies the time a user agent will wait to \n receive a final response to an INVITE before canceling the \n transaction.') sip_ua_cfg_timer_ack = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(100, 1000))).setUnits('milliseconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgTimerAck.setDescription('This object specifies the time a user agent will wait to \n receive an ACK confirmation indicating that a session is \n established.') sip_ua_cfg_timer_disconnect = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(100, 1000))).setUnits('milliseconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgTimerDisconnect.setDescription('This object specifies the time a user agent will wait to \n receive a BYE confirmation indicating that a session is \n disconnected.') sip_ua_cfg_timer_re_register = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgTimerReRegister.setDescription('This object specifies how long the user agent wishes its \n registrations to be valid.') sip_ua_cfg_retry_table = mib_table((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1)) if mibBuilder.loadTexts: sipUACfgRetryTable.setDescription('This table contains retry configuration objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sip_ua_cfg_retry_entry = mib_table_row((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: sipUACfgRetryEntry.setDescription('A row of retry configuration.') sip_ua_cfg_retry_invite = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgRetryInvite.setDescription('This object will specify the number of times a user agent \n will retry sending an INVITE request.') sip_ua_cfg_retry_bye = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgRetryBye.setDescription('This object will specify the number of times a user agent \n will retry sending a BYE request.') sip_ua_cfg_retry_cancel = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgRetryCancel.setDescription('This object will specify the number of times a user agent \n will retry sending a CANCEL request.') sip_ua_cfg_retry_register = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgRetryRegister.setDescription('This object will specify the number of times a user agent \n will retry sending a REGISTER request.') sip_ua_cfg_retry_response = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 1, 2, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sipUACfgRetryResponse.setDescription('This object will specify the number of times a user agent \n will retry sending a Response and expecting an ACK.') sip_ua_stats_retry_table = mib_table((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1)) if mibBuilder.loadTexts: sipUAStatsRetryTable.setDescription('This table contains retry statistics objects applicable \n to each SIP user agent in this system. The instances of \n SIP entities are uniquely identified by applIndex.') sip_ua_stats_retry_entry = mib_table_row((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: sipUAStatsRetryEntry.setDescription('A row of retry statistics.') sip_stats_retry_invites = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sipStatsRetryInvites.setDescription("This object reflects the total number of INVITE retries \n that have been sent by the user agent. If the number of \n 'first attempt' INVITES is of interest, subtract the value \n of this object from sipStatsTrafficInviteOut.") sip_stats_retry_byes = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sipStatsRetryByes.setDescription('This object reflects the total number of BYE retries that \n have been sent by the user agent.') sip_stats_retry_cancels = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sipStatsRetryCancels.setDescription('This object reflects the total number of CANCEL retries \n that have been sent by the user agent.') sip_stats_retry_registers = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sipStatsRetryRegisters.setDescription('This object reflects the total number of REGISTER retries \n that have been sent by the user agent.') sip_stats_retry_responses = mib_table_column((1, 3, 6, 1, 2, 1, 9998, 3, 2, 1, 1, 1, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sipStatsRetryResponses.setDescription('This object reflects the total number of Response (while \n expecting an ACK) retries that have been sent by the user \n agent.') sip_uamib_notif = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 3)) sip_uamib_conformance = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 4)) sip_uamib_compliances = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 4, 1)) sip_uamib_groups = mib_identifier((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2)) sip_ua_compliance = module_compliance((1, 3, 6, 1, 2, 1, 9998, 3, 4, 1, 1)).setObjects(*(('SIP-UA-MIB', 'sipUAConfigGroup'), ('SIP-UA-MIB', 'sipUAStatsGroup'))) if mibBuilder.loadTexts: sipUACompliance.setDescription('The compliance statement for SIP entities.') sip_ua_config_group = object_group((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2, 1)).setObjects(*(('SIP-UA-MIB', 'sipUACfgTimerTrying'), ('SIP-UA-MIB', 'sipUACfgTimerProv'), ('SIP-UA-MIB', 'sipUACfgTimerAck'), ('SIP-UA-MIB', 'sipUACfgTimerDisconnect'), ('SIP-UA-MIB', 'sipUACfgTimerReRegister'), ('SIP-UA-MIB', 'sipUACfgRetryInvite'), ('SIP-UA-MIB', 'sipUACfgRetryBye'), ('SIP-UA-MIB', 'sipUACfgRetryCancel'), ('SIP-UA-MIB', 'sipUACfgRetryRegister'), ('SIP-UA-MIB', 'sipUACfgRetryResponse'))) if mibBuilder.loadTexts: sipUAConfigGroup.setDescription('A collection of objects providing configuration for \n SIP User Agents.') sip_ua_stats_group = object_group((1, 3, 6, 1, 2, 1, 9998, 3, 4, 2, 2)).setObjects(*(('SIP-UA-MIB', 'sipStatsRetryInvites'), ('SIP-UA-MIB', 'sipStatsRetryByes'), ('SIP-UA-MIB', 'sipStatsRetryCancels'), ('SIP-UA-MIB', 'sipStatsRetryRegisters'), ('SIP-UA-MIB', 'sipStatsRetryResponses'))) if mibBuilder.loadTexts: sipUAStatsGroup.setDescription('A collection of objects providing statistics for \n SIP User Agents.') mibBuilder.exportSymbols('SIP-UA-MIB', PYSNMP_MODULE_ID=sipUAMIB, sipStatsRetryInvites=sipStatsRetryInvites, sipUACfgTimerTrying=sipUACfgTimerTrying, sipUACfgTimerAck=sipUACfgTimerAck, sipUAMIBNotif=sipUAMIBNotif, sipUACfgRetryEntry=sipUACfgRetryEntry, sipUACfgRetryCancel=sipUACfgRetryCancel, sipUAMIBCompliances=sipUAMIBCompliances, sipUAMIBGroups=sipUAMIBGroups, sipStatsRetryRegisters=sipStatsRetryRegisters, sipUAStatsRetryTable=sipUAStatsRetryTable, sipUAMIB=sipUAMIB, sipUACfgTimerDisconnect=sipUACfgTimerDisconnect, sipStatsRetryCancels=sipStatsRetryCancels, sipStatsRetryResponses=sipStatsRetryResponses, sipUACfgRetryBye=sipUACfgRetryBye, sipUAStatsRetry=sipUAStatsRetry, sipUACfgTimer=sipUACfgTimer, sipUACfgTimerProv=sipUACfgTimerProv, sipUACfgTimerEntry=sipUACfgTimerEntry, sipUAStatsRetryEntry=sipUAStatsRetryEntry, sipUACfg=sipUACfg, sipUACfgRetryInvite=sipUACfgRetryInvite, sipUACfgRetryRegister=sipUACfgRetryRegister, sipUAStatsGroup=sipUAStatsGroup, sipUACfgTimerReRegister=sipUACfgTimerReRegister, sipUACfgRetryResponse=sipUACfgRetryResponse, sipUAConfigGroup=sipUAConfigGroup, sipUACfgRetryTable=sipUACfgRetryTable, sipUAMIBConformance=sipUAMIBConformance, sipUACompliance=sipUACompliance, sipUACfgRetry=sipUACfgRetry, sipStatsRetryByes=sipStatsRetryByes, sipUAStats=sipUAStats, sipUACfgTimerTable=sipUACfgTimerTable)
class Model(object): def __init__(self): self.username = None self.password = None self.deck = None def username(self): return self.username def password(self): return self.password def deck(self): return self.deck
class Model(object): def __init__(self): self.username = None self.password = None self.deck = None def username(self): return self.username def password(self): return self.password def deck(self): return self.deck
with open('text.txt', 'r') as f: for num, line in enumerate(f): if line.find('text') > -1: print(f'The word text is present on the line {num + 1}') # print(content)
with open('text.txt', 'r') as f: for (num, line) in enumerate(f): if line.find('text') > -1: print(f'The word text is present on the line {num + 1}')
def collision(x1, y1, radius1, x2, y2, radius2) -> bool: if ((x1 - x2) ** 2 + (y1 - y2) ** 2) <= (radius1 + radius2) ** 2: return True return False
def collision(x1, y1, radius1, x2, y2, radius2) -> bool: if (x1 - x2) ** 2 + (y1 - y2) ** 2 <= (radius1 + radius2) ** 2: return True return False
#removing duplicates l1=list() for i in range(5): l1.append((input("enter element:"))) print(l1) i=0 while i<len(l1): j=i+1 while j<len(l1): if l1[i]==l1[j]: del l1[j] else: j+=1 i+=1 print(l1)
l1 = list() for i in range(5): l1.append(input('enter element:')) print(l1) i = 0 while i < len(l1): j = i + 1 while j < len(l1): if l1[i] == l1[j]: del l1[j] else: j += 1 i += 1 print(l1)
EXPECTED_METRICS = { "php_apcu.cache.mem_size": 0, "php_apcu.cache.num_slots": 1, "php_apcu.cache.ttl": 0, "php_apcu.cache.num_hits": 0, "php_apcu.cache.num_misses": 0, "php_apcu.cache.num_inserts": 0, "php_apcu.cache.num_entries": 0, "php_apcu.cache.num_expunges": 0, "php_apcu.cache.uptime": 1, "php_apcu.sma.avail_mem": 1, "php_apcu.sma.seg_size": 1, "php_apcu.sma.num_seg": 1, }
expected_metrics = {'php_apcu.cache.mem_size': 0, 'php_apcu.cache.num_slots': 1, 'php_apcu.cache.ttl': 0, 'php_apcu.cache.num_hits': 0, 'php_apcu.cache.num_misses': 0, 'php_apcu.cache.num_inserts': 0, 'php_apcu.cache.num_entries': 0, 'php_apcu.cache.num_expunges': 0, 'php_apcu.cache.uptime': 1, 'php_apcu.sma.avail_mem': 1, 'php_apcu.sma.seg_size': 1, 'php_apcu.sma.num_seg': 1}
''' QUESTION: 868. Binary Gap Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. If there aren't two consecutive 1's, return 0. Example 1: Input: 22 Output: 2 Explanation: 22 in binary is 0b10110. In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2. The second consecutive pair of 1's have distance 1. The answer is the largest of these two distances, which is 2. Example 2: Input: 5 Output: 2 Explanation: 5 in binary is 0b101. Example 3: Input: 6 Output: 1 Explanation: 6 in binary is 0b110. Example 4: Input: 8 Output: 0 Explanation: 8 in binary is 0b1000. There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0. ''' class Solution(object): def binaryGap(self, N): index_lst = [] b = bin(N)[2:] for i in range(len(b)): if b[i] == '1': index_lst.append(i) max = 0 for i in range(len(index_lst) - 1): if (index_lst[i + 1] - index_lst[i]) > max: max = index_lst[i + 1] - index_lst[i] return max ''' Ideas/thoughts: convert the binary and find the positions of 1's and and see the long diff of digits. '''
""" QUESTION: 868. Binary Gap Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. If there aren't two consecutive 1's, return 0. Example 1: Input: 22 Output: 2 Explanation: 22 in binary is 0b10110. In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2. The second consecutive pair of 1's have distance 1. The answer is the largest of these two distances, which is 2. Example 2: Input: 5 Output: 2 Explanation: 5 in binary is 0b101. Example 3: Input: 6 Output: 1 Explanation: 6 in binary is 0b110. Example 4: Input: 8 Output: 0 Explanation: 8 in binary is 0b1000. There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0. """ class Solution(object): def binary_gap(self, N): index_lst = [] b = bin(N)[2:] for i in range(len(b)): if b[i] == '1': index_lst.append(i) max = 0 for i in range(len(index_lst) - 1): if index_lst[i + 1] - index_lst[i] > max: max = index_lst[i + 1] - index_lst[i] return max "\nIdeas/thoughts:\nconvert the binary and find the positions of 1's and \nand see the long diff of digits.\n\n"
def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") class InputExample(object): """A single training/test example for simple classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample.""" self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3) else: if len(tokens_a) > max_seq_length - 2: tokens_a = tokens_a[:(max_seq_length - 2)] tokens = ["[CLS]"] + tokens_a + ["[SEP]"] segment_ids = [0] * len(tokens) if tokens_b: tokens += tokens_b + ["[SEP]"] segment_ids += [1] * (len(tokens_b) + 1) input_ids = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_id = label_map[example.label] features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id)) return features
def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode('utf-8', 'ignore') else: raise value_error('Unsupported string type: %s' % type(text)) elif six.PY2: if isinstance(text, str): return text.decode('utf-8', 'ignore') elif isinstance(text, unicode): return text else: raise value_error('Unsupported string type: %s' % type(text)) else: raise value_error('Not running on Python2 or Python 3?') class Inputexample(object): """A single training/test example for simple classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample.""" self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label class Inputfeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label: i for (i, label) in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3) elif len(tokens_a) > max_seq_length - 2: tokens_a = tokens_a[:max_seq_length - 2] tokens = ['[CLS]'] + tokens_a + ['[SEP]'] segment_ids = [0] * len(tokens) if tokens_b: tokens += tokens_b + ['[SEP]'] segment_ids += [1] * (len(tokens_b) + 1) input_ids = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_id = label_map[example.label] features.append(input_features(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id)) return features