作者:Brian Tarbox
译者:豌豆花下猫@Python猫
英文:https://blog.symops.com/2022/08/31/amazon-codewhisperer
转载请保留作者&译者&来源信息
Python猫注:截至2022年9月17日,这个服务还未全面开放。
若要试用,可在官网申请:https://pages.awscloud.com/codewhisperer-sign-up-form.html
Function to open an S3 file
# Function to open an S3 file
def open_s3_file(filename):
"""
:param filename:
:return:
"""
s3 = boto3.resource('s3')
return s3.Object(bucket, filename).get()['Body'].read()
boto3
API 的时间,你只需要检查代码,确保语义正确。# Function to get first n lines from a file in S3
def get_first_n_lines_from_s3(filename, n):
"""
Get the first n lines of a file in S3
:param filename:
:param n:
:return:
"""
lines = []
for line in open_s3_file(filename):
lines.append(line)
if len(lines) >= n:
break
return lines
# Function to find common elements in lists
def find_common_elements(list1, list2)
def find_common_elements(first, second)
# Function to find common elements in lists
def find_common_elements(first, second):
return list(set(first) & set(second))
# reverse the list order
lines.reverse()
# Function to emit a cloudwatch metric
def put_metric_data(metric_name, metric_data):
"""
Put a metric data into cloudwatch
:param metric_name:
:param metric_data:
:return:
"""
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_data(
Namespace='my_namespace',
MetricData=[
{
'MetricName': metric_name,
'Dimensions': [
{
'Name': 'string',
'Value': 'string'
},
],
'Unit': 'Seconds',
'Value': metric_data
},
]
)
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
# Function that returns whether this item costs more than $10
def expensive(self) -> bool:
return self.unit_price > 10
# Function to test InventoryItem class
def test_inventory_item():
"""
Test InventoryItem class
:return:
"""
item = InventoryItem("Widget", 10, 5)
assert item.name == "Widget"
assert item.unit_price == 10
assert item.quantity_on_hand == 5
assert item.total_cost() == 50
assert not item.expensive()
# Function to find the longest common line in two files
def find_longest_common_line(file1, file2):
"""
Find the longest common line in two files
:param file1:
:param file2:
:return:
"""
with open(file1, 'r') as f1:
with open(file2, 'r') as f2:
for line in f1:
if line in f2:
return line