code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
file_path = os.path.join(path.abspath(conf.config['log_directory']),
'v2ex.log')
for line in deque(open(file_path, encoding='utf-8'), int(count)):
click.echo(line, nl=False) | def read(conf, count) | Read log file. | 5.633967 | 5.355305 | 1.052035 |
try:
v2ex = V2ex(conf.config)
v2ex.login()
last_date = v2ex.get_last()
click.echo(last_date)
except KeyError:
click.echo('Keyerror, please check your config file.')
except IndexError:
click.echo('Please check your username and password.') | def last(conf) | How long you have kept signing in. | 4.402705 | 4.273004 | 1.030354 |
uploads = []
for match in UPLOAD_RE.finditer(text):
try:
upload = FileUpload.objects.get(slug=match.group(1))
except FileUpload.DoesNotExist:
continue
yield upload | def get_uploads(text) | Return a generator yielding uploads referenced in the given text. | 3.269787 | 2.631166 | 1.242714 |
try:
upload = FileUpload.objects.get(slug=match.group(1))
except FileUpload.DoesNotExist:
upload = None
options = parse_options(match.group(2))
return (upload, options) | def parse_match(match) | Accept an re match object resulting from an ``UPLOAD_RE`` match
and return a two-tuple where the first element is the
corresponding ``FileUpload`` and the second is a dictionary of the
key=value options.
If there is no ``FileUpload`` object corresponding to the match,
the first element of the retur... | 3.776354 | 2.326867 | 1.622935 |
options = {}
for option in s.split(':'):
if '=' in option:
key, val = option.split('=')
options[str(key).strip()] = val.strip()
return options | def parse_options(s) | Expects a string in the form "key=val:key2=val2" and returns a
dictionary. | 2.684257 | 2.378935 | 1.128344 |
jokers = jokers or self.jokers
num_jokers = num_jokers or self.num_jokers
self.decks_used += 1
self.cards += build_cards(jokers, num_jokers) | def build(self, jokers=False, num_jokers=0) | Builds a standard 52 card French deck of Card instances.
:arg bool jokers:
Whether or not to include jokers in the deck.
:arg int num_jokers:
The number of jokers to include. | 2.834892 | 3.346105 | 0.847221 |
_num = num
rebuild = rebuild or self.rebuild
re_shuffle = shuffle or self.re_shuffle
self_size = self.size
if rebuild or num <= self_size:
dealt_cards = [None] * num
elif num > self_size:
dealt_cards = [None] * self_size
while ... | def deal(self, num=1, rebuild=False, shuffle=False, end=TOP) | Returns a list of cards, which are removed from the deck.
:arg int num:
The number of cards to deal.
:arg bool rebuild:
Whether or not to rebuild the deck when cards run out.
:arg bool shuffle:
Whether or not to shuffle on rebuild.
:arg str end:
... | 3.568742 | 3.763331 | 0.948293 |
data = b""
while len(data) < length:
data += socket.recv(bufsize)
return data | def socket_recvall(socket, length, bufsize=4096) | A helper method to read of bytes from a socket to a maximum length | 2.264436 | 2.314698 | 0.978286 |
self.socket.sendto(message.SerializeToString(), self.address)
return None | def send(self, message) | Sends a message, but does not return a response
:returns: None - can't receive a response over UDP | 5.585059 | 5.681513 | 0.983023 |
self.socket = socket.create_connection(self.address, self.timeout) | def connect(self) | Connects to the given host | 4.951725 | 5.145004 | 0.962434 |
message = message.SerializeToString()
self.socket.sendall(struct.pack('!I', len(message)) + message)
length = struct.unpack('!I', self.socket.recv(4))[0]
response = riemann_client.riemann_pb2.Msg()
response.ParseFromString(socket_recvall(self.socket, length))
i... | def send(self, message) | Sends a message to a Riemann server and returns it's response
:param message: The message to send to the Riemann server
:returns: The response message from Riemann
:raises RiemannError: if the server returns an error | 2.998955 | 2.948261 | 1.017195 |
super(TLSTransport, self).connect()
self.socket = ssl.wrap_socket(
self.socket,
ssl_version=ssl.PROTOCOL_TLSv1,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_certs) | def connect(self) | Connects using :py:meth:`TLSTransport.connect` and wraps with TLS | 2.577482 | 2.105003 | 1.224455 |
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
return reply | def send(self, message) | Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True`` | 7.462196 | 7.823677 | 0.953797 |
self.domain.put_attributes(self.name, self, replace)
# Delete any attributes set to "None"
if replace:
del_attrs = []
for name in self:
if self[name] == None:
del_attrs.append(name)
if len(del_attrs) > 0:
... | def save(self, replace=True) | Saves this item to SDB.
:param bool replace: If ``True``, delete any attributes on the remote
SDB item that have a ``None`` value on this object. | 3.277952 | 3.212623 | 1.020335 |
if key in self:
# We already have this key on the item.
if not isinstance(self[key], list):
# The key isn't already a list, take its current value and
# convert it to a list with the only member being the
# current value.
... | def add_value(self, key, value) | Helps set or add to attributes on this item. If you are adding a new
attribute that has yet to be set, it will simply create an attribute
named ``key`` with your given ``value`` as its value. If you are
adding a value to an existing attribute, this method will convert the
attribute to a ... | 3.712217 | 3.458022 | 1.073509 |
"Copy constructor"
assert frame._framespec == cls._framespec
new = cls(flags=frame.flags, frameno=frame.frameno)
for spec in cls._framespec:
setattr(new, spec.name, getattr(frame, spec.name, None))
return new | def _from_frame(cls, frame) | Copy constructor | 4.847029 | 4.576778 | 1.059048 |
"Returns true if this frame is in any of the specified versions of ID3."
for version in versions:
if (self._version == version
or (isinstance(self._version, collections.Container)
and version in self._version)):
return True
return ... | def _in_version(self, *versions) | Returns true if this frame is in any of the specified versions of ID3. | 5.845787 | 3.445054 | 1.696864 |
"Return the named spec."
for s in self._framespec:
if s.name == name:
return s
raise ValueError("Unknown spec: " + name) | def _spec(self, name) | Return the named spec. | 6.241252 | 5.765779 | 1.082465 |
def existence_tested(response):
if callable(callback):
callback(bool(response))
self.bucket.lookup(self.name, callback=existence_tested) | def exists(self, callback=None) | Returns True if the key exists
:rtype: bool
:return: Whether the key exists on S3 | 8.085648 | 9.80372 | 0.824753 |
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, callback=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.463326 | 3.594533 | 0.963498 |
provider = self.bucket.connection.provider
if headers is None:
headers = {}
if policy:
headers[provider.acl_header] = policy
if encrypt_key:
headers[provider.server_side_encryption_header] = 'AES256'
if reduced_redundancy:
... | def set_contents_from_file(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=False, query_args=None,
encrypt_key=False, callback=None) | Store an object in S3 using the name of the Key object as the
key in S3 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: Additional HTTP headers that will be ... | 3.001674 | 3.043987 | 0.9861 |
if cb:
if num_cb > 2:
cb_count = self.size / self.BufferSize / (num_cb-2)
elif num_cb < 0:
cb_count = -1
else:
cb_count = 0
i = total_bytes = 0
cb(total_bytes, self.size)
save_debug = sel... | def get_file(self, fp, headers=None, cb=None, num_cb=10,
torrent=False, version_id=None, override_num_retries=None,
response_headers=None, callback=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... | 3.098559 | 3.031564 | 1.022099 |
fp = open(filename, 'wb')
def got_contents_to_filename(response):
fp.close()
# if last_modified date was sent from s3, try to set file's timestamp
if self.last_modified != None:
try:
modified_tuple = rfc822.parsedate_tz(sel... | def get_contents_to_filename(self, filename, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None,
response_headers=... | Retrieve an object from S3 using the name of the Key object as the
key in S3. Store contents of the object to a file named by 'filename'.
See get_contents_to_file method for details about the
parameters.
:type filename: string
:param filename: The filename of where to put the f... | 2.647183 | 2.892882 | 0.915068 |
fp = StringIO.StringIO()
def got_contents_as_string(response):
if callable(callback):
callback(fp.getvalue())
self.get_contents_to_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id,
... | def get_contents_as_string(self, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
response_headers=None, callback=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.56474 | 3.454141 | 0.742512 |
"Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag."
if len(data) < 10:
raise ValueError("Tag too short")
if data[0:3] != b"ID3":
raise ValueError("Missing ID3 identifier")
if data[3] >= 5 or data[4] != 0:
raise ValueError("Unknown ID3 version")
length = sta... | def check_tag_data(data) | Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag. | 5.212609 | 3.772368 | 1.381787 |
"Return the ID3 tag in FILENAME as a raw byte string."
with open(filename, "rb") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
return bytes()
file.seek(offset)
return file.read(length) | def get_raw_tag_data(filename) | Return the ID3 tag in FILENAME as a raw byte string. | 6.695311 | 4.359553 | 1.535779 |
"Replace the ID3 tag in FILENAME with DATA."
check_tag_data(data)
with open(filename, "rb+") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
(offset, length) = (0, 0)
if length > 0:
verb(verbose, "{0}:... | def set_raw_tag_data(filename, data, act=True, verbose=False) | Replace the ID3 tag in FILENAME with DATA. | 4.617127 | 3.986886 | 1.158079 |
prefix = 'Tags.member.%d.' % i
params[prefix+'ResourceId'] = self.resource_id
params[prefix+'ResourceType'] = self.resource_type
params[prefix+'Key'] = self.key
params[prefix+'Value'] = self.value
if self.propagate_at_launch:
params[prefix+'PropagateA... | def build_params(self, params, i) | Populates a dictionary with the name/value pairs necessary
to identify this Tag in a request. | 2.127832 | 1.962412 | 1.084294 |
params = {'QueueName': queue_name}
if visibility_timeout:
params['Attribute.1.Name'] = 'VisibilityTimeout'
params['Attribute.1.Value'] = int(visibility_timeout)
return self.get_object('CreateQueue', params, Queue) | def create_queue(self, queue_name, visibility_timeout=None) | Create an SQS Queue.
:type queue_name: str or unicode
:param queue_name: The name of the new queue. Names are scoped to
an account and need to be unique within that
account. Calling this method on an existing
queue name ... | 2.28041 | 2.599639 | 0.877203 |
params = {'ReceiptHandle' : message.receipt_handle}
return self.get_status('DeleteMessage', params, queue.id) | def delete_message(self, queue, message) | Delete a message from a queue.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type message: A :class:`boto.sqs.message.Message` object
:param message: The Message to be deleted
:rtype: bool
:re... | 5.679159 | 5.607705 | 1.012742 |
params = {'ReceiptHandle' : receipt_handle}
return self.get_status('DeleteMessage', params, queue.id) | def delete_message_from_handle(self, queue, receipt_handle) | Delete a message from a queue, given a receipt handle.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type receipt_handle: str
:param receipt_handle: The receipt handle for the message
:rtype: bool
... | 4.800235 | 5.710551 | 0.840591 |
params = {}
for i, msg in enumerate(messages):
p_name = 'SendMessageBatchRequestEntry.%i.Id' % (i+1)
params[p_name] = msg[0]
p_name = 'SendMessageBatchRequestEntry.%i.MessageBody' % (i+1)
params[p_name] = msg[1]
p_name = 'SendMessageBa... | def send_message_batch(self, queue, messages) | Delivers up to 10 messages to a queue in a single request.
:type queue: A :class:`boto.sqs.queue.Queue` object.
:param queue: The Queue to which the messages will be written.
:type messages: List of lists.
:param messages: A list of lists or tuples. Each inner
tuple repres... | 2.405912 | 2.345785 | 1.025632 |
params = {}
if prefix:
params['QueueNamePrefix'] = prefix
return self.get_list('ListQueues', params, [('QueueUrl', Queue)]) | def get_all_queues(self, prefix='') | Retrieves all queues.
:keyword str prefix: Optionally, only return queues that start with
this value.
:rtype: list
:returns: A list of :py:class:`boto.sqs.queue.Queue` instances. | 4.546703 | 4.451321 | 1.021428 |
rs = self.get_all_queues(queue_name)
for q in rs:
if q.url.endswith(queue_name):
return q
return None | def get_queue(self, queue_name) | Retrieves the queue with the given name, or ``None`` if no match
was found.
:param str queue_name: The name of the queue to retrieve.
:rtype: :py:class:`boto.sqs.queue.Queue` or ``None``
:returns: The requested queue, or ``None`` if no match was found. | 3.958394 | 3.672071 | 1.077973 |
params = {'Label': label}
return self.get_status('RemovePermission', params, queue.id) | def remove_permission(self, queue, label) | Remove a permission from a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: The unique label associated with the permission
being removed.
:rtype: bool
:return: True if succ... | 7.704965 | 6.782692 | 1.135974 |
db_user = boto.config.get('DB', 'db_user', None)
db_passwd = boto.config.get('DB', 'db_passwd', None)
db_type = boto.config.get('DB', 'db_type', 'SimpleDB')
db_name = boto.config.get('DB', 'db_name', None)
db_table = boto.config.get('DB', 'db_table', None)
db_host = boto.config.get('DB', 'd... | def get_manager(cls) | Returns the appropriate Manager class for a given Model class. It does this by
looking in the boto config for a section like this::
[DB]
db_type = SimpleDB
db_user = <aws access key id>
db_passwd = <aws secret access key>
db_name = my_domain
[DB_TestBasic]
... | 1.799543 | 1.701465 | 1.057644 |
''' increase counter by one and check whether a period is end '''
self.counter += 1
self.counter %= self.period
if not self.counter:
return True
else:
return False | def increase_and_check_counter(self) | increase counter by one and check whether a period is end | 6.574693 | 4.075031 | 1.613409 |
''' consume ticks '''
assert self.symbols
assert self.symbols[0] in tick_dict.keys()
symbol=self.symbols[0]
tick=tick_dict[symbol]
if self.increase_and_check_counter():
self.place_order(Order(account=self.account,
action=Acti... | def tickUpdate(self, tick_dict) | consume ticks | 6.348963 | 6.177685 | 1.027725 |
heatmap, scale = multi_feat_match(template, image, options)
min_val, _, min_loc, _ = cv.minMaxLoc(heatmap)
top_left = tuple(scale * x for x in min_loc)
score = min_val
h, w = template.shape[:2]
return Box(top_left[0], top_left[1], w, h), score | def match_one(template, image, options=None) | Match template and find exactly one match in the Image using specified features.
:param template: Template Image
:param image: Search Image
:param options: Options include
- features: List of options for each feature
:return: (Box, Score) Bounding box of the matched object, Heatmap value | 4.092479 | 4.437094 | 0.922333 |
h, w = image.shape[:2]
scale = 1
if options is not None and 'features' in options:
heatmap = np.zeros((h, w), dtype=np.float64)
for foptions in options['features']:
f_hmap, _ = feature_match(template, image, foptions)
heatmap += cv.resize(f_hmap, (w, h), interpol... | def multi_feat_match(template, image, options=None) | Match template and image by extracting multiple features (specified) from it.
:param template: Template image
:param image: Search image
:param options: Options include
- features: List of options for each feature
:return: | 2.492819 | 2.461704 | 1.01264 |
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
feat = fe.factory(op['feature'])
tmpl_f = feat(template, op)
img_f = feat(image, op)
scale = image.shape[0] / img_f.shape[0]
heatmap = match_template(tmpl_f, img_f, op)
return heatmap, scale | def feature_match(template, image, options=None) | Match template and image by extracting specified feature
:param template: Template image
:param image: Search image
:param options: Options include
- feature: Feature extractor to use. Default is 'rgb'. Available options are:
'hog', 'lab', 'rgb', 'gray'
:return: Heatmap | 4.585623 | 4.377903 | 1.047448 |
# If the input has max of 3 channels, use the faster OpenCV matching
if len(image.shape) <= 3 and image.shape[2] <= 3:
return match_template_opencv(template, image, options)
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
template = img_utils.gray3(template)... | def match_template(template, image, options=None) | Multi channel template matching using simple correlation distance
:param template: Template image
:param image: Search image
:param options: Other options:
- distance: Distance measure to use. Default: 'correlation'
- normalize: Heatmap values will be in the range of 0 to 1. Default: True
... | 2.690224 | 2.458676 | 1.094176 |
# if image has more than 3 channels, use own implementation
if len(image.shape) > 3:
return match_template(template, image, options)
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
method = cv.TM_CCORR_NORMED
if op['normalize'] and op['distance'] == 'euc... | def match_template_opencv(template, image, options) | Match template using OpenCV template matching implementation.
Limited by number of channels as maximum of 3.
Suitable for direct RGB or Gray-scale matching
:param options: Other options:
- distance: Distance measure to use. (euclidean | correlation | ccoeff).
Default: 'correlati... | 2.545351 | 2.27997 | 1.116397 |
if isinstance(resp, flask.Response):
if 400 <= resp.status_code < 600:
msg = resp.status
try:
result = loads(resp.data.decode("utf-8"))
if isinstance(result, str):
msg = "%s, %s" % (resp.status, result)
else:
... | def resp_json(resp) | Get JSON from response if success, raise requests.HTTPError otherwise.
Args:
resp: requests.Response or flask.Response
Retuens:
JSON value | 2.692371 | 2.64219 | 1.018992 |
i = action.find("_")
if i < 0:
url = "/" + resource
httpmethod = action
else:
url = "/%s/%s" % (resource, action[i + 1:])
httpmethod = action[:i]
return url, httpmethod.upper() | def res_to_url(resource, action) | Convert resource.action to (url, HTTP_METHOD) | 3.301974 | 2.533127 | 1.303517 |
params = {
"method": method,
"url": self.url_prefix + url,
"headers": headers
}
if data is not None:
if method in ["GET", "DELETE"]:
params["params"] = data
elif method in ["POST", "PUT", "PATCH"]:
... | def ajax(self, url, method="GET", data=None, headers=None) | Send request | 2.287962 | 2.247945 | 1.017801 |
url, httpmethod = res_to_url(resource, action)
return self.ajax(url, httpmethod, data, headers) | def _request(self, resource, action, data=None, headers=None) | Send request
Args:
resource: resource
action: action
data: string or object which can be json.dumps
headers: http headers | 7.502103 | 9.754921 | 0.769058 |
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
... | def create_event(data) | Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object | 2.858597 | 2.870653 | 0.9958 |
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message) | def send_events(self, events) | Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann | 5.248407 | 5.039413 | 1.041472 |
return self.send_events(self.create_event(e) for e in events) | def events(self, *events) | Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann | 7.342027 | 8.44879 | 0.869003 |
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
... | def create_dict(event) | Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes | 3.538532 | 3.196718 | 1.106927 |
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message) | def send_query(self, query) | Sends a query to the Riemann server
:returns: The response message from Riemann | 8.519234 | 7.208981 | 1.181753 |
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events] | def query(self, query) | Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport` | 6.519006 | 4.413791 | 1.476963 |
for event in events:
self.queue.events.add().MergeFrom(event)
return None | def send_events(self, events) | Adds multiple events to the queued message
:returns: None - nothing has been sent to the Riemann server yet | 13.505713 | 11.847777 | 1.139936 |
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname'] | def GetValidHostsForCert(cert) | Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs. | 2.381033 | 2.633282 | 0.904207 |
hosts = GetValidHostsForCert(cert)
boto.log.debug(
"validating server certificate: hostname=%s, certificate hosts=%s",
hostname, hosts)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return Fa... | def ValidateCertificateHostname(cert, hostname) | Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate. | 4.288594 | 4.809715 | 0.891652 |
"Connect to a host on a given (SSL) port."
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
boto.log.debug("wrapping ssl socket; CA certificate file=%s",
self.ca_certs)
self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
... | def connect(self) | Connect to a host on a given (SSL) port. | 3.379918 | 3.107295 | 1.087736 |
def got_canonical_user_id(rs):
if callable(callback):
callback(rs.ID)
self.get_all_buckets(headers=headers, callback=got_canonical_user_id) | def get_canonical_user_id(self, headers=None, callback=None) | Convenience method that returns the "CanonicalUserID" of the
user who's credentials are associated with the connection.
The only way to get this value is to do a GET request on the
service which returns all buckets associated with the account.
As part of that response, the canonical user... | 6.132255 | 5.552825 | 1.104349 |
if end is TOP:
try:
self.cards += cards
except:
self.cards += [cards]
elif end is BOTTOM:
try:
self.cards.extendleft(cards)
except:
self.cards.extendleft([cards]) | def add(self, cards, end=TOP) | Adds the given list of ``Card`` instances to the top of the stack.
:arg cards:
The cards to add to the ``Stack``. Can be a single ``Card``
instance, or a ``list`` of cards.
:arg str end:
The end of the ``Stack`` to add the cards to. Can be ``TOP`` ("top")
... | 2.343535 | 2.707204 | 0.865666 |
ends = {TOP: self.cards.pop, BOTTOM: self.cards.popleft}
self_size = self.size
if num <= self_size:
dealt_cards = [None] * num
else:
num = self_size
dealt_cards = [None] * self_size
if self_size:
for n in xrange(num):
... | def deal(self, num=1, end=TOP) | Returns a list of cards, which are removed from the Stack.
:arg int num:
The number of cards to deal.
:arg str end:
Which end to deal from. Can be ``0`` (top) or ``1`` (bottom).
:returns:
The given number of cards from the stack. | 3.174466 | 3.445771 | 0.921265 |
cards = list(self.cards)
self.cards = []
if return_cards:
return cards | def empty(self, return_cards=False) | Empties the stack, removing all cards from it, and returns them.
:arg bool return_cards:
Whether or not to return the cards.
:returns:
If ``return_cards=True``, a list containing the cards removed
from the Stack. | 3.948732 | 7.669254 | 0.514878 |
ranks = ranks or self.ranks
found_indices = []
count = 0
if not limit:
for i, card in enumerate(self.cards):
if check_term(card, term):
found_indices.append(i)
else:
for i, card in enumerate(self.cards):
... | def find(self, term, limit=0, sort=False, ranks=None) | Searches the stack for cards with a value, suit, name, or
abbreviation matching the given argument, 'term'.
:arg str term:
The search term. Can be a card full name, value, suit,
or abbreviation.
:arg int limit:
The number of items to retrieve for each term. `... | 2.20716 | 2.423391 | 0.910773 |
ranks = ranks or self.ranks
got_cards = []
try:
indices = self.find(term, limit=limit)
got_cards = [self.cards[i] for i in indices]
self.cards = [v for i, v in enumerate(self.cards) if
i not in indices]
except:
got... | def get(self, term, limit=0, sort=False, ranks=None) | Get the specified card from the stack.
:arg term:
The search term. Can be a card full name, value, suit,
abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term.
:arg bool sort:
Whether or not to sort the resul... | 2.986346 | 3.113825 | 0.95906 |
ranks = ranks or self.ranks
got_cards = []
try:
indices = self.find_list(terms, limit=limit)
got_cards = [self.cards[i] for i in indices if self.cards[i]
not in got_cards]
self.cards = [v for i, v in enumerate(self.cards) if
... | def get_list(self, terms, limit=0, sort=False, ranks=None) | Get the specified cards from the stack.
:arg term:
The search term. Can be a card full name, value, suit,
abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term.
:arg bool sort:
Whether or not to sort the resu... | 2.25228 | 2.331195 | 0.966148 |
self_size = len(self.cards)
if indice in [0, -1]:
if indice == -1:
self.cards.append(card)
else:
self.cards.appendleft(card)
elif indice != self_size:
half_x, half_y = self.split(indice)
self.cards = list(h... | def insert(self, card, indice=-1) | Insert a given card into the stack at a given indice.
:arg Card card:
The card to insert into the stack.
:arg int indice:
Where to insert the given card. | 3.116788 | 3.28174 | 0.949736 |
self_size = len(self.cards)
if indice in [0, -1]:
if indice == -1:
self.cards += cards
else:
self.cards.extendleft(cards)
elif indice != self_size:
half_x, half_y = self.split(indice)
self.cards = list(half... | def insert_list(self, cards, indice=-1) | Insert a list of given cards into the stack at a given indice.
:arg list cards:
The list of cards to insert into the stack.
:arg int indice:
Where to insert the given cards. | 3.295173 | 3.539318 | 0.931019 |
ranks = ranks or self.ranks
return check_sorted(self, ranks) | def is_sorted(self, ranks=None) | Checks whether the stack is sorted.
:arg dict ranks:
The rank dict to reference for checking. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
Whether or not the cards are sorted. | 7.81159 | 22.137676 | 0.352864 |
for _ in xrange(times):
random.shuffle(self.cards) | def shuffle(self, times=1) | Shuffles the Stack.
.. note::
Shuffling large numbers of cards (100,000+) may take a while.
:arg int times:
The number of times to shuffle. | 5.298528 | 8.467453 | 0.625752 |
ranks = ranks or self.ranks
self.cards = sort_cards(self.cards, ranks) | def sort(self, ranks=None) | Sorts the stack, either by poker ranks, or big two ranks.
:arg dict ranks:
The rank dict to reference for sorting. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
The sorted cards. | 5.420156 | 10.16113 | 0.533421 |
self_size = self.size
if self_size > 1:
if not indice:
mid = self_size // 2
return Stack(cards=self[0:mid]), Stack(cards=self[mid::])
else:
return Stack(cards=self[0:indice]), Stack(cards=self[indice::])
else:
... | def split(self, indice=None) | Splits the Stack, either in half, or at the given indice, into two
separate Stacks.
:arg int indice:
Optional. The indice to split the Stack at. Defaults to the middle
of the ``Stack``.
:returns:
The two parts of the Stack, as separate Stack instances. | 2.894361 | 2.697243 | 1.073081 |
if error is None:
flask_abort(code)
elif isinstance(error, Response):
error.status_code = code
flask_abort(code, response=error)
else:
body = {
"status": code,
"error": error,
"message": message
}
flask_abort(code, resp... | def abort(code, error=None, message=None) | Abort with suitable error response
Args:
code (int): status code
error (str): error symbol or flask.Response
message (str): error message | 3.156021 | 3.335071 | 0.946313 |
status = headers = None
if isinstance(rv, tuple):
rv, status, headers = rv + (None,) * (3 - len(rv))
if isinstance(status, (dict, list)):
headers, status = status, headers
return (rv, status, headers) | def unpack(rv) | Convert rv to tuple(data, code, headers)
Args:
rv: data or tuple that contain code and headers
Returns:
tuple (rv, status, headers) | 3.545737 | 2.942828 | 1.204874 |
if isinstance(rv, ResponseBase):
return make_response(rv, code, headers)
else:
if code is None:
code = 200
mediatype = request.accept_mimetypes.best_match(
exporters.keys(), default='application/json')
return exporters[mediatype](rv, code, headers) | def export(rv, code=None, headers=None) | Create a suitable response
Args:
rv: return value of action
code: status code
headers: response headers
Returns:
flask.Response | 3.096302 | 3.420654 | 0.905178 |
if docs is None:
return {}
indexs = []
for mark in marks:
i = docs.find(mark)
if i >= 0:
indexs.append(i)
if not indexs:
return {"$desc": textwrap.dedent(docs).strip()}
start = min(indexs)
start = docs.rfind("\n", 0, start)
yamltext = textwrap... | def parse_docs(docs, marks) | Parse YAML syntax content from docs
If docs is None, return {}
If docs has no YAML content, return {"$desc": docs}
Else, parse YAML content, return {"$desc": docs, YAML}
Args:
docs (str): docs to be parsed
marks (list): list of which indicate YAML content starts
Returns:
A ... | 3.338112 | 2.651068 | 1.259158 |
method = request.method.lower()
if method in ["get", "delete"]:
return request.args
elif method in ["post", "put", "patch"]:
if request.mimetype == 'application/json':
try:
return request.get_json()
except:
abort(400, "InvalidData"... | def get_request_data() | Get request data based on request.method
If method is GET or DELETE, get data from request.args
If method is POST, PATCH or PUT, get data from request.form or request.json | 2.638836 | 2.540564 | 1.038681 |
find = None
if request.endpoint is not None:
find = PATTERN_ENDPOINT.findall(request.endpoint)
if not find:
raise ValueError("invalid endpoint %s" % request.endpoint)
__, resource, action_name = find[0]
if action_name:
action = request.method.lower() + "_" + action_name
... | def parse_request() | Parse request endpoint and return (resource, action) | 3.602161 | 3.045861 | 1.182641 |
if not desc:
return default
lines = desc.strip('\n').split('\n')
if not lines:
return default
return lines[0].lstrip('# ').rstrip(' ') | def get_title(desc, default=None) | Get title of desc | 3.599583 | 3.322415 | 1.083424 |
# API_URL_PREFIX maybe diffierent in development and production,
# so pick it from app.config other than store it in metafile
self.meta["$url_prefix"] = current_app.config.get("API_URL_PREFIX", "")
mediatype = request.accept_mimetypes.best_match(
['text/html', 'appli... | def meta_view(self) | Meta data / API document
By default, this view func will return API document(HTML),
you can set request header `Accept` to `application/json`
or set query string `json` to get meta data(JSON). | 3.948584 | 3.907243 | 1.010581 |
name = resource.__name__.lower()
meta_resource = parse_docs(resource.__doc__, ["$shared"])
self.meta[name] = meta_resource
shared = self.meta["$shared"].copy()
shared.update(meta_resource.get("$shared", {}))
with MarkKey("%s.$shared" % resource.__name__):
... | def add_resource(self, resource, *class_args, **class_kwargs) | Add resource
Parse resource and it's actions, route actions by naming rule.
Args:
resource: resource class
class_args: class_args
class_kwargs: class_kwargs | 3.592221 | 3.608279 | 0.995549 |
validate_input = validate_output = None
if "$input" in meta:
with MarkKey("$input"):
validate_input = schema_parser.parse(meta["$input"])
if "$output" in meta:
with MarkKey("$output"):
validate_output = schema_parser.parse(meta["$o... | def make_action(self, fn, schema_parser, meta) | Make resource's method an action
Validate input, output by schema in meta.
If no input schema, call fn without params.
If no output schema, will not validate return value.
Args:
fn: resource's method
schema_parser: for parsing schema in meta
meta: me... | 2.515049 | 2.527375 | 0.995123 |
def view(*args, **kwargs):
try:
httpmathod = request.method.lower()
if httpmathod not in action_group:
abort(405)
resp = self._before_request()
if resp is None:
fn = action_group[httpmath... | def make_view(self, action_group) | Create a view function
Check permission and Dispatch request to action by request.method | 5.257356 | 4.547943 | 1.155985 |
resource, action = parse_request()
roles = self.meta.get("$roles", {})
message = "%s can't access %s.%s" % (role, resource, action)
try:
if action not in roles[role][resource]:
abort(403, "PermissionDeny", message)
except KeyError:
... | def authorize(self, role) | Check permission | 4.698143 | 4.526093 | 1.038013 |
return [RegionInfo(name='us-east-1',
endpoint='sns.us-east-1.amazonaws.com',
connection_cls=SNSConnection),
RegionInfo(name='eu-west-1',
endpoint='sns.eu-west-1.amazonaws.com',
connection_cls=SNSConnection),... | def regions() | Get all available regions for the SNS service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo` instances | 1.422124 | 1.345184 | 1.057197 |
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None | def connect_to_region(region_name, **kw_params) | Given a valid region name, return a
:class:`boto.sns.connection.SNSConnection`.
:type: str
:param region_name: The name of the region to connect to.
:rtype: :class:`boto.sns.connection.SNSConnection` or ``None``
:return: A connection to the given region, or None if an invalid region
... | 3.252275 | 4.379912 | 0.742544 |
for region in regions(**kw_params):
if region.name == region_name:
return region
return None | def get_region(region_name, **kw_params) | Find and return a :class:`boto.regioninfo.RegionInfo` object
given a region name.
:type: str
:param: The name of the region.
:rtype: :class:`boto.regioninfo.RegionInfo`
:return: The RegionInfo object for the given region or None if
an invalid region name is provided. | 3.657874 | 5.507575 | 0.664153 |
status = self.connection.create_tags([self.id], {key : value})
if self.tags is None:
self.tags = TagSet()
self.tags[key] = value | def add_tag(self, key, value='') | Add a tag to this object. Tag's are stored by AWS and can be used
to organize and filter resources. Adding a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional va... | 4.490438 | 5.349237 | 0.839454 |
if value:
tags = {key : value}
else:
tags = [key]
status = self.connection.delete_tags([self.id], tags)
if key in self.tags:
del self.tags[key] | def remove_tag(self, key, value=None) | Remove a tag from this object. Removing a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional value that can be stored with the tag.
If a value is pro... | 3.737188 | 4.915915 | 0.760222 |
"Returns a list of values, eats all of data."
seq = []
while data:
elem, data = self.spec.read(frame, data)
seq.append(elem)
return seq, data | def read(self, frame, data) | Returns a list of values, eats all of data. | 8.427091 | 4.116853 | 2.046974 |
assert self.connection != None
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version
for p in self.paths:
s += ' <Path>%s</Path>\n' % self.escape(p)
s += ' <... | def to_xml(self) | Get this batch as XML | 2.856804 | 2.679175 | 1.0663 |
return self.connection.get_queue_attributes(self, attributes, callback=callback) | def get_attributes(self, attributes='All', callback=None) | Retrieves attributes about this queue object and returns
them in an Attribute instance (subclass of a Dictionary).
:type attributes: string
:param attributes: String containing one of:
ApproximateNumberOfMessages,
ApproximateNumberOfMessages... | 7.050801 | 8.518391 | 0.827715 |
return self.connection.set_queue_attribute(self, attribute, value, callback=callback) | def set_attribute(self, attribute, value, callback=None) | Set a new value for an attribute of the Queue.
:type attribute: String
:param attribute: The name of the attribute you want to set. The
only valid value at this time is: VisibilityTimeout
:type value: int
:param value: The new value for the attribute.... | 5.518505 | 5.463923 | 1.009989 |
def got_timeout(a):
if callable(callback):
callback(int(a['VisibilityTimeout']))
self.get_attributes('VisibilityTimeout', callback=got_timeout) | def get_timeout(self, callback=None) | Get the visibility timeout for the queue.
:rtype: int
:return: The number of seconds as an integer. | 8.599205 | 7.523846 | 1.142927 |
def _set_timeout(retval):
if retval:
self.visibility_timeout = visibility_timeout
if callable(callback):
callback(retval)
retval = self.set_attribute('VisibilityTimeout', visibility_timeout, callback=_set_timeout) | def set_timeout(self, visibility_timeout, callback=None) | Set the visibility timeout for the queue.
:type visibility_timeout: int
:param visibility_timeout: The desired timeout in seconds | 3.883319 | 4.904583 | 0.791773 |
return self.connection.add_permission(self, label, aws_account_id, action_name, callback=callback) | def add_permission(self, label, aws_account_id, action_name, callback=None) | Add a permission to a queue.
:type label: str or unicode
:param label: A unique identification of the permission you are setting.
Maximum of 80 characters ``[0-9a-zA-Z_-]``
Example, AliceSendMessage
:type aws_account_id: str or unicode
:param... | 2.88101 | 3.50662 | 0.821592 |
return self.connection.remove_permission(self, label, callback=callback) | def remove_permission(self, label, callback=None) | Remove a permission from a queue.
:type label: str or unicode
:param label: The unique label associated with the permission being removed.
:rtype: bool
:return: True if successful, False otherwise. | 5.426976 | 7.144437 | 0.759609 |
def _read(rs):
if callable(callback):
callback(rs[0] if len(rs) == 1 else None)
self.get_messages(1, visibility_timeout, callback=callback) | def read(self, visibility_timeout=None, callback=None) | Read a single message from the queue.
:type visibility_timeout: int
:param visibility_timeout: The timeout for this message in seconds
:rtype: :class:`boto.sqs.message.Message`
:return: A single message or None if queue is empty | 6.313116 | 6.965047 | 0.9064 |
def wrote(new_msg):
message.id = new_msg.id
message.md5 = new_msg.md5
if callable(callback):
callback(message)
self.connection.send_message(self, message.get_body_encoded(), callback=wrote) | def write(self, message, callback=None) | Add a single message to the queue.
:type message: Message
:param message: The message to be written to the queue
:rtype: :class:`boto.sqs.message.Message`
:return: The :class:`boto.sqs.message.Message` object that was written. | 5.400496 | 4.851723 | 1.113109 |
return self.connection.receive_message(self, number_messages=num_messages,
visibility_timeout=visibility_timeout,
attributes=attributes, callback=callback) | def get_messages(self, num_messages=1, visibility_timeout=None,
attributes=None, callback=None) | Get a variable number of messages.
:type num_messages: int
:param num_messages: The maximum number of messages to read from the queue.
:type visibility_timeout: int
:param visibility_timeout: The VisibilityTimeout for the messages read.
:type attributes: str
:p... | 3.03134 | 4.277709 | 0.708636 |
return self.connection.delete_message(self, message, callback=callback) | def delete_message(self, message, callback=None) | Delete a message from the queue.
:type message: :class:`boto.sqs.message.Message`
:param message: The :class:`boto.sqs.message.Message` object to delete.
:rtype: bool
:return: True if successful, False otherwise | 4.790841 | 7.881062 | 0.607893 |
def counted(a):
if callable(callback):
callback(int(a['ApproximateNumberOfMessages']))
self.get_attributes('ApproximateNumberOfMessages', callback=counted) | def count(self, page_size=10, vtimeout=10, callback=None) | Utility function to count the number of messages in a queue.
Note: This function now calls GetQueueAttributes to obtain
an 'approximate' count of the number of messages in a queue. | 7.452052 | 5.702823 | 1.30673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.