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
abilian/abilian-core
abilian/app.py
Application.add_static_url
def add_static_url(self, url_path, directory, endpoint=None, roles=None): """Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flask endpoint name for this url rule. Example:: app.add_static_url('myplugin', '/path/to/myplugin/resources', endpoint='myplugin_static') With default setup it will serve content from directory `/path/to/myplugin/resources` from url `http://.../static/myplugin` """ url_path = self.static_url_path + "/" + url_path + "/<path:filename>" self.add_url_rule( url_path, endpoint=endpoint, view_func=partial(send_file_from_directory, directory=directory), roles=roles, ) self.add_access_controller( endpoint, allow_access_for_roles(Anonymous), endpoint=True )
python
def add_static_url(self, url_path, directory, endpoint=None, roles=None): """Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flask endpoint name for this url rule. Example:: app.add_static_url('myplugin', '/path/to/myplugin/resources', endpoint='myplugin_static') With default setup it will serve content from directory `/path/to/myplugin/resources` from url `http://.../static/myplugin` """ url_path = self.static_url_path + "/" + url_path + "/<path:filename>" self.add_url_rule( url_path, endpoint=endpoint, view_func=partial(send_file_from_directory, directory=directory), roles=roles, ) self.add_access_controller( endpoint, allow_access_for_roles(Anonymous), endpoint=True )
[ "def", "add_static_url", "(", "self", ",", "url_path", ",", "directory", ",", "endpoint", "=", "None", ",", "roles", "=", "None", ")", ":", "url_path", "=", "self", ".", "static_url_path", "+", "\"/\"", "+", "url_path", "+", "\"/<path:filename>\"", "self", ...
Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flask endpoint name for this url rule. Example:: app.add_static_url('myplugin', '/path/to/myplugin/resources', endpoint='myplugin_static') With default setup it will serve content from directory `/path/to/myplugin/resources` from url `http://.../static/myplugin`
[ "Add", "a", "new", "url", "rule", "for", "static", "files", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L410-L436
train
43,100
abilian/abilian-core
abilian/core/extensions/__init__.py
_message_send
def _message_send(self, connection): """Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance. """ sender = current_app.config["MAIL_SENDER"] if not self.extra_headers: self.extra_headers = {} self.extra_headers["Sender"] = sender connection.send(self, sender)
python
def _message_send(self, connection): """Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance. """ sender = current_app.config["MAIL_SENDER"] if not self.extra_headers: self.extra_headers = {} self.extra_headers["Sender"] = sender connection.send(self, sender)
[ "def", "_message_send", "(", "self", ",", "connection", ")", ":", "sender", "=", "current_app", ".", "config", "[", "\"MAIL_SENDER\"", "]", "if", "not", "self", ".", "extra_headers", ":", "self", ".", "extra_headers", "=", "{", "}", "self", ".", "extra_hea...
Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance.
[ "Send", "a", "single", "message", "instance", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/extensions/__init__.py#L30-L41
train
43,101
abilian/abilian-core
abilian/core/extensions/__init__.py
_filter_metadata_for_connection
def _filter_metadata_for_connection(target, connection, **kw): """Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine names. """ engine = connection.engine.name default_engines = (engine,) tables = target if isinstance(target, sa.Table) else kw.get("tables", []) for table in tables: indexes = list(table.indexes) for idx in indexes: if engine not in idx.info.get("engines", default_engines): table.indexes.remove(idx)
python
def _filter_metadata_for_connection(target, connection, **kw): """Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine names. """ engine = connection.engine.name default_engines = (engine,) tables = target if isinstance(target, sa.Table) else kw.get("tables", []) for table in tables: indexes = list(table.indexes) for idx in indexes: if engine not in idx.info.get("engines", default_engines): table.indexes.remove(idx)
[ "def", "_filter_metadata_for_connection", "(", "target", ",", "connection", ",", "*", "*", "kw", ")", ":", "engine", "=", "connection", ".", "engine", ".", "name", "default_engines", "=", "(", "engine", ",", ")", "tables", "=", "target", "if", "isinstance", ...
Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine names.
[ "Listener", "to", "control", "what", "indexes", "get", "created", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/extensions/__init__.py#L58-L73
train
43,102
abilian/abilian-core
abilian/web/util.py
url_for
def url_for(obj, **kw): """Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it """ if isinstance(obj, str): return flask_url_for(obj, **kw) try: return current_app.default_view.url_for(obj, **kw) except KeyError: if hasattr(obj, "_url"): return obj._url elif hasattr(obj, "url"): return obj.url raise BuildError(repr(obj), kw, "GET")
python
def url_for(obj, **kw): """Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it """ if isinstance(obj, str): return flask_url_for(obj, **kw) try: return current_app.default_view.url_for(obj, **kw) except KeyError: if hasattr(obj, "_url"): return obj._url elif hasattr(obj, "url"): return obj.url raise BuildError(repr(obj), kw, "GET")
[ "def", "url_for", "(", "obj", ",", "*", "*", "kw", ")", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "return", "flask_url_for", "(", "obj", ",", "*", "*", "kw", ")", "try", ":", "return", "current_app", ".", "default_view", ".", "url_...
Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it
[ "Polymorphic", "variant", "of", "Flask", "s", "url_for", "function", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/util.py#L13-L30
train
43,103
abilian/abilian-core
abilian/web/util.py
send_file_from_directory
def send_file_from_directory(filename, directory, app=None): """Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, directory='/path/to/static/files/dir')) """ if app is None: app = current_app cache_timeout = app.get_send_file_max_age(filename) return send_from_directory(directory, filename, cache_timeout=cache_timeout)
python
def send_file_from_directory(filename, directory, app=None): """Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, directory='/path/to/static/files/dir')) """ if app is None: app = current_app cache_timeout = app.get_send_file_max_age(filename) return send_from_directory(directory, filename, cache_timeout=cache_timeout)
[ "def", "send_file_from_directory", "(", "filename", ",", "directory", ",", "app", "=", "None", ")", ":", "if", "app", "is", "None", ":", "app", "=", "current_app", "cache_timeout", "=", "app", ".", "get_send_file_max_age", "(", "filename", ")", "return", "se...
Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, directory='/path/to/static/files/dir'))
[ "Helper", "to", "add", "static", "rules", "like", "in", "abilian", ".", "app", ".", "app", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/util.py#L39-L53
train
43,104
abilian/abilian-core
abilian/services/audit/service.py
get_model_changes
def get_model_changes( entity_type, year=None, month=None, day=None, hour=None, since=None ): # type: (Text, int, int, int, int, datetime) -> Query """Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware the typo, there won't be a warning message. :param since: datetime :param year: int :param month: int :param day: int :param hour: int :returns: a query object """ query = AuditEntry.query if since: query = query.filter(AuditEntry.happened_at >= since) if year: query = query.filter(extract("year", AuditEntry.happened_at) == year) if month: query = query.filter(extract("month", AuditEntry.happened_at) == month) if day: query = query.filter(extract("day", AuditEntry.happened_at) == day) if hour: query = query.filter(extract("hour", AuditEntry.happened_at) == hour) query = query.filter(AuditEntry.entity_type.like(entity_type)).order_by( AuditEntry.happened_at ) return query
python
def get_model_changes( entity_type, year=None, month=None, day=None, hour=None, since=None ): # type: (Text, int, int, int, int, datetime) -> Query """Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware the typo, there won't be a warning message. :param since: datetime :param year: int :param month: int :param day: int :param hour: int :returns: a query object """ query = AuditEntry.query if since: query = query.filter(AuditEntry.happened_at >= since) if year: query = query.filter(extract("year", AuditEntry.happened_at) == year) if month: query = query.filter(extract("month", AuditEntry.happened_at) == month) if day: query = query.filter(extract("day", AuditEntry.happened_at) == day) if hour: query = query.filter(extract("hour", AuditEntry.happened_at) == hour) query = query.filter(AuditEntry.entity_type.like(entity_type)).order_by( AuditEntry.happened_at ) return query
[ "def", "get_model_changes", "(", "entity_type", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "since", "=", "None", ")", ":", "# type: (Text, int, int, int, int, datetime) -> Query", "query", "=", ...
Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware the typo, there won't be a warning message. :param since: datetime :param year: int :param month: int :param day: int :param hour: int :returns: a query object
[ "Get", "models", "modified", "at", "the", "given", "date", "with", "the", "Audit", "service", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/audit/service.py#L340-L374
train
43,105
abilian/abilian-core
abilian/services/audit/service.py
get_columns_diff
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: change.diff = [] elt_changes = change.get_changes() if elt_changes: change.diff = elt_changes.columns return changes
python
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: change.diff = [] elt_changes = change.get_changes() if elt_changes: change.diff = elt_changes.columns return changes
[ "def", "get_columns_diff", "(", "changes", ")", ":", "for", "change", "in", "changes", ":", "change", ".", "diff", "=", "[", "]", "elt_changes", "=", "change", ".", "get_changes", "(", ")", "if", "elt_changes", ":", "change", ".", "diff", "=", "elt_chang...
Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to [].
[ "Add", "the", "changed", "columns", "as", "a", "diff", "attribute", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/audit/service.py#L377-L391
train
43,106
Ceasar/staticjinja
staticjinja/staticjinja.py
_has_argument
def _has_argument(func): """Test whether a function expects an argument. :param func: The function to be tested for existence of an argument. """ if hasattr(inspect, 'signature'): # New way in python 3.3 sig = inspect.signature(func) return bool(sig.parameters) else: # Old way return bool(inspect.getargspec(func).args)
python
def _has_argument(func): """Test whether a function expects an argument. :param func: The function to be tested for existence of an argument. """ if hasattr(inspect, 'signature'): # New way in python 3.3 sig = inspect.signature(func) return bool(sig.parameters) else: # Old way return bool(inspect.getargspec(func).args)
[ "def", "_has_argument", "(", "func", ")", ":", "if", "hasattr", "(", "inspect", ",", "'signature'", ")", ":", "# New way in python 3.3", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "return", "bool", "(", "sig", ".", "parameters", ")", "else"...
Test whether a function expects an argument. :param func: The function to be tested for existence of an argument.
[ "Test", "whether", "a", "function", "expects", "an", "argument", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L23-L35
train
43,107
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.get_context
def get_context(self, template): """Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the value is a function. If several matching values are found, the resulting dictionaries will be merged before being returned if mergecontexts is True. Otherwise, only the first matching value is returned. :param template: the template to get the context for """ context = {} for regex, context_generator in self.contexts: if re.match(regex, template.name): if inspect.isfunction(context_generator): if _has_argument(context_generator): context.update(context_generator(template)) else: context.update(context_generator()) else: context.update(context_generator) if not self.mergecontexts: break return context
python
def get_context(self, template): """Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the value is a function. If several matching values are found, the resulting dictionaries will be merged before being returned if mergecontexts is True. Otherwise, only the first matching value is returned. :param template: the template to get the context for """ context = {} for regex, context_generator in self.contexts: if re.match(regex, template.name): if inspect.isfunction(context_generator): if _has_argument(context_generator): context.update(context_generator(template)) else: context.update(context_generator()) else: context.update(context_generator) if not self.mergecontexts: break return context
[ "def", "get_context", "(", "self", ",", "template", ")", ":", "context", "=", "{", "}", "for", "regex", ",", "context_generator", "in", "self", ".", "contexts", ":", "if", "re", ".", "match", "(", "regex", ",", "template", ".", "name", ")", ":", "if"...
Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the value is a function. If several matching values are found, the resulting dictionaries will be merged before being returned if mergecontexts is True. Otherwise, only the first matching value is returned. :param template: the template to get the context for
[ "Get", "the", "context", "for", "a", "template", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L236-L263
train
43,108
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.get_rule
def get_rule(self, template_name): """Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template """ for regex, render_func in self.rules: if re.match(regex, template_name): return render_func raise ValueError("no matching rule")
python
def get_rule(self, template_name): """Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template """ for regex, render_func in self.rules: if re.match(regex, template_name): return render_func raise ValueError("no matching rule")
[ "def", "get_rule", "(", "self", ",", "template_name", ")", ":", "for", "regex", ",", "render_func", "in", "self", ".", "rules", ":", "if", "re", ".", "match", "(", "regex", ",", "template_name", ")", ":", "return", "render_func", "raise", "ValueError", "...
Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template
[ "Find", "a", "matching", "compilation", "rule", "for", "a", "function", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L265-L275
train
43,109
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.is_partial
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of the file to check """ return any((x.startswith("_") for x in filename.split(os.path.sep)))
python
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of the file to check """ return any((x.startswith("_") for x in filename.split(os.path.sep)))
[ "def", "is_partial", "(", "self", ",", "filename", ")", ":", "return", "any", "(", "(", "x", ".", "startswith", "(", "\"_\"", ")", "for", "x", "in", "filename", ".", "split", "(", "os", ".", "path", ".", "sep", ")", ")", ")" ]
Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of the file to check
[ "Check", "if", "a", "file", "is", "a", "partial", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L296-L307
train
43,110
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.is_template
def is_template(self, filename): """Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check """ if self.is_partial(filename): return False if self.is_ignored(filename): return False if self.is_static(filename): return False return True
python
def is_template(self, filename): """Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check """ if self.is_partial(filename): return False if self.is_ignored(filename): return False if self.is_static(filename): return False return True
[ "def", "is_template", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "is_partial", "(", "filename", ")", ":", "return", "False", "if", "self", ".", "is_ignored", "(", "filename", ")", ":", "return", "False", "if", "self", ".", "is_static", ...
Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check
[ "Check", "if", "a", "file", "is", "a", "template", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L321-L338
train
43,111
Ceasar/staticjinja
staticjinja/staticjinja.py
Site._ensure_dir
def _ensure_dir(self, template_name): """Ensure the output directory for a template exists.""" head = os.path.dirname(template_name) if head: file_dirpath = os.path.join(self.outpath, head) if not os.path.exists(file_dirpath): os.makedirs(file_dirpath)
python
def _ensure_dir(self, template_name): """Ensure the output directory for a template exists.""" head = os.path.dirname(template_name) if head: file_dirpath = os.path.join(self.outpath, head) if not os.path.exists(file_dirpath): os.makedirs(file_dirpath)
[ "def", "_ensure_dir", "(", "self", ",", "template_name", ")", ":", "head", "=", "os", ".", "path", ".", "dirname", "(", "template_name", ")", "if", "head", ":", "file_dirpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "outpath", ",", "h...
Ensure the output directory for a template exists.
[ "Ensure", "the", "output", "directory", "for", "a", "template", "exists", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L340-L346
train
43,112
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.render
def render(self, use_reloader=False): """Generate the site. :param use_reloader: if given, reload templates on modification """ self.render_templates(self.templates) self.copy_static(self.static_names) if use_reloader: self.logger.info("Watching '%s' for changes..." % self.searchpath) self.logger.info("Press Ctrl+C to stop.") Reloader(self).watch()
python
def render(self, use_reloader=False): """Generate the site. :param use_reloader: if given, reload templates on modification """ self.render_templates(self.templates) self.copy_static(self.static_names) if use_reloader: self.logger.info("Watching '%s' for changes..." % self.searchpath) self.logger.info("Press Ctrl+C to stop.") Reloader(self).watch()
[ "def", "render", "(", "self", ",", "use_reloader", "=", "False", ")", ":", "self", ".", "render_templates", "(", "self", ".", "templates", ")", "self", ".", "copy_static", "(", "self", ".", "static_names", ")", "if", "use_reloader", ":", "self", ".", "lo...
Generate the site. :param use_reloader: if given, reload templates on modification
[ "Generate", "the", "site", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L423-L435
train
43,113
abilian/abilian-core
abilian/web/jinja.py
JinjaManagerMixin.register_jinja_loaders
def register_jinja_loaders(self, *loaders): """Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered is first looked up (after standard Flask lookup in app template folder). This allows a plugin to override templates provided by others, or by base application. The application can override any template from any plugins from its template folder (See `Flask.Application.template_folder`). :raise: `ValueError` if a template has already been rendered """ if not hasattr(self, "_jinja_loaders"): raise ValueError( "Cannot register new jinja loaders after first template rendered" ) self._jinja_loaders.extend(loaders)
python
def register_jinja_loaders(self, *loaders): """Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered is first looked up (after standard Flask lookup in app template folder). This allows a plugin to override templates provided by others, or by base application. The application can override any template from any plugins from its template folder (See `Flask.Application.template_folder`). :raise: `ValueError` if a template has already been rendered """ if not hasattr(self, "_jinja_loaders"): raise ValueError( "Cannot register new jinja loaders after first template rendered" ) self._jinja_loaders.extend(loaders)
[ "def", "register_jinja_loaders", "(", "self", ",", "*", "loaders", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_jinja_loaders\"", ")", ":", "raise", "ValueError", "(", "\"Cannot register new jinja loaders after first template rendered\"", ")", "self", ".", ...
Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered is first looked up (after standard Flask lookup in app template folder). This allows a plugin to override templates provided by others, or by base application. The application can override any template from any plugins from its template folder (See `Flask.Application.template_folder`). :raise: `ValueError` if a template has already been rendered
[ "Register", "one", "or", "many", "jinja2", ".", "Loader", "instances", "for", "templates", "lookup", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/jinja.py#L62-L81
train
43,114
Ceasar/staticjinja
staticjinja/cli.py
render
def render(args): """ Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False, 'build': True, 'watch': False } """ srcpath = ( os.path.join(os.getcwd(), 'templates') if args['--srcpath'] is None else args['--srcpath'] if os.path.isabs(args['--srcpath']) else os.path.join(os.getcwd(), args['--srcpath']) ) if not os.path.isdir(srcpath): print("The templates directory '%s' is invalid." % srcpath) sys.exit(1) if args['--outpath'] is not None: outpath = args['--outpath'] else: outpath = os.getcwd() if not os.path.isdir(outpath): print("The output directory '%s' is invalid." % outpath) sys.exit(1) staticdirs = args['--static'] staticpaths = None if staticdirs: staticpaths = staticdirs.split(",") for path in staticpaths: path = os.path.join(srcpath, path) if not os.path.isdir(path): print("The static files directory '%s' is invalid." % path) sys.exit(1) site = staticjinja.make_site( searchpath=srcpath, outpath=outpath, staticpaths=staticpaths ) use_reloader = args['watch'] site.render(use_reloader=use_reloader)
python
def render(args): """ Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False, 'build': True, 'watch': False } """ srcpath = ( os.path.join(os.getcwd(), 'templates') if args['--srcpath'] is None else args['--srcpath'] if os.path.isabs(args['--srcpath']) else os.path.join(os.getcwd(), args['--srcpath']) ) if not os.path.isdir(srcpath): print("The templates directory '%s' is invalid." % srcpath) sys.exit(1) if args['--outpath'] is not None: outpath = args['--outpath'] else: outpath = os.getcwd() if not os.path.isdir(outpath): print("The output directory '%s' is invalid." % outpath) sys.exit(1) staticdirs = args['--static'] staticpaths = None if staticdirs: staticpaths = staticdirs.split(",") for path in staticpaths: path = os.path.join(srcpath, path) if not os.path.isdir(path): print("The static files directory '%s' is invalid." % path) sys.exit(1) site = staticjinja.make_site( searchpath=srcpath, outpath=outpath, staticpaths=staticpaths ) use_reloader = args['watch'] site.render(use_reloader=use_reloader)
[ "def", "render", "(", "args", ")", ":", "srcpath", "=", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'templates'", ")", "if", "args", "[", "'--srcpath'", "]", "is", "None", "else", "args", "[", "'--srcpath'", "]", ...
Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False, 'build': True, 'watch': False }
[ "Render", "a", "site", "." ]
57b8cac81da7fee3387510af4843e1bd1fd3ba28
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/cli.py#L24-L81
train
43,115
abilian/abilian-core
abilian/services/indexing/schema.py
indexable_role
def indexable_role(principal): """Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`. """ principal = unwrap(principal) if hasattr(principal, "is_anonymous") and principal.is_anonymous: # transform anonymous user to anonymous role principal = Anonymous if isinstance(principal, Role): return f"role:{principal.name}" elif isinstance(principal, User): fmt = "user:{:d}" elif isinstance(principal, Group): fmt = "group:{:d}" else: raise ValueError(repr(principal)) return fmt.format(principal.id)
python
def indexable_role(principal): """Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`. """ principal = unwrap(principal) if hasattr(principal, "is_anonymous") and principal.is_anonymous: # transform anonymous user to anonymous role principal = Anonymous if isinstance(principal, Role): return f"role:{principal.name}" elif isinstance(principal, User): fmt = "user:{:d}" elif isinstance(principal, Group): fmt = "group:{:d}" else: raise ValueError(repr(principal)) return fmt.format(principal.id)
[ "def", "indexable_role", "(", "principal", ")", ":", "principal", "=", "unwrap", "(", "principal", ")", "if", "hasattr", "(", "principal", ",", "\"is_anonymous\"", ")", "and", "principal", ".", "is_anonymous", ":", "# transform anonymous user to anonymous role", "pr...
Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`.
[ "Return", "a", "string", "suitable", "for", "query", "against", "allowed_roles_and_users", "field", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/schema.py#L68-L90
train
43,116
abilian/abilian-core
abilian/services/conversion/service.py
Converter.to_text
def to_text(self, digest, blob, mime_type): """Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = "txt:" + digest text = self.cache.get(cache_key) if text: return text # Direct conversion possible for handler in self.handlers: if handler.accept(mime_type, "text/plain"): text = handler.convert(blob) self.cache[cache_key] = text return text # Use PDF as a pivot format pdf = self.to_pdf(digest, blob, mime_type) for handler in self.handlers: if handler.accept("application/pdf", "text/plain"): text = handler.convert(pdf) self.cache[cache_key] = text return text raise HandlerNotFound(f"No handler found to convert from {mime_type} to text")
python
def to_text(self, digest, blob, mime_type): """Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = "txt:" + digest text = self.cache.get(cache_key) if text: return text # Direct conversion possible for handler in self.handlers: if handler.accept(mime_type, "text/plain"): text = handler.convert(blob) self.cache[cache_key] = text return text # Use PDF as a pivot format pdf = self.to_pdf(digest, blob, mime_type) for handler in self.handlers: if handler.accept("application/pdf", "text/plain"): text = handler.convert(pdf) self.cache[cache_key] = text return text raise HandlerNotFound(f"No handler found to convert from {mime_type} to text")
[ "def", "to_text", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key", "=", "\"txt:\"", "+", "digest", "text", ...
Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string.
[ "Convert", "a", "file", "to", "plain", "text", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L125-L155
train
43,117
abilian/abilian-core
abilian/services/conversion/service.py
Converter.has_image
def has_image(self, digest, mime_type, index, size=500): """Tell if there is a preview image.""" cache_key = f"img:{index}:{size}:{digest}" return mime_type.startswith("image/") or cache_key in self.cache
python
def has_image(self, digest, mime_type, index, size=500): """Tell if there is a preview image.""" cache_key = f"img:{index}:{size}:{digest}" return mime_type.startswith("image/") or cache_key in self.cache
[ "def", "has_image", "(", "self", ",", "digest", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "cache_key", "=", "f\"img:{index}:{size}:{digest}\"", "return", "mime_type", ".", "startswith", "(", "\"image/\"", ")", "or", "cache_key", "in", ...
Tell if there is a preview image.
[ "Tell", "if", "there", "is", "a", "preview", "image", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L157-L160
train
43,118
abilian/abilian-core
abilian/services/conversion/service.py
Converter.get_image
def get_image(self, digest, blob, mime_type, index, size=500): """Return an image for the given content, only if it already exists in the image cache.""" # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" return self.cache.get(cache_key)
python
def get_image(self, digest, blob, mime_type, index, size=500): """Return an image for the given content, only if it already exists in the image cache.""" # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" return self.cache.get(cache_key)
[ "def", "get_image", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key"...
Return an image for the given content, only if it already exists in the image cache.
[ "Return", "an", "image", "for", "the", "given", "content", "only", "if", "it", "already", "exists", "in", "the", "image", "cache", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L162-L170
train
43,119
abilian/abilian-core
abilian/services/conversion/service.py
Converter.to_image
def to_image(self, digest, blob, mime_type, index, size=500): """Convert a file to a list of images. Returns image at the given index. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" converted = self.cache.get(cache_key) if converted: return converted # Direct conversion possible for handler in self.handlers: if handler.accept(mime_type, "image/jpeg"): converted_images = handler.convert(blob, size=size) for i in range(0, len(converted_images)): converted = converted_images[i] cache_key = f"img:{i}:{size}:{digest}" self.cache[cache_key] = converted return converted_images[index] # Use PDF as a pivot format pdf = self.to_pdf(digest, blob, mime_type) for handler in self.handlers: if handler.accept("application/pdf", "image/jpeg"): converted_images = handler.convert(pdf, size=size) for i in range(0, len(converted_images)): converted = converted_images[i] cache_key = f"img:{i}:{size}:{digest}" self.cache[cache_key] = converted return converted_images[index] raise HandlerNotFound(f"No handler found to convert from {mime_type} to image")
python
def to_image(self, digest, blob, mime_type, index, size=500): """Convert a file to a list of images. Returns image at the given index. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" converted = self.cache.get(cache_key) if converted: return converted # Direct conversion possible for handler in self.handlers: if handler.accept(mime_type, "image/jpeg"): converted_images = handler.convert(blob, size=size) for i in range(0, len(converted_images)): converted = converted_images[i] cache_key = f"img:{i}:{size}:{digest}" self.cache[cache_key] = converted return converted_images[index] # Use PDF as a pivot format pdf = self.to_pdf(digest, blob, mime_type) for handler in self.handlers: if handler.accept("application/pdf", "image/jpeg"): converted_images = handler.convert(pdf, size=size) for i in range(0, len(converted_images)): converted = converted_images[i] cache_key = f"img:{i}:{size}:{digest}" self.cache[cache_key] = converted return converted_images[index] raise HandlerNotFound(f"No handler found to convert from {mime_type} to image")
[ "def", "to_image", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key",...
Convert a file to a list of images. Returns image at the given index.
[ "Convert", "a", "file", "to", "a", "list", "of", "images", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L172-L207
train
43,120
abilian/abilian-core
abilian/services/conversion/service.py
Converter.get_metadata
def get_metadata(self, digest, content, mime_type): """Get a dictionary representing the metadata embedded in the given content.""" # XXX: ad-hoc for now, refactor later if mime_type.startswith("image/"): img = Image.open(BytesIO(content)) ret = {} if not hasattr(img, "_getexif"): return {} info = img._getexif() if not info: return {} for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret["EXIF:" + str(decoded)] = value return ret else: if mime_type != "application/pdf": content = self.to_pdf(digest, content, mime_type) with make_temp_file(content) as in_fn: try: output = subprocess.check_output(["pdfinfo", in_fn]) except OSError: logger.error("Conversion failed, probably pdfinfo is not installed") raise ret = {} for line in output.split(b"\n"): if b":" in line: key, value = line.strip().split(b":", 1) key = str(key) ret["PDF:" + key] = str(value.strip(), errors="replace") return ret
python
def get_metadata(self, digest, content, mime_type): """Get a dictionary representing the metadata embedded in the given content.""" # XXX: ad-hoc for now, refactor later if mime_type.startswith("image/"): img = Image.open(BytesIO(content)) ret = {} if not hasattr(img, "_getexif"): return {} info = img._getexif() if not info: return {} for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret["EXIF:" + str(decoded)] = value return ret else: if mime_type != "application/pdf": content = self.to_pdf(digest, content, mime_type) with make_temp_file(content) as in_fn: try: output = subprocess.check_output(["pdfinfo", in_fn]) except OSError: logger.error("Conversion failed, probably pdfinfo is not installed") raise ret = {} for line in output.split(b"\n"): if b":" in line: key, value = line.strip().split(b":", 1) key = str(key) ret["PDF:" + key] = str(value.strip(), errors="replace") return ret
[ "def", "get_metadata", "(", "self", ",", "digest", ",", "content", ",", "mime_type", ")", ":", "# XXX: ad-hoc for now, refactor later", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "img", "=", "Image", ".", "open", "(", "BytesIO", "(", ...
Get a dictionary representing the metadata embedded in the given content.
[ "Get", "a", "dictionary", "representing", "the", "metadata", "embedded", "in", "the", "given", "content", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L209-L244
train
43,121
google/pyu2f
pyu2f/apdu.py
CommandApdu.ToByteArray
def ToByteArray(self): """Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command. """ lc = self.InternalEncodeLc() out = bytearray(4) # will extend out[0] = self.cla out[1] = self.ins out[2] = self.p1 out[3] = self.p2 if self.data: out.extend(lc) out.extend(self.data) out.extend([0x00, 0x00]) # Le else: out.extend([0x00, 0x00, 0x00]) # Le return out
python
def ToByteArray(self): """Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command. """ lc = self.InternalEncodeLc() out = bytearray(4) # will extend out[0] = self.cla out[1] = self.ins out[2] = self.p1 out[3] = self.p2 if self.data: out.extend(lc) out.extend(self.data) out.extend([0x00, 0x00]) # Le else: out.extend([0x00, 0x00, 0x00]) # Le return out
[ "def", "ToByteArray", "(", "self", ")", ":", "lc", "=", "self", ".", "InternalEncodeLc", "(", ")", "out", "=", "bytearray", "(", "4", ")", "# will extend", "out", "[", "0", "]", "=", "self", ".", "cla", "out", "[", "1", "]", "=", "self", ".", "in...
Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command.
[ "Serialize", "the", "command", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/apdu.py#L56-L79
train
43,122
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._BuildPluginRequest
def _BuildPluginRequest(self, app_id, challenge_data, origin): """Builds a JSON request in the form that the plugin expects.""" client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item['key'] key_handle_encoded = self._Base64Encode(key.key_handle) raw_challenge = challenge_item['challenge'] client_data_json = model.ClientData( model.ClientData.TYP_AUTHENTICATION, raw_challenge, origin).GetJson() challenge_hash_encoded = self._Base64Encode( self._SHA256(client_data_json)) # Populate challenges list encoded_challenges.append({ 'appIdHash': app_id_hash_encoded, 'challengeHash': challenge_hash_encoded, 'keyHandle': key_handle_encoded, 'version': key.version, }) # Populate ClientData map key_challenge_pair = (key_handle_encoded, challenge_hash_encoded) client_data_map[key_challenge_pair] = client_data_json signing_request = { 'type': 'sign_helper_request', 'signData': encoded_challenges, 'timeoutSeconds': U2F_SIGNATURE_TIMEOUT_SECONDS, 'localAlways': True } return client_data_map, json.dumps(signing_request)
python
def _BuildPluginRequest(self, app_id, challenge_data, origin): """Builds a JSON request in the form that the plugin expects.""" client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item['key'] key_handle_encoded = self._Base64Encode(key.key_handle) raw_challenge = challenge_item['challenge'] client_data_json = model.ClientData( model.ClientData.TYP_AUTHENTICATION, raw_challenge, origin).GetJson() challenge_hash_encoded = self._Base64Encode( self._SHA256(client_data_json)) # Populate challenges list encoded_challenges.append({ 'appIdHash': app_id_hash_encoded, 'challengeHash': challenge_hash_encoded, 'keyHandle': key_handle_encoded, 'version': key.version, }) # Populate ClientData map key_challenge_pair = (key_handle_encoded, challenge_hash_encoded) client_data_map[key_challenge_pair] = client_data_json signing_request = { 'type': 'sign_helper_request', 'signData': encoded_challenges, 'timeoutSeconds': U2F_SIGNATURE_TIMEOUT_SECONDS, 'localAlways': True } return client_data_map, json.dumps(signing_request)
[ "def", "_BuildPluginRequest", "(", "self", ",", "app_id", ",", "challenge_data", ",", "origin", ")", ":", "client_data_map", "=", "{", "}", "encoded_challenges", "=", "[", "]", "app_id_hash_encoded", "=", "self", ".", "_Base64Encode", "(", "self", ".", "_SHA25...
Builds a JSON request in the form that the plugin expects.
[ "Builds", "a", "JSON", "request", "in", "the", "form", "that", "the", "plugin", "expects", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L116-L154
train
43,123
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._BuildAuthenticatorResponse
def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response): """Builds the response to return to the caller.""" encoded_client_data = self._Base64Encode(client_data) signature_data = str(plugin_response['signatureData']) key_handle = str(plugin_response['keyHandle']) response = { 'clientData': encoded_client_data, 'signatureData': signature_data, 'applicationId': app_id, 'keyHandle': key_handle, } return response
python
def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response): """Builds the response to return to the caller.""" encoded_client_data = self._Base64Encode(client_data) signature_data = str(plugin_response['signatureData']) key_handle = str(plugin_response['keyHandle']) response = { 'clientData': encoded_client_data, 'signatureData': signature_data, 'applicationId': app_id, 'keyHandle': key_handle, } return response
[ "def", "_BuildAuthenticatorResponse", "(", "self", ",", "app_id", ",", "client_data", ",", "plugin_response", ")", ":", "encoded_client_data", "=", "self", ".", "_Base64Encode", "(", "client_data", ")", "signature_data", "=", "str", "(", "plugin_response", "[", "'...
Builds the response to return to the caller.
[ "Builds", "the", "response", "to", "return", "to", "the", "caller", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L156-L168
train
43,124
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._CallPlugin
def _CallPlugin(self, cmd, input_json): """Calls the plugin and validates the response.""" # Calculate length of input input_length = len(input_json) length_bytes_le = struct.pack('<I', input_length) request = length_bytes_le + input_json.encode() # Call plugin sign_process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout = sign_process.communicate(request)[0] exit_status = sign_process.wait() # Parse and validate response size response_len_le = stdout[:4] response_len = struct.unpack('<I', response_len_le)[0] response = stdout[4:] if response_len != len(response): raise errors.PluginError( 'Plugin response length {} does not match data {} (exit_status={})' .format(response_len, len(response), exit_status)) # Ensure valid json try: json_response = json.loads(response.decode()) except ValueError: raise errors.PluginError('Plugin returned invalid output (exit_status={})' .format(exit_status)) # Ensure response type if json_response.get('type') != 'sign_helper_reply': raise errors.PluginError('Plugin returned invalid response type ' '(exit_status={})' .format(exit_status)) # Parse response codes result_code = json_response.get('code') if result_code is None: raise errors.PluginError('Plugin missing result code (exit_status={})' .format(exit_status)) # Handle errors if result_code == SK_SIGNING_PLUGIN_TOUCH_REQUIRED: raise errors.U2FError(errors.U2FError.TIMEOUT) elif result_code == SK_SIGNING_PLUGIN_WRONG_DATA: raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) elif result_code != SK_SIGNING_PLUGIN_NO_ERROR: raise errors.PluginError( 'Plugin failed with error {} - {} (exit_status={})' .format(result_code, json_response.get('errorDetail'), exit_status)) # Ensure response data is present response_data = json_response.get('responseData') if response_data is None: raise errors.PluginErrors( 'Plugin returned output with missing responseData (exit_status={})' .format(exit_status)) return response_data
python
def _CallPlugin(self, cmd, input_json): """Calls the plugin and validates the response.""" # Calculate length of input input_length = len(input_json) length_bytes_le = struct.pack('<I', input_length) request = length_bytes_le + input_json.encode() # Call plugin sign_process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout = sign_process.communicate(request)[0] exit_status = sign_process.wait() # Parse and validate response size response_len_le = stdout[:4] response_len = struct.unpack('<I', response_len_le)[0] response = stdout[4:] if response_len != len(response): raise errors.PluginError( 'Plugin response length {} does not match data {} (exit_status={})' .format(response_len, len(response), exit_status)) # Ensure valid json try: json_response = json.loads(response.decode()) except ValueError: raise errors.PluginError('Plugin returned invalid output (exit_status={})' .format(exit_status)) # Ensure response type if json_response.get('type') != 'sign_helper_reply': raise errors.PluginError('Plugin returned invalid response type ' '(exit_status={})' .format(exit_status)) # Parse response codes result_code = json_response.get('code') if result_code is None: raise errors.PluginError('Plugin missing result code (exit_status={})' .format(exit_status)) # Handle errors if result_code == SK_SIGNING_PLUGIN_TOUCH_REQUIRED: raise errors.U2FError(errors.U2FError.TIMEOUT) elif result_code == SK_SIGNING_PLUGIN_WRONG_DATA: raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) elif result_code != SK_SIGNING_PLUGIN_NO_ERROR: raise errors.PluginError( 'Plugin failed with error {} - {} (exit_status={})' .format(result_code, json_response.get('errorDetail'), exit_status)) # Ensure response data is present response_data = json_response.get('responseData') if response_data is None: raise errors.PluginErrors( 'Plugin returned output with missing responseData (exit_status={})' .format(exit_status)) return response_data
[ "def", "_CallPlugin", "(", "self", ",", "cmd", ",", "input_json", ")", ":", "# Calculate length of input", "input_length", "=", "len", "(", "input_json", ")", "length_bytes_le", "=", "struct", ".", "pack", "(", "'<I'", ",", "input_length", ")", "request", "=",...
Calls the plugin and validates the response.
[ "Calls", "the", "plugin", "and", "validates", "the", "response", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L170-L232
train
43,125
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalInit
def InternalInit(self): """Initializes the device and obtains channel id.""" self.cid = UsbHidTransport.U2FHID_BROADCAST_CID nonce = bytearray(os.urandom(8)) r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce) if len(r) < 17: raise errors.HidError('unexpected init reply len') if r[0:8] != nonce: raise errors.HidError('nonce mismatch') self.cid = bytearray(r[8:12]) self.u2fhid_version = r[12]
python
def InternalInit(self): """Initializes the device and obtains channel id.""" self.cid = UsbHidTransport.U2FHID_BROADCAST_CID nonce = bytearray(os.urandom(8)) r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce) if len(r) < 17: raise errors.HidError('unexpected init reply len') if r[0:8] != nonce: raise errors.HidError('nonce mismatch') self.cid = bytearray(r[8:12]) self.u2fhid_version = r[12]
[ "def", "InternalInit", "(", "self", ")", ":", "self", ".", "cid", "=", "UsbHidTransport", ".", "U2FHID_BROADCAST_CID", "nonce", "=", "bytearray", "(", "os", ".", "urandom", "(", "8", ")", ")", "r", "=", "self", ".", "InternalExchange", "(", "UsbHidTranspor...
Initializes the device and obtains channel id.
[ "Initializes", "the", "device", "and", "obtains", "channel", "id", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L226-L237
train
43,126
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalExchange
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload) ret_cmd, ret_payload = self.InternalRecv() if ret_cmd == UsbHidTransport.U2FHID_ERROR: if ret_payload == UsbHidTransport.ERR_CHANNEL_BUSY: time.sleep(0.5) continue raise errors.HidError('Device error: %d' % int(ret_payload[0])) elif ret_cmd != cmd: raise errors.HidError('Command mismatch!') return ret_payload raise errors.HidError('Device Busy. Please retry')
python
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload) ret_cmd, ret_payload = self.InternalRecv() if ret_cmd == UsbHidTransport.U2FHID_ERROR: if ret_payload == UsbHidTransport.ERR_CHANNEL_BUSY: time.sleep(0.5) continue raise errors.HidError('Device error: %d' % int(ret_payload[0])) elif ret_cmd != cmd: raise errors.HidError('Command mismatch!') return ret_payload raise errors.HidError('Device Busy. Please retry')
[ "def", "InternalExchange", "(", "self", ",", "cmd", ",", "payload_in", ")", ":", "# make a copy because we destroy it below", "self", ".", "logger", ".", "debug", "(", "'payload: '", "+", "str", "(", "list", "(", "payload_in", ")", ")", ")", "payload", "=", ...
Sends and receives a message from the device.
[ "Sends", "and", "receives", "a", "message", "from", "the", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L239-L258
train
43,127
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalSend
def InternalSend(self, cmd, payload): """Sends a message to the device, including fragmenting it.""" length_to_send = len(payload) max_payload = self.packet_size - 7 first_frame = payload[0:max_payload] first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd, len(payload), first_frame) del payload[0:max_payload] length_to_send -= len(first_frame) self.InternalSendPacket(first_packet) seq = 0 while length_to_send > 0: max_payload = self.packet_size - 5 next_frame = payload[0:max_payload] del payload[0:max_payload] length_to_send -= len(next_frame) next_packet = UsbHidTransport.ContPacket(self.packet_size, self.cid, seq, next_frame) self.InternalSendPacket(next_packet) seq += 1
python
def InternalSend(self, cmd, payload): """Sends a message to the device, including fragmenting it.""" length_to_send = len(payload) max_payload = self.packet_size - 7 first_frame = payload[0:max_payload] first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd, len(payload), first_frame) del payload[0:max_payload] length_to_send -= len(first_frame) self.InternalSendPacket(first_packet) seq = 0 while length_to_send > 0: max_payload = self.packet_size - 5 next_frame = payload[0:max_payload] del payload[0:max_payload] length_to_send -= len(next_frame) next_packet = UsbHidTransport.ContPacket(self.packet_size, self.cid, seq, next_frame) self.InternalSendPacket(next_packet) seq += 1
[ "def", "InternalSend", "(", "self", ",", "cmd", ",", "payload", ")", ":", "length_to_send", "=", "len", "(", "payload", ")", "max_payload", "=", "self", ".", "packet_size", "-", "7", "first_frame", "=", "payload", "[", "0", ":", "max_payload", "]", "firs...
Sends a message to the device, including fragmenting it.
[ "Sends", "a", "message", "to", "the", "device", "including", "fragmenting", "it", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L260-L281
train
43,128
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalRecv
def InternalRecv(self): """Receives a message from the device, including defragmenting it.""" first_read = self.InternalReadFrame() first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size, first_read) data = first_packet.payload to_read = first_packet.size - len(first_packet.payload) seq = 0 while to_read > 0: next_read = self.InternalReadFrame() next_packet = UsbHidTransport.ContPacket.FromWireFormat(self.packet_size, next_read) if self.cid != next_packet.cid: # Skip over packets that are for communication with other clients. # HID is broadcast, so we see potentially all communication from the # device. For well-behaved devices, these should be BUSY messages # sent to other clients of the device because at this point we're # in mid-message transit. continue if seq != next_packet.seq: raise errors.HardwareError('Packets received out of order') # This packet for us at this point, so debit it against our # balance of bytes to read. to_read -= len(next_packet.payload) data.extend(next_packet.payload) seq += 1 # truncate incomplete frames data = data[0:first_packet.size] return (first_packet.cmd, data)
python
def InternalRecv(self): """Receives a message from the device, including defragmenting it.""" first_read = self.InternalReadFrame() first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size, first_read) data = first_packet.payload to_read = first_packet.size - len(first_packet.payload) seq = 0 while to_read > 0: next_read = self.InternalReadFrame() next_packet = UsbHidTransport.ContPacket.FromWireFormat(self.packet_size, next_read) if self.cid != next_packet.cid: # Skip over packets that are for communication with other clients. # HID is broadcast, so we see potentially all communication from the # device. For well-behaved devices, these should be BUSY messages # sent to other clients of the device because at this point we're # in mid-message transit. continue if seq != next_packet.seq: raise errors.HardwareError('Packets received out of order') # This packet for us at this point, so debit it against our # balance of bytes to read. to_read -= len(next_packet.payload) data.extend(next_packet.payload) seq += 1 # truncate incomplete frames data = data[0:first_packet.size] return (first_packet.cmd, data)
[ "def", "InternalRecv", "(", "self", ")", ":", "first_read", "=", "self", ".", "InternalReadFrame", "(", ")", "first_packet", "=", "UsbHidTransport", ".", "InitPacket", ".", "FromWireFormat", "(", "self", ".", "packet_size", ",", "first_read", ")", "data", "=",...
Receives a message from the device, including defragmenting it.
[ "Receives", "a", "message", "from", "the", "device", "including", "defragmenting", "it", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L297-L331
train
43,129
google/pyu2f
pyu2f/hid/__init__.py
InternalPlatformSwitch
def InternalPlatformSwitch(funcname, *args, **kwargs): """Determine, on a platform-specific basis, which module to use.""" # pylint: disable=g-import-not-at-top clz = None if sys.platform.startswith('linux'): from pyu2f.hid import linux clz = linux.LinuxHidDevice elif sys.platform.startswith('win32'): from pyu2f.hid import windows clz = windows.WindowsHidDevice elif sys.platform.startswith('darwin'): from pyu2f.hid import macos clz = macos.MacOsHidDevice if not clz: raise Exception('Unsupported platform: ' + sys.platform) if funcname == '__init__': return clz(*args, **kwargs) return getattr(clz, funcname)(*args, **kwargs)
python
def InternalPlatformSwitch(funcname, *args, **kwargs): """Determine, on a platform-specific basis, which module to use.""" # pylint: disable=g-import-not-at-top clz = None if sys.platform.startswith('linux'): from pyu2f.hid import linux clz = linux.LinuxHidDevice elif sys.platform.startswith('win32'): from pyu2f.hid import windows clz = windows.WindowsHidDevice elif sys.platform.startswith('darwin'): from pyu2f.hid import macos clz = macos.MacOsHidDevice if not clz: raise Exception('Unsupported platform: ' + sys.platform) if funcname == '__init__': return clz(*args, **kwargs) return getattr(clz, funcname)(*args, **kwargs)
[ "def", "InternalPlatformSwitch", "(", "funcname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=g-import-not-at-top", "clz", "=", "None", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "from", "pyu2f", "....
Determine, on a platform-specific basis, which module to use.
[ "Determine", "on", "a", "platform", "-", "specific", "basis", "which", "module", "to", "use", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/__init__.py#L31-L50
train
43,130
google/pyu2f
pyu2f/model.py
ClientData.GetJson
def GetJson(self): """Returns JSON version of ClientData compatible with FIDO spec.""" # The U2F Raw Messages specification specifies that the challenge is encoded # with URL safe Base64 without padding encoding specified in RFC 4648. # Python does not natively support a paddingless encoding, so we simply # remove the padding from the end of the string. server_challenge_b64 = base64.urlsafe_b64encode( self.raw_server_challenge).decode() server_challenge_b64 = server_challenge_b64.rstrip('=') return json.dumps({'typ': self.typ, 'challenge': server_challenge_b64, 'origin': self.origin}, sort_keys=True)
python
def GetJson(self): """Returns JSON version of ClientData compatible with FIDO spec.""" # The U2F Raw Messages specification specifies that the challenge is encoded # with URL safe Base64 without padding encoding specified in RFC 4648. # Python does not natively support a paddingless encoding, so we simply # remove the padding from the end of the string. server_challenge_b64 = base64.urlsafe_b64encode( self.raw_server_challenge).decode() server_challenge_b64 = server_challenge_b64.rstrip('=') return json.dumps({'typ': self.typ, 'challenge': server_challenge_b64, 'origin': self.origin}, sort_keys=True)
[ "def", "GetJson", "(", "self", ")", ":", "# The U2F Raw Messages specification specifies that the challenge is encoded", "# with URL safe Base64 without padding encoding specified in RFC 4648.", "# Python does not natively support a paddingless encoding, so we simply", "# remove the padding from t...
Returns JSON version of ClientData compatible with FIDO spec.
[ "Returns", "JSON", "version", "of", "ClientData", "compatible", "with", "FIDO", "spec", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/model.py#L43-L55
train
43,131
google/pyu2f
pyu2f/hid/linux.py
GetValueLength
def GetValueLength(rd, pos): """Get value length for a key in rd. For a key at position pos in the Report Descriptor rd, return the length of the associated value. This supports both short and long format values. Args: rd: Report Descriptor pos: The position of the key in rd. Returns: (key_size, data_len) where key_size is the number of bytes occupied by the key and data_len is the length of the value associated by the key. """ rd = bytearray(rd) key = rd[pos] if key == LONG_ITEM_ENCODING: # If the key is tagged as a long item (0xfe), then the format is # [key (1 byte)] [data len (1 byte)] [item tag (1 byte)] [data (n # bytes)]. # Thus, the entire key record is 3 bytes long. if pos + 1 < len(rd): return (3, rd[pos + 1]) else: raise errors.HidError('Malformed report descriptor') else: # If the key is tagged as a short item, then the item tag and data len are # packed into one byte. The format is thus: # [tag (high 4 bits)] [type (2 bits)] [size code (2 bits)] [data (n bytes)]. # The size code specifies 1,2, or 4 bytes (0x03 means 4 bytes). code = key & 0x03 if code <= 0x02: return (1, code) elif code == 0x03: return (1, 4) raise errors.HidError('Cannot happen')
python
def GetValueLength(rd, pos): """Get value length for a key in rd. For a key at position pos in the Report Descriptor rd, return the length of the associated value. This supports both short and long format values. Args: rd: Report Descriptor pos: The position of the key in rd. Returns: (key_size, data_len) where key_size is the number of bytes occupied by the key and data_len is the length of the value associated by the key. """ rd = bytearray(rd) key = rd[pos] if key == LONG_ITEM_ENCODING: # If the key is tagged as a long item (0xfe), then the format is # [key (1 byte)] [data len (1 byte)] [item tag (1 byte)] [data (n # bytes)]. # Thus, the entire key record is 3 bytes long. if pos + 1 < len(rd): return (3, rd[pos + 1]) else: raise errors.HidError('Malformed report descriptor') else: # If the key is tagged as a short item, then the item tag and data len are # packed into one byte. The format is thus: # [tag (high 4 bits)] [type (2 bits)] [size code (2 bits)] [data (n bytes)]. # The size code specifies 1,2, or 4 bytes (0x03 means 4 bytes). code = key & 0x03 if code <= 0x02: return (1, code) elif code == 0x03: return (1, 4) raise errors.HidError('Cannot happen')
[ "def", "GetValueLength", "(", "rd", ",", "pos", ")", ":", "rd", "=", "bytearray", "(", "rd", ")", "key", "=", "rd", "[", "pos", "]", "if", "key", "==", "LONG_ITEM_ENCODING", ":", "# If the key is tagged as a long item (0xfe), then the format is", "# [key (1 byte)]...
Get value length for a key in rd. For a key at position pos in the Report Descriptor rd, return the length of the associated value. This supports both short and long format values. Args: rd: Report Descriptor pos: The position of the key in rd. Returns: (key_size, data_len) where key_size is the number of bytes occupied by the key and data_len is the length of the value associated by the key.
[ "Get", "value", "length", "for", "a", "key", "in", "rd", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/linux.py#L35-L72
train
43,132
google/pyu2f
pyu2f/hid/linux.py
ReadLsbBytes
def ReadLsbBytes(rd, offset, value_size): """Reads value_size bytes from rd at offset, least signifcant byte first.""" encoding = None if value_size == 1: encoding = '<B' elif value_size == 2: encoding = '<H' elif value_size == 4: encoding = '<L' else: raise errors.HidError('Invalid value size specified') ret, = struct.unpack(encoding, rd[offset:offset + value_size]) return ret
python
def ReadLsbBytes(rd, offset, value_size): """Reads value_size bytes from rd at offset, least signifcant byte first.""" encoding = None if value_size == 1: encoding = '<B' elif value_size == 2: encoding = '<H' elif value_size == 4: encoding = '<L' else: raise errors.HidError('Invalid value size specified') ret, = struct.unpack(encoding, rd[offset:offset + value_size]) return ret
[ "def", "ReadLsbBytes", "(", "rd", ",", "offset", ",", "value_size", ")", ":", "encoding", "=", "None", "if", "value_size", "==", "1", ":", "encoding", "=", "'<B'", "elif", "value_size", "==", "2", ":", "encoding", "=", "'<H'", "elif", "value_size", "==",...
Reads value_size bytes from rd at offset, least signifcant byte first.
[ "Reads", "value_size", "bytes", "from", "rd", "at", "offset", "least", "signifcant", "byte", "first", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/linux.py#L75-L89
train
43,133
google/pyu2f
pyu2f/hid/linux.py
ParseReportDescriptor
def ParseReportDescriptor(rd, desc): """Parse the binary report descriptor. Parse the binary report descriptor into a DeviceDescriptor object. Args: rd: The binary report descriptor desc: The DeviceDescriptor object to update with the results from parsing the descriptor. Returns: None """ rd = bytearray(rd) pos = 0 report_count = None report_size = None usage_page = None usage = None while pos < len(rd): key = rd[pos] # First step, determine the value encoding (either long or short). key_size, value_length = GetValueLength(rd, pos) if key & REPORT_DESCRIPTOR_KEY_MASK == INPUT_ITEM: if report_count and report_size: byte_length = (report_count * report_size) // 8 desc.internal_max_in_report_len = max( desc.internal_max_in_report_len, byte_length) report_count = None report_size = None elif key & REPORT_DESCRIPTOR_KEY_MASK == OUTPUT_ITEM: if report_count and report_size: byte_length = (report_count * report_size) // 8 desc.internal_max_out_report_len = max( desc.internal_max_out_report_len, byte_length) report_count = None report_size = None elif key & REPORT_DESCRIPTOR_KEY_MASK == COLLECTION_ITEM: if usage_page: desc.usage_page = usage_page if usage: desc.usage = usage elif key & REPORT_DESCRIPTOR_KEY_MASK == REPORT_COUNT: if len(rd) >= pos + 1 + value_length: report_count = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == REPORT_SIZE: if len(rd) >= pos + 1 + value_length: report_size = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == USAGE_PAGE: if len(rd) >= pos + 1 + value_length: usage_page = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == USAGE: if len(rd) >= pos + 1 + value_length: usage = ReadLsbBytes(rd, pos + 1, value_length) pos += value_length + key_size return desc
python
def ParseReportDescriptor(rd, desc): """Parse the binary report descriptor. Parse the binary report descriptor into a DeviceDescriptor object. Args: rd: The binary report descriptor desc: The DeviceDescriptor object to update with the results from parsing the descriptor. Returns: None """ rd = bytearray(rd) pos = 0 report_count = None report_size = None usage_page = None usage = None while pos < len(rd): key = rd[pos] # First step, determine the value encoding (either long or short). key_size, value_length = GetValueLength(rd, pos) if key & REPORT_DESCRIPTOR_KEY_MASK == INPUT_ITEM: if report_count and report_size: byte_length = (report_count * report_size) // 8 desc.internal_max_in_report_len = max( desc.internal_max_in_report_len, byte_length) report_count = None report_size = None elif key & REPORT_DESCRIPTOR_KEY_MASK == OUTPUT_ITEM: if report_count and report_size: byte_length = (report_count * report_size) // 8 desc.internal_max_out_report_len = max( desc.internal_max_out_report_len, byte_length) report_count = None report_size = None elif key & REPORT_DESCRIPTOR_KEY_MASK == COLLECTION_ITEM: if usage_page: desc.usage_page = usage_page if usage: desc.usage = usage elif key & REPORT_DESCRIPTOR_KEY_MASK == REPORT_COUNT: if len(rd) >= pos + 1 + value_length: report_count = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == REPORT_SIZE: if len(rd) >= pos + 1 + value_length: report_size = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == USAGE_PAGE: if len(rd) >= pos + 1 + value_length: usage_page = ReadLsbBytes(rd, pos + 1, value_length) elif key & REPORT_DESCRIPTOR_KEY_MASK == USAGE: if len(rd) >= pos + 1 + value_length: usage = ReadLsbBytes(rd, pos + 1, value_length) pos += value_length + key_size return desc
[ "def", "ParseReportDescriptor", "(", "rd", ",", "desc", ")", ":", "rd", "=", "bytearray", "(", "rd", ")", "pos", "=", "0", "report_count", "=", "None", "report_size", "=", "None", "usage_page", "=", "None", "usage", "=", "None", "while", "pos", "<", "l...
Parse the binary report descriptor. Parse the binary report descriptor into a DeviceDescriptor object. Args: rd: The binary report descriptor desc: The DeviceDescriptor object to update with the results from parsing the descriptor. Returns: None
[ "Parse", "the", "binary", "report", "descriptor", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/linux.py#L96-L156
train
43,134
google/pyu2f
pyu2f/hid/windows.py
FillDeviceAttributes
def FillDeviceAttributes(device, descriptor): """Fill out the attributes of the device. Fills the devices HidAttributes and product string into the descriptor. Args: device: A handle to the open device descriptor: The DeviceDescriptor to populate with the attributes. Returns: None Raises: WindowsError when unable to obtain attributes or product string. """ attributes = HidAttributes() result = hid.HidD_GetAttributes(device, ctypes.byref(attributes)) if not result: raise ctypes.WinError() buf = ctypes.create_string_buffer(1024) result = hid.HidD_GetProductString(device, buf, 1024) if not result: raise ctypes.WinError() descriptor.vendor_id = attributes.VendorID descriptor.product_id = attributes.ProductID descriptor.product_string = ctypes.wstring_at(buf)
python
def FillDeviceAttributes(device, descriptor): """Fill out the attributes of the device. Fills the devices HidAttributes and product string into the descriptor. Args: device: A handle to the open device descriptor: The DeviceDescriptor to populate with the attributes. Returns: None Raises: WindowsError when unable to obtain attributes or product string. """ attributes = HidAttributes() result = hid.HidD_GetAttributes(device, ctypes.byref(attributes)) if not result: raise ctypes.WinError() buf = ctypes.create_string_buffer(1024) result = hid.HidD_GetProductString(device, buf, 1024) if not result: raise ctypes.WinError() descriptor.vendor_id = attributes.VendorID descriptor.product_id = attributes.ProductID descriptor.product_string = ctypes.wstring_at(buf)
[ "def", "FillDeviceAttributes", "(", "device", ",", "descriptor", ")", ":", "attributes", "=", "HidAttributes", "(", ")", "result", "=", "hid", ".", "HidD_GetAttributes", "(", "device", ",", "ctypes", ".", "byref", "(", "attributes", ")", ")", "if", "not", ...
Fill out the attributes of the device. Fills the devices HidAttributes and product string into the descriptor. Args: device: A handle to the open device descriptor: The DeviceDescriptor to populate with the attributes. Returns: None Raises: WindowsError when unable to obtain attributes or product string.
[ "Fill", "out", "the", "attributes", "of", "the", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/windows.py#L147-L178
train
43,135
google/pyu2f
pyu2f/hid/windows.py
FillDeviceCapabilities
def FillDeviceCapabilities(device, descriptor): """Fill out device capabilities. Fills the HidCapabilitites of the device into descriptor. Args: device: A handle to the open device descriptor: DeviceDescriptor to populate with the capabilities Returns: none Raises: WindowsError when unable to obtain capabilitites. """ preparsed_data = PHIDP_PREPARSED_DATA(0) ret = hid.HidD_GetPreparsedData(device, ctypes.byref(preparsed_data)) if not ret: raise ctypes.WinError() try: caps = HidCapabilities() ret = hid.HidP_GetCaps(preparsed_data, ctypes.byref(caps)) if ret != HIDP_STATUS_SUCCESS: raise ctypes.WinError() descriptor.usage = caps.Usage descriptor.usage_page = caps.UsagePage descriptor.internal_max_in_report_len = caps.InputReportByteLength descriptor.internal_max_out_report_len = caps.OutputReportByteLength finally: hid.HidD_FreePreparsedData(preparsed_data)
python
def FillDeviceCapabilities(device, descriptor): """Fill out device capabilities. Fills the HidCapabilitites of the device into descriptor. Args: device: A handle to the open device descriptor: DeviceDescriptor to populate with the capabilities Returns: none Raises: WindowsError when unable to obtain capabilitites. """ preparsed_data = PHIDP_PREPARSED_DATA(0) ret = hid.HidD_GetPreparsedData(device, ctypes.byref(preparsed_data)) if not ret: raise ctypes.WinError() try: caps = HidCapabilities() ret = hid.HidP_GetCaps(preparsed_data, ctypes.byref(caps)) if ret != HIDP_STATUS_SUCCESS: raise ctypes.WinError() descriptor.usage = caps.Usage descriptor.usage_page = caps.UsagePage descriptor.internal_max_in_report_len = caps.InputReportByteLength descriptor.internal_max_out_report_len = caps.OutputReportByteLength finally: hid.HidD_FreePreparsedData(preparsed_data)
[ "def", "FillDeviceCapabilities", "(", "device", ",", "descriptor", ")", ":", "preparsed_data", "=", "PHIDP_PREPARSED_DATA", "(", "0", ")", "ret", "=", "hid", ".", "HidD_GetPreparsedData", "(", "device", ",", "ctypes", ".", "byref", "(", "preparsed_data", ")", ...
Fill out device capabilities. Fills the HidCapabilitites of the device into descriptor. Args: device: A handle to the open device descriptor: DeviceDescriptor to populate with the capabilities Returns: none Raises: WindowsError when unable to obtain capabilitites.
[ "Fill", "out", "device", "capabilities", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/windows.py#L181-L215
train
43,136
google/pyu2f
pyu2f/hid/windows.py
OpenDevice
def OpenDevice(path, enum=False): """Open the device and return a handle to it.""" desired_access = GENERIC_WRITE | GENERIC_READ share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE if enum: desired_access = 0 h = kernel32.CreateFileA(path, desired_access, share_mode, None, OPEN_EXISTING, 0, None) if h == INVALID_HANDLE_VALUE: raise ctypes.WinError() return h
python
def OpenDevice(path, enum=False): """Open the device and return a handle to it.""" desired_access = GENERIC_WRITE | GENERIC_READ share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE if enum: desired_access = 0 h = kernel32.CreateFileA(path, desired_access, share_mode, None, OPEN_EXISTING, 0, None) if h == INVALID_HANDLE_VALUE: raise ctypes.WinError() return h
[ "def", "OpenDevice", "(", "path", ",", "enum", "=", "False", ")", ":", "desired_access", "=", "GENERIC_WRITE", "|", "GENERIC_READ", "share_mode", "=", "FILE_SHARE_READ", "|", "FILE_SHARE_WRITE", "if", "enum", ":", "desired_access", "=", "0", "h", "=", "kernel3...
Open the device and return a handle to it.
[ "Open", "the", "device", "and", "return", "a", "handle", "to", "it", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/windows.py#L225-L238
train
43,137
google/pyu2f
pyu2f/u2f.py
GetLocalU2FInterface
def GetLocalU2FInterface(origin=socket.gethostname()): """Obtains a U2FInterface for the first valid local U2FHID device found.""" hid_transports = hidtransport.DiscoverLocalHIDU2FDevices() for t in hid_transports: try: return U2FInterface(security_key=hardware.SecurityKey(transport=t), origin=origin) except errors.UnsupportedVersionException: # Skip over devices that don't speak the proper version of the protocol. pass # Unable to find a device raise errors.NoDeviceFoundError()
python
def GetLocalU2FInterface(origin=socket.gethostname()): """Obtains a U2FInterface for the first valid local U2FHID device found.""" hid_transports = hidtransport.DiscoverLocalHIDU2FDevices() for t in hid_transports: try: return U2FInterface(security_key=hardware.SecurityKey(transport=t), origin=origin) except errors.UnsupportedVersionException: # Skip over devices that don't speak the proper version of the protocol. pass # Unable to find a device raise errors.NoDeviceFoundError()
[ "def", "GetLocalU2FInterface", "(", "origin", "=", "socket", ".", "gethostname", "(", ")", ")", ":", "hid_transports", "=", "hidtransport", ".", "DiscoverLocalHIDU2FDevices", "(", ")", "for", "t", "in", "hid_transports", ":", "try", ":", "return", "U2FInterface"...
Obtains a U2FInterface for the first valid local U2FHID device found.
[ "Obtains", "a", "U2FInterface", "for", "the", "first", "valid", "local", "U2FHID", "device", "found", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/u2f.py#L33-L45
train
43,138
google/pyu2f
pyu2f/u2f.py
U2FInterface.Register
def Register(self, app_id, challenge, registered_keys): """Registers app_id with the security key. Executes the U2F registration flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key. registered_keys: List of keys already registered for this app_id+user. Returns: RegisterResponse with key_handle and attestation information in it ( encoded in FIDO U2F binary format within registration_data field). Raises: U2FError: There was some kind of problem with registration (e.g. the device was already registered or there was a timeout waiting for the test of user presence). """ client_data = model.ClientData(model.ClientData.TYP_REGISTRATION, challenge, self.origin) challenge_param = self.InternalSHA256(client_data.GetJson()) app_param = self.InternalSHA256(app_id) for key in registered_keys: try: # skip non U2F_V2 keys if key.version != u'U2F_V2': continue resp = self.security_key.CmdAuthenticate(challenge_param, app_param, key.key_handle, True) # check_only mode CmdAuthenticate should always raise some # exception raise errors.HardwareError('Should Never Happen') except errors.TUPRequiredError: # This indicates key was valid. Thus, no need to register raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) except errors.InvalidKeyHandleError as e: # This is the case of a key for a different token, so we just ignore it. pass except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) # Now register the new key for _ in range(30): try: resp = self.security_key.CmdRegister(challenge_param, app_param) return model.RegisterResponse(resp, client_data) except errors.TUPRequiredError as e: self.security_key.CmdWink() time.sleep(0.5) except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) raise errors.U2FError(errors.U2FError.TIMEOUT)
python
def Register(self, app_id, challenge, registered_keys): """Registers app_id with the security key. Executes the U2F registration flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key. registered_keys: List of keys already registered for this app_id+user. Returns: RegisterResponse with key_handle and attestation information in it ( encoded in FIDO U2F binary format within registration_data field). Raises: U2FError: There was some kind of problem with registration (e.g. the device was already registered or there was a timeout waiting for the test of user presence). """ client_data = model.ClientData(model.ClientData.TYP_REGISTRATION, challenge, self.origin) challenge_param = self.InternalSHA256(client_data.GetJson()) app_param = self.InternalSHA256(app_id) for key in registered_keys: try: # skip non U2F_V2 keys if key.version != u'U2F_V2': continue resp = self.security_key.CmdAuthenticate(challenge_param, app_param, key.key_handle, True) # check_only mode CmdAuthenticate should always raise some # exception raise errors.HardwareError('Should Never Happen') except errors.TUPRequiredError: # This indicates key was valid. Thus, no need to register raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) except errors.InvalidKeyHandleError as e: # This is the case of a key for a different token, so we just ignore it. pass except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) # Now register the new key for _ in range(30): try: resp = self.security_key.CmdRegister(challenge_param, app_param) return model.RegisterResponse(resp, client_data) except errors.TUPRequiredError as e: self.security_key.CmdWink() time.sleep(0.5) except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) raise errors.U2FError(errors.U2FError.TIMEOUT)
[ "def", "Register", "(", "self", ",", "app_id", ",", "challenge", ",", "registered_keys", ")", ":", "client_data", "=", "model", ".", "ClientData", "(", "model", ".", "ClientData", ".", "TYP_REGISTRATION", ",", "challenge", ",", "self", ".", "origin", ")", ...
Registers app_id with the security key. Executes the U2F registration flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key. registered_keys: List of keys already registered for this app_id+user. Returns: RegisterResponse with key_handle and attestation information in it ( encoded in FIDO U2F binary format within registration_data field). Raises: U2FError: There was some kind of problem with registration (e.g. the device was already registered or there was a timeout waiting for the test of user presence).
[ "Registers", "app_id", "with", "the", "security", "key", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/u2f.py#L74-L129
train
43,139
google/pyu2f
pyu2f/u2f.py
U2FInterface.Authenticate
def Authenticate(self, app_id, challenge, registered_keys): """Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key as a bytes object. registered_keys: List of keys already registered for this app_id+user. Returns: SignResponse with client_data, key_handle, and signature_data. The client data is an object, while the signature_data is encoded in FIDO U2F binary format. Raises: U2FError: There was some kind of problem with authentication (e.g. there was a timeout while waiting for the test of user presence.) """ client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION, challenge, self.origin) app_param = self.InternalSHA256(app_id) challenge_param = self.InternalSHA256(client_data.GetJson()) num_invalid_keys = 0 for key in registered_keys: try: if key.version != u'U2F_V2': continue for _ in range(30): try: resp = self.security_key.CmdAuthenticate(challenge_param, app_param, key.key_handle) return model.SignResponse(key.key_handle, resp, client_data) except errors.TUPRequiredError: self.security_key.CmdWink() time.sleep(0.5) except errors.InvalidKeyHandleError: num_invalid_keys += 1 continue except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) if num_invalid_keys == len(registered_keys): # In this case, all provided keys were invalid. raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) # In this case, the TUP was not pressed. raise errors.U2FError(errors.U2FError.TIMEOUT)
python
def Authenticate(self, app_id, challenge, registered_keys): """Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key as a bytes object. registered_keys: List of keys already registered for this app_id+user. Returns: SignResponse with client_data, key_handle, and signature_data. The client data is an object, while the signature_data is encoded in FIDO U2F binary format. Raises: U2FError: There was some kind of problem with authentication (e.g. there was a timeout while waiting for the test of user presence.) """ client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION, challenge, self.origin) app_param = self.InternalSHA256(app_id) challenge_param = self.InternalSHA256(client_data.GetJson()) num_invalid_keys = 0 for key in registered_keys: try: if key.version != u'U2F_V2': continue for _ in range(30): try: resp = self.security_key.CmdAuthenticate(challenge_param, app_param, key.key_handle) return model.SignResponse(key.key_handle, resp, client_data) except errors.TUPRequiredError: self.security_key.CmdWink() time.sleep(0.5) except errors.InvalidKeyHandleError: num_invalid_keys += 1 continue except errors.HardwareError as e: raise errors.U2FError(errors.U2FError.BAD_REQUEST, e) if num_invalid_keys == len(registered_keys): # In this case, all provided keys were invalid. raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE) # In this case, the TUP was not pressed. raise errors.U2FError(errors.U2FError.TIMEOUT)
[ "def", "Authenticate", "(", "self", ",", "app_id", ",", "challenge", ",", "registered_keys", ")", ":", "client_data", "=", "model", ".", "ClientData", "(", "model", ".", "ClientData", ".", "TYP_AUTHENTICATION", ",", "challenge", ",", "self", ".", "origin", "...
Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key as a bytes object. registered_keys: List of keys already registered for this app_id+user. Returns: SignResponse with client_data, key_handle, and signature_data. The client data is an object, while the signature_data is encoded in FIDO U2F binary format. Raises: U2FError: There was some kind of problem with authentication (e.g. there was a timeout while waiting for the test of user presence.)
[ "Authenticates", "app_id", "with", "the", "security", "key", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/u2f.py#L131-L178
train
43,140
google/pyu2f
pyu2f/hardware.py
SecurityKey.CmdRegister
def CmdRegister(self, challenge_param, app_param): """Register security key. Ask the security key to register with a particular origin & client. Args: challenge_param: Arbitrary 32 byte challenge string. app_param: Arbitrary 32 byte applciation parameter. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: A Test of User Precense is required to proceed. ApduError: Something went wrong on the device. """ self.logger.debug('CmdRegister') if len(challenge_param) != 32 or len(app_param) != 32: raise errors.InvalidRequestError() body = bytearray(challenge_param + app_param) response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_REGISTER, 0x03, # Per the U2F reference code tests 0x00, body)) response.CheckSuccessOrRaise() return response.body
python
def CmdRegister(self, challenge_param, app_param): """Register security key. Ask the security key to register with a particular origin & client. Args: challenge_param: Arbitrary 32 byte challenge string. app_param: Arbitrary 32 byte applciation parameter. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: A Test of User Precense is required to proceed. ApduError: Something went wrong on the device. """ self.logger.debug('CmdRegister') if len(challenge_param) != 32 or len(app_param) != 32: raise errors.InvalidRequestError() body = bytearray(challenge_param + app_param) response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_REGISTER, 0x03, # Per the U2F reference code tests 0x00, body)) response.CheckSuccessOrRaise() return response.body
[ "def", "CmdRegister", "(", "self", ",", "challenge_param", ",", "app_param", ")", ":", "self", ".", "logger", ".", "debug", "(", "'CmdRegister'", ")", "if", "len", "(", "challenge_param", ")", "!=", "32", "or", "len", "(", "app_param", ")", "!=", "32", ...
Register security key. Ask the security key to register with a particular origin & client. Args: challenge_param: Arbitrary 32 byte challenge string. app_param: Arbitrary 32 byte applciation parameter. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: A Test of User Precense is required to proceed. ApduError: Something went wrong on the device.
[ "Register", "security", "key", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hardware.py#L38-L69
train
43,141
google/pyu2f
pyu2f/hardware.py
SecurityKey.CmdAuthenticate
def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False): """Attempt to obtain an authentication signature. Ask the security key to sign a challenge for a particular key handle in order to authenticate the user. Args: challenge_param: SHA-256 hash of client_data object as a bytes object. app_param: SHA-256 hash of the app id as a bytes object. key_handle: The key handle to use to issue the signature as a bytes object. check_only: If true, only check if key_handle is valid. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: If check_only is False, a Test of User Precense is required to proceed. If check_only is True, this means the key_handle is valid. InvalidKeyHandleError: The key_handle is not valid for this device. ApduError: Something else went wrong on the device. """ self.logger.debug('CmdAuthenticate') if len(challenge_param) != 32 or len(app_param) != 32: raise errors.InvalidRequestError() control = 0x07 if check_only else 0x03 body = bytearray(challenge_param + app_param + bytearray([len(key_handle)]) + key_handle) response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_AUTH, control, 0x00, body)) response.CheckSuccessOrRaise() return response.body
python
def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False): """Attempt to obtain an authentication signature. Ask the security key to sign a challenge for a particular key handle in order to authenticate the user. Args: challenge_param: SHA-256 hash of client_data object as a bytes object. app_param: SHA-256 hash of the app id as a bytes object. key_handle: The key handle to use to issue the signature as a bytes object. check_only: If true, only check if key_handle is valid. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: If check_only is False, a Test of User Precense is required to proceed. If check_only is True, this means the key_handle is valid. InvalidKeyHandleError: The key_handle is not valid for this device. ApduError: Something else went wrong on the device. """ self.logger.debug('CmdAuthenticate') if len(challenge_param) != 32 or len(app_param) != 32: raise errors.InvalidRequestError() control = 0x07 if check_only else 0x03 body = bytearray(challenge_param + app_param + bytearray([len(key_handle)]) + key_handle) response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_AUTH, control, 0x00, body)) response.CheckSuccessOrRaise() return response.body
[ "def", "CmdAuthenticate", "(", "self", ",", "challenge_param", ",", "app_param", ",", "key_handle", ",", "check_only", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "'CmdAuthenticate'", ")", "if", "len", "(", "challenge_param", ")", "!=",...
Attempt to obtain an authentication signature. Ask the security key to sign a challenge for a particular key handle in order to authenticate the user. Args: challenge_param: SHA-256 hash of client_data object as a bytes object. app_param: SHA-256 hash of the app id as a bytes object. key_handle: The key handle to use to issue the signature as a bytes object. check_only: If true, only check if key_handle is valid. Returns: A binary structure containing the key handle, attestation, and a signature over that by the attestation key. The precise format is dictated by the FIDO U2F specs. Raises: TUPRequiredError: If check_only is False, a Test of User Precense is required to proceed. If check_only is True, this means the key_handle is valid. InvalidKeyHandleError: The key_handle is not valid for this device. ApduError: Something else went wrong on the device.
[ "Attempt", "to", "obtain", "an", "authentication", "signature", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hardware.py#L71-L112
train
43,142
google/pyu2f
pyu2f/hardware.py
SecurityKey.CmdVersion
def CmdVersion(self): """Obtain the version of the device and test transport format. Obtains the version of the device and determines whether to use ISO 7816-4 or the U2f variant. This function should be called at least once before CmdAuthenticate or CmdRegister to make sure the object is using the proper transport for the device. Returns: The version of the U2F protocol in use. """ self.logger.debug('CmdVersion') response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_VERSION, 0x00, 0x00)) if not response.IsSuccess(): raise errors.ApduError(response.sw1, response.sw2) return response.body
python
def CmdVersion(self): """Obtain the version of the device and test transport format. Obtains the version of the device and determines whether to use ISO 7816-4 or the U2f variant. This function should be called at least once before CmdAuthenticate or CmdRegister to make sure the object is using the proper transport for the device. Returns: The version of the U2F protocol in use. """ self.logger.debug('CmdVersion') response = self.InternalSendApdu(apdu.CommandApdu( 0, apdu.CMD_VERSION, 0x00, 0x00)) if not response.IsSuccess(): raise errors.ApduError(response.sw1, response.sw2) return response.body
[ "def", "CmdVersion", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'CmdVersion'", ")", "response", "=", "self", ".", "InternalSendApdu", "(", "apdu", ".", "CommandApdu", "(", "0", ",", "apdu", ".", "CMD_VERSION", ",", "0x00", ",", "...
Obtain the version of the device and test transport format. Obtains the version of the device and determines whether to use ISO 7816-4 or the U2f variant. This function should be called at least once before CmdAuthenticate or CmdRegister to make sure the object is using the proper transport for the device. Returns: The version of the U2F protocol in use.
[ "Obtain", "the", "version", "of", "the", "device", "and", "test", "transport", "format", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hardware.py#L114-L132
train
43,143
google/pyu2f
pyu2f/hardware.py
SecurityKey.InternalSendApdu
def InternalSendApdu(self, apdu_to_send): """Send an APDU to the device. Sends an APDU to the device, possibly falling back to the legacy encoding format that is not ISO7816-4 compatible. Args: apdu_to_send: The CommandApdu object to send Returns: The ResponseApdu object constructed out of the devices reply. """ response = None if not self.use_legacy_format: response = apdu.ResponseApdu(self.transport.SendMsgBytes( apdu_to_send.ToByteArray())) if response.sw1 == 0x67 and response.sw2 == 0x00: # If we failed using the standard format, retry with the # legacy format. self.use_legacy_format = True return self.InternalSendApdu(apdu_to_send) else: response = apdu.ResponseApdu(self.transport.SendMsgBytes( apdu_to_send.ToLegacyU2FByteArray())) return response
python
def InternalSendApdu(self, apdu_to_send): """Send an APDU to the device. Sends an APDU to the device, possibly falling back to the legacy encoding format that is not ISO7816-4 compatible. Args: apdu_to_send: The CommandApdu object to send Returns: The ResponseApdu object constructed out of the devices reply. """ response = None if not self.use_legacy_format: response = apdu.ResponseApdu(self.transport.SendMsgBytes( apdu_to_send.ToByteArray())) if response.sw1 == 0x67 and response.sw2 == 0x00: # If we failed using the standard format, retry with the # legacy format. self.use_legacy_format = True return self.InternalSendApdu(apdu_to_send) else: response = apdu.ResponseApdu(self.transport.SendMsgBytes( apdu_to_send.ToLegacyU2FByteArray())) return response
[ "def", "InternalSendApdu", "(", "self", ",", "apdu_to_send", ")", ":", "response", "=", "None", "if", "not", "self", ".", "use_legacy_format", ":", "response", "=", "apdu", ".", "ResponseApdu", "(", "self", ".", "transport", ".", "SendMsgBytes", "(", "apdu_t...
Send an APDU to the device. Sends an APDU to the device, possibly falling back to the legacy encoding format that is not ISO7816-4 compatible. Args: apdu_to_send: The CommandApdu object to send Returns: The ResponseApdu object constructed out of the devices reply.
[ "Send", "an", "APDU", "to", "the", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hardware.py#L146-L170
train
43,144
google/pyu2f
pyu2f/hid/macos.py
GetDeviceIntProperty
def GetDeviceIntProperty(dev_ref, key): """Reads int property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID(): raise errors.OsHidError('Expected number type, got {}'.format( cf.CFGetTypeID(type_ref))) out = ctypes.c_int32() ret = cf.CFNumberGetValue(type_ref, K_CF_NUMBER_SINT32_TYPE, ctypes.byref(out)) if not ret: return None return out.value
python
def GetDeviceIntProperty(dev_ref, key): """Reads int property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID(): raise errors.OsHidError('Expected number type, got {}'.format( cf.CFGetTypeID(type_ref))) out = ctypes.c_int32() ret = cf.CFNumberGetValue(type_ref, K_CF_NUMBER_SINT32_TYPE, ctypes.byref(out)) if not ret: return None return out.value
[ "def", "GetDeviceIntProperty", "(", "dev_ref", ",", "key", ")", ":", "cf_key", "=", "CFStr", "(", "key", ")", "type_ref", "=", "iokit", ".", "IOHIDDeviceGetProperty", "(", "dev_ref", ",", "cf_key", ")", "cf", ".", "CFRelease", "(", "cf_key", ")", "if", "...
Reads int property from the HID device.
[ "Reads", "int", "property", "from", "the", "HID", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/macos.py#L194-L212
train
43,145
google/pyu2f
pyu2f/hid/macos.py
GetDeviceStringProperty
def GetDeviceStringProperty(dev_ref, key): """Reads string property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID(): raise errors.OsHidError('Expected string type, got {}'.format( cf.CFGetTypeID(type_ref))) type_ref = ctypes.cast(type_ref, CF_STRING_REF) out = ctypes.create_string_buffer(DEVICE_STRING_PROPERTY_BUFFER_SIZE) ret = cf.CFStringGetCString(type_ref, out, DEVICE_STRING_PROPERTY_BUFFER_SIZE, K_CF_STRING_ENCODING_UTF8) if not ret: return None return out.value.decode('utf8')
python
def GetDeviceStringProperty(dev_ref, key): """Reads string property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID(): raise errors.OsHidError('Expected string type, got {}'.format( cf.CFGetTypeID(type_ref))) type_ref = ctypes.cast(type_ref, CF_STRING_REF) out = ctypes.create_string_buffer(DEVICE_STRING_PROPERTY_BUFFER_SIZE) ret = cf.CFStringGetCString(type_ref, out, DEVICE_STRING_PROPERTY_BUFFER_SIZE, K_CF_STRING_ENCODING_UTF8) if not ret: return None return out.value.decode('utf8')
[ "def", "GetDeviceStringProperty", "(", "dev_ref", ",", "key", ")", ":", "cf_key", "=", "CFStr", "(", "key", ")", "type_ref", "=", "iokit", ".", "IOHIDDeviceGetProperty", "(", "dev_ref", ",", "cf_key", ")", "cf", ".", "CFRelease", "(", "cf_key", ")", "if", ...
Reads string property from the HID device.
[ "Reads", "string", "property", "from", "the", "HID", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/macos.py#L215-L234
train
43,146
google/pyu2f
pyu2f/hid/macos.py
GetDevicePath
def GetDevicePath(device_handle): """Obtains the unique path for the device. Args: device_handle: reference to the device Returns: A unique path for the device, obtained from the IO Registry """ # Obtain device path from IO Registry io_service_obj = iokit.IOHIDDeviceGetService(device_handle) str_buffer = ctypes.create_string_buffer(DEVICE_PATH_BUFFER_SIZE) iokit.IORegistryEntryGetPath(io_service_obj, K_IO_SERVICE_PLANE, str_buffer) return str_buffer.value
python
def GetDevicePath(device_handle): """Obtains the unique path for the device. Args: device_handle: reference to the device Returns: A unique path for the device, obtained from the IO Registry """ # Obtain device path from IO Registry io_service_obj = iokit.IOHIDDeviceGetService(device_handle) str_buffer = ctypes.create_string_buffer(DEVICE_PATH_BUFFER_SIZE) iokit.IORegistryEntryGetPath(io_service_obj, K_IO_SERVICE_PLANE, str_buffer) return str_buffer.value
[ "def", "GetDevicePath", "(", "device_handle", ")", ":", "# Obtain device path from IO Registry", "io_service_obj", "=", "iokit", ".", "IOHIDDeviceGetService", "(", "device_handle", ")", "str_buffer", "=", "ctypes", ".", "create_string_buffer", "(", "DEVICE_PATH_BUFFER_SIZE"...
Obtains the unique path for the device. Args: device_handle: reference to the device Returns: A unique path for the device, obtained from the IO Registry
[ "Obtains", "the", "unique", "path", "for", "the", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/macos.py#L237-L252
train
43,147
google/pyu2f
pyu2f/hid/macos.py
HidReadCallback
def HidReadCallback(read_queue, result, sender, report_type, report_id, report, report_length): """Handles incoming IN report from HID device.""" del result, sender, report_type, report_id # Unused by the callback function incoming_bytes = [report[i] for i in range(report_length)] read_queue.put(incoming_bytes)
python
def HidReadCallback(read_queue, result, sender, report_type, report_id, report, report_length): """Handles incoming IN report from HID device.""" del result, sender, report_type, report_id # Unused by the callback function incoming_bytes = [report[i] for i in range(report_length)] read_queue.put(incoming_bytes)
[ "def", "HidReadCallback", "(", "read_queue", ",", "result", ",", "sender", ",", "report_type", ",", "report_id", ",", "report", ",", "report_length", ")", ":", "del", "result", ",", "sender", ",", "report_type", ",", "report_id", "# Unused by the callback function...
Handles incoming IN report from HID device.
[ "Handles", "incoming", "IN", "report", "from", "HID", "device", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/macos.py#L255-L261
train
43,148
google/pyu2f
pyu2f/hid/macos.py
DeviceReadThread
def DeviceReadThread(hid_device): """Binds a device to the thread's run loop, then starts the run loop. Args: hid_device: The MacOsHidDevice object The HID manager requires a run loop to handle Report reads. This thread function serves that purpose. """ # Schedule device events with run loop hid_device.run_loop_ref = cf.CFRunLoopGetCurrent() if not hid_device.run_loop_ref: logger.error('Failed to get current run loop') return iokit.IOHIDDeviceScheduleWithRunLoop(hid_device.device_handle, hid_device.run_loop_ref, K_CF_RUNLOOP_DEFAULT_MODE) # Run the run loop run_loop_run_result = K_CF_RUN_LOOP_RUN_TIMED_OUT while (run_loop_run_result == K_CF_RUN_LOOP_RUN_TIMED_OUT or run_loop_run_result == K_CF_RUN_LOOP_RUN_HANDLED_SOURCE): run_loop_run_result = cf.CFRunLoopRunInMode( K_CF_RUNLOOP_DEFAULT_MODE, 1000, # Timeout in seconds False) # Return after source handled # log any unexpected run loop exit if run_loop_run_result != K_CF_RUN_LOOP_RUN_STOPPED: logger.error('Unexpected run loop exit code: %d', run_loop_run_result) # Unschedule from run loop iokit.IOHIDDeviceUnscheduleFromRunLoop(hid_device.device_handle, hid_device.run_loop_ref, K_CF_RUNLOOP_DEFAULT_MODE)
python
def DeviceReadThread(hid_device): """Binds a device to the thread's run loop, then starts the run loop. Args: hid_device: The MacOsHidDevice object The HID manager requires a run loop to handle Report reads. This thread function serves that purpose. """ # Schedule device events with run loop hid_device.run_loop_ref = cf.CFRunLoopGetCurrent() if not hid_device.run_loop_ref: logger.error('Failed to get current run loop') return iokit.IOHIDDeviceScheduleWithRunLoop(hid_device.device_handle, hid_device.run_loop_ref, K_CF_RUNLOOP_DEFAULT_MODE) # Run the run loop run_loop_run_result = K_CF_RUN_LOOP_RUN_TIMED_OUT while (run_loop_run_result == K_CF_RUN_LOOP_RUN_TIMED_OUT or run_loop_run_result == K_CF_RUN_LOOP_RUN_HANDLED_SOURCE): run_loop_run_result = cf.CFRunLoopRunInMode( K_CF_RUNLOOP_DEFAULT_MODE, 1000, # Timeout in seconds False) # Return after source handled # log any unexpected run loop exit if run_loop_run_result != K_CF_RUN_LOOP_RUN_STOPPED: logger.error('Unexpected run loop exit code: %d', run_loop_run_result) # Unschedule from run loop iokit.IOHIDDeviceUnscheduleFromRunLoop(hid_device.device_handle, hid_device.run_loop_ref, K_CF_RUNLOOP_DEFAULT_MODE)
[ "def", "DeviceReadThread", "(", "hid_device", ")", ":", "# Schedule device events with run loop", "hid_device", ".", "run_loop_ref", "=", "cf", ".", "CFRunLoopGetCurrent", "(", ")", "if", "not", "hid_device", ".", "run_loop_ref", ":", "logger", ".", "error", "(", ...
Binds a device to the thread's run loop, then starts the run loop. Args: hid_device: The MacOsHidDevice object The HID manager requires a run loop to handle Report reads. This thread function serves that purpose.
[ "Binds", "a", "device", "to", "the", "thread", "s", "run", "loop", "then", "starts", "the", "run", "loop", "." ]
8742d798027a21cbde0704aac0e93269bad2c3d0
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/macos.py#L268-L304
train
43,149
idlesign/django-admirarchy
admirarchy/utils.py
HierarchicalModelAdmin.change_view
def change_view(self, *args, **kwargs): """Renders detailed model edit page.""" Hierarchy.init_hierarchy(self) self.hierarchy.hook_change_view(self, args, kwargs) return super(HierarchicalModelAdmin, self).change_view(*args, **kwargs)
python
def change_view(self, *args, **kwargs): """Renders detailed model edit page.""" Hierarchy.init_hierarchy(self) self.hierarchy.hook_change_view(self, args, kwargs) return super(HierarchicalModelAdmin, self).change_view(*args, **kwargs)
[ "def", "change_view", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "Hierarchy", ".", "init_hierarchy", "(", "self", ")", "self", ".", "hierarchy", ".", "hook_change_view", "(", "self", ",", "args", ",", "kwargs", ")", "return", "su...
Renders detailed model edit page.
[ "Renders", "detailed", "model", "edit", "page", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L37-L43
train
43,150
idlesign/django-admirarchy
admirarchy/utils.py
HierarchicalModelAdmin.action_checkbox
def action_checkbox(self, obj): """Renders checkboxes. Disable checkbox for parent item navigation link. """ if getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False): return '' return super(HierarchicalModelAdmin, self).action_checkbox(obj)
python
def action_checkbox(self, obj): """Renders checkboxes. Disable checkbox for parent item navigation link. """ if getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False): return '' return super(HierarchicalModelAdmin, self).action_checkbox(obj)
[ "def", "action_checkbox", "(", "self", ",", "obj", ")", ":", "if", "getattr", "(", "obj", ",", "Hierarchy", ".", "UPPER_LEVEL_MODEL_ATTR", ",", "False", ")", ":", "return", "''", "return", "super", "(", "HierarchicalModelAdmin", ",", "self", ")", ".", "act...
Renders checkboxes. Disable checkbox for parent item navigation link.
[ "Renders", "checkboxes", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L45-L54
train
43,151
idlesign/django-admirarchy
admirarchy/utils.py
HierarchicalChangeList.get_queryset
def get_queryset(self, request): """Constructs a query set. :param request: :return: """ self._hierarchy.hook_get_queryset(self, request) return super(HierarchicalChangeList, self).get_queryset(request)
python
def get_queryset(self, request): """Constructs a query set. :param request: :return: """ self._hierarchy.hook_get_queryset(self, request) return super(HierarchicalChangeList, self).get_queryset(request)
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "self", ".", "_hierarchy", ".", "hook_get_queryset", "(", "self", ",", "request", ")", "return", "super", "(", "HierarchicalChangeList", ",", "self", ")", ".", "get_queryset", "(", "request", ")" ...
Constructs a query set. :param request: :return:
[ "Constructs", "a", "query", "set", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L121-L129
train
43,152
idlesign/django-admirarchy
admirarchy/utils.py
HierarchicalChangeList.get_results
def get_results(self, request): """Gets query set results. :param request: :return: """ super(HierarchicalChangeList, self).get_results(request) self._hierarchy.hook_get_results(self)
python
def get_results(self, request): """Gets query set results. :param request: :return: """ super(HierarchicalChangeList, self).get_results(request) self._hierarchy.hook_get_results(self)
[ "def", "get_results", "(", "self", ",", "request", ")", ":", "super", "(", "HierarchicalChangeList", ",", "self", ")", ".", "get_results", "(", "request", ")", "self", ".", "_hierarchy", ".", "hook_get_results", "(", "self", ")" ]
Gets query set results. :param request: :return:
[ "Gets", "query", "set", "results", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L131-L139
train
43,153
idlesign/django-admirarchy
admirarchy/utils.py
HierarchicalChangeList.check_field_exists
def check_field_exists(self, field_name): """Implements field exists check for debugging purposes. :param field_name: :return: """ if not settings.DEBUG: return try: self.lookup_opts.get_field(field_name) except FieldDoesNotExist as e: raise AdmirarchyConfigurationError(e)
python
def check_field_exists(self, field_name): """Implements field exists check for debugging purposes. :param field_name: :return: """ if not settings.DEBUG: return try: self.lookup_opts.get_field(field_name) except FieldDoesNotExist as e: raise AdmirarchyConfigurationError(e)
[ "def", "check_field_exists", "(", "self", ",", "field_name", ")", ":", "if", "not", "settings", ".", "DEBUG", ":", "return", "try", ":", "self", ".", "lookup_opts", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", "as", "e", ":", "r...
Implements field exists check for debugging purposes. :param field_name: :return:
[ "Implements", "field", "exists", "check", "for", "debugging", "purposes", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L141-L154
train
43,154
idlesign/django-admirarchy
admirarchy/utils.py
Hierarchy.init_hierarchy
def init_hierarchy(cls, model_admin): """Initializes model admin with hierarchy data.""" hierarchy = getattr(model_admin, 'hierarchy') if hierarchy: if not isinstance(hierarchy, Hierarchy): hierarchy = AdjacencyList() # For `True` and etc. TODO heuristics maybe. else: hierarchy = NoHierarchy() model_admin.hierarchy = hierarchy
python
def init_hierarchy(cls, model_admin): """Initializes model admin with hierarchy data.""" hierarchy = getattr(model_admin, 'hierarchy') if hierarchy: if not isinstance(hierarchy, Hierarchy): hierarchy = AdjacencyList() # For `True` and etc. TODO heuristics maybe. else: hierarchy = NoHierarchy() model_admin.hierarchy = hierarchy
[ "def", "init_hierarchy", "(", "cls", ",", "model_admin", ")", ":", "hierarchy", "=", "getattr", "(", "model_admin", ",", "'hierarchy'", ")", "if", "hierarchy", ":", "if", "not", "isinstance", "(", "hierarchy", ",", "Hierarchy", ")", ":", "hierarchy", "=", ...
Initializes model admin with hierarchy data.
[ "Initializes", "model", "admin", "with", "hierarchy", "data", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L169-L180
train
43,155
idlesign/django-admirarchy
admirarchy/utils.py
Hierarchy.get_pid_from_request
def get_pid_from_request(cls, changelist, request): """Gets parent ID from query string. :param changelist: :param request: :return: """ val = request.GET.get(cls.PARENT_ID_QS_PARAM, False) pid = val or None try: del changelist.params[cls.PARENT_ID_QS_PARAM] except KeyError: pass return pid
python
def get_pid_from_request(cls, changelist, request): """Gets parent ID from query string. :param changelist: :param request: :return: """ val = request.GET.get(cls.PARENT_ID_QS_PARAM, False) pid = val or None try: del changelist.params[cls.PARENT_ID_QS_PARAM] except KeyError: pass return pid
[ "def", "get_pid_from_request", "(", "cls", ",", "changelist", ",", "request", ")", ":", "val", "=", "request", ".", "GET", ".", "get", "(", "cls", ".", "PARENT_ID_QS_PARAM", ",", "False", ")", "pid", "=", "val", "or", "None", "try", ":", "del", "change...
Gets parent ID from query string. :param changelist: :param request: :return:
[ "Gets", "parent", "ID", "from", "query", "string", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L183-L199
train
43,156
idlesign/django-admirarchy
setup.py
read_file
def read_file(fpath): """Reads a file within package directories.""" with io.open(os.path.join(PATH_BASE, fpath)) as f: return f.read()
python
def read_file(fpath): """Reads a file within package directories.""" with io.open(os.path.join(PATH_BASE, fpath)) as f: return f.read()
[ "def", "read_file", "(", "fpath", ")", ":", "with", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "PATH_BASE", ",", "fpath", ")", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Reads a file within package directories.
[ "Reads", "a", "file", "within", "package", "directories", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/setup.py#L10-L13
train
43,157
idlesign/django-admirarchy
setup.py
get_version
def get_version(): """Returns version number, without module import (which can lead to ImportError if some dependencies are unavailable before install.""" contents = read_file(os.path.join('admirarchy', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version
python
def get_version(): """Returns version number, without module import (which can lead to ImportError if some dependencies are unavailable before install.""" contents = read_file(os.path.join('admirarchy', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version
[ "def", "get_version", "(", ")", ":", "contents", "=", "read_file", "(", "os", ".", "path", ".", "join", "(", "'admirarchy'", ",", "'__init__.py'", ")", ")", "version", "=", "re", ".", "search", "(", "'VERSION = \\(([^)]+)\\)'", ",", "contents", ")", "versi...
Returns version number, without module import (which can lead to ImportError if some dependencies are unavailable before install.
[ "Returns", "version", "number", "without", "module", "import", "(", "which", "can", "lead", "to", "ImportError", "if", "some", "dependencies", "are", "unavailable", "before", "install", "." ]
723e4fd212fdebcc156492cb16b9d65356f5ca73
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/setup.py#L16-L22
train
43,158
robotpy/pynetworktables2js
pynetworktables2js/nt_serial.py
NTSerial.process_update
def process_update(self, update): """Process an incoming update from a remote NetworkTables""" data = json.loads(update) NetworkTables.getEntry(data["k"]).setValue(data["v"])
python
def process_update(self, update): """Process an incoming update from a remote NetworkTables""" data = json.loads(update) NetworkTables.getEntry(data["k"]).setValue(data["v"])
[ "def", "process_update", "(", "self", ",", "update", ")", ":", "data", "=", "json", ".", "loads", "(", "update", ")", "NetworkTables", ".", "getEntry", "(", "data", "[", "\"k\"", "]", ")", ".", "setValue", "(", "data", "[", "\"v\"", "]", ")" ]
Process an incoming update from a remote NetworkTables
[ "Process", "an", "incoming", "update", "from", "a", "remote", "NetworkTables" ]
a2a925013b17de38306da36f091262d68610624c
https://github.com/robotpy/pynetworktables2js/blob/a2a925013b17de38306da36f091262d68610624c/pynetworktables2js/nt_serial.py#L25-L28
train
43,159
robotpy/pynetworktables2js
pynetworktables2js/nt_serial.py
NTSerial._send_update
def _send_update(self, data): """Send a NetworkTables update via the stored send_update callback""" if isinstance(data, dict): data = json.dumps(data) self.update_callback(data)
python
def _send_update(self, data): """Send a NetworkTables update via the stored send_update callback""" if isinstance(data, dict): data = json.dumps(data) self.update_callback(data)
[ "def", "_send_update", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "self", ".", "update_callback", "(", "data", ")" ]
Send a NetworkTables update via the stored send_update callback
[ "Send", "a", "NetworkTables", "update", "via", "the", "stored", "send_update", "callback" ]
a2a925013b17de38306da36f091262d68610624c
https://github.com/robotpy/pynetworktables2js/blob/a2a925013b17de38306da36f091262d68610624c/pynetworktables2js/nt_serial.py#L30-L34
train
43,160
robotpy/pynetworktables2js
pynetworktables2js/nt_serial.py
NTSerial._nt_on_change
def _nt_on_change(self, key, value, isNew): """NetworkTables global listener callback""" self._send_update({"k": key, "v": value, "n": isNew})
python
def _nt_on_change(self, key, value, isNew): """NetworkTables global listener callback""" self._send_update({"k": key, "v": value, "n": isNew})
[ "def", "_nt_on_change", "(", "self", ",", "key", ",", "value", ",", "isNew", ")", ":", "self", ".", "_send_update", "(", "{", "\"k\"", ":", "key", ",", "\"v\"", ":", "value", ",", "\"n\"", ":", "isNew", "}", ")" ]
NetworkTables global listener callback
[ "NetworkTables", "global", "listener", "callback" ]
a2a925013b17de38306da36f091262d68610624c
https://github.com/robotpy/pynetworktables2js/blob/a2a925013b17de38306da36f091262d68610624c/pynetworktables2js/nt_serial.py#L36-L38
train
43,161
robotpy/pynetworktables2js
pynetworktables2js/nt_serial.py
NTSerial.close
def close(self): """ Clean up NetworkTables listeners """ NetworkTables.removeGlobalListener(self._nt_on_change) NetworkTables.removeConnectionListener(self._nt_connected)
python
def close(self): """ Clean up NetworkTables listeners """ NetworkTables.removeGlobalListener(self._nt_on_change) NetworkTables.removeConnectionListener(self._nt_connected)
[ "def", "close", "(", "self", ")", ":", "NetworkTables", ".", "removeGlobalListener", "(", "self", ".", "_nt_on_change", ")", "NetworkTables", ".", "removeConnectionListener", "(", "self", ".", "_nt_connected", ")" ]
Clean up NetworkTables listeners
[ "Clean", "up", "NetworkTables", "listeners" ]
a2a925013b17de38306da36f091262d68610624c
https://github.com/robotpy/pynetworktables2js/blob/a2a925013b17de38306da36f091262d68610624c/pynetworktables2js/nt_serial.py#L44-L49
train
43,162
openeemeter/eeweather
eeweather/ranking.py
select_station
def select_station( candidates, coverage_range=None, min_fraction_coverage=0.9, distance_warnings=(50000, 200000), rank=1, ): """ Select a station from a list of candidates that meets given data quality criteria. Parameters ---------- candidates : :any:`pandas.DataFrame` A dataframe of the form given by :any:`eeweather.rank_stations` or :any:`eeweather.combine_ranked_stations`, specifically having at least an index with ``usaf_id`` values and the column ``distance_meters``. Returns ------- isd_station, warnings : tuple of (:any:`eeweather.ISDStation`, list of str) A qualified weather station. ``None`` if no station meets criteria. """ def _test_station(station): if coverage_range is None: return True, [] else: start_date, end_date = coverage_range try: tempC, warnings = eeweather.mockable.load_isd_hourly_temp_data( station, start_date, end_date ) except ISDDataNotAvailableError: return False, [] # reject # TODO(philngo): also need to incorporate within-day limits if len(tempC) > 0: fraction_coverage = tempC.notnull().sum() / float(len(tempC)) return (fraction_coverage > min_fraction_coverage), warnings else: return False, [] # reject def _station_warnings(station, distance_meters): return [ EEWeatherWarning( qualified_name="eeweather.exceeds_maximum_distance", description=( "Distance from target to weather station is greater" "than the specified km." ), data={ "distance_meters": distance_meters, "max_distance_meters": d, "rank": rank, }, ) for d in distance_warnings if distance_meters > d ] n_stations_passed = 0 for usaf_id, row in candidates.iterrows(): station = ISDStation(usaf_id) test_result, warnings = _test_station(station) if test_result: n_stations_passed += 1 if n_stations_passed == rank: if not warnings: warnings = [] warnings.extend(_station_warnings(station, row.distance_meters)) return station, warnings no_station_warning = EEWeatherWarning( qualified_name="eeweather.no_weather_station_selected", description=( "No weather station found with the specified rank and" " minimum fracitional coverage." ), data={"rank": rank, "min_fraction_coverage": min_fraction_coverage}, ) return None, [no_station_warning]
python
def select_station( candidates, coverage_range=None, min_fraction_coverage=0.9, distance_warnings=(50000, 200000), rank=1, ): """ Select a station from a list of candidates that meets given data quality criteria. Parameters ---------- candidates : :any:`pandas.DataFrame` A dataframe of the form given by :any:`eeweather.rank_stations` or :any:`eeweather.combine_ranked_stations`, specifically having at least an index with ``usaf_id`` values and the column ``distance_meters``. Returns ------- isd_station, warnings : tuple of (:any:`eeweather.ISDStation`, list of str) A qualified weather station. ``None`` if no station meets criteria. """ def _test_station(station): if coverage_range is None: return True, [] else: start_date, end_date = coverage_range try: tempC, warnings = eeweather.mockable.load_isd_hourly_temp_data( station, start_date, end_date ) except ISDDataNotAvailableError: return False, [] # reject # TODO(philngo): also need to incorporate within-day limits if len(tempC) > 0: fraction_coverage = tempC.notnull().sum() / float(len(tempC)) return (fraction_coverage > min_fraction_coverage), warnings else: return False, [] # reject def _station_warnings(station, distance_meters): return [ EEWeatherWarning( qualified_name="eeweather.exceeds_maximum_distance", description=( "Distance from target to weather station is greater" "than the specified km." ), data={ "distance_meters": distance_meters, "max_distance_meters": d, "rank": rank, }, ) for d in distance_warnings if distance_meters > d ] n_stations_passed = 0 for usaf_id, row in candidates.iterrows(): station = ISDStation(usaf_id) test_result, warnings = _test_station(station) if test_result: n_stations_passed += 1 if n_stations_passed == rank: if not warnings: warnings = [] warnings.extend(_station_warnings(station, row.distance_meters)) return station, warnings no_station_warning = EEWeatherWarning( qualified_name="eeweather.no_weather_station_selected", description=( "No weather station found with the specified rank and" " minimum fracitional coverage." ), data={"rank": rank, "min_fraction_coverage": min_fraction_coverage}, ) return None, [no_station_warning]
[ "def", "select_station", "(", "candidates", ",", "coverage_range", "=", "None", ",", "min_fraction_coverage", "=", "0.9", ",", "distance_warnings", "=", "(", "50000", ",", "200000", ")", ",", "rank", "=", "1", ",", ")", ":", "def", "_test_station", "(", "s...
Select a station from a list of candidates that meets given data quality criteria. Parameters ---------- candidates : :any:`pandas.DataFrame` A dataframe of the form given by :any:`eeweather.rank_stations` or :any:`eeweather.combine_ranked_stations`, specifically having at least an index with ``usaf_id`` values and the column ``distance_meters``. Returns ------- isd_station, warnings : tuple of (:any:`eeweather.ISDStation`, list of str) A qualified weather station. ``None`` if no station meets criteria.
[ "Select", "a", "station", "from", "a", "list", "of", "candidates", "that", "meets", "given", "data", "quality", "criteria", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/ranking.py#L358-L438
train
43,163
openeemeter/eeweather
eeweather/database.py
_load_isd_station_metadata
def _load_isd_station_metadata(download_path): """ Collect metadata for US isd stations. """ from shapely.geometry import Point # load ISD history which contains metadata isd_history = pd.read_csv( os.path.join(download_path, "isd-history.csv"), dtype=str, parse_dates=["BEGIN", "END"], ) hasGEO = ( isd_history.LAT.notnull() & isd_history.LON.notnull() & (isd_history.LAT != 0) ) isUS = ( ((isd_history.CTRY == "US") & (isd_history.STATE.notnull())) # AQ = American Samoa, GQ = Guam, RQ = Peurto Rico, VQ = Virgin Islands | (isd_history.CTRY.str[1] == "Q") ) hasUSAF = isd_history.USAF != "999999" metadata = {} for usaf_station, group in isd_history[hasGEO & isUS & hasUSAF].groupby("USAF"): # find most recent recent = group.loc[group.END.idxmax()] wban_stations = list(group.WBAN) metadata[usaf_station] = { "usaf_id": usaf_station, "wban_ids": wban_stations, "recent_wban_id": recent.WBAN, "name": recent["STATION NAME"], "icao_code": recent.ICAO, "latitude": recent.LAT if recent.LAT not in ("+00.000",) else None, "longitude": recent.LON if recent.LON not in ("+000.000",) else None, "point": Point(float(recent.LON), float(recent.LAT)), "elevation": recent["ELEV(M)"] if not str(float(recent["ELEV(M)"])).startswith("-999") else None, "state": recent.STATE, } return metadata
python
def _load_isd_station_metadata(download_path): """ Collect metadata for US isd stations. """ from shapely.geometry import Point # load ISD history which contains metadata isd_history = pd.read_csv( os.path.join(download_path, "isd-history.csv"), dtype=str, parse_dates=["BEGIN", "END"], ) hasGEO = ( isd_history.LAT.notnull() & isd_history.LON.notnull() & (isd_history.LAT != 0) ) isUS = ( ((isd_history.CTRY == "US") & (isd_history.STATE.notnull())) # AQ = American Samoa, GQ = Guam, RQ = Peurto Rico, VQ = Virgin Islands | (isd_history.CTRY.str[1] == "Q") ) hasUSAF = isd_history.USAF != "999999" metadata = {} for usaf_station, group in isd_history[hasGEO & isUS & hasUSAF].groupby("USAF"): # find most recent recent = group.loc[group.END.idxmax()] wban_stations = list(group.WBAN) metadata[usaf_station] = { "usaf_id": usaf_station, "wban_ids": wban_stations, "recent_wban_id": recent.WBAN, "name": recent["STATION NAME"], "icao_code": recent.ICAO, "latitude": recent.LAT if recent.LAT not in ("+00.000",) else None, "longitude": recent.LON if recent.LON not in ("+000.000",) else None, "point": Point(float(recent.LON), float(recent.LAT)), "elevation": recent["ELEV(M)"] if not str(float(recent["ELEV(M)"])).startswith("-999") else None, "state": recent.STATE, } return metadata
[ "def", "_load_isd_station_metadata", "(", "download_path", ")", ":", "from", "shapely", ".", "geometry", "import", "Point", "# load ISD history which contains metadata", "isd_history", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "download_p...
Collect metadata for US isd stations.
[ "Collect", "metadata", "for", "US", "isd", "stations", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/database.py#L160-L202
train
43,164
openeemeter/eeweather
eeweather/database.py
_load_isd_file_metadata
def _load_isd_file_metadata(download_path, isd_station_metadata): """ Collect data counts for isd files. """ isd_inventory = pd.read_csv( os.path.join(download_path, "isd-inventory.csv"), dtype=str ) # filter to stations with metadata station_keep = [usaf in isd_station_metadata for usaf in isd_inventory.USAF] isd_inventory = isd_inventory[station_keep] # filter by year year_keep = isd_inventory.YEAR > "2005" isd_inventory = isd_inventory[year_keep] metadata = {} for (usaf_station, year), group in isd_inventory.groupby(["USAF", "YEAR"]): if usaf_station not in metadata: metadata[usaf_station] = {"usaf_id": usaf_station, "years": {}} metadata[usaf_station]["years"][year] = [ { "wban_id": row.WBAN, "counts": [ row.JAN, row.FEB, row.MAR, row.APR, row.MAY, row.JUN, row.JUL, row.AUG, row.SEP, row.OCT, row.NOV, row.DEC, ], } for i, row in group.iterrows() ] return metadata
python
def _load_isd_file_metadata(download_path, isd_station_metadata): """ Collect data counts for isd files. """ isd_inventory = pd.read_csv( os.path.join(download_path, "isd-inventory.csv"), dtype=str ) # filter to stations with metadata station_keep = [usaf in isd_station_metadata for usaf in isd_inventory.USAF] isd_inventory = isd_inventory[station_keep] # filter by year year_keep = isd_inventory.YEAR > "2005" isd_inventory = isd_inventory[year_keep] metadata = {} for (usaf_station, year), group in isd_inventory.groupby(["USAF", "YEAR"]): if usaf_station not in metadata: metadata[usaf_station] = {"usaf_id": usaf_station, "years": {}} metadata[usaf_station]["years"][year] = [ { "wban_id": row.WBAN, "counts": [ row.JAN, row.FEB, row.MAR, row.APR, row.MAY, row.JUN, row.JUL, row.AUG, row.SEP, row.OCT, row.NOV, row.DEC, ], } for i, row in group.iterrows() ] return metadata
[ "def", "_load_isd_file_metadata", "(", "download_path", ",", "isd_station_metadata", ")", ":", "isd_inventory", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "download_path", ",", "\"isd-inventory.csv\"", ")", ",", "dtype", "=", "str", ...
Collect data counts for isd files.
[ "Collect", "data", "counts", "for", "isd", "files", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/database.py#L205-L244
train
43,165
openeemeter/eeweather
eeweather/database.py
build_metadata_db
def build_metadata_db( zcta_geometry=False, iecc_climate_zone_geometry=True, iecc_moisture_regime_geometry=True, ba_climate_zone_geometry=True, ca_climate_zone_geometry=True, ): """ Build database of metadata from primary sources. Downloads primary sources, clears existing DB, and rebuilds from scratch. Parameters ---------- zcta_geometry : bool, optional Whether or not to include ZCTA geometry in database. iecc_climate_zone_geometry : bool, optional Whether or not to include IECC Climate Zone geometry in database. iecc_moisture_regime_geometry : bool, optional Whether or not to include IECC Moisture Regime geometry in database. ba_climate_zone_geometry : bool, optional Whether or not to include Building America Climate Zone geometry in database. ca_climate_zone_geometry : bool, optional Whether or not to include California Building Climate Zone Area geometry in database. """ try: import shapely except ImportError: raise ImportError("Loading polygons requires shapely.") try: from bs4 import BeautifulSoup except ImportError: raise ImportError("Scraping TMY3 station data requires beautifulsoup4.") try: import pyproj except ImportError: raise ImportError("Computing distances requires pyproj.") try: import simplejson except ImportError: raise ImportError("Writing geojson requires simplejson.") download_path = _download_primary_sources() conn = metadata_db_connection_proxy.reset_database() # Load data into memory print("Loading ZCTAs") zcta_metadata = _load_zcta_metadata(download_path) print("Loading counties") county_metadata = _load_county_metadata(download_path) print("Merging county climate zones") ( iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ) = _create_merged_climate_zones_metadata(county_metadata) print("Loading CA climate zones") ca_climate_zone_metadata = _load_CA_climate_zone_metadata(download_path) print("Loading ISD station metadata") isd_station_metadata = _load_isd_station_metadata(download_path) print("Loading ISD station file metadata") isd_file_metadata = _load_isd_file_metadata(download_path, isd_station_metadata) print("Loading TMY3 station metadata") tmy3_station_metadata = _load_tmy3_station_metadata(download_path) print("Loading CZ2010 station metadata") cz2010_station_metadata = _load_cz2010_station_metadata() # Augment data in memory print("Computing ISD station quality") # add rough station quality to station metadata # (all months in last 5 years have at least 600 points) _compute_isd_station_quality(isd_station_metadata, isd_file_metadata) print("Mapping ZCTAs to climate zones") # add county and ca climate zone mappings _map_zcta_to_climate_zones( zcta_metadata, iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ca_climate_zone_metadata, ) print("Mapping ISD stations to climate zones") # add county and ca climate zone mappings _map_isd_station_to_climate_zones( isd_station_metadata, iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ca_climate_zone_metadata, ) # Write tables print("Creating table structures") _create_table_structures(conn) print("Writing ZCTA data") _write_zcta_metadata_table(conn, zcta_metadata, geometry=zcta_geometry) print("Writing IECC climate zone data") _write_iecc_climate_zone_metadata_table( conn, iecc_climate_zone_metadata, geometry=iecc_climate_zone_geometry ) print("Writing IECC moisture regime data") _write_iecc_moisture_regime_metadata_table( conn, iecc_moisture_regime_metadata, geometry=iecc_moisture_regime_geometry ) print("Writing BA climate zone data") _write_ba_climate_zone_metadata_table( conn, ba_climate_zone_metadata, geometry=ba_climate_zone_geometry ) print("Writing CA climate zone data") _write_ca_climate_zone_metadata_table( conn, ca_climate_zone_metadata, geometry=ca_climate_zone_geometry ) print("Writing ISD station metadata") _write_isd_station_metadata_table(conn, isd_station_metadata) print("Writing ISD file metadata") _write_isd_file_metadata_table(conn, isd_file_metadata) print("Writing TMY3 station metadata") _write_tmy3_station_metadata_table(conn, tmy3_station_metadata) print("Writing CZ2010 station metadata") _write_cz2010_station_metadata_table(conn, cz2010_station_metadata) print("Cleaning up...") shutil.rmtree(download_path) print("\u2728 Completed! \u2728")
python
def build_metadata_db( zcta_geometry=False, iecc_climate_zone_geometry=True, iecc_moisture_regime_geometry=True, ba_climate_zone_geometry=True, ca_climate_zone_geometry=True, ): """ Build database of metadata from primary sources. Downloads primary sources, clears existing DB, and rebuilds from scratch. Parameters ---------- zcta_geometry : bool, optional Whether or not to include ZCTA geometry in database. iecc_climate_zone_geometry : bool, optional Whether or not to include IECC Climate Zone geometry in database. iecc_moisture_regime_geometry : bool, optional Whether or not to include IECC Moisture Regime geometry in database. ba_climate_zone_geometry : bool, optional Whether or not to include Building America Climate Zone geometry in database. ca_climate_zone_geometry : bool, optional Whether or not to include California Building Climate Zone Area geometry in database. """ try: import shapely except ImportError: raise ImportError("Loading polygons requires shapely.") try: from bs4 import BeautifulSoup except ImportError: raise ImportError("Scraping TMY3 station data requires beautifulsoup4.") try: import pyproj except ImportError: raise ImportError("Computing distances requires pyproj.") try: import simplejson except ImportError: raise ImportError("Writing geojson requires simplejson.") download_path = _download_primary_sources() conn = metadata_db_connection_proxy.reset_database() # Load data into memory print("Loading ZCTAs") zcta_metadata = _load_zcta_metadata(download_path) print("Loading counties") county_metadata = _load_county_metadata(download_path) print("Merging county climate zones") ( iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ) = _create_merged_climate_zones_metadata(county_metadata) print("Loading CA climate zones") ca_climate_zone_metadata = _load_CA_climate_zone_metadata(download_path) print("Loading ISD station metadata") isd_station_metadata = _load_isd_station_metadata(download_path) print("Loading ISD station file metadata") isd_file_metadata = _load_isd_file_metadata(download_path, isd_station_metadata) print("Loading TMY3 station metadata") tmy3_station_metadata = _load_tmy3_station_metadata(download_path) print("Loading CZ2010 station metadata") cz2010_station_metadata = _load_cz2010_station_metadata() # Augment data in memory print("Computing ISD station quality") # add rough station quality to station metadata # (all months in last 5 years have at least 600 points) _compute_isd_station_quality(isd_station_metadata, isd_file_metadata) print("Mapping ZCTAs to climate zones") # add county and ca climate zone mappings _map_zcta_to_climate_zones( zcta_metadata, iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ca_climate_zone_metadata, ) print("Mapping ISD stations to climate zones") # add county and ca climate zone mappings _map_isd_station_to_climate_zones( isd_station_metadata, iecc_climate_zone_metadata, iecc_moisture_regime_metadata, ba_climate_zone_metadata, ca_climate_zone_metadata, ) # Write tables print("Creating table structures") _create_table_structures(conn) print("Writing ZCTA data") _write_zcta_metadata_table(conn, zcta_metadata, geometry=zcta_geometry) print("Writing IECC climate zone data") _write_iecc_climate_zone_metadata_table( conn, iecc_climate_zone_metadata, geometry=iecc_climate_zone_geometry ) print("Writing IECC moisture regime data") _write_iecc_moisture_regime_metadata_table( conn, iecc_moisture_regime_metadata, geometry=iecc_moisture_regime_geometry ) print("Writing BA climate zone data") _write_ba_climate_zone_metadata_table( conn, ba_climate_zone_metadata, geometry=ba_climate_zone_geometry ) print("Writing CA climate zone data") _write_ca_climate_zone_metadata_table( conn, ca_climate_zone_metadata, geometry=ca_climate_zone_geometry ) print("Writing ISD station metadata") _write_isd_station_metadata_table(conn, isd_station_metadata) print("Writing ISD file metadata") _write_isd_file_metadata_table(conn, isd_file_metadata) print("Writing TMY3 station metadata") _write_tmy3_station_metadata_table(conn, tmy3_station_metadata) print("Writing CZ2010 station metadata") _write_cz2010_station_metadata_table(conn, cz2010_station_metadata) print("Cleaning up...") shutil.rmtree(download_path) print("\u2728 Completed! \u2728")
[ "def", "build_metadata_db", "(", "zcta_geometry", "=", "False", ",", "iecc_climate_zone_geometry", "=", "True", ",", "iecc_moisture_regime_geometry", "=", "True", ",", "ba_climate_zone_geometry", "=", "True", ",", "ca_climate_zone_geometry", "=", "True", ",", ")", ":"...
Build database of metadata from primary sources. Downloads primary sources, clears existing DB, and rebuilds from scratch. Parameters ---------- zcta_geometry : bool, optional Whether or not to include ZCTA geometry in database. iecc_climate_zone_geometry : bool, optional Whether or not to include IECC Climate Zone geometry in database. iecc_moisture_regime_geometry : bool, optional Whether or not to include IECC Moisture Regime geometry in database. ba_climate_zone_geometry : bool, optional Whether or not to include Building America Climate Zone geometry in database. ca_climate_zone_geometry : bool, optional Whether or not to include California Building Climate Zone Area geometry in database.
[ "Build", "database", "of", "metadata", "from", "primary", "sources", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/database.py#L1130-L1275
train
43,166
openeemeter/eeweather
eeweather/stations.py
ISDStation.json
def json(self): """ Return a JSON-serializeable object containing station metadata.""" return { "elevation": self.elevation, "latitude": self.latitude, "longitude": self.longitude, "icao_code": self.icao_code, "name": self.name, "quality": self.quality, "wban_ids": self.wban_ids, "recent_wban_id": self.recent_wban_id, "climate_zones": { "iecc_climate_zone": self.iecc_climate_zone, "iecc_moisture_regime": self.iecc_moisture_regime, "ba_climate_zone": self.ba_climate_zone, "ca_climate_zone": self.ca_climate_zone, }, }
python
def json(self): """ Return a JSON-serializeable object containing station metadata.""" return { "elevation": self.elevation, "latitude": self.latitude, "longitude": self.longitude, "icao_code": self.icao_code, "name": self.name, "quality": self.quality, "wban_ids": self.wban_ids, "recent_wban_id": self.recent_wban_id, "climate_zones": { "iecc_climate_zone": self.iecc_climate_zone, "iecc_moisture_regime": self.iecc_moisture_regime, "ba_climate_zone": self.ba_climate_zone, "ca_climate_zone": self.ca_climate_zone, }, }
[ "def", "json", "(", "self", ")", ":", "return", "{", "\"elevation\"", ":", "self", ".", "elevation", ",", "\"latitude\"", ":", "self", ".", "latitude", ",", "\"longitude\"", ":", "self", ".", "longitude", ",", "\"icao_code\"", ":", "self", ".", "icao_code"...
Return a JSON-serializeable object containing station metadata.
[ "Return", "a", "JSON", "-", "serializeable", "object", "containing", "station", "metadata", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/stations.py#L1151-L1168
train
43,167
openeemeter/eeweather
eeweather/stations.py
ISDStation.get_isd_filenames
def get_isd_filenames(self, year=None, with_host=False): """ Get filenames of raw ISD station data. """ return get_isd_filenames(self.usaf_id, year, with_host=with_host)
python
def get_isd_filenames(self, year=None, with_host=False): """ Get filenames of raw ISD station data. """ return get_isd_filenames(self.usaf_id, year, with_host=with_host)
[ "def", "get_isd_filenames", "(", "self", ",", "year", "=", "None", ",", "with_host", "=", "False", ")", ":", "return", "get_isd_filenames", "(", "self", ".", "usaf_id", ",", "year", ",", "with_host", "=", "with_host", ")" ]
Get filenames of raw ISD station data.
[ "Get", "filenames", "of", "raw", "ISD", "station", "data", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/stations.py#L1170-L1172
train
43,168
openeemeter/eeweather
eeweather/stations.py
ISDStation.get_gsod_filenames
def get_gsod_filenames(self, year=None, with_host=False): """ Get filenames of raw GSOD station data. """ return get_gsod_filenames(self.usaf_id, year, with_host=with_host)
python
def get_gsod_filenames(self, year=None, with_host=False): """ Get filenames of raw GSOD station data. """ return get_gsod_filenames(self.usaf_id, year, with_host=with_host)
[ "def", "get_gsod_filenames", "(", "self", ",", "year", "=", "None", ",", "with_host", "=", "False", ")", ":", "return", "get_gsod_filenames", "(", "self", ".", "usaf_id", ",", "year", ",", "with_host", "=", "with_host", ")" ]
Get filenames of raw GSOD station data.
[ "Get", "filenames", "of", "raw", "GSOD", "station", "data", "." ]
d32b7369b26edfa3ee431c60457afeb0593123a7
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/stations.py#L1174-L1176
train
43,169
SuperCowPowers/workbench
workbench/workers/view_pdf.py
ViewPDF.execute
def execute(self, input_data): ''' Execute the ViewPDF worker ''' # Just a small check to make sure we haven't been called on the wrong file type if (input_data['meta']['type_tag'] != 'pdf'): return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']} view = {} view['strings'] = input_data['strings']['string_list'][:5] view.update(input_data['meta']) return view
python
def execute(self, input_data): ''' Execute the ViewPDF worker ''' # Just a small check to make sure we haven't been called on the wrong file type if (input_data['meta']['type_tag'] != 'pdf'): return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']} view = {} view['strings'] = input_data['strings']['string_list'][:5] view.update(input_data['meta']) return view
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "# Just a small check to make sure we haven't been called on the wrong file type", "if", "(", "input_data", "[", "'meta'", "]", "[", "'type_tag'", "]", "!=", "'pdf'", ")", ":", "return", "{", "'error'", ":"...
Execute the ViewPDF worker
[ "Execute", "the", "ViewPDF", "worker" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_pdf.py#L9-L19
train
43,170
SuperCowPowers/workbench
workbench/workers/pcap_graph.py
PcapGraph.add_node
def add_node(self, node_id, name, labels): ''' Cache aware add_node ''' if node_id not in self.node_cache: self.workbench.add_node(node_id, name, labels) self.node_cache.add(node_id)
python
def add_node(self, node_id, name, labels): ''' Cache aware add_node ''' if node_id not in self.node_cache: self.workbench.add_node(node_id, name, labels) self.node_cache.add(node_id)
[ "def", "add_node", "(", "self", ",", "node_id", ",", "name", ",", "labels", ")", ":", "if", "node_id", "not", "in", "self", ".", "node_cache", ":", "self", ".", "workbench", ".", "add_node", "(", "node_id", ",", "name", ",", "labels", ")", "self", "....
Cache aware add_node
[ "Cache", "aware", "add_node" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_graph.py#L33-L37
train
43,171
SuperCowPowers/workbench
workbench/workers/pcap_graph.py
PcapGraph.add_rel
def add_rel(self, source_id, target_id, rel): ''' Cache aware add_rel ''' if (source_id, target_id) not in self.rel_cache: self.workbench.add_rel(source_id, target_id, rel) self.rel_cache.add((source_id, target_id))
python
def add_rel(self, source_id, target_id, rel): ''' Cache aware add_rel ''' if (source_id, target_id) not in self.rel_cache: self.workbench.add_rel(source_id, target_id, rel) self.rel_cache.add((source_id, target_id))
[ "def", "add_rel", "(", "self", ",", "source_id", ",", "target_id", ",", "rel", ")", ":", "if", "(", "source_id", ",", "target_id", ")", "not", "in", "self", ".", "rel_cache", ":", "self", ".", "workbench", ".", "add_rel", "(", "source_id", ",", "target...
Cache aware add_rel
[ "Cache", "aware", "add_rel" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_graph.py#L39-L43
train
43,172
SuperCowPowers/workbench
workbench/clients/help_client.py
run
def run(): ''' This client calls a bunch of help commands from workbench ''' # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Call help methods print workbench.help() print workbench.help('basic') print workbench.help('commands') print workbench.help('store_sample') print workbench.help('workers') print workbench.help('meta') # Call a test worker print workbench.test_worker('meta')
python
def run(): ''' This client calls a bunch of help commands from workbench ''' # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Call help methods print workbench.help() print workbench.help('basic') print workbench.help('commands') print workbench.help('store_sample') print workbench.help('workers') print workbench.help('meta') # Call a test worker print workbench.test_worker('meta')
[ "def", "run", "(", ")", ":", "# Grab server args", "args", "=", "client_helper", ".", "grab_server_args", "(", ")", "# Start up workbench connection", "workbench", "=", "zerorpc", ".", "Client", "(", "timeout", "=", "300", ",", "heartbeat", "=", "60", ")", "wo...
This client calls a bunch of help commands from workbench
[ "This", "client", "calls", "a", "bunch", "of", "help", "commands", "from", "workbench" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/help_client.py#L5-L24
train
43,173
SuperCowPowers/workbench
workbench/workers/url.py
URLS.execute
def execute(self, input_data): ''' Execute the URL worker ''' string_output = input_data['strings']['string_list'] flatten = ' '.join(string_output) urls = self.url_match.findall(flatten) return {'url_list': urls}
python
def execute(self, input_data): ''' Execute the URL worker ''' string_output = input_data['strings']['string_list'] flatten = ' '.join(string_output) urls = self.url_match.findall(flatten) return {'url_list': urls}
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "string_output", "=", "input_data", "[", "'strings'", "]", "[", "'string_list'", "]", "flatten", "=", "' '", ".", "join", "(", "string_output", ")", "urls", "=", "self", ".", "url_match", ".", "...
Execute the URL worker
[ "Execute", "the", "URL", "worker" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/url.py#L14-L19
train
43,174
SuperCowPowers/workbench
workbench_apps/workbench_cli/repr_to_str_decorator.py
r_to_s
def r_to_s(func): """Decorator method for Workbench methods returning a str""" @functools.wraps(func) def wrapper(*args, **kwargs): """Decorator method for Workbench methods returning a str""" class ReprToStr(str): """Replaces a class __repr__ with it's string representation""" def __repr__(self): return str(self) return ReprToStr(func(*args, **kwargs)) return wrapper
python
def r_to_s(func): """Decorator method for Workbench methods returning a str""" @functools.wraps(func) def wrapper(*args, **kwargs): """Decorator method for Workbench methods returning a str""" class ReprToStr(str): """Replaces a class __repr__ with it's string representation""" def __repr__(self): return str(self) return ReprToStr(func(*args, **kwargs)) return wrapper
[ "def", "r_to_s", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Decorator method for Workbench methods returning a str\"\"\"", "class", "ReprToStr", "(", "s...
Decorator method for Workbench methods returning a str
[ "Decorator", "method", "for", "Workbench", "methods", "returning", "a", "str" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/repr_to_str_decorator.py#L6-L18
train
43,175
SuperCowPowers/workbench
workbench/clients/upload_dir.py
all_files_in_directory
def all_files_in_directory(path): """ Recursively ist all files under a directory """ file_list = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: file_list.append(os.path.join(dirname, filename)) return file_list
python
def all_files_in_directory(path): """ Recursively ist all files under a directory """ file_list = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: file_list.append(os.path.join(dirname, filename)) return file_list
[ "def", "all_files_in_directory", "(", "path", ")", ":", "file_list", "=", "[", "]", "for", "dirname", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "filename", "in", "filenames", ":", "file_list", ".", "append"...
Recursively ist all files under a directory
[ "Recursively", "ist", "all", "files", "under", "a", "directory" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/upload_dir.py#L9-L15
train
43,176
SuperCowPowers/workbench
workbench/clients/upload_dir.py
run
def run(): """This client pushes a big directory of different files into Workbench.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Grab all the filenames from the data directory data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data') file_list = all_files_in_directory(data_dir) # Upload the files into workbench md5_list = [] for path in file_list: # Skip OS generated files if '.DS_Store' in path: continue with open(path,'rb') as f: filename = os.path.basename(path) # Here we're going to save network traffic by asking # Workbench if it already has this md5 raw_bytes = f.read() md5 = hashlib.md5(raw_bytes).hexdigest() md5_list.append(md5) if workbench.has_sample(md5): print 'Workbench already has this sample %s' % md5 else: # Store the sample into workbench md5 = workbench.store_sample(raw_bytes, filename, 'unknown') print 'Filename %s uploaded: type_tag %s, md5 %s' % (filename, 'unknown', md5) # Okay now explode any container types zip_files = workbench.generate_sample_set('zip') _foo = workbench.set_work_request('unzip', zip_files); list(_foo) # See Issue #306 pcap_files = workbench.generate_sample_set('pcap') _foo = workbench.set_work_request('pcap_bro', pcap_files); list(_foo) # See Issue #306 mem_files = workbench.generate_sample_set('mem') _foo = workbench.set_work_request('mem_procdump', mem_files); list(_foo) # See Issue #306 # Make sure all files are properly identified print 'Info: Ensuring File Identifications...' type_tag_set = set() all_files = workbench.generate_sample_set() meta_all = workbench.set_work_request('meta', all_files) for meta in meta_all: type_tag_set.add(meta['type_tag']) if meta['type_tag'] in ['unknown', 'own']: print meta pprint.pprint(type_tag_set)
python
def run(): """This client pushes a big directory of different files into Workbench.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Grab all the filenames from the data directory data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data') file_list = all_files_in_directory(data_dir) # Upload the files into workbench md5_list = [] for path in file_list: # Skip OS generated files if '.DS_Store' in path: continue with open(path,'rb') as f: filename = os.path.basename(path) # Here we're going to save network traffic by asking # Workbench if it already has this md5 raw_bytes = f.read() md5 = hashlib.md5(raw_bytes).hexdigest() md5_list.append(md5) if workbench.has_sample(md5): print 'Workbench already has this sample %s' % md5 else: # Store the sample into workbench md5 = workbench.store_sample(raw_bytes, filename, 'unknown') print 'Filename %s uploaded: type_tag %s, md5 %s' % (filename, 'unknown', md5) # Okay now explode any container types zip_files = workbench.generate_sample_set('zip') _foo = workbench.set_work_request('unzip', zip_files); list(_foo) # See Issue #306 pcap_files = workbench.generate_sample_set('pcap') _foo = workbench.set_work_request('pcap_bro', pcap_files); list(_foo) # See Issue #306 mem_files = workbench.generate_sample_set('mem') _foo = workbench.set_work_request('mem_procdump', mem_files); list(_foo) # See Issue #306 # Make sure all files are properly identified print 'Info: Ensuring File Identifications...' type_tag_set = set() all_files = workbench.generate_sample_set() meta_all = workbench.set_work_request('meta', all_files) for meta in meta_all: type_tag_set.add(meta['type_tag']) if meta['type_tag'] in ['unknown', 'own']: print meta pprint.pprint(type_tag_set)
[ "def", "run", "(", ")", ":", "# Grab server args", "args", "=", "client_helper", ".", "grab_server_args", "(", ")", "# Start up workbench connection", "workbench", "=", "zerorpc", ".", "Client", "(", "timeout", "=", "300", ",", "heartbeat", "=", "60", ")", "wo...
This client pushes a big directory of different files into Workbench.
[ "This", "client", "pushes", "a", "big", "directory", "of", "different", "files", "into", "Workbench", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/upload_dir.py#L17-L72
train
43,177
SuperCowPowers/workbench
workbench/server/plugin_manager.py
PluginManager.load_all_plugins
def load_all_plugins(self): """Load all the plugins in the plugin directory""" # Go through the existing python files in the plugin directory self.plugin_path = os.path.realpath(self.plugin_dir) sys.path.append(self.plugin_dir) print '<<< Plugin Manager >>>' for f in [os.path.join(self.plugin_dir, child) for child in os.listdir(self.plugin_dir)]: # Skip certain files if '.DS_Store' in f or '__init__.py' in f: continue # Add the plugin self.add_plugin(f)
python
def load_all_plugins(self): """Load all the plugins in the plugin directory""" # Go through the existing python files in the plugin directory self.plugin_path = os.path.realpath(self.plugin_dir) sys.path.append(self.plugin_dir) print '<<< Plugin Manager >>>' for f in [os.path.join(self.plugin_dir, child) for child in os.listdir(self.plugin_dir)]: # Skip certain files if '.DS_Store' in f or '__init__.py' in f: continue # Add the plugin self.add_plugin(f)
[ "def", "load_all_plugins", "(", "self", ")", ":", "# Go through the existing python files in the plugin directory", "self", ".", "plugin_path", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "plugin_dir", ")", "sys", ".", "path", ".", "append", "(", ...
Load all the plugins in the plugin directory
[ "Load", "all", "the", "plugins", "in", "the", "plugin", "directory" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/plugin_manager.py#L35-L49
train
43,178
SuperCowPowers/workbench
workbench/server/plugin_manager.py
PluginManager.remove_plugin
def remove_plugin(self, f): """Remvoing a deleted plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): plugin_name = os.path.splitext(os.path.basename(f))[0] print '- %s %sREMOVED' % (plugin_name, color.Red) print '\t%sNote: still in memory, restart Workbench to remove...%s' % \ (color.Yellow, color.Normal)
python
def remove_plugin(self, f): """Remvoing a deleted plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): plugin_name = os.path.splitext(os.path.basename(f))[0] print '- %s %sREMOVED' % (plugin_name, color.Red) print '\t%sNote: still in memory, restart Workbench to remove...%s' % \ (color.Yellow, color.Normal)
[ "def", "remove_plugin", "(", "self", ",", "f", ")", ":", "if", "f", ".", "endswith", "(", "'.py'", ")", ":", "plugin_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "[", "0", "]", "pr...
Remvoing a deleted plugin. Args: f: the filepath for the plugin.
[ "Remvoing", "a", "deleted", "plugin", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/plugin_manager.py#L78-L88
train
43,179
SuperCowPowers/workbench
workbench/server/plugin_manager.py
PluginManager.add_plugin
def add_plugin(self, f): """Adding and verifying plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): # Just the basename without extension plugin_name = os.path.splitext(os.path.basename(f))[0] # It's possible the plugin has been modified and needs to be reloaded if plugin_name in sys.modules: try: handler = reload(sys.modules[plugin_name]) print'\t- %s %sRELOAD%s' % (plugin_name, color.Yellow, color.Normal) except ImportError, error: print 'Failed to import plugin: %s (%s)' % (plugin_name, error) return else: # Not already loaded so try to import it try: handler = __import__(plugin_name, globals(), locals(), [], -1) except ImportError, error: print 'Failed to import plugin: %s (%s)' % (plugin_name, error) return # Run the handler through plugin validation plugin = self.validate(handler) print '\t- %s %sOK%s' % (plugin_name, color.Green, color.Normal) if plugin: # Okay must be successfully loaded so capture the plugin meta-data, # modification time and register the plugin through the callback plugin['name'] = plugin_name plugin['dependencies'] = plugin['class'].dependencies plugin['docstring'] = plugin['class'].__doc__ plugin['mod_time'] = datetime.utcfromtimestamp(os.path.getmtime(f)) # Plugin may accept sample_sets as input try: plugin['sample_set_input'] = getattr(plugin['class'], 'sample_set_input') except AttributeError: plugin['sample_set_input'] = False # Now pass the plugin back to workbench self.plugin_callback(plugin)
python
def add_plugin(self, f): """Adding and verifying plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): # Just the basename without extension plugin_name = os.path.splitext(os.path.basename(f))[0] # It's possible the plugin has been modified and needs to be reloaded if plugin_name in sys.modules: try: handler = reload(sys.modules[plugin_name]) print'\t- %s %sRELOAD%s' % (plugin_name, color.Yellow, color.Normal) except ImportError, error: print 'Failed to import plugin: %s (%s)' % (plugin_name, error) return else: # Not already loaded so try to import it try: handler = __import__(plugin_name, globals(), locals(), [], -1) except ImportError, error: print 'Failed to import plugin: %s (%s)' % (plugin_name, error) return # Run the handler through plugin validation plugin = self.validate(handler) print '\t- %s %sOK%s' % (plugin_name, color.Green, color.Normal) if plugin: # Okay must be successfully loaded so capture the plugin meta-data, # modification time and register the plugin through the callback plugin['name'] = plugin_name plugin['dependencies'] = plugin['class'].dependencies plugin['docstring'] = plugin['class'].__doc__ plugin['mod_time'] = datetime.utcfromtimestamp(os.path.getmtime(f)) # Plugin may accept sample_sets as input try: plugin['sample_set_input'] = getattr(plugin['class'], 'sample_set_input') except AttributeError: plugin['sample_set_input'] = False # Now pass the plugin back to workbench self.plugin_callback(plugin)
[ "def", "add_plugin", "(", "self", ",", "f", ")", ":", "if", "f", ".", "endswith", "(", "'.py'", ")", ":", "# Just the basename without extension", "plugin_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "f", ...
Adding and verifying plugin. Args: f: the filepath for the plugin.
[ "Adding", "and", "verifying", "plugin", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/plugin_manager.py#L90-L136
train
43,180
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.store_sample
def store_sample(self, sample_bytes, filename, type_tag): """Store a sample into the datastore. Args: filename: Name of the file. sample_bytes: Actual bytes of sample. type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...) Returns: md5 digest of the sample. """ # Temp sanity check for old clients if len(filename) > 1000: print 'switched bytes/filename... %s %s' % (sample_bytes[:100], filename[:100]) exit(1) sample_info = {} # Compute the MD5 hash sample_info['md5'] = hashlib.md5(sample_bytes).hexdigest() # Check if sample already exists if self.has_sample(sample_info['md5']): return sample_info['md5'] # Run the periodic operations self.periodic_ops() # Check if we need to expire anything self.expire_data() # Okay start populating the sample for adding to the data store # Filename, length, import time and type_tag sample_info['filename'] = filename sample_info['length'] = len(sample_bytes) sample_info['import_time'] = datetime.datetime.utcnow() sample_info['type_tag'] = type_tag # Random customer for now import random sample_info['customer'] = random.choice(['Mega Corp', 'Huge Inc', 'BearTron', 'Dorseys Mom']) # Push the file into the MongoDB GridFS sample_info['__grid_fs'] = self.gridfs_handle.put(sample_bytes) self.database[self.sample_collection].insert(sample_info) # Print info print 'Sample Storage: %.2f out of %.2f MB' % (self.sample_storage_size(), self.samples_cap) # Return the sample md5 return sample_info['md5']
python
def store_sample(self, sample_bytes, filename, type_tag): """Store a sample into the datastore. Args: filename: Name of the file. sample_bytes: Actual bytes of sample. type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...) Returns: md5 digest of the sample. """ # Temp sanity check for old clients if len(filename) > 1000: print 'switched bytes/filename... %s %s' % (sample_bytes[:100], filename[:100]) exit(1) sample_info = {} # Compute the MD5 hash sample_info['md5'] = hashlib.md5(sample_bytes).hexdigest() # Check if sample already exists if self.has_sample(sample_info['md5']): return sample_info['md5'] # Run the periodic operations self.periodic_ops() # Check if we need to expire anything self.expire_data() # Okay start populating the sample for adding to the data store # Filename, length, import time and type_tag sample_info['filename'] = filename sample_info['length'] = len(sample_bytes) sample_info['import_time'] = datetime.datetime.utcnow() sample_info['type_tag'] = type_tag # Random customer for now import random sample_info['customer'] = random.choice(['Mega Corp', 'Huge Inc', 'BearTron', 'Dorseys Mom']) # Push the file into the MongoDB GridFS sample_info['__grid_fs'] = self.gridfs_handle.put(sample_bytes) self.database[self.sample_collection].insert(sample_info) # Print info print 'Sample Storage: %.2f out of %.2f MB' % (self.sample_storage_size(), self.samples_cap) # Return the sample md5 return sample_info['md5']
[ "def", "store_sample", "(", "self", ",", "sample_bytes", ",", "filename", ",", "type_tag", ")", ":", "# Temp sanity check for old clients", "if", "len", "(", "filename", ")", ">", "1000", ":", "print", "'switched bytes/filename... %s %s'", "%", "(", "sample_bytes", ...
Store a sample into the datastore. Args: filename: Name of the file. sample_bytes: Actual bytes of sample. type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...) Returns: md5 digest of the sample.
[ "Store", "a", "sample", "into", "the", "datastore", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L51-L102
train
43,181
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.sample_storage_size
def sample_storage_size(self): """Get the storage size of the samples storage collection.""" try: coll_stats = self.database.command('collStats', 'fs.chunks') sample_storage_size = coll_stats['size']/1024.0/1024.0 return sample_storage_size except pymongo.errors.OperationFailure: return 0
python
def sample_storage_size(self): """Get the storage size of the samples storage collection.""" try: coll_stats = self.database.command('collStats', 'fs.chunks') sample_storage_size = coll_stats['size']/1024.0/1024.0 return sample_storage_size except pymongo.errors.OperationFailure: return 0
[ "def", "sample_storage_size", "(", "self", ")", ":", "try", ":", "coll_stats", "=", "self", ".", "database", ".", "command", "(", "'collStats'", ",", "'fs.chunks'", ")", "sample_storage_size", "=", "coll_stats", "[", "'size'", "]", "/", "1024.0", "/", "1024....
Get the storage size of the samples storage collection.
[ "Get", "the", "storage", "size", "of", "the", "samples", "storage", "collection", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L104-L112
train
43,182
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.expire_data
def expire_data(self): """Expire data within the samples collection.""" # Do we need to start deleting stuff? while self.sample_storage_size() > self.samples_cap: # This should return the 'oldest' record in samples record = self.database[self.sample_collection].find().sort('import_time',pymongo.ASCENDING).limit(1)[0] self.remove_sample(record['md5'])
python
def expire_data(self): """Expire data within the samples collection.""" # Do we need to start deleting stuff? while self.sample_storage_size() > self.samples_cap: # This should return the 'oldest' record in samples record = self.database[self.sample_collection].find().sort('import_time',pymongo.ASCENDING).limit(1)[0] self.remove_sample(record['md5'])
[ "def", "expire_data", "(", "self", ")", ":", "# Do we need to start deleting stuff?", "while", "self", ".", "sample_storage_size", "(", ")", ">", "self", ".", "samples_cap", ":", "# This should return the 'oldest' record in samples", "record", "=", "self", ".", "databas...
Expire data within the samples collection.
[ "Expire", "data", "within", "the", "samples", "collection", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L114-L122
train
43,183
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.remove_sample
def remove_sample(self, md5): """Delete a specific sample""" # Grab the sample record = self.database[self.sample_collection].find_one({'md5': md5}) if not record: return # Delete it print 'Deleting sample: %s (%.2f MB)...' % (record['md5'], record['length']/1024.0/1024.0) self.database[self.sample_collection].remove({'md5': record['md5']}) self.gridfs_handle.delete(record['__grid_fs']) # Print info print 'Sample Storage: %.2f out of %.2f MB' % (self.sample_storage_size(), self.samples_cap)
python
def remove_sample(self, md5): """Delete a specific sample""" # Grab the sample record = self.database[self.sample_collection].find_one({'md5': md5}) if not record: return # Delete it print 'Deleting sample: %s (%.2f MB)...' % (record['md5'], record['length']/1024.0/1024.0) self.database[self.sample_collection].remove({'md5': record['md5']}) self.gridfs_handle.delete(record['__grid_fs']) # Print info print 'Sample Storage: %.2f out of %.2f MB' % (self.sample_storage_size(), self.samples_cap)
[ "def", "remove_sample", "(", "self", ",", "md5", ")", ":", "# Grab the sample", "record", "=", "self", ".", "database", "[", "self", ".", "sample_collection", "]", ".", "find_one", "(", "{", "'md5'", ":", "md5", "}", ")", "if", "not", "record", ":", "r...
Delete a specific sample
[ "Delete", "a", "specific", "sample" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L124-L138
train
43,184
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.clean_for_serialization
def clean_for_serialization(self, data): """Clean data in preparation for serialization. Deletes items having key either a BSON, datetime, dict or a list instance, or starting with __. Args: data: Sample data to be serialized. Returns: Cleaned data dictionary. """ if isinstance(data, dict): for k in data.keys(): if (k.startswith('__')): del data[k] elif isinstance(data[k], bson.objectid.ObjectId): del data[k] elif isinstance(data[k], datetime.datetime): data[k] = data[k].isoformat()+'Z' elif isinstance(data[k], dict): data[k] = self.clean_for_serialization(data[k]) elif isinstance(data[k], list): data[k] = [self.clean_for_serialization(item) for item in data[k]] return data
python
def clean_for_serialization(self, data): """Clean data in preparation for serialization. Deletes items having key either a BSON, datetime, dict or a list instance, or starting with __. Args: data: Sample data to be serialized. Returns: Cleaned data dictionary. """ if isinstance(data, dict): for k in data.keys(): if (k.startswith('__')): del data[k] elif isinstance(data[k], bson.objectid.ObjectId): del data[k] elif isinstance(data[k], datetime.datetime): data[k] = data[k].isoformat()+'Z' elif isinstance(data[k], dict): data[k] = self.clean_for_serialization(data[k]) elif isinstance(data[k], list): data[k] = [self.clean_for_serialization(item) for item in data[k]] return data
[ "def", "clean_for_serialization", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "k", "in", "data", ".", "keys", "(", ")", ":", "if", "(", "k", ".", "startswith", "(", "'__'", ")", ")", ":", "de...
Clean data in preparation for serialization. Deletes items having key either a BSON, datetime, dict or a list instance, or starting with __. Args: data: Sample data to be serialized. Returns: Cleaned data dictionary.
[ "Clean", "data", "in", "preparation", "for", "serialization", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L140-L165
train
43,185
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.clean_for_storage
def clean_for_storage(self, data): """Clean data in preparation for storage. Deletes items with key having a '.' or is '_id'. Also deletes those items whose value is a dictionary or a list. Args: data: Sample data dictionary to be cleaned. Returns: Cleaned data dictionary. """ data = self.data_to_unicode(data) if isinstance(data, dict): for k in dict(data).keys(): if k == '_id': del data[k] continue if '.' in k: new_k = k.replace('.', '_') data[new_k] = data[k] del data[k] k = new_k if isinstance(data[k], dict): data[k] = self.clean_for_storage(data[k]) elif isinstance(data[k], list): data[k] = [self.clean_for_storage(item) for item in data[k]] return data
python
def clean_for_storage(self, data): """Clean data in preparation for storage. Deletes items with key having a '.' or is '_id'. Also deletes those items whose value is a dictionary or a list. Args: data: Sample data dictionary to be cleaned. Returns: Cleaned data dictionary. """ data = self.data_to_unicode(data) if isinstance(data, dict): for k in dict(data).keys(): if k == '_id': del data[k] continue if '.' in k: new_k = k.replace('.', '_') data[new_k] = data[k] del data[k] k = new_k if isinstance(data[k], dict): data[k] = self.clean_for_storage(data[k]) elif isinstance(data[k], list): data[k] = [self.clean_for_storage(item) for item in data[k]] return data
[ "def", "clean_for_storage", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "data_to_unicode", "(", "data", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "k", "in", "dict", "(", "data", ")", ".", "keys", "(", ")"...
Clean data in preparation for storage. Deletes items with key having a '.' or is '_id'. Also deletes those items whose value is a dictionary or a list. Args: data: Sample data dictionary to be cleaned. Returns: Cleaned data dictionary.
[ "Clean", "data", "in", "preparation", "for", "storage", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L167-L194
train
43,186
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.get_sample
def get_sample(self, md5): """Get the sample from the data store. This method first fetches the data from datastore, then cleans it for serialization and then updates it with 'raw_bytes' item. Args: md5: The md5 digest of the sample to be fetched from datastore. Returns: The sample dictionary or None """ # Support 'short' md5s but don't waste performance if the full md5 is provided if len(md5) < 32: md5 = self.get_full_md5(md5, self.sample_collection) # Grab the sample sample_info = self.database[self.sample_collection].find_one({'md5': md5}) if not sample_info: return None # Get the raw bytes from GridFS (note: this could fail) try: grid_fs_id = sample_info['__grid_fs'] sample_info = self.clean_for_serialization(sample_info) sample_info.update({'raw_bytes':self.gridfs_handle.get(grid_fs_id).read()}) return sample_info except gridfs.errors.CorruptGridFile: # If we don't have the gridfs files, delete the entry from samples self.database[self.sample_collection].update({'md5': md5}, {'md5': None}) return None
python
def get_sample(self, md5): """Get the sample from the data store. This method first fetches the data from datastore, then cleans it for serialization and then updates it with 'raw_bytes' item. Args: md5: The md5 digest of the sample to be fetched from datastore. Returns: The sample dictionary or None """ # Support 'short' md5s but don't waste performance if the full md5 is provided if len(md5) < 32: md5 = self.get_full_md5(md5, self.sample_collection) # Grab the sample sample_info = self.database[self.sample_collection].find_one({'md5': md5}) if not sample_info: return None # Get the raw bytes from GridFS (note: this could fail) try: grid_fs_id = sample_info['__grid_fs'] sample_info = self.clean_for_serialization(sample_info) sample_info.update({'raw_bytes':self.gridfs_handle.get(grid_fs_id).read()}) return sample_info except gridfs.errors.CorruptGridFile: # If we don't have the gridfs files, delete the entry from samples self.database[self.sample_collection].update({'md5': md5}, {'md5': None}) return None
[ "def", "get_sample", "(", "self", ",", "md5", ")", ":", "# Support 'short' md5s but don't waste performance if the full md5 is provided", "if", "len", "(", "md5", ")", "<", "32", ":", "md5", "=", "self", ".", "get_full_md5", "(", "md5", ",", "self", ".", "sample...
Get the sample from the data store. This method first fetches the data from datastore, then cleans it for serialization and then updates it with 'raw_bytes' item. Args: md5: The md5 digest of the sample to be fetched from datastore. Returns: The sample dictionary or None
[ "Get", "the", "sample", "from", "the", "data", "store", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L203-L234
train
43,187
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.has_sample
def has_sample(self, md5): """Checks if data store has this sample. Args: md5: The md5 digest of the required sample. Returns: True if sample with this md5 is present, else False. """ # The easiest thing is to simply get the sample and if that # succeeds than return True, else return False sample = self.get_sample(md5) return True if sample else False
python
def has_sample(self, md5): """Checks if data store has this sample. Args: md5: The md5 digest of the required sample. Returns: True if sample with this md5 is present, else False. """ # The easiest thing is to simply get the sample and if that # succeeds than return True, else return False sample = self.get_sample(md5) return True if sample else False
[ "def", "has_sample", "(", "self", ",", "md5", ")", ":", "# The easiest thing is to simply get the sample and if that", "# succeeds than return True, else return False", "sample", "=", "self", ".", "get_sample", "(", "md5", ")", "return", "True", "if", "sample", "else", ...
Checks if data store has this sample. Args: md5: The md5 digest of the required sample. Returns: True if sample with this md5 is present, else False.
[ "Checks", "if", "data", "store", "has", "this", "sample", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L265-L278
train
43,188
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore._list_samples
def _list_samples(self, predicate=None): """List all samples that meet the predicate or all if predicate is not specified. Args: predicate: Match samples against this predicate (or all if not specified) Returns: List of the md5s for the matching samples """ cursor = self.database[self.sample_collection].find(predicate, {'_id':0, 'md5':1}) return [item['md5'] for item in cursor]
python
def _list_samples(self, predicate=None): """List all samples that meet the predicate or all if predicate is not specified. Args: predicate: Match samples against this predicate (or all if not specified) Returns: List of the md5s for the matching samples """ cursor = self.database[self.sample_collection].find(predicate, {'_id':0, 'md5':1}) return [item['md5'] for item in cursor]
[ "def", "_list_samples", "(", "self", ",", "predicate", "=", "None", ")", ":", "cursor", "=", "self", ".", "database", "[", "self", ".", "sample_collection", "]", ".", "find", "(", "predicate", ",", "{", "'_id'", ":", "0", ",", "'md5'", ":", "1", "}",...
List all samples that meet the predicate or all if predicate is not specified. Args: predicate: Match samples against this predicate (or all if not specified) Returns: List of the md5s for the matching samples
[ "List", "all", "samples", "that", "meet", "the", "predicate", "or", "all", "if", "predicate", "is", "not", "specified", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L280-L290
train
43,189
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.tag_match
def tag_match(self, tags=None): """List all samples that match the tags or all if tags are not specified. Args: tags: Match samples against these tags (or all if not specified) Returns: List of the md5s for the matching samples """ if 'tags' not in self.database.collection_names(): print 'Warning: Searching on non-existance tags collection' return None if not tags: cursor = self.database['tags'].find({}, {'_id':0, 'md5':1}) else: cursor = self.database['tags'].find({'tags': {'$in': tags}}, {'_id':0, 'md5':1}) # We have the tags, now make sure we only return those md5 which # also exist in the samples collection tag_md5s = set([item['md5'] for item in cursor]) sample_md5s = set(item['md5'] for item in self.database['samples'].find({}, {'_id':0, 'md5':1})) return list(tag_md5s.intersection(sample_md5s))
python
def tag_match(self, tags=None): """List all samples that match the tags or all if tags are not specified. Args: tags: Match samples against these tags (or all if not specified) Returns: List of the md5s for the matching samples """ if 'tags' not in self.database.collection_names(): print 'Warning: Searching on non-existance tags collection' return None if not tags: cursor = self.database['tags'].find({}, {'_id':0, 'md5':1}) else: cursor = self.database['tags'].find({'tags': {'$in': tags}}, {'_id':0, 'md5':1}) # We have the tags, now make sure we only return those md5 which # also exist in the samples collection tag_md5s = set([item['md5'] for item in cursor]) sample_md5s = set(item['md5'] for item in self.database['samples'].find({}, {'_id':0, 'md5':1})) return list(tag_md5s.intersection(sample_md5s))
[ "def", "tag_match", "(", "self", ",", "tags", "=", "None", ")", ":", "if", "'tags'", "not", "in", "self", ".", "database", ".", "collection_names", "(", ")", ":", "print", "'Warning: Searching on non-existance tags collection'", "return", "None", "if", "not", ...
List all samples that match the tags or all if tags are not specified. Args: tags: Match samples against these tags (or all if not specified) Returns: List of the md5s for the matching samples
[ "List", "all", "samples", "that", "match", "the", "tags", "or", "all", "if", "tags", "are", "not", "specified", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L292-L313
train
43,190
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.store_work_results
def store_work_results(self, results, collection, md5): """Store the output results of the worker. Args: results: a dictionary. collection: the database collection to store the results in. md5: the md5 of sample data to be updated. """ # Make sure the md5 and time stamp is on the data before storing results['md5'] = md5 results['__time_stamp'] = datetime.datetime.utcnow() # If the data doesn't have a 'mod_time' field add one now if 'mod_time' not in results: results['mod_time'] = results['__time_stamp'] # Fixme: Occasionally a capped collection will not let you update with a # larger object, if you have MongoDB 2.6 or above this shouldn't # really happen, so for now just kinda punting and giving a message. try: self.database[collection].update({'md5':md5}, self.clean_for_storage(results), True) except pymongo.errors.OperationFailure: #self.database[collection].insert({'md5':md5}, self.clean_for_storage(results), True) print 'Could not update exising object in capped collection, punting...' print 'collection: %s md5:%s' % (collection, md5)
python
def store_work_results(self, results, collection, md5): """Store the output results of the worker. Args: results: a dictionary. collection: the database collection to store the results in. md5: the md5 of sample data to be updated. """ # Make sure the md5 and time stamp is on the data before storing results['md5'] = md5 results['__time_stamp'] = datetime.datetime.utcnow() # If the data doesn't have a 'mod_time' field add one now if 'mod_time' not in results: results['mod_time'] = results['__time_stamp'] # Fixme: Occasionally a capped collection will not let you update with a # larger object, if you have MongoDB 2.6 or above this shouldn't # really happen, so for now just kinda punting and giving a message. try: self.database[collection].update({'md5':md5}, self.clean_for_storage(results), True) except pymongo.errors.OperationFailure: #self.database[collection].insert({'md5':md5}, self.clean_for_storage(results), True) print 'Could not update exising object in capped collection, punting...' print 'collection: %s md5:%s' % (collection, md5)
[ "def", "store_work_results", "(", "self", ",", "results", ",", "collection", ",", "md5", ")", ":", "# Make sure the md5 and time stamp is on the data before storing", "results", "[", "'md5'", "]", "=", "md5", "results", "[", "'__time_stamp'", "]", "=", "datetime", "...
Store the output results of the worker. Args: results: a dictionary. collection: the database collection to store the results in. md5: the md5 of sample data to be updated.
[ "Store", "the", "output", "results", "of", "the", "worker", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L330-L356
train
43,191
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.clear_worker_output
def clear_worker_output(self): """Drops all of the worker output collections""" print 'Dropping all of the worker output collections... Whee!' # Get all the collections in the workbench database all_c = self.database.collection_names() # Remove collections that we don't want to cap try: all_c.remove('system.indexes') all_c.remove('fs.chunks') all_c.remove('fs.files') all_c.remove('sample_set') all_c.remove('tags') all_c.remove(self.sample_collection) except ValueError: print 'Catching a benign exception thats expected...' for collection in all_c: self.database.drop_collection(collection)
python
def clear_worker_output(self): """Drops all of the worker output collections""" print 'Dropping all of the worker output collections... Whee!' # Get all the collections in the workbench database all_c = self.database.collection_names() # Remove collections that we don't want to cap try: all_c.remove('system.indexes') all_c.remove('fs.chunks') all_c.remove('fs.files') all_c.remove('sample_set') all_c.remove('tags') all_c.remove(self.sample_collection) except ValueError: print 'Catching a benign exception thats expected...' for collection in all_c: self.database.drop_collection(collection)
[ "def", "clear_worker_output", "(", "self", ")", ":", "print", "'Dropping all of the worker output collections... Whee!'", "# Get all the collections in the workbench database", "all_c", "=", "self", ".", "database", ".", "collection_names", "(", ")", "# Remove collections that we...
Drops all of the worker output collections
[ "Drops", "all", "of", "the", "worker", "output", "collections" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L386-L405
train
43,192
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.periodic_ops
def periodic_ops(self): """Run periodic operations on the the data store. Operations like making sure collections are capped and indexes are set up. """ # Only run every 30 seconds if (time.time() - self.last_ops_run) < 30: return try: # Reset last ops run self.last_ops_run = time.time() print 'Running Periodic Ops' # Get all the collections in the workbench database all_c = self.database.collection_names() # Remove collections that we don't want to cap try: all_c.remove('system.indexes') all_c.remove('fs.chunks') all_c.remove('fs.files') all_c.remove('info') all_c.remove('tags') all_c.remove(self.sample_collection) except ValueError: print 'Catching a benign exception thats expected...' # Convert collections to capped if desired if self.worker_cap: size = self.worker_cap * pow(1024, 2) # MegaBytes per collection for collection in all_c: self.database.command('convertToCapped', collection, size=size) # Loop through all collections ensuring they have an index on MD5s for collection in all_c: self.database[collection].ensure_index('md5') # Add required indexes for samples collection self.database[self.sample_collection].create_index('import_time') # Create an index on tags self.database['tags'].create_index('tags') # Mongo may throw an autoreconnect exception so catch it and just return # the autoreconnect means that some operations didn't get executed but # because this method gets called every 30 seconds no biggy... except pymongo.errors.AutoReconnect as e: print 'Warning: MongoDB raised an AutoReconnect...' % e return except Exception as e: print 'Critical: MongoDB raised an exception' % e return
python
def periodic_ops(self): """Run periodic operations on the the data store. Operations like making sure collections are capped and indexes are set up. """ # Only run every 30 seconds if (time.time() - self.last_ops_run) < 30: return try: # Reset last ops run self.last_ops_run = time.time() print 'Running Periodic Ops' # Get all the collections in the workbench database all_c = self.database.collection_names() # Remove collections that we don't want to cap try: all_c.remove('system.indexes') all_c.remove('fs.chunks') all_c.remove('fs.files') all_c.remove('info') all_c.remove('tags') all_c.remove(self.sample_collection) except ValueError: print 'Catching a benign exception thats expected...' # Convert collections to capped if desired if self.worker_cap: size = self.worker_cap * pow(1024, 2) # MegaBytes per collection for collection in all_c: self.database.command('convertToCapped', collection, size=size) # Loop through all collections ensuring they have an index on MD5s for collection in all_c: self.database[collection].ensure_index('md5') # Add required indexes for samples collection self.database[self.sample_collection].create_index('import_time') # Create an index on tags self.database['tags'].create_index('tags') # Mongo may throw an autoreconnect exception so catch it and just return # the autoreconnect means that some operations didn't get executed but # because this method gets called every 30 seconds no biggy... except pymongo.errors.AutoReconnect as e: print 'Warning: MongoDB raised an AutoReconnect...' % e return except Exception as e: print 'Critical: MongoDB raised an exception' % e return
[ "def", "periodic_ops", "(", "self", ")", ":", "# Only run every 30 seconds", "if", "(", "time", ".", "time", "(", ")", "-", "self", ".", "last_ops_run", ")", "<", "30", ":", "return", "try", ":", "# Reset last ops run", "self", ".", "last_ops_run", "=", "t...
Run periodic operations on the the data store. Operations like making sure collections are capped and indexes are set up.
[ "Run", "periodic", "operations", "on", "the", "the", "data", "store", ".", "Operations", "like", "making", "sure", "collections", "are", "capped", "and", "indexes", "are", "set", "up", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L413-L468
train
43,193
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.to_unicode
def to_unicode(self, s): """Convert an elementary datatype to unicode. Args: s: the datatype to be unicoded. Returns: Unicoded data. """ # Fixme: This is total horseshit if isinstance(s, unicode): return s if isinstance(s, str): return unicode(s, errors='ignore') # Just return the original object return s
python
def to_unicode(self, s): """Convert an elementary datatype to unicode. Args: s: the datatype to be unicoded. Returns: Unicoded data. """ # Fixme: This is total horseshit if isinstance(s, unicode): return s if isinstance(s, str): return unicode(s, errors='ignore') # Just return the original object return s
[ "def", "to_unicode", "(", "self", ",", "s", ")", ":", "# Fixme: This is total horseshit", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "unicode", "(", "s", ",", "er...
Convert an elementary datatype to unicode. Args: s: the datatype to be unicoded. Returns: Unicoded data.
[ "Convert", "an", "elementary", "datatype", "to", "unicode", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L471-L488
train
43,194
SuperCowPowers/workbench
workbench/server/data_store.py
DataStore.data_to_unicode
def data_to_unicode(self, data): """Recursively convert a list or dictionary to unicode. Args: data: The data to be unicoded. Returns: Unicoded data. """ if isinstance(data, dict): return {self.to_unicode(k): self.to_unicode(v) for k, v in data.iteritems()} if isinstance(data, list): return [self.to_unicode(l) for l in data] else: return self.to_unicode(data)
python
def data_to_unicode(self, data): """Recursively convert a list or dictionary to unicode. Args: data: The data to be unicoded. Returns: Unicoded data. """ if isinstance(data, dict): return {self.to_unicode(k): self.to_unicode(v) for k, v in data.iteritems()} if isinstance(data, list): return [self.to_unicode(l) for l in data] else: return self.to_unicode(data)
[ "def", "data_to_unicode", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "{", "self", ".", "to_unicode", "(", "k", ")", ":", "self", ".", "to_unicode", "(", "v", ")", "for", "k", ",", "v", "i...
Recursively convert a list or dictionary to unicode. Args: data: The data to be unicoded. Returns: Unicoded data.
[ "Recursively", "convert", "a", "list", "or", "dictionary", "to", "unicode", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L490-L504
train
43,195
SuperCowPowers/workbench
workbench/clients/client_helper.py
grab_server_args
def grab_server_args(): """Grab server info from configuration file""" workbench_conf = ConfigParser.ConfigParser() config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') workbench_conf.read(config_path) server = workbench_conf.get('workbench', 'server_uri') port = workbench_conf.get('workbench', 'server_port') # Collect args from the command line parser = argparse.ArgumentParser() parser.add_argument('-s', '--server', type=str, default=server, help='location of workbench server') parser.add_argument('-p', '--port', type=int, default=port, help='port used by workbench server') args, commands = parser.parse_known_args() server = str(args.server) port = str(args.port) return {'server':server, 'port':port, 'commands': commands}
python
def grab_server_args(): """Grab server info from configuration file""" workbench_conf = ConfigParser.ConfigParser() config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') workbench_conf.read(config_path) server = workbench_conf.get('workbench', 'server_uri') port = workbench_conf.get('workbench', 'server_port') # Collect args from the command line parser = argparse.ArgumentParser() parser.add_argument('-s', '--server', type=str, default=server, help='location of workbench server') parser.add_argument('-p', '--port', type=int, default=port, help='port used by workbench server') args, commands = parser.parse_known_args() server = str(args.server) port = str(args.port) return {'server':server, 'port':port, 'commands': commands}
[ "def", "grab_server_args", "(", ")", ":", "workbench_conf", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "_...
Grab server info from configuration file
[ "Grab", "server", "info", "from", "configuration", "file" ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/client_helper.py#L7-L24
train
43,196
kidig/django-mailjet
django_mailjet/backends.py
MailjetBackend._make_attachment
def _make_attachment(self, attachment, str_encoding=None): """Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image """ is_inline_image = False if isinstance(attachment, MIMEBase): name = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype = attachment.get_content_type() if attachment.get_content_maintype() == 'image' and attachment['Content-ID'] is not None: is_inline_image = True name = attachment['Content-ID'] else: (name, content, mimetype) = attachment # Guess missing mimetype from filename, borrowed from # django.core.mail.EmailMessage._create_attachment() if mimetype is None and name is not None: mimetype, _ = mimetypes.guess_type(name) if mimetype is None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE try: # noinspection PyUnresolvedReferences if isinstance(content, unicode): # Python 2.x unicode string content = content.encode(str_encoding) except NameError: # Python 3 doesn't differentiate between strings and unicode # Convert python3 unicode str to bytes attachment: if isinstance(content, str): content = content.encode(str_encoding) content_b64 = b64encode(content) mj_attachment = { 'Content-type': mimetype, 'Filename': name or '', 'content': content_b64.decode('ascii'), } return mj_attachment, is_inline_image
python
def _make_attachment(self, attachment, str_encoding=None): """Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image """ is_inline_image = False if isinstance(attachment, MIMEBase): name = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype = attachment.get_content_type() if attachment.get_content_maintype() == 'image' and attachment['Content-ID'] is not None: is_inline_image = True name = attachment['Content-ID'] else: (name, content, mimetype) = attachment # Guess missing mimetype from filename, borrowed from # django.core.mail.EmailMessage._create_attachment() if mimetype is None and name is not None: mimetype, _ = mimetypes.guess_type(name) if mimetype is None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE try: # noinspection PyUnresolvedReferences if isinstance(content, unicode): # Python 2.x unicode string content = content.encode(str_encoding) except NameError: # Python 3 doesn't differentiate between strings and unicode # Convert python3 unicode str to bytes attachment: if isinstance(content, str): content = content.encode(str_encoding) content_b64 = b64encode(content) mj_attachment = { 'Content-type': mimetype, 'Filename': name or '', 'content': content_b64.decode('ascii'), } return mj_attachment, is_inline_image
[ "def", "_make_attachment", "(", "self", ",", "attachment", ",", "str_encoding", "=", "None", ")", ":", "is_inline_image", "=", "False", "if", "isinstance", "(", "attachment", ",", "MIMEBase", ")", ":", "name", "=", "attachment", ".", "get_filename", "(", ")"...
Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image
[ "Returns", "EmailMessage", ".", "attachments", "item", "formatted", "for", "sending", "with", "Mailjet" ]
103dd96383eab6251ae3783d5673050dc90f5a17
https://github.com/kidig/django-mailjet/blob/103dd96383eab6251ae3783d5673050dc90f5a17/django_mailjet/backends.py#L196-L238
train
43,197
SuperCowPowers/workbench
workbench/server/els_indexer.py
ELSIndexer.index_data
def index_data(self, data, index_name, doc_type): """Take an arbitrary dictionary of data and index it with ELS. Args: data: data to be Indexed. Should be a dictionary. index_name: Name of the index. doc_type: The type of the document. Raises: RuntimeError: When the Indexing fails. """ # Index the data (which needs to be a dict/object) if it's not # we're going to toss an exception if not isinstance(data, dict): raise RuntimeError('Index failed, data needs to be a dict!') try: self.els_search.index(index=index_name, doc_type=doc_type, body=data) except Exception, error: print 'Index failed: %s' % str(error) raise RuntimeError('Index failed: %s' % str(error))
python
def index_data(self, data, index_name, doc_type): """Take an arbitrary dictionary of data and index it with ELS. Args: data: data to be Indexed. Should be a dictionary. index_name: Name of the index. doc_type: The type of the document. Raises: RuntimeError: When the Indexing fails. """ # Index the data (which needs to be a dict/object) if it's not # we're going to toss an exception if not isinstance(data, dict): raise RuntimeError('Index failed, data needs to be a dict!') try: self.els_search.index(index=index_name, doc_type=doc_type, body=data) except Exception, error: print 'Index failed: %s' % str(error) raise RuntimeError('Index failed: %s' % str(error))
[ "def", "index_data", "(", "self", ",", "data", ",", "index_name", ",", "doc_type", ")", ":", "# Index the data (which needs to be a dict/object) if it's not", "# we're going to toss an exception", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", ...
Take an arbitrary dictionary of data and index it with ELS. Args: data: data to be Indexed. Should be a dictionary. index_name: Name of the index. doc_type: The type of the document. Raises: RuntimeError: When the Indexing fails.
[ "Take", "an", "arbitrary", "dictionary", "of", "data", "and", "index", "it", "with", "ELS", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/els_indexer.py#L29-L50
train
43,198
SuperCowPowers/workbench
workbench/server/els_indexer.py
ELSIndexer.search
def search(self, index_name, query): """Search the given index_name with the given ELS query. Args: index_name: Name of the Index query: The string to be searched. Returns: List of results. Raises: RuntimeError: When the search query fails. """ try: results = self.els_search.search(index=index_name, body=query) return results except Exception, error: error_str = 'Query failed: %s\n' % str(error) error_str += '\nIs there a dynamic script in the query?, see www.elasticsearch.org' print error_str raise RuntimeError(error_str)
python
def search(self, index_name, query): """Search the given index_name with the given ELS query. Args: index_name: Name of the Index query: The string to be searched. Returns: List of results. Raises: RuntimeError: When the search query fails. """ try: results = self.els_search.search(index=index_name, body=query) return results except Exception, error: error_str = 'Query failed: %s\n' % str(error) error_str += '\nIs there a dynamic script in the query?, see www.elasticsearch.org' print error_str raise RuntimeError(error_str)
[ "def", "search", "(", "self", ",", "index_name", ",", "query", ")", ":", "try", ":", "results", "=", "self", ".", "els_search", ".", "search", "(", "index", "=", "index_name", ",", "body", "=", "query", ")", "return", "results", "except", "Exception", ...
Search the given index_name with the given ELS query. Args: index_name: Name of the Index query: The string to be searched. Returns: List of results. Raises: RuntimeError: When the search query fails.
[ "Search", "the", "given", "index_name", "with", "the", "given", "ELS", "query", "." ]
710232756dd717f734253315e3d0b33c9628dafb
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/els_indexer.py#L52-L73
train
43,199