code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
params = {'AutoScalingGroupName': as_group,
'ScheduledActionName': name,
'Time': time.isoformat()}
if desired_capacity is not None:
params['DesiredCapacity'] = desired_capacity
if min_size is not None:
params['MinSize'] = min_s... | def create_scheduled_group_action(self, as_group, name, time,
desired_capacity=None,
min_size=None, max_size=None) | Creates a scheduled scaling action for a Auto Scaling group. If you
leave a parameter unspecified, the corresponding value remains
unchanged in the affected Auto Scaling group.
:type as_group: string
:param as_group: The auto scaling group to get activities on.
:type name: stri... | 1.506798 | 1.668602 | 0.90303 |
params = {'AutoScalingGroupName': as_group}
if metrics:
self.build_list_params(params, metrics, 'Metrics')
return self.get_status('DisableMetricsCollection', params) | def disable_metrics_collection(self, as_group, metrics=None) | Disables monitoring of group metrics for the Auto Scaling group
specified in AutoScalingGroupName. You can specify the list of affected
metrics with the Metrics parameter. | 3.755641 | 3.62453 | 1.036173 |
params = {'AutoScalingGroupName': as_group,
'Granularity': granularity}
if metrics:
self.build_list_params(params, metrics, 'Metrics')
return self.get_status('EnableMetricsCollection', params) | def enable_metrics_collection(self, as_group, granularity, metrics=None) | Enables monitoring of group metrics for the Auto Scaling group
specified in AutoScalingGroupName. You can specify the list of enabled
metrics with the Metrics parameter.
Auto scaling metrics collection can be turned on only if the
InstanceMonitoring.Enabled flag, in the Auto Scaling gro... | 3.177361 | 3.773073 | 0.842115 |
params = {'InstanceId': instance_id,
'HealthStatus': health_status}
if should_respect_grace_period:
params['ShouldRespectGracePeriod'] = 'true'
else:
params['ShouldRespectGracePeriod'] = 'false'
return self.get_status('SetInstanceHealth'... | def set_instance_health(self, instance_id, health_status,
should_respect_grace_period=True) | Explicitly set the health status of an instance.
:type instance_id: str
:param instance_id: The identifier of the EC2 instance.
:type health_status: str
:param health_status: The health status of the instance.
"Healthy" means that the instance is healthy and should remain
... | 1.729818 | 2.070776 | 0.835348 |
params = {}
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
return self.get_list('DescribeTags', params,
[('member', Tag)]) | def get_all_tags(self, filters=None, max_records=None, next_token=None) | Lists the Auto Scaling group tags.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the next page, call this action again with the returned token as the NextToken parameter.
:type filters: dict
:param filters: The value of the... | 2.618644 | 2.727918 | 0.959942 |
params = {}
for i, tag in enumerate(tags):
tag.build_params(params, i+1)
return self.get_status('CreateOrUpdateTags', params, verb='POST') | def create_or_update_tags(self, tags) | Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags. | 6.426732 | 4.783851 | 1.343422 |
return [SQSRegionInfo(name='us-east-1',
endpoint='sqs.us-east-1.amazonaws.com'),
SQSRegionInfo(name='eu-west-1',
endpoint='sqs.eu-west-1.amazonaws.com'),
SQSRegionInfo(name='us-west-1',
endpoint='sqs.us-west-1... | def regions() | Get all available regions for the SQS service.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo` | 1.445051 | 1.39615 | 1.035026 |
import binascii
digest = binascii.unhexlify(md5_hexdigest)
base64md5 = base64.encodestring(digest)
if base64md5[-1] == '\n':
base64md5 = base64md5[0:-1]
return (md5_hexdigest, base64md5) | def get_md5_from_hexdigest(self, md5_hexdigest) | A utility function to create the 2-tuple (md5hexdigest, base64md5)
from just having a precalculated md5_hexdigest. | 2.318154 | 1.86439 | 1.243385 |
if self.resp == None:
self.mode = 'r'
provider = self.bucket.connection.provider
self.resp = self.bucket.connection.make_request(
'GET', self.bucket.name, self.name, headers,
query_args=query_args,
override_num_retries... | def open_read(self, headers=None, query_args='',
override_num_retries=None, response_headers=None) | Open this key for reading
:type headers: dict
:param headers: Headers to pass in the web request
:type query_args: string
:param query_args: Arguments to pass in the query string (ie, 'torrent')
:type override_num_retries: int
:param override_num_retries: If not None w... | 2.326043 | 2.403707 | 0.96769 |
self.open_read()
data = self.resp.read(self.BufferSize)
if not data:
self.close()
raise StopIteration
return data | def next(self) | By providing a next method, the key object supports use as an iterator.
For example, you can now say:
for bytes in key:
write bytes to a file or whatever
All of the HTTP connection stuff is handled for you. | 5.883579 | 5.713431 | 1.02978 |
if new_storage_class == 'STANDARD':
return self.copy(self.bucket.name, self.name,
reduced_redundancy=False, preserve_acl=True)
elif new_storage_class == 'REDUCED_REDUNDANCY':
return self.copy(self.bucket.name, self.name,
... | def change_storage_class(self, new_storage_class, dst_bucket=None) | Change the storage class of an existing key.
Depending on whether a different destination bucket is supplied
or not, this will either move the item within the bucket, preserving
all metadata and ACL info bucket changing the storage class or it
will copy the item to the provided destinati... | 2.180072 | 2.22598 | 0.979376 |
dst_bucket = self.bucket.connection.lookup(dst_bucket)
if reduced_redundancy:
storage_class = 'REDUCED_REDUNDANCY'
else:
storage_class = self.storage_class
return dst_bucket.copy_key(dst_key, self.bucket.name,
self.name,... | def copy(self, dst_bucket, dst_key, metadata=None,
reduced_redundancy=False, preserve_acl=False,
encrypt_key=False) | Copy this Key to another bucket.
:type dst_bucket: string
:param dst_bucket: The name of the destination bucket
:type dst_key: string
:param dst_key: The name of the destination key
:type metadata: dict
:param metadata: Metadata to be associated with new key.
... | 1.979139 | 2.469593 | 0.801403 |
return self.bucket.delete_key(self.name, version_id=self.version_id) | def delete(self) | Delete this key from S3 | 5.309732 | 3.336387 | 1.591462 |
return self.bucket.connection.generate_url(expires_in, method,
self.bucket.name, self.name,
headers, query_auth,
force_http,
... | def generate_url(self, expires_in, method='GET', headers=None,
query_auth=True, force_http=False, response_headers=None,
expires_in_absolute=False) | Generate a URL to access this key.
:type expires_in: int
:param expires_in: How long the url is valid for, in seconds
:type method: string
:param method: The method to use for retrieving the file
(default is GET)
:type headers: dict
:param header... | 2.875582 | 3.07264 | 0.935867 |
tup = compute_md5(fp, size=size)
# Returned values are MD5 hash, base64 encoded MD5 hash, and data size.
# The internal implementation of compute_md5() needs to return the
# data size but we don't want to return that value to the external
# caller because it changes the... | def compute_md5(self, fp, size=None) | :type fp: file
:param fp: File pointer to the file to MD5 hash. The file pointer
will be reset to the same position before the
method returns.
:type size: int
:param size: (optional) The Maximum number of bytes to read from
the file po... | 8.430572 | 8.83908 | 0.953784 |
provider = self.bucket.connection.provider
if not provider.supports_chunked_transfer():
raise BotoClientError('%s does not support chunked transfer'
% provider.get_provider_name())
# Name of the Object should be specified explicitly for Streams.
if ... | def set_contents_from_stream(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None,
reduced_redundancy=False, query_args=None,
size=None) | Store an object using the name of the Key object as the key in
cloud and the contents of the data stream pointed to by 'fp' as
the contents.
The stream object is not seekable and total size is not known.
This has the implication that we can't specify the Content-Size and
Content-... | 3.376261 | 3.476752 | 0.971096 |
fp = open(filename, 'rb')
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, reduced_redundancy,
encrypt_key=encrypt_key)
fp.close() | def set_contents_from_filename(self, filename, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=False,
encrypt_key=False) | Store an object in S3 using the name of the Key object as the
key in S3 and the contents of the file named by 'filename'.
See set_contents_from_file method for details about the
parameters.
:type filename: string
:param filename: The name of the file that you want to put onto S3... | 1.895619 | 2.399978 | 0.789849 |
save_debug = self.bucket.connection.debug
if self.bucket.connection.debug == 1:
self.bucket.connection.debug = 0
query_args = []
if torrent:
query_args.append('torrent')
m = None
else:
m = md5()
# If a version_id i... | def get_file(self, fp, headers=None, cb=None, num_cb=10,
torrent=False, version_id=None, override_num_retries=None,
response_headers=None) | Retrieves a file from an S3 Key
:type fp: file
:param fp: File pointer to put the data into
:type headers: string
:param: headers to send when retrieving the files
:type cb: function
:param cb: a callback function that will be called to report
progre... | 2.769195 | 2.720832 | 1.017775 |
return self.get_file(fp, headers, cb, num_cb, torrent=True) | def get_torrent_file(self, fp, headers=None, cb=None, num_cb=10) | Get a torrent file (see to get_file)
:type fp: file
:param fp: The file pointer of where to put the torrent
:type headers: dict
:param headers: Headers to be passed
:type cb: function
:param cb: a callback function that will be called to report
progr... | 4.04423 | 7.729381 | 0.523228 |
if self.bucket != None:
if res_download_handler:
res_download_handler.get_file(self, fp, headers, cb, num_cb,
torrent=torrent,
version_id=version_id)
else:
... | def get_contents_to_file(self, fp, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None,
response_headers=None) | Retrieve an object from S3 using the name of the Key object as the
key in S3. Write the contents of the object to the file pointed
to by 'fp'.
:type fp: File -like object
:param fp:
:type headers: dict
:param headers: additional HTTP headers that will be sent with
... | 2.128656 | 2.289932 | 0.929572 |
fp = StringIO.StringIO()
self.get_contents_to_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id,
response_headers=response_headers)
return fp.getvalue() | def get_contents_as_string(self, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
response_headers=None) | Retrieve an object from S3 using the name of the Key object as the
key in S3. Return the contents of the object as a string.
See get_contents_to_file method for details about the
parameters.
:type headers: dict
:param headers: Any additional headers to send in the request
... | 2.1261 | 2.799616 | 0.759426 |
policy = self.get_acl(headers=headers)
policy.acl.add_email_grant(permission, email_address)
self.set_acl(policy, headers=headers) | def add_email_grant(self, permission, email_address, headers=None) | Convenience method that provides a quick way to add an email grant
to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL
and then PUT's the new ACL back to S3.
:type permission: string
:param permission... | 3.230146 | 3.500654 | 0.922726 |
policy = self.get_acl()
policy.acl.add_user_grant(permission, user_id,
display_name=display_name)
self.set_acl(policy, headers=headers) | def add_user_grant(self, permission, user_id, headers=None,
display_name=None) | Convenience method that provides a quick way to add a canonical
user grant to a key. This method retrieves the current ACL,
creates a new grant based on the parameters passed in, adds that
grant to the ACL and then PUT's the new ACL back to S3.
:type permission: string
:param p... | 3.278105 | 3.458027 | 0.94797 |
from botornado.sqs.connection import AsyncSQSConnection
return AsyncSQSConnection(aws_access_key_id, aws_secret_access_key, **kwargs) | def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs) | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sqs.connection.SQSConnection`
:return: A connection to Amazon's SQS | 3.854313 | 5.155745 | 0.747576 |
from botornado.s3.connection import AsyncS3Connection
return AsyncS3Connection(aws_access_key_id, aws_secret_access_key, **kwargs) | def connect_s3(aws_access_key_id=None, aws_secret_access_key=None, **kwargs) | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.connection.S3Connection`
:return: A connection to Amazon's S3 | 3.644351 | 4.908405 | 0.742472 |
raise BotoClientError('Not Implemented') | def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None,
port=8773, path='/services/Eucalyptus', is_secure=False,
**kwargs) | Connect to a Eucalyptus service.
:type host: string
:param host: the host name or ip address of the Eucalyptus server
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
... | 36.325542 | 63.086689 | 0.575804 |
val = self.get(name)
if not val:
return None
if name.find('queue') >= 0:
obj = boto.lookup('sqs', val)
if obj:
obj.set_message_class(ServiceMessage)
elif name.find('bucket') >= 0:
obj = boto.lookup('s3', val)
... | def get_obj(self, name) | Returns the AWS object associated with a given option.
The heuristics used are a bit lame. If the option name contains
the word 'bucket' it is assumed to be an S3 bucket, if the name
contains the word 'queue' it is assumed to be an SQS queue and
if it contains the word 'domain' it is a... | 3.09232 | 2.370806 | 1.304333 |
dumped = json.dumps(data, ensure_ascii=False)
resp = current_app.response_class(
dumped, status=status, headers=headers,
content_type='application/json; charset=utf-8')
return resp | def export_json(data, status, headers) | Creates a JSON response
JSON content is encoded by utf-8, not unicode escape.
Args:
data: any type object that can dump to json
status (int): http status code
headers (dict): http headers | 2.360721 | 2.929631 | 0.805808 |
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
else:
group_name = None
group_owner_id = None
return self.connection.authorize_dbsecurity_group(self.name,
... | def authorize(self, cidr_ip=None, ec2_group=None) | Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`
@rtype: bool... | 2.474279 | 2.309023 | 1.07157 |
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
return self.connection.revoke_dbsecurity_group(
self.name,
ec2_security_group_name=group_name,
ec2_security_group_... | def revoke(self, cidr_ip=None, ec2_group=None) | Revoke access to a CIDR range or EC2 SecurityGroup.
You need to pass in either a CIDR block or
an EC2 SecurityGroup from which to revoke access.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to revoke
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`... | 2.751007 | 2.674521 | 1.028598 |
if user[0] == '#':
LOGGER.warning(f"Whisper is for users only.")
else:
super().message('#jtv', f".w {user} {message}") | def whisper(self, user, message) | This seems super gimmicky, but so far this is the only way
way I've seen to do this (at least through IRC). It's definitely
not documented. | 10.510758 | 9.776443 | 1.075111 |
if message.params[1] in {'WHO', 'WHOIS'}:
LOGGER.debug('Pydle sent WHO/WHOIS which resulted in 421')
else:
super().on_raw_421(message) | def on_raw_421(self, message) | Twitch doesn't support WHO/WHOIS,
so ignore errors from those commands | 6.936955 | 4.70434 | 1.474586 |
more_results = True
part = None
while more_results:
parts = mpupload.get_all_parts(None, part_number_marker)
for part in parts:
yield part
part_number_marker = mpupload.next_part_number_marker
more_results= mpupload.is_truncated | def part_lister(mpupload, part_number_marker=None) | A generator function for listing parts of a multipart upload. | 2.766744 | 2.543317 | 1.087848 |
self._parts = []
query_args = 'uploadId=%s' % self.id
if max_parts:
query_args += '&max-parts=%d' % max_parts
if part_number_marker:
query_args += '&part-number-marker=%s' % part_number_marker
response = self.bucket.connection.make_request('GET', ... | def get_all_parts(self, max_parts=None, part_number_marker=None) | Return the uploaded parts of this MultiPart Upload. This is
a lower-level method that requires you to manually page through
results. To simplify this process, you can just use the
object itself as an iterator and it will automatically handle
all of the paging with S3. | 2.074256 | 2.005493 | 1.034287 |
if part_num < 1:
raise ValueError('Part numbers must be greater than zero')
query_args = 'uploadId=%s&partNumber=%d' % (self.id, part_num)
key = self.bucket.new_key(self.key_name)
key.set_contents_from_file(fp, headers, replace, cb, num_cb, policy,
... | def upload_part_from_file(self, fp, part_num, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
size=None) | Upload another part of this MultiPart Upload.
:type fp: file
:param fp: The file object you want to upload.
:type part_num: int
:param part_num: The number of this part.
The other parameters are exactly as defined for the
:class:`boto.s3.key.Key` set_co... | 2.445264 | 2.497416 | 0.979117 |
if part_num < 1:
raise ValueError('Part numbers must be greater than zero')
query_args = 'uploadId=%s&partNumber=%d' % (self.id, part_num)
if start is not None and end is not None:
rng = 'bytes=%s-%s' % (start, end)
provider = self.bucket.connection.p... | def copy_part_from_key(self, src_bucket_name, src_key_name, part_num,
start=None, end=None) | Copy another part of this MultiPart Upload.
:type src_bucket_name: string
:param src_bucket_name: Name of the bucket containing the source key
:type src_key_name: string
:param src_key_name: Name of the source key
:type part_num: int
:param part_num: The number of this... | 2.632117 | 3.090612 | 0.851649 |
xml = self.to_xml()
return self.bucket.complete_multipart_upload(self.key_name,
self.id, xml) | def complete_upload(self) | Complete the MultiPart Upload operation. This method should
be called when all parts of the file have been successfully
uploaded to S3.
:rtype: :class:`boto.s3.multipart.CompletedMultiPartUpload`
:returns: An object representing the completed upload. | 6.637767 | 7.439792 | 0.892198 |
token_data = json.loads(raw_token)
# This header is the 'magic' that makes this empty GET request work.
headers = {'Authorization': 'OAuth %s' % token_data['access_token']}
try:
response = self.request('get', self.profile_url, headers=headers)
response.r... | def get_profile_data(self, raw_token) | Fetch user profile information. | 3.893449 | 3.768582 | 1.033134 |
''' place buy order'''
cash=self.__getCashToBuyStock()
if cash == 0:
return
share=math.floor(cash / float(tick.close))
order=Order(accountId=self.__strategy.accountId,
action=Action.BUY,
is_market=True,
... | def __placeBuyOrder(self, tick) | place buy order | 5.462088 | 5.707955 | 0.956926 |
''' place sell order '''
if self.__position < 0:
return
share=self.__position
order=Order(accountId=self.__strategy.accountId,
action=Action.SELL,
is_market=True,
symbol=self.__symbol,
... | def __placeSellOrder(self, tick) | place sell order | 5.389701 | 5.659251 | 0.95237 |
''' consume ticks '''
LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__symbol, tick.time, tick.close))
self.__priceZscore(tick.close)
self.__volumeZscore(tick.volume)
# get zscore
priceZscore=self.__priceZscore.getLastValue()
volumeZscore=self.__volumeZ... | def tickUpdate(self, tick) | consume ticks | 4.261579 | 4.176705 | 1.020321 |
if self.provider is not None:
return self.provider
return providers.by_id(provider) | def get_provider(self, provider) | Get instance of the OAuth client for this provider. | 6.303657 | 6.203554 | 1.016136 |
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id}) | def get_callback_url(self, provider) | Return the callback url for this provider. | 3.123115 | 2.825224 | 1.105439 |
provider_id = kwargs.get('provider', '')
provider = self.get_provider(provider_id)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
params = self.get_additional_parameters(provider)
return provider.g... | def get_redirect_url(self, **kwargs) | Build redirect url for a given provider. | 3.075438 | 2.816067 | 1.092104 |
info = self.model._meta.app_label, self.model._meta.model_name
# inline import to prevent circular imports.
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse('admin:%s... | def get_login_redirect(self, provider, account) | Return url to redirect authenticated users. | 2.802919 | 2.647314 | 1.058778 |
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_changelist' % info) | def get_error_redirect(self, provider, reason) | Return url to redirect on login failure. | 3.751207 | 3.24491 | 1.156028 |
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason)) | def handle_login_failure(self, provider, reason) | Message user and redirect on error. | 4.322509 | 3.979038 | 1.08632 |
s = FakeServer(instance, ssh_key_file)
return SSHClient(s, host_key_file, user_name, ssh_pwd) | def sshclient_from_instance(instance, ssh_key_file,
host_key_file='~/.ssh/known_hosts',
user_name='root', ssh_pwd=None) | Create and return an SSHClient object given an
instance object.
:type instance: :class`boto.ec2.instance.Instance` object
:param instance: The instance object.
:type ssh_key_file: str
:param ssh_key_file: A path to the private key file used
to log into instance.
:type... | 3.603188 | 6.157259 | 0.585193 |
sftp_client = self.open_sftp()
return sftp_client.open(filename, mode, bufsize) | def open(self, filename, mode='r', bufsize=-1) | Open a file on the remote system and return a file-like object. | 3.401785 | 3.086133 | 1.102281 |
boto.log.debug('running:%s on %s' % (command, self.server.instance_id))
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
status = 1
std_out = t[1].read()
std_err = t[2].read()
t[0].close()
... | def run(self, command) | Execute a command on the remote host. Return a tuple containing
an integer status and a two strings, the first containing stdout
and the second containing stderr from the command. | 2.42816 | 2.239202 | 1.084386 |
boto.log.debug('running:%s on %s' % (command, self.server.instance_id))
channel = self._ssh_client.get_transport().open_session()
channel.get_pty()
channel.exec_command(command)
return channel.recv(1024) | def run_pty(self, command) | Execute a command on the remote host with a pseudo-terminal.
Returns a string containing the output of the command. | 3.397471 | 3.202096 | 1.061015 |
if feature == 'hog':
return hog
elif feature == 'deep':
return deep
elif feature == 'gray':
return gray
elif feature == 'lab':
return lab
elif feature == 'luv':
return luv
elif feature == 'hsv':
return hsv
elif feature == 'hls':
re... | def factory(feature) | Factory to choose feature extractor
:param feature: name of the feature
:return: Feature extractor function | 2.390757 | 2.60945 | 0.916192 |
op = _DEF_HOG_OPTS.copy()
if options is not None:
op.update(options)
img = gray(img)
img_fd = skimage.feature.hog(img,
orientations=op['orientations'],
pixels_per_cell=op['cell_size'],
cells_... | def hog(img, options=None) | HOG feature extractor.
:param img:
:param options:
:return: HOG Feature for given image
The output will have channels same as number of orientations.
Height and Width will be reduced based on block-size and cell-size | 2.662422 | 2.784664 | 0.956102 |
if self.key_type & self.KEY_STREAM_READABLE:
raise BotoClientError('Stream is not Readable')
elif self.key_type & self.KEY_STREAM_WRITABLE:
key_file = self.fp
else:
key_file = open(self.full_path, 'rb')
try:
shutil.copyfileobj(key_... | def get_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False) | Retrieves a file from a Key
:type fp: file
:param fp: File pointer to put the data into
:type headers: string
:param: ignored in this subclass.
:type cb: function
:param cb: ignored in this subclass.
:type cb: int
:param num_cb: ignored in this subclas... | 4.066047 | 4.343235 | 0.93618 |
if self.key_type & self.KEY_STREAM_WRITABLE:
raise BotoClientError('Stream is not writable')
elif self.key_type & self.KEY_STREAM_READABLE:
key_file = self.fp
else:
if not replace and os.path.exists(self.full_path):
return
... | def set_contents_from_file(self, fp, headers=None, replace=True, cb=None,
num_cb=10, policy=None, md5=None) | Store an object in a file using the name of the Key object as the
key in file URI and the contents of the file pointed to by 'fp' as the
contents.
:type fp: file
:param fp: the file whose contents to upload
:type headers: dict
:param headers: ignored in this subclass.
... | 3.067428 | 3.574519 | 0.858137 |
fp = StringIO.StringIO()
self.get_contents_to_file(fp)
return fp.getvalue() | def get_contents_as_string(self, headers=None, cb=None, num_cb=10,
torrent=False) | Retrieve file data from the Key, and return contents as a string.
:type headers: dict
:param headers: ignored in this subclass.
:type cb: function
:param cb: ignored in this subclass.
:type cb: int
:param num_cb: ignored in this subclass.
:type cb: int
... | 4.358916 | 5.531756 | 0.787981 |
x = max(0, min([box.x for box in boxes]))
y = max(0, min([box.y for box in boxes]))
x2 = max([box.bottom_right()[0] for box in boxes])
y2 = max([box.bottom_right()[1] for box in boxes])
return Box.from_xy(x, y, x2, y2) | def enclosing_box(boxes) | Finds a new box that exactly encloses all the given boxes.
:param boxes: Array of Box objects
:return: Box object that encloses all boxes | 2.425047 | 2.434725 | 0.996025 |
x_list = [(box.x, box) for box in boxes]
x_list.sort()
return x_list[0][1] | def left_most(boxes) | Finds the left most box out of the given boxes.
:param boxes: Array of Box objects
:return: The left-most Box object | 3.470098 | 4.277235 | 0.811295 |
x_list = [(box.x, box) for box in boxes]
x_list.sort()
return x_list[-1][1] | def right_most(boxes) | Finds the right most box out of the given boxes.
:param boxes: Array of Box objects
:return: The right-most Box object | 3.791918 | 4.533536 | 0.836415 |
b1_x2, b1_y2 = box1.bottom_right()
b2_x2, b2_y2 = box2.bottom_right()
x, y = max(box1.x, box2.x), max(box1.y, box2.y)
x2, y2 = min(b1_x2, b2_x2), min(b1_y2, b2_y2)
w, h = max(0, x2-x), max(0, y2-y)
return Box(x, y, w, h) | def intersection_box(box1, box2) | Finds an intersection box that is common to both given boxes.
:param box1: Box object 1
:param box2: Box object 2
:return: None if there is no intersection otherwise the new Box | 1.652036 | 1.787197 | 0.924373 |
int_box = Box.intersection_box(box1, box2)
int_area = int_box.area()
union_area = box1.area() + box2.area() - int_area
result = 0.0
if union_area > 0:
result = float(int_area) / float(union_area)
return result | def iou(box1, box2) | Find intersection over union-area for given two boxes.
It the ratio of intersection-area / union-area
:param box1: Box object 1
:param box2: Box object 2
:return: Intersection-over-union value | 2.379069 | 2.550928 | 0.932629 |
int_box = Box.intersection_box(self, box)
small_box = self if self.smaller(box) else box
return True if int_box.area() / small_box.area() >= th else False | def overlaps(self, box, th=0.0001) | Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps | 5.111466 | 5.715178 | 0.894367 |
ex_h = math.ceil(self.height * percentage / 100)
ex_w = math.ceil(self.width * percentage / 100)
x = max(0, self.x - ex_w)
y = max(0, self.y - ex_h)
x2 = self.x + self.width + ex_w
y2 = self.y + self.height + ex_h
return Box.from_xy(x, y, x2, y2) | def expand(self, percentage) | Expands the box co-ordinates by given percentage on four sides. Ignores negative values.
:param percentage: Percentage to expand
:return: New expanded Box | 2.00979 | 2.129303 | 0.943872 |
# if px is not an array, have equal padding all sides
if not isinstance(px, list):
px = [px] * 4
x = max(0, self.x - px[3])
y = max(0, self.y - px[0])
x2 = self.x + self.width + px[1]
y2 = self.y + self.height + px[2]
return Box.from_xy(x, y,... | def padding(self, px) | Add padding around four sides of box
:param px: padding value in pixels.
Can be an array in the format of [top right bottom left] or single value.
:return: New padding added box | 2.925653 | 2.620333 | 1.116519 |
w, h = box_size
rows = round(self.height / h)
cols = round(self.width / w)
boxes = []
for row in range(rows):
for col in range(cols):
box = Box(self.x + (col * w), self.y + (row * h), w, h)
boxes.append(box)
return box... | def split(self, box_size) | Splits the box object into many boxes each of given size.
Assumption: the entire box can be split into rows and columns with the given size.
:param box_size: (width, height) of the new tiny boxes
:return: Array of tiny boxes | 2.014469 | 2.033334 | 0.990722 |
x = round(x_percent * self.width)
y = round(y_percent * self.height)
return int(x), int(y) | def pos_by_percent(self, x_percent, y_percent) | Finds a point inside the box that is exactly at the given percentage place.
:param x_percent: how much percentage from left edge
:param y_percent: how much percentage from top edge
:return: A point inside the box | 2.561243 | 3.236505 | 0.791361 |
if reverse:
point = [-1 * i for i in point]
return Box(self.x + point[0], self.y + point[1], self.width, self.height) | def move(self, point, reverse=False) | Translates the box by given (tx, ty)
:param point: (tx, ty)
:param reverse: If true, the translation direction is reversed. ie. (-tx, -ty)
:return: New translated box | 3.06773 | 3.402439 | 0.901627 |
coord = [int(round(x)) for x in self.xy_coord()]
return self.from_xy(coord[0], coord[1], coord[2], coord[3]) | def to_int(self) | Rounds off and converts (x,y,w,h) to int
:return: a Box object with all integer values | 4.834277 | 5.060486 | 0.955299 |
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python') | def _python_rpath(self) | The relative path (from environment root) to python. | 10.069878 | 8.897958 | 1.131707 |
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n... | def pip_version(self) | Version of installed pip. | 4.151593 | 4.064994 | 1.021303 |
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.py... | def _create(self) | Executes `virtualenv` to create a new environment. | 2.818194 | 2.532427 | 1.112843 |
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append(... | def _execute_pip(self, args, log=True) | Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute | 5.603834 | 5.711278 | 0.981187 |
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.r... | def _execute(self, args, log=True) | Executes the given command inside the environment and returns the output. | 2.763873 | 2.720474 | 1.015953 |
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), )) | def _write_to_log(self, s, truncate=False) | Writes the given output to the log file, appending unless `truncate` is True. | 5.830678 | 6.07071 | 0.960461 |
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), ) | def _write_to_error(self, s, truncate=False) | Writes the given output to the error file, appending unless `truncate` is True. | 7.937593 | 7.610783 | 1.04294 |
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) | def _pip_exists(self) | Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed. | 3.956367 | 2.946438 | 1.342763 |
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
... | def install(self, package, force=False, upgrade=False, options=None) | Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
... | 3.048608 | 2.773556 | 1.099169 |
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subproc... | def uninstall(self, package) | Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment. | 3.549752 | 3.265062 | 1.087193 |
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package mu... | def wheel(self, package, options=None) | Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strin... | 3.649307 | 3.445795 | 1.059061 |
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_na... | def is_installed(self, package) | Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment. | 2.880907 | 2.622608 | 1.098489 |
self.install(package, upgrade=True, force=force) | def upgrade(self, package, force=False) | Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op. | 6.885716 | 5.933393 | 1.160502 |
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True) | def upgrade_all(self) | Upgrades all installed packages to their latest versions. | 7.139559 | 5.01893 | 1.422526 |
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in resul... | def search(self, term) | Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples | 5.451187 | 5.316986 | 1.02524 |
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep)))) | def installed_packages(self) | List of all packages that are installed in this environment in
the format [(name, ver), ..]. | 6.05367 | 6.311057 | 0.959217 |
if isinstance(zones, str) or isinstance(zones, unicode):
zones = [zones]
new_zones = self.connection.enable_availability_zones(self.name, zones)
self.availability_zones = new_zones | def enable_zones(self, zones) | Enable availability zones to this Access Point.
All zones must be in the same region as the Access Point.
:type zones: string or List of strings
:param zones: The name of the zone(s) to add. | 3.527971 | 3.968993 | 0.888883 |
if isinstance(zones, str) or isinstance(zones, unicode):
zones = [zones]
new_zones = self.connection.disable_availability_zones(self.name, zones)
self.availability_zones = new_zones | def disable_zones(self, zones) | Disable availability zones from this Access Point.
:type zones: string or List of strings
:param zones: The name of the zone(s) to add. | 3.498221 | 4.024573 | 0.869216 |
if isinstance(instances, str) or isinstance(instances, unicode):
instances = [instances]
new_instances = self.connection.register_instances(self.name, instances)
self.instances = new_instances | def register_instances(self, instances) | Adds instances to this load balancer. All instances must be in the same
region as the load balancer. Adding endpoints that are already
registered with the load balancer has no effect.
:param list instances: List of instance IDs (strings) that you'd like
to add to this load balancer. | 3.338281 | 3.235961 | 1.03162 |
if isinstance(subnets, str) or isinstance(subnets, unicode):
subnets = [subnets]
new_subnets = self.connection.attach_lb_to_subnets(self.name, subnets)
self.subnets = new_subnets | def attach_subnets(self, subnets) | Attaches load balancer to one or more subnets.
Attaching subnets that are already registered with the
Load Balancer has no effect.
:type subnets: string or List of strings
:param subnets: The name of the subnet(s) to add. | 2.791596 | 2.734451 | 1.020898 |
if isinstance(subnets, str) or isinstance(subnets, unicode):
subnets = [subnets]
new_subnets = self.connection.detach_lb_to_subnets(self.name, subnets)
self.subnets = new_subnets | def detach_subnets(self, subnets) | Detaches load balancer from one or more subnets.
:type subnets: string or List of strings
:param subnets: The name of the subnet(s) to detach. | 2.797309 | 2.967418 | 0.942674 |
if isinstance(security_groups, str) or \
isinstance(security_groups, unicode):
security_groups = [security_groups]
new_sgs = self.connection.apply_security_groups_to_lb(
self.name, security_groups)
self.security_groups =... | def apply_security_groups(self, security_groups) | Applies security groups to the load balancer.
Applying security groups that are already registered with the
Load Balancer has no effect.
:type security_groups: string or List of strings
:param security_groups: The name of the security group(s) to add. | 3.295762 | 3.477324 | 0.947787 |
with fileutil.opened(filename, "rb") as file:
file.seek(0)
header = file.read(10)
file.seek(0)
if len(header) < 10:
raise NoTagError("File too short")
if header[0:3] != b"ID3":
raise NoTagError("ID3v2 tag not found")
if header[3] not in _t... | def detect_tag(filename) | Return type and position of ID3v2 tag in filename.
Returns (tag_class, offset, length), where tag_class
is either Tag22, Tag23, or Tag24, and (offset, length)
is the position of the tag in the file. | 3.912018 | 3.336749 | 1.172404 |
assert issubclass(cls, Frames.Frame)
# Register v2.2 versions of v2.3/v2.4 frames if encoded by inheritance.
if len(cls.__name__) == 3:
base = cls.__bases__[0]
if issubclass(base, Frames.Frame) and base._in_version(3, 4):
assert not hasattr(base, "_v2_frame")
ba... | def frameclass(cls) | Register cls as a class representing an ID3 frame.
Sets cls.frameid and cls._version if not present, and registers the
new frame in Tag's known_frames dictionary.
To be used as a decorator on the class definition:
@frameclass
class UFID(Frame):
_framespec = (NullTerminatedStringSpec("owne... | 3.996538 | 3.77701 | 1.058122 |
"Return the sort key for the given frame."
def keytuple(primary):
if frame.frameno is None:
return (primary, 1)
return (primary, 0, frame.frameno)
# Look up frame by exact match
if type(frame) in self.frame_keys:
return keytuple(self.f... | def key(self, frame) | Return the sort key for the given frame. | 4.432262 | 4.291158 | 1.032882 |
if key is not None:
# If there are multiple frames, then they are already in original order.
key = self._normalize_key(key)
if len(self._frames[key]) == 0:
raise KeyError("Key not found: " + repr(key))
return self._frames[key]
... | def frames(self, key=None, orig_order=False) | Returns a list of frames in this tag.
If KEY is None, returns all frames in the tag; otherwise returns all frames
whose frameid matches KEY.
If ORIG_ORDER is True, then the frames are returned in their original order.
Otherwise the frames are sorted in canonical order according ... | 3.374759 | 3.369099 | 1.00168 |
if Frames.is_frame_class(key):
key = key.frameid
if isinstance(key, str):
if not self._is_frame_id(key):
raise KeyError("{0}: Invalid frame id".format(key))
if key not in self.known_frames:
if unknown_ok:
wa... | def _normalize_key(self, key, unknown_ok=True) | Return the normalized version of KEY.
KEY may be a frameid (a string), or a Frame class object.
If KEY corresponds to a registered frameid, then that frameid is returned.
Otherwise, either KeyError is raised, or KEY is returned verbatim,
depending on the value of UNKNOWN_OK. | 3.308815 | 2.788036 | 1.186791 |
i = 0
with fileutil.opened(filename, "rb") as file:
file.seek(offset)
tag = cls()
tag._read_header(file)
for (frameid, bflags, data) in tag._read_frames(file):
if len(data) == 0:
warn("{0}: Ignoring empty frame"... | def read(cls, filename, offset=0) | Read an ID3v2 tag from a file. | 3.784116 | 3.515545 | 1.076395 |
acl = self.get_acl()
acl.add_email_grant(permission, email_address)
self.set_acl(acl) | def add_email_grant(self, permission, email_address) | Convenience method that provides a quick way to add an email grant to a
key. This method retrieves the current ACL, creates a new grant based on
the parameters passed in, adds that grant to the ACL and then PUT's the
new ACL back to GS.
:type permission: string
:param permission... | 2.84915 | 3.049517 | 0.934295 |
acl = self.get_acl()
acl.add_user_grant(permission, user_id)
self.set_acl(acl) | def add_user_grant(self, permission, user_id) | Convenience method that provides a quick way to add a canonical user
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param pe... | 2.675001 | 3.085387 | 0.86699 |
acl = self.get_acl(headers=headers)
acl.add_group_email_grant(permission, email_address)
self.set_acl(acl, headers=headers) | def add_group_email_grant(self, permission, email_address, headers=None) | Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param perm... | 2.640104 | 2.911092 | 0.906912 |
acl = self.get_acl()
acl.add_group_grant(permission, group_id)
self.set_acl(acl) | def add_group_grant(self, permission, group_id) | Convenience method that provides a quick way to add a canonical group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param p... | 2.676015 | 3.254498 | 0.822251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.