Best Python code snippet using localstack_python
Customer.py
Source: Customer.py
1#2# Customer.py3#4# Marco Ermini - March 2021 for ASU CSE531 Course5# Do not leech!6# Built with python 3.8 with GRPC and GRPC-tools libraries; may work with other Python versions7'''Implementation of a banking's branches/customers RPC synchronisation using GRPC, multiprocessing and Python8Customer Class'''9import time10import datetime11import multiprocessing12#import array13import json14from concurrent import futures15from Util import setup_logger, MyLog16import grpc17import banking_pb218import banking_pb2_grpc19#from Main import get_operation, get_operation_name, get_result_name20ONE_DAY = datetime.timedelta(days=1)21logger = setup_logger("Customer")22class Customer:23 def __init__(self, ID, events):24 # unique ID of the Customer25 self.id = ID26 # events from the input27 self.events = events28 # a list of received messages used for debugging purpose29 self.recvMsg = list()30 # pointer for the stub31 self.stub = None32 # Create stub for the customer, matching them with their respective branch33 #34 def createStub(self, Branch_address, THREAD_CONCURRENCY):35 """Start a client (customer) stub."""36 37 MyLog(logger, f'Initializing customer stub to branch stub at {Branch_address}')38 39 self.stub = banking_pb2_grpc.BankingStub(grpc.insecure_channel(Branch_address))40 client = grpc.server(futures.ThreadPoolExecutor(max_workers=THREAD_CONCURRENCY,),)41 #banking_pb2_grpc.add_BankingServicer_to_server(Customer, client)42 client.start()43 # Iterate through the list of the customer events, sends the messages,44 # and output to the JSON file45 #46 def executeEvents(self, output_file):47 """Execute customer events."""48 49 # DEBUG50 #MyLog(logger,f'Executing events for Customer #{self.id}')51 52 record = {'id': self.id, 'recv': []}53 for event in self.events:54 request_id = event['id']55 request_operation = get_operation(event['interface'])56 request_amount = event['money']57 response = self.stub.MsgDelivery(58 banking_pb2.MsgDeliveryRequest(59 S_ID=request_id,60 OP=request_operation,61 Amount=request_amount,62 D_ID=self.id,63 )64 )65 MyLog(logger,66 f'Customer {self.id} sent request {request_id} to Branch {response.ID} '67 f'interface {get_operation_name(request_operation)} result {get_result_name(response.RC)} '68 f'money {response.Amount}')69 values = {70 'interface': get_operation_name(request_operation),71 'result': get_result_name(response.RC),72 }73 if request_operation == banking_pb2.QUERY:74 values['money'] = response.Amount75 record['recv'].append(values)76 if record['recv']:77 # DEBUG78 #MyLog(logger,f'Writing JSON file on #{output_file}')79 with open(f'{output_file}', 'a') as outfile:80 json.dump(record, outfile)81 outfile.write('\n')82 # Spawn the Customer process client. No need to bind to a port here; rather, we are connecting to one.83 #84 def Run_Customer(self, Branch_address, output_file, THREAD_CONCURRENCY):85 """Start a client (customer) in a subprocess."""86 # DEBUG87 #MyLog(logger,f'Processing Customer #{self.id} with Events:' )88 #for e in self.events:89 # MyLog(logger,f' #{e["id"]} = {e["interface"]}, {e["money"]}' )90 91 MyLog(logger,f'Running client customer #{self.id} connecting to server {Branch_address}...')92 Customer.createStub(self, Branch_address, THREAD_CONCURRENCY)93 Customer.executeEvents(self, output_file)94 # Wait one day until keypress95 #try:96 # while True:97 # time.sleep(ONE_DAY.total_seconds())98 #except KeyboardInterrupt:99 # server.stop(None)100 101 MyLog(logger,f'Client customer #{self.id} connecting to server {Branch_address} exiting successfully.')102# Utility functions, used for readability103#104def get_operation(operation):105 """Returns the message type from the operation described in the input file."""106 if operation == 'query':107 return banking_pb2.QUERY108 if operation == 'deposit':109 return banking_pb2.DEPOSIT110 if operation == 'withdraw':111 return banking_pb2.WITHDRAW112def get_operation_name(operation):113 """Returns the operation type from the message."""114 if operation == banking_pb2.QUERY:115 return 'QUERY'116 if operation == banking_pb2.DEPOSIT:117 return 'DEPOSIT'118 if operation == banking_pb2.WITHDRAW:119 return 'WITHDRAW'120def get_result_name(name):121 """Return state of a client's operation."""122 if name == banking_pb2.SUCCESS:123 return 'SUCCESS'124 if name == banking_pb2.FAILURE:125 return 'FAILURE'126 if name == banking_pb2.ERROR:...
1.py
Source: 1.py
...6ÐÑли полÑзоваÑÐµÐ»Ñ Ð²Ð²Ð¾Ð´Ð¸Ñ Ð½ÐµÐ²ÐµÑнÑй знак (не '0', '+', '-', '*', '/'), Ñо пÑогÑамма должна ÑообÑаÑÑ ÐµÐ¼Ñ Ð¾Ð± оÑибке7и Ñнова запÑаÑиваÑÑ Ð·Ð½Ð°Ðº опеÑаÑии. Также ÑообÑаÑÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð¾ невозможноÑÑи Ð´ÐµÐ»ÐµÐ½Ð¸Ñ Ð½Ð° нолÑ, еÑли он ввел 08в каÑеÑÑве делиÑелÑ.9"""10def request_operation():11 allow_operations = ['0', '+', '-', '*', '/']12 operation = str(input('знак опеÑаÑии или 0 Ð´Ð»Ñ Ð¿ÑекÑаÑениÑ: '))13 if operation not in allow_operations:14 print(f'-- допÑÑÑимÑе знаÑÐµÐ½Ð¸Ñ Ð¾Ð¿ÐµÑаÑии {allow_operations}, еÑе Ñаз --')15 operation = request_operation()16 return operation17while True:18 dig1, dig2 = map(int, input('введиÑе два ÑиÑла: ').split())19 operation = request_operation()20 if operation == '0':21 break22 elif operation == '/' and dig2 == 0:23 print('нелÑÐ·Ñ Ð´ÐµÐ»Ð¸ÑÑ Ð½Ð° нолÑ!')24 else:25 # if operation == '+':26 # res = dig1 + dig227 # elif operation == '-':28 # res = dig1 - dig229 # elif operation == '*':30 # res = dig1 * dig231 # else:32 # res = dig1 / dig233 res = eval(f'{dig1} {operation} {dig2}')...
youtube_api.py
Source: youtube_api.py
...38 }39 request_operation = dic.get(method, None)40 if request_operation:41 if method == "get":42 response = request_operation(url, params=params, headers=headers)43 elif not file:44 response = request_operation(url, params=params, headers=headers,45 json=body)46 else:47 response = request_operation(url, params=params, headers=headers,48 json=body, files=file)49 if response_file:50 save_file(response_file, response)51 return response52if __name__ == "__main__":53 scope = ['https://www.googleapis.com/auth/youtube',54 'https://www.googleapis.com/auth/youtube.force-ssl']55 client_secret_file = 'client_secret.json'56 info = read_config()57 credentials = get_credential_token()58 # For authentication59 info['headers']['Authorization'] = 'Bearer {}'.format(credentials)60 response = request(info['method'],61 info['url'],...
Check out the latest blogs from LambdaTest on this topic:
The fact is not alien to us anymore that cross browser testing is imperative to enhance your application’s user experience. Enhanced knowledge of popular and highly acclaimed testing frameworks goes a long way in developing a new app. It holds more significance if you are a full-stack developer or expert programmer.
QA testers have a unique role and responsibility to serve the customer. Serving the customer in software testing means protecting customers from application defects, failures, and perceived failures from missing or misunderstood requirements. Testing for known requirements based on documentation or discussion is the core of the testing profession. One unique way QA testers can both differentiate themselves and be innovative occurs when senseshaping is used to improve the application user experience.
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!