def test_add_item(): repo = Repository() repo.add_item(1) assert repo.get_items() == [1] repo.undo() assert repo.get_items() == []
def create_repo(self, name): print('New repo is created') for repo in self.repo: if repo.get_name() == name: raise ValueError('A repository with this name already exists.') new_repo = Repository(name=name) self.repo.append(new_repo)
def save_card(word, image_path, filepath='data/cards/', filename=None): '''Функция для генерации и сохранения изображения Возвращает filepath+filename Параметры: word - слово, чей контент будет на карточке image - задний фон изображения filepath - путь для хранения изображения filename - имя изображения ''' content = urbandictionary_api.get_word_data(word) image = Image.open(image_path) rep = Repository() fonts = rep.fonts model = CardModel(content=content, image=image, auth_font=fonts.aut_font, cat_font=fonts.cat_font, def_font=fonts.def_font, ex_font=fonts.ex_font, rect_font=fonts.rect_font, word_font=fonts.word_font, thumb_font=fonts.thumb_font) card_drawer = CardDrawer(model) card_drawer.draw_card() path = card_drawer.save(filepath=filepath, filename=filename) return path
def get_balance(repo: Repository, day: int): """ Returns the account balance on a day. :param repo: The transactions repository. :param day: A day. :return balance: The balance on the given day. """ in_transactions = repo.get_items( lambda t: t.get_type() == 'in' and t.get_day() <= day) out_transactions = repo.get_items( lambda t: t.get_type() == 'out' and t.get_day() <= day) balance = 0 for in_transaction in in_transactions: balance += in_transaction.get_money_amount() for out_transaction in out_transactions: balance -= out_transaction.get_money_amount() return balance
def get_sum(repo: Repository, type: str): """ Returns the total amount from a transaction type. :param repo: The transactions repository. :param type: The transaction type. :return type_amount: The total amount from a transaction type. """ transactions = repo.get_items(lambda t: t.get_type() == type) type_amount = 0 for transaction in transactions: type_amount += transaction.get_money_amount() return type_amount
def get_repo(self, id=None, name=None): if name is not None: for repo in self.repo: if repo.get_name() == name: return repo elif id is not None: for repo in self.repo: if repo.get_id() == id: return repo return None else: # From App init repo_id = os.listdir( PATH_REPO) # Read files in repositories folder repo = [Repository(id=id) for id in repo_id] # Create Repositories objec from file return repo
class Service: def __init__(self, addr): self.rp = Repository(addr) def task1(self, country): all_tasks1 = self.rp.t1(country) val1 = list(all_tasks1) return JSONEncoder().encode(val1) # return jsonify(val) def task1_spark(self, country): all_tasks1_spark = self.rp.t1_spark(country) return jsonify(all_tasks1_spark) def task2(self, country): all_tasks2 = self.rp.t2(country) val2 = list(all_tasks2) return JSONEncoder().encode(val2) def task2_spark(self, country): all_tasks2_spark = self.rp.t2_spark(country) return jsonify(all_tasks2_spark) def task3(self, limit): all_task3 = self.rp.t3(limit) val3 = list(all_task3) return jsonify(val3) def task3_spark(self, limit): all_task3_spark = self.rp.t3_spark(limit) #return jsonify(all_task3_spark) #return jsonify(all_task3_spark) return JSONEncoder().encode(all_task3_spark) def task4(self, limit, country): all_task4 = self.rp.t4(limit, country) val4 = list(all_task4) return JSONEncoder().encode(val4) def task4_spark(self, limit, country): all_task4_spark = self.rp.t4_spark(limit, country) #return jsonify(all_task4_spark) return JSONEncoder().encode(all_task4_spark)
def get_max(repo: Repository, type: str, day: int): """ Returns the transaction with the maximum amount from a day, of a type. :param repo: The transactions repository. :param type: The transaction type. :param day: The transaction day. :return max_transaction: The transaction with the maximum amount from a day, of a type. """ transactions = repo.get_items( lambda t: t.get_day() == day and t.get_type() == type) if len(transactions) == 0: return None max_transaction: Transaction = transactions[0] for transaction in transactions: if transaction.get_money_amount() > max_transaction.get_money_amount(): max_transaction = transaction return max_transaction
def repositoryUser(self, nameUser, numPage=80): queryVariables = { "nameUser": nameUser, "numPage": numPage } RepositoryAffiliation = {'OWNER': [], 'COLLABORATOR': []} # RepositoryAffiliation = {'OWNER': [], 'COLLABORATOR': []} for repAff in RepositoryAffiliation.keys(): queryVariables["RepositoryAffiliation"] = repAff after = '' c=0 while True: query = Query.repInfo(after) resp = self.requestApiGitHubV4(query, queryVariables) for rep in resp['data']['user']['repositories']['nodes']: RepositoryAffiliation[repAff].append(Repository(repAff, self.user, rep)) if not resp['data']['user']['repositories']['pageInfo']['hasNextPage']: break after = resp['data']['user']['repositories']['pageInfo']['endCursor'] break return RepositoryAffiliation['OWNER'], RepositoryAffiliation['COLLABORATOR']
def test_replace_item(): repo = Repository() repo.add_item(0) repo.add_item(1) repo.add_item(1) repo.add_item(1) repo.replace_item(lambda item: item == 1, 0) assert repo.get_items() == [0, 0, 1, 1] repo.undo() assert repo.get_items() == [0, 1, 1, 1]
def test_get_max(): repo = Repository() repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) repo.add_item(Transaction(2, 178, 'out', 'food')) repo.add_item(Transaction(1, 1200, 'out', 'rent')) repo.add_item(Transaction(14, 54, 'out', 'food')) repo.add_item(Transaction(14, 55023, 'in', 'salary')) repo.add_item(Transaction(14, 550, 'in', 'freelancing')) repo.add_item(Transaction(23, 1200, 'out', 'project')) repo.add_item(Transaction(2, 230, 'out', 'food')) repo.add_item(Transaction(16, 176, 'out', 'food')) repo.add_item(Transaction(5, 188, 'out', 'food')) assert get_max(repo, 'in', 14).get_money_amount() == 55023 assert get_max(repo, 'out', 2).get_money_amount() == 230
def run_main() -> int: try: # Read commit information: dd_sdk_ios_commit = DogfoodedCommit() # Resolve and read `dd-sdk-ios` dependencies: dd_sdk_package_path = '../..' os.system( f'swift package --package-path {dd_sdk_package_path} resolve') dd_sdk_ios_package = PackageResolvedFile( path=f'{dd_sdk_package_path}/Package.resolved') kronos_dependency = dd_sdk_ios_package.read_dependency( package_name='Kronos') plcrash_reporter_dependency = dd_sdk_ios_package.read_dependency( package_name='PLCrashReporter') if dd_sdk_ios_package.get_number_of_dependencies() > 2: raise Exception( '`dogfood.py` needs update as `dd-sdk-ios` has unrecognized dependencies' ) # Clone `datadog-ios` repository to temporary location and update its `Package.resolved` so it points # to the current `dd-sdk-ios` commit. After that, push changes to `datadog-ios` and create dogfooding PR. with TemporaryDirectory() as temp_dir: with remember_cwd(): repository = Repository.clone( ssh='[email protected]:DataDog/datadog-ios.git', repository_name='datadog-ios', temp_dir=temp_dir) repository.create_branch( f'dogfooding-{dd_sdk_ios_commit.hash_short}') package = PackageResolvedFile( path= 'Datadog.xcworkspace/xcshareddata/swiftpm/Package.resolved' ) # Update version of `dd-sdk-ios`: package.update_dependency(package_name='DatadogSDK', new_branch='dogfooding', new_revision=dd_sdk_ios_commit.hash, new_version=None) # Set version of `Kronos` to as it is resolved in `dd-sdk-ios`: package.update_dependency( package_name='Kronos', new_branch=kronos_dependency['branch'], new_revision=kronos_dependency['revision'], new_version=kronos_dependency['version'], ) # Set version of `PLCrashReporter` to as it is resolved in `dd-sdk-ios`: package.update_dependency( package_name='PLCrashReporter', new_branch=plcrash_reporter_dependency['branch'], new_revision=plcrash_reporter_dependency['revision'], new_version=plcrash_reporter_dependency['version'], ) package.save() # Push changes to `datadog-ios`: repository.commit( message= f'Dogfooding dd-sdk-ios commit: {dd_sdk_ios_commit.hash}\n\n' + f'Dogfooded commit message: {dd_sdk_ios_commit.message}', author=dd_sdk_ios_commit.author) repository.push() # Create PR: repository.create_pr( title= f'[Dogfooding] Upgrade dd-sdk-ios to {dd_sdk_ios_commit.hash_short}', description= '⚙️ This is an automated PR upgrading the version of \`dd-sdk-ios\` to ' + f'https://github.com/DataDog/dd-sdk-ios/commit/{dd_sdk_ios_commit.hash}' ) except Exception as error: print(f'❌ Dogfooding failed: {error}') return 1 return 0
#!/usr/bin/env python3 # Copyright (c) 2015 Nuxi, https://nuxi.nl/ # # This file is distributed under a 2-clause BSD license. # See the LICENSE file for details. import logging import os import sys from src import util from src.repository import Repository # Setup logging logging.basicConfig(level=logging.INFO) # Locations relative to the source tree. DIR_ROOT = os.getcwd() DIR_DISTFILES = os.path.join(DIR_ROOT, "_obj/distfiles") DIR_TMP = os.path.join(DIR_ROOT, "_obj/fixup_patches") # Parse all of the BUILD rules. repo = Repository(None) for filename in util.walk_files(sys.argv[1]): if os.path.basename(filename) == "BUILD": repo.add_build_file(filename, DIR_DISTFILES) # Regenerate all the patches. for distfile in repo.get_distfiles(): distfile.fixup_patches(DIR_TMP)
def dogfood(dry_run: bool, repository_url: str, repository_name: str, repository_package_resolved_path: str) -> int: print(f'🐶 Dogfooding: {repository_name}...') # Read commit information: dd_sdk_ios_commit = DogfoodedCommit() # Resolve and read `dd-sdk-ios` dependencies: dd_sdk_package_path = '../..' os.system(f'swift package --package-path {dd_sdk_package_path} resolve') dd_sdk_ios_package = PackageResolvedFile( path=f'{dd_sdk_package_path}/Package.resolved') # Clone dependant repo to temporary location and update its `Package.resolved` so it points # to the current `dd-sdk-ios` commit. After that, push changes to dependant repo and create dogfooding PR. with TemporaryDirectory() as temp_dir: with remember_cwd(): repository = Repository.clone(ssh=repository_url, repository_name=repository_name, temp_dir=temp_dir) repository.create_branch( f'dogfooding-{dd_sdk_ios_commit.hash_short}') package = PackageResolvedFile( path=repository_package_resolved_path) # Update version of `dd-sdk-ios`: package.update_dependency(package_name='DatadogSDK', new_branch='dogfooding', new_revision=dd_sdk_ios_commit.hash, new_version=None) # Add or update `dd-sdk-ios` dependencies for dependency_name in dd_sdk_ios_package.read_dependency_names(): dependency = dd_sdk_ios_package.read_dependency( package_name=dependency_name) if package.has_dependency(package_name=dependency_name): package.update_dependency( package_name=dependency_name, new_branch=dependency['state']['branch'], new_revision=dependency['state']['revision'], new_version=dependency['state']['version'], ) else: package.add_dependency( package_name=dependency_name, repository_url=dependency['repositoryURL'], branch=dependency['state']['branch'], revision=dependency['state']['revision'], version=dependency['state']['version']) package.save() # Push changes to dependant repo: repository.commit( message= f'Dogfooding dd-sdk-ios commit: {dd_sdk_ios_commit.hash}\n\n' + f'Dogfooded commit message: {dd_sdk_ios_commit.message}', author=dd_sdk_ios_commit.author) if dry_run: package.print() else: repository.push() # Create PR: repository.create_pr( title= f'[Dogfooding] Upgrade dd-sdk-ios to {dd_sdk_ios_commit.hash_short}', description= '⚙️ This is an automated PR upgrading the version of \`dd-sdk-ios\` to ' + f'https://github.com/DataDog/dd-sdk-ios/commit/{dd_sdk_ios_commit.hash}' )
def setup_class(self): print(f'setup_class: {self.__name__}') print('----------------------------------') self.store = Repository(host='localhost', port=6379)
# Location of the catalog signing keys. ARCHLINUX_PRIVATE_KEY = '31344B15' CYGWIN_PRIVATE_KEY = 'A4836F43' DEBIAN_PRIVATE_KEY = '31344B15' FREEBSD_PRIVATE_KEY = '/home/ed/.cloudabi-ports-freebsd.key' REDHAT_PRIVATE_KEY = '31344B15' # The Homebrew repository needs to know its own URL. HOMEBREW_URL = 'https://nuxi.nl/distfiles/cloudabi-ports/homebrew/' # Zap the old temporary directory. util.remove_and_make_dir(DIR_TMP) # Parse all of the BUILD rules. repo = Repository(os.path.join(DIR_TMP, 'install')) # repo = Repository(os.path.join(os.getcwd(), '_obj/install')) for filename in util.walk_files(os.path.join(os.getcwd(), 'packages')): if os.path.basename(filename) == 'BUILD': repo.add_build_file(filename, DIR_DISTFILES) target_packages = repo.get_target_packages() # The catalogs that we want to create. archlinux_path = os.path.join(DIR_TMP, 'archlinux') archlinux_catalog = ArchLinuxCatalog(DIR_ARCHLINUX_CATALOG, archlinux_path) cygwin_path = os.path.join(DIR_TMP, 'cygwin') cygwin_catalog = CygwinCatalog(DIR_CYGWIN_CATALOG, cygwin_path) debian_path = os.path.join(DIR_TMP, 'debian') debian_catalog = DebianCatalog(DIR_DEBIAN_CATALOG, debian_path) freebsd_path = os.path.join(DIR_TMP, 'freebsd') freebsd_catalog = FreeBSDCatalog(DIR_FREEBSD_CATALOG, freebsd_path)
def test_get_balance(): repo = Repository() repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) repo.add_item(Transaction(24, 178, 'out', 'food')) repo.add_item(Transaction(1, 1200, 'out', 'rent')) repo.add_item(Transaction(14, 54, 'out', 'food')) repo.add_item(Transaction(14, 55023, 'in', 'salary')) repo.add_item(Transaction(16, 550, 'in', 'freelancing')) repo.add_item(Transaction(23, 1200, 'out', 'project')) repo.add_item(Transaction(2, 230, 'out', 'food')) repo.add_item(Transaction(16, 176, 'out', 'food')) repo.add_item(Transaction(5, 188, 'out', 'food')) assert get_balance(repo, 2) == 479 assert get_balance(repo, 5) == 291
# Locations relative to the source tree. DIR_ROOT = os.getcwd() DIR_DISTFILES = os.path.join(DIR_ROOT, '_obj/distfiles') DIR_INSTALL = os.path.join(DIR_ROOT, '_obj/install') DIR_PACKAGES_ARCHLINUX = os.path.join(DIR_ROOT, '_obj/packages/archlinux') DIR_PACKAGES_CYGWIN = os.path.join(DIR_ROOT, '_obj/packages/cygwin') DIR_PACKAGES_DEBIAN = os.path.join(DIR_ROOT, '_obj/packages/debian') DIR_PACKAGES_FREEBSD = os.path.join(DIR_ROOT, '_obj/packages/freebsd') DIR_PACKAGES_HOMEBREW = os.path.join(DIR_ROOT, '_obj/packages/homebrew') DIR_PACKAGES_NETBSD = os.path.join(DIR_ROOT, '_obj/packages/netbsd') DIR_PACKAGES_OPENBSD = os.path.join(DIR_ROOT, '_obj/packages/openbsd') DIR_PACKAGES_REDHAT = os.path.join(DIR_ROOT, '_obj/packages/redhat') DIR_REPOSITORY = os.path.join(DIR_ROOT, 'packages') # Parse all of the BUILD rules. repo = Repository(DIR_INSTALL) for filename in util.walk_files(DIR_REPOSITORY): if os.path.basename(filename) == 'BUILD': repo.add_build_file(filename, DIR_DISTFILES) target_packages = repo.get_target_packages() catalogs = { ArchLinuxCatalog(None, DIR_PACKAGES_ARCHLINUX), CygwinCatalog(None, DIR_PACKAGES_CYGWIN), DebianCatalog(None, DIR_PACKAGES_DEBIAN), FreeBSDCatalog(None, DIR_PACKAGES_FREEBSD), HomebrewCatalog(None, DIR_PACKAGES_HOMEBREW, 'http://example.com/'), NetBSDCatalog(None, DIR_PACKAGES_NETBSD), OpenBSDCatalog(None, DIR_PACKAGES_OPENBSD), RedHatCatalog(None, DIR_PACKAGES_REDHAT), }
def test_get_items(): repo = Repository() repo.add_item(0) repo.add_item(1) assert repo.get_item(lambda item: item == 1) == 1 repo.add_item(1) assert repo.get_items() == [0, 1, 1] assert repo.get_items(lambda item: item == 1) == [1, 1] assert not repo.get_items(lambda item: item > 1) repo.add_item(2) assert repo.get_items(lambda item: item > 1) == [2]
def __init__(self, addr): self.rp = Repository(addr)
import stat import subprocess import sys from src import config from src import util from src.repository import Repository # Locations relative to the source tree. DIR_ROOT = os.getcwd() DIR_DISTFILES = os.path.join(DIR_ROOT, '_obj/distfiles') DIR_INSTALL = os.path.join(DIR_ROOT, '_obj/install') DIR_REPOSITORY = os.path.join(DIR_ROOT, 'packages') # Parse all of the BUILD rules. repo = Repository(DIR_INSTALL) for dirname, filename in util.walk_files(DIR_REPOSITORY): if filename == 'BUILD': repo.add_build_file(os.path.join(dirname, 'BUILD'), DIR_DISTFILES) target_packages = repo.get_target_packages() if len(sys.argv) > 1: # Only build the packages provided on the command line. for name in set(sys.argv[1:]): for arch in config.ARCHITECTURES: target_packages[(name, arch)].build() else: # Build all packages. for name, arch in target_packages: target_packages[(name, arch)].build()
# Final location of the catalogs. DIR_DEBIAN_CATALOG = '/usr/local/www/nuxi.nl/public/distfiles/cloudabi-ports/debian' DIR_FREEBSD_CATALOG = '/usr/local/www/nuxi.nl/public/distfiles/cloudabi-ports/freebsd' DIR_NETBSD_CATALOG = '/usr/local/www/nuxi.nl/public/distfiles/cloudabi-ports/netbsd' DIR_OPENBSD_CATALOG = '/usr/local/www/nuxi.nl/public/distfiles/cloudabi-ports/openbsd' # Location of the catalog signing keys. DEBIAN_PRIVATE_KEY = '31344B15' FREEBSD_PRIVATE_KEY = '/home/edje/.cloudabi-ports-freebsd.key' # Zap the old temporary directory. util.remove_and_make_dir(DIR_TMP) # Parse all of the BUILD rules. repo = Repository(os.path.join(DIR_TMP, 'install')) # repo = Repository(os.path.join(os.getcwd(), '_obj/install')) for filename in util.walk_files(os.path.join(os.getcwd(), 'packages')): if os.path.basename(filename) == 'BUILD': repo.add_build_file(filename, DIR_DISTFILES) target_packages = repo.get_target_packages() # The catalogs that we want to create. debian_path = os.path.join(DIR_TMP, 'debian') debian_catalog = DebianCatalog(DIR_DEBIAN_CATALOG, debian_path) freebsd_path = os.path.join(DIR_TMP, 'freebsd') freebsd_catalog = FreeBSDCatalog(DIR_FREEBSD_CATALOG, freebsd_path) netbsd_path = os.path.join(DIR_TMP, 'netbsd') netbsd_catalog = NetBSDCatalog(DIR_NETBSD_CATALOG, netbsd_path) openbsd_path = os.path.join(DIR_TMP, 'openbsd') openbsd_catalog = OpenBSDCatalog(DIR_OPENBSD_CATALOG, openbsd_path)
class TransactionCommands(clisys.CLISys): def __init__(self): super().__init__() self.__repo = Repository() self.init_repo() @clisys.command(name='help') def help(self, args): """ Displays help for all commands or a single command. help help <command> """ count = len(args) commands = self.get_commands() if count == 0: for cmd_name, cmd in commands.items(): print(f'{cmd_name}: {cmd.__doc__}') elif count == 1: cmd_name = args[0] if not (cmd_name in commands.keys()): raise clisys.InvalidArgument(args[0]) cmd = commands[cmd_name] print(f'{cmd_name}: {cmd.__doc__}') @clisys.command(name='test') def test(self, args): """ Test command. """ print('TEST') @clisys.command(name='exit') def exit_command(self, args): """ Exits the program. """ exit(0) @clisys.command(name='add') def add_transaction(self, args): """ Add a transaction to the list. add <value> <type> <description> """ try: value = int(args[0]) except ValueError: raise clisys.InvalidArgument(args[0]) type = args[1] description = args[2] transaction = Transaction(int(datetime.today().strftime('%d')), value, type, description) self.__repo.add_item(transaction) @clisys.command(name='insert') def insert_transaction(self, args): """ Insert a transaction in the list. insert <day> <value> <type> <description> """ try: day = int(args[0]) except ValueError: raise clisys.InvalidArgument(args[0]) try: value = int(args[1]) except ValueError: raise clisys.InvalidArgument(args[1]) type = args[2] description = args[3] transaction = Transaction(day, value, type, description) self.__repo.add_item(transaction) @clisys.command(name='remove') def remove_transaction(self, args): """ Remove transactions from the list. remove <day> remove <start day> to <end day> remove <type> """ count = len(args) if count == 1: try: day = int(args[0]) self.__repo.remove_items(lambda t: t.get_day() == day) except ValueError: type = args[0] self.__repo.remove_items(lambda t: t.get_type() == type) elif count == 3: if args[1] != 'to': raise clisys.InvalidArgument(args[1]) start_day = int(args[0]) end_day = int(args[2]) self.__repo.remove_items( lambda t: start_day <= t.get_day() <= end_day) else: raise clisys.InvalidArgumentCount @clisys.command(name='replace') def replace_transaction(self, args): """ Replace the amount of a transaction with a given value. replace <day> <type> <description> with <value> """ if len(args) != 5: raise clisys.InvalidArgumentCount if args[3] != 'with': raise clisys.InvalidArgument(args[3]) try: day = int(args[0]) except ValueError: raise clisys.InvalidArgument(args[0]) type = args[1] description = args[2] try: value = int(args[4]) except ValueError: raise clisys.InvalidArgument(args[4]) self.__repo.replace_item( lambda t: t.get_day() == day and t.get_type() == type and t. get_description() == description, Transaction(day, value, type, description)) @clisys.command(name='list') def list_transactions(self, args): """ Display the list of transactions. list list <type> list [ < | = | > ] <value> list balance <day> """ count = len(args) if count == 0: display_transactions(self.__repo.get_items()) elif count == 1: type = args[0] display_transactions( self.__repo.get_items(lambda t: t.get_type() == type)) elif count == 2: option = args[0] if option == 'balance': try: day = int(args[1]) except ValueError: raise clisys.InvalidArgument(args[1]) balance = get_balance(self.__repo, day) print(f"Balance on day {day}: {balance}") elif option in ['<', '=', '>']: try: amount = int(args[1]) except ValueError: raise clisys.InvalidArgument(args[1]) if option == '<': display_transactions( self.__repo.get_items( lambda t: t.get_money_amount() < amount)) elif option == '=': display_transactions( self.__repo.get_items( lambda t: t.get_money_amount() == amount)) elif option == '>': display_transactions( self.__repo.get_items( lambda t: t.get_money_amount() > amount)) else: raise clisys.InvalidArgument(args[0]) else: raise clisys.InvalidArgumentCount @clisys.command(name='sum') def sum_transactions(self, args): """ Displays the total amount from a transaction type. sum <type> """ if len(args) > 1: raise clisys.InvalidArgumentCount type = args[0] result = get_sum(self.__repo, type) print(f'Total amount from "{type}" transactions: {result}') @clisys.command(name='max') def max_transaction(self, args): if len(args) != 2: raise clisys.InvalidArgumentCount type = args[0] try: day = int(args[1]) except ValueError: raise clisys.InvalidArgument(args[1]) result = get_max(self.__repo, type, day) if result is None: print(f'No transaction of type "{type}" on day {day}.') else: print( f'The maximum "{type}" transaction on day {day}: "{result.get_description()}: {result.get_money_amount()}"' ) @clisys.command(name='filter') def filter_transactions(self, args): """ Filters the transactions. filter <type> filter <type> <value> """ count = len(args) if count == 1: type = args[0] self.__repo.remove_items(lambda t: t.get_type() != type) elif count == 2: type = args[0] try: value = int(args[1]) except ValueError: raise clisys.InvalidArgument([args[1]]) self.__repo.remove_items(lambda t: t.get_type() != type or t. get_money_amount() >= value) print('Transactions filtered successfully!') @clisys.command(name='undo') def undo(self, args): """ Undo the last command that changed the transactions list. undo """ try: self.__repo.undo() print('Undo executed successfully!') except cmdsys.EmptyActionsStack: print('Nothing to undo.') @clisys.command(name='redo') def redo(self, args): """ Redo the last undo-ed command. redo """ try: self.__repo.redo() print('Redo executed successfully!') except cmdsys.EmptyUndoStack: print('Nothing to redo.') @clisys.exception_handler def handle_exceptions(self, exception: Exception): """ Handles exceptions raised in commands. :param exception: The exception. :return: """ try: raise exception except clisys.InvalidCommand as e: print(f'Invalid command: "{str(e.command_name)}" .') except clisys.InvalidArgument as e: print(f'Invalid argument: "{str(e.argument_name)}" .') except clisys.InvalidArgumentCount: print(f'Invalid argument count.') @clisys.input_handler def get_input(self): """ Gets the input and returns it as a list :return: A list of strings. """ i = input('\n> ') i = re.split(r' +', i) return i def init_repo(self): self.__repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) self.__repo.add_item(Transaction(24, 178, 'out', 'food')) self.__repo.add_item(Transaction(1, 1200, 'out', 'rent')) self.__repo.add_item(Transaction(14, 54, 'out', 'food')) self.__repo.add_item(Transaction(14, 55023, 'in', 'salary')) self.__repo.add_item(Transaction(16, 550, 'in', 'freelancing')) self.__repo.add_item(Transaction(23, 1200, 'out', 'project')) self.__repo.add_item(Transaction(2, 230, 'out', 'food')) self.__repo.add_item(Transaction(16, 176, 'out', 'food')) self.__repo.add_item(Transaction(5, 188, 'out', 'food'))
#!/usr/bin/env python3 # Copyright (c) 2015 Nuxi, https://nuxi.nl/ # # SPDX-License-Identifier: BSD-2-Clause import logging import os import sys from src import util from src.repository import Repository # Setup logging logging.basicConfig(level=logging.INFO) # Locations relative to the source tree. DIR_ROOT = os.getcwd() DIR_DISTFILES = os.path.join(DIR_ROOT, '_obj/distfiles') DIR_TMP = os.path.join(DIR_ROOT, '_obj/fixup_patches') # Parse all of the BUILD rules. repo = Repository(None) # type: ignore for arg in sys.argv[1:]: for filename in util.walk_files(arg): if os.path.basename(filename) == 'BUILD': repo.add_build_file(filename, DIR_DISTFILES) # Regenerate all the patches. for distfile in repo.get_distfiles(): distfile.fixup_patches(DIR_TMP)
def __init__(self): super().__init__() self.__repo = Repository() self.init_repo()
class TestDataStore: def setup_class(self): print(f'setup_class: {self.__name__}') print('----------------------------------') self.store = Repository(host='localhost', port=6379) # self.db_filedescriptor, acrewstic.app.config['DATABASE'] # = tempfile.mkstemp() # acrewstic.app.config['TESTING'] = True # self.app = acrewstic.app.test_client() # with acrewstic.app.app_context(): # acrewstic.init_db() def teardown_class(self): print(f'teardown_class: {self.__name__}') print('----------------------------------') # os.close(self.db_filedescriptor) # os.unlink(acrewstic.app.config['DATABASE']) def setup_method(self): self.store.delete(TEST_KEY_STORE) def teardown_method(self): self.store.delete(TEST_KEY_STORE) def test_0_put_string(self): current_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert current_size == 0 self.store.append_item(TEST_KEY_STORE, test_string) new_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert new_size == current_size + 1 print("Successfully setting up string") def test_1_put_int(self): current_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert current_size == 0 self.store.append_item(TEST_KEY_STORE, test_int) new_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert new_size == current_size + 1 print("Successfully setting up int") def test_2_put_dict(self): current_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert current_size == 0 self.store.append_item(TEST_KEY_STORE, test_dict) new_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert new_size == current_size + 1 print("Successfully setting up dict") def test_3_append_and_get(self): current_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert current_size == 0 self.store.append_item(TEST_KEY_STORE, test_string) self.store.append_item(TEST_KEY_STORE, test_int) self.store.append_item(TEST_KEY_STORE, test_dict) new_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert new_size == current_size + 3 item = self.store.get_item(TEST_KEY_STORE, 0) assert isinstance(item, str) item = self.store.get_item(TEST_KEY_STORE, 1) assert isinstance(item, int) item = self.store.get_item(TEST_KEY_STORE, 2) assert isinstance(item, dict) print("Successfully appending string, int and dict in correct order") def test_4_set_and_get(self): self.store.set(TEST_KEY_STORE, test_list) current_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert current_size == len(test_list) index = 4 item = self.store.get_item(TEST_KEY_STORE, index) assert isinstance(item, int) assert item == index + 1 new_size = len(self.store.fetch_all(TEST_KEY_STORE)) assert new_size == len(test_list) assert new_size == current_size item = self.store.get_item(TEST_KEY_STORE, index) assert item == index + 1 print("Successfully setting up list and retrieving items")
class UI(clisys.CLISys): def __init__(self): super().__init__() self.__repo = Repository() self.init_repo() @clisys.command('1', description='Add expense.') def add_expense(self, args): try: expense = read_expense() except ValueError: raise ExpenseError('Invalid expense.') self.__repo.add_item(expense) print('Expense added successfully!') @clisys.command('2', description='Show expenses.') def list_expenses(self, args): """ Displays the list of expenses. :param args: :return: """ expenses = self.__repo.get_items() print('Id\t|\tDay\t|\tAmount\t|\tType', end='\n\n') for i, expense in enumerate(expenses): print(f'{i + 1}.\t\t{expense.day}\t\t{expense.money_amount}\t\t\t{expense.type}') @clisys.command(name='3', description='Filter expenses.') def filter_expenses(self, args): """ Filter the expenses list :param args: :return: """ try: min_value = int(input('Input the minimum value: ')) except ValueError: raise ValueError('Invalid minimum value.') self.__repo.remove_items(lambda e: e.money_amount <= min_value) print('Expenses filtered successfully!') @clisys.command(name='4', description='Undo.') def undo(self, args): """ Undo the last command that changed the expenses list. :param args: :return: """ self.__repo.undo() print('Undo executed successfully!') @clisys.command(name='5', description='Redo.') def redo(self, args): """ Undo the last command that changed the expenses list. :param args: :return: """ self.__repo.redo() print('Redo executed successfully!') @clisys.command(name='-1', description='Exit.') def exit_program(self, args): """ Exits the program. """ exit(0) @clisys.exception_handler def handle_exceptions(self, exception: Exception): """ Handles exceptions raised in commands. :param exception: The exception. :return: """ try: raise exception except clisys.InvalidCommand as e: print(f'Invalid option: "{str(e.command_name)}" .') except clisys.InvalidArgument as e: print(f'Invalid argument: "{str(e.argument_name)}" .') except clisys.InvalidArgumentCount: print('Invalid argument count.') except cmdsys.EmptyActionsStack: print('Nothing to undo.') except cmdsys.EmptyUndoStack: print('Nothing to redo.') except ExpenseError as e: print(e) except ValueError as e: print(e) def display_options(self): """ Displays the list of options. :return: """ print() options = list(self.get_commands().values()) options.sort(key=lambda op: op.name) for option in options: print(f'{option.name}. {option.description}') @clisys.input_handler def get_option(self): """ Gets the input and returns it as a list :return: A list of strings. (first element is the name of the command) """ self.display_options() i = input('\nOption: ') return [i] def init_repo(self): self.__repo.add_item(Expense(1, 10, 'food')) self.__repo.add_item(Expense(1, 120, 'internet')) self.__repo.add_item(Expense(1, 112, 'food')) self.__repo.add_item(Expense(4, 20, 'food')) self.__repo.add_item(Expense(4, 100, 'electricity')) self.__repo.add_item(Expense(6, 980, 'phone')) self.__repo.add_item(Expense(8, 1, 'food')) self.__repo.add_item(Expense(8, 16, 'food')) self.__repo.add_item(Expense(23, 100, 'food')) self.__repo.add_item(Expense(30, 233, 'gas'))