text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Get information about an attribute of a snapshot. Only one attribute
<END_TASK>
<USER_TASK:>
Description:
def get_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission'):
"""
Get information about an attribute of a snapshot. Only one attribute
can be specified per call.
:type snapshot_id: str
:param snapshot_id: The ID of the snapshot.
:type attribute: str
:param attribute: The requested attribute. Valid values are:
* createVolumePermission
:rtype: list of :class:`boto.ec2.snapshotattribute.SnapshotAttribute`
:return: The requested Snapshot attribute
""" |
params = {'Attribute' : attribute}
if snapshot_id:
params['SnapshotId'] = snapshot_id
return self.get_object('DescribeSnapshotAttribute', params,
SnapshotAttribute, verb='POST') |
<SYSTEM_TASK:>
Resets an attribute of a snapshot to its default value.
<END_TASK>
<USER_TASK:>
Description:
def reset_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission'):
"""
Resets an attribute of a snapshot to its default value.
:type snapshot_id: string
:param snapshot_id: ID of the snapshot
:type attribute: string
:param attribute: The attribute to reset
:rtype: bool
:return: Whether the operation succeeded or not
""" |
params = {'SnapshotId' : snapshot_id,
'Attribute' : attribute}
return self.get_status('ResetSnapshotAttribute', params, verb='POST') |
<SYSTEM_TASK:>
Get all key pairs associated with your account.
<END_TASK>
<USER_TASK:>
Description:
def get_all_key_pairs(self, keynames=None, filters=None):
"""
Get all key pairs associated with your account.
:type keynames: list
:param keynames: A list of the names of keypairs to retrieve.
If not provided, all key pairs will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.keypair.KeyPair`
""" |
params = {}
if keynames:
self.build_list_params(params, keynames, 'KeyName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeKeyPairs', params,
[('item', KeyPair)], verb='POST') |
<SYSTEM_TASK:>
Create a new key pair for your account.
<END_TASK>
<USER_TASK:>
Description:
def create_key_pair(self, key_name):
"""
Create a new key pair for your account.
This will create the key pair within the region you
are currently connected to.
:type key_name: string
:param key_name: The name of the new keypair
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
The material attribute of the new KeyPair object
will contain the the unencrypted PEM encoded RSA private key.
""" |
params = {'KeyName':key_name}
return self.get_object('CreateKeyPair', params, KeyPair, verb='POST') |
<SYSTEM_TASK:>
mports the public key from an RSA key pair that you created
<END_TASK>
<USER_TASK:>
Description:
def import_key_pair(self, key_name, public_key_material):
"""
mports the public key from an RSA key pair that you created
with a third-party tool.
Supported formats:
* OpenSSH public key format (e.g., the format
in ~/.ssh/authorized_keys)
* Base64 encoded DER format
* SSH public key file format as specified in RFC4716
DSA keys are not supported. Make sure your key generator is
set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
:type key_name: string
:param key_name: The name of the new keypair
:type public_key_material: string
:param public_key_material: The public key. You must base64 encode
the public key material before sending
it to AWS.
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
The material attribute of the new KeyPair object
will contain the the unencrypted PEM encoded RSA private key.
""" |
public_key_material = base64.b64encode(public_key_material)
params = {'KeyName' : key_name,
'PublicKeyMaterial' : public_key_material}
return self.get_object('ImportKeyPair', params, KeyPair, verb='POST') |
<SYSTEM_TASK:>
Delete a security group from your account.
<END_TASK>
<USER_TASK:>
Description:
def delete_security_group(self, name=None, group_id=None):
"""
Delete a security group from your account.
:type name: string
:param name: The name of the security group to delete.
:type group_id: string
:param group_id: The ID of the security group to delete within
a VPC.
:rtype: bool
:return: True if successful.
""" |
params = {}
if name is not None:
params['GroupName'] = name
elif group_id is not None:
params['GroupId'] = group_id
return self.get_status('DeleteSecurityGroup', params, verb='POST') |
<SYSTEM_TASK:>
Add a new rule to an existing security group.
<END_TASK>
<USER_TASK:>
Description:
def authorize_security_group(self, group_name=None,
src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, group_id=None,
src_security_group_group_id=None):
"""
Add a new rule to an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are authorizing another
group or you are authorizing some ip-based rule.
:type group_name: string
:param group_name: The name of the security group you are adding
the rule to.
:type src_security_group_name: string
:param src_security_group_name: The name of the security group you are
granting access to.
:type src_security_group_owner_id: string
:param src_security_group_owner_id: The ID of the owner of the security
group you are granting access to.
:type ip_protocol: string
:param ip_protocol: Either tcp | udp | icmp
:type from_port: int
:param from_port: The beginning port number you are enabling
:type to_port: int
:param to_port: The ending port number you are enabling
:type cidr_ip: string
:param cidr_ip: The CIDR block you are providing access to.
See http://goo.gl/Yj5QC
:type group_id: string
:param group_id: ID of the EC2 or VPC security group to modify.
This is required for VPC security groups and
can be used instead of group_name for EC2
security groups.
:type group_id: string
:param group_id: ID of the EC2 or VPC source security group.
This is required for VPC security groups and
can be used instead of group_name for EC2
security groups.
:rtype: bool
:return: True if successful.
""" |
if src_security_group_name:
if from_port is None and to_port is None and ip_protocol is None:
return self.authorize_security_group_deprecated(
group_name, src_security_group_name,
src_security_group_owner_id)
params = {}
if group_name:
params['GroupName'] = group_name
if group_id:
params['GroupId'] = group_id
if src_security_group_name:
param_name = 'IpPermissions.1.Groups.1.GroupName'
params[param_name] = src_security_group_name
if src_security_group_owner_id:
param_name = 'IpPermissions.1.Groups.1.UserId'
params[param_name] = src_security_group_owner_id
if src_security_group_group_id:
param_name = 'IpPermissions.1.Groups.1.GroupId'
params[param_name] = src_security_group_group_id
if ip_protocol:
params['IpPermissions.1.IpProtocol'] = ip_protocol
if from_port is not None:
params['IpPermissions.1.FromPort'] = from_port
if to_port is not None:
params['IpPermissions.1.ToPort'] = to_port
if cidr_ip:
params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip
return self.get_status('AuthorizeSecurityGroupIngress',
params, verb='POST') |
<SYSTEM_TASK:>
The action adds one or more egress rules to a VPC security
<END_TASK>
<USER_TASK:>
Description:
def authorize_security_group_egress(self,
group_id,
ip_protocol,
from_port=None,
to_port=None,
src_group_id=None,
cidr_ip=None):
"""
The action adds one or more egress rules to a VPC security
group. Specifically, this action permits instances in a
security group to send traffic to one or more destination
CIDR IP address ranges, or to one or more destination
security groups in the same VPC.
""" |
params = {
'GroupId': group_id,
'IpPermissions.1.IpProtocol': ip_protocol
}
if from_port is not None:
params['IpPermissions.1.FromPort'] = from_port
if to_port is not None:
params['IpPermissions.1.ToPort'] = to_port
if src_group_id is not None:
params['IpPermissions.1.Groups.1.GroupId'] = src_group_id
if cidr_ip is not None:
params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip
return self.get_status('AuthorizeSecurityGroupEgress',
params, verb='POST') |
<SYSTEM_TASK:>
Remove an existing rule from an existing security group.
<END_TASK>
<USER_TASK:>
Description:
def revoke_security_group(self, group_name=None, src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, group_id=None,
src_security_group_group_id=None):
"""
Remove an existing rule from an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are revoking another
group or you are revoking some ip-based rule.
:type group_name: string
:param group_name: The name of the security group you are removing
the rule from.
:type src_security_group_name: string
:param src_security_group_name: The name of the security group you are
revoking access to.
:type src_security_group_owner_id: string
:param src_security_group_owner_id: The ID of the owner of the security
group you are revoking access to.
:type ip_protocol: string
:param ip_protocol: Either tcp | udp | icmp
:type from_port: int
:param from_port: The beginning port number you are disabling
:type to_port: int
:param to_port: The ending port number you are disabling
:type cidr_ip: string
:param cidr_ip: The CIDR block you are revoking access to.
See http://goo.gl/Yj5QC
:rtype: bool
:return: True if successful.
""" |
if src_security_group_name:
if from_port is None and to_port is None and ip_protocol is None:
return self.revoke_security_group_deprecated(
group_name, src_security_group_name,
src_security_group_owner_id)
params = {}
if group_name is not None:
params['GroupName'] = group_name
if group_id is not None:
params['GroupId'] = group_id
if src_security_group_name:
param_name = 'IpPermissions.1.Groups.1.GroupName'
params[param_name] = src_security_group_name
if src_security_group_group_id:
param_name = 'IpPermissions.1.Groups.1.GroupId'
params[param_name] = src_security_group_group_id
if src_security_group_owner_id:
param_name = 'IpPermissions.1.Groups.1.UserId'
params[param_name] = src_security_group_owner_id
if ip_protocol:
params['IpPermissions.1.IpProtocol'] = ip_protocol
if from_port is not None:
params['IpPermissions.1.FromPort'] = from_port
if to_port is not None:
params['IpPermissions.1.ToPort'] = to_port
if cidr_ip:
params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip
return self.get_status('RevokeSecurityGroupIngress',
params, verb='POST') |
<SYSTEM_TASK:>
Get all available regions for the EC2 service.
<END_TASK>
<USER_TASK:>
Description:
def get_all_regions(self, region_names=None, filters=None):
"""
Get all available regions for the EC2 service.
:type region_names: list of str
:param region_names: Names of regions to limit output
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
""" |
params = {}
if region_names:
self.build_list_params(params, region_names, 'RegionName')
if filters:
self.build_filter_params(params, filters)
regions = self.get_list('DescribeRegions', params,
[('item', RegionInfo)], verb='POST')
for region in regions:
region.connection_cls = EC2Connection
return regions |
<SYSTEM_TASK:>
Enable CloudWatch monitoring for the supplied instances.
<END_TASK>
<USER_TASK:>
Description:
def monitor_instances(self, instance_ids):
"""
Enable CloudWatch monitoring for the supplied instances.
:type instance_id: list of strings
:param instance_id: The instance ids
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
""" |
params = {}
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_list('MonitorInstances', params,
[('item', InstanceInfo)], verb='POST') |
<SYSTEM_TASK:>
Disable CloudWatch monitoring for the supplied instance.
<END_TASK>
<USER_TASK:>
Description:
def unmonitor_instances(self, instance_ids):
"""
Disable CloudWatch monitoring for the supplied instance.
:type instance_id: list of string
:param instance_id: The instance id
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
""" |
params = {}
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_list('UnmonitorInstances', params,
[('item', InstanceInfo)], verb='POST') |
<SYSTEM_TASK:>
Bundle Windows instance.
<END_TASK>
<USER_TASK:>
Description:
def bundle_instance(self, instance_id,
s3_bucket,
s3_prefix,
s3_upload_policy):
"""
Bundle Windows instance.
:type instance_id: string
:param instance_id: The instance id
:type s3_bucket: string
:param s3_bucket: The bucket in which the AMI should be stored.
:type s3_prefix: string
:param s3_prefix: The beginning of the file name for the AMI.
:type s3_upload_policy: string
:param s3_upload_policy: Base64 encoded policy that specifies condition
and permissions for Amazon EC2 to upload the
user's image into Amazon S3.
""" |
params = {'InstanceId' : instance_id,
'Storage.S3.Bucket' : s3_bucket,
'Storage.S3.Prefix' : s3_prefix,
'Storage.S3.UploadPolicy' : s3_upload_policy}
s3auth = boto.auth.get_auth_handler(None, boto.config,
self.provider, ['s3'])
params['Storage.S3.AWSAccessKeyId'] = self.aws_access_key_id
signature = s3auth.sign_string(s3_upload_policy)
params['Storage.S3.UploadPolicySignature'] = signature
return self.get_object('BundleInstance', params,
BundleInstanceTask, verb='POST') |
<SYSTEM_TASK:>
Retrieve current bundling tasks. If no bundle id is specified, all
<END_TASK>
<USER_TASK:>
Description:
def get_all_bundle_tasks(self, bundle_ids=None, filters=None):
"""
Retrieve current bundling tasks. If no bundle id is specified, all
tasks are retrieved.
:type bundle_ids: list
:param bundle_ids: A list of strings containing identifiers for
previously created bundling tasks.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
""" |
params = {}
if bundle_ids:
self.build_list_params(params, bundle_ids, 'BundleId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeBundleTasks', params,
[('item', BundleInstanceTask)], verb='POST') |
<SYSTEM_TASK:>
Cancel a previously submitted bundle task
<END_TASK>
<USER_TASK:>
Description:
def cancel_bundle_task(self, bundle_id):
"""
Cancel a previously submitted bundle task
:type bundle_id: string
:param bundle_id: The identifier of the bundle task to cancel.
""" |
params = {'BundleId' : bundle_id}
return self.get_object('CancelBundleTask', params,
BundleInstanceTask, verb='POST') |
<SYSTEM_TASK:>
Get encrypted administrator password for a Windows instance.
<END_TASK>
<USER_TASK:>
Description:
def get_password_data(self, instance_id):
"""
Get encrypted administrator password for a Windows instance.
:type instance_id: string
:param instance_id: The identifier of the instance to retrieve the
password for.
""" |
params = {'InstanceId' : instance_id}
rs = self.get_object('GetPasswordData', params, ResultSet, verb='POST')
return rs.passwordData |
<SYSTEM_TASK:>
Get all placement groups associated with your account in a region.
<END_TASK>
<USER_TASK:>
Description:
def get_all_placement_groups(self, groupnames=None, filters=None):
"""
Get all placement groups associated with your account in a region.
:type groupnames: list
:param groupnames: A list of the names of placement groups to retrieve.
If not provided, all placement groups will be
returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.placementgroup.PlacementGroup`
""" |
params = {}
if groupnames:
self.build_list_params(params, groupnames, 'GroupName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribePlacementGroups', params,
[('item', PlacementGroup)], verb='POST') |
<SYSTEM_TASK:>
Create a new placement group for your account.
<END_TASK>
<USER_TASK:>
Description:
def create_placement_group(self, name, strategy='cluster'):
"""
Create a new placement group for your account.
This will create the placement group within the region you
are currently connected to.
:type name: string
:param name: The name of the new placement group
:type strategy: string
:param strategy: The placement strategy of the new placement group.
Currently, the only acceptable value is "cluster".
:rtype: bool
:return: True if successful
""" |
params = {'GroupName':name, 'Strategy':strategy}
group = self.get_status('CreatePlacementGroup', params, verb='POST')
return group |
<SYSTEM_TASK:>
Retrieve all the metadata tags associated with your account.
<END_TASK>
<USER_TASK:>
Description:
def get_all_tags(self, filters=None):
"""
Retrieve all the metadata tags associated with your account.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: dict
:return: A dictionary containing metadata tags
""" |
params = {}
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeTags', params,
[('item', Tag)], verb='POST') |
<SYSTEM_TASK:>
Creates a network interface in the specified subnet.
<END_TASK>
<USER_TASK:>
Description:
def create_network_interface(self, subnet_id, private_ip_address=None,
description=None, groups=None):
"""
Creates a network interface in the specified subnet.
:type subnet_id: str
:param subnet_id: The ID of the subnet to associate with the
network interface.
:type private_ip_address: str
:param private_ip_address: The private IP address of the
network interface. If not supplied, one will be chosen
for you.
:type description: str
:param description: The description of the network interface.
:type groups: list
:param groups: Lists the groups for use by the network interface.
This can be either a list of group ID's or a list of
:class:`boto.ec2.securitygroup.SecurityGroup` objects.
:rtype: :class:`boto.ec2.networkinterface.NetworkInterface`
:return: The newly created network interface.
""" |
params = {'SubnetId' : subnet_id}
if private_ip_address:
params['PrivateIpAddress'] = private_ip_address
if description:
params['Description'] = description
if groups:
ids = []
for group in groups:
if isinstance(group, SecurityGroup):
ids.append(group.id)
else:
ids.append(group)
self.build_list_params(params, ids, 'SecurityGroupId')
return self.get_object('CreateNetworkInterface', params,
NetworkInterface, verb='POST') |
<SYSTEM_TASK:>
Attaches a network interface to an instance.
<END_TASK>
<USER_TASK:>
Description:
def attach_network_interface(self, network_interface_id,
instance_id, device_index):
"""
Attaches a network interface to an instance.
:type network_interface_id: str
:param network_interface_id: The ID of the network interface to attach.
:type instance_id: str
:param instance_id: The ID of the instance that will be attached
to the network interface.
:type device_index: int
:param device_index: The index of the device for the network
interface attachment on the instance.
""" |
params = {'NetworkInterfaceId' : network_interface_id,
'InstanceId' : instance_id,
'Deviceindex' : device_index}
return self.get_status('AttachNetworkInterface', params, verb='POST') |
<SYSTEM_TASK:>
Detaches a network interface from an instance.
<END_TASK>
<USER_TASK:>
Description:
def detach_network_interface(self, network_interface_id, force=False):
"""
Detaches a network interface from an instance.
:type network_interface_id: str
:param network_interface_id: The ID of the network interface to detach.
:type force: bool
:param force: Set to true to force a detachment.
""" |
params = {'NetworkInterfaceId' : network_interface_id}
if force:
params['Force'] = 'true'
return self.get_status('DetachNetworkInterface', params, verb='POST') |
<SYSTEM_TASK:>
Set the desired capacity for the group.
<END_TASK>
<USER_TASK:>
Description:
def set_capacity(self, capacity):
"""
Set the desired capacity for the group.
""" |
params = {'AutoScalingGroupName' : self.name,
'DesiredCapacity' : capacity}
req = self.connection.get_object('SetDesiredCapacity', params,
Request)
self.connection.last_request = req
return req |
<SYSTEM_TASK:>
Convenience method which shuts down all instances associated with
<END_TASK>
<USER_TASK:>
Description:
def shutdown_instances(self):
"""
Convenience method which shuts down all instances associated with
this group.
""" |
self.min_size = 0
self.max_size = 0
self.desired_capacity = 0
self.update() |
<SYSTEM_TASK:>
Delete this auto-scaling group if no instances attached or no
<END_TASK>
<USER_TASK:>
Description:
def delete(self, force_delete=False):
"""
Delete this auto-scaling group if no instances attached or no
scaling activities in progress.
""" |
return self.connection.delete_auto_scaling_group(self.name, force_delete) |
<SYSTEM_TASK:>
Get all activies for this group.
<END_TASK>
<USER_TASK:>
Description:
def get_activities(self, activity_ids=None, max_records=50):
"""
Get all activies for this group.
""" |
return self.connection.get_all_activities(self, activity_ids,
max_records) |
<SYSTEM_TASK:>
Utility method to handle calls to IAM and parsing of responses.
<END_TASK>
<USER_TASK:>
Description:
def get_response(self, action, params, path='/', parent=None,
verb='GET', list_marker='Set'):
"""
Utility method to handle calls to IAM and parsing of responses.
""" |
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
e = boto.jsonresponse.Element(list_marker=list_marker,
pythonize_name=True)
h = boto.jsonresponse.XmlHandler(e, parent)
h.parse(body)
return e
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
List the groups that have the specified path prefix.
<END_TASK>
<USER_TASK:>
Description:
def get_all_groups(self, path_prefix='/', marker=None, max_items=None):
"""
List the groups that have the specified path prefix.
:type path_prefix: string
:param path_prefix: If provided, only groups whose paths match
the provided prefix will be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {}
if path_prefix:
params['PathPrefix'] = path_prefix
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroups', params,
list_marker='Groups') |
<SYSTEM_TASK:>
Return a list of users that are in the specified group.
<END_TASK>
<USER_TASK:>
Description:
def get_group(self, group_name, marker=None, max_items=None):
"""
Return a list of users that are in the specified group.
:type group_name: string
:param group_name: The name of the group whose information should
be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('GetGroup', params, list_marker='Users') |
<SYSTEM_TASK:>
List the names of the policies associated with the specified group.
<END_TASK>
<USER_TASK:>
Description:
def get_all_group_policies(self, group_name, marker=None, max_items=None):
"""
List the names of the policies associated with the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroupPolicies', params,
list_marker='PolicyNames') |
<SYSTEM_TASK:>
Deletes the specified policy document for the specified group.
<END_TASK>
<USER_TASK:>
Description:
def delete_group_policy(self, group_name, policy_name):
"""
Deletes the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to delete.
""" |
params = {'GroupName' : group_name,
'PolicyName' : policy_name}
return self.get_response('DeleteGroupPolicy', params, verb='POST') |
<SYSTEM_TASK:>
List the users that have the specified path prefix.
<END_TASK>
<USER_TASK:>
Description:
def get_all_users(self, path_prefix='/', marker=None, max_items=None):
"""
List the users that have the specified path prefix.
:type path_prefix: string
:param path_prefix: If provided, only users whose paths match
the provided prefix will be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'PathPrefix' : path_prefix}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUsers', params, list_marker='Users') |
<SYSTEM_TASK:>
Retrieve information about the specified user.
<END_TASK>
<USER_TASK:>
Description:
def get_user(self, user_name=None):
"""
Retrieve information about the specified user.
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The name of the user to delete.
If not specified, defaults to user making
request.
""" |
params = {}
if user_name:
params['UserName'] = user_name
return self.get_response('GetUser', params) |
<SYSTEM_TASK:>
List the names of the policies associated with the specified user.
<END_TASK>
<USER_TASK:>
Description:
def get_all_user_policies(self, user_name, marker=None, max_items=None):
"""
List the names of the policies associated with the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUserPolicies', params,
list_marker='PolicyNames') |
<SYSTEM_TASK:>
Deletes the specified policy document for the specified user.
<END_TASK>
<USER_TASK:>
Description:
def delete_user_policy(self, user_name, policy_name):
"""
Deletes the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to delete.
""" |
params = {'UserName' : user_name,
'PolicyName' : policy_name}
return self.get_response('DeleteUserPolicy', params, verb='POST') |
<SYSTEM_TASK:>
List the groups that a specified user belongs to.
<END_TASK>
<USER_TASK:>
Description:
def get_groups_for_user(self, user_name, marker=None, max_items=None):
"""
List the groups that a specified user belongs to.
:type user_name: string
:param user_name: The name of the user to list groups for.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroupsForUser', params,
list_marker='Groups') |
<SYSTEM_TASK:>
Get all access keys associated with an account.
<END_TASK>
<USER_TASK:>
Description:
def get_all_access_keys(self, user_name, marker=None, max_items=None):
"""
Get all access keys associated with an account.
:type user_name: string
:param user_name: The username of the user
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListAccessKeys', params,
list_marker='AccessKeyMetadata') |
<SYSTEM_TASK:>
Changes the status of the specified access key from Active to Inactive
<END_TASK>
<USER_TASK:>
Description:
def update_access_key(self, access_key_id, status, user_name=None):
"""
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type access_key_id: string
:param access_key_id: The ID of the access key.
:type status: string
:param status: Either Active or Inactive.
:type user_name: string
:param user_name: The username of user (optional).
""" |
params = {'AccessKeyId' : access_key_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateAccessKey', params) |
<SYSTEM_TASK:>
Delete an access key associated with a user.
<END_TASK>
<USER_TASK:>
Description:
def delete_access_key(self, access_key_id, user_name=None):
"""
Delete an access key associated with a user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type access_key_id: string
:param access_key_id: The ID of the access key to be deleted.
:type user_name: string
:param user_name: The username of the user
""" |
params = {'AccessKeyId' : access_key_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteAccessKey', params) |
<SYSTEM_TASK:>
Get all signing certificates associated with an account.
<END_TASK>
<USER_TASK:>
Description:
def get_all_signing_certs(self, marker=None, max_items=None,
user_name=None):
"""
Get all signing certificates associated with an account.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
:type user_name: string
:param user_name: The username of the user
""" |
params = {}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
if user_name:
params['UserName'] = user_name
return self.get_response('ListSigningCertificates',
params, list_marker='Certificates') |
<SYSTEM_TASK:>
Change the status of the specified signing certificate from
<END_TASK>
<USER_TASK:>
Description:
def update_signing_cert(self, cert_id, status, user_name=None):
"""
Change the status of the specified signing certificate from
Active to Inactive or vice versa.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type cert_id: string
:param cert_id: The ID of the signing certificate
:type status: string
:param status: Either Active or Inactive.
:type user_name: string
:param user_name: The username of the user
""" |
params = {'CertificateId' : cert_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateSigningCertificate', params) |
<SYSTEM_TASK:>
Uploads an X.509 signing certificate and associates it with
<END_TASK>
<USER_TASK:>
Description:
def upload_signing_cert(self, cert_body, user_name=None):
"""
Uploads an X.509 signing certificate and associates it with
the specified user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type cert_body: string
:param cert_body: The body of the signing certificate.
:type user_name: string
:param user_name: The username of the user
""" |
params = {'CertificateBody' : cert_body}
if user_name:
params['UserName'] = user_name
return self.get_response('UploadSigningCertificate', params,
verb='POST') |
<SYSTEM_TASK:>
Delete a signing certificate associated with a user.
<END_TASK>
<USER_TASK:>
Description:
def delete_signing_cert(self, cert_id, user_name=None):
"""
Delete a signing certificate associated with a user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The username of the user
:type cert_id: string
:param cert_id: The ID of the certificate.
""" |
params = {'CertificateId' : cert_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteSigningCertificate', params) |
<SYSTEM_TASK:>
Lists the server certificates that have the specified path prefix.
<END_TASK>
<USER_TASK:>
Description:
def get_all_server_certs(self, path_prefix='/',
marker=None, max_items=None):
"""
Lists the server certificates that have the specified path prefix.
If none exist, the action returns an empty list.
:type path_prefix: string
:param path_prefix: If provided, only certificates whose paths match
the provided prefix will be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {}
if path_prefix:
params['PathPrefix'] = path_prefix
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListServerCertificates',
params,
list_marker='ServerCertificateMetadataList') |
<SYSTEM_TASK:>
Uploads a server certificate entity for the AWS Account.
<END_TASK>
<USER_TASK:>
Description:
def upload_server_cert(self, cert_name, cert_body, private_key,
cert_chain=None, path=None):
"""
Uploads a server certificate entity for the AWS Account.
The server certificate entity includes a public key certificate,
a private key, and an optional certificate chain, which should
all be PEM-encoded.
:type cert_name: string
:param cert_name: The name for the server certificate. Do not
include the path in this value.
:type cert_body: string
:param cert_body: The contents of the public key certificate
in PEM-encoded format.
:type private_key: string
:param private_key: The contents of the private key in
PEM-encoded format.
:type cert_chain: string
:param cert_chain: The contents of the certificate chain. This
is typically a concatenation of the PEM-encoded
public key certificates of the chain.
:type path: string
:param path: The path for the server certificate.
""" |
params = {'ServerCertificateName' : cert_name,
'CertificateBody' : cert_body,
'PrivateKey' : private_key}
if cert_chain:
params['CertificateChain'] = cert_chain
if path:
params['Path'] = path
return self.get_response('UploadServerCertificate', params,
verb='POST') |
<SYSTEM_TASK:>
Get all MFA devices associated with an account.
<END_TASK>
<USER_TASK:>
Description:
def get_all_mfa_devices(self, user_name, marker=None, max_items=None):
"""
Get all MFA devices associated with an account.
:type user_name: string
:param user_name: The username of the user
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
""" |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListMFADevices',
params, list_marker='MFADevices') |
<SYSTEM_TASK:>
Enables the specified MFA device and associates it with the
<END_TASK>
<USER_TASK:>
Description:
def enable_mfa_device(self, user_name, serial_number,
auth_code_1, auth_code_2):
"""
Enables the specified MFA device and associates it with the
specified user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
:type auth_code_1: string
:param auth_code_1: An authentication code emitted by the device.
:type auth_code_2: string
:param auth_code_2: A subsequent authentication code emitted
by the device.
""" |
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('EnableMFADevice', params) |
<SYSTEM_TASK:>
Deactivates the specified MFA device and removes it from
<END_TASK>
<USER_TASK:>
Description:
def deactivate_mfa_device(self, user_name, serial_number):
"""
Deactivates the specified MFA device and removes it from
association with the user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
""" |
params = {'UserName' : user_name,
'SerialNumber' : serial_number}
return self.get_response('DeactivateMFADevice', params) |
<SYSTEM_TASK:>
Syncronizes the specified MFA device with the AWS servers.
<END_TASK>
<USER_TASK:>
Description:
def resync_mfa_device(self, user_name, serial_number,
auth_code_1, auth_code_2):
"""
Syncronizes the specified MFA device with the AWS servers.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
:type auth_code_1: string
:param auth_code_1: An authentication code emitted by the device.
:type auth_code_2: string
:param auth_code_2: A subsequent authentication code emitted
by the device.
""" |
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('ResyncMFADevice', params) |
<SYSTEM_TASK:>
Resets the password associated with the user's login profile.
<END_TASK>
<USER_TASK:>
Description:
def update_login_profile(self, user_name, password):
"""
Resets the password associated with the user's login profile.
:type user_name: string
:param user_name: The name of the user
:type password: string
:param password: The new password for the user
""" |
params = {'UserName' : user_name,
'Password' : password}
return self.get_response('UpdateLoginProfile', params) |
<SYSTEM_TASK:>
Get the URL where IAM users can use their login profile to sign in
<END_TASK>
<USER_TASK:>
Description:
def get_signin_url(self, service='ec2'):
"""
Get the URL where IAM users can use their login profile to sign in
to this account's console.
:type service: string
:param service: Default service to go to in the console.
""" |
alias = self.get_account_alias()
if not alias:
raise Exception('No alias associated with this account. Please use iam.create_account_alias() first.')
return "https://%s.signin.aws.amazon.com/console/%s" % (alias, service) |
<SYSTEM_TASK:>
Replace length bytes of data with chunk, starting at offset.
<END_TASK>
<USER_TASK:>
Description:
def replace_chunk(filename, offset, length, chunk, in_place=True, max_mem=5):
"""Replace length bytes of data with chunk, starting at offset.
Any KeyboardInterrupts arriving while replace_chunk is runnning
are deferred until the operation is complete.
If in_place is true, the operation works directly on the original
file; this is fast and works on files that are already open, but
an error or interrupt may lead to corrupt file contents.
If in_place is false, the function prepares a copy first, then
renames it back over the original file. This method is slower,
but it prevents corruption on systems with atomic renames (UNIX),
and reduces the window of vulnerability elsewhere (Windows).
If there is no need to move data that is not being replaced, then we use
the direct method irrespective of in_place. (In this case an interrupt
may only corrupt the chunk being replaced.)
""" |
with suppress_interrupt():
_replace_chunk(filename, offset, length, chunk, in_place, max_mem) |
<SYSTEM_TASK:>
Symbolizes a single frame based on the information provided. If
<END_TASK>
<USER_TASK:>
Description:
def symbolize(self, dsym_path, image_vmaddr, image_addr,
instruction_addr, cpu_name,
symbolize_inlined=False):
"""Symbolizes a single frame based on the information provided. If
the symbolication fails a `SymbolicationError` is raised.
`dsym_path` is the path to the dsym file on the file system.
`image_vmaddr` is the slide of the image. For most situations this
can just be set to `0`. If it's zero or unset we will attempt to
find the slide from the dsym file. `image_addr` is the canonical
image address as loaded. `instruction_addr` is the address where the
error happened.
`cpu_name` is the CPU name. It follows general apple conventions and
is used to special case certain behavior and look up the right
symbols. Common names are `armv7` and `arm64`.
Additionally if `symbolize_inlined` is set to `True` then a list of
frames is returned instead which might contain inlined frames. In
that case the return value might be an empty list instead.
""" |
if self._closed:
raise RuntimeError('Symbolizer is closed')
dsym_path = normalize_dsym_path(dsym_path)
image_vmaddr = parse_addr(image_vmaddr)
if not image_vmaddr:
di = self._symbolizer.get_debug_info(dsym_path)
if di is not None:
variant = di.get_variant(cpu_name)
if variant is not None:
image_vmaddr = variant.vmaddr
image_addr = parse_addr(image_addr)
instruction_addr = parse_addr(instruction_addr)
if not is_valid_cpu_name(cpu_name):
raise SymbolicationError('"%s" is not a valid cpu name' % cpu_name)
addr = image_vmaddr + instruction_addr - image_addr
with self._lock:
with timedsection('symbolize'):
if symbolize_inlined:
return self._symbolizer.symbolize_inlined(
dsym_path, addr, cpu_name)
return self._symbolizer.symbolize(
dsym_path, addr, cpu_name) |
<SYSTEM_TASK:>
Return a list of table names associated with the current account
<END_TASK>
<USER_TASK:>
Description:
def list_tables(self, limit=None, start_table=None):
"""
Return a list of table names associated with the current account
and endpoint.
:type limit: int
:param limit: The maximum number of tables to return.
:type start_table: str
:param limit: The name of the table that starts the
list. If you ran a previous list_tables and not
all results were returned, the response dict would
include a LastEvaluatedTableName attribute. Use
that value here to continue the listing.
""" |
data = {}
if limit:
data['Limit'] = limit
if start_table:
data['ExclusiveStartTableName'] = start_table
json_input = json.dumps(data)
return self.make_request('ListTables', json_input) |
<SYSTEM_TASK:>
Returns information about the table including current
<END_TASK>
<USER_TASK:>
Description:
def describe_table(self, table_name):
"""
Returns information about the table including current
state of the table, primary key schema and when the
table was created.
:type table_name: str
:param table_name: The name of the table to describe.
""" |
data = {'TableName' : table_name}
json_input = json.dumps(data)
return self.make_request('DescribeTable', json_input) |
<SYSTEM_TASK:>
Add a new table to your account. The table name must be unique
<END_TASK>
<USER_TASK:>
Description:
def create_table(self, table_name, schema, provisioned_throughput):
"""
Add a new table to your account. The table name must be unique
among those associated with the account issuing the request.
This request triggers an asynchronous workflow to begin creating
the table. When the workflow is complete, the state of the
table will be ACTIVE.
:type table_name: str
:param table_name: The name of the table to create.
:type schema: dict
:param schema: A Python version of the KeySchema data structure
as defined by DynamoDB
:type provisioned_throughput: dict
:param provisioned_throughput: A Python version of the
ProvisionedThroughput data structure defined by
DynamoDB.
""" |
data = {'TableName' : table_name,
'KeySchema' : schema,
'ProvisionedThroughput': provisioned_throughput}
json_input = json.dumps(data)
response_dict = self.make_request('CreateTable', json_input)
return response_dict |
<SYSTEM_TASK:>
Deletes the table and all of it's data. After this request
<END_TASK>
<USER_TASK:>
Description:
def delete_table(self, table_name):
"""
Deletes the table and all of it's data. After this request
the table will be in the DELETING state until DynamoDB
completes the delete operation.
:type table_name: str
:param table_name: The name of the table to delete.
""" |
data = {'TableName': table_name}
json_input = json.dumps(data)
return self.make_request('DeleteTable', json_input) |
<SYSTEM_TASK:>
Return a set of attributes for an item that matches
<END_TASK>
<USER_TASK:>
Description:
def get_item(self, table_name, key, attributes_to_get=None,
consistent_read=False, object_hook=None):
"""
Return a set of attributes for an item that matches
the supplied key.
:type table_name: str
:param table_name: The name of the table containing the item.
:type key: dict
:param key: A Python version of the Key data structure
defined by DynamoDB.
:type attributes_to_get: list
:param attributes_to_get: A list of attribute names.
If supplied, only the specified attribute names will
be returned. Otherwise, all attributes will be returned.
:type consistent_read: bool
:param consistent_read: If True, a consistent read
request is issued. Otherwise, an eventually consistent
request is issued.
""" |
data = {'TableName': table_name,
'Key': key}
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if consistent_read:
data['ConsistentRead'] = True
json_input = json.dumps(data)
response = self.make_request('GetItem', json_input,
object_hook=object_hook)
if not response.has_key('Item'):
raise dynamodb_exceptions.DynamoDBKeyNotFoundError(
"Key does not exist."
)
return response |
<SYSTEM_TASK:>
Delete an item and all of it's attributes by primary key.
<END_TASK>
<USER_TASK:>
Description:
def delete_item(self, table_name, key,
expected=None, return_values=None,
object_hook=None):
"""
Delete an item and all of it's attributes by primary key.
You can perform a conditional delete by specifying an
expected rule.
:type table_name: str
:param table_name: The name of the table containing the item.
:type key: dict
:param key: A Python version of the Key data structure
defined by DynamoDB.
:type expected: dict
:param expected: A Python version of the Expected
data structure defined by DynamoDB.
:type return_values: str
:param return_values: Controls the return of attribute
name-value pairs before then were changed. Possible
values are: None or 'ALL_OLD'. If 'ALL_OLD' is
specified and the item is overwritten, the content
of the old item is returned.
""" |
data = {'TableName' : table_name,
'Key' : key}
if expected:
data['Expected'] = expected
if return_values:
data['ReturnValues'] = return_values
json_input = json.dumps(data)
return self.make_request('DeleteItem', json_input,
object_hook=object_hook) |
<SYSTEM_TASK:>
Perform a query of DynamoDB. This version is currently punting
<END_TASK>
<USER_TASK:>
Description:
def query(self, table_name, hash_key_value, range_key_conditions=None,
attributes_to_get=None, limit=None, consistent_read=False,
scan_index_forward=True, exclusive_start_key=None,
object_hook=None):
"""
Perform a query of DynamoDB. This version is currently punting
and expecting you to provide a full and correct JSON body
which is passed as is to DynamoDB.
:type table_name: str
:param table_name: The name of the table to query.
:type hash_key_value: dict
:param key: A DynamoDB-style HashKeyValue.
:type range_key_conditions: dict
:param range_key_conditions: A Python version of the
RangeKeyConditions data structure.
:type attributes_to_get: list
:param attributes_to_get: A list of attribute names.
If supplied, only the specified attribute names will
be returned. Otherwise, all attributes will be returned.
:type limit: int
:param limit: The maximum number of items to return.
:type consistent_read: bool
:param consistent_read: If True, a consistent read
request is issued. Otherwise, an eventually consistent
request is issued.
:type scan_index_forward: bool
:param scan_index_forward: Specified forward or backward
traversal of the index. Default is forward (True).
:type exclusive_start_key: list or tuple
:param exclusive_start_key: Primary key of the item from
which to continue an earlier query. This would be
provided as the LastEvaluatedKey in that query.
""" |
data = {'TableName': table_name,
'HashKeyValue': hash_key_value}
if range_key_conditions:
data['RangeKeyCondition'] = range_key_conditions
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if limit:
data['Limit'] = limit
if consistent_read:
data['ConsistentRead'] = True
if scan_index_forward:
data['ScanIndexForward'] = True
else:
data['ScanIndexForward'] = False
if exclusive_start_key:
data['ExclusiveStartKey'] = exclusive_start_key
json_input = json.dumps(data)
return self.make_request('Query', json_input,
object_hook=object_hook) |
<SYSTEM_TASK:>
Perform a scan of DynamoDB. This version is currently punting
<END_TASK>
<USER_TASK:>
Description:
def scan(self, table_name, scan_filter=None,
attributes_to_get=None, limit=None,
count=False, exclusive_start_key=None,
object_hook=None):
"""
Perform a scan of DynamoDB. This version is currently punting
and expecting you to provide a full and correct JSON body
which is passed as is to DynamoDB.
:type table_name: str
:param table_name: The name of the table to scan.
:type scan_filter: dict
:param scan_filter: A Python version of the
ScanFilter data structure.
:type attributes_to_get: list
:param attributes_to_get: A list of attribute names.
If supplied, only the specified attribute names will
be returned. Otherwise, all attributes will be returned.
:type limit: int
:param limit: The maximum number of items to return.
:type count: bool
:param count: If True, Amazon DynamoDB returns a total
number of items for the Scan operation, even if the
operation has no matching items for the assigned filter.
:type exclusive_start_key: list or tuple
:param exclusive_start_key: Primary key of the item from
which to continue an earlier query. This would be
provided as the LastEvaluatedKey in that query.
""" |
data = {'TableName': table_name}
if scan_filter:
data['ScanFilter'] = scan_filter
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if limit:
data['Limit'] = limit
if count:
data['Count'] = True
if exclusive_start_key:
data['ExclusiveStartKey'] = exclusive_start_key
json_input = json.dumps(data)
return self.make_request('Scan', json_input, object_hook=object_hook) |
<SYSTEM_TASK:>
Removes similar colored background in the given image.
<END_TASK>
<USER_TASK:>
Description:
def remove_bg(img, th=(240, 255)):
"""
Removes similar colored background in the given image.
:param img: Input image
:param th: Tuple(2)
Background color threshold (lower-limit, upper-limit)
:return: Background removed image as result
""" |
if img.size == 0:
return img
img = gray3(img)
# delete rows with complete background color
h, w = img.shape[:2]
i = 0
while i < h:
mask = np.logical_or(img[i, :, :] < th[0], img[i, :, :] > th[1])
if not mask.any():
img = np.delete(img, i, axis=0)
i -= 1
h -= 1
i += 1
# if image is complete background only
if img.size == 0:
return img
# delete columns with complete background color
h, w = img.shape[:2]
i = 0
while i < w:
mask = np.logical_or(img[:, i, :] < th[0], img[:, i, :] > th[1])
if not mask.any():
img = np.delete(img, i, axis=1)
i -= 1
w -= 1
i += 1
return img |
<SYSTEM_TASK:>
Adds a padding to the given image as background of specified color
<END_TASK>
<USER_TASK:>
Description:
def add_bg(img, padding, color=COL_WHITE):
"""
Adds a padding to the given image as background of specified color
:param img: Input image.
:param padding: constant padding around the image.
:param color: background color that needs to filled for the newly padded region.
:return: New image with background.
""" |
img = gray3(img)
h, w, d = img.shape
new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d]
new_img = new_img.astype(np.uint8)
set_img_box(new_img, (padding, padding, w, h), img)
return new_img |
<SYSTEM_TASK:>
Selects the sub-image inside the given box
<END_TASK>
<USER_TASK:>
Description:
def img_box(img, box):
"""
Selects the sub-image inside the given box
:param img: Image to crop from
:param box: Box to crop from. Box can be either Box object or array of [x, y, width, height]
:return: Cropped sub-image from the main image
""" |
if isinstance(box, tuple):
box = Box.from_tup(box)
if len(img.shape) == 3:
return img[box.y:box.y + box.height, box.x:box.x + box.width, :]
else:
return img[box.y:box.y + box.height, box.x:box.x + box.width] |
<SYSTEM_TASK:>
Adds the given text in the image.
<END_TASK>
<USER_TASK:>
Description:
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False):
"""
Adds the given text in the image.
:param img: Input image
:param text: String text
:param pos: (x, y) in the image or relative to the given Box object
:param box: Box object. If not None, the text is placed inside the box.
:param color: Color of the text.
:param thickness: Thickness of the font.
:param scale: Font size scale.
:param vertical: If true, the text is displayed vertically. (slow)
:return:
""" |
if color is None:
color = COL_WHITE
text = str(text)
top_left = pos
if box is not None:
top_left = box.move(pos).to_int().top_left()
if top_left[0] > img.shape[1]:
return
if vertical:
if box is not None:
h, w, d = box.height, box.width, 3
else:
h, w, d = img.shape
txt_img = np.zeros((w, h, d), dtype=np.uint8)
# 90 deg rotation
top_left = h - pos[1], pos[0]
cv.putText(txt_img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)
txt_img = ndimage.rotate(txt_img, 90)
mask = txt_img > 0
if box is not None:
im_box = img_box(img, box)
im_box[mask] = txt_img[mask]
else:
img[mask] = txt_img[mask]
else:
cv.putText(img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness) |
<SYSTEM_TASK:>
Draws a bounding box inside the image.
<END_TASK>
<USER_TASK:>
Description:
def add_rect(img, box, color=None, thickness=1):
"""
Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image
""" |
if color is None:
color = COL_GRAY
box = box.to_int()
cv.rectangle(img, box.top_left(), box.bottom_right(), color, thickness) |
<SYSTEM_TASK:>
Constructs a collage of same-sized images with specified padding.
<END_TASK>
<USER_TASK:>
Description:
def collage(imgs, size, padding=10, bg=COL_BLACK):
"""
Constructs a collage of same-sized images with specified padding.
:param imgs: Array of images. Either 1d-array or 2d-array.
:param size: (no. of rows, no. of cols)
:param padding: Padding space between each image
:param bg: Background color for the collage. Default: Black
:return: New collage
""" |
# make 2d array
if not isinstance(imgs[0], list):
imgs = [imgs]
h, w = imgs[0][0].shape[:2]
nrows, ncols = size
nr, nc = nrows * h + (nrows-1) * padding, ncols * w + (ncols-1) * padding
res = np.ones((nr, nc, 3), dtype=np.uint8) * np.array(bg, dtype=np.uint8)
for r in range(nrows):
for c in range(ncols):
img = imgs[r][c]
if is_gray(img):
img = gray3ch(img)
rs = r * (h + padding)
re = rs + h
cs = c * (w + padding)
ce = cs + w
res[rs:re, cs:ce, :] = img
return res |
<SYSTEM_TASK:>
Reads and iterates through each image file in the given directory
<END_TASK>
<USER_TASK:>
Description:
def each_img(img_dir):
"""
Reads and iterates through each image file in the given directory
""" |
for fname in utils.each_img(img_dir):
fname = os.path.join(img_dir, fname)
yield cv.imread(fname), fname |
<SYSTEM_TASK:>
Temporarily sets the state of an alarm.
<END_TASK>
<USER_TASK:>
Description:
def set_state(self, value, reason, data=None):
""" Temporarily sets the state of an alarm.
:type value: str
:param value: OK | ALARM | INSUFFICIENT_DATA
:type reason: str
:param reason: Reason alarm set (human readable).
:type data: str
:param data: Reason data (will be jsonified).
""" |
return self.connection.set_alarm_state(self.name, reason, value, data) |
<SYSTEM_TASK:>
Adds an alarm action, represented as an SNS topic, to this alarm.
<END_TASK>
<USER_TASK:>
Description:
def add_alarm_action(self, action_arn=None):
"""
Adds an alarm action, represented as an SNS topic, to this alarm.
What do do when alarm is triggered.
:type action_arn: str
:param action_arn: SNS topics to which notification should be
sent if the alarm goes to state ALARM.
""" |
if not action_arn:
return # Raise exception instead?
self.actions_enabled = 'true'
self.alarm_actions.append(action_arn) |
<SYSTEM_TASK:>
Adds an insufficient_data action, represented as an SNS topic, to
<END_TASK>
<USER_TASK:>
Description:
def add_insufficient_data_action(self, action_arn=None):
"""
Adds an insufficient_data action, represented as an SNS topic, to
this alarm. What to do when the insufficient_data state is reached.
:type action_arn: str
:param action_arn: SNS topics to which notification should be
sent if the alarm goes to state INSUFFICIENT_DATA.
""" |
if not action_arn:
return
self.actions_enabled = 'true'
self.insufficient_data_actions.append(action_arn) |
<SYSTEM_TASK:>
Adds an ok action, represented as an SNS topic, to this alarm. What
<END_TASK>
<USER_TASK:>
Description:
def add_ok_action(self, action_arn=None):
"""
Adds an ok action, represented as an SNS topic, to this alarm. What
to do when the ok state is reached.
:type action_arn: str
:param action_arn: SNS topics to which notification should be
sent if the alarm goes to state INSUFFICIENT_DATA.
""" |
if not action_arn:
return
self.actions_enabled = 'true'
self.ok_actions.append(action_arn) |
<SYSTEM_TASK:>
Return a valid session token. Because retrieving new tokens
<END_TASK>
<USER_TASK:>
Description:
def get_session_token(self, duration=None, force_new=False):
"""
Return a valid session token. Because retrieving new tokens
from the Secure Token Service is a fairly heavyweight operation
this module caches previously retrieved tokens and returns
them when appropriate. Each token is cached with a key
consisting of the region name of the STS endpoint
concatenated with the requesting user's access id. If there
is a token in the cache meeting with this key, the session
expiration is checked to make sure it is still valid and if
so, the cached token is returned. Otherwise, a new session
token is requested from STS and it is placed into the cache
and returned.
:type duration: int
:param duration: The number of seconds the credentials should
remain valid.
:type force_new: bool
:param force_new: If this parameter is True, a new session token
will be retrieved from the Secure Token Service regardless
of whether there is a valid cached token or not.
""" |
token_key = '%s:%s' % (self.region.name, self.provider.access_key)
token = self._check_token_cache(token_key, duration)
if force_new or not token:
boto.log.debug('fetching a new token for %s' % token_key)
self._mutex.acquire()
token = self._get_session_token(duration)
_session_token_cache[token_key] = token
self._mutex.release()
return token |
<SYSTEM_TASK:>
Get attributes of a Topic
<END_TASK>
<USER_TASK:>
Description:
def set_topic_attributes(self, topic, attr_name, attr_value):
"""
Get attributes of a Topic
:type topic: string
:param topic: The ARN of the topic.
:type attr_name: string
:param attr_name: The name of the attribute you want to set.
Only a subset of the topic's attributes are mutable.
Valid values: Policy | DisplayName
:type attr_value: string
:param attr_value: The new value for the attribute.
""" |
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'AttributeName' : attr_name,
'AttributeValue' : attr_value}
response = self.make_request('SetTopicAttributes', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Adds a statement to a topic's access control policy, granting
<END_TASK>
<USER_TASK:>
Description:
def add_permission(self, topic, label, account_ids, actions):
"""
Adds a statement to a topic's access control policy, granting
access for the specified AWS accounts to the specified actions.
:type topic: string
:param topic: The ARN of the topic.
:type label: string
:param label: A unique identifier for the new policy statement.
:type account_ids: list of strings
:param account_ids: The AWS account ids of the users who will be
give access to the specified actions.
:type actions: list of strings
:param actions: The actions you want to allow for each of the
specified principal(s).
""" |
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Label' : label}
self.build_list_params(params, account_ids, 'AWSAccountId')
self.build_list_params(params, actions, 'ActionName')
response = self.make_request('AddPermission', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Subscribe an SQS queue to a topic.
<END_TASK>
<USER_TASK:>
Description:
def subscribe_sqs_queue(self, topic, queue):
"""
Subscribe an SQS queue to a topic.
This is convenience method that handles most of the complexity involved
in using ans SQS queue as an endpoint for an SNS topic. To achieve this
the following operations are performed:
* The correct ARN is constructed for the SQS queue and that ARN is
then subscribed to the topic.
* A JSON policy document is contructed that grants permission to
the SNS topic to send messages to the SQS queue.
* This JSON policy is then associated with the SQS queue using
the queue's set_attribute method. If the queue already has
a policy associated with it, this process will add a Statement to
that policy. If no policy exists, a new policy will be created.
:type topic: string
:param topic: The name of the new topic.
:type queue: A boto Queue object
:param queue: The queue you wish to subscribe to the SNS Topic.
""" |
t = queue.id.split('/')
q_arn = 'arn:aws:sqs:%s:%s:%s' % (queue.connection.region.name,
t[1], t[2])
resp = self.subscribe(topic, 'sqs', q_arn)
policy = queue.get_attributes('Policy')
if 'Version' not in policy:
policy['Version'] = '2008-10-17'
if 'Statement' not in policy:
policy['Statement'] = []
statement = {'Action' : 'SQS:SendMessage',
'Effect' : 'Allow',
'Principal' : {'AWS' : '*'},
'Resource' : q_arn,
'Sid' : str(uuid.uuid4()),
'Condition' : {'StringLike' : {'aws:SourceArn' : topic}}}
policy['Statement'].append(statement)
queue.set_attribute('Policy', json.dumps(policy))
return resp |
<SYSTEM_TASK:>
Allows endpoint owner to delete subscription.
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(self, subscription):
"""
Allows endpoint owner to delete subscription.
Confirmation message will be delivered.
:type subscription: string
:param subscription: The ARN of the subscription to be deleted.
""" |
params = {'ContentType' : 'JSON',
'SubscriptionArn' : subscription}
response = self.make_request('Unsubscribe', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Get list of all subscriptions.
<END_TASK>
<USER_TASK:>
Description:
def get_all_subscriptions(self, next_token=None):
"""
Get list of all subscriptions.
:type next_token: string
:param next_token: Token returned by the previous call to
this method.
""" |
params = {'ContentType' : 'JSON'}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListSubscriptions', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Set us up as a caller
<END_TASK>
<USER_TASK:>
Description:
def install_caller_instruction(self, token_type="Unrestricted",
transaction_id=None):
"""
Set us up as a caller
This will install a new caller_token into the FPS section.
This should really only be called to regenerate the caller token.
""" |
response = self.install_payment_instruction("MyRole=='Caller';",
token_type=token_type,
transaction_id=transaction_id)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
caller_token = rs.TokenId
try:
boto.config.save_system_option("FPS", "caller_token",
caller_token)
except(IOError):
boto.config.save_user_option("FPS", "caller_token",
caller_token)
return caller_token
else:
raise FPSResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Generate the URL with the signature required for signing up a recipient
<END_TASK>
<USER_TASK:>
Description:
def make_marketplace_registration_url(self, returnURL, pipelineName,
maxFixedFee=0.0, maxVariableFee=0.0,
recipientPaysFee=True, **params):
"""
Generate the URL with the signature required for signing up a recipient
""" |
# use the sandbox authorization endpoint if we're using the
# sandbox for API calls.
endpoint_host = 'authorize.payments.amazon.com'
if 'sandbox' in self.host:
endpoint_host = 'authorize.payments-sandbox.amazon.com'
base = "/cobranded-ui/actions/start"
params['callerKey'] = str(self.aws_access_key_id)
params['returnURL'] = str(returnURL)
params['pipelineName'] = str(pipelineName)
params['maxFixedFee'] = str(maxFixedFee)
params['maxVariableFee'] = str(maxVariableFee)
params['recipientPaysFee'] = str(recipientPaysFee)
params["signatureMethod"] = 'HmacSHA256'
params["signatureVersion"] = '2'
if(not params.has_key('callerReference')):
params['callerReference'] = str(uuid.uuid4())
parts = ''
for k in sorted(params.keys()):
parts += "&%s=%s" % (k, urllib.quote(params[k], '~'))
canonical = '\n'.join(['GET',
str(endpoint_host).lower(),
base,
parts[1:]])
signature = self._auth_handler.sign_string(canonical)
params["signature"] = signature
urlsuffix = ''
for k in sorted(params.keys()):
urlsuffix += "&%s=%s" % (k, urllib.quote(params[k], '~'))
urlsuffix = urlsuffix[1:] # strip the first &
fmt = "https://%(endpoint_host)s%(base)s?%(urlsuffix)s"
final = fmt % vars()
return final |
<SYSTEM_TASK:>
Generate the URL with the signature required for a transaction
<END_TASK>
<USER_TASK:>
Description:
def make_url(self, returnURL, paymentReason, pipelineName,
transactionAmount, **params):
"""
Generate the URL with the signature required for a transaction
""" |
# use the sandbox authorization endpoint if we're using the
# sandbox for API calls.
endpoint_host = 'authorize.payments.amazon.com'
if 'sandbox' in self.host:
endpoint_host = 'authorize.payments-sandbox.amazon.com'
base = "/cobranded-ui/actions/start"
params['callerKey'] = str(self.aws_access_key_id)
params['returnURL'] = str(returnURL)
params['paymentReason'] = str(paymentReason)
params['pipelineName'] = pipelineName
params['transactionAmount'] = transactionAmount
params["signatureMethod"] = 'HmacSHA256'
params["signatureVersion"] = '2'
if(not params.has_key('callerReference')):
params['callerReference'] = str(uuid.uuid4())
parts = ''
for k in sorted(params.keys()):
parts += "&%s=%s" % (k, urllib.quote(params[k], '~'))
canonical = '\n'.join(['GET',
str(endpoint_host).lower(),
base,
parts[1:]])
signature = self._auth_handler.sign_string(canonical)
params["signature"] = signature
urlsuffix = ''
for k in sorted(params.keys()):
urlsuffix += "&%s=%s" % (k, urllib.quote(params[k], '~'))
urlsuffix = urlsuffix[1:] # strip the first &
fmt = "https://%(endpoint_host)s%(base)s?%(urlsuffix)s"
final = fmt % vars()
return final |
<SYSTEM_TASK:>
Make a payment transaction. You must specify the amount.
<END_TASK>
<USER_TASK:>
Description:
def pay(self, transactionAmount, senderTokenId,
recipientTokenId=None, callerTokenId=None,
chargeFeeTo="Recipient",
callerReference=None, senderReference=None, recipientReference=None,
senderDescription=None, recipientDescription=None,
callerDescription=None, metadata=None,
transactionDate=None, reserve=False):
"""
Make a payment transaction. You must specify the amount.
This can also perform a Reserve request if 'reserve' is set to True.
""" |
params = {}
params['SenderTokenId'] = senderTokenId
# this is for 2008-09-17 specification
params['TransactionAmount.Amount'] = str(transactionAmount)
params['TransactionAmount.CurrencyCode'] = "USD"
#params['TransactionAmount'] = str(transactionAmount)
params['ChargeFeeTo'] = chargeFeeTo
params['RecipientTokenId'] = (
recipientTokenId if recipientTokenId is not None
else boto.config.get("FPS", "recipient_token")
)
params['CallerTokenId'] = (
callerTokenId if callerTokenId is not None
else boto.config.get("FPS", "caller_token")
)
if(transactionDate != None):
params['TransactionDate'] = transactionDate
if(senderReference != None):
params['SenderReference'] = senderReference
if(recipientReference != None):
params['RecipientReference'] = recipientReference
if(senderDescription != None):
params['SenderDescription'] = senderDescription
if(recipientDescription != None):
params['RecipientDescription'] = recipientDescription
if(callerDescription != None):
params['CallerDescription'] = callerDescription
if(metadata != None):
params['MetaData'] = metadata
if(callerReference == None):
callerReference = uuid.uuid4()
params['CallerReference'] = callerReference
if reserve:
response = self.make_request("Reserve", params)
else:
response = self.make_request("Pay", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Charges for a reserved payment.
<END_TASK>
<USER_TASK:>
Description:
def settle(self, reserveTransactionId, transactionAmount=None):
"""
Charges for a reserved payment.
""" |
params = {}
params['ReserveTransactionId'] = reserveTransactionId
if(transactionAmount != None):
params['TransactionAmount'] = transactionAmount
response = self.make_request("Settle", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Refund a transaction. This refunds the full amount by default
<END_TASK>
<USER_TASK:>
Description:
def refund(self, callerReference, transactionId, refundAmount=None,
callerDescription=None):
"""
Refund a transaction. This refunds the full amount by default
unless 'refundAmount' is specified.
""" |
params = {}
params['CallerReference'] = callerReference
params['TransactionId'] = transactionId
if(refundAmount != None):
params['RefundAmount'] = refundAmount
if(callerDescription != None):
params['CallerDescription'] = callerDescription
response = self.make_request("Refund", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body) |
<SYSTEM_TASK:>
Read sitemap from a URI including handling sitemapindexes.
<END_TASK>
<USER_TASK:>
Description:
def read(self, uri=None, resources=None, index_only=False):
"""Read sitemap from a URI including handling sitemapindexes.
If index_only is True then individual sitemaps references in a sitemapindex
will not be read. This will result in no resources being returned and is
useful only to read the metadata and links listed in the sitemapindex.
Includes the subtlety that if the input URI is a local file and is a
sitemapindex which contains URIs for the individual sitemaps, then these
are mapped to the filesystem also.
""" |
try:
fh = URLopener().open(uri)
self.num_files += 1
except IOError as e:
raise IOError(
"Failed to load sitemap/sitemapindex from %s (%s)" %
(uri, str(e)))
# Get the Content-Length if we can (works fine for local files)
try:
self.content_length = int(fh.info()['Content-Length'])
self.bytes_read += self.content_length
self.logger.debug(
"Read %d bytes from %s" %
(self.content_length, uri))
except KeyError:
# If we don't get a length then c'est la vie
self.logger.debug("Read ????? bytes from %s" % (uri))
pass
self.logger.info("Read sitemap/sitemapindex from %s" % (uri))
s = self.new_sitemap()
s.parse_xml(fh=fh, resources=self, capability=self.capability_name)
# what did we read? sitemap or sitemapindex?
if (s.parsed_index):
# sitemapindex
if (not self.allow_multifile):
raise ListBaseIndexError(
"Got sitemapindex from %s but support for sitemapindex disabled" %
(uri))
self.logger.info(
"Parsed as sitemapindex, %d sitemaps" %
(len(
self.resources)))
sitemapindex_is_file = self.is_file_uri(uri)
if (index_only):
# don't read the component sitemaps
self.sitemapindex = True
return
# now loop over all entries to read each sitemap and add to
# resources
sitemaps = self.resources
self.resources = self.resources_class()
self.logger.info("Now reading %d sitemaps" % len(sitemaps.uris()))
for sitemap_uri in sorted(sitemaps.uris()):
self.read_component_sitemap(
uri, sitemap_uri, s, sitemapindex_is_file)
else:
# sitemap
self.logger.info("Parsed as sitemap, %d resources" %
(len(self.resources))) |
<SYSTEM_TASK:>
Read a component sitemap of a Resource List with index.
<END_TASK>
<USER_TASK:>
Description:
def read_component_sitemap(
self, sitemapindex_uri, sitemap_uri, sitemap, sitemapindex_is_file):
"""Read a component sitemap of a Resource List with index.
Each component must be a sitemap with the
""" |
if (sitemapindex_is_file):
if (not self.is_file_uri(sitemap_uri)):
# Attempt to map URI to local file
remote_uri = sitemap_uri
sitemap_uri = self.mapper.src_to_dst(remote_uri)
self.logger.info(
"Mapped %s to local file %s" %
(remote_uri, sitemap_uri))
else:
# The individual sitemaps should be at a URL (scheme/server/path)
# that the sitemapindex URL can speak authoritatively about
if (self.check_url_authority and
not UrlAuthority(sitemapindex_uri).has_authority_over(sitemap_uri)):
raise ListBaseIndexError(
"The sitemapindex (%s) refers to sitemap at a location it does not have authority over (%s)" %
(sitemapindex_uri, sitemap_uri))
try:
fh = URLopener().open(sitemap_uri)
self.num_files += 1
except IOError as e:
raise ListBaseIndexError(
"Failed to load sitemap from %s listed in sitemap index %s (%s)" %
(sitemap_uri, sitemapindex_uri, str(e)))
# Get the Content-Length if we can (works fine for local files)
try:
self.content_length = int(fh.info()['Content-Length'])
self.bytes_read += self.content_length
except KeyError:
# If we don't get a length then c'est la vie
pass
self.logger.info(
"Reading sitemap from %s (%d bytes)" %
(sitemap_uri, self.content_length))
component = sitemap.parse_xml(fh=fh, sitemapindex=False)
# Copy resources into self, check any metadata
for r in component:
self.resources.add(r) |
<SYSTEM_TASK:>
Return False or the number of component sitemaps required.
<END_TASK>
<USER_TASK:>
Description:
def requires_multifile(self):
"""Return False or the number of component sitemaps required.
In the case that no len() is available for self.resources then
then self.count must be set beforehand to avoid an exception.
""" |
if (self.max_sitemap_entries is None or
len(self) <= self.max_sitemap_entries):
return(False)
return(int(math.ceil(len(self) / float(self.max_sitemap_entries)))) |
<SYSTEM_TASK:>
Return a string of the index for a large list that is split.
<END_TASK>
<USER_TASK:>
Description:
def as_xml_index(self, basename="/tmp/sitemap.xml"):
"""Return a string of the index for a large list that is split.
All we need to do is determine the number of component sitemaps will
be is and generate their URIs based on a pattern.
Q - should there be a flag to select generation of each component sitemap
in order to calculate the md5sum?
Q - what timestamp should be used?
""" |
num_parts = self.requires_multifile()
if (not num_parts):
raise ListBaseIndexError(
"Request for sitemapindex for list with only %d entries when max_sitemap_entries is set to %s" %
(len(self), str(
self.max_sitemap_entries)))
index = ListBase()
index.sitemapindex = True
index.capability_name = self.capability_name
index.default_capability()
for n in range(num_parts):
r = Resource(uri=self.part_name(basename, n))
index.add(r)
return(index.as_xml()) |
<SYSTEM_TASK:>
Return a string of component sitemap number part_number.
<END_TASK>
<USER_TASK:>
Description:
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0):
"""Return a string of component sitemap number part_number.
Used in the case of a large list that is split into component
sitemaps.
basename is used to create "index" links to the sitemapindex
Q - what timestamp should be used?
""" |
if (not self.requires_multifile()):
raise ListBaseIndexError(
"Request for component sitemap for list with only %d entries when max_sitemap_entries is set to %s" %
(len(self), str(
self.max_sitemap_entries)))
start = part_number * self.max_sitemap_entries
if (start > len(self)):
raise ListBaseIndexError(
"Request for component sitemap with part_number too high, would start at entry %d yet the list has only %d entries" %
(start, len(self)))
stop = start + self.max_sitemap_entries
if (stop > len(self)):
stop = len(self)
part = ListBase(itertools.islice(self.resources, start, stop))
part.capability_name = self.capability_name
part.default_capability()
part.index = basename
s = self.new_sitemap()
return(s.resources_as_xml(part)) |
<SYSTEM_TASK:>
Write one or a set of sitemap files to disk.
<END_TASK>
<USER_TASK:>
Description:
def write(self, basename='/tmp/sitemap.xml'):
"""Write one or a set of sitemap files to disk.
resources is a ResourceContainer that may be an ResourceList or
a ChangeList. This may be a generator so data is read as needed
and length is determined at the end.
basename is used as the name of the single sitemap file or the
sitemapindex for a set of sitemap files.
Uses self.max_sitemap_entries to determine whether the resource_list can
be written as one sitemap. If there are more entries and
self.allow_multifile is set True then a set of sitemap files,
with an sitemapindex, will be written.
""" |
# Access resources through iterator only
resources_iter = iter(self.resources)
(chunk, nxt) = self.get_resources_chunk(resources_iter)
s = self.new_sitemap()
if (nxt is not None):
# Have more than self.max_sitemap_entries => sitemapindex
if (not self.allow_multifile):
raise ListBaseIndexError(
"Too many entries for a single sitemap but multifile disabled")
# Work out URI of sitemapindex so that we can link up to
# it from the individual sitemap files
try:
index_uri = self.mapper.dst_to_src(basename)
except MapperError as e:
raise ListBaseIndexError(
"Cannot map sitemapindex filename to URI (%s)" %
str(e))
# Use iterator over all resources and count off sets of
# max_sitemap_entries to go into each sitemap, store the
# names of the sitemaps as we go. Copy md from self into
# the index and use this for all chunks also
index = ListBase(md=self.md.copy(), ln=list(self.ln))
index.capability_name = self.capability_name
index.default_capability()
while (len(chunk) > 0):
file = self.part_name(basename, len(index))
# Check that we can map the filename of this sitemap into
# URI space for the sitemapindex
try:
uri = self.mapper.dst_to_src(file)
except MapperError as e:
raise ListBaseIndexError(
"Cannot map sitemap filename to URI (%s)" % str(e))
self.logger.info("Writing sitemap %s..." % (file))
f = open(file, 'w')
chunk.index = index_uri
chunk.md = index.md
s.resources_as_xml(chunk, fh=f)
f.close()
# Record information about this sitemap for index
r = Resource(uri=uri,
timestamp=os.stat(file).st_mtime,
md5=Hashes(['md5'], file).md5)
index.add(r)
# Get next chunk
(chunk, nxt) = self.get_resources_chunk(resources_iter, nxt)
self.logger.info("Wrote %d sitemaps" % (len(index)))
f = open(basename, 'w')
self.logger.info("Writing sitemapindex %s..." % (basename))
s.resources_as_xml(index, sitemapindex=True, fh=f)
f.close()
self.logger.info("Wrote sitemapindex %s" % (basename))
elif self.sitemapindex:
f = open(basename, 'w')
self.logger.info("Writing sitemapindex %s..." % (basename))
s.resources_as_xml(chunk, sitemapindex=True, fh=f)
f.close()
self.logger.info("Wrote sitemapindex %s" % (basename))
else:
f = open(basename, 'w')
self.logger.info("Writing sitemap %s..." % (basename))
s.resources_as_xml(chunk, fh=f)
f.close()
self.logger.info("Wrote sitemap %s" % (basename)) |
<SYSTEM_TASK:>
Return next chunk of resources from resource_iter, and next item.
<END_TASK>
<USER_TASK:>
Description:
def get_resources_chunk(self, resource_iter, first=None):
"""Return next chunk of resources from resource_iter, and next item.
If first parameter is specified then this will be prepended to
the list.
The chunk will contain self.max_sitemap_entries if the iterator
returns that many. next will have the value of the next value from
the iterator, providing indication of whether more is available.
Use this as first when asking for the following chunk.
""" |
chunk = ListBase(md=self.md.copy(), ln=list(self.ln))
chunk.capability_name = self.capability_name
chunk.default_capability()
if (first is not None):
chunk.add(first)
for r in resource_iter:
chunk.add(r)
if (len(chunk) >= self.max_sitemap_entries):
break
# Get next to see whether there are more resources
try:
nxt = next(resource_iter)
except StopIteration:
nxt = None
return(chunk, nxt) |
<SYSTEM_TASK:>
Given some coefficients, return a the derivative of a B-spline.
<END_TASK>
<USER_TASK:>
Description:
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a the derivative of a B-spline.
""" |
return cls._basis_spline_factory(coef, degree, knots, 1, ext) |
<SYSTEM_TASK:>
Given some coefficients, return a B-spline.
<END_TASK>
<USER_TASK:>
Description:
def functions_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a B-spline.
""" |
return cls._basis_spline_factory(coef, degree, knots, 0, ext) |
<SYSTEM_TASK:>
Set the master url that this object works with.
<END_TASK>
<USER_TASK:>
Description:
def set_master(self, url):
"""Set the master url that this object works with.""" |
m = urlparse(url)
self.master_scheme = m.scheme
self.master_netloc = m.netloc
self.master_path = os.path.dirname(m.path) |
<SYSTEM_TASK:>
Return True of the current master has authority over url.
<END_TASK>
<USER_TASK:>
Description:
def has_authority_over(self, url):
"""Return True of the current master has authority over url.
In strict mode checks scheme, server and path. Otherwise checks
just that the server names match or the query url is a
sub-domain of the master.
""" |
s = urlparse(url)
if (s.scheme != self.master_scheme):
return(False)
if (s.netloc != self.master_netloc):
if (not s.netloc.endswith('.' + self.master_netloc)):
return(False)
# Maybe should allow parallel for 3+ components, eg. a.example.org,
# b.example.org
path = os.path.dirname(s.path)
if (self.strict and
path != self.master_path and
not path.startswith(self.master_path)):
return(False)
return(True) |
<SYSTEM_TASK:>
Default factory for creating a permission for an admin.
<END_TASK>
<USER_TASK:>
Description:
def admin_permission_factory(admin_view):
"""Default factory for creating a permission for an admin.
It tries to load a :class:`invenio_access.permissions.Permission`
instance if `invenio_access` is installed.
Otherwise, it loads a :class:`flask_principal.Permission` instance.
:param admin_view: Instance of administration view which is currently being
protected.
:returns: Permission instance.
""" |
try:
pkg_resources.get_distribution('invenio-access')
from invenio_access import Permission
except pkg_resources.DistributionNotFound:
from flask_principal import Permission
return Permission(action_admin_access) |
<SYSTEM_TASK:>
Collect node data asynchronously using gevent lib.
<END_TASK>
<USER_TASK:>
Description:
def get_conns(cred, providers):
"""Collect node data asynchronously using gevent lib.""" |
cld_svc_map = {"aws": conn_aws,
"azure": conn_az,
"gcp": conn_gcp,
"alicloud": conn_ali}
sys.stdout.write("\rEstablishing Connections: ")
sys.stdout.flush()
busy_obj = busy_disp_on()
conn_fn = [[cld_svc_map[x.rstrip('1234567890')], cred[x], x]
for x in providers]
cgroup = Group()
conn_res = []
conn_res = cgroup.map(get_conn, conn_fn)
cgroup.join()
conn_objs = {}
for item in conn_res:
conn_objs.update(item)
busy_disp_off(dobj=busy_obj)
sys.stdout.write("\r \r")
sys.stdout.write("\033[?25h") # cursor back on
sys.stdout.flush()
return conn_objs |
<SYSTEM_TASK:>
Refresh node data using existing connection-objects.
<END_TASK>
<USER_TASK:>
Description:
def get_data(conn_objs, providers):
"""Refresh node data using existing connection-objects.""" |
cld_svc_map = {"aws": nodes_aws,
"azure": nodes_az,
"gcp": nodes_gcp,
"alicloud": nodes_ali}
sys.stdout.write("\rCollecting Info: ")
sys.stdout.flush()
busy_obj = busy_disp_on()
collec_fn = [[cld_svc_map[x.rstrip('1234567890')], conn_objs[x]]
for x in providers]
ngroup = Group()
node_list = []
node_list = ngroup.map(get_nodes, collec_fn)
ngroup.join()
busy_disp_off(dobj=busy_obj)
sys.stdout.write("\r \r")
sys.stdout.write("\033[?25h") # cursor back on
sys.stdout.flush()
return node_list |
<SYSTEM_TASK:>
Establish connection to AWS service.
<END_TASK>
<USER_TASK:>
Description:
def conn_aws(cred, crid):
"""Establish connection to AWS service.""" |
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cred['aws_secret_access_key'],
region=cred['aws_default_region'])
except SSLError as e:
abort_err("\r SSL Error with AWS: {}".format(e))
except InvalidCredsError as e:
abort_err("\r Error with AWS Credentials: {}".format(e))
return {crid: aws_obj} |
<SYSTEM_TASK:>
Establish connection to Azure service.
<END_TASK>
<USER_TASK:>
Description:
def conn_az(cred, crid):
"""Establish connection to Azure service.""" |
driver = get_driver(Provider.AZURE_ARM)
try:
az_obj = driver(tenant_id=cred['az_tenant_id'],
subscription_id=cred['az_sub_id'],
key=cred['az_app_id'],
secret=cred['az_app_sec'])
except SSLError as e:
abort_err("\r SSL Error with Azure: {}".format(e))
except InvalidCredsError as e:
abort_err("\r Error with Azure Credentials: {}".format(e))
return {crid: az_obj} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.