repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
mrcagney/gtfstk
gtfstk/feed.py
Feed.trips
def trips(self, val): """ Update ``self._trips_i`` if ``self.trips`` changes. """ self._trips = val if val is not None and not val.empty: self._trips_i = self._trips.set_index("trip_id") else: self._trips_i = None
python
def trips(self, val): """ Update ``self._trips_i`` if ``self.trips`` changes. """ self._trips = val if val is not None and not val.empty: self._trips_i = self._trips.set_index("trip_id") else: self._trips_i = None
[ "def", "trips", "(", "self", ",", "val", ")", ":", "self", ".", "_trips", "=", "val", "if", "val", "is", "not", "None", "and", "not", "val", ".", "empty", ":", "self", ".", "_trips_i", "=", "self", ".", "_trips", ".", "set_index", "(", "\"trip_id\"...
Update ``self._trips_i`` if ``self.trips`` changes.
[ "Update", "self", ".", "_trips_i", "if", "self", ".", "trips", "changes", "." ]
c91494e6fefc02523889655a0dc92d1c0eee8d03
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/feed.py#L225-L233
train
30,500
mrcagney/gtfstk
gtfstk/feed.py
Feed.calendar
def calendar(self, val): """ Update ``self._calendar_i``if ``self.calendar`` changes. """ self._calendar = val if val is not None and not val.empty: self._calendar_i = self._calendar.set_index("service_id") else: self._calendar_i = None
python
def calendar(self, val): """ Update ``self._calendar_i``if ``self.calendar`` changes. """ self._calendar = val if val is not None and not val.empty: self._calendar_i = self._calendar.set_index("service_id") else: self._calendar_i = None
[ "def", "calendar", "(", "self", ",", "val", ")", ":", "self", ".", "_calendar", "=", "val", "if", "val", "is", "not", "None", "and", "not", "val", ".", "empty", ":", "self", ".", "_calendar_i", "=", "self", ".", "_calendar", ".", "set_index", "(", ...
Update ``self._calendar_i``if ``self.calendar`` changes.
[ "Update", "self", ".", "_calendar_i", "if", "self", ".", "calendar", "changes", "." ]
c91494e6fefc02523889655a0dc92d1c0eee8d03
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/feed.py#L243-L251
train
30,501
mrcagney/gtfstk
gtfstk/feed.py
Feed.calendar_dates
def calendar_dates(self, val): """ Update ``self._calendar_dates_g`` if ``self.calendar_dates`` changes. """ self._calendar_dates = val if val is not None and not val.empty: self._calendar_dates_g = self._calendar_dates.groupby( ["service_id", "date"] ) else: self._calendar_dates_g = None
python
def calendar_dates(self, val): """ Update ``self._calendar_dates_g`` if ``self.calendar_dates`` changes. """ self._calendar_dates = val if val is not None and not val.empty: self._calendar_dates_g = self._calendar_dates.groupby( ["service_id", "date"] ) else: self._calendar_dates_g = None
[ "def", "calendar_dates", "(", "self", ",", "val", ")", ":", "self", ".", "_calendar_dates", "=", "val", "if", "val", "is", "not", "None", "and", "not", "val", ".", "empty", ":", "self", ".", "_calendar_dates_g", "=", "self", ".", "_calendar_dates", ".", ...
Update ``self._calendar_dates_g`` if ``self.calendar_dates`` changes.
[ "Update", "self", ".", "_calendar_dates_g", "if", "self", ".", "calendar_dates", "changes", "." ]
c91494e6fefc02523889655a0dc92d1c0eee8d03
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/feed.py#L261-L272
train
30,502
mrcagney/gtfstk
gtfstk/feed.py
Feed.copy
def copy(self) -> "Feed": """ Return a copy of this feed, that is, a feed with all the same attributes. """ other = Feed(dist_units=self.dist_units) for key in set(cs.FEED_ATTRS) - set(["dist_units"]): value = getattr(self, key) if isinstance(value, pd.DataFrame): # Pandas copy DataFrame value = value.copy() elif isinstance(value, pd.core.groupby.DataFrameGroupBy): # Pandas does not have a copy method for groupby objects # as far as i know value = deepcopy(value) setattr(other, key, value) return other
python
def copy(self) -> "Feed": """ Return a copy of this feed, that is, a feed with all the same attributes. """ other = Feed(dist_units=self.dist_units) for key in set(cs.FEED_ATTRS) - set(["dist_units"]): value = getattr(self, key) if isinstance(value, pd.DataFrame): # Pandas copy DataFrame value = value.copy() elif isinstance(value, pd.core.groupby.DataFrameGroupBy): # Pandas does not have a copy method for groupby objects # as far as i know value = deepcopy(value) setattr(other, key, value) return other
[ "def", "copy", "(", "self", ")", "->", "\"Feed\"", ":", "other", "=", "Feed", "(", "dist_units", "=", "self", ".", "dist_units", ")", "for", "key", "in", "set", "(", "cs", ".", "FEED_ATTRS", ")", "-", "set", "(", "[", "\"dist_units\"", "]", ")", ":...
Return a copy of this feed, that is, a feed with all the same attributes.
[ "Return", "a", "copy", "of", "this", "feed", "that", "is", "a", "feed", "with", "all", "the", "same", "attributes", "." ]
c91494e6fefc02523889655a0dc92d1c0eee8d03
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/feed.py#L316-L333
train
30,503
5monkeys/djedi-cms
djedi/backends/django/cache/backend.py
DjangoCacheBackend._encode_content
def _encode_content(self, uri, content): """ Join node uri and content as string and convert to bytes to ensure no pickling in memcached. """ if content is None: content = self.NONE return smart_str('|'.join([six.text_type(uri), content]))
python
def _encode_content(self, uri, content): """ Join node uri and content as string and convert to bytes to ensure no pickling in memcached. """ if content is None: content = self.NONE return smart_str('|'.join([six.text_type(uri), content]))
[ "def", "_encode_content", "(", "self", ",", "uri", ",", "content", ")", ":", "if", "content", "is", "None", ":", "content", "=", "self", ".", "NONE", "return", "smart_str", "(", "'|'", ".", "join", "(", "[", "six", ".", "text_type", "(", "uri", ")", ...
Join node uri and content as string and convert to bytes to ensure no pickling in memcached.
[ "Join", "node", "uri", "and", "content", "as", "string", "and", "convert", "to", "bytes", "to", "ensure", "no", "pickling", "in", "memcached", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/backends/django/cache/backend.py#L47-L53
train
30,504
5monkeys/djedi-cms
djedi/backends/django/cache/backend.py
DjangoCacheBackend._decode_content
def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ content = smart_unicode(content) uri, _, content = content.partition(u'|') if content == self.NONE: content = None return uri or None, content
python
def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ content = smart_unicode(content) uri, _, content = content.partition(u'|') if content == self.NONE: content = None return uri or None, content
[ "def", "_decode_content", "(", "self", ",", "content", ")", ":", "content", "=", "smart_unicode", "(", "content", ")", "uri", ",", "_", ",", "content", "=", "content", ".", "partition", "(", "u'|'", ")", "if", "content", "==", "self", ".", "NONE", ":",...
Split node string to uri and content and convert back to unicode.
[ "Split", "node", "string", "to", "uri", "and", "content", "and", "convert", "back", "to", "unicode", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/backends/django/cache/backend.py#L55-L63
train
30,505
5monkeys/djedi-cms
djedi/templatetags/djedi_tags.py
render_node
def render_node(node, context=None, edit=True): """ Render node as html for templates, with edit tagging. """ output = node.render(**context or {}) or u'' if edit: return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(scheme=None, ext=None, version=None), output) else: return output
python
def render_node(node, context=None, edit=True): """ Render node as html for templates, with edit tagging. """ output = node.render(**context or {}) or u'' if edit: return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(scheme=None, ext=None, version=None), output) else: return output
[ "def", "render_node", "(", "node", ",", "context", "=", "None", ",", "edit", "=", "True", ")", ":", "output", "=", "node", ".", "render", "(", "*", "*", "context", "or", "{", "}", ")", "or", "u''", "if", "edit", ":", "return", "u'<span data-i18n=\"{0...
Render node as html for templates, with edit tagging.
[ "Render", "node", "as", "html", "for", "templates", "with", "edit", "tagging", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/templatetags/djedi_tags.py#L10-L18
train
30,506
5monkeys/djedi-cms
djedi/admin/api.py
APIView.get_post_data
def get_post_data(self, request): """ Collect and merge post parameters with multipart files. """ params = dict(request.POST) params.update(request.FILES) data = defaultdict(dict) # Split data and meta parameters for param in sorted(params.keys()): value = params[param] if isinstance(value, list) and len(value) <= 1: value = value[0] if value else None prefix, _, field = param.partition('[') if field: field = field[:-1] try: data[prefix][field] = value except TypeError: raise InvalidNodeData('Got both reserved parameter "data" and plugin specific parameters.') else: data[prefix] = value return data['data'], data['meta']
python
def get_post_data(self, request): """ Collect and merge post parameters with multipart files. """ params = dict(request.POST) params.update(request.FILES) data = defaultdict(dict) # Split data and meta parameters for param in sorted(params.keys()): value = params[param] if isinstance(value, list) and len(value) <= 1: value = value[0] if value else None prefix, _, field = param.partition('[') if field: field = field[:-1] try: data[prefix][field] = value except TypeError: raise InvalidNodeData('Got both reserved parameter "data" and plugin specific parameters.') else: data[prefix] = value return data['data'], data['meta']
[ "def", "get_post_data", "(", "self", ",", "request", ")", ":", "params", "=", "dict", "(", "request", ".", "POST", ")", "params", ".", "update", "(", "request", ".", "FILES", ")", "data", "=", "defaultdict", "(", "dict", ")", "# Split data and meta paramet...
Collect and merge post parameters with multipart files.
[ "Collect", "and", "merge", "post", "parameters", "with", "multipart", "files", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L35-L61
train
30,507
5monkeys/djedi-cms
djedi/admin/api.py
NodeApi.get
def get(self, request, uri): """ Return published node or specified version. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.get(uri, lazy=False) if node.content is None: raise Http404 return self.render_to_json({ 'uri': node.uri, 'content': node.content })
python
def get(self, request, uri): """ Return published node or specified version. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.get(uri, lazy=False) if node.content is None: raise Http404 return self.render_to_json({ 'uri': node.uri, 'content': node.content })
[ "def", "get", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "node", "=", "cio", ".", "get", "(", "uri", ",", "lazy", "=", "False", ")", "if", "node", ".", "content", "is", "None", ":"...
Return published node or specified version. JSON Response: {uri: x, content: y}
[ "Return", "published", "node", "or", "specified", "version", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L79-L95
train
30,508
5monkeys/djedi-cms
djedi/admin/api.py
NodeApi.post
def post(self, request, uri): """ Set node data for uri, return rendered content. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) data, meta = self.get_post_data(request) meta['author'] = auth.get_username(request) node = cio.set(uri, data, publish=False, **meta) return self.render_to_json(node)
python
def post(self, request, uri): """ Set node data for uri, return rendered content. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) data, meta = self.get_post_data(request) meta['author'] = auth.get_username(request) node = cio.set(uri, data, publish=False, **meta) return self.render_to_json(node)
[ "def", "post", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "data", ",", "meta", "=", "self", ".", "get_post_data", "(", "request", ")", "meta", "[", "'author'", "]", "=", "auth", ".", ...
Set node data for uri, return rendered content. JSON Response: {uri: x, content: y}
[ "Set", "node", "data", "for", "uri", "return", "rendered", "content", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L97-L108
train
30,509
5monkeys/djedi-cms
djedi/admin/api.py
NodeApi.delete
def delete(self, request, uri): """ Delete versioned uri and return empty text response on success. """ uri = self.decode_uri(uri) uris = cio.delete(uri) if uri not in uris: raise Http404 return self.render_to_response()
python
def delete(self, request, uri): """ Delete versioned uri and return empty text response on success. """ uri = self.decode_uri(uri) uris = cio.delete(uri) if uri not in uris: raise Http404 return self.render_to_response()
[ "def", "delete", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "uris", "=", "cio", ".", "delete", "(", "uri", ")", "if", "uri", "not", "in", "uris", ":", "raise", "Http404", "return", "...
Delete versioned uri and return empty text response on success.
[ "Delete", "versioned", "uri", "and", "return", "empty", "text", "response", "on", "success", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L110-L120
train
30,510
5monkeys/djedi-cms
djedi/admin/api.py
PublishApi.put
def put(self, request, uri): """ Publish versioned uri. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.publish(uri) if not node: raise Http404 return self.render_to_json(node)
python
def put(self, request, uri): """ Publish versioned uri. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.publish(uri) if not node: raise Http404 return self.render_to_json(node)
[ "def", "put", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "node", "=", "cio", ".", "publish", "(", "uri", ")", "if", "not", "node", ":", "raise", "Http404", "return", "self", ".", "re...
Publish versioned uri. JSON Response: {uri: x, content: y}
[ "Publish", "versioned", "uri", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L125-L138
train
30,511
5monkeys/djedi-cms
djedi/admin/api.py
RevisionsApi.get
def get(self, request, uri): """ List uri revisions. JSON Response: [[uri, state], ...] """ uri = self.decode_uri(uri) revisions = cio.revisions(uri) revisions = [list(revision) for revision in revisions] # Convert tuples to lists return self.render_to_json(revisions)
python
def get(self, request, uri): """ List uri revisions. JSON Response: [[uri, state], ...] """ uri = self.decode_uri(uri) revisions = cio.revisions(uri) revisions = [list(revision) for revision in revisions] # Convert tuples to lists return self.render_to_json(revisions)
[ "def", "get", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "revisions", "=", "cio", ".", "revisions", "(", "uri", ")", "revisions", "=", "[", "list", "(", "revision", ")", "for", "revisi...
List uri revisions. JSON Response: [[uri, state], ...]
[ "List", "uri", "revisions", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L143-L153
train
30,512
5monkeys/djedi-cms
djedi/admin/api.py
LoadApi.get
def get(self, request, uri): """ Load raw node source from storage. JSON Response: {uri: x, data: y} """ uri = self.decode_uri(uri) node = cio.load(uri) return self.render_to_json(node)
python
def get(self, request, uri): """ Load raw node source from storage. JSON Response: {uri: x, data: y} """ uri = self.decode_uri(uri) node = cio.load(uri) return self.render_to_json(node)
[ "def", "get", "(", "self", ",", "request", ",", "uri", ")", ":", "uri", "=", "self", ".", "decode_uri", "(", "uri", ")", "node", "=", "cio", ".", "load", "(", "uri", ")", "return", "self", ".", "render_to_json", "(", "node", ")" ]
Load raw node source from storage. JSON Response: {uri: x, data: y}
[ "Load", "raw", "node", "source", "from", "storage", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L159-L168
train
30,513
5monkeys/djedi-cms
djedi/admin/api.py
RenderApi.post
def post(self, request, ext): """ Render data for plugin and return text response. """ try: plugin = plugins.get(ext) data, meta = self.get_post_data(request) data = plugin.load(data) except UnknownPlugin: raise Http404 else: content = plugin.render(data) return self.render_to_response(content)
python
def post(self, request, ext): """ Render data for plugin and return text response. """ try: plugin = plugins.get(ext) data, meta = self.get_post_data(request) data = plugin.load(data) except UnknownPlugin: raise Http404 else: content = plugin.render(data) return self.render_to_response(content)
[ "def", "post", "(", "self", ",", "request", ",", "ext", ")", ":", "try", ":", "plugin", "=", "plugins", ".", "get", "(", "ext", ")", "data", ",", "meta", "=", "self", ".", "get_post_data", "(", "request", ")", "data", "=", "plugin", ".", "load", ...
Render data for plugin and return text response.
[ "Render", "data", "for", "plugin", "and", "return", "text", "response", "." ]
3c077edfda310717b9cdb4f2ee14e78723c94894
https://github.com/5monkeys/djedi-cms/blob/3c077edfda310717b9cdb4f2ee14e78723c94894/djedi/admin/api.py#L173-L185
train
30,514
philadams/habitica
habitica/core.py
set_checklists_status
def set_checklists_status(auth, args): """Set display_checklist status, toggling from cli flag""" global checklists_on if auth['checklists'] == "true": checklists_on = True else: checklists_on = False # reverse the config setting if specified by the CLI option if args['--checklists']: checklists_on = not checklists_on return
python
def set_checklists_status(auth, args): """Set display_checklist status, toggling from cli flag""" global checklists_on if auth['checklists'] == "true": checklists_on = True else: checklists_on = False # reverse the config setting if specified by the CLI option if args['--checklists']: checklists_on = not checklists_on return
[ "def", "set_checklists_status", "(", "auth", ",", "args", ")", ":", "global", "checklists_on", "if", "auth", "[", "'checklists'", "]", "==", "\"true\"", ":", "checklists_on", "=", "True", "else", ":", "checklists_on", "=", "False", "# reverse the config setting if...
Set display_checklist status, toggling from cli flag
[ "Set", "display_checklist", "status", "toggling", "from", "cli", "flag" ]
3f2d26300c1320c3fe0b621cf7ecbc85eccdfc85
https://github.com/philadams/habitica/blob/3f2d26300c1320c3fe0b621cf7ecbc85eccdfc85/habitica/core.py#L190-L203
train
30,515
rackerlabs/fleece
fleece/handlers/wsgi.py
build_wsgi_environ_from_event
def build_wsgi_environ_from_event(event): """Create a WSGI environment from the proxy integration event.""" params = event.get('queryStringParameters') environ = EnvironBuilder(method=event.get('httpMethod') or 'GET', path=event.get('path') or '/', headers=event.get('headers') or {}, data=event.get('body') or b'', query_string=params or {}).get_environ() environ['SERVER_PORT'] = 443 if 'execute-api' in environ['HTTP_HOST']: # this is the API-Gateway hostname, which takes the stage as the first # script path component environ['SCRIPT_NAME'] = '/' + event['requestContext'].get('stage') else: # we are using our own hostname, nothing gets added to the script path environ['SCRIPT_NAME'] = '' environ['wsgi.url_scheme'] = 'https' environ['lambda.event'] = event return environ
python
def build_wsgi_environ_from_event(event): """Create a WSGI environment from the proxy integration event.""" params = event.get('queryStringParameters') environ = EnvironBuilder(method=event.get('httpMethod') or 'GET', path=event.get('path') or '/', headers=event.get('headers') or {}, data=event.get('body') or b'', query_string=params or {}).get_environ() environ['SERVER_PORT'] = 443 if 'execute-api' in environ['HTTP_HOST']: # this is the API-Gateway hostname, which takes the stage as the first # script path component environ['SCRIPT_NAME'] = '/' + event['requestContext'].get('stage') else: # we are using our own hostname, nothing gets added to the script path environ['SCRIPT_NAME'] = '' environ['wsgi.url_scheme'] = 'https' environ['lambda.event'] = event return environ
[ "def", "build_wsgi_environ_from_event", "(", "event", ")", ":", "params", "=", "event", ".", "get", "(", "'queryStringParameters'", ")", "environ", "=", "EnvironBuilder", "(", "method", "=", "event", ".", "get", "(", "'httpMethod'", ")", "or", "'GET'", ",", ...
Create a WSGI environment from the proxy integration event.
[ "Create", "a", "WSGI", "environment", "from", "the", "proxy", "integration", "event", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/handlers/wsgi.py#L4-L22
train
30,516
rackerlabs/fleece
fleece/handlers/wsgi.py
wsgi_handler
def wsgi_handler(event, context, app, logger): """lambda handler function. This function runs the WSGI app with it and collects its response, then translates the response back into the format expected by the API Gateway proxy integration. """ environ = build_wsgi_environ_from_event(event) wsgi_status = [] wsgi_headers = [] logger.info('Processing {} request'.format(environ['REQUEST_METHOD'])) def start_response(status, headers): if len(wsgi_status) or len(wsgi_headers): raise RuntimeError('start_response called more than once!') wsgi_status.append(status) wsgi_headers.append(headers) resp = list(app(environ, start_response)) proxy = {'statusCode': int(wsgi_status[0].split()[0]), 'headers': {h[0]: h[1] for h in wsgi_headers[0]}, 'body': b''.join(resp).decode('utf-8')} logger.info("Returning {}".format(proxy['statusCode']), http_status=proxy['statusCode']) return proxy
python
def wsgi_handler(event, context, app, logger): """lambda handler function. This function runs the WSGI app with it and collects its response, then translates the response back into the format expected by the API Gateway proxy integration. """ environ = build_wsgi_environ_from_event(event) wsgi_status = [] wsgi_headers = [] logger.info('Processing {} request'.format(environ['REQUEST_METHOD'])) def start_response(status, headers): if len(wsgi_status) or len(wsgi_headers): raise RuntimeError('start_response called more than once!') wsgi_status.append(status) wsgi_headers.append(headers) resp = list(app(environ, start_response)) proxy = {'statusCode': int(wsgi_status[0].split()[0]), 'headers': {h[0]: h[1] for h in wsgi_headers[0]}, 'body': b''.join(resp).decode('utf-8')} logger.info("Returning {}".format(proxy['statusCode']), http_status=proxy['statusCode']) return proxy
[ "def", "wsgi_handler", "(", "event", ",", "context", ",", "app", ",", "logger", ")", ":", "environ", "=", "build_wsgi_environ_from_event", "(", "event", ")", "wsgi_status", "=", "[", "]", "wsgi_headers", "=", "[", "]", "logger", ".", "info", "(", "'Process...
lambda handler function. This function runs the WSGI app with it and collects its response, then translates the response back into the format expected by the API Gateway proxy integration.
[ "lambda", "handler", "function", ".", "This", "function", "runs", "the", "WSGI", "app", "with", "it", "and", "collects", "its", "response", "then", "translates", "the", "response", "back", "into", "the", "format", "expected", "by", "the", "API", "Gateway", "...
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/handlers/wsgi.py#L25-L52
train
30,517
rackerlabs/fleece
fleece/cli/run/run.py
assume_role
def assume_role(credentials, account, role): """Use FAWS provided credentials to assume defined role.""" sts = boto3.client( 'sts', aws_access_key_id=credentials['accessKeyId'], aws_secret_access_key=credentials['secretAccessKey'], aws_session_token=credentials['sessionToken'], ) resp = sts.assume_role( RoleArn='arn:aws:sts::{}:role/{}'.format(account, role), RoleSessionName='fleece_assumed_role' ) return { 'accessKeyId': resp['Credentials']['AccessKeyId'], 'secretAccessKey': resp['Credentials']['SecretAccessKey'], 'sessionToken': resp['Credentials']['SessionToken'], }
python
def assume_role(credentials, account, role): """Use FAWS provided credentials to assume defined role.""" sts = boto3.client( 'sts', aws_access_key_id=credentials['accessKeyId'], aws_secret_access_key=credentials['secretAccessKey'], aws_session_token=credentials['sessionToken'], ) resp = sts.assume_role( RoleArn='arn:aws:sts::{}:role/{}'.format(account, role), RoleSessionName='fleece_assumed_role' ) return { 'accessKeyId': resp['Credentials']['AccessKeyId'], 'secretAccessKey': resp['Credentials']['SecretAccessKey'], 'sessionToken': resp['Credentials']['SessionToken'], }
[ "def", "assume_role", "(", "credentials", ",", "account", ",", "role", ")", ":", "sts", "=", "boto3", ".", "client", "(", "'sts'", ",", "aws_access_key_id", "=", "credentials", "[", "'accessKeyId'", "]", ",", "aws_secret_access_key", "=", "credentials", "[", ...
Use FAWS provided credentials to assume defined role.
[ "Use", "FAWS", "provided", "credentials", "to", "assume", "defined", "role", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L80-L96
train
30,518
rackerlabs/fleece
fleece/cli/run/run.py
get_environment
def get_environment(config, stage): """Find default environment name in stage.""" stage_data = get_stage_data(stage, config.get('stages', {})) if not stage_data: sys.exit(NO_STAGE_DATA.format(stage)) try: return stage_data['environment'] except KeyError: sys.exit(NO_ENV_IN_STAGE.format(stage))
python
def get_environment(config, stage): """Find default environment name in stage.""" stage_data = get_stage_data(stage, config.get('stages', {})) if not stage_data: sys.exit(NO_STAGE_DATA.format(stage)) try: return stage_data['environment'] except KeyError: sys.exit(NO_ENV_IN_STAGE.format(stage))
[ "def", "get_environment", "(", "config", ",", "stage", ")", ":", "stage_data", "=", "get_stage_data", "(", "stage", ",", "config", ".", "get", "(", "'stages'", ",", "{", "}", ")", ")", "if", "not", "stage_data", ":", "sys", ".", "exit", "(", "NO_STAGE_...
Find default environment name in stage.
[ "Find", "default", "environment", "name", "in", "stage", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L109-L117
train
30,519
rackerlabs/fleece
fleece/cli/run/run.py
get_account
def get_account(config, environment, stage=None): """Find environment name in config object and return AWS account.""" if environment is None and stage: environment = get_environment(config, stage) account = None for env in config.get('environments', []): if env.get('name') == environment: account = env.get('account') role = env.get('role') username = os.environ.get(env.get('rs_username_var')) \ if env.get('rs_username_var') else None apikey = os.environ.get(env.get('rs_apikey_var')) \ if env.get('rs_apikey_var') else None if not account: sys.exit(ACCT_NOT_FOUND_ERROR.format(environment)) return account, role, username, apikey
python
def get_account(config, environment, stage=None): """Find environment name in config object and return AWS account.""" if environment is None and stage: environment = get_environment(config, stage) account = None for env in config.get('environments', []): if env.get('name') == environment: account = env.get('account') role = env.get('role') username = os.environ.get(env.get('rs_username_var')) \ if env.get('rs_username_var') else None apikey = os.environ.get(env.get('rs_apikey_var')) \ if env.get('rs_apikey_var') else None if not account: sys.exit(ACCT_NOT_FOUND_ERROR.format(environment)) return account, role, username, apikey
[ "def", "get_account", "(", "config", ",", "environment", ",", "stage", "=", "None", ")", ":", "if", "environment", "is", "None", "and", "stage", ":", "environment", "=", "get_environment", "(", "config", ",", "stage", ")", "account", "=", "None", "for", ...
Find environment name in config object and return AWS account.
[ "Find", "environment", "name", "in", "config", "object", "and", "return", "AWS", "account", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L120-L135
train
30,520
rackerlabs/fleece
fleece/cli/run/run.py
get_aws_creds
def get_aws_creds(account, tenant, token): """Get AWS account credentials to enable access to AWS. Returns a time bound set of AWS credentials. """ url = (FAWS_API_URL.format(account)) headers = { 'X-Auth-Token': token, 'X-Tenant-Id': tenant, } response = requests.post(url, headers=headers, json={'credential': {'duration': '3600'}}) if not response.ok: sys.exit(FAWS_API_ERROR.format(response.status_code, response.text)) return response.json()['credential']
python
def get_aws_creds(account, tenant, token): """Get AWS account credentials to enable access to AWS. Returns a time bound set of AWS credentials. """ url = (FAWS_API_URL.format(account)) headers = { 'X-Auth-Token': token, 'X-Tenant-Id': tenant, } response = requests.post(url, headers=headers, json={'credential': {'duration': '3600'}}) if not response.ok: sys.exit(FAWS_API_ERROR.format(response.status_code, response.text)) return response.json()['credential']
[ "def", "get_aws_creds", "(", "account", ",", "tenant", ",", "token", ")", ":", "url", "=", "(", "FAWS_API_URL", ".", "format", "(", "account", ")", ")", "headers", "=", "{", "'X-Auth-Token'", ":", "token", ",", "'X-Tenant-Id'", ":", "tenant", ",", "}", ...
Get AWS account credentials to enable access to AWS. Returns a time bound set of AWS credentials.
[ "Get", "AWS", "account", "credentials", "to", "enable", "access", "to", "AWS", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L138-L153
train
30,521
rackerlabs/fleece
fleece/cli/run/run.py
get_config
def get_config(config_file): """Get config file and parse YAML into dict.""" config_path = os.path.abspath(config_file) try: with open(config_path, 'r') as data: config = yaml.safe_load(data) except IOError as exc: sys.exit(str(exc)) return config
python
def get_config(config_file): """Get config file and parse YAML into dict.""" config_path = os.path.abspath(config_file) try: with open(config_path, 'r') as data: config = yaml.safe_load(data) except IOError as exc: sys.exit(str(exc)) return config
[ "def", "get_config", "(", "config_file", ")", ":", "config_path", "=", "os", ".", "path", ".", "abspath", "(", "config_file", ")", "try", ":", "with", "open", "(", "config_path", ",", "'r'", ")", "as", "data", ":", "config", "=", "yaml", ".", "safe_loa...
Get config file and parse YAML into dict.
[ "Get", "config", "file", "and", "parse", "YAML", "into", "dict", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L156-L166
train
30,522
rackerlabs/fleece
fleece/cli/run/run.py
get_rackspace_token
def get_rackspace_token(username, apikey): """Get Rackspace Identity token. Login to Rackspace with cloud account and api key from environment vars. Returns dict of the token and tenant id. """ auth_params = { "auth": { "RAX-KSKEY:apiKeyCredentials": { "username": username, "apiKey": apikey, } } } response = requests.post(RS_IDENTITY_URL, json=auth_params) if not response.ok: sys.exit(RS_AUTH_ERROR.format(response.status_code, response.text)) identity = response.json() return (identity['access']['token']['id'], identity['access']['token']['tenant']['id'])
python
def get_rackspace_token(username, apikey): """Get Rackspace Identity token. Login to Rackspace with cloud account and api key from environment vars. Returns dict of the token and tenant id. """ auth_params = { "auth": { "RAX-KSKEY:apiKeyCredentials": { "username": username, "apiKey": apikey, } } } response = requests.post(RS_IDENTITY_URL, json=auth_params) if not response.ok: sys.exit(RS_AUTH_ERROR.format(response.status_code, response.text)) identity = response.json() return (identity['access']['token']['id'], identity['access']['token']['tenant']['id'])
[ "def", "get_rackspace_token", "(", "username", ",", "apikey", ")", ":", "auth_params", "=", "{", "\"auth\"", ":", "{", "\"RAX-KSKEY:apiKeyCredentials\"", ":", "{", "\"username\"", ":", "username", ",", "\"apiKey\"", ":", "apikey", ",", "}", "}", "}", "response...
Get Rackspace Identity token. Login to Rackspace with cloud account and api key from environment vars. Returns dict of the token and tenant id.
[ "Get", "Rackspace", "Identity", "token", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L169-L189
train
30,523
rackerlabs/fleece
fleece/cli/run/run.py
validate_args
def validate_args(args): """Validate command-line arguments.""" if not any([args.environment, args.stage, args.account]): sys.exit(NO_ACCT_OR_ENV_ERROR) if args.environment and args.account: sys.exit(ENV_AND_ACCT_ERROR) if args.environment and args.role: sys.exit(ENV_AND_ROLE_ERROR)
python
def validate_args(args): """Validate command-line arguments.""" if not any([args.environment, args.stage, args.account]): sys.exit(NO_ACCT_OR_ENV_ERROR) if args.environment and args.account: sys.exit(ENV_AND_ACCT_ERROR) if args.environment and args.role: sys.exit(ENV_AND_ROLE_ERROR)
[ "def", "validate_args", "(", "args", ")", ":", "if", "not", "any", "(", "[", "args", ".", "environment", ",", "args", ".", "stage", ",", "args", ".", "account", "]", ")", ":", "sys", ".", "exit", "(", "NO_ACCT_OR_ENV_ERROR", ")", "if", "args", ".", ...
Validate command-line arguments.
[ "Validate", "command", "-", "line", "arguments", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L192-L199
train
30,524
rackerlabs/fleece
fleece/requests.py
set_default_timeout
def set_default_timeout(timeout=None, connect_timeout=None, read_timeout=None): """ The purpose of this function is to install default socket timeouts and retry policy for requests calls. Any requests issued through the requests wrappers defined in this module will have these automatically set, unless explicitly overriden. The default timeouts and retries set through this option apply to the entire process. For that reason, it is recommended that this function is only called once during startup, and from the main thread, before any other threads are spawned. :param timeout timeout for socket connections and reads in seconds. This is a convenience argument that applies the same default to both connection and read timeouts. :param connect_timeout timeout for socket connections in seconds. :param read_timeout timeout for socket reads in seconds. """ global DEFAULT_CONNECT_TIMEOUT global DEFAULT_READ_TIMEOUT DEFAULT_CONNECT_TIMEOUT = connect_timeout if connect_timeout is not None \ else timeout DEFAULT_READ_TIMEOUT = read_timeout if read_timeout is not None \ else timeout
python
def set_default_timeout(timeout=None, connect_timeout=None, read_timeout=None): """ The purpose of this function is to install default socket timeouts and retry policy for requests calls. Any requests issued through the requests wrappers defined in this module will have these automatically set, unless explicitly overriden. The default timeouts and retries set through this option apply to the entire process. For that reason, it is recommended that this function is only called once during startup, and from the main thread, before any other threads are spawned. :param timeout timeout for socket connections and reads in seconds. This is a convenience argument that applies the same default to both connection and read timeouts. :param connect_timeout timeout for socket connections in seconds. :param read_timeout timeout for socket reads in seconds. """ global DEFAULT_CONNECT_TIMEOUT global DEFAULT_READ_TIMEOUT DEFAULT_CONNECT_TIMEOUT = connect_timeout if connect_timeout is not None \ else timeout DEFAULT_READ_TIMEOUT = read_timeout if read_timeout is not None \ else timeout
[ "def", "set_default_timeout", "(", "timeout", "=", "None", ",", "connect_timeout", "=", "None", ",", "read_timeout", "=", "None", ")", ":", "global", "DEFAULT_CONNECT_TIMEOUT", "global", "DEFAULT_READ_TIMEOUT", "DEFAULT_CONNECT_TIMEOUT", "=", "connect_timeout", "if", ...
The purpose of this function is to install default socket timeouts and retry policy for requests calls. Any requests issued through the requests wrappers defined in this module will have these automatically set, unless explicitly overriden. The default timeouts and retries set through this option apply to the entire process. For that reason, it is recommended that this function is only called once during startup, and from the main thread, before any other threads are spawned. :param timeout timeout for socket connections and reads in seconds. This is a convenience argument that applies the same default to both connection and read timeouts. :param connect_timeout timeout for socket connections in seconds. :param read_timeout timeout for socket reads in seconds.
[ "The", "purpose", "of", "this", "function", "is", "to", "install", "default", "socket", "timeouts", "and", "retry", "policy", "for", "requests", "calls", ".", "Any", "requests", "issued", "through", "the", "requests", "wrappers", "defined", "in", "this", "modu...
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/requests.py#L13-L36
train
30,525
rackerlabs/fleece
fleece/requests.py
Session.request
def request(self, method, url, **kwargs): """ Send a request. If timeout is not explicitly given, use the default timeouts. """ if 'timeout' not in kwargs: if self.timeout is not None: kwargs['timeout'] = self.timeout else: kwargs['timeout'] = (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT) return super(Session, self).request(method=method, url=url, **kwargs)
python
def request(self, method, url, **kwargs): """ Send a request. If timeout is not explicitly given, use the default timeouts. """ if 'timeout' not in kwargs: if self.timeout is not None: kwargs['timeout'] = self.timeout else: kwargs['timeout'] = (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT) return super(Session, self).request(method=method, url=url, **kwargs)
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "if", "'timeout'", "not", "in", "kwargs", ":", "if", "self", ".", "timeout", "is", "not", "None", ":", "kwargs", "[", "'timeout'", "]", "=", "self", ".", ...
Send a request. If timeout is not explicitly given, use the default timeouts.
[ "Send", "a", "request", ".", "If", "timeout", "is", "not", "explicitly", "given", "use", "the", "default", "timeouts", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/requests.py#L91-L102
train
30,526
rackerlabs/fleece
fleece/log.py
_has_streamhandler
def _has_streamhandler(logger, level=None, fmt=LOG_FORMAT, stream=DEFAULT_STREAM): """Check the named logger for an appropriate existing StreamHandler. This only returns True if a StreamHandler that exaclty matches our specification is found. If other StreamHandlers are seen, we assume they were added for a different purpose. """ # Ensure we are talking the same type of logging levels # if they passed in a string we need to convert it to a number if isinstance(level, basestring): level = logging.getLevelName(level) for handler in logger.handlers: if not isinstance(handler, logging.StreamHandler): continue if handler.stream is not stream: continue if handler.level != level: continue if not handler.formatter or handler.formatter._fmt != fmt: continue return True return False
python
def _has_streamhandler(logger, level=None, fmt=LOG_FORMAT, stream=DEFAULT_STREAM): """Check the named logger for an appropriate existing StreamHandler. This only returns True if a StreamHandler that exaclty matches our specification is found. If other StreamHandlers are seen, we assume they were added for a different purpose. """ # Ensure we are talking the same type of logging levels # if they passed in a string we need to convert it to a number if isinstance(level, basestring): level = logging.getLevelName(level) for handler in logger.handlers: if not isinstance(handler, logging.StreamHandler): continue if handler.stream is not stream: continue if handler.level != level: continue if not handler.formatter or handler.formatter._fmt != fmt: continue return True return False
[ "def", "_has_streamhandler", "(", "logger", ",", "level", "=", "None", ",", "fmt", "=", "LOG_FORMAT", ",", "stream", "=", "DEFAULT_STREAM", ")", ":", "# Ensure we are talking the same type of logging levels", "# if they passed in a string we need to convert it to a number", "...
Check the named logger for an appropriate existing StreamHandler. This only returns True if a StreamHandler that exaclty matches our specification is found. If other StreamHandlers are seen, we assume they were added for a different purpose.
[ "Check", "the", "named", "logger", "for", "an", "appropriate", "existing", "StreamHandler", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/log.py#L93-L116
train
30,527
rackerlabs/fleece
fleece/log.py
inject_request_ids_into_environment
def inject_request_ids_into_environment(func): """Decorator for the Lambda handler to inject request IDs for logging.""" @wraps(func) def wrapper(event, context): # This might not always be an API Gateway event, so only log the # request ID, if it looks like to be coming from there. if 'requestContext' in event: os.environ[ENV_APIG_REQUEST_ID] = event['requestContext'].get( 'requestId', 'N/A') os.environ[ENV_LAMBDA_REQUEST_ID] = context.aws_request_id return func(event, context) return wrapper
python
def inject_request_ids_into_environment(func): """Decorator for the Lambda handler to inject request IDs for logging.""" @wraps(func) def wrapper(event, context): # This might not always be an API Gateway event, so only log the # request ID, if it looks like to be coming from there. if 'requestContext' in event: os.environ[ENV_APIG_REQUEST_ID] = event['requestContext'].get( 'requestId', 'N/A') os.environ[ENV_LAMBDA_REQUEST_ID] = context.aws_request_id return func(event, context) return wrapper
[ "def", "inject_request_ids_into_environment", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "event", ",", "context", ")", ":", "# This might not always be an API Gateway event, so only log the", "# request ID, if it looks like to be coming from...
Decorator for the Lambda handler to inject request IDs for logging.
[ "Decorator", "for", "the", "Lambda", "handler", "to", "inject", "request", "IDs", "for", "logging", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/log.py#L119-L132
train
30,528
rackerlabs/fleece
fleece/log.py
add_request_ids_from_environment
def add_request_ids_from_environment(logger, name, event_dict): """Custom processor adding request IDs to the log event, if available.""" if ENV_APIG_REQUEST_ID in os.environ: event_dict['api_request_id'] = os.environ[ENV_APIG_REQUEST_ID] if ENV_LAMBDA_REQUEST_ID in os.environ: event_dict['lambda_request_id'] = os.environ[ENV_LAMBDA_REQUEST_ID] return event_dict
python
def add_request_ids_from_environment(logger, name, event_dict): """Custom processor adding request IDs to the log event, if available.""" if ENV_APIG_REQUEST_ID in os.environ: event_dict['api_request_id'] = os.environ[ENV_APIG_REQUEST_ID] if ENV_LAMBDA_REQUEST_ID in os.environ: event_dict['lambda_request_id'] = os.environ[ENV_LAMBDA_REQUEST_ID] return event_dict
[ "def", "add_request_ids_from_environment", "(", "logger", ",", "name", ",", "event_dict", ")", ":", "if", "ENV_APIG_REQUEST_ID", "in", "os", ".", "environ", ":", "event_dict", "[", "'api_request_id'", "]", "=", "os", ".", "environ", "[", "ENV_APIG_REQUEST_ID", "...
Custom processor adding request IDs to the log event, if available.
[ "Custom", "processor", "adding", "request", "IDs", "to", "the", "log", "event", "if", "available", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/log.py#L135-L141
train
30,529
rackerlabs/fleece
fleece/log.py
get_logger
def get_logger(name=None, level=None, stream=DEFAULT_STREAM, clobber_root_handler=True, logger_factory=None, wrapper_class=None): """Configure and return a logger with structlog and stdlib.""" _configure_logger( logger_factory=logger_factory, wrapper_class=wrapper_class) log = structlog.get_logger(name) root_logger = logging.root if log == root_logger: if not _has_streamhandler(root_logger, level=level, stream=stream): stream_handler = logging.StreamHandler(stream) stream_handler.setLevel(level) stream_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) root_logger.addHandler(stream_handler) else: if clobber_root_handler: for handler in root_logger.handlers: handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) if level: log.setLevel(level) return log
python
def get_logger(name=None, level=None, stream=DEFAULT_STREAM, clobber_root_handler=True, logger_factory=None, wrapper_class=None): """Configure and return a logger with structlog and stdlib.""" _configure_logger( logger_factory=logger_factory, wrapper_class=wrapper_class) log = structlog.get_logger(name) root_logger = logging.root if log == root_logger: if not _has_streamhandler(root_logger, level=level, stream=stream): stream_handler = logging.StreamHandler(stream) stream_handler.setLevel(level) stream_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) root_logger.addHandler(stream_handler) else: if clobber_root_handler: for handler in root_logger.handlers: handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) if level: log.setLevel(level) return log
[ "def", "get_logger", "(", "name", "=", "None", ",", "level", "=", "None", ",", "stream", "=", "DEFAULT_STREAM", ",", "clobber_root_handler", "=", "True", ",", "logger_factory", "=", "None", ",", "wrapper_class", "=", "None", ")", ":", "_configure_logger", "(...
Configure and return a logger with structlog and stdlib.
[ "Configure", "and", "return", "a", "logger", "with", "structlog", "and", "stdlib", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/log.py#L181-L202
train
30,530
rackerlabs/fleece
fleece/raxauth.py
validate
def validate(token): """Validate token and return auth context.""" token_url = TOKEN_URL_FMT.format(token=token) headers = { 'x-auth-token': token, 'accept': 'application/json', } resp = requests.get(token_url, headers=headers) if not resp.status_code == 200: raise HTTPError(status=401) return resp.json()
python
def validate(token): """Validate token and return auth context.""" token_url = TOKEN_URL_FMT.format(token=token) headers = { 'x-auth-token': token, 'accept': 'application/json', } resp = requests.get(token_url, headers=headers) if not resp.status_code == 200: raise HTTPError(status=401) return resp.json()
[ "def", "validate", "(", "token", ")", ":", "token_url", "=", "TOKEN_URL_FMT", ".", "format", "(", "token", "=", "token", ")", "headers", "=", "{", "'x-auth-token'", ":", "token", ",", "'accept'", ":", "'application/json'", ",", "}", "resp", "=", "requests"...
Validate token and return auth context.
[ "Validate", "token", "and", "return", "auth", "context", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/raxauth.py#L23-L34
train
30,531
rackerlabs/fleece
fleece/utils.py
_fullmatch
def _fullmatch(pattern, text, *args, **kwargs): """re.fullmatch is not available on Python<3.4.""" match = re.match(pattern, text, *args, **kwargs) return match if match.group(0) == text else None
python
def _fullmatch(pattern, text, *args, **kwargs): """re.fullmatch is not available on Python<3.4.""" match = re.match(pattern, text, *args, **kwargs) return match if match.group(0) == text else None
[ "def", "_fullmatch", "(", "pattern", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "match", "=", "re", ".", "match", "(", "pattern", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "match", "if", "match"...
re.fullmatch is not available on Python<3.4.
[ "re", ".", "fullmatch", "is", "not", "available", "on", "Python<3", ".", "4", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/utils.py#L5-L8
train
30,532
rackerlabs/fleece
fleece/cli/config/config.py
_read_config_file
def _read_config_file(args): """Decrypt config file, returns a tuple with stages and config.""" stage = args.stage with open(args.config, 'rt') as f: config = yaml.safe_load(f.read()) STATE['stages'] = config['stages'] config['config'] = _decrypt_item(config['config'], stage=stage, key='', render=True) return config['stages'], config['config']
python
def _read_config_file(args): """Decrypt config file, returns a tuple with stages and config.""" stage = args.stage with open(args.config, 'rt') as f: config = yaml.safe_load(f.read()) STATE['stages'] = config['stages'] config['config'] = _decrypt_item(config['config'], stage=stage, key='', render=True) return config['stages'], config['config']
[ "def", "_read_config_file", "(", "args", ")", ":", "stage", "=", "args", ".", "stage", "with", "open", "(", "args", ".", "config", ",", "'rt'", ")", "as", "f", ":", "config", "=", "yaml", ".", "safe_load", "(", "f", ".", "read", "(", ")", ")", "S...
Decrypt config file, returns a tuple with stages and config.
[ "Decrypt", "config", "file", "returns", "a", "tuple", "with", "stages", "and", "config", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/config/config.py#L265-L273
train
30,533
rackerlabs/fleece
fleece/xray.py
get_trace_id
def get_trace_id(): """Parse X-Ray Trace ID environment variable. The value looks something like this: Root=1-5901e3bc-8da3814a5f3ccbc864b66ecc;Parent=328f72132deac0ce;Sampled=1 `Root` is the main X-Ray Trace ID, `Parent` points to the top-level segment, and `Sampled` shows whether the current request should be traced or not. If the environment variable doesn't exist, just return an `XRayTraceID` instance with default values, which means that tracing will be skipped due to `sampled` being set to `False`. """ raw_trace_id = os.environ.get('_X_AMZN_TRACE_ID', '') trace_id_parts = raw_trace_id.split(';') trace_kwargs = { 'trace_id': None, 'parent_id': None, 'sampled': False, } if trace_id_parts[0] != '': # This means the trace ID environment variable is not empty for part in trace_id_parts: name, value = part.split('=') if name == 'Root': trace_kwargs['trace_id'] = value elif name == 'Parent': trace_kwargs['parent_id'] = value elif name == 'Sampled': trace_kwargs['sampled'] = bool(int(value)) return XRayTraceID(**trace_kwargs)
python
def get_trace_id(): """Parse X-Ray Trace ID environment variable. The value looks something like this: Root=1-5901e3bc-8da3814a5f3ccbc864b66ecc;Parent=328f72132deac0ce;Sampled=1 `Root` is the main X-Ray Trace ID, `Parent` points to the top-level segment, and `Sampled` shows whether the current request should be traced or not. If the environment variable doesn't exist, just return an `XRayTraceID` instance with default values, which means that tracing will be skipped due to `sampled` being set to `False`. """ raw_trace_id = os.environ.get('_X_AMZN_TRACE_ID', '') trace_id_parts = raw_trace_id.split(';') trace_kwargs = { 'trace_id': None, 'parent_id': None, 'sampled': False, } if trace_id_parts[0] != '': # This means the trace ID environment variable is not empty for part in trace_id_parts: name, value = part.split('=') if name == 'Root': trace_kwargs['trace_id'] = value elif name == 'Parent': trace_kwargs['parent_id'] = value elif name == 'Sampled': trace_kwargs['sampled'] = bool(int(value)) return XRayTraceID(**trace_kwargs)
[ "def", "get_trace_id", "(", ")", ":", "raw_trace_id", "=", "os", ".", "environ", ".", "get", "(", "'_X_AMZN_TRACE_ID'", ",", "''", ")", "trace_id_parts", "=", "raw_trace_id", ".", "split", "(", "';'", ")", "trace_kwargs", "=", "{", "'trace_id'", ":", "None...
Parse X-Ray Trace ID environment variable. The value looks something like this: Root=1-5901e3bc-8da3814a5f3ccbc864b66ecc;Parent=328f72132deac0ce;Sampled=1 `Root` is the main X-Ray Trace ID, `Parent` points to the top-level segment, and `Sampled` shows whether the current request should be traced or not. If the environment variable doesn't exist, just return an `XRayTraceID` instance with default values, which means that tracing will be skipped due to `sampled` being set to `False`.
[ "Parse", "X", "-", "Ray", "Trace", "ID", "environment", "variable", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L61-L94
train
30,534
rackerlabs/fleece
fleece/xray.py
get_xray_daemon
def get_xray_daemon(): """Parse X-Ray Daemon address environment variable. If the environment variable is not set, raise an exception to signal that we're unable to send data to X-Ray. """ env_value = os.environ.get('AWS_XRAY_DAEMON_ADDRESS') if env_value is None: raise XRayDaemonNotFoundError() xray_ip, xray_port = env_value.split(':') return XRayDaemon(ip_address=xray_ip, port=int(xray_port))
python
def get_xray_daemon(): """Parse X-Ray Daemon address environment variable. If the environment variable is not set, raise an exception to signal that we're unable to send data to X-Ray. """ env_value = os.environ.get('AWS_XRAY_DAEMON_ADDRESS') if env_value is None: raise XRayDaemonNotFoundError() xray_ip, xray_port = env_value.split(':') return XRayDaemon(ip_address=xray_ip, port=int(xray_port))
[ "def", "get_xray_daemon", "(", ")", ":", "env_value", "=", "os", ".", "environ", ".", "get", "(", "'AWS_XRAY_DAEMON_ADDRESS'", ")", "if", "env_value", "is", "None", ":", "raise", "XRayDaemonNotFoundError", "(", ")", "xray_ip", ",", "xray_port", "=", "env_value...
Parse X-Ray Daemon address environment variable. If the environment variable is not set, raise an exception to signal that we're unable to send data to X-Ray.
[ "Parse", "X", "-", "Ray", "Daemon", "address", "environment", "variable", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L97-L108
train
30,535
rackerlabs/fleece
fleece/xray.py
send_segment_document_to_xray_daemon
def send_segment_document_to_xray_daemon(segment_document): """Format and send document to the X-Ray Daemon.""" try: xray_daemon = get_xray_daemon() except XRayDaemonNotFoundError: LOGGER.error('X-Ray Daemon not running, skipping send') return message = u'{header}\n{document}'.format( header=json.dumps(XRAY_DAEMON_HEADER), document=json.dumps( segment_document, ensure_ascii=False, cls=StringJSONEncoder, ), ) send_data_on_udp( ip_address=xray_daemon.ip_address, port=xray_daemon.port, data=message, )
python
def send_segment_document_to_xray_daemon(segment_document): """Format and send document to the X-Ray Daemon.""" try: xray_daemon = get_xray_daemon() except XRayDaemonNotFoundError: LOGGER.error('X-Ray Daemon not running, skipping send') return message = u'{header}\n{document}'.format( header=json.dumps(XRAY_DAEMON_HEADER), document=json.dumps( segment_document, ensure_ascii=False, cls=StringJSONEncoder, ), ) send_data_on_udp( ip_address=xray_daemon.ip_address, port=xray_daemon.port, data=message, )
[ "def", "send_segment_document_to_xray_daemon", "(", "segment_document", ")", ":", "try", ":", "xray_daemon", "=", "get_xray_daemon", "(", ")", "except", "XRayDaemonNotFoundError", ":", "LOGGER", ".", "error", "(", "'X-Ray Daemon not running, skipping send'", ")", "return"...
Format and send document to the X-Ray Daemon.
[ "Format", "and", "send", "document", "to", "the", "X", "-", "Ray", "Daemon", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L122-L143
train
30,536
rackerlabs/fleece
fleece/xray.py
send_subsegment_to_xray_daemon
def send_subsegment_to_xray_daemon(subsegment_id, parent_id, start_time, end_time=None, name=None, namespace='remote', extra_data=None): """High level function to send data to the X-Ray Daemon. If `end_time` is set to `None` (which is the default), a partial subsegment will be sent to X-Ray, which has to be completed by a subsequent call to this function after the underlying operation finishes. The `namespace` argument can either be `aws` or `remote` (`local` is used as a default, but it's not officially supported by X-Ray). The `extra_data` argument must be a `dict` that is used for updating the segment document with arbitrary data. """ extra_data = extra_data or {} trace_id = get_trace_id() segment_document = { 'type': 'subsegment', 'id': subsegment_id, 'trace_id': trace_id.trace_id, 'parent_id': parent_id, 'start_time': start_time, } if end_time is None: segment_document['in_progress'] = True else: segment_document.update({ 'end_time': end_time, 'name': name, 'namespace': namespace, }) segment_document.update(extra_data) LOGGER.debug( 'Prepared segment document for X-Ray Daemon', segment_document=segment_document, ) send_segment_document_to_xray_daemon(segment_document)
python
def send_subsegment_to_xray_daemon(subsegment_id, parent_id, start_time, end_time=None, name=None, namespace='remote', extra_data=None): """High level function to send data to the X-Ray Daemon. If `end_time` is set to `None` (which is the default), a partial subsegment will be sent to X-Ray, which has to be completed by a subsequent call to this function after the underlying operation finishes. The `namespace` argument can either be `aws` or `remote` (`local` is used as a default, but it's not officially supported by X-Ray). The `extra_data` argument must be a `dict` that is used for updating the segment document with arbitrary data. """ extra_data = extra_data or {} trace_id = get_trace_id() segment_document = { 'type': 'subsegment', 'id': subsegment_id, 'trace_id': trace_id.trace_id, 'parent_id': parent_id, 'start_time': start_time, } if end_time is None: segment_document['in_progress'] = True else: segment_document.update({ 'end_time': end_time, 'name': name, 'namespace': namespace, }) segment_document.update(extra_data) LOGGER.debug( 'Prepared segment document for X-Ray Daemon', segment_document=segment_document, ) send_segment_document_to_xray_daemon(segment_document)
[ "def", "send_subsegment_to_xray_daemon", "(", "subsegment_id", ",", "parent_id", ",", "start_time", ",", "end_time", "=", "None", ",", "name", "=", "None", ",", "namespace", "=", "'remote'", ",", "extra_data", "=", "None", ")", ":", "extra_data", "=", "extra_d...
High level function to send data to the X-Ray Daemon. If `end_time` is set to `None` (which is the default), a partial subsegment will be sent to X-Ray, which has to be completed by a subsequent call to this function after the underlying operation finishes. The `namespace` argument can either be `aws` or `remote` (`local` is used as a default, but it's not officially supported by X-Ray). The `extra_data` argument must be a `dict` that is used for updating the segment document with arbitrary data.
[ "High", "level", "function", "to", "send", "data", "to", "the", "X", "-", "Ray", "Daemon", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L146-L184
train
30,537
rackerlabs/fleece
fleece/xray.py
generic_xray_wrapper
def generic_xray_wrapper(wrapped, instance, args, kwargs, name, namespace, metadata_extractor, error_handling_type=ERROR_HANDLING_GENERIC): """Wrapper function around existing calls to send traces to X-Ray. `wrapped` is the original function, `instance` is the original instance, if the function is an instance method (otherwise it'll be `None`), `args` and `kwargs` are the positional and keyword arguments the original function was called with. The `name` argument can either be a `string` or a callable. In the latter case the function must accept the following arguments: def callback(wrapped, instance, args, kwargs): pass The `metadata_extractor` argument has to be a function with the following definition: def callback(wrapped, instance, args, kwargs, return_value): pass It has to return a `dict` that will be used to extend the segment document. The `error_handling_type` determines how exceptions raised by the wrapped function are handled. Currently `botocore` requires some special care. """ if not get_trace_id().sampled: # Request not sampled by X-Ray, let's get to the call # immediately. LOGGER.debug('Request not sampled by X-Ray, skipping trace') return wrapped(*args, **kwargs) start_time = time.time() error = False cause = None # Fetch the parent ID from the current thread, and set it to the current # subsegment, so that downstream subsegments will be correctly nested. original_parent_id = get_parent_id() # If not parent ID exists in the thread-local storage, it means we're at # the topmost level, so we have to retrieve the parent ID from the trace ID # environment variable. parent_id = original_parent_id or get_parent_id_from_trace_id() subsegment_id = generate_subsegment_id() set_parent_id(subsegment_id) # Send partial subsegment to X-Ray, so that it'll know about the relations # upfront (otherwise we'll lose data, since downstream subsegments will # have invalid parent IDs). send_subsegment_to_xray_daemon( subsegment_id=subsegment_id, parent_id=parent_id, start_time=start_time, ) try: return_value = wrapped(*args, **kwargs) except Exception as exc: error = True cause = { 'exceptions': [ { 'message': str(exc), 'type': '{}.{}'.format( type(exc).__module__, type(exc).__name__, ), } ] } if error_handling_type == ERROR_HANDLING_GENERIC: return_value = None elif error_handling_type == ERROR_HANDLING_BOTOCORE: if isinstance(exc, ClientError): return_value = exc.response else: return_value = {} raise finally: end_time = time.time() extra_data = metadata_extractor( wrapped=wrapped, instance=instance, args=args, kwargs=kwargs, return_value=return_value, ) extra_data['error'] = error if error: extra_data['cause'] = cause # We allow the name to be determined dynamically when a function is # passed in as the `name` argument. if callable(name): name = name(wrapped, instance, args, kwargs) send_subsegment_to_xray_daemon( subsegment_id=subsegment_id, parent_id=parent_id, start_time=start_time, end_time=end_time, name=name, namespace=namespace, extra_data=extra_data, ) # After done with reporting the current subsegment, reset parent # ID to the original one. set_parent_id(original_parent_id) return return_value
python
def generic_xray_wrapper(wrapped, instance, args, kwargs, name, namespace, metadata_extractor, error_handling_type=ERROR_HANDLING_GENERIC): """Wrapper function around existing calls to send traces to X-Ray. `wrapped` is the original function, `instance` is the original instance, if the function is an instance method (otherwise it'll be `None`), `args` and `kwargs` are the positional and keyword arguments the original function was called with. The `name` argument can either be a `string` or a callable. In the latter case the function must accept the following arguments: def callback(wrapped, instance, args, kwargs): pass The `metadata_extractor` argument has to be a function with the following definition: def callback(wrapped, instance, args, kwargs, return_value): pass It has to return a `dict` that will be used to extend the segment document. The `error_handling_type` determines how exceptions raised by the wrapped function are handled. Currently `botocore` requires some special care. """ if not get_trace_id().sampled: # Request not sampled by X-Ray, let's get to the call # immediately. LOGGER.debug('Request not sampled by X-Ray, skipping trace') return wrapped(*args, **kwargs) start_time = time.time() error = False cause = None # Fetch the parent ID from the current thread, and set it to the current # subsegment, so that downstream subsegments will be correctly nested. original_parent_id = get_parent_id() # If not parent ID exists in the thread-local storage, it means we're at # the topmost level, so we have to retrieve the parent ID from the trace ID # environment variable. parent_id = original_parent_id or get_parent_id_from_trace_id() subsegment_id = generate_subsegment_id() set_parent_id(subsegment_id) # Send partial subsegment to X-Ray, so that it'll know about the relations # upfront (otherwise we'll lose data, since downstream subsegments will # have invalid parent IDs). send_subsegment_to_xray_daemon( subsegment_id=subsegment_id, parent_id=parent_id, start_time=start_time, ) try: return_value = wrapped(*args, **kwargs) except Exception as exc: error = True cause = { 'exceptions': [ { 'message': str(exc), 'type': '{}.{}'.format( type(exc).__module__, type(exc).__name__, ), } ] } if error_handling_type == ERROR_HANDLING_GENERIC: return_value = None elif error_handling_type == ERROR_HANDLING_BOTOCORE: if isinstance(exc, ClientError): return_value = exc.response else: return_value = {} raise finally: end_time = time.time() extra_data = metadata_extractor( wrapped=wrapped, instance=instance, args=args, kwargs=kwargs, return_value=return_value, ) extra_data['error'] = error if error: extra_data['cause'] = cause # We allow the name to be determined dynamically when a function is # passed in as the `name` argument. if callable(name): name = name(wrapped, instance, args, kwargs) send_subsegment_to_xray_daemon( subsegment_id=subsegment_id, parent_id=parent_id, start_time=start_time, end_time=end_time, name=name, namespace=namespace, extra_data=extra_data, ) # After done with reporting the current subsegment, reset parent # ID to the original one. set_parent_id(original_parent_id) return return_value
[ "def", "generic_xray_wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "name", ",", "namespace", ",", "metadata_extractor", ",", "error_handling_type", "=", "ERROR_HANDLING_GENERIC", ")", ":", "if", "not", "get_trace_id", "(", ")", ".",...
Wrapper function around existing calls to send traces to X-Ray. `wrapped` is the original function, `instance` is the original instance, if the function is an instance method (otherwise it'll be `None`), `args` and `kwargs` are the positional and keyword arguments the original function was called with. The `name` argument can either be a `string` or a callable. In the latter case the function must accept the following arguments: def callback(wrapped, instance, args, kwargs): pass The `metadata_extractor` argument has to be a function with the following definition: def callback(wrapped, instance, args, kwargs, return_value): pass It has to return a `dict` that will be used to extend the segment document. The `error_handling_type` determines how exceptions raised by the wrapped function are handled. Currently `botocore` requires some special care.
[ "Wrapper", "function", "around", "existing", "calls", "to", "send", "traces", "to", "X", "-", "Ray", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L208-L314
train
30,538
rackerlabs/fleece
fleece/xray.py
extract_function_metadata
def extract_function_metadata(wrapped, instance, args, kwargs, return_value): """Stash the `args` and `kwargs` into the metadata of the subsegment.""" LOGGER.debug( 'Extracting function call metadata', args=args, kwargs=kwargs, ) return { 'metadata': { 'args': args, 'kwargs': kwargs, }, }
python
def extract_function_metadata(wrapped, instance, args, kwargs, return_value): """Stash the `args` and `kwargs` into the metadata of the subsegment.""" LOGGER.debug( 'Extracting function call metadata', args=args, kwargs=kwargs, ) return { 'metadata': { 'args': args, 'kwargs': kwargs, }, }
[ "def", "extract_function_metadata", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "return_value", ")", ":", "LOGGER", ".", "debug", "(", "'Extracting function call metadata'", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ",", ")"...
Stash the `args` and `kwargs` into the metadata of the subsegment.
[ "Stash", "the", "args", "and", "kwargs", "into", "the", "metadata", "of", "the", "subsegment", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L322-L334
train
30,539
rackerlabs/fleece
fleece/xray.py
trace_xray_subsegment
def trace_xray_subsegment(skip_args=False): """Can be applied to any function or method to be traced by X-Ray. If `skip_args` is True, the arguments of the function won't be sent to X-Ray. """ @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): metadata_extractor = ( noop_function_metadata if skip_args else extract_function_metadata ) return generic_xray_wrapper( wrapped, instance, args, kwargs, name=get_function_name, namespace='local', metadata_extractor=metadata_extractor, ) return wrapper
python
def trace_xray_subsegment(skip_args=False): """Can be applied to any function or method to be traced by X-Ray. If `skip_args` is True, the arguments of the function won't be sent to X-Ray. """ @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): metadata_extractor = ( noop_function_metadata if skip_args else extract_function_metadata ) return generic_xray_wrapper( wrapped, instance, args, kwargs, name=get_function_name, namespace='local', metadata_extractor=metadata_extractor, ) return wrapper
[ "def", "trace_xray_subsegment", "(", "skip_args", "=", "False", ")", ":", "@", "wrapt", ".", "decorator", "def", "wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "metadata_extractor", "=", "(", "noop_function_metadata", "if", ...
Can be applied to any function or method to be traced by X-Ray. If `skip_args` is True, the arguments of the function won't be sent to X-Ray.
[ "Can", "be", "applied", "to", "any", "function", "or", "method", "to", "be", "traced", "by", "X", "-", "Ray", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L337-L357
train
30,540
rackerlabs/fleece
fleece/xray.py
get_service_name
def get_service_name(wrapped, instance, args, kwargs): """Return the AWS service name the client is communicating with.""" if 'serviceAbbreviation' not in instance._service_model.metadata: return instance._service_model.metadata['endpointPrefix'] return instance._service_model.metadata['serviceAbbreviation']
python
def get_service_name(wrapped, instance, args, kwargs): """Return the AWS service name the client is communicating with.""" if 'serviceAbbreviation' not in instance._service_model.metadata: return instance._service_model.metadata['endpointPrefix'] return instance._service_model.metadata['serviceAbbreviation']
[ "def", "get_service_name", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "if", "'serviceAbbreviation'", "not", "in", "instance", ".", "_service_model", ".", "metadata", ":", "return", "instance", ".", "_service_model", ".", "metadata", ...
Return the AWS service name the client is communicating with.
[ "Return", "the", "AWS", "service", "name", "the", "client", "is", "communicating", "with", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L360-L364
train
30,541
rackerlabs/fleece
fleece/xray.py
extract_aws_metadata
def extract_aws_metadata(wrapped, instance, args, kwargs, return_value): """Provide AWS metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-aws """ response = return_value LOGGER.debug( 'Extracting AWS metadata', args=args, kwargs=kwargs, ) if 'operation_name' in kwargs: operation_name = kwargs['operation_name'] else: operation_name = args[0] # Most of the time the actual keyword arguments to the client call are # passed in as a positial argument after the operation name. if len(kwargs) == 0 and len(args) == 2: kwargs = args[1] region_name = instance._client_config.region_name response_metadata = response.get('ResponseMetadata') metadata = { 'aws': { 'operation': operation_name, 'region': region_name, } } if 'TableName' in kwargs: metadata['aws']['table_name'] = kwargs['TableName'] if 'QueueUrl' in kwargs: metadata['aws']['queue_url'] = kwargs['QueueUrl'] if response_metadata is not None: metadata['http'] = { 'response': { 'status': response_metadata['HTTPStatusCode'], }, } metadata['aws']['request_id'] = response_metadata['RequestId'] return metadata
python
def extract_aws_metadata(wrapped, instance, args, kwargs, return_value): """Provide AWS metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-aws """ response = return_value LOGGER.debug( 'Extracting AWS metadata', args=args, kwargs=kwargs, ) if 'operation_name' in kwargs: operation_name = kwargs['operation_name'] else: operation_name = args[0] # Most of the time the actual keyword arguments to the client call are # passed in as a positial argument after the operation name. if len(kwargs) == 0 and len(args) == 2: kwargs = args[1] region_name = instance._client_config.region_name response_metadata = response.get('ResponseMetadata') metadata = { 'aws': { 'operation': operation_name, 'region': region_name, } } if 'TableName' in kwargs: metadata['aws']['table_name'] = kwargs['TableName'] if 'QueueUrl' in kwargs: metadata['aws']['queue_url'] = kwargs['QueueUrl'] if response_metadata is not None: metadata['http'] = { 'response': { 'status': response_metadata['HTTPStatusCode'], }, } metadata['aws']['request_id'] = response_metadata['RequestId'] return metadata
[ "def", "extract_aws_metadata", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "return_value", ")", ":", "response", "=", "return_value", "LOGGER", ".", "debug", "(", "'Extracting AWS metadata'", ",", "args", "=", "args", ",", "kwargs", "=", ...
Provide AWS metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-aws
[ "Provide", "AWS", "metadata", "for", "improved", "visualization", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L367-L413
train
30,542
rackerlabs/fleece
fleece/xray.py
xray_botocore_api_call
def xray_botocore_api_call(wrapped, instance, args, kwargs): """Wrapper around botocore's base client API call method.""" return generic_xray_wrapper( wrapped, instance, args, kwargs, name=get_service_name, namespace='aws', metadata_extractor=extract_aws_metadata, error_handling_type=ERROR_HANDLING_BOTOCORE, )
python
def xray_botocore_api_call(wrapped, instance, args, kwargs): """Wrapper around botocore's base client API call method.""" return generic_xray_wrapper( wrapped, instance, args, kwargs, name=get_service_name, namespace='aws', metadata_extractor=extract_aws_metadata, error_handling_type=ERROR_HANDLING_BOTOCORE, )
[ "def", "xray_botocore_api_call", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "return", "generic_xray_wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "name", "=", "get_service_name", ",", "namespace", "=", ...
Wrapper around botocore's base client API call method.
[ "Wrapper", "around", "botocore", "s", "base", "client", "API", "call", "method", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L416-L424
train
30,543
rackerlabs/fleece
fleece/xray.py
extract_http_metadata
def extract_http_metadata(wrapped, instance, args, kwargs, return_value): """Provide HTTP request metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-http """ response = return_value LOGGER.debug( 'Extracting HTTP metadata', args=args, kwargs=kwargs, ) if 'request' in kwargs: request = kwargs['request'] else: request = args[0] metadata = { 'http': { 'request': { 'method': request.method.upper(), 'url': request.url, }, }, } if response is not None: metadata['http']['response'] = { 'status': response.status_code, } return metadata
python
def extract_http_metadata(wrapped, instance, args, kwargs, return_value): """Provide HTTP request metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-http """ response = return_value LOGGER.debug( 'Extracting HTTP metadata', args=args, kwargs=kwargs, ) if 'request' in kwargs: request = kwargs['request'] else: request = args[0] metadata = { 'http': { 'request': { 'method': request.method.upper(), 'url': request.url, }, }, } if response is not None: metadata['http']['response'] = { 'status': response.status_code, } return metadata
[ "def", "extract_http_metadata", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "return_value", ")", ":", "response", "=", "return_value", "LOGGER", ".", "debug", "(", "'Extracting HTTP metadata'", ",", "args", "=", "args", ",", "kwargs", "="...
Provide HTTP request metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-http
[ "Provide", "HTTP", "request", "metadata", "for", "improved", "visualization", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L436-L466
train
30,544
rackerlabs/fleece
fleece/xray.py
xray_requests_send
def xray_requests_send(wrapped, instance, args, kwargs): """Wrapper around the requests library's low-level send method.""" return generic_xray_wrapper( wrapped, instance, args, kwargs, name='requests', namespace='remote', metadata_extractor=extract_http_metadata, )
python
def xray_requests_send(wrapped, instance, args, kwargs): """Wrapper around the requests library's low-level send method.""" return generic_xray_wrapper( wrapped, instance, args, kwargs, name='requests', namespace='remote', metadata_extractor=extract_http_metadata, )
[ "def", "xray_requests_send", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "return", "generic_xray_wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "name", "=", "'requests'", ",", "namespace", "=", "'remote...
Wrapper around the requests library's low-level send method.
[ "Wrapper", "around", "the", "requests", "library", "s", "low", "-", "level", "send", "method", "." ]
42d79dfa0777e99dbb09bc46105449a9be5dbaa9
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/xray.py#L469-L476
train
30,545
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.set_unit_spike_features
def set_unit_spike_features(self, unit_id, feature_name, value): '''This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: str The name of the feature to be stored value The data associated with the given feature name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_features.keys(): self._unit_features[unit_id] = {} if isinstance(feature_name, str) and len(value) == len(self.get_unit_spike_train(unit_id)): self._unit_features[unit_id][feature_name] = np.asarray(value) else: if not isinstance(feature_name, str): raise ValueError("feature_name must be a string") else: raise ValueError("feature values should have the same length as the spike train") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
python
def set_unit_spike_features(self, unit_id, feature_name, value): '''This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: str The name of the feature to be stored value The data associated with the given feature name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_features.keys(): self._unit_features[unit_id] = {} if isinstance(feature_name, str) and len(value) == len(self.get_unit_spike_train(unit_id)): self._unit_features[unit_id][feature_name] = np.asarray(value) else: if not isinstance(feature_name, str): raise ValueError("feature_name must be a string") else: raise ValueError("feature values should have the same length as the spike train") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
[ "def", "set_unit_spike_features", "(", "self", ",", "unit_id", ",", "feature_name", ",", "value", ")", ":", "if", "isinstance", "(", "unit_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "unit_id", "in", "self", ".", "get_unit_ids",...
This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: str The name of the feature to be stored value The data associated with the given feature name. Could be many formats as specified by the user.
[ "This", "function", "adds", "a", "unit", "features", "data", "set", "under", "the", "given", "features", "name", "to", "the", "given", "unit", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L65-L93
train
30,546
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.set_unit_property
def set_unit_property(self, unit_id, property_name, value): '''This function adds a unit property data set under the given property name to the given unit. Parameters ---------- unit_id: int The unit id for which the property will be set property_name: str The name of the property to be stored value The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} if isinstance(property_name, str): self._unit_properties[unit_id][property_name] = value else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
python
def set_unit_property(self, unit_id, property_name, value): '''This function adds a unit property data set under the given property name to the given unit. Parameters ---------- unit_id: int The unit id for which the property will be set property_name: str The name of the property to be stored value The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} if isinstance(property_name, str): self._unit_properties[unit_id][property_name] = value else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
[ "def", "set_unit_property", "(", "self", ",", "unit_id", ",", "property_name", ",", "value", ")", ":", "if", "isinstance", "(", "unit_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "unit_id", "in", "self", ".", "get_unit_ids", "(...
This function adds a unit property data set under the given property name to the given unit. Parameters ---------- unit_id: int The unit id for which the property will be set property_name: str The name of the property to be stored value The data associated with the given property name. Could be many formats as specified by the user.
[ "This", "function", "adds", "a", "unit", "property", "data", "set", "under", "the", "given", "property", "name", "to", "the", "given", "unit", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L178-L203
train
30,547
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.set_units_property
def set_units_property(self, *, unit_ids=None, property_name, values): '''Sets unit property data for a list of units Parameters ---------- unit_ids: list The list of unit ids for which the property will be set Defaults to get_unit_ids() property_name: str The name of the property value: list The list of values to be set ''' if unit_ids is None: unit_ids = self.get_unit_ids() for i, unit in enumerate(unit_ids): self.set_unit_property(unit_id=unit, property_name=property_name, value=values[i])
python
def set_units_property(self, *, unit_ids=None, property_name, values): '''Sets unit property data for a list of units Parameters ---------- unit_ids: list The list of unit ids for which the property will be set Defaults to get_unit_ids() property_name: str The name of the property value: list The list of values to be set ''' if unit_ids is None: unit_ids = self.get_unit_ids() for i, unit in enumerate(unit_ids): self.set_unit_property(unit_id=unit, property_name=property_name, value=values[i])
[ "def", "set_units_property", "(", "self", ",", "*", ",", "unit_ids", "=", "None", ",", "property_name", ",", "values", ")", ":", "if", "unit_ids", "is", "None", ":", "unit_ids", "=", "self", ".", "get_unit_ids", "(", ")", "for", "i", ",", "unit", "in",...
Sets unit property data for a list of units Parameters ---------- unit_ids: list The list of unit ids for which the property will be set Defaults to get_unit_ids() property_name: str The name of the property value: list The list of values to be set
[ "Sets", "unit", "property", "data", "for", "a", "list", "of", "units" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L205-L221
train
30,548
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.get_unit_property
def get_unit_property(self, unit_id, property_name): '''This function rerturns the data stored under the property name given from the given unit. Parameters ---------- unit_id: int The unit id for which the property will be returned property_name: str The name of the property Returns ---------- value The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} if isinstance(property_name, str): if property_name in list(self._unit_properties[unit_id].keys()): return self._unit_properties[unit_id][property_name] else: raise ValueError(str(property_name) + " has not been added to unit " + str(unit_id)) else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
python
def get_unit_property(self, unit_id, property_name): '''This function rerturns the data stored under the property name given from the given unit. Parameters ---------- unit_id: int The unit id for which the property will be returned property_name: str The name of the property Returns ---------- value The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} if isinstance(property_name, str): if property_name in list(self._unit_properties[unit_id].keys()): return self._unit_properties[unit_id][property_name] else: raise ValueError(str(property_name) + " has not been added to unit " + str(unit_id)) else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
[ "def", "get_unit_property", "(", "self", ",", "unit_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "unit_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "unit_id", "in", "self", ".", "get_unit_ids", "(", ")", ":", ...
This function rerturns the data stored under the property name given from the given unit. Parameters ---------- unit_id: int The unit id for which the property will be returned property_name: str The name of the property Returns ---------- value The data associated with the given property name. Could be many formats as specified by the user.
[ "This", "function", "rerturns", "the", "data", "stored", "under", "the", "property", "name", "given", "from", "the", "given", "unit", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L249-L279
train
30,549
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.get_units_property
def get_units_property(self, *, unit_ids=None, property_name): '''Returns a list of values stored under the property name corresponding to a list of units Parameters ---------- unit_ids: list The unit ids for which the property will be returned Defaults to get_unit_ids() property_name: str The name of the property Returns ---------- values The list of values ''' if unit_ids is None: unit_ids = self.get_unit_ids() values = [self.get_unit_property(unit_id=unit, property_name=property_name) for unit in unit_ids] return values
python
def get_units_property(self, *, unit_ids=None, property_name): '''Returns a list of values stored under the property name corresponding to a list of units Parameters ---------- unit_ids: list The unit ids for which the property will be returned Defaults to get_unit_ids() property_name: str The name of the property Returns ---------- values The list of values ''' if unit_ids is None: unit_ids = self.get_unit_ids() values = [self.get_unit_property(unit_id=unit, property_name=property_name) for unit in unit_ids] return values
[ "def", "get_units_property", "(", "self", ",", "*", ",", "unit_ids", "=", "None", ",", "property_name", ")", ":", "if", "unit_ids", "is", "None", ":", "unit_ids", "=", "self", ".", "get_unit_ids", "(", ")", "values", "=", "[", "self", ".", "get_unit_prop...
Returns a list of values stored under the property name corresponding to a list of units Parameters ---------- unit_ids: list The unit ids for which the property will be returned Defaults to get_unit_ids() property_name: str The name of the property Returns ---------- values The list of values
[ "Returns", "a", "list", "of", "values", "stored", "under", "the", "property", "name", "corresponding", "to", "a", "list", "of", "units" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L281-L300
train
30,550
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.get_unit_property_names
def get_unit_property_names(self, unit_id=None): '''Get a list of property names for a given unit, or for all units if unit_id is None Parameters ---------- unit_id: int The unit id for which the property names will be returned If None (default), will return property names for all units Returns ---------- property_names The list of property names from the specified unit(s) ''' if unit_id is None: property_names = [] for unit_id in self.get_unit_ids(): curr_property_names = self.get_unit_property_names(unit_id) for curr_property_name in curr_property_names: property_names.append(curr_property_name) property_names = sorted(list(set(property_names))) return property_names if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} property_names = sorted(self._unit_properties[unit_id].keys()) return property_names else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
python
def get_unit_property_names(self, unit_id=None): '''Get a list of property names for a given unit, or for all units if unit_id is None Parameters ---------- unit_id: int The unit id for which the property names will be returned If None (default), will return property names for all units Returns ---------- property_names The list of property names from the specified unit(s) ''' if unit_id is None: property_names = [] for unit_id in self.get_unit_ids(): curr_property_names = self.get_unit_property_names(unit_id) for curr_property_name in curr_property_names: property_names.append(curr_property_name) property_names = sorted(list(set(property_names))) return property_names if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_properties: self._unit_properties[unit_id] = {} property_names = sorted(self._unit_properties[unit_id].keys()) return property_names else: raise ValueError(str(unit_id) + " is not a valid unit_id") else: raise ValueError(str(unit_id) + " must be an int")
[ "def", "get_unit_property_names", "(", "self", ",", "unit_id", "=", "None", ")", ":", "if", "unit_id", "is", "None", ":", "property_names", "=", "[", "]", "for", "unit_id", "in", "self", ".", "get_unit_ids", "(", ")", ":", "curr_property_names", "=", "self...
Get a list of property names for a given unit, or for all units if unit_id is None Parameters ---------- unit_id: int The unit id for which the property names will be returned If None (default), will return property names for all units Returns ---------- property_names The list of property names from the specified unit(s)
[ "Get", "a", "list", "of", "property", "names", "for", "a", "given", "unit", "or", "for", "all", "units", "if", "unit_id", "is", "None" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L302-L332
train
30,551
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.copy_unit_properties
def copy_unit_properties(self, sorting, unit_ids=None): '''Copy unit properties from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the properties will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the properties will be copied. ''' if unit_ids is None: unit_ids = sorting.get_unit_ids() if isinstance(unit_ids, int): curr_property_names = sorting.get_unit_property_names(unit_id=unit_ids) for curr_property_name in curr_property_names: value = sorting.get_unit_property(unit_id=unit_ids, property_name=curr_property_name) self.set_unit_property(unit_id=unit_ids, property_name=curr_property_name, value=value) else: for unit_id in unit_ids: curr_property_names = sorting.get_unit_property_names(unit_id=unit_id) for curr_property_name in curr_property_names: value = sorting.get_unit_property(unit_id=unit_id, property_name=curr_property_name) self.set_unit_property(unit_id=unit_id, property_name=curr_property_name, value=value)
python
def copy_unit_properties(self, sorting, unit_ids=None): '''Copy unit properties from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the properties will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the properties will be copied. ''' if unit_ids is None: unit_ids = sorting.get_unit_ids() if isinstance(unit_ids, int): curr_property_names = sorting.get_unit_property_names(unit_id=unit_ids) for curr_property_name in curr_property_names: value = sorting.get_unit_property(unit_id=unit_ids, property_name=curr_property_name) self.set_unit_property(unit_id=unit_ids, property_name=curr_property_name, value=value) else: for unit_id in unit_ids: curr_property_names = sorting.get_unit_property_names(unit_id=unit_id) for curr_property_name in curr_property_names: value = sorting.get_unit_property(unit_id=unit_id, property_name=curr_property_name) self.set_unit_property(unit_id=unit_id, property_name=curr_property_name, value=value)
[ "def", "copy_unit_properties", "(", "self", ",", "sorting", ",", "unit_ids", "=", "None", ")", ":", "if", "unit_ids", "is", "None", ":", "unit_ids", "=", "sorting", ".", "get_unit_ids", "(", ")", "if", "isinstance", "(", "unit_ids", ",", "int", ")", ":",...
Copy unit properties from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the properties will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the properties will be copied.
[ "Copy", "unit", "properties", "from", "another", "sorting", "extractor", "to", "the", "current", "sorting", "extractor", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L334-L357
train
30,552
SpikeInterface/spikeextractors
spikeextractors/SortingExtractor.py
SortingExtractor.copy_unit_spike_features
def copy_unit_spike_features(self, sorting, unit_ids=None): '''Copy unit spike features from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the spike features will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the spike features will be copied. def get_unit_spike_features(self, unit_id, feature_name, start_frame=None, end_frame=None): ''' if unit_ids is None: unit_ids = sorting.get_unit_ids() if isinstance(unit_ids, int): curr_feature_names = sorting.get_unit_spike_feature_names(unit_id=unit_ids) for curr_feature_name in curr_feature_names: value = sorting.get_unit_spike_features(unit_id=unit_ids, feature_name=curr_feature_name) self.set_unit_spike_features(unit_id=unit_ids, feature_name=curr_feature_name, value=value) else: for unit_id in unit_ids: curr_feature_names = sorting.get_unit_spike_feature_names(unit_id=unit_id) for curr_feature_name in curr_feature_names: value = sorting.get_unit_spike_features(unit_id=unit_id, feature_name=curr_feature_name) self.set_unit_spike_features(unit_id=unit_id, feature_name=curr_feature_name, value=value)
python
def copy_unit_spike_features(self, sorting, unit_ids=None): '''Copy unit spike features from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the spike features will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the spike features will be copied. def get_unit_spike_features(self, unit_id, feature_name, start_frame=None, end_frame=None): ''' if unit_ids is None: unit_ids = sorting.get_unit_ids() if isinstance(unit_ids, int): curr_feature_names = sorting.get_unit_spike_feature_names(unit_id=unit_ids) for curr_feature_name in curr_feature_names: value = sorting.get_unit_spike_features(unit_id=unit_ids, feature_name=curr_feature_name) self.set_unit_spike_features(unit_id=unit_ids, feature_name=curr_feature_name, value=value) else: for unit_id in unit_ids: curr_feature_names = sorting.get_unit_spike_feature_names(unit_id=unit_id) for curr_feature_name in curr_feature_names: value = sorting.get_unit_spike_features(unit_id=unit_id, feature_name=curr_feature_name) self.set_unit_spike_features(unit_id=unit_id, feature_name=curr_feature_name, value=value)
[ "def", "copy_unit_spike_features", "(", "self", ",", "sorting", ",", "unit_ids", "=", "None", ")", ":", "if", "unit_ids", "is", "None", ":", "unit_ids", "=", "sorting", ".", "get_unit_ids", "(", ")", "if", "isinstance", "(", "unit_ids", ",", "int", ")", ...
Copy unit spike features from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the spike features will be copied unit_ids: (array_like, int) The list (or single value) of unit_ids for which the spike features will be copied. def get_unit_spike_features(self, unit_id, feature_name, start_frame=None, end_frame=None):
[ "Copy", "unit", "spike", "features", "from", "another", "sorting", "extractor", "to", "the", "current", "sorting", "extractor", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L359-L383
train
30,553
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_snippets
def get_snippets(self, *, reference_frames, snippet_len, channel_ids=None): '''This function returns data snippets from the given channels that are starting on the given frames and are the length of the given snippet lengths before and after. Parameters ---------- snippet_len: int or tuple If int, the snippet will be centered at the reference frame and and return half before and half after of the length. If tuple, it will return the first value of before frames and the second value of after frames around the reference frame (allows for asymmetry) reference_frames: array_like A list or array of frames that will be used as the reference frame of each snippet channel_ids: array_like A list or array of channel ids (ints) from which each trace will be extracted. Returns ---------- snippets: numpy.ndarray Returns a list of the snippets as numpy arrays. The length of the list is len(reference_frames) Each array has dimensions: (num_channels x snippet_len) Out-of-bounds cases should be handled by filling in zeros in the snippet. ''' # Default implementation if isinstance(snippet_len, (tuple, list, np.ndarray)): snippet_len_before = snippet_len[0] snippet_len_after = snippet_len[1] else: snippet_len_before = int((snippet_len + 1) / 2) snippet_len_after = snippet_len - snippet_len_before if channel_ids is None: channel_ids = self.get_channel_ids() num_snippets = len(reference_frames) num_channels = len(channel_ids) num_frames = self.get_num_frames() snippet_len_total = snippet_len_before + snippet_len_after # snippets = [] snippets = np.zeros((num_snippets, num_channels, snippet_len_total)) #TODO extract all waveforms in a chunk pad_first = False pad_last = False pad_samples_first = 0 pad_samples_last = 0 snippet_idxs = np.array([], dtype=int) for i in range(num_snippets): snippet_chunk = np.zeros((num_channels, snippet_len_total)) if (0 <= reference_frames[i]) and (reference_frames[i] < num_frames): snippet_range = np.array( [int(reference_frames[i]) - snippet_len_before, int(reference_frames[i]) + snippet_len_after]) snippet_buffer = np.array([0, snippet_len_total]) # The following handles the out-of-bounds cases if snippet_range[0] < 0: snippet_buffer[0] -= snippet_range[0] snippet_range[0] -= snippet_range[0] if snippet_range[1] >= num_frames: snippet_buffer[1] -= snippet_range[1] - num_frames snippet_range[1] -= snippet_range[1] - num_frames snippet_chunk[:, snippet_buffer[0]:snippet_buffer[1]] = self.get_traces(channel_ids=channel_ids, start_frame=snippet_range[0], end_frame=snippet_range[1]) snippets[i] = snippet_chunk return snippets
python
def get_snippets(self, *, reference_frames, snippet_len, channel_ids=None): '''This function returns data snippets from the given channels that are starting on the given frames and are the length of the given snippet lengths before and after. Parameters ---------- snippet_len: int or tuple If int, the snippet will be centered at the reference frame and and return half before and half after of the length. If tuple, it will return the first value of before frames and the second value of after frames around the reference frame (allows for asymmetry) reference_frames: array_like A list or array of frames that will be used as the reference frame of each snippet channel_ids: array_like A list or array of channel ids (ints) from which each trace will be extracted. Returns ---------- snippets: numpy.ndarray Returns a list of the snippets as numpy arrays. The length of the list is len(reference_frames) Each array has dimensions: (num_channels x snippet_len) Out-of-bounds cases should be handled by filling in zeros in the snippet. ''' # Default implementation if isinstance(snippet_len, (tuple, list, np.ndarray)): snippet_len_before = snippet_len[0] snippet_len_after = snippet_len[1] else: snippet_len_before = int((snippet_len + 1) / 2) snippet_len_after = snippet_len - snippet_len_before if channel_ids is None: channel_ids = self.get_channel_ids() num_snippets = len(reference_frames) num_channels = len(channel_ids) num_frames = self.get_num_frames() snippet_len_total = snippet_len_before + snippet_len_after # snippets = [] snippets = np.zeros((num_snippets, num_channels, snippet_len_total)) #TODO extract all waveforms in a chunk pad_first = False pad_last = False pad_samples_first = 0 pad_samples_last = 0 snippet_idxs = np.array([], dtype=int) for i in range(num_snippets): snippet_chunk = np.zeros((num_channels, snippet_len_total)) if (0 <= reference_frames[i]) and (reference_frames[i] < num_frames): snippet_range = np.array( [int(reference_frames[i]) - snippet_len_before, int(reference_frames[i]) + snippet_len_after]) snippet_buffer = np.array([0, snippet_len_total]) # The following handles the out-of-bounds cases if snippet_range[0] < 0: snippet_buffer[0] -= snippet_range[0] snippet_range[0] -= snippet_range[0] if snippet_range[1] >= num_frames: snippet_buffer[1] -= snippet_range[1] - num_frames snippet_range[1] -= snippet_range[1] - num_frames snippet_chunk[:, snippet_buffer[0]:snippet_buffer[1]] = self.get_traces(channel_ids=channel_ids, start_frame=snippet_range[0], end_frame=snippet_range[1]) snippets[i] = snippet_chunk return snippets
[ "def", "get_snippets", "(", "self", ",", "*", ",", "reference_frames", ",", "snippet_len", ",", "channel_ids", "=", "None", ")", ":", "# Default implementation", "if", "isinstance", "(", "snippet_len", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray...
This function returns data snippets from the given channels that are starting on the given frames and are the length of the given snippet lengths before and after. Parameters ---------- snippet_len: int or tuple If int, the snippet will be centered at the reference frame and and return half before and half after of the length. If tuple, it will return the first value of before frames and the second value of after frames around the reference frame (allows for asymmetry) reference_frames: array_like A list or array of frames that will be used as the reference frame of each snippet channel_ids: array_like A list or array of channel ids (ints) from which each trace will be extracted. Returns ---------- snippets: numpy.ndarray Returns a list of the snippets as numpy arrays. The length of the list is len(reference_frames) Each array has dimensions: (num_channels x snippet_len) Out-of-bounds cases should be handled by filling in zeros in the snippet.
[ "This", "function", "returns", "data", "snippets", "from", "the", "given", "channels", "that", "are", "starting", "on", "the", "given", "frames", "and", "are", "the", "length", "of", "the", "given", "snippet", "lengths", "before", "and", "after", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L137-L204
train
30,554
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.set_channel_locations
def set_channel_locations(self, channel_ids, locations): '''This function sets the location properties of each specified channel id with the corresponding locations of the passed in locations list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be specified locations: array_like A list of corresonding locations (array_like) for the given channel_ids ''' if len(channel_ids) == len(locations): for i in range(len(channel_ids)): if isinstance(locations[i],(list,np.ndarray)): location = np.asarray(locations[i]) self.set_channel_property(channel_ids[i], 'location', location.astype(float)) else: raise ValueError(str(locations[i]) + " must be an array_like") else: raise ValueError("channel_ids and locations must have same length")
python
def set_channel_locations(self, channel_ids, locations): '''This function sets the location properties of each specified channel id with the corresponding locations of the passed in locations list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be specified locations: array_like A list of corresonding locations (array_like) for the given channel_ids ''' if len(channel_ids) == len(locations): for i in range(len(channel_ids)): if isinstance(locations[i],(list,np.ndarray)): location = np.asarray(locations[i]) self.set_channel_property(channel_ids[i], 'location', location.astype(float)) else: raise ValueError(str(locations[i]) + " must be an array_like") else: raise ValueError("channel_ids and locations must have same length")
[ "def", "set_channel_locations", "(", "self", ",", "channel_ids", ",", "locations", ")", ":", "if", "len", "(", "channel_ids", ")", "==", "len", "(", "locations", ")", ":", "for", "i", "in", "range", "(", "len", "(", "channel_ids", ")", ")", ":", "if", ...
This function sets the location properties of each specified channel id with the corresponding locations of the passed in locations list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be specified locations: array_like A list of corresonding locations (array_like) for the given channel_ids
[ "This", "function", "sets", "the", "location", "properties", "of", "each", "specified", "channel", "id", "with", "the", "corresponding", "locations", "of", "the", "passed", "in", "locations", "list", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L206-L225
train
30,555
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_channel_locations
def get_channel_locations(self, channel_ids): '''This function returns the location of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be returned Returns ---------- locations: array_like Returns a list of corresonding locations (floats) for the given channel_ids ''' locations = [] for channel_id in channel_ids: location = self.get_channel_property(channel_id, 'location') locations.append(location) return locations
python
def get_channel_locations(self, channel_ids): '''This function returns the location of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be returned Returns ---------- locations: array_like Returns a list of corresonding locations (floats) for the given channel_ids ''' locations = [] for channel_id in channel_ids: location = self.get_channel_property(channel_id, 'location') locations.append(location) return locations
[ "def", "get_channel_locations", "(", "self", ",", "channel_ids", ")", ":", "locations", "=", "[", "]", "for", "channel_id", "in", "channel_ids", ":", "location", "=", "self", ".", "get_channel_property", "(", "channel_id", ",", "'location'", ")", "locations", ...
This function returns the location of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the locations will be returned Returns ---------- locations: array_like Returns a list of corresonding locations (floats) for the given channel_ids
[ "This", "function", "returns", "the", "location", "of", "each", "channel", "specifed", "by", "channel_ids" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L227-L246
train
30,556
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.set_channel_groups
def set_channel_groups(self, channel_ids, groups): '''This function sets the group property of each specified channel id with the corresponding group of the passed in groups list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be specified groups: array_like A list of corresonding groups (ints) for the given channel_ids ''' if len(channel_ids) == len(groups): for i in range(len(channel_ids)): if isinstance(groups[i], int): self.set_channel_property(channel_ids[i], 'group', groups[i]) else: raise ValueError(str(groups[i]) + " must be an int") else: raise ValueError("channel_ids and groups must have same length")
python
def set_channel_groups(self, channel_ids, groups): '''This function sets the group property of each specified channel id with the corresponding group of the passed in groups list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be specified groups: array_like A list of corresonding groups (ints) for the given channel_ids ''' if len(channel_ids) == len(groups): for i in range(len(channel_ids)): if isinstance(groups[i], int): self.set_channel_property(channel_ids[i], 'group', groups[i]) else: raise ValueError(str(groups[i]) + " must be an int") else: raise ValueError("channel_ids and groups must have same length")
[ "def", "set_channel_groups", "(", "self", ",", "channel_ids", ",", "groups", ")", ":", "if", "len", "(", "channel_ids", ")", "==", "len", "(", "groups", ")", ":", "for", "i", "in", "range", "(", "len", "(", "channel_ids", ")", ")", ":", "if", "isinst...
This function sets the group property of each specified channel id with the corresponding group of the passed in groups list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be specified groups: array_like A list of corresonding groups (ints) for the given channel_ids
[ "This", "function", "sets", "the", "group", "property", "of", "each", "specified", "channel", "id", "with", "the", "corresponding", "group", "of", "the", "passed", "in", "groups", "list", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L248-L266
train
30,557
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_channel_groups
def get_channel_groups(self, channel_ids): '''This function returns the group of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be returned Returns ---------- groups: array_like Returns a list of corresonding groups (ints) for the given channel_ids ''' groups = [] for channel_id in channel_ids: group = self.get_channel_property(channel_id, 'group') groups.append(group) return groups
python
def get_channel_groups(self, channel_ids): '''This function returns the group of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be returned Returns ---------- groups: array_like Returns a list of corresonding groups (ints) for the given channel_ids ''' groups = [] for channel_id in channel_ids: group = self.get_channel_property(channel_id, 'group') groups.append(group) return groups
[ "def", "get_channel_groups", "(", "self", ",", "channel_ids", ")", ":", "groups", "=", "[", "]", "for", "channel_id", "in", "channel_ids", ":", "group", "=", "self", ".", "get_channel_property", "(", "channel_id", ",", "'group'", ")", "groups", ".", "append"...
This function returns the group of each channel specifed by channel_ids Parameters ---------- channel_ids: array_like The channel ids (ints) for which the groups will be returned Returns ---------- groups: array_like Returns a list of corresonding groups (ints) for the given channel_ids
[ "This", "function", "returns", "the", "group", "of", "each", "channel", "specifed", "by", "channel_ids" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L268-L287
train
30,558
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.set_channel_property
def set_channel_property(self, channel_id, property_name, value): '''This function adds a property dataset to the given channel under the property name. Parameters ---------- channel_id: int The channel id for which the property will be added property_name: str A property stored by the RecordingExtractor (location, etc.) value: The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(channel_id, (int, np.integer)): if channel_id in self.get_channel_ids(): if channel_id not in self._channel_properties: self._channel_properties[channel_id] = {} if isinstance(property_name, str): self._channel_properties[channel_id][property_name] = value else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(channel_id) + " is not a valid channel_id") else: raise ValueError(str(channel_id) + " must be an int")
python
def set_channel_property(self, channel_id, property_name, value): '''This function adds a property dataset to the given channel under the property name. Parameters ---------- channel_id: int The channel id for which the property will be added property_name: str A property stored by the RecordingExtractor (location, etc.) value: The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(channel_id, (int, np.integer)): if channel_id in self.get_channel_ids(): if channel_id not in self._channel_properties: self._channel_properties[channel_id] = {} if isinstance(property_name, str): self._channel_properties[channel_id][property_name] = value else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(channel_id) + " is not a valid channel_id") else: raise ValueError(str(channel_id) + " must be an int")
[ "def", "set_channel_property", "(", "self", ",", "channel_id", ",", "property_name", ",", "value", ")", ":", "if", "isinstance", "(", "channel_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "channel_id", "in", "self", ".", "get_cha...
This function adds a property dataset to the given channel under the property name. Parameters ---------- channel_id: int The channel id for which the property will be added property_name: str A property stored by the RecordingExtractor (location, etc.) value: The data associated with the given property name. Could be many formats as specified by the user.
[ "This", "function", "adds", "a", "property", "dataset", "to", "the", "given", "channel", "under", "the", "property", "name", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L289-L314
train
30,559
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_channel_property
def get_channel_property(self, channel_id, property_name): '''This function returns the data stored under the property name from the given channel. Parameters ---------- channel_id: int The channel id for which the property will be returned property_name: str A property stored by the RecordingExtractor (location, etc.) Returns ---------- property_data The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(channel_id, (int, np.integer)): if channel_id in self.get_channel_ids(): if channel_id not in self._channel_properties: self._channel_properties[channel_id] = {} if isinstance(property_name, str): if property_name in list(self._channel_properties[channel_id].keys()): return self._channel_properties[channel_id][property_name] else: raise ValueError(str(property_name) + " has not been added to channel " + str(channel_id)) else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(channel_id) + " is not a valid channel_id") else: raise ValueError(str(channel_id) + " must be an int")
python
def get_channel_property(self, channel_id, property_name): '''This function returns the data stored under the property name from the given channel. Parameters ---------- channel_id: int The channel id for which the property will be returned property_name: str A property stored by the RecordingExtractor (location, etc.) Returns ---------- property_data The data associated with the given property name. Could be many formats as specified by the user. ''' if isinstance(channel_id, (int, np.integer)): if channel_id in self.get_channel_ids(): if channel_id not in self._channel_properties: self._channel_properties[channel_id] = {} if isinstance(property_name, str): if property_name in list(self._channel_properties[channel_id].keys()): return self._channel_properties[channel_id][property_name] else: raise ValueError(str(property_name) + " has not been added to channel " + str(channel_id)) else: raise ValueError(str(property_name) + " must be a string") else: raise ValueError(str(channel_id) + " is not a valid channel_id") else: raise ValueError(str(channel_id) + " must be an int")
[ "def", "get_channel_property", "(", "self", ",", "channel_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "channel_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "channel_id", "in", "self", ".", "get_channel_ids", "(", ...
This function returns the data stored under the property name from the given channel. Parameters ---------- channel_id: int The channel id for which the property will be returned property_name: str A property stored by the RecordingExtractor (location, etc.) Returns ---------- property_data The data associated with the given property name. Could be many formats as specified by the user.
[ "This", "function", "returns", "the", "data", "stored", "under", "the", "property", "name", "from", "the", "given", "channel", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L316-L347
train
30,560
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.add_epoch
def add_epoch(self, epoch_name, start_frame, end_frame): '''This function adds an epoch to your recording extractor that tracks a certain time period in your recording. It is stored in an internal dictionary of start and end frame tuples. Parameters ---------- epoch_name: str The name of the epoch to be added start_frame: int The start frame of the epoch to be added (inclusive) end_frame: int The end frame of the epoch to be added (exclusive) ''' # Default implementation only allows for frame info. Can override to put more info if isinstance(epoch_name, str): self._epochs[epoch_name] = {'start_frame': int(start_frame), 'end_frame': int(end_frame)} else: raise ValueError("epoch_name must be a string")
python
def add_epoch(self, epoch_name, start_frame, end_frame): '''This function adds an epoch to your recording extractor that tracks a certain time period in your recording. It is stored in an internal dictionary of start and end frame tuples. Parameters ---------- epoch_name: str The name of the epoch to be added start_frame: int The start frame of the epoch to be added (inclusive) end_frame: int The end frame of the epoch to be added (exclusive) ''' # Default implementation only allows for frame info. Can override to put more info if isinstance(epoch_name, str): self._epochs[epoch_name] = {'start_frame': int(start_frame), 'end_frame': int(end_frame)} else: raise ValueError("epoch_name must be a string")
[ "def", "add_epoch", "(", "self", ",", "epoch_name", ",", "start_frame", ",", "end_frame", ")", ":", "# Default implementation only allows for frame info. Can override to put more info", "if", "isinstance", "(", "epoch_name", ",", "str", ")", ":", "self", ".", "_epochs",...
This function adds an epoch to your recording extractor that tracks a certain time period in your recording. It is stored in an internal dictionary of start and end frame tuples. Parameters ---------- epoch_name: str The name of the epoch to be added start_frame: int The start frame of the epoch to be added (inclusive) end_frame: int The end frame of the epoch to be added (exclusive)
[ "This", "function", "adds", "an", "epoch", "to", "your", "recording", "extractor", "that", "tracks", "a", "certain", "time", "period", "in", "your", "recording", ".", "It", "is", "stored", "in", "an", "internal", "dictionary", "of", "start", "and", "end", ...
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L405-L424
train
30,561
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.remove_epoch
def remove_epoch(self, epoch_name): '''This function removes an epoch from your recording extractor. Parameters ---------- epoch_name: str The name of the epoch to be removed ''' if isinstance(epoch_name, str): if epoch_name in list(self._epochs.keys()): del self._epochs[epoch_name] else: raise ValueError("This epoch has not been added") else: raise ValueError("epoch_name must be a string")
python
def remove_epoch(self, epoch_name): '''This function removes an epoch from your recording extractor. Parameters ---------- epoch_name: str The name of the epoch to be removed ''' if isinstance(epoch_name, str): if epoch_name in list(self._epochs.keys()): del self._epochs[epoch_name] else: raise ValueError("This epoch has not been added") else: raise ValueError("epoch_name must be a string")
[ "def", "remove_epoch", "(", "self", ",", "epoch_name", ")", ":", "if", "isinstance", "(", "epoch_name", ",", "str", ")", ":", "if", "epoch_name", "in", "list", "(", "self", ".", "_epochs", ".", "keys", "(", ")", ")", ":", "del", "self", ".", "_epochs...
This function removes an epoch from your recording extractor. Parameters ---------- epoch_name: str The name of the epoch to be removed
[ "This", "function", "removes", "an", "epoch", "from", "your", "recording", "extractor", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L426-L440
train
30,562
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_epoch_names
def get_epoch_names(self): '''This function returns a list of all the epoch names in your recording Returns ---------- epoch_names: list List of epoch names in the recording extractor ''' epoch_names = list(self._epochs.keys()) if not epoch_names: pass else: epoch_start_frames = [] for epoch_name in epoch_names: epoch_info = self.get_epoch_info(epoch_name) start_frame = epoch_info['start_frame'] epoch_start_frames.append(start_frame) epoch_names = [epoch_name for _, epoch_name in sorted(zip(epoch_start_frames, epoch_names))] return epoch_names
python
def get_epoch_names(self): '''This function returns a list of all the epoch names in your recording Returns ---------- epoch_names: list List of epoch names in the recording extractor ''' epoch_names = list(self._epochs.keys()) if not epoch_names: pass else: epoch_start_frames = [] for epoch_name in epoch_names: epoch_info = self.get_epoch_info(epoch_name) start_frame = epoch_info['start_frame'] epoch_start_frames.append(start_frame) epoch_names = [epoch_name for _, epoch_name in sorted(zip(epoch_start_frames, epoch_names))] return epoch_names
[ "def", "get_epoch_names", "(", "self", ")", ":", "epoch_names", "=", "list", "(", "self", ".", "_epochs", ".", "keys", "(", ")", ")", "if", "not", "epoch_names", ":", "pass", "else", ":", "epoch_start_frames", "=", "[", "]", "for", "epoch_name", "in", ...
This function returns a list of all the epoch names in your recording Returns ---------- epoch_names: list List of epoch names in the recording extractor
[ "This", "function", "returns", "a", "list", "of", "all", "the", "epoch", "names", "in", "your", "recording" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L442-L460
train
30,563
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_epoch_info
def get_epoch_info(self, epoch_name): '''This function returns the start frame and end frame of the epoch in a dict. Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_info: dict A dict containing the start frame and end frame of the epoch ''' # Default (Can add more information into each epoch in subclass) if isinstance(epoch_name, str): if epoch_name in list(self._epochs.keys()): epoch_info = self._epochs[epoch_name] return epoch_info else: raise ValueError("This epoch has not been added") else: raise ValueError("epoch_name must be a string")
python
def get_epoch_info(self, epoch_name): '''This function returns the start frame and end frame of the epoch in a dict. Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_info: dict A dict containing the start frame and end frame of the epoch ''' # Default (Can add more information into each epoch in subclass) if isinstance(epoch_name, str): if epoch_name in list(self._epochs.keys()): epoch_info = self._epochs[epoch_name] return epoch_info else: raise ValueError("This epoch has not been added") else: raise ValueError("epoch_name must be a string")
[ "def", "get_epoch_info", "(", "self", ",", "epoch_name", ")", ":", "# Default (Can add more information into each epoch in subclass)", "if", "isinstance", "(", "epoch_name", ",", "str", ")", ":", "if", "epoch_name", "in", "list", "(", "self", ".", "_epochs", ".", ...
This function returns the start frame and end frame of the epoch in a dict. Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_info: dict A dict containing the start frame and end frame of the epoch
[ "This", "function", "returns", "the", "start", "frame", "and", "end", "frame", "of", "the", "epoch", "in", "a", "dict", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L462-L484
train
30,564
SpikeInterface/spikeextractors
spikeextractors/RecordingExtractor.py
RecordingExtractor.get_epoch
def get_epoch(self, epoch_name): '''This function returns a SubRecordingExtractor which is a view to the given epoch Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_extractor: SubRecordingExtractor A SubRecordingExtractor which is a view to the given epoch ''' epoch_info = self.get_epoch_info(epoch_name) start_frame = epoch_info['start_frame'] end_frame = epoch_info['end_frame'] from .SubRecordingExtractor import SubRecordingExtractor return SubRecordingExtractor(parent_recording=self, start_frame=start_frame, end_frame=end_frame)
python
def get_epoch(self, epoch_name): '''This function returns a SubRecordingExtractor which is a view to the given epoch Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_extractor: SubRecordingExtractor A SubRecordingExtractor which is a view to the given epoch ''' epoch_info = self.get_epoch_info(epoch_name) start_frame = epoch_info['start_frame'] end_frame = epoch_info['end_frame'] from .SubRecordingExtractor import SubRecordingExtractor return SubRecordingExtractor(parent_recording=self, start_frame=start_frame, end_frame=end_frame)
[ "def", "get_epoch", "(", "self", ",", "epoch_name", ")", ":", "epoch_info", "=", "self", ".", "get_epoch_info", "(", "epoch_name", ")", "start_frame", "=", "epoch_info", "[", "'start_frame'", "]", "end_frame", "=", "epoch_info", "[", "'end_frame'", "]", "from"...
This function returns a SubRecordingExtractor which is a view to the given epoch Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_extractor: SubRecordingExtractor A SubRecordingExtractor which is a view to the given epoch
[ "This", "function", "returns", "a", "SubRecordingExtractor", "which", "is", "a", "view", "to", "the", "given", "epoch" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/RecordingExtractor.py#L486-L505
train
30,565
SpikeInterface/spikeextractors
spikeextractors/CurationSortingExtractor.py
CurationSortingExtractor.exclude_units
def exclude_units(self, unit_ids): '''This function deletes roots from the curation tree according to the given unit_ids Parameters ---------- unit_ids: list The unit ids to be excluded ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) if(set(unit_ids).issubset(set(root_ids)) and len(unit_ids) > 0): indices_to_be_deleted = [] for unit_id in unit_ids: root_index = root_ids.index(unit_id) indices_to_be_deleted.append(root_index) if unit_id in self._unit_features: del self._unit_features[unit_id] self._roots = [self._roots[i] for i,_ in enumerate(root_ids) if i not in indices_to_be_deleted] else: raise ValueError(str(unit_ids) + " has one or more invalid unit ids")
python
def exclude_units(self, unit_ids): '''This function deletes roots from the curation tree according to the given unit_ids Parameters ---------- unit_ids: list The unit ids to be excluded ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) if(set(unit_ids).issubset(set(root_ids)) and len(unit_ids) > 0): indices_to_be_deleted = [] for unit_id in unit_ids: root_index = root_ids.index(unit_id) indices_to_be_deleted.append(root_index) if unit_id in self._unit_features: del self._unit_features[unit_id] self._roots = [self._roots[i] for i,_ in enumerate(root_ids) if i not in indices_to_be_deleted] else: raise ValueError(str(unit_ids) + " has one or more invalid unit ids")
[ "def", "exclude_units", "(", "self", ",", "unit_ids", ")", ":", "root_ids", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_roots", ")", ")", ":", "root_id", "=", "self", ".", "_roots", "[", "i", "]", ".", "unit_id", "ro...
This function deletes roots from the curation tree according to the given unit_ids Parameters ---------- unit_ids: list The unit ids to be excluded
[ "This", "function", "deletes", "roots", "from", "the", "curation", "tree", "according", "to", "the", "given", "unit_ids" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/CurationSortingExtractor.py#L73-L95
train
30,566
SpikeInterface/spikeextractors
spikeextractors/CurationSortingExtractor.py
CurationSortingExtractor.merge_units
def merge_units(self, unit_ids): '''This function merges two roots from the curation tree according to the given unit_ids. It creates a new unit_id and root that has the merged roots as children. Parameters ---------- unit_ids: list The unit ids to be merged ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) indices_to_be_deleted = [] if(set(unit_ids).issubset(set(root_ids)) and len(unit_ids) > 1): #Find all unique feature names and create all feature lists all_feature_names = [] for unit_id in unit_ids: feature_names = self.get_unit_spike_feature_names(unit_id) all_feature_names.append(feature_names) shared_feature_names = set(all_feature_names[0]) for feature_names in all_feature_names[1:]: shared_feature_names.intersection_update(feature_names) shared_feature_names = list(shared_feature_names) shared_features = [] for i in range(len(shared_feature_names)): shared_features.append([]) new_root_id = max(self._all_ids)+1 self._all_ids.append(new_root_id) new_root = Unit(new_root_id) all_spike_trains = [] for unit_id in unit_ids: root_index = root_ids.index(unit_id) new_root.add_child(self._roots[root_index]) all_spike_trains.append(self._roots[root_index].get_spike_train()) for i, feature_name in enumerate(shared_feature_names): features = self.get_unit_spike_features(unit_id, feature_name) shared_features[i].append(features) del self._unit_features[unit_id] self._roots[root_index].set_spike_train(np.asarray([])) #clear spiketrain indices_to_be_deleted.append(root_index) all_spike_trains = np.concatenate(all_spike_trains) sort_indices = np.argsort(all_spike_trains) new_root.set_spike_train(np.asarray(all_spike_trains)[sort_indices]) del all_spike_trains self._roots = [self._roots[i] for i,_ in enumerate(root_ids) if i not in indices_to_be_deleted] self._roots.append(new_root) for i, feature_name in enumerate(shared_feature_names): self.set_unit_spike_features(new_root_id, feature_name, np.concatenate(shared_features[i])[sort_indices]) else: raise ValueError(str(unit_ids) + " has one or more invalid unit ids")
python
def merge_units(self, unit_ids): '''This function merges two roots from the curation tree according to the given unit_ids. It creates a new unit_id and root that has the merged roots as children. Parameters ---------- unit_ids: list The unit ids to be merged ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) indices_to_be_deleted = [] if(set(unit_ids).issubset(set(root_ids)) and len(unit_ids) > 1): #Find all unique feature names and create all feature lists all_feature_names = [] for unit_id in unit_ids: feature_names = self.get_unit_spike_feature_names(unit_id) all_feature_names.append(feature_names) shared_feature_names = set(all_feature_names[0]) for feature_names in all_feature_names[1:]: shared_feature_names.intersection_update(feature_names) shared_feature_names = list(shared_feature_names) shared_features = [] for i in range(len(shared_feature_names)): shared_features.append([]) new_root_id = max(self._all_ids)+1 self._all_ids.append(new_root_id) new_root = Unit(new_root_id) all_spike_trains = [] for unit_id in unit_ids: root_index = root_ids.index(unit_id) new_root.add_child(self._roots[root_index]) all_spike_trains.append(self._roots[root_index].get_spike_train()) for i, feature_name in enumerate(shared_feature_names): features = self.get_unit_spike_features(unit_id, feature_name) shared_features[i].append(features) del self._unit_features[unit_id] self._roots[root_index].set_spike_train(np.asarray([])) #clear spiketrain indices_to_be_deleted.append(root_index) all_spike_trains = np.concatenate(all_spike_trains) sort_indices = np.argsort(all_spike_trains) new_root.set_spike_train(np.asarray(all_spike_trains)[sort_indices]) del all_spike_trains self._roots = [self._roots[i] for i,_ in enumerate(root_ids) if i not in indices_to_be_deleted] self._roots.append(new_root) for i, feature_name in enumerate(shared_feature_names): self.set_unit_spike_features(new_root_id, feature_name, np.concatenate(shared_features[i])[sort_indices]) else: raise ValueError(str(unit_ids) + " has one or more invalid unit ids")
[ "def", "merge_units", "(", "self", ",", "unit_ids", ")", ":", "root_ids", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_roots", ")", ")", ":", "root_id", "=", "self", ".", "_roots", "[", "i", "]", ".", "unit_id", "root...
This function merges two roots from the curation tree according to the given unit_ids. It creates a new unit_id and root that has the merged roots as children. Parameters ---------- unit_ids: list The unit ids to be merged
[ "This", "function", "merges", "two", "roots", "from", "the", "curation", "tree", "according", "to", "the", "given", "unit_ids", ".", "It", "creates", "a", "new", "unit_id", "and", "root", "that", "has", "the", "merged", "roots", "as", "children", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/CurationSortingExtractor.py#L97-L151
train
30,567
SpikeInterface/spikeextractors
spikeextractors/CurationSortingExtractor.py
CurationSortingExtractor.split_unit
def split_unit(self, unit_id, indices): '''This function splits a root from the curation tree according to the given unit_id and indices. It creates two new unit_ids and roots that have the split root as a child. This function splits the spike train of the root by the given indices. Parameters ---------- unit_id: int The unit id to be split indices: list The indices of the unit spike train at which the spike train will be split. ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) if(unit_id in root_ids): indices_1 = np.sort(np.asarray(list(set(indices)))) root_index = root_ids.index(unit_id) new_child = self._roots[root_index] original_spike_train = self._roots[root_index].get_spike_train() try: spike_train_1 = original_spike_train[indices_1] except IndexError: print(str(indices) + " out of bounds for the spike train of " + str(unit_id)) indices_2 = list(set(range(len(original_spike_train))) - set(indices_1)) spike_train_2 = original_spike_train[indices_2] del original_spike_train new_root_1_id = max(self._all_ids)+1 self._all_ids.append(new_root_1_id) new_root_1 = Unit(new_root_1_id) new_root_1.add_child(new_child) new_root_1.set_spike_train(spike_train_1) new_root_2_id = max(self._all_ids)+1 self._all_ids.append(new_root_2_id) new_root_2 = Unit(new_root_2_id) new_root_2.add_child(new_child) new_root_2.set_spike_train(spike_train_2) self._roots.append(new_root_1) self._roots.append(new_root_2) for feature_name in self.get_unit_spike_feature_names(unit_id): full_features = self.get_unit_spike_features(unit_id, feature_name) self.set_unit_spike_features(new_root_1_id, feature_name, full_features[indices_1]) self.set_unit_spike_features(new_root_2_id, feature_name, full_features[indices_2]) del self._unit_features[unit_id] del self._roots[root_index] else: raise ValueError(str(unit_id) + " non-valid unit id")
python
def split_unit(self, unit_id, indices): '''This function splits a root from the curation tree according to the given unit_id and indices. It creates two new unit_ids and roots that have the split root as a child. This function splits the spike train of the root by the given indices. Parameters ---------- unit_id: int The unit id to be split indices: list The indices of the unit spike train at which the spike train will be split. ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) if(unit_id in root_ids): indices_1 = np.sort(np.asarray(list(set(indices)))) root_index = root_ids.index(unit_id) new_child = self._roots[root_index] original_spike_train = self._roots[root_index].get_spike_train() try: spike_train_1 = original_spike_train[indices_1] except IndexError: print(str(indices) + " out of bounds for the spike train of " + str(unit_id)) indices_2 = list(set(range(len(original_spike_train))) - set(indices_1)) spike_train_2 = original_spike_train[indices_2] del original_spike_train new_root_1_id = max(self._all_ids)+1 self._all_ids.append(new_root_1_id) new_root_1 = Unit(new_root_1_id) new_root_1.add_child(new_child) new_root_1.set_spike_train(spike_train_1) new_root_2_id = max(self._all_ids)+1 self._all_ids.append(new_root_2_id) new_root_2 = Unit(new_root_2_id) new_root_2.add_child(new_child) new_root_2.set_spike_train(spike_train_2) self._roots.append(new_root_1) self._roots.append(new_root_2) for feature_name in self.get_unit_spike_feature_names(unit_id): full_features = self.get_unit_spike_features(unit_id, feature_name) self.set_unit_spike_features(new_root_1_id, feature_name, full_features[indices_1]) self.set_unit_spike_features(new_root_2_id, feature_name, full_features[indices_2]) del self._unit_features[unit_id] del self._roots[root_index] else: raise ValueError(str(unit_id) + " non-valid unit id")
[ "def", "split_unit", "(", "self", ",", "unit_id", ",", "indices", ")", ":", "root_ids", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_roots", ")", ")", ":", "root_id", "=", "self", ".", "_roots", "[", "i", "]", ".", ...
This function splits a root from the curation tree according to the given unit_id and indices. It creates two new unit_ids and roots that have the split root as a child. This function splits the spike train of the root by the given indices. Parameters ---------- unit_id: int The unit id to be split indices: list The indices of the unit spike train at which the spike train will be split.
[ "This", "function", "splits", "a", "root", "from", "the", "curation", "tree", "according", "to", "the", "given", "unit_id", "and", "indices", ".", "It", "creates", "two", "new", "unit_ids", "and", "roots", "that", "have", "the", "split", "root", "as", "a",...
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/CurationSortingExtractor.py#L153-L207
train
30,568
SpikeInterface/spikeextractors
spikeextractors/tools.py
read_python
def read_python(path): '''Parses python scripts in a dictionary Parameters ---------- path: str Path to file to parse Returns ------- metadata: dictionary containing parsed file ''' from six import exec_ path = Path(path).absolute() assert path.is_file() with path.open('r') as f: contents = f.read() metadata = {} exec_(contents, {}, metadata) metadata = {k.lower(): v for (k, v) in metadata.items()} return metadata
python
def read_python(path): '''Parses python scripts in a dictionary Parameters ---------- path: str Path to file to parse Returns ------- metadata: dictionary containing parsed file ''' from six import exec_ path = Path(path).absolute() assert path.is_file() with path.open('r') as f: contents = f.read() metadata = {} exec_(contents, {}, metadata) metadata = {k.lower(): v for (k, v) in metadata.items()} return metadata
[ "def", "read_python", "(", "path", ")", ":", "from", "six", "import", "exec_", "path", "=", "Path", "(", "path", ")", ".", "absolute", "(", ")", "assert", "path", ".", "is_file", "(", ")", "with", "path", ".", "open", "(", "'r'", ")", "as", "f", ...
Parses python scripts in a dictionary Parameters ---------- path: str Path to file to parse Returns ------- metadata: dictionary containing parsed file
[ "Parses", "python", "scripts", "in", "a", "dictionary" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/tools.py#L10-L32
train
30,569
SpikeInterface/spikeextractors
spikeextractors/tools.py
save_probe_file
def save_probe_file(recording, probe_file, format=None, radius=100, dimensions=None): '''Saves probe file from the channel information of the given recording extractor Parameters ---------- recording: RecordingExtractor The recording extractor to save probe file from probe_file: str file name of .prb or .csv file to save probe information to format: str (optional) Format for .prb file. It can be either 'klusta' or 'spyking_circus'. Default is None. ''' probe_file = Path(probe_file) if not probe_file.parent.is_dir(): probe_file.parent.mkdir() if probe_file.suffix == '.csv': # write csv probe file with probe_file.open('w') as f: if 'location' in recording.get_channel_property_names(): for chan in recording.get_channel_ids(): loc = recording.get_channel_property(chan, 'location') if len(loc) == 2: f.write(str(loc[0])) f.write(',') f.write(str(loc[1])) f.write('\n') elif len(loc) == 3: f.write(str(loc[0])) f.write(',') f.write(str(loc[1])) f.write(',') f.write(str(loc[2])) f.write('\n') else: raise AttributeError("Recording extractor needs to have " "'location' property to save .csv probe file") elif probe_file.suffix == '.prb': _export_prb_file(recording, probe_file, format, radius=radius, dimensions=dimensions) else: raise NotImplementedError("Only .csv and .prb probe files can be saved.")
python
def save_probe_file(recording, probe_file, format=None, radius=100, dimensions=None): '''Saves probe file from the channel information of the given recording extractor Parameters ---------- recording: RecordingExtractor The recording extractor to save probe file from probe_file: str file name of .prb or .csv file to save probe information to format: str (optional) Format for .prb file. It can be either 'klusta' or 'spyking_circus'. Default is None. ''' probe_file = Path(probe_file) if not probe_file.parent.is_dir(): probe_file.parent.mkdir() if probe_file.suffix == '.csv': # write csv probe file with probe_file.open('w') as f: if 'location' in recording.get_channel_property_names(): for chan in recording.get_channel_ids(): loc = recording.get_channel_property(chan, 'location') if len(loc) == 2: f.write(str(loc[0])) f.write(',') f.write(str(loc[1])) f.write('\n') elif len(loc) == 3: f.write(str(loc[0])) f.write(',') f.write(str(loc[1])) f.write(',') f.write(str(loc[2])) f.write('\n') else: raise AttributeError("Recording extractor needs to have " "'location' property to save .csv probe file") elif probe_file.suffix == '.prb': _export_prb_file(recording, probe_file, format, radius=radius, dimensions=dimensions) else: raise NotImplementedError("Only .csv and .prb probe files can be saved.")
[ "def", "save_probe_file", "(", "recording", ",", "probe_file", ",", "format", "=", "None", ",", "radius", "=", "100", ",", "dimensions", "=", "None", ")", ":", "probe_file", "=", "Path", "(", "probe_file", ")", "if", "not", "probe_file", ".", "parent", "...
Saves probe file from the channel information of the given recording extractor Parameters ---------- recording: RecordingExtractor The recording extractor to save probe file from probe_file: str file name of .prb or .csv file to save probe information to format: str (optional) Format for .prb file. It can be either 'klusta' or 'spyking_circus'. Default is None.
[ "Saves", "probe", "file", "from", "the", "channel", "information", "of", "the", "given", "recording", "extractor" ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/tools.py#L139-L180
train
30,570
SpikeInterface/spikeextractors
spikeextractors/tools.py
write_binary_dat_format
def write_binary_dat_format(recording, save_path, time_axis=0, dtype=None, chunksize=None): '''Saves the traces of a recording extractor in binary .dat format. Parameters ---------- recording: RecordingExtractor The recording extractor object to be saved in .dat format save_path: str The path to the file. time_axis: 0 (default) or 1 If 0 then traces are transposed to ensure (nb_sample, nb_channel) in the file. If 1, the traces shape (nb_channel, nb_sample) is kept in the file. dtype: dtype Type of the saved data. Default float32 chunksize: None or int If not None then the copy done by chunk size. Thi avoid to much memory consumption for big files. Returns ------- ''' save_path = Path(save_path) if save_path.suffix == '': # when suffix is already raw/bin/dat do not change it. save_path = save_path.parent / (save_path.name + '.dat') if chunksize is None: traces = recording.get_traces() if dtype is not None: traces = traces.astype(dtype) if time_axis == 0: traces = traces.T with save_path.open('wb') as f: traces.tofile(f) else: assert time_axis ==0, 'chunked writting work only with time_axis 0' n_sample = recording.get_num_frames() n_chan = recording.get_num_channels() n_chunk = n_sample // chunksize if n_sample % chunksize > 0: n_chunk += 1 with save_path.open('wb') as f: for i in range(n_chunk): traces = recording.get_traces(start_frame=i*chunksize, end_frame=min((i+1)*chunksize, n_sample)) if dtype is not None: traces = traces.astype(dtype) if time_axis == 0: traces = traces.T f.write(traces.tobytes()) return save_path
python
def write_binary_dat_format(recording, save_path, time_axis=0, dtype=None, chunksize=None): '''Saves the traces of a recording extractor in binary .dat format. Parameters ---------- recording: RecordingExtractor The recording extractor object to be saved in .dat format save_path: str The path to the file. time_axis: 0 (default) or 1 If 0 then traces are transposed to ensure (nb_sample, nb_channel) in the file. If 1, the traces shape (nb_channel, nb_sample) is kept in the file. dtype: dtype Type of the saved data. Default float32 chunksize: None or int If not None then the copy done by chunk size. Thi avoid to much memory consumption for big files. Returns ------- ''' save_path = Path(save_path) if save_path.suffix == '': # when suffix is already raw/bin/dat do not change it. save_path = save_path.parent / (save_path.name + '.dat') if chunksize is None: traces = recording.get_traces() if dtype is not None: traces = traces.astype(dtype) if time_axis == 0: traces = traces.T with save_path.open('wb') as f: traces.tofile(f) else: assert time_axis ==0, 'chunked writting work only with time_axis 0' n_sample = recording.get_num_frames() n_chan = recording.get_num_channels() n_chunk = n_sample // chunksize if n_sample % chunksize > 0: n_chunk += 1 with save_path.open('wb') as f: for i in range(n_chunk): traces = recording.get_traces(start_frame=i*chunksize, end_frame=min((i+1)*chunksize, n_sample)) if dtype is not None: traces = traces.astype(dtype) if time_axis == 0: traces = traces.T f.write(traces.tobytes()) return save_path
[ "def", "write_binary_dat_format", "(", "recording", ",", "save_path", ",", "time_axis", "=", "0", ",", "dtype", "=", "None", ",", "chunksize", "=", "None", ")", ":", "save_path", "=", "Path", "(", "save_path", ")", "if", "save_path", ".", "suffix", "==", ...
Saves the traces of a recording extractor in binary .dat format. Parameters ---------- recording: RecordingExtractor The recording extractor object to be saved in .dat format save_path: str The path to the file. time_axis: 0 (default) or 1 If 0 then traces are transposed to ensure (nb_sample, nb_channel) in the file. If 1, the traces shape (nb_channel, nb_sample) is kept in the file. dtype: dtype Type of the saved data. Default float32 chunksize: None or int If not None then the copy done by chunk size. Thi avoid to much memory consumption for big files. Returns -------
[ "Saves", "the", "traces", "of", "a", "recording", "extractor", "in", "binary", ".", "dat", "format", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/tools.py#L183-L233
train
30,571
SpikeInterface/spikeextractors
spikeextractors/extractors/biocamrecordingextractor/biocamrecordingextractor.py
openBiocamFile
def openBiocamFile(filename, verbose=False): """Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller.""" rf = h5py.File(filename, 'r') # Read recording variables recVars = rf.require_group('3BRecInfo/3BRecVars/') # bitDepth = recVars['BitDepth'].value[0] # maxV = recVars['MaxVolt'].value[0] # minV = recVars['MinVolt'].value[0] nFrames = recVars['NRecFrames'][0] samplingRate = recVars['SamplingRate'][0] signalInv = recVars['SignalInversion'][0] # Read chip variables chipVars = rf.require_group('3BRecInfo/3BMeaChip/') nCols = chipVars['NCols'][0] # Get the actual number of channels used in the recording file_format = rf['3BData'].attrs.get('Version') if file_format == 100: nRecCh = len(rf['3BData/Raw'][0]) elif file_format == 101: nRecCh = int(1. * rf['3BData/Raw'].shape[0] / nFrames) else: raise Exception('Unknown data file format.') if verbose: print('# 3Brain data format:', file_format, 'signal inversion', signalInv) print('# signal range: ', recVars['MinVolt'][0], '- ', recVars['MaxVolt'][0]) print('# channels: ', nRecCh) print('# frames: ', nFrames) print('# sampling rate: ', samplingRate) # get channel locations r = rf['3BRecInfo/3BMeaStreams/Raw/Chs'][()]['Row'] c = rf['3BRecInfo/3BMeaStreams/Raw/Chs'][()]['Col'] rawIndices = np.vstack((r, c)).T # assign channel numbers chIndices = np.array([(x - 1) + (y - 1) * nCols for (y, x) in rawIndices]) # determine correct function to read data if verbose: print("# Signal inversion looks like " + str(signalInv) + ", guessing correct method for data access.") print("# If your results look wrong, signal polarity is may be wrong.") if file_format == 100: if signalInv == -1: read_function = readHDF5t_100 else: read_function = readHDF5t_100_i else: if signalInv == -1: read_function = readHDF5t_101_i else: read_function = readHDF5t_101 return (rf, nFrames, samplingRate, nRecCh, chIndices, file_format, signalInv, rawIndices, read_function)
python
def openBiocamFile(filename, verbose=False): """Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller.""" rf = h5py.File(filename, 'r') # Read recording variables recVars = rf.require_group('3BRecInfo/3BRecVars/') # bitDepth = recVars['BitDepth'].value[0] # maxV = recVars['MaxVolt'].value[0] # minV = recVars['MinVolt'].value[0] nFrames = recVars['NRecFrames'][0] samplingRate = recVars['SamplingRate'][0] signalInv = recVars['SignalInversion'][0] # Read chip variables chipVars = rf.require_group('3BRecInfo/3BMeaChip/') nCols = chipVars['NCols'][0] # Get the actual number of channels used in the recording file_format = rf['3BData'].attrs.get('Version') if file_format == 100: nRecCh = len(rf['3BData/Raw'][0]) elif file_format == 101: nRecCh = int(1. * rf['3BData/Raw'].shape[0] / nFrames) else: raise Exception('Unknown data file format.') if verbose: print('# 3Brain data format:', file_format, 'signal inversion', signalInv) print('# signal range: ', recVars['MinVolt'][0], '- ', recVars['MaxVolt'][0]) print('# channels: ', nRecCh) print('# frames: ', nFrames) print('# sampling rate: ', samplingRate) # get channel locations r = rf['3BRecInfo/3BMeaStreams/Raw/Chs'][()]['Row'] c = rf['3BRecInfo/3BMeaStreams/Raw/Chs'][()]['Col'] rawIndices = np.vstack((r, c)).T # assign channel numbers chIndices = np.array([(x - 1) + (y - 1) * nCols for (y, x) in rawIndices]) # determine correct function to read data if verbose: print("# Signal inversion looks like " + str(signalInv) + ", guessing correct method for data access.") print("# If your results look wrong, signal polarity is may be wrong.") if file_format == 100: if signalInv == -1: read_function = readHDF5t_100 else: read_function = readHDF5t_100_i else: if signalInv == -1: read_function = readHDF5t_101_i else: read_function = readHDF5t_101 return (rf, nFrames, samplingRate, nRecCh, chIndices, file_format, signalInv, rawIndices, read_function)
[ "def", "openBiocamFile", "(", "filename", ",", "verbose", "=", "False", ")", ":", "rf", "=", "h5py", ".", "File", "(", "filename", ",", "'r'", ")", "# Read recording variables", "recVars", "=", "rf", ".", "require_group", "(", "'3BRecInfo/3BRecVars/'", ")", ...
Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller.
[ "Open", "a", "Biocam", "hdf5", "file", "read", "and", "return", "the", "recording", "info", "pick", "te", "correct", "method", "to", "access", "raw", "data", "and", "return", "this", "to", "the", "caller", "." ]
cbe3b8778a215f0bbd743af8b306856a87e438e1
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/extractors/biocamrecordingextractor/biocamrecordingextractor.py#L94-L143
train
30,572
quantmind/ccy
ccy/core/country.py
countries
def countries(): ''' get country dictionar from pytz and add some extra. ''' global _countries if not _countries: v = {} _countries = v try: from pytz import country_names for k, n in country_names.items(): v[k.upper()] = n except Exception: pass return _countries
python
def countries(): ''' get country dictionar from pytz and add some extra. ''' global _countries if not _countries: v = {} _countries = v try: from pytz import country_names for k, n in country_names.items(): v[k.upper()] = n except Exception: pass return _countries
[ "def", "countries", "(", ")", ":", "global", "_countries", "if", "not", "_countries", ":", "v", "=", "{", "}", "_countries", "=", "v", "try", ":", "from", "pytz", "import", "country_names", "for", "k", ",", "n", "in", "country_names", ".", "items", "("...
get country dictionar from pytz and add some extra.
[ "get", "country", "dictionar", "from", "pytz", "and", "add", "some", "extra", "." ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L41-L55
train
30,573
quantmind/ccy
ccy/core/country.py
countryccys
def countryccys(): ''' Create a dictionary with keys given by countries ISO codes and values given by their currencies ''' global _country_ccys if not _country_ccys: v = {} _country_ccys = v ccys = currencydb() for c in eurozone: v[c] = 'EUR' for c in ccys.values(): if c.default_country: v[c.default_country] = c.code return _country_ccys
python
def countryccys(): ''' Create a dictionary with keys given by countries ISO codes and values given by their currencies ''' global _country_ccys if not _country_ccys: v = {} _country_ccys = v ccys = currencydb() for c in eurozone: v[c] = 'EUR' for c in ccys.values(): if c.default_country: v[c.default_country] = c.code return _country_ccys
[ "def", "countryccys", "(", ")", ":", "global", "_country_ccys", "if", "not", "_country_ccys", ":", "v", "=", "{", "}", "_country_ccys", "=", "v", "ccys", "=", "currencydb", "(", ")", "for", "c", "in", "eurozone", ":", "v", "[", "c", "]", "=", "'EUR'"...
Create a dictionary with keys given by countries ISO codes and values given by their currencies
[ "Create", "a", "dictionary", "with", "keys", "given", "by", "countries", "ISO", "codes", "and", "values", "given", "by", "their", "currencies" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L58-L73
train
30,574
quantmind/ccy
ccy/core/country.py
set_country_map
def set_country_map(cfrom, cto, name=None, replace=True): ''' Set a mapping between a country code to another code ''' global _country_maps cdb = countries() cfrom = str(cfrom).upper() c = cdb.get(cfrom) if c: if name: c = name cto = str(cto).upper() if cto in cdb: raise CountryError('Country %s already in database' % cto) cdb[cto] = c _country_maps[cfrom] = cto ccys = currencydb() cccys = countryccys() ccy = cccys[cfrom] cccys[cto] = ccy # If set, remove cfrom from database if replace: ccy = ccys.get(ccy) ccy.default_country = cto cdb.pop(cfrom) cccys.pop(cfrom) else: raise CountryError('Country %s not in database' % c)
python
def set_country_map(cfrom, cto, name=None, replace=True): ''' Set a mapping between a country code to another code ''' global _country_maps cdb = countries() cfrom = str(cfrom).upper() c = cdb.get(cfrom) if c: if name: c = name cto = str(cto).upper() if cto in cdb: raise CountryError('Country %s already in database' % cto) cdb[cto] = c _country_maps[cfrom] = cto ccys = currencydb() cccys = countryccys() ccy = cccys[cfrom] cccys[cto] = ccy # If set, remove cfrom from database if replace: ccy = ccys.get(ccy) ccy.default_country = cto cdb.pop(cfrom) cccys.pop(cfrom) else: raise CountryError('Country %s not in database' % c)
[ "def", "set_country_map", "(", "cfrom", ",", "cto", ",", "name", "=", "None", ",", "replace", "=", "True", ")", ":", "global", "_country_maps", "cdb", "=", "countries", "(", ")", "cfrom", "=", "str", "(", "cfrom", ")", ".", "upper", "(", ")", "c", ...
Set a mapping between a country code to another code
[ "Set", "a", "mapping", "between", "a", "country", "code", "to", "another", "code" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L76-L104
train
30,575
quantmind/ccy
ccy/core/country.py
set_new_country
def set_new_country(code, ccy, name): ''' Add new country code to database ''' code = str(code).upper() cdb = countries() if code in cdb: raise CountryError('Country %s already in database' % code) ccys = currencydb() ccy = str(ccy).upper() if ccy not in ccys: raise CountryError('Currency %s not in database' % ccy) cdb[code] = str(name) cccys = countryccys() cccys[code] = ccy
python
def set_new_country(code, ccy, name): ''' Add new country code to database ''' code = str(code).upper() cdb = countries() if code in cdb: raise CountryError('Country %s already in database' % code) ccys = currencydb() ccy = str(ccy).upper() if ccy not in ccys: raise CountryError('Currency %s not in database' % ccy) cdb[code] = str(name) cccys = countryccys() cccys[code] = ccy
[ "def", "set_new_country", "(", "code", ",", "ccy", ",", "name", ")", ":", "code", "=", "str", "(", "code", ")", ".", "upper", "(", ")", "cdb", "=", "countries", "(", ")", "if", "code", "in", "cdb", ":", "raise", "CountryError", "(", "'Country %s alre...
Add new country code to database
[ "Add", "new", "country", "code", "to", "database" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L107-L121
train
30,576
quantmind/ccy
docs/_ext/table.py
TableDirective.run
def run(self): """ Implements the directive """ # Get content and options data_path = self.arguments[0] header = self.options.get('header', True) bits = data_path.split('.') name = bits[-1] path = '.'.join(bits[:-1]) node = table_node() code = None try: module = import_module(path) except Exception: code = '<p>Could not import %s</p>' % path try: callable = getattr(module, name) except Exception: code = 'Could not import %s from %s' % (name, path) if not code: data = callable() table = ['<table>'] if header: headers, data = data[0], data[1:] table.append('<thead>') tr = ['<tr>'] for head in headers: tr.append('<th>%s</th>' % head) tr.append('</tr>') table.append(''.join(tr)) table.append('</thead>') table.append('</tbody>') for row in data: tr = ['<tr>'] for c in row: tr.append('<td>%s</td>' % c) tr.append('</tr>') table.append(''.join(tr)) table.append('</tbody>') table.append('</table>') code = '\n'.join(table) node['code'] = code return [node]
python
def run(self): """ Implements the directive """ # Get content and options data_path = self.arguments[0] header = self.options.get('header', True) bits = data_path.split('.') name = bits[-1] path = '.'.join(bits[:-1]) node = table_node() code = None try: module = import_module(path) except Exception: code = '<p>Could not import %s</p>' % path try: callable = getattr(module, name) except Exception: code = 'Could not import %s from %s' % (name, path) if not code: data = callable() table = ['<table>'] if header: headers, data = data[0], data[1:] table.append('<thead>') tr = ['<tr>'] for head in headers: tr.append('<th>%s</th>' % head) tr.append('</tr>') table.append(''.join(tr)) table.append('</thead>') table.append('</tbody>') for row in data: tr = ['<tr>'] for c in row: tr.append('<td>%s</td>' % c) tr.append('</tr>') table.append(''.join(tr)) table.append('</tbody>') table.append('</table>') code = '\n'.join(table) node['code'] = code return [node]
[ "def", "run", "(", "self", ")", ":", "# Get content and options", "data_path", "=", "self", ".", "arguments", "[", "0", "]", "header", "=", "self", ".", "options", ".", "get", "(", "'header'", ",", "True", ")", "bits", "=", "data_path", ".", "split", "...
Implements the directive
[ "Implements", "the", "directive" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/docs/_ext/table.py#L35-L78
train
30,577
quantmind/ccy
ccy/dates/converters.py
todate
def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. If it fails it raise a ValueError exception. ''' if not val: raise ValueError("Value not provided") if isinstance(val, datetime): return val.date() elif isinstance(val, date): return val else: try: ival = int(val) sval = str(ival) if len(sval) == 8: return yyyymmdd2date(val) elif len(sval) == 5: return juldate2date(val) else: raise ValueError except Exception: # Try to convert using the parsing algorithm try: return date_from_string(val).date() except Exception: raise ValueError("Could not convert %s to date" % val)
python
def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. If it fails it raise a ValueError exception. ''' if not val: raise ValueError("Value not provided") if isinstance(val, datetime): return val.date() elif isinstance(val, date): return val else: try: ival = int(val) sval = str(ival) if len(sval) == 8: return yyyymmdd2date(val) elif len(sval) == 5: return juldate2date(val) else: raise ValueError except Exception: # Try to convert using the parsing algorithm try: return date_from_string(val).date() except Exception: raise ValueError("Could not convert %s to date" % val)
[ "def", "todate", "(", "val", ")", ":", "if", "not", "val", ":", "raise", "ValueError", "(", "\"Value not provided\"", ")", "if", "isinstance", "(", "val", ",", "datetime", ")", ":", "return", "val", ".", "date", "(", ")", "elif", "isinstance", "(", "va...
Convert val to a datetime.date instance by trying several conversion algorithm. If it fails it raise a ValueError exception.
[ "Convert", "val", "to", "a", "datetime", ".", "date", "instance", "by", "trying", "several", "conversion", "algorithm", ".", "If", "it", "fails", "it", "raise", "a", "ValueError", "exception", "." ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/converters.py#L12-L38
train
30,578
quantmind/ccy
ccy/dates/period.py
Period.components
def components(self): '''The period string''' p = '' neg = self.totaldays < 0 y = self.years m = self.months w = self.weeks d = self.days if y: p = '%sY' % abs(y) if m: p = '%s%sM' % (p, abs(m)) if w: p = '%s%sW' % (p, abs(w)) if d: p = '%s%sD' % (p, abs(d)) return '-'+p if neg else p
python
def components(self): '''The period string''' p = '' neg = self.totaldays < 0 y = self.years m = self.months w = self.weeks d = self.days if y: p = '%sY' % abs(y) if m: p = '%s%sM' % (p, abs(m)) if w: p = '%s%sW' % (p, abs(w)) if d: p = '%s%sD' % (p, abs(d)) return '-'+p if neg else p
[ "def", "components", "(", "self", ")", ":", "p", "=", "''", "neg", "=", "self", ".", "totaldays", "<", "0", "y", "=", "self", ".", "years", "m", "=", "self", ".", "months", "w", "=", "self", ".", "weeks", "d", "=", "self", ".", "days", "if", ...
The period string
[ "The", "period", "string" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/period.py#L79-L95
train
30,579
quantmind/ccy
ccy/dates/period.py
Period.simple
def simple(self): '''A string representation with only one period delimiter.''' if self._days: return '%sD' % self.totaldays elif self.months: return '%sM' % self._months elif self.years: return '%sY' % self.years else: return ''
python
def simple(self): '''A string representation with only one period delimiter.''' if self._days: return '%sD' % self.totaldays elif self.months: return '%sM' % self._months elif self.years: return '%sY' % self.years else: return ''
[ "def", "simple", "(", "self", ")", ":", "if", "self", ".", "_days", ":", "return", "'%sD'", "%", "self", ".", "totaldays", "elif", "self", ".", "months", ":", "return", "'%sM'", "%", "self", ".", "_months", "elif", "self", ".", "years", ":", "return"...
A string representation with only one period delimiter.
[ "A", "string", "representation", "with", "only", "one", "period", "delimiter", "." ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/period.py#L97-L106
train
30,580
quantmind/ccy
ccy/core/currency.py
ccy.swap
def swap(self, c2): ''' put the order of currencies as market standard ''' inv = False c1 = self if c1.order > c2.order: ct = c1 c1 = c2 c2 = ct inv = True return inv, c1, c2
python
def swap(self, c2): ''' put the order of currencies as market standard ''' inv = False c1 = self if c1.order > c2.order: ct = c1 c1 = c2 c2 = ct inv = True return inv, c1, c2
[ "def", "swap", "(", "self", ",", "c2", ")", ":", "inv", "=", "False", "c1", "=", "self", "if", "c1", ".", "order", ">", "c2", ".", "order", ":", "ct", "=", "c1", "c1", "=", "c2", "c2", "=", "ct", "inv", "=", "True", "return", "inv", ",", "c...
put the order of currencies as market standard
[ "put", "the", "order", "of", "currencies", "as", "market", "standard" ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L100-L111
train
30,581
quantmind/ccy
ccy/core/currency.py
ccy.as_cross
def as_cross(self, delimiter=''): ''' Return a cross rate representation with respect USD. @param delimiter: could be '' or '/' normally ''' if self.order > usd_order: return 'USD%s%s' % (delimiter, self.code) else: return '%s%sUSD' % (self.code, delimiter)
python
def as_cross(self, delimiter=''): ''' Return a cross rate representation with respect USD. @param delimiter: could be '' or '/' normally ''' if self.order > usd_order: return 'USD%s%s' % (delimiter, self.code) else: return '%s%sUSD' % (self.code, delimiter)
[ "def", "as_cross", "(", "self", ",", "delimiter", "=", "''", ")", ":", "if", "self", ".", "order", ">", "usd_order", ":", "return", "'USD%s%s'", "%", "(", "delimiter", ",", "self", ".", "code", ")", "else", ":", "return", "'%s%sUSD'", "%", "(", "self...
Return a cross rate representation with respect USD. @param delimiter: could be '' or '/' normally
[ "Return", "a", "cross", "rate", "representation", "with", "respect", "USD", "." ]
068cf6887489087cd26657a937a932e82106b47f
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L125-L133
train
30,582
airbus-cert/mispy
mispy/misp.py
MispServer.POST
def POST(self, path, body, xml=True): """ Raw POST to the MISP server :param path: URL fragment (ie /events/) :param body: HTTP Body (raw bytes) :returns: HTTP raw content (as seen by :class:`requests.Response`) """ url = self._absolute_url(path) headers = dict(self.headers) if xml: headers['Content-Type'] = 'application/xml' headers['Accept'] = 'application/xml' else: headers['Content-Type'] = 'application/json' headers['Accept'] = 'application/json' resp = requests.post(url, data=body, headers=headers, verify=self.verify_ssl) if resp.status_code != 200: raise MispTransportError('POST %s: returned status=%d', path, resp.status_code) return resp.content
python
def POST(self, path, body, xml=True): """ Raw POST to the MISP server :param path: URL fragment (ie /events/) :param body: HTTP Body (raw bytes) :returns: HTTP raw content (as seen by :class:`requests.Response`) """ url = self._absolute_url(path) headers = dict(self.headers) if xml: headers['Content-Type'] = 'application/xml' headers['Accept'] = 'application/xml' else: headers['Content-Type'] = 'application/json' headers['Accept'] = 'application/json' resp = requests.post(url, data=body, headers=headers, verify=self.verify_ssl) if resp.status_code != 200: raise MispTransportError('POST %s: returned status=%d', path, resp.status_code) return resp.content
[ "def", "POST", "(", "self", ",", "path", ",", "body", ",", "xml", "=", "True", ")", ":", "url", "=", "self", ".", "_absolute_url", "(", "path", ")", "headers", "=", "dict", "(", "self", ".", "headers", ")", "if", "xml", ":", "headers", "[", "'Con...
Raw POST to the MISP server :param path: URL fragment (ie /events/) :param body: HTTP Body (raw bytes) :returns: HTTP raw content (as seen by :class:`requests.Response`)
[ "Raw", "POST", "to", "the", "MISP", "server" ]
6d523d6f134d2bd38ec8264be74e73b68403da65
https://github.com/airbus-cert/mispy/blob/6d523d6f134d2bd38ec8264be74e73b68403da65/mispy/misp.py#L778-L798
train
30,583
airbus-cert/mispy
mispy/misp.py
MispServer.GET
def GET(self, path): """ Raw GET to the MISP server :param path: URL fragment (ie /events/) :returns: HTTP raw content (as seen by :class:`requests.Response`) """ url = self._absolute_url(path) resp = requests.get(url, headers=self.headers, verify=self.verify_ssl) if resp.status_code != 200: raise MispTransportError('GET %s: returned status=%d', path, resp.status_code) return resp.content
python
def GET(self, path): """ Raw GET to the MISP server :param path: URL fragment (ie /events/) :returns: HTTP raw content (as seen by :class:`requests.Response`) """ url = self._absolute_url(path) resp = requests.get(url, headers=self.headers, verify=self.verify_ssl) if resp.status_code != 200: raise MispTransportError('GET %s: returned status=%d', path, resp.status_code) return resp.content
[ "def", "GET", "(", "self", ",", "path", ")", ":", "url", "=", "self", ".", "_absolute_url", "(", "path", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "verify", "=", "self", ".", "verify_ssl...
Raw GET to the MISP server :param path: URL fragment (ie /events/) :returns: HTTP raw content (as seen by :class:`requests.Response`)
[ "Raw", "GET", "to", "the", "MISP", "server" ]
6d523d6f134d2bd38ec8264be74e73b68403da65
https://github.com/airbus-cert/mispy/blob/6d523d6f134d2bd38ec8264be74e73b68403da65/mispy/misp.py#L800-L811
train
30,584
airbus-cert/mispy
mispy/misp.py
MispShadowAttribute.from_attribute
def from_attribute(attr): """ Converts an attribute into a shadow attribute. :param attr: :class:`MispAttribute` instance to be converted :returns: Converted :class:`MispShadowAttribute` :example: >>> server = MispServer() >>> event = server.events.get(12) >>> attr = event.attributes[0] >>> prop = MispShadowAttribute.from_attribute(attr) """ assert attr is not MispAttribute prop = MispShadowAttribute() prop.distribution = attr.distribution prop.type = attr.type prop.comment = attr.comment prop.value = attr.value prop.category = attr.category prop.to_ids = attr.to_ids return prop
python
def from_attribute(attr): """ Converts an attribute into a shadow attribute. :param attr: :class:`MispAttribute` instance to be converted :returns: Converted :class:`MispShadowAttribute` :example: >>> server = MispServer() >>> event = server.events.get(12) >>> attr = event.attributes[0] >>> prop = MispShadowAttribute.from_attribute(attr) """ assert attr is not MispAttribute prop = MispShadowAttribute() prop.distribution = attr.distribution prop.type = attr.type prop.comment = attr.comment prop.value = attr.value prop.category = attr.category prop.to_ids = attr.to_ids return prop
[ "def", "from_attribute", "(", "attr", ")", ":", "assert", "attr", "is", "not", "MispAttribute", "prop", "=", "MispShadowAttribute", "(", ")", "prop", ".", "distribution", "=", "attr", ".", "distribution", "prop", ".", "type", "=", "attr", ".", "type", "pro...
Converts an attribute into a shadow attribute. :param attr: :class:`MispAttribute` instance to be converted :returns: Converted :class:`MispShadowAttribute` :example: >>> server = MispServer() >>> event = server.events.get(12) >>> attr = event.attributes[0] >>> prop = MispShadowAttribute.from_attribute(attr)
[ "Converts", "an", "attribute", "into", "a", "shadow", "attribute", "." ]
6d523d6f134d2bd38ec8264be74e73b68403da65
https://github.com/airbus-cert/mispy/blob/6d523d6f134d2bd38ec8264be74e73b68403da65/mispy/misp.py#L1389-L1411
train
30,585
gmr/rejected
rejected/mcp.py
MasterControlProgram.active_processes
def active_processes(self, use_cache=True): """Return a list of all active processes, pruning dead ones :rtype: list """ LOGGER.debug('Checking active processes (cache: %s)', use_cache) if self.can_use_process_cache(use_cache): return self._active_cache[1] active_processes, dead_processes = list(), list() for consumer in self.consumers: processes = list(self.consumers[consumer].processes) for name in processes: child = self.get_consumer_process(consumer, name) if child is None: dead_processes.append((consumer, name)) elif child.pid is None: dead_processes.append((consumer, name)) continue elif child.pid == self.pid: continue try: proc = psutil.Process(child.pid) except psutil.NoSuchProcess: dead_processes.append((consumer, name)) continue if self.unresponsive[name] >= self.MAX_UNRESPONSIVE_COUNT: LOGGER.info('Killing unresponsive consumer %s (%i): ' '%i misses', name, proc.pid, self.unresponsive[name]) try: os.kill(child.pid, signal.SIGABRT) except OSError: pass dead_processes.append((consumer, name)) elif self.is_dead(proc, name): dead_processes.append((consumer, name)) else: active_processes.append(child) if dead_processes: LOGGER.debug('Removing %i dead process(es)', len(dead_processes)) for proc in dead_processes: self.remove_consumer_process(*proc) self._active_cache = time.time(), active_processes return active_processes
python
def active_processes(self, use_cache=True): """Return a list of all active processes, pruning dead ones :rtype: list """ LOGGER.debug('Checking active processes (cache: %s)', use_cache) if self.can_use_process_cache(use_cache): return self._active_cache[1] active_processes, dead_processes = list(), list() for consumer in self.consumers: processes = list(self.consumers[consumer].processes) for name in processes: child = self.get_consumer_process(consumer, name) if child is None: dead_processes.append((consumer, name)) elif child.pid is None: dead_processes.append((consumer, name)) continue elif child.pid == self.pid: continue try: proc = psutil.Process(child.pid) except psutil.NoSuchProcess: dead_processes.append((consumer, name)) continue if self.unresponsive[name] >= self.MAX_UNRESPONSIVE_COUNT: LOGGER.info('Killing unresponsive consumer %s (%i): ' '%i misses', name, proc.pid, self.unresponsive[name]) try: os.kill(child.pid, signal.SIGABRT) except OSError: pass dead_processes.append((consumer, name)) elif self.is_dead(proc, name): dead_processes.append((consumer, name)) else: active_processes.append(child) if dead_processes: LOGGER.debug('Removing %i dead process(es)', len(dead_processes)) for proc in dead_processes: self.remove_consumer_process(*proc) self._active_cache = time.time(), active_processes return active_processes
[ "def", "active_processes", "(", "self", ",", "use_cache", "=", "True", ")", ":", "LOGGER", ".", "debug", "(", "'Checking active processes (cache: %s)'", ",", "use_cache", ")", "if", "self", ".", "can_use_process_cache", "(", "use_cache", ")", ":", "return", "sel...
Return a list of all active processes, pruning dead ones :rtype: list
[ "Return", "a", "list", "of", "all", "active", "processes", "pruning", "dead", "ones" ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L93-L139
train
30,586
gmr/rejected
rejected/mcp.py
MasterControlProgram.calculate_stats
def calculate_stats(self, data): """Calculate the stats data for our process level data. :param data: The collected stats data to report on :type data: dict """ timestamp = data['timestamp'] del data['timestamp'] # Iterate through the last poll results stats = self.consumer_stats_counter() consumer_stats = dict() for name in data.keys(): consumer_stats[name] = self.consumer_stats_counter() consumer_stats[name]['processes'] = self.process_count(name) for proc in data[name].keys(): for key in stats: value = data[name][proc]['counts'].get(key, 0) stats[key] += value consumer_stats[name][key] += value # Return a data structure that can be used in reporting out the stats stats['processes'] = len(self.active_processes()) return { 'last_poll': timestamp, 'consumers': consumer_stats, 'process_data': data, 'counts': stats }
python
def calculate_stats(self, data): """Calculate the stats data for our process level data. :param data: The collected stats data to report on :type data: dict """ timestamp = data['timestamp'] del data['timestamp'] # Iterate through the last poll results stats = self.consumer_stats_counter() consumer_stats = dict() for name in data.keys(): consumer_stats[name] = self.consumer_stats_counter() consumer_stats[name]['processes'] = self.process_count(name) for proc in data[name].keys(): for key in stats: value = data[name][proc]['counts'].get(key, 0) stats[key] += value consumer_stats[name][key] += value # Return a data structure that can be used in reporting out the stats stats['processes'] = len(self.active_processes()) return { 'last_poll': timestamp, 'consumers': consumer_stats, 'process_data': data, 'counts': stats }
[ "def", "calculate_stats", "(", "self", ",", "data", ")", ":", "timestamp", "=", "data", "[", "'timestamp'", "]", "del", "data", "[", "'timestamp'", "]", "# Iterate through the last poll results", "stats", "=", "self", ".", "consumer_stats_counter", "(", ")", "co...
Calculate the stats data for our process level data. :param data: The collected stats data to report on :type data: dict
[ "Calculate", "the", "stats", "data", "for", "our", "process", "level", "data", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L141-L170
train
30,587
gmr/rejected
rejected/mcp.py
MasterControlProgram.can_use_process_cache
def can_use_process_cache(self, use_cache): """Returns True if the process cache can be used :param bool use_cache: Override the logic to force non-cached values :rtype: bool """ return (use_cache and self._active_cache and self._active_cache[0] > (time.time() - self.poll_interval))
python
def can_use_process_cache(self, use_cache): """Returns True if the process cache can be used :param bool use_cache: Override the logic to force non-cached values :rtype: bool """ return (use_cache and self._active_cache and self._active_cache[0] > (time.time() - self.poll_interval))
[ "def", "can_use_process_cache", "(", "self", ",", "use_cache", ")", ":", "return", "(", "use_cache", "and", "self", ".", "_active_cache", "and", "self", ".", "_active_cache", "[", "0", "]", ">", "(", "time", ".", "time", "(", ")", "-", "self", ".", "po...
Returns True if the process cache can be used :param bool use_cache: Override the logic to force non-cached values :rtype: bool
[ "Returns", "True", "if", "the", "process", "cache", "can", "be", "used" ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L172-L181
train
30,588
gmr/rejected
rejected/mcp.py
MasterControlProgram.check_process_counts
def check_process_counts(self): """Check for the minimum consumer process levels and start up new processes needed. """ LOGGER.debug('Checking minimum consumer process levels') for name in self.consumers: processes_needed = self.process_spawn_qty(name) if processes_needed: LOGGER.info('Need to spawn %i processes for %s', processes_needed, name) self.start_processes(name, processes_needed)
python
def check_process_counts(self): """Check for the minimum consumer process levels and start up new processes needed. """ LOGGER.debug('Checking minimum consumer process levels') for name in self.consumers: processes_needed = self.process_spawn_qty(name) if processes_needed: LOGGER.info('Need to spawn %i processes for %s', processes_needed, name) self.start_processes(name, processes_needed)
[ "def", "check_process_counts", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Checking minimum consumer process levels'", ")", "for", "name", "in", "self", ".", "consumers", ":", "processes_needed", "=", "self", ".", "process_spawn_qty", "(", "name", ")", ...
Check for the minimum consumer process levels and start up new processes needed.
[ "Check", "for", "the", "minimum", "consumer", "process", "levels", "and", "start", "up", "new", "processes", "needed", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L183-L194
train
30,589
gmr/rejected
rejected/mcp.py
MasterControlProgram.collect_results
def collect_results(self, data_values): """Receive the data from the consumers polled and process it. :param dict data_values: The poll data returned from the consumer :type data_values: dict """ self.last_poll_results['timestamp'] = self.poll_data['timestamp'] # Get the name and consumer name and remove it from what is reported consumer_name = data_values['consumer_name'] del data_values['consumer_name'] process_name = data_values['name'] del data_values['name'] # Add it to our last poll global data if consumer_name not in self.last_poll_results: self.last_poll_results[consumer_name] = dict() self.last_poll_results[consumer_name][process_name] = data_values # Calculate the stats self.stats = self.calculate_stats(self.last_poll_results)
python
def collect_results(self, data_values): """Receive the data from the consumers polled and process it. :param dict data_values: The poll data returned from the consumer :type data_values: dict """ self.last_poll_results['timestamp'] = self.poll_data['timestamp'] # Get the name and consumer name and remove it from what is reported consumer_name = data_values['consumer_name'] del data_values['consumer_name'] process_name = data_values['name'] del data_values['name'] # Add it to our last poll global data if consumer_name not in self.last_poll_results: self.last_poll_results[consumer_name] = dict() self.last_poll_results[consumer_name][process_name] = data_values # Calculate the stats self.stats = self.calculate_stats(self.last_poll_results)
[ "def", "collect_results", "(", "self", ",", "data_values", ")", ":", "self", ".", "last_poll_results", "[", "'timestamp'", "]", "=", "self", ".", "poll_data", "[", "'timestamp'", "]", "# Get the name and consumer name and remove it from what is reported", "consumer_name",...
Receive the data from the consumers polled and process it. :param dict data_values: The poll data returned from the consumer :type data_values: dict
[ "Receive", "the", "data", "from", "the", "consumers", "polled", "and", "process", "it", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L196-L217
train
30,590
gmr/rejected
rejected/mcp.py
MasterControlProgram.consumer_stats_counter
def consumer_stats_counter(): """Return a new consumer stats counter instance. :rtype: dict """ return { process.Process.ERROR: 0, process.Process.PROCESSED: 0, process.Process.REDELIVERED: 0 }
python
def consumer_stats_counter(): """Return a new consumer stats counter instance. :rtype: dict """ return { process.Process.ERROR: 0, process.Process.PROCESSED: 0, process.Process.REDELIVERED: 0 }
[ "def", "consumer_stats_counter", "(", ")", ":", "return", "{", "process", ".", "Process", ".", "ERROR", ":", "0", ",", "process", ".", "Process", ".", "PROCESSED", ":", "0", ",", "process", ".", "Process", ".", "REDELIVERED", ":", "0", "}" ]
Return a new consumer stats counter instance. :rtype: dict
[ "Return", "a", "new", "consumer", "stats", "counter", "instance", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L230-L240
train
30,591
gmr/rejected
rejected/mcp.py
MasterControlProgram.get_consumer_process
def get_consumer_process(self, consumer, name): """Get the process object for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name :returns: multiprocessing.Process """ return self.consumers[consumer].processes.get(name)
python
def get_consumer_process(self, consumer, name): """Get the process object for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name :returns: multiprocessing.Process """ return self.consumers[consumer].processes.get(name)
[ "def", "get_consumer_process", "(", "self", ",", "consumer", ",", "name", ")", ":", "return", "self", ".", "consumers", "[", "consumer", "]", ".", "processes", ".", "get", "(", "name", ")" ]
Get the process object for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name :returns: multiprocessing.Process
[ "Get", "the", "process", "object", "for", "the", "specified", "consumer", "and", "process", "name", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L242-L250
train
30,592
gmr/rejected
rejected/mcp.py
MasterControlProgram.get_consumer_cfg
def get_consumer_cfg(config, only, qty): """Get the consumers config, possibly filtering the config if only or qty is set. :param config: The consumers config section :type config: helper.config.Config :param str only: When set, filter to run only this consumer :param int qty: When set, set the consumer qty to this value :rtype: dict """ consumers = dict(config.application.Consumers or {}) if only: for key in list(consumers.keys()): if key != only: del consumers[key] if qty: consumers[only]['qty'] = qty return consumers
python
def get_consumer_cfg(config, only, qty): """Get the consumers config, possibly filtering the config if only or qty is set. :param config: The consumers config section :type config: helper.config.Config :param str only: When set, filter to run only this consumer :param int qty: When set, set the consumer qty to this value :rtype: dict """ consumers = dict(config.application.Consumers or {}) if only: for key in list(consumers.keys()): if key != only: del consumers[key] if qty: consumers[only]['qty'] = qty return consumers
[ "def", "get_consumer_cfg", "(", "config", ",", "only", ",", "qty", ")", ":", "consumers", "=", "dict", "(", "config", ".", "application", ".", "Consumers", "or", "{", "}", ")", "if", "only", ":", "for", "key", "in", "list", "(", "consumers", ".", "ke...
Get the consumers config, possibly filtering the config if only or qty is set. :param config: The consumers config section :type config: helper.config.Config :param str only: When set, filter to run only this consumer :param int qty: When set, set the consumer qty to this value :rtype: dict
[ "Get", "the", "consumers", "config", "possibly", "filtering", "the", "config", "if", "only", "or", "qty", "is", "set", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L253-L271
train
30,593
gmr/rejected
rejected/mcp.py
MasterControlProgram.is_dead
def is_dead(self, proc, name): """Checks to see if the specified process is dead. :param psutil.Process proc: The process to check :param str name: The name of consumer :rtype: bool """ LOGGER.debug('Checking %s (%r)', name, proc) try: status = proc.status() except psutil.NoSuchProcess: LOGGER.debug('NoSuchProcess: %s (%r)', name, proc) return True LOGGER.debug('Process %s (%s) status: %r (Unresponsive Count: %s)', name, proc.pid, status, self.unresponsive[name]) if status in _PROCESS_RUNNING: return False elif status == psutil.STATUS_ZOMBIE: try: proc.wait(0.1) except psutil.TimeoutExpired: pass try: proc.terminate() status = proc.status() except psutil.NoSuchProcess: LOGGER.debug('NoSuchProcess: %s (%r)', name, proc) return True return status in _PROCESS_STOPPED_OR_DEAD
python
def is_dead(self, proc, name): """Checks to see if the specified process is dead. :param psutil.Process proc: The process to check :param str name: The name of consumer :rtype: bool """ LOGGER.debug('Checking %s (%r)', name, proc) try: status = proc.status() except psutil.NoSuchProcess: LOGGER.debug('NoSuchProcess: %s (%r)', name, proc) return True LOGGER.debug('Process %s (%s) status: %r (Unresponsive Count: %s)', name, proc.pid, status, self.unresponsive[name]) if status in _PROCESS_RUNNING: return False elif status == psutil.STATUS_ZOMBIE: try: proc.wait(0.1) except psutil.TimeoutExpired: pass try: proc.terminate() status = proc.status() except psutil.NoSuchProcess: LOGGER.debug('NoSuchProcess: %s (%r)', name, proc) return True return status in _PROCESS_STOPPED_OR_DEAD
[ "def", "is_dead", "(", "self", ",", "proc", ",", "name", ")", ":", "LOGGER", ".", "debug", "(", "'Checking %s (%r)'", ",", "name", ",", "proc", ")", "try", ":", "status", "=", "proc", ".", "status", "(", ")", "except", "psutil", ".", "NoSuchProcess", ...
Checks to see if the specified process is dead. :param psutil.Process proc: The process to check :param str name: The name of consumer :rtype: bool
[ "Checks", "to", "see", "if", "the", "specified", "process", "is", "dead", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L273-L303
train
30,594
gmr/rejected
rejected/mcp.py
MasterControlProgram.kill_processes
def kill_processes(self): """Gets called on shutdown by the timer when too much time has gone by, calling the terminate method instead of nicely asking for the consumers to stop. """ LOGGER.critical('Max shutdown exceeded, forcibly exiting') processes = self.active_processes(False) while processes: for proc in self.active_processes(False): if int(proc.pid) != int(os.getpid()): LOGGER.warning('Killing %s (%s)', proc.name, proc.pid) try: os.kill(int(proc.pid), signal.SIGKILL) except OSError: pass else: LOGGER.warning('Cowardly refusing kill self (%s, %s)', proc.pid, os.getpid()) time.sleep(0.5) processes = self.active_processes(False) LOGGER.info('Killed all children') return self.set_state(self.STATE_STOPPED)
python
def kill_processes(self): """Gets called on shutdown by the timer when too much time has gone by, calling the terminate method instead of nicely asking for the consumers to stop. """ LOGGER.critical('Max shutdown exceeded, forcibly exiting') processes = self.active_processes(False) while processes: for proc in self.active_processes(False): if int(proc.pid) != int(os.getpid()): LOGGER.warning('Killing %s (%s)', proc.name, proc.pid) try: os.kill(int(proc.pid), signal.SIGKILL) except OSError: pass else: LOGGER.warning('Cowardly refusing kill self (%s, %s)', proc.pid, os.getpid()) time.sleep(0.5) processes = self.active_processes(False) LOGGER.info('Killed all children') return self.set_state(self.STATE_STOPPED)
[ "def", "kill_processes", "(", "self", ")", ":", "LOGGER", ".", "critical", "(", "'Max shutdown exceeded, forcibly exiting'", ")", "processes", "=", "self", ".", "active_processes", "(", "False", ")", "while", "processes", ":", "for", "proc", "in", "self", ".", ...
Gets called on shutdown by the timer when too much time has gone by, calling the terminate method instead of nicely asking for the consumers to stop.
[ "Gets", "called", "on", "shutdown", "by", "the", "timer", "when", "too", "much", "time", "has", "gone", "by", "calling", "the", "terminate", "method", "instead", "of", "nicely", "asking", "for", "the", "consumers", "to", "stop", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L305-L328
train
30,595
gmr/rejected
rejected/mcp.py
MasterControlProgram.log_stats
def log_stats(self): """Output the stats to the LOGGER.""" if not self.stats.get('counts'): if self.consumers: LOGGER.info('Did not receive any stats data from children') return if self.poll_data['processes']: LOGGER.warning('%i process(es) did not respond with stats: %r', len(self.poll_data['processes']), self.poll_data['processes']) if self.stats['counts']['processes'] > 1: LOGGER.info('%i consumers processed %i messages with %i errors', self.stats['counts']['processes'], self.stats['counts']['processed'], self.stats['counts']['failed']) for key in self.stats['consumers'].keys(): LOGGER.info('%i %s %s processed %i messages with %i errors', self.stats['consumers'][key]['processes'], key, self.consumer_keyword(self.stats['consumers'][key]), self.stats['consumers'][key]['processed'], self.stats['consumers'][key]['failed'])
python
def log_stats(self): """Output the stats to the LOGGER.""" if not self.stats.get('counts'): if self.consumers: LOGGER.info('Did not receive any stats data from children') return if self.poll_data['processes']: LOGGER.warning('%i process(es) did not respond with stats: %r', len(self.poll_data['processes']), self.poll_data['processes']) if self.stats['counts']['processes'] > 1: LOGGER.info('%i consumers processed %i messages with %i errors', self.stats['counts']['processes'], self.stats['counts']['processed'], self.stats['counts']['failed']) for key in self.stats['consumers'].keys(): LOGGER.info('%i %s %s processed %i messages with %i errors', self.stats['consumers'][key]['processes'], key, self.consumer_keyword(self.stats['consumers'][key]), self.stats['consumers'][key]['processed'], self.stats['consumers'][key]['failed'])
[ "def", "log_stats", "(", "self", ")", ":", "if", "not", "self", ".", "stats", ".", "get", "(", "'counts'", ")", ":", "if", "self", ".", "consumers", ":", "LOGGER", ".", "info", "(", "'Did not receive any stats data from children'", ")", "return", "if", "se...
Output the stats to the LOGGER.
[ "Output", "the", "stats", "to", "the", "LOGGER", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L330-L353
train
30,596
gmr/rejected
rejected/mcp.py
MasterControlProgram.new_consumer
def new_consumer(self, config, consumer_name): """Return a consumer dict for the given name and configuration. :param dict config: The consumer configuration :param str consumer_name: The consumer name :rtype: dict """ return Consumer(0, dict(), config.get('qty', self.DEFAULT_CONSUMER_QTY), config.get('queue', consumer_name))
python
def new_consumer(self, config, consumer_name): """Return a consumer dict for the given name and configuration. :param dict config: The consumer configuration :param str consumer_name: The consumer name :rtype: dict """ return Consumer(0, dict(), config.get('qty', self.DEFAULT_CONSUMER_QTY), config.get('queue', consumer_name))
[ "def", "new_consumer", "(", "self", ",", "config", ",", "consumer_name", ")", ":", "return", "Consumer", "(", "0", ",", "dict", "(", ")", ",", "config", ".", "get", "(", "'qty'", ",", "self", ".", "DEFAULT_CONSUMER_QTY", ")", ",", "config", ".", "get",...
Return a consumer dict for the given name and configuration. :param dict config: The consumer configuration :param str consumer_name: The consumer name :rtype: dict
[ "Return", "a", "consumer", "dict", "for", "the", "given", "name", "and", "configuration", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L355-L366
train
30,597
gmr/rejected
rejected/mcp.py
MasterControlProgram.new_process
def new_process(self, consumer_name): """Create a new consumer instances :param str consumer_name: The name of the consumer :return tuple: (str, process.Process) """ process_name = '%s-%s' % (consumer_name, self.new_process_number(consumer_name)) kwargs = { 'config': self.config.application, 'consumer_name': consumer_name, 'profile': self.profile, 'daemon': False, 'stats_queue': self.stats_queue, 'logging_config': self.config.logging } return process_name, process.Process(name=process_name, kwargs=kwargs)
python
def new_process(self, consumer_name): """Create a new consumer instances :param str consumer_name: The name of the consumer :return tuple: (str, process.Process) """ process_name = '%s-%s' % (consumer_name, self.new_process_number(consumer_name)) kwargs = { 'config': self.config.application, 'consumer_name': consumer_name, 'profile': self.profile, 'daemon': False, 'stats_queue': self.stats_queue, 'logging_config': self.config.logging } return process_name, process.Process(name=process_name, kwargs=kwargs)
[ "def", "new_process", "(", "self", ",", "consumer_name", ")", ":", "process_name", "=", "'%s-%s'", "%", "(", "consumer_name", ",", "self", ".", "new_process_number", "(", "consumer_name", ")", ")", "kwargs", "=", "{", "'config'", ":", "self", ".", "config", ...
Create a new consumer instances :param str consumer_name: The name of the consumer :return tuple: (str, process.Process)
[ "Create", "a", "new", "consumer", "instances" ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L368-L385
train
30,598
gmr/rejected
rejected/mcp.py
MasterControlProgram.new_process_number
def new_process_number(self, name): """Increment the counter for the process id number for a given consumer configuration. :param str name: Consumer name :rtype: int """ self.consumers[name].last_proc_num += 1 return self.consumers[name].last_proc_num
python
def new_process_number(self, name): """Increment the counter for the process id number for a given consumer configuration. :param str name: Consumer name :rtype: int """ self.consumers[name].last_proc_num += 1 return self.consumers[name].last_proc_num
[ "def", "new_process_number", "(", "self", ",", "name", ")", ":", "self", ".", "consumers", "[", "name", "]", ".", "last_proc_num", "+=", "1", "return", "self", ".", "consumers", "[", "name", "]", ".", "last_proc_num" ]
Increment the counter for the process id number for a given consumer configuration. :param str name: Consumer name :rtype: int
[ "Increment", "the", "counter", "for", "the", "process", "id", "number", "for", "a", "given", "consumer", "configuration", "." ]
610a3e1401122ecb98d891b6795cca0255e5b044
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L387-L396
train
30,599