Best Python code snippet using localstack_python
test_cloudformation_apigateway.py
...96 apis = [api for api in apigateway_client.get_rest_apis()["items"] if api["name"] == api_name]97 assert len(apis) == 198 api_id = apis[0]["id"]99 # construct API endpoint URL100 url = api_invoke_url(api_id, stage="dev", path="/test")101 # invoke API endpoint, assert results102 result = requests.post(url, data="test 123")103 assert result.ok104 content = json.loads(to_str(result.content))105 assert content["data"] == "test 123"106 assert content["url"].endswith("/post")107@pytest.mark.only_localstack108def test_url_output(apigateway_client, tmp_http_server, deploy_cfn_template):109 test_port, invocations, proxy = tmp_http_server110 integration_uri = f"http://localhost:{test_port}/{{proxy}}"111 api_name = f"rest-api-{short_uid()}"112 stack = deploy_cfn_template(113 template_path=os.path.join(114 os.path.dirname(__file__), "../templates/apigateway-url-output.yaml"...
detectron2_cloud_vision_api_client.py
1# import some common libraries2# Using Python Request library3import requests4import json5import numpy as np6import time7import io8from PIL import Image, ImageDraw, ImageFont9# Define Constants10API_INVOKE_URL="<INSERT_API_INVOKE_URL>"11# define variables12url=API_INVOKE_URL13#Used to print time lapsed during different parts of code execution.14def printTimeStamp(start, log):15 end = time.time()16 print(log + ': time: {0:.2f}s'.format(end-start))17#Program reference start timestamp18# start = time.time()19# printTimeStamp(start, "Detection Time")20def cloud_api_predict(headers, payload):21 # send POST request to url22 return requests.request("POST", url, headers=headers, data=payload).text23def get_prediction_data(predictions_json):24 # Parse inference results received from the API call25 res = json.loads(predictions_json) # convert json string to Python dict for parsing26 # opacity=15027 boxes=res[0]["pred_boxes"]28 panoptic_seg=np.array(res[0]["panoptic_seg"])29 instance_list=res[0]["instance_list"]30 return boxes, panoptic_seg, instance_list31# Define Panoptic segmentation visualizer function32def pan_seg_visualizer(panoptic_seg, instance_list, metadata, boxes, opacity):33 stuff_classes=metadata["stuff_classes"]34 stuff_colors=metadata["stuff_colors"]35 thing_classes=metadata["thing_classes"]36 thing_colors=metadata["thing_colors"]37 rgba = np.zeros([480,640,4], dtype = np.uint8)38 rgba[:, :] = [255, 255, 255, 0]39 font = ImageFont.truetype('./fonts/Ubuntu-Bold.ttf', 8)40 stuff_array=[]41 for seg_info in instance_list:42 maskX=(panoptic_seg==seg_info["id"])43 binary_mask=np.array((maskX == True), dtype=int)44 if (seg_info["isthing"]):45 color=thing_colors[seg_info["category_id"]]46 rgba[(binary_mask == 1), :] = np.append(color, opacity)47 else: # isStuff48 name=stuff_classes[seg_info['category_id']]49# if (name=="road"): # filter stuff to display50 color=stuff_colors[seg_info["category_id"]]51 x,y = np.argwhere(binary_mask == 1).mean(axis=0)52 stuff_array.append((name,x,y))53 rgba[(binary_mask == 1), :] = np.append(color, opacity)54 maskXImg = Image.fromarray(np.asarray(rgba),mode='RGBA')55 draw = ImageDraw.Draw(maskXImg)56# Draw boxes and instance labels57 for seg_info, box in zip(instance_list, boxes):58 if(seg_info["isthing"]): #only process things not stuff59 # text = f"{thing_classes[seg_info['category_id']]} {.85:.0%}" # this only works with python 3.6 and above60 text = "{0} {1:.0%}".format(thing_classes[seg_info['category_id']], seg_info['score'])61 txtSize = font.getsize(text)62 width_text, height_text = txtSize[0], txtSize[1]63 draw.rectangle([(box[0], box[1]-height_text), (box[0] + width_text, box[1])], fill=(0,0,0))#text background rectangle64 draw.text((box[0], box[1]-height_text), text, fill=(255, 255, 255)) # draw text on instance65 draw.rectangle([(box[0], box[1]), (box[2], box[3])], outline=(0,255,0))#blue rectangle66 for stuff in stuff_array: 67 x1=stuff[1]68 y1=stuff[2]69 text=stuff[0]70 txtSize = font.getsize(text)71 width_text, height_text = txtSize[0], txtSize[1]72 draw.rectangle([(y1, x1), (y1 + width_text, x1+height_text)], fill=(0,0,0))#text background rectangle73 draw.text((y1, x1), text, fill=(255, 255, 255)) # draw text on instance...
__main__.py
Source: __main__.py
1import json2import pulumi3import pulumi_aws as aws4config = {}5with open('./config.json') as fp:6 config = json.load(fp)7APP_NAME = config['AppName']8LAMBDA_ROLE = config['LambdaRole']9connection_table = aws.dynamodb.Table(10 f'{APP_NAME}Connections',11 name=f'{APP_NAME}Connections',12 attributes=[13 aws.dynamodb.TableAttributeArgs(14 name='ConnectionId',15 type='S',16 ),17 ],18 billing_mode='PROVISIONED',19 hash_key='ConnectionId',20 read_capacity=5,21 write_capacity=5,22)23ws_handler = aws.lambda_.Function(24 f'{APP_NAME}WebsocketHandler',25 name=f'{APP_NAME}WebsocketHandler',26 role=LAMBDA_ROLE,27 runtime='python3.8',28 handler='app.lambda_handler',29 code=pulumi.AssetArchive({30 '.': pulumi.FileArchive('./initial_code'),31 }),32)33ws_api = aws.apigatewayv2.Api(34 f'{APP_NAME}WebsocketAPI',35 name=f'{APP_NAME}WebsocketAPI',36 protocol_type='WEBSOCKET',37 route_selection_expression='$request.body.action',38)39lambda_integration = aws.apigatewayv2.Integration(40 f'{APP_NAME}LambdaIntegration',41 api_id=ws_api.id,42 integration_type='AWS_PROXY',43 connection_type='INTERNET',44 content_handling_strategy='CONVERT_TO_TEXT',45 integration_method='POST',46 integration_uri=ws_handler.invoke_arn,47 passthrough_behavior='WHEN_NO_MATCH',48)49connect_route = aws.apigatewayv2.Route(50 f'{APP_NAME}ConnectRoute',51 api_id=ws_api.id,52 route_key='$connect',53 target=lambda_integration.id.apply(lambda integration_id: 'integrations/' + integration_id),54)55disconnect_route = aws.apigatewayv2.Route(56 f'{APP_NAME}DisconnectRoute',57 api_id=ws_api.id,58 route_key='$disconnect',59 target=lambda_integration.id.apply(lambda integration_id: 'integrations/' + integration_id),60)61default_route = aws.apigatewayv2.Route(62 f'{APP_NAME}DefaultRoute',63 api_id=ws_api.id,64 route_key='$default',65 target=lambda_integration.id.apply(lambda integration_id: 'integrations/' + integration_id),66)67stage = aws.apigatewayv2.Stage(68 f'{APP_NAME}APIStage',69 name=f'ws',70 api_id=ws_api.id,71 auto_deploy=True,72)73invoke_permission = aws.lambda_.Permission(74 f'{APP_NAME}LambdaPermission',75 action='lambda:invokeFunction',76 function=ws_handler.name,77 principal='apigateway.amazonaws.com',78 source_arn=stage.execution_arn.apply(lambda arn: arn + '*/*'),79)80pulumi.export('api_endpoint', ws_api.api_endpoint)...
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!!