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
sequencelengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
sequencelengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
account_groups_and_extra_data
def account_groups_and_extra_data(account, resource, refresh_timedelta=None): """Fetch account groups and extra data from resource if necessary.""" updated = datetime.utcnow() modified_since = updated if refresh_timedelta is not None: modified_since += refresh_timedelta modified_since = modified_since.isoformat() last_update = account.extra_data.get('updated', modified_since) if last_update > modified_since: return account.extra_data.get('groups', []) groups = fetch_groups(resource['Group']) extra_data = current_app.config.get( 'OAUTHCLIENT_CERN_EXTRA_DATA_SERIALIZER', fetch_extra_data )(resource) account.extra_data.update( groups=groups, updated=updated.isoformat(), **extra_data ) return groups
python
def account_groups_and_extra_data(account, resource, refresh_timedelta=None): """Fetch account groups and extra data from resource if necessary.""" updated = datetime.utcnow() modified_since = updated if refresh_timedelta is not None: modified_since += refresh_timedelta modified_since = modified_since.isoformat() last_update = account.extra_data.get('updated', modified_since) if last_update > modified_since: return account.extra_data.get('groups', []) groups = fetch_groups(resource['Group']) extra_data = current_app.config.get( 'OAUTHCLIENT_CERN_EXTRA_DATA_SERIALIZER', fetch_extra_data )(resource) account.extra_data.update( groups=groups, updated=updated.isoformat(), **extra_data ) return groups
[ "def", "account_groups_and_extra_data", "(", "account", ",", "resource", ",", "refresh_timedelta", "=", "None", ")", ":", "updated", "=", "datetime", ".", "utcnow", "(", ")", "modified_since", "=", "updated", "if", "refresh_timedelta", "is", "not", "None", ":", "modified_since", "+=", "refresh_timedelta", "modified_since", "=", "modified_since", ".", "isoformat", "(", ")", "last_update", "=", "account", ".", "extra_data", ".", "get", "(", "'updated'", ",", "modified_since", ")", "if", "last_update", ">", "modified_since", ":", "return", "account", ".", "extra_data", ".", "get", "(", "'groups'", ",", "[", "]", ")", "groups", "=", "fetch_groups", "(", "resource", "[", "'Group'", "]", ")", "extra_data", "=", "current_app", ".", "config", ".", "get", "(", "'OAUTHCLIENT_CERN_EXTRA_DATA_SERIALIZER'", ",", "fetch_extra_data", ")", "(", "resource", ")", "account", ".", "extra_data", ".", "update", "(", "groups", "=", "groups", ",", "updated", "=", "updated", ".", "isoformat", "(", ")", ",", "*", "*", "extra_data", ")", "return", "groups" ]
Fetch account groups and extra data from resource if necessary.
[ "Fetch", "account", "groups", "and", "extra", "data", "from", "resource", "if", "necessary", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L232-L256
train
1,100
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
extend_identity
def extend_identity(identity, groups): """Extend identity with roles based on CERN groups.""" provides = set([UserNeed(current_user.email)] + [ RoleNeed('{0}@cern.ch'.format(name)) for name in groups ]) identity.provides |= provides session[OAUTHCLIENT_CERN_SESSION_KEY] = provides
python
def extend_identity(identity, groups): """Extend identity with roles based on CERN groups.""" provides = set([UserNeed(current_user.email)] + [ RoleNeed('{0}@cern.ch'.format(name)) for name in groups ]) identity.provides |= provides session[OAUTHCLIENT_CERN_SESSION_KEY] = provides
[ "def", "extend_identity", "(", "identity", ",", "groups", ")", ":", "provides", "=", "set", "(", "[", "UserNeed", "(", "current_user", ".", "email", ")", "]", "+", "[", "RoleNeed", "(", "'{0}@cern.ch'", ".", "format", "(", "name", ")", ")", "for", "name", "in", "groups", "]", ")", "identity", ".", "provides", "|=", "provides", "session", "[", "OAUTHCLIENT_CERN_SESSION_KEY", "]", "=", "provides" ]
Extend identity with roles based on CERN groups.
[ "Extend", "identity", "with", "roles", "based", "on", "CERN", "groups", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L259-L265
train
1,101
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
get_dict_from_response
def get_dict_from_response(response): """Prepare new mapping with 'Value's groupped by 'Type'.""" result = {} if getattr(response, '_resp') and response._resp.code > 400: return result for i in response.data: # strip the schema from the key k = i['Type'].replace(REMOTE_APP_RESOURCE_SCHEMA, '') result.setdefault(k, list()) result[k].append(i['Value']) return result
python
def get_dict_from_response(response): """Prepare new mapping with 'Value's groupped by 'Type'.""" result = {} if getattr(response, '_resp') and response._resp.code > 400: return result for i in response.data: # strip the schema from the key k = i['Type'].replace(REMOTE_APP_RESOURCE_SCHEMA, '') result.setdefault(k, list()) result[k].append(i['Value']) return result
[ "def", "get_dict_from_response", "(", "response", ")", ":", "result", "=", "{", "}", "if", "getattr", "(", "response", ",", "'_resp'", ")", "and", "response", ".", "_resp", ".", "code", ">", "400", ":", "return", "result", "for", "i", "in", "response", ".", "data", ":", "# strip the schema from the key", "k", "=", "i", "[", "'Type'", "]", ".", "replace", "(", "REMOTE_APP_RESOURCE_SCHEMA", ",", "''", ")", "result", ".", "setdefault", "(", "k", ",", "list", "(", ")", ")", "result", "[", "k", "]", ".", "append", "(", "i", "[", "'Value'", "]", ")", "return", "result" ]
Prepare new mapping with 'Value's groupped by 'Type'.
[ "Prepare", "new", "mapping", "with", "Value", "s", "groupped", "by", "Type", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L274-L285
train
1,102
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
get_resource
def get_resource(remote): """Query CERN Resources to get user info and groups.""" cached_resource = session.pop('cern_resource', None) if cached_resource: return cached_resource response = remote.get(REMOTE_APP_RESOURCE_API_URL) dict_response = get_dict_from_response(response) session['cern_resource'] = dict_response return dict_response
python
def get_resource(remote): """Query CERN Resources to get user info and groups.""" cached_resource = session.pop('cern_resource', None) if cached_resource: return cached_resource response = remote.get(REMOTE_APP_RESOURCE_API_URL) dict_response = get_dict_from_response(response) session['cern_resource'] = dict_response return dict_response
[ "def", "get_resource", "(", "remote", ")", ":", "cached_resource", "=", "session", ".", "pop", "(", "'cern_resource'", ",", "None", ")", "if", "cached_resource", ":", "return", "cached_resource", "response", "=", "remote", ".", "get", "(", "REMOTE_APP_RESOURCE_API_URL", ")", "dict_response", "=", "get_dict_from_response", "(", "response", ")", "session", "[", "'cern_resource'", "]", "=", "dict_response", "return", "dict_response" ]
Query CERN Resources to get user info and groups.
[ "Query", "CERN", "Resources", "to", "get", "user", "info", "and", "groups", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L288-L297
train
1,103
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
on_identity_changed
def on_identity_changed(sender, identity): """Store groups in session whenever identity changes. :param identity: The user identity where information are stored. """ if isinstance(identity, AnonymousIdentity): return client_id = current_app.config['CERN_APP_CREDENTIALS']['consumer_key'] account = RemoteAccount.get( user_id=current_user.get_id(), client_id=client_id, ) groups = [] if account: remote = find_remote_by_client_id(client_id) resource = get_resource(remote) refresh = current_app.config.get( 'OAUTHCLIENT_CERN_REFRESH_TIMEDELTA', OAUTHCLIENT_CERN_REFRESH_TIMEDELTA ) groups.extend( account_groups_and_extra_data(account, resource, refresh_timedelta=refresh) ) extend_identity(identity, groups)
python
def on_identity_changed(sender, identity): """Store groups in session whenever identity changes. :param identity: The user identity where information are stored. """ if isinstance(identity, AnonymousIdentity): return client_id = current_app.config['CERN_APP_CREDENTIALS']['consumer_key'] account = RemoteAccount.get( user_id=current_user.get_id(), client_id=client_id, ) groups = [] if account: remote = find_remote_by_client_id(client_id) resource = get_resource(remote) refresh = current_app.config.get( 'OAUTHCLIENT_CERN_REFRESH_TIMEDELTA', OAUTHCLIENT_CERN_REFRESH_TIMEDELTA ) groups.extend( account_groups_and_extra_data(account, resource, refresh_timedelta=refresh) ) extend_identity(identity, groups)
[ "def", "on_identity_changed", "(", "sender", ",", "identity", ")", ":", "if", "isinstance", "(", "identity", ",", "AnonymousIdentity", ")", ":", "return", "client_id", "=", "current_app", ".", "config", "[", "'CERN_APP_CREDENTIALS'", "]", "[", "'consumer_key'", "]", "account", "=", "RemoteAccount", ".", "get", "(", "user_id", "=", "current_user", ".", "get_id", "(", ")", ",", "client_id", "=", "client_id", ",", ")", "groups", "=", "[", "]", "if", "account", ":", "remote", "=", "find_remote_by_client_id", "(", "client_id", ")", "resource", "=", "get_resource", "(", "remote", ")", "refresh", "=", "current_app", ".", "config", ".", "get", "(", "'OAUTHCLIENT_CERN_REFRESH_TIMEDELTA'", ",", "OAUTHCLIENT_CERN_REFRESH_TIMEDELTA", ")", "groups", ".", "extend", "(", "account_groups_and_extra_data", "(", "account", ",", "resource", ",", "refresh_timedelta", "=", "refresh", ")", ")", "extend_identity", "(", "identity", ",", "groups", ")" ]
Store groups in session whenever identity changes. :param identity: The user identity where information are stored.
[ "Store", "groups", "in", "session", "whenever", "identity", "changes", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L373-L400
train
1,104
inveniosoftware/invenio-oauthclient
invenio_oauthclient/models.py
RemoteAccount.get
def get(cls, user_id, client_id): """Get RemoteAccount object for user. :param user_id: User id :param client_id: Client id. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. """ return cls.query.filter_by( user_id=user_id, client_id=client_id, ).first()
python
def get(cls, user_id, client_id): """Get RemoteAccount object for user. :param user_id: User id :param client_id: Client id. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. """ return cls.query.filter_by( user_id=user_id, client_id=client_id, ).first()
[ "def", "get", "(", "cls", ",", "user_id", ",", "client_id", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "user_id", "=", "user_id", ",", "client_id", "=", "client_id", ",", ")", ".", "first", "(", ")" ]
Get RemoteAccount object for user. :param user_id: User id :param client_id: Client id. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
[ "Get", "RemoteAccount", "object", "for", "user", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/models.py#L63-L73
train
1,105
inveniosoftware/invenio-oauthclient
invenio_oauthclient/models.py
RemoteAccount.create
def create(cls, user_id, client_id, extra_data): """Create new remote account for user. :param user_id: User id. :param client_id: Client id. :param extra_data: JSON-serializable dictionary of any extra data that needs to be save together with this link. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. """ with db.session.begin_nested(): account = cls( user_id=user_id, client_id=client_id, extra_data=extra_data or dict() ) db.session.add(account) return account
python
def create(cls, user_id, client_id, extra_data): """Create new remote account for user. :param user_id: User id. :param client_id: Client id. :param extra_data: JSON-serializable dictionary of any extra data that needs to be save together with this link. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. """ with db.session.begin_nested(): account = cls( user_id=user_id, client_id=client_id, extra_data=extra_data or dict() ) db.session.add(account) return account
[ "def", "create", "(", "cls", ",", "user_id", ",", "client_id", ",", "extra_data", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "account", "=", "cls", "(", "user_id", "=", "user_id", ",", "client_id", "=", "client_id", ",", "extra_data", "=", "extra_data", "or", "dict", "(", ")", ")", "db", ".", "session", ".", "add", "(", "account", ")", "return", "account" ]
Create new remote account for user. :param user_id: User id. :param client_id: Client id. :param extra_data: JSON-serializable dictionary of any extra data that needs to be save together with this link. :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
[ "Create", "new", "remote", "account", "for", "user", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/models.py#L76-L92
train
1,106
inveniosoftware/invenio-oauthclient
invenio_oauthclient/models.py
RemoteToken.update_token
def update_token(self, token, secret): """Update token with new values. :param token: The token value. :param secret: The secret key. """ if self.access_token != token or self.secret != secret: with db.session.begin_nested(): self.access_token = token self.secret = secret db.session.add(self)
python
def update_token(self, token, secret): """Update token with new values. :param token: The token value. :param secret: The secret key. """ if self.access_token != token or self.secret != secret: with db.session.begin_nested(): self.access_token = token self.secret = secret db.session.add(self)
[ "def", "update_token", "(", "self", ",", "token", ",", "secret", ")", ":", "if", "self", ".", "access_token", "!=", "token", "or", "self", ".", "secret", "!=", "secret", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "self", ".", "access_token", "=", "token", "self", ".", "secret", "=", "secret", "db", ".", "session", ".", "add", "(", "self", ")" ]
Update token with new values. :param token: The token value. :param secret: The secret key.
[ "Update", "token", "with", "new", "values", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/models.py#L153-L163
train
1,107
inveniosoftware/invenio-oauthclient
invenio_oauthclient/models.py
RemoteToken.get
def get(cls, user_id, client_id, token_type='', access_token=None): """Get RemoteToken for user. :param user_id: The user id. :param client_id: The client id. :param token_type: The token type. (Default: ``''``) :param access_token: If set, will filter also by access token. (Default: ``None``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. """ args = [ RemoteAccount.id == RemoteToken.id_remote_account, RemoteAccount.user_id == user_id, RemoteAccount.client_id == client_id, RemoteToken.token_type == token_type, ] if access_token: args.append(RemoteToken.access_token == access_token) return cls.query.options( db.joinedload('remote_account') ).filter(*args).first()
python
def get(cls, user_id, client_id, token_type='', access_token=None): """Get RemoteToken for user. :param user_id: The user id. :param client_id: The client id. :param token_type: The token type. (Default: ``''``) :param access_token: If set, will filter also by access token. (Default: ``None``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. """ args = [ RemoteAccount.id == RemoteToken.id_remote_account, RemoteAccount.user_id == user_id, RemoteAccount.client_id == client_id, RemoteToken.token_type == token_type, ] if access_token: args.append(RemoteToken.access_token == access_token) return cls.query.options( db.joinedload('remote_account') ).filter(*args).first()
[ "def", "get", "(", "cls", ",", "user_id", ",", "client_id", ",", "token_type", "=", "''", ",", "access_token", "=", "None", ")", ":", "args", "=", "[", "RemoteAccount", ".", "id", "==", "RemoteToken", ".", "id_remote_account", ",", "RemoteAccount", ".", "user_id", "==", "user_id", ",", "RemoteAccount", ".", "client_id", "==", "client_id", ",", "RemoteToken", ".", "token_type", "==", "token_type", ",", "]", "if", "access_token", ":", "args", ".", "append", "(", "RemoteToken", ".", "access_token", "==", "access_token", ")", "return", "cls", ".", "query", ".", "options", "(", "db", ".", "joinedload", "(", "'remote_account'", ")", ")", ".", "filter", "(", "*", "args", ")", ".", "first", "(", ")" ]
Get RemoteToken for user. :param user_id: The user id. :param client_id: The client id. :param token_type: The token type. (Default: ``''``) :param access_token: If set, will filter also by access token. (Default: ``None``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance.
[ "Get", "RemoteToken", "for", "user", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/models.py#L166-L188
train
1,108
inveniosoftware/invenio-oauthclient
invenio_oauthclient/models.py
RemoteToken.get_by_token
def get_by_token(cls, client_id, access_token, token_type=''): """Get RemoteAccount object for token. :param client_id: The client id. :param access_token: The access token. :param token_type: The token type. (Default: ``''``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. """ return cls.query.options(db.joinedload('remote_account')).filter( RemoteAccount.id == RemoteToken.id_remote_account, RemoteAccount.client_id == client_id, RemoteToken.token_type == token_type, RemoteToken.access_token == access_token, ).first()
python
def get_by_token(cls, client_id, access_token, token_type=''): """Get RemoteAccount object for token. :param client_id: The client id. :param access_token: The access token. :param token_type: The token type. (Default: ``''``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. """ return cls.query.options(db.joinedload('remote_account')).filter( RemoteAccount.id == RemoteToken.id_remote_account, RemoteAccount.client_id == client_id, RemoteToken.token_type == token_type, RemoteToken.access_token == access_token, ).first()
[ "def", "get_by_token", "(", "cls", ",", "client_id", ",", "access_token", ",", "token_type", "=", "''", ")", ":", "return", "cls", ".", "query", ".", "options", "(", "db", ".", "joinedload", "(", "'remote_account'", ")", ")", ".", "filter", "(", "RemoteAccount", ".", "id", "==", "RemoteToken", ".", "id_remote_account", ",", "RemoteAccount", ".", "client_id", "==", "client_id", ",", "RemoteToken", ".", "token_type", "==", "token_type", ",", "RemoteToken", ".", "access_token", "==", "access_token", ",", ")", ".", "first", "(", ")" ]
Get RemoteAccount object for token. :param client_id: The client id. :param access_token: The access token. :param token_type: The token type. (Default: ``''``) :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance.
[ "Get", "RemoteAccount", "object", "for", "token", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/models.py#L191-L204
train
1,109
qacafe/cdrouter.py
cdrouter/exports.py
ExportsService.bulk_export
def bulk_export(self, config_ids=None, device_ids=None, package_ids=None, result_ids=None, exclude_captures=False): """Bulk export a set of configs, devices, packages and results. :param config_ids: (optional) Int list of config IDs. :param device_ids: (optional) Int list of device IDs. :param package_ids: (optional) Int list of package IDs. :param result_ids: (optional) Int list of result IDs. :param exclude_captures: (optional) Exclude capture files if bool `True`. :rtype: tuple `(io.BytesIO, 'filename')` """ if config_ids is None: config_ids = [] if device_ids is None: device_ids = [] if package_ids is None: package_ids = [] if result_ids is None: result_ids = [] json = { 'configs': map(int, config_ids), 'devices': map(int, device_ids), 'packages': map(int, package_ids), 'results': map(int, result_ids), 'options': {'exclude_captures': exclude_captures} } resp = self.service.post(self.base, json=json, stream=True) b = io.BytesIO() stream.stream_response_to_file(resp, path=b) resp.close() b.seek(0) return (b, self.service.filename(resp))
python
def bulk_export(self, config_ids=None, device_ids=None, package_ids=None, result_ids=None, exclude_captures=False): """Bulk export a set of configs, devices, packages and results. :param config_ids: (optional) Int list of config IDs. :param device_ids: (optional) Int list of device IDs. :param package_ids: (optional) Int list of package IDs. :param result_ids: (optional) Int list of result IDs. :param exclude_captures: (optional) Exclude capture files if bool `True`. :rtype: tuple `(io.BytesIO, 'filename')` """ if config_ids is None: config_ids = [] if device_ids is None: device_ids = [] if package_ids is None: package_ids = [] if result_ids is None: result_ids = [] json = { 'configs': map(int, config_ids), 'devices': map(int, device_ids), 'packages': map(int, package_ids), 'results': map(int, result_ids), 'options': {'exclude_captures': exclude_captures} } resp = self.service.post(self.base, json=json, stream=True) b = io.BytesIO() stream.stream_response_to_file(resp, path=b) resp.close() b.seek(0) return (b, self.service.filename(resp))
[ "def", "bulk_export", "(", "self", ",", "config_ids", "=", "None", ",", "device_ids", "=", "None", ",", "package_ids", "=", "None", ",", "result_ids", "=", "None", ",", "exclude_captures", "=", "False", ")", ":", "if", "config_ids", "is", "None", ":", "config_ids", "=", "[", "]", "if", "device_ids", "is", "None", ":", "device_ids", "=", "[", "]", "if", "package_ids", "is", "None", ":", "package_ids", "=", "[", "]", "if", "result_ids", "is", "None", ":", "result_ids", "=", "[", "]", "json", "=", "{", "'configs'", ":", "map", "(", "int", ",", "config_ids", ")", ",", "'devices'", ":", "map", "(", "int", ",", "device_ids", ")", ",", "'packages'", ":", "map", "(", "int", ",", "package_ids", ")", ",", "'results'", ":", "map", "(", "int", ",", "result_ids", ")", ",", "'options'", ":", "{", "'exclude_captures'", ":", "exclude_captures", "}", "}", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", ",", "json", "=", "json", ",", "stream", "=", "True", ")", "b", "=", "io", ".", "BytesIO", "(", ")", "stream", ".", "stream_response_to_file", "(", "resp", ",", "path", "=", "b", ")", "resp", ".", "close", "(", ")", "b", ".", "seek", "(", "0", ")", "return", "(", "b", ",", "self", ".", "service", ".", "filename", "(", "resp", ")", ")" ]
Bulk export a set of configs, devices, packages and results. :param config_ids: (optional) Int list of config IDs. :param device_ids: (optional) Int list of device IDs. :param package_ids: (optional) Int list of package IDs. :param result_ids: (optional) Int list of result IDs. :param exclude_captures: (optional) Exclude capture files if bool `True`. :rtype: tuple `(io.BytesIO, 'filename')`
[ "Bulk", "export", "a", "set", "of", "configs", "devices", "packages", "and", "results", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/exports.py#L22-L52
train
1,110
cokelaer/reports
reports/report.py
Report._init_report
def _init_report(self): """create the report directory and return the directory name""" self.sections = [] self.section_names = [] # if the directory already exists, print a warning try: if os.path.isdir(self.directory) is False: if self.verbose: print("Created directory {}".format(self.directory)) os.mkdir(self.directory) # list of directories created in the constructor for this in self._to_create: try: os.mkdir(self.directory + os.sep + this) except: pass # already created ? except Exception: pass finally: # Once the main directory is created, copy files required temp_path = easydev.get_package_location("reports") temp_path += os.sep + "reports" + os.sep + "resources" # Copy the CSS from reports/resources/css filenames = glob.glob(os.sep.join([temp_path, "css", "*.css"])) # If there are CSS in the directory with JINJA templates, use them # as well filenames += glob.glob(os.sep.join([self.searchpath, '*.css'])) # In addition, the user may also provide his own CSS as a list filenames += self.extra_css_list for filename in filenames: target = os.sep.join([self.directory, 'css' ]) if os.path.isfile(target) is False: shutil.copy(filename, target) # We copy all javascript from reports resources for filename in ['sorttable.js', 'highlight.pack.js', "jquery-1.12.3.min.js"]: target = os.sep.join([self.directory, 'js', filename ]) if os.path.isfile(target) is False: filename = os.sep.join([temp_path, "javascript", filename]) shutil.copy(filename, target) for filename in self.extra_js_list: basename = os.path.basename(filename) target = os.sep.join([self.directory, 'js', basename ]) if os.path.isfile(target) is False: shutil.copy(filename, target)
python
def _init_report(self): """create the report directory and return the directory name""" self.sections = [] self.section_names = [] # if the directory already exists, print a warning try: if os.path.isdir(self.directory) is False: if self.verbose: print("Created directory {}".format(self.directory)) os.mkdir(self.directory) # list of directories created in the constructor for this in self._to_create: try: os.mkdir(self.directory + os.sep + this) except: pass # already created ? except Exception: pass finally: # Once the main directory is created, copy files required temp_path = easydev.get_package_location("reports") temp_path += os.sep + "reports" + os.sep + "resources" # Copy the CSS from reports/resources/css filenames = glob.glob(os.sep.join([temp_path, "css", "*.css"])) # If there are CSS in the directory with JINJA templates, use them # as well filenames += glob.glob(os.sep.join([self.searchpath, '*.css'])) # In addition, the user may also provide his own CSS as a list filenames += self.extra_css_list for filename in filenames: target = os.sep.join([self.directory, 'css' ]) if os.path.isfile(target) is False: shutil.copy(filename, target) # We copy all javascript from reports resources for filename in ['sorttable.js', 'highlight.pack.js', "jquery-1.12.3.min.js"]: target = os.sep.join([self.directory, 'js', filename ]) if os.path.isfile(target) is False: filename = os.sep.join([temp_path, "javascript", filename]) shutil.copy(filename, target) for filename in self.extra_js_list: basename = os.path.basename(filename) target = os.sep.join([self.directory, 'js', basename ]) if os.path.isfile(target) is False: shutil.copy(filename, target)
[ "def", "_init_report", "(", "self", ")", ":", "self", ".", "sections", "=", "[", "]", "self", ".", "section_names", "=", "[", "]", "# if the directory already exists, print a warning", "try", ":", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "directory", ")", "is", "False", ":", "if", "self", ".", "verbose", ":", "print", "(", "\"Created directory {}\"", ".", "format", "(", "self", ".", "directory", ")", ")", "os", ".", "mkdir", "(", "self", ".", "directory", ")", "# list of directories created in the constructor", "for", "this", "in", "self", ".", "_to_create", ":", "try", ":", "os", ".", "mkdir", "(", "self", ".", "directory", "+", "os", ".", "sep", "+", "this", ")", "except", ":", "pass", "# already created ?", "except", "Exception", ":", "pass", "finally", ":", "# Once the main directory is created, copy files required", "temp_path", "=", "easydev", ".", "get_package_location", "(", "\"reports\"", ")", "temp_path", "+=", "os", ".", "sep", "+", "\"reports\"", "+", "os", ".", "sep", "+", "\"resources\"", "# Copy the CSS from reports/resources/css", "filenames", "=", "glob", ".", "glob", "(", "os", ".", "sep", ".", "join", "(", "[", "temp_path", ",", "\"css\"", ",", "\"*.css\"", "]", ")", ")", "# If there are CSS in the directory with JINJA templates, use them", "# as well", "filenames", "+=", "glob", ".", "glob", "(", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "searchpath", ",", "'*.css'", "]", ")", ")", "# In addition, the user may also provide his own CSS as a list", "filenames", "+=", "self", ".", "extra_css_list", "for", "filename", "in", "filenames", ":", "target", "=", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "directory", ",", "'css'", "]", ")", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", "is", "False", ":", "shutil", ".", "copy", "(", "filename", ",", "target", ")", "# We copy all javascript from reports resources", "for", "filename", "in", "[", "'sorttable.js'", ",", "'highlight.pack.js'", ",", "\"jquery-1.12.3.min.js\"", "]", ":", "target", "=", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "directory", ",", "'js'", ",", "filename", "]", ")", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", "is", "False", ":", "filename", "=", "os", ".", "sep", ".", "join", "(", "[", "temp_path", ",", "\"javascript\"", ",", "filename", "]", ")", "shutil", ".", "copy", "(", "filename", ",", "target", ")", "for", "filename", "in", "self", ".", "extra_js_list", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "target", "=", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "directory", ",", "'js'", ",", "basename", "]", ")", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", "is", "False", ":", "shutil", ".", "copy", "(", "filename", ",", "target", ")" ]
create the report directory and return the directory name
[ "create", "the", "report", "directory", "and", "return", "the", "directory", "name" ]
7703b1e27d440c3193ee6cc90bfecd78cc98b737
https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/report.py#L159-L209
train
1,111
cokelaer/reports
reports/report.py
Report.get_time_now
def get_time_now(self): """Returns a time stamp""" import datetime import getpass username = getpass.getuser() # this is not working on some systems: os.environ["USERNAME"] timenow = str(datetime.datetime.now()) timenow = timenow.split('.')[0] msg = '<div class="date">Created on ' + timenow msg += " by " + username +'</div>' return msg
python
def get_time_now(self): """Returns a time stamp""" import datetime import getpass username = getpass.getuser() # this is not working on some systems: os.environ["USERNAME"] timenow = str(datetime.datetime.now()) timenow = timenow.split('.')[0] msg = '<div class="date">Created on ' + timenow msg += " by " + username +'</div>' return msg
[ "def", "get_time_now", "(", "self", ")", ":", "import", "datetime", "import", "getpass", "username", "=", "getpass", ".", "getuser", "(", ")", "# this is not working on some systems: os.environ[\"USERNAME\"]", "timenow", "=", "str", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "timenow", "=", "timenow", ".", "split", "(", "'.'", ")", "[", "0", "]", "msg", "=", "'<div class=\"date\">Created on '", "+", "timenow", "msg", "+=", "\" by \"", "+", "username", "+", "'</div>'", "return", "msg" ]
Returns a time stamp
[ "Returns", "a", "time", "stamp" ]
7703b1e27d440c3193ee6cc90bfecd78cc98b737
https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/report.py#L230-L240
train
1,112
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class_related_field
def _track_class_related_field(cls, field): """ Track a field on a related model """ # field = field on current model # related_field = field on related model (field, related_field) = field.split('__', 1) field_obj = cls._meta.get_field(field) related_cls = field_obj.remote_field.model related_name = field_obj.remote_field.get_accessor_name() if not hasattr(related_cls, '_tracked_related_fields'): setattr(related_cls, '_tracked_related_fields', {}) if related_field not in related_cls._tracked_related_fields.keys(): related_cls._tracked_related_fields[related_field] = [] # There can be several field from different or same model # related to a single model. # Thus _tracked_related_fields will be of the form: # { # 'field name on related model': [ # ('field name on current model', 'field name to current model'), # ('field name on another model', 'field name to another model'), # ... # ], # ... # } related_cls._tracked_related_fields[related_field].append( (field, related_name) ) _add_signals_to_cls(related_cls) # Detect m2m fields changes if isinstance(related_cls._meta.get_field(related_field), ManyToManyField): m2m_changed.connect( tracking_m2m, sender=getattr(related_cls, related_field).through, dispatch_uid=repr(related_cls), )
python
def _track_class_related_field(cls, field): """ Track a field on a related model """ # field = field on current model # related_field = field on related model (field, related_field) = field.split('__', 1) field_obj = cls._meta.get_field(field) related_cls = field_obj.remote_field.model related_name = field_obj.remote_field.get_accessor_name() if not hasattr(related_cls, '_tracked_related_fields'): setattr(related_cls, '_tracked_related_fields', {}) if related_field not in related_cls._tracked_related_fields.keys(): related_cls._tracked_related_fields[related_field] = [] # There can be several field from different or same model # related to a single model. # Thus _tracked_related_fields will be of the form: # { # 'field name on related model': [ # ('field name on current model', 'field name to current model'), # ('field name on another model', 'field name to another model'), # ... # ], # ... # } related_cls._tracked_related_fields[related_field].append( (field, related_name) ) _add_signals_to_cls(related_cls) # Detect m2m fields changes if isinstance(related_cls._meta.get_field(related_field), ManyToManyField): m2m_changed.connect( tracking_m2m, sender=getattr(related_cls, related_field).through, dispatch_uid=repr(related_cls), )
[ "def", "_track_class_related_field", "(", "cls", ",", "field", ")", ":", "# field = field on current model", "# related_field = field on related model", "(", "field", ",", "related_field", ")", "=", "field", ".", "split", "(", "'__'", ",", "1", ")", "field_obj", "=", "cls", ".", "_meta", ".", "get_field", "(", "field", ")", "related_cls", "=", "field_obj", ".", "remote_field", ".", "model", "related_name", "=", "field_obj", ".", "remote_field", ".", "get_accessor_name", "(", ")", "if", "not", "hasattr", "(", "related_cls", ",", "'_tracked_related_fields'", ")", ":", "setattr", "(", "related_cls", ",", "'_tracked_related_fields'", ",", "{", "}", ")", "if", "related_field", "not", "in", "related_cls", ".", "_tracked_related_fields", ".", "keys", "(", ")", ":", "related_cls", ".", "_tracked_related_fields", "[", "related_field", "]", "=", "[", "]", "# There can be several field from different or same model", "# related to a single model.", "# Thus _tracked_related_fields will be of the form:", "# {", "# 'field name on related model': [", "# ('field name on current model', 'field name to current model'),", "# ('field name on another model', 'field name to another model'),", "# ...", "# ],", "# ...", "# }", "related_cls", ".", "_tracked_related_fields", "[", "related_field", "]", ".", "append", "(", "(", "field", ",", "related_name", ")", ")", "_add_signals_to_cls", "(", "related_cls", ")", "# Detect m2m fields changes", "if", "isinstance", "(", "related_cls", ".", "_meta", ".", "get_field", "(", "related_field", ")", ",", "ManyToManyField", ")", ":", "m2m_changed", ".", "connect", "(", "tracking_m2m", ",", "sender", "=", "getattr", "(", "related_cls", ",", "related_field", ")", ".", "through", ",", "dispatch_uid", "=", "repr", "(", "related_cls", ")", ",", ")" ]
Track a field on a related model
[ "Track", "a", "field", "on", "a", "related", "model" ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L35-L71
train
1,113
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class_field
def _track_class_field(cls, field): """ Track a field on the current model """ if '__' in field: _track_class_related_field(cls, field) return # Will raise FieldDoesNotExist if there is an error cls._meta.get_field(field) # Detect m2m fields changes if isinstance(cls._meta.get_field(field), ManyToManyField): m2m_changed.connect( tracking_m2m, sender=getattr(cls, field).through, dispatch_uid=repr(cls), )
python
def _track_class_field(cls, field): """ Track a field on the current model """ if '__' in field: _track_class_related_field(cls, field) return # Will raise FieldDoesNotExist if there is an error cls._meta.get_field(field) # Detect m2m fields changes if isinstance(cls._meta.get_field(field), ManyToManyField): m2m_changed.connect( tracking_m2m, sender=getattr(cls, field).through, dispatch_uid=repr(cls), )
[ "def", "_track_class_field", "(", "cls", ",", "field", ")", ":", "if", "'__'", "in", "field", ":", "_track_class_related_field", "(", "cls", ",", "field", ")", "return", "# Will raise FieldDoesNotExist if there is an error", "cls", ".", "_meta", ".", "get_field", "(", "field", ")", "# Detect m2m fields changes", "if", "isinstance", "(", "cls", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "m2m_changed", ".", "connect", "(", "tracking_m2m", ",", "sender", "=", "getattr", "(", "cls", ",", "field", ")", ".", "through", ",", "dispatch_uid", "=", "repr", "(", "cls", ")", ",", ")" ]
Track a field on the current model
[ "Track", "a", "field", "on", "the", "current", "model" ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L74-L87
train
1,114
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class
def _track_class(cls, fields): """ Track fields on the specified model """ # Small tests to ensure everything is all right assert not getattr(cls, '_is_tracked', False) for field in fields: _track_class_field(cls, field) _add_signals_to_cls(cls) # Mark the class as tracked cls._is_tracked = True # Do not directly track related fields (tracked on related model) # or m2m fields (tracked by another signal) cls._tracked_fields = [ field for field in fields if '__' not in field ]
python
def _track_class(cls, fields): """ Track fields on the specified model """ # Small tests to ensure everything is all right assert not getattr(cls, '_is_tracked', False) for field in fields: _track_class_field(cls, field) _add_signals_to_cls(cls) # Mark the class as tracked cls._is_tracked = True # Do not directly track related fields (tracked on related model) # or m2m fields (tracked by another signal) cls._tracked_fields = [ field for field in fields if '__' not in field ]
[ "def", "_track_class", "(", "cls", ",", "fields", ")", ":", "# Small tests to ensure everything is all right", "assert", "not", "getattr", "(", "cls", ",", "'_is_tracked'", ",", "False", ")", "for", "field", "in", "fields", ":", "_track_class_field", "(", "cls", ",", "field", ")", "_add_signals_to_cls", "(", "cls", ")", "# Mark the class as tracked", "cls", ".", "_is_tracked", "=", "True", "# Do not directly track related fields (tracked on related model)", "# or m2m fields (tracked by another signal)", "cls", ".", "_tracked_fields", "=", "[", "field", "for", "field", "in", "fields", "if", "'__'", "not", "in", "field", "]" ]
Track fields on the specified model
[ "Track", "fields", "on", "the", "specified", "model" ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L90-L107
train
1,115
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_add_get_tracking_url
def _add_get_tracking_url(cls): """ Add a method to get the tracking url of an object. """ def get_tracking_url(self): """ return url to tracking view in admin panel """ url = reverse('admin:tracking_fields_trackingevent_changelist') object_id = '{0}%3A{1}'.format( ContentType.objects.get_for_model(self).pk, self.pk ) return '{0}?object={1}'.format(url, object_id) if not hasattr(cls, 'get_tracking_url'): setattr(cls, 'get_tracking_url', get_tracking_url)
python
def _add_get_tracking_url(cls): """ Add a method to get the tracking url of an object. """ def get_tracking_url(self): """ return url to tracking view in admin panel """ url = reverse('admin:tracking_fields_trackingevent_changelist') object_id = '{0}%3A{1}'.format( ContentType.objects.get_for_model(self).pk, self.pk ) return '{0}?object={1}'.format(url, object_id) if not hasattr(cls, 'get_tracking_url'): setattr(cls, 'get_tracking_url', get_tracking_url)
[ "def", "_add_get_tracking_url", "(", "cls", ")", ":", "def", "get_tracking_url", "(", "self", ")", ":", "\"\"\" return url to tracking view in admin panel \"\"\"", "url", "=", "reverse", "(", "'admin:tracking_fields_trackingevent_changelist'", ")", "object_id", "=", "'{0}%3A{1}'", ".", "format", "(", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ")", ".", "pk", ",", "self", ".", "pk", ")", "return", "'{0}?object={1}'", ".", "format", "(", "url", ",", "object_id", ")", "if", "not", "hasattr", "(", "cls", ",", "'get_tracking_url'", ")", ":", "setattr", "(", "cls", ",", "'get_tracking_url'", ",", "get_tracking_url", ")" ]
Add a method to get the tracking url of an object.
[ "Add", "a", "method", "to", "get", "the", "tracking", "url", "of", "an", "object", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L110-L121
train
1,116
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
track
def track(*fields): """ Decorator used to track changes on Model's fields. :Example: >>> @track('name') ... class Human(models.Model): ... name = models.CharField(max_length=30) """ def inner(cls): _track_class(cls, fields) _add_get_tracking_url(cls) return cls return inner
python
def track(*fields): """ Decorator used to track changes on Model's fields. :Example: >>> @track('name') ... class Human(models.Model): ... name = models.CharField(max_length=30) """ def inner(cls): _track_class(cls, fields) _add_get_tracking_url(cls) return cls return inner
[ "def", "track", "(", "*", "fields", ")", ":", "def", "inner", "(", "cls", ")", ":", "_track_class", "(", "cls", ",", "fields", ")", "_add_get_tracking_url", "(", "cls", ")", "return", "cls", "return", "inner" ]
Decorator used to track changes on Model's fields. :Example: >>> @track('name') ... class Human(models.Model): ... name = models.CharField(max_length=30)
[ "Decorator", "used", "to", "track", "changes", "on", "Model", "s", "fields", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L124-L137
train
1,117
dourvaris/nano-python
docs/generate.py
indent
def indent(value, n=2, character=' '): """ Indent a value by `n` `character`s :param value: string to indent :param n: number of characters to indent by :param character: character to indent with """ prefix = n * character return '\n'.join(prefix + line for line in value.splitlines())
python
def indent(value, n=2, character=' '): """ Indent a value by `n` `character`s :param value: string to indent :param n: number of characters to indent by :param character: character to indent with """ prefix = n * character return '\n'.join(prefix + line for line in value.splitlines())
[ "def", "indent", "(", "value", ",", "n", "=", "2", ",", "character", "=", "' '", ")", ":", "prefix", "=", "n", "*", "character", "return", "'\\n'", ".", "join", "(", "prefix", "+", "line", "for", "line", "in", "value", ".", "splitlines", "(", ")", ")" ]
Indent a value by `n` `character`s :param value: string to indent :param n: number of characters to indent by :param character: character to indent with
[ "Indent", "a", "value", "by", "n", "character", "s" ]
f26b8bc895b997067780f925049a70e82c0c2479
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/docs/generate.py#L13-L23
train
1,118
NetworkAutomation/jaide
jaide/core.py
Jaide.check_instance
def check_instance(function): """ Wrapper that tests the type of _session. Purpose: This decorator function is used by all functions within | the Jaide class that interact with a device to ensure the | proper session type is in use. If it is not, it will | attempt to migrate _session to that type before moving | to the originally requested function. | > **NOTE:** This function is a decorator, and should not be | > used directly. All other methods in this class that touch | > the Junos device are wrapped by this function to ensure the | > proper connection type is used. @param function: the function that is being wrapped around @type function: function @returns: the originally requested function @rtype: function """ def wrapper(self, *args, **kwargs): func_trans = { "commit": manager.Manager, "compare_config": manager.Manager, "commit_check": manager.Manager, "device_info": manager.Manager, "diff_config": manager.Manager, "health_check": manager.Manager, "interface_errors": manager.Manager, "op_cmd": paramiko.client.SSHClient, "shell_cmd": paramiko.client.SSHClient, "scp_pull": paramiko.client.SSHClient, "scp_push": paramiko.client.SSHClient } # when doing an operational command, logging in as root # brings you to shell, so we need to enter the device as a shell # connection, and move to cli to perform the command # this is a one-off because the isinstance() check will be bypassed if self.username == "root" and function.__name__ == "op_cmd": if not self._session: self.conn_type = "paramiko" self.connect() if not self._shell: self.conn_type = "root" self.connect() self.shell_to_cli() # check if we're in the cli # Have to call shell command separately, since we are using _shell # for comparison, not _session. elif function.__name__ == 'shell_cmd': if not self._shell: self.conn_type = "shell" self.connect() self.cli_to_shell() # check if we're in shell. if isinstance(self._session, func_trans[function.__name__]): # If they're doing SCP, we have to check for both _session and # _scp if function.__name__ in ['scp_pull', 'scp_push']: if not isinstance(self._scp, SCPClient): self.conn_type = "scp" self.connect() else: self.disconnect() if function.__name__ == "op_cmd": self.conn_type = "paramiko" elif function.__name__ in ["scp_pull", "scp_push"]: self.conn_type = "scp" else: self.conn_type = "ncclient" self.connect() return function(self, *args, **kwargs) return wrapper
python
def check_instance(function): """ Wrapper that tests the type of _session. Purpose: This decorator function is used by all functions within | the Jaide class that interact with a device to ensure the | proper session type is in use. If it is not, it will | attempt to migrate _session to that type before moving | to the originally requested function. | > **NOTE:** This function is a decorator, and should not be | > used directly. All other methods in this class that touch | > the Junos device are wrapped by this function to ensure the | > proper connection type is used. @param function: the function that is being wrapped around @type function: function @returns: the originally requested function @rtype: function """ def wrapper(self, *args, **kwargs): func_trans = { "commit": manager.Manager, "compare_config": manager.Manager, "commit_check": manager.Manager, "device_info": manager.Manager, "diff_config": manager.Manager, "health_check": manager.Manager, "interface_errors": manager.Manager, "op_cmd": paramiko.client.SSHClient, "shell_cmd": paramiko.client.SSHClient, "scp_pull": paramiko.client.SSHClient, "scp_push": paramiko.client.SSHClient } # when doing an operational command, logging in as root # brings you to shell, so we need to enter the device as a shell # connection, and move to cli to perform the command # this is a one-off because the isinstance() check will be bypassed if self.username == "root" and function.__name__ == "op_cmd": if not self._session: self.conn_type = "paramiko" self.connect() if not self._shell: self.conn_type = "root" self.connect() self.shell_to_cli() # check if we're in the cli # Have to call shell command separately, since we are using _shell # for comparison, not _session. elif function.__name__ == 'shell_cmd': if not self._shell: self.conn_type = "shell" self.connect() self.cli_to_shell() # check if we're in shell. if isinstance(self._session, func_trans[function.__name__]): # If they're doing SCP, we have to check for both _session and # _scp if function.__name__ in ['scp_pull', 'scp_push']: if not isinstance(self._scp, SCPClient): self.conn_type = "scp" self.connect() else: self.disconnect() if function.__name__ == "op_cmd": self.conn_type = "paramiko" elif function.__name__ in ["scp_pull", "scp_push"]: self.conn_type = "scp" else: self.conn_type = "ncclient" self.connect() return function(self, *args, **kwargs) return wrapper
[ "def", "check_instance", "(", "function", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func_trans", "=", "{", "\"commit\"", ":", "manager", ".", "Manager", ",", "\"compare_config\"", ":", "manager", ".", "Manager", ",", "\"commit_check\"", ":", "manager", ".", "Manager", ",", "\"device_info\"", ":", "manager", ".", "Manager", ",", "\"diff_config\"", ":", "manager", ".", "Manager", ",", "\"health_check\"", ":", "manager", ".", "Manager", ",", "\"interface_errors\"", ":", "manager", ".", "Manager", ",", "\"op_cmd\"", ":", "paramiko", ".", "client", ".", "SSHClient", ",", "\"shell_cmd\"", ":", "paramiko", ".", "client", ".", "SSHClient", ",", "\"scp_pull\"", ":", "paramiko", ".", "client", ".", "SSHClient", ",", "\"scp_push\"", ":", "paramiko", ".", "client", ".", "SSHClient", "}", "# when doing an operational command, logging in as root", "# brings you to shell, so we need to enter the device as a shell", "# connection, and move to cli to perform the command", "# this is a one-off because the isinstance() check will be bypassed", "if", "self", ".", "username", "==", "\"root\"", "and", "function", ".", "__name__", "==", "\"op_cmd\"", ":", "if", "not", "self", ".", "_session", ":", "self", ".", "conn_type", "=", "\"paramiko\"", "self", ".", "connect", "(", ")", "if", "not", "self", ".", "_shell", ":", "self", ".", "conn_type", "=", "\"root\"", "self", ".", "connect", "(", ")", "self", ".", "shell_to_cli", "(", ")", "# check if we're in the cli", "# Have to call shell command separately, since we are using _shell", "# for comparison, not _session.", "elif", "function", ".", "__name__", "==", "'shell_cmd'", ":", "if", "not", "self", ".", "_shell", ":", "self", ".", "conn_type", "=", "\"shell\"", "self", ".", "connect", "(", ")", "self", ".", "cli_to_shell", "(", ")", "# check if we're in shell.", "if", "isinstance", "(", "self", ".", "_session", ",", "func_trans", "[", "function", ".", "__name__", "]", ")", ":", "# If they're doing SCP, we have to check for both _session and", "# _scp", "if", "function", ".", "__name__", "in", "[", "'scp_pull'", ",", "'scp_push'", "]", ":", "if", "not", "isinstance", "(", "self", ".", "_scp", ",", "SCPClient", ")", ":", "self", ".", "conn_type", "=", "\"scp\"", "self", ".", "connect", "(", ")", "else", ":", "self", ".", "disconnect", "(", ")", "if", "function", ".", "__name__", "==", "\"op_cmd\"", ":", "self", ".", "conn_type", "=", "\"paramiko\"", "elif", "function", ".", "__name__", "in", "[", "\"scp_pull\"", ",", "\"scp_push\"", "]", ":", "self", ".", "conn_type", "=", "\"scp\"", "else", ":", "self", ".", "conn_type", "=", "\"ncclient\"", "self", ".", "connect", "(", ")", "return", "function", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Wrapper that tests the type of _session. Purpose: This decorator function is used by all functions within | the Jaide class that interact with a device to ensure the | proper session type is in use. If it is not, it will | attempt to migrate _session to that type before moving | to the originally requested function. | > **NOTE:** This function is a decorator, and should not be | > used directly. All other methods in this class that touch | > the Junos device are wrapped by this function to ensure the | > proper connection type is used. @param function: the function that is being wrapped around @type function: function @returns: the originally requested function @rtype: function
[ "Wrapper", "that", "tests", "the", "type", "of", "_session", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L132-L201
train
1,119
NetworkAutomation/jaide
jaide/core.py
Jaide.commit
def commit(self, commands="", confirmed=None, comment=None, at_time=None, synchronize=False, req_format='text'): """ Perform a commit operation. Purpose: Executes a commit operation. All parameters are optional. | commit confirm and commit at are mutually exclusive. All | the others can be used with each other and commit confirm/at. @param commands: A string or list of multiple commands | that the device will compare with. | If a string, it can be a single command, | multiple commands separated by commas, or | a filepath location of a file with multiple | commands, each on its own line. @type commands: str or list @param confirmed: integer value of the number of **seconds** to | confirm the commit for, if requested. @type confirmed: int @param comment: string that the user wants to comment the commit | with. Will show up in the 'show system commit' log. @type comment: str @param at_time: string designating the time at which the commit | should happen. Can be in one of two Junos approved | formats. @type comment: str @param synchronize: boolean set to true if desiring a commit | synchronize operation. @type synchronize: bool @param req_format: string to specify the response format. Accepts | either 'text' or 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ # ncclient doesn't support a truly blank commit, so if nothing is # passed, use 'annotate system' to make a blank commit if not commands: commands = 'annotate system ""' clean_cmds = [] for cmd in clean_lines(commands): clean_cmds.append(cmd) # try to lock the candidate config so we can make changes. self.lock() self._session.load_configuration(action='set', config=commands) results = "" # confirmed and commit at are mutually exclusive. commit confirm # takes precedence. if confirmed: results = self._session.commit(confirmed=True, timeout=str(confirmed), comment=comment, synchronize=synchronize) else: results = self._session.commit(comment=comment, at_time=at_time, synchronize=synchronize) self.unlock() if results: if req_format == 'xml': return results # commit() DOES NOT return a parse-able xml tree, so we # convert it to an ElementTree xml tree. results = ET.fromstring(results.tostring) out = '' for i in results.iter(): # the success message is just a tag, so we need to get it # specifically. if i.tag == 'commit-check-success': out += 'configuration check succeeds\n' elif i.tag == 'commit-success': out += 'commit complete\n' elif i.tag == 'ok': out += 'commit complete\n' # this is for normal output with a tag and inner text, it will # strip the inner text and add it to the output. elif i.text is not None: if i.text.strip() + '\n' != '\n': out += i.text.strip() + '\n' # this is for elements that don't have inner text, # it will add the tag to the output. elif i.text is None: if i.tag + '\n' != '\n': out += i.tag + '\n' return out return False
python
def commit(self, commands="", confirmed=None, comment=None, at_time=None, synchronize=False, req_format='text'): """ Perform a commit operation. Purpose: Executes a commit operation. All parameters are optional. | commit confirm and commit at are mutually exclusive. All | the others can be used with each other and commit confirm/at. @param commands: A string or list of multiple commands | that the device will compare with. | If a string, it can be a single command, | multiple commands separated by commas, or | a filepath location of a file with multiple | commands, each on its own line. @type commands: str or list @param confirmed: integer value of the number of **seconds** to | confirm the commit for, if requested. @type confirmed: int @param comment: string that the user wants to comment the commit | with. Will show up in the 'show system commit' log. @type comment: str @param at_time: string designating the time at which the commit | should happen. Can be in one of two Junos approved | formats. @type comment: str @param synchronize: boolean set to true if desiring a commit | synchronize operation. @type synchronize: bool @param req_format: string to specify the response format. Accepts | either 'text' or 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ # ncclient doesn't support a truly blank commit, so if nothing is # passed, use 'annotate system' to make a blank commit if not commands: commands = 'annotate system ""' clean_cmds = [] for cmd in clean_lines(commands): clean_cmds.append(cmd) # try to lock the candidate config so we can make changes. self.lock() self._session.load_configuration(action='set', config=commands) results = "" # confirmed and commit at are mutually exclusive. commit confirm # takes precedence. if confirmed: results = self._session.commit(confirmed=True, timeout=str(confirmed), comment=comment, synchronize=synchronize) else: results = self._session.commit(comment=comment, at_time=at_time, synchronize=synchronize) self.unlock() if results: if req_format == 'xml': return results # commit() DOES NOT return a parse-able xml tree, so we # convert it to an ElementTree xml tree. results = ET.fromstring(results.tostring) out = '' for i in results.iter(): # the success message is just a tag, so we need to get it # specifically. if i.tag == 'commit-check-success': out += 'configuration check succeeds\n' elif i.tag == 'commit-success': out += 'commit complete\n' elif i.tag == 'ok': out += 'commit complete\n' # this is for normal output with a tag and inner text, it will # strip the inner text and add it to the output. elif i.text is not None: if i.text.strip() + '\n' != '\n': out += i.text.strip() + '\n' # this is for elements that don't have inner text, # it will add the tag to the output. elif i.text is None: if i.tag + '\n' != '\n': out += i.tag + '\n' return out return False
[ "def", "commit", "(", "self", ",", "commands", "=", "\"\"", ",", "confirmed", "=", "None", ",", "comment", "=", "None", ",", "at_time", "=", "None", ",", "synchronize", "=", "False", ",", "req_format", "=", "'text'", ")", ":", "# ncclient doesn't support a truly blank commit, so if nothing is", "# passed, use 'annotate system' to make a blank commit", "if", "not", "commands", ":", "commands", "=", "'annotate system \"\"'", "clean_cmds", "=", "[", "]", "for", "cmd", "in", "clean_lines", "(", "commands", ")", ":", "clean_cmds", ".", "append", "(", "cmd", ")", "# try to lock the candidate config so we can make changes.", "self", ".", "lock", "(", ")", "self", ".", "_session", ".", "load_configuration", "(", "action", "=", "'set'", ",", "config", "=", "commands", ")", "results", "=", "\"\"", "# confirmed and commit at are mutually exclusive. commit confirm", "# takes precedence.", "if", "confirmed", ":", "results", "=", "self", ".", "_session", ".", "commit", "(", "confirmed", "=", "True", ",", "timeout", "=", "str", "(", "confirmed", ")", ",", "comment", "=", "comment", ",", "synchronize", "=", "synchronize", ")", "else", ":", "results", "=", "self", ".", "_session", ".", "commit", "(", "comment", "=", "comment", ",", "at_time", "=", "at_time", ",", "synchronize", "=", "synchronize", ")", "self", ".", "unlock", "(", ")", "if", "results", ":", "if", "req_format", "==", "'xml'", ":", "return", "results", "# commit() DOES NOT return a parse-able xml tree, so we", "# convert it to an ElementTree xml tree.", "results", "=", "ET", ".", "fromstring", "(", "results", ".", "tostring", ")", "out", "=", "''", "for", "i", "in", "results", ".", "iter", "(", ")", ":", "# the success message is just a tag, so we need to get it", "# specifically.", "if", "i", ".", "tag", "==", "'commit-check-success'", ":", "out", "+=", "'configuration check succeeds\\n'", "elif", "i", ".", "tag", "==", "'commit-success'", ":", "out", "+=", "'commit complete\\n'", "elif", "i", ".", "tag", "==", "'ok'", ":", "out", "+=", "'commit complete\\n'", "# this is for normal output with a tag and inner text, it will", "# strip the inner text and add it to the output.", "elif", "i", ".", "text", "is", "not", "None", ":", "if", "i", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", "!=", "'\\n'", ":", "out", "+=", "i", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", "# this is for elements that don't have inner text,", "# it will add the tag to the output.", "elif", "i", ".", "text", "is", "None", ":", "if", "i", ".", "tag", "+", "'\\n'", "!=", "'\\n'", ":", "out", "+=", "i", ".", "tag", "+", "'\\n'", "return", "out", "return", "False" ]
Perform a commit operation. Purpose: Executes a commit operation. All parameters are optional. | commit confirm and commit at are mutually exclusive. All | the others can be used with each other and commit confirm/at. @param commands: A string or list of multiple commands | that the device will compare with. | If a string, it can be a single command, | multiple commands separated by commas, or | a filepath location of a file with multiple | commands, each on its own line. @type commands: str or list @param confirmed: integer value of the number of **seconds** to | confirm the commit for, if requested. @type confirmed: int @param comment: string that the user wants to comment the commit | with. Will show up in the 'show system commit' log. @type comment: str @param at_time: string designating the time at which the commit | should happen. Can be in one of two Junos approved | formats. @type comment: str @param synchronize: boolean set to true if desiring a commit | synchronize operation. @type synchronize: bool @param req_format: string to specify the response format. Accepts | either 'text' or 'xml' @type req_format: str @returns: The reply from the device. @rtype: str
[ "Perform", "a", "commit", "operation", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L214-L298
train
1,120
NetworkAutomation/jaide
jaide/core.py
Jaide.commit_check
def commit_check(self, commands="", req_format="text"): """ Execute a commit check operation. Purpose: This method will take in string of multiple commands, | and perform and 'commit check' on the device to ensure | the commands are syntactically correct. The response can | be formatted as text or as xml. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ if not commands: raise InvalidCommandError('No commands specified') clean_cmds = [] for cmd in clean_lines(commands): clean_cmds.append(cmd) self.lock() self._session.load_configuration(action='set', config=clean_cmds) # conn.validate() DOES NOT return a parse-able xml tree, so we # convert it to an ElementTree xml tree. results = ET.fromstring(self._session.validate( source='candidate').tostring) # release the candidate configuration self.unlock() if req_format == "xml": return ET.tostring(results) out = "" # we have to parse the elementTree object, and get the text # from the xml. for i in results.iter(): # the success message is just a tag, so we need to get it # specifically. if i.tag == 'commit-check-success': out += 'configuration check succeeds\n' # this is for normal output with a tag and inner text, it will # strip the inner text and add it to the output. elif i.text is not None: if i.text.strip() + '\n' != '\n': out += i.text.strip() + '\n' # this is for elements that don't have inner text, it will add the # tag to the output. elif i.text is None: if i.tag + '\n' != '\n': out += i.tag + '\n' return out
python
def commit_check(self, commands="", req_format="text"): """ Execute a commit check operation. Purpose: This method will take in string of multiple commands, | and perform and 'commit check' on the device to ensure | the commands are syntactically correct. The response can | be formatted as text or as xml. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ if not commands: raise InvalidCommandError('No commands specified') clean_cmds = [] for cmd in clean_lines(commands): clean_cmds.append(cmd) self.lock() self._session.load_configuration(action='set', config=clean_cmds) # conn.validate() DOES NOT return a parse-able xml tree, so we # convert it to an ElementTree xml tree. results = ET.fromstring(self._session.validate( source='candidate').tostring) # release the candidate configuration self.unlock() if req_format == "xml": return ET.tostring(results) out = "" # we have to parse the elementTree object, and get the text # from the xml. for i in results.iter(): # the success message is just a tag, so we need to get it # specifically. if i.tag == 'commit-check-success': out += 'configuration check succeeds\n' # this is for normal output with a tag and inner text, it will # strip the inner text and add it to the output. elif i.text is not None: if i.text.strip() + '\n' != '\n': out += i.text.strip() + '\n' # this is for elements that don't have inner text, it will add the # tag to the output. elif i.text is None: if i.tag + '\n' != '\n': out += i.tag + '\n' return out
[ "def", "commit_check", "(", "self", ",", "commands", "=", "\"\"", ",", "req_format", "=", "\"text\"", ")", ":", "if", "not", "commands", ":", "raise", "InvalidCommandError", "(", "'No commands specified'", ")", "clean_cmds", "=", "[", "]", "for", "cmd", "in", "clean_lines", "(", "commands", ")", ":", "clean_cmds", ".", "append", "(", "cmd", ")", "self", ".", "lock", "(", ")", "self", ".", "_session", ".", "load_configuration", "(", "action", "=", "'set'", ",", "config", "=", "clean_cmds", ")", "# conn.validate() DOES NOT return a parse-able xml tree, so we", "# convert it to an ElementTree xml tree.", "results", "=", "ET", ".", "fromstring", "(", "self", ".", "_session", ".", "validate", "(", "source", "=", "'candidate'", ")", ".", "tostring", ")", "# release the candidate configuration", "self", ".", "unlock", "(", ")", "if", "req_format", "==", "\"xml\"", ":", "return", "ET", ".", "tostring", "(", "results", ")", "out", "=", "\"\"", "# we have to parse the elementTree object, and get the text", "# from the xml.", "for", "i", "in", "results", ".", "iter", "(", ")", ":", "# the success message is just a tag, so we need to get it", "# specifically.", "if", "i", ".", "tag", "==", "'commit-check-success'", ":", "out", "+=", "'configuration check succeeds\\n'", "# this is for normal output with a tag and inner text, it will", "# strip the inner text and add it to the output.", "elif", "i", ".", "text", "is", "not", "None", ":", "if", "i", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", "!=", "'\\n'", ":", "out", "+=", "i", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", "# this is for elements that don't have inner text, it will add the", "# tag to the output.", "elif", "i", ".", "text", "is", "None", ":", "if", "i", ".", "tag", "+", "'\\n'", "!=", "'\\n'", ":", "out", "+=", "i", ".", "tag", "+", "'\\n'", "return", "out" ]
Execute a commit check operation. Purpose: This method will take in string of multiple commands, | and perform and 'commit check' on the device to ensure | the commands are syntactically correct. The response can | be formatted as text or as xml. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str
[ "Execute", "a", "commit", "check", "operation", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L301-L352
train
1,121
NetworkAutomation/jaide
jaide/core.py
Jaide.compare_config
def compare_config(self, commands="", req_format="text"): """ Execute a 'show | compare' against the specified commands. Purpose: This method will take in string of multiple commands, | and perform and 'show | compare' on the device to show the | differences between the active running configuration and | the changes proposed by the passed commands parameter. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ if not commands: raise InvalidCommandError('No commands specified') clean_cmds = [cmd for cmd in clean_lines(commands)] self.lock() self._session.load_configuration(action='set', config=clean_cmds) out = self._session.compare_configuration() self.unlock() if req_format.lower() == "xml": return out return out.xpath( 'configuration-information/configuration-output')[0].text
python
def compare_config(self, commands="", req_format="text"): """ Execute a 'show | compare' against the specified commands. Purpose: This method will take in string of multiple commands, | and perform and 'show | compare' on the device to show the | differences between the active running configuration and | the changes proposed by the passed commands parameter. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str """ if not commands: raise InvalidCommandError('No commands specified') clean_cmds = [cmd for cmd in clean_lines(commands)] self.lock() self._session.load_configuration(action='set', config=clean_cmds) out = self._session.compare_configuration() self.unlock() if req_format.lower() == "xml": return out return out.xpath( 'configuration-information/configuration-output')[0].text
[ "def", "compare_config", "(", "self", ",", "commands", "=", "\"\"", ",", "req_format", "=", "\"text\"", ")", ":", "if", "not", "commands", ":", "raise", "InvalidCommandError", "(", "'No commands specified'", ")", "clean_cmds", "=", "[", "cmd", "for", "cmd", "in", "clean_lines", "(", "commands", ")", "]", "self", ".", "lock", "(", ")", "self", ".", "_session", ".", "load_configuration", "(", "action", "=", "'set'", ",", "config", "=", "clean_cmds", ")", "out", "=", "self", ".", "_session", ".", "compare_configuration", "(", ")", "self", ".", "unlock", "(", ")", "if", "req_format", ".", "lower", "(", ")", "==", "\"xml\"", ":", "return", "out", "return", "out", ".", "xpath", "(", "'configuration-information/configuration-output'", ")", "[", "0", "]", ".", "text" ]
Execute a 'show | compare' against the specified commands. Purpose: This method will take in string of multiple commands, | and perform and 'show | compare' on the device to show the | differences between the active running configuration and | the changes proposed by the passed commands parameter. @param commands: A string, filepath, or list of multiple commands | that the device will compare with. @type commands: str or list @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml' @type req_format: str @returns: The reply from the device. @rtype: str
[ "Execute", "a", "show", "|", "compare", "against", "the", "specified", "commands", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L355-L383
train
1,122
NetworkAutomation/jaide
jaide/core.py
Jaide.connect
def connect(self): """ Establish a connection to the device. Purpose: This method is used to make a connection to the junos | device. The internal property conn_type is what | determines the type of connection we make to the device. | - 'paramiko' is used for operational commands (to allow | pipes in commands) | - 'scp' is used for copying files | - 'shell' is used for to send shell commands | - 'root' is used when logging into the device as root, and | wanting to send operational commands | - 'ncclient' is used for the rest (commit, compare_config, | commit_check) @returns: None @rtype: None """ if self.conn_type == 'paramiko': self._session = paramiko.SSHClient() # These two lines set the paramiko logging to Critical to # remove extra messages from being sent to the user output. logger = logging.Logger.manager.getLogger('paramiko.transport') logger.setLevel(logging.CRITICAL) self._session.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self._session.connect(hostname=self.host, username=self.username, password=self.password, port=self.port, timeout=self.connect_timeout) if self.conn_type == 'scp': self._scp_session = paramiko.SSHClient() logger = logging.Logger.manager.getLogger('paramiko.transport') logger.setLevel(logging.CRITICAL) self._scp_session.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self._scp_session.connect(hostname=self.host, username=self.username, password=self.password, port=self.port, timeout=self.connect_timeout) self._scp = SCPClient(self._scp_session.get_transport()) elif self.conn_type == "ncclient": self._session = manager.connect( host=self.host, port=self.port, username=self.username, password=self.password, timeout=self.connect_timeout, device_params={'name': 'junos'}, hostkey_verify=False ) elif self.conn_type == 'shell': if not self._session: self.conn_type = 'paramiko' self.connect() self.conn_type = 'shell' if not self._shell: self._shell = self._session.invoke_shell() time.sleep(2) if self.username != 'root' and not self._in_cli: self._in_cli = True if not self.cli_to_shell(): self._shell.recv(9999) elif self.conn_type == 'root': # open the shell if necessary, and move into CLI if not self._shell: self._shell = self._session.invoke_shell() time.sleep(2) if not self.shell_to_cli(): self._shell.recv(9999) self._update_timeout(self.session_timeout)
python
def connect(self): """ Establish a connection to the device. Purpose: This method is used to make a connection to the junos | device. The internal property conn_type is what | determines the type of connection we make to the device. | - 'paramiko' is used for operational commands (to allow | pipes in commands) | - 'scp' is used for copying files | - 'shell' is used for to send shell commands | - 'root' is used when logging into the device as root, and | wanting to send operational commands | - 'ncclient' is used for the rest (commit, compare_config, | commit_check) @returns: None @rtype: None """ if self.conn_type == 'paramiko': self._session = paramiko.SSHClient() # These two lines set the paramiko logging to Critical to # remove extra messages from being sent to the user output. logger = logging.Logger.manager.getLogger('paramiko.transport') logger.setLevel(logging.CRITICAL) self._session.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self._session.connect(hostname=self.host, username=self.username, password=self.password, port=self.port, timeout=self.connect_timeout) if self.conn_type == 'scp': self._scp_session = paramiko.SSHClient() logger = logging.Logger.manager.getLogger('paramiko.transport') logger.setLevel(logging.CRITICAL) self._scp_session.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self._scp_session.connect(hostname=self.host, username=self.username, password=self.password, port=self.port, timeout=self.connect_timeout) self._scp = SCPClient(self._scp_session.get_transport()) elif self.conn_type == "ncclient": self._session = manager.connect( host=self.host, port=self.port, username=self.username, password=self.password, timeout=self.connect_timeout, device_params={'name': 'junos'}, hostkey_verify=False ) elif self.conn_type == 'shell': if not self._session: self.conn_type = 'paramiko' self.connect() self.conn_type = 'shell' if not self._shell: self._shell = self._session.invoke_shell() time.sleep(2) if self.username != 'root' and not self._in_cli: self._in_cli = True if not self.cli_to_shell(): self._shell.recv(9999) elif self.conn_type == 'root': # open the shell if necessary, and move into CLI if not self._shell: self._shell = self._session.invoke_shell() time.sleep(2) if not self.shell_to_cli(): self._shell.recv(9999) self._update_timeout(self.session_timeout)
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "conn_type", "==", "'paramiko'", ":", "self", ".", "_session", "=", "paramiko", ".", "SSHClient", "(", ")", "# These two lines set the paramiko logging to Critical to", "# remove extra messages from being sent to the user output.", "logger", "=", "logging", ".", "Logger", ".", "manager", ".", "getLogger", "(", "'paramiko.transport'", ")", "logger", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "self", ".", "_session", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "self", ".", "_session", ".", "connect", "(", "hostname", "=", "self", ".", "host", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "port", "=", "self", ".", "port", ",", "timeout", "=", "self", ".", "connect_timeout", ")", "if", "self", ".", "conn_type", "==", "'scp'", ":", "self", ".", "_scp_session", "=", "paramiko", ".", "SSHClient", "(", ")", "logger", "=", "logging", ".", "Logger", ".", "manager", ".", "getLogger", "(", "'paramiko.transport'", ")", "logger", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "self", ".", "_scp_session", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "self", ".", "_scp_session", ".", "connect", "(", "hostname", "=", "self", ".", "host", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "port", "=", "self", ".", "port", ",", "timeout", "=", "self", ".", "connect_timeout", ")", "self", ".", "_scp", "=", "SCPClient", "(", "self", ".", "_scp_session", ".", "get_transport", "(", ")", ")", "elif", "self", ".", "conn_type", "==", "\"ncclient\"", ":", "self", ".", "_session", "=", "manager", ".", "connect", "(", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "timeout", "=", "self", ".", "connect_timeout", ",", "device_params", "=", "{", "'name'", ":", "'junos'", "}", ",", "hostkey_verify", "=", "False", ")", "elif", "self", ".", "conn_type", "==", "'shell'", ":", "if", "not", "self", ".", "_session", ":", "self", ".", "conn_type", "=", "'paramiko'", "self", ".", "connect", "(", ")", "self", ".", "conn_type", "=", "'shell'", "if", "not", "self", ".", "_shell", ":", "self", ".", "_shell", "=", "self", ".", "_session", ".", "invoke_shell", "(", ")", "time", ".", "sleep", "(", "2", ")", "if", "self", ".", "username", "!=", "'root'", "and", "not", "self", ".", "_in_cli", ":", "self", ".", "_in_cli", "=", "True", "if", "not", "self", ".", "cli_to_shell", "(", ")", ":", "self", ".", "_shell", ".", "recv", "(", "9999", ")", "elif", "self", ".", "conn_type", "==", "'root'", ":", "# open the shell if necessary, and move into CLI", "if", "not", "self", ".", "_shell", ":", "self", ".", "_shell", "=", "self", ".", "_session", ".", "invoke_shell", "(", ")", "time", ".", "sleep", "(", "2", ")", "if", "not", "self", ".", "shell_to_cli", "(", ")", ":", "self", ".", "_shell", ".", "recv", "(", "9999", ")", "self", ".", "_update_timeout", "(", "self", ".", "session_timeout", ")" ]
Establish a connection to the device. Purpose: This method is used to make a connection to the junos | device. The internal property conn_type is what | determines the type of connection we make to the device. | - 'paramiko' is used for operational commands (to allow | pipes in commands) | - 'scp' is used for copying files | - 'shell' is used for to send shell commands | - 'root' is used when logging into the device as root, and | wanting to send operational commands | - 'ncclient' is used for the rest (commit, compare_config, | commit_check) @returns: None @rtype: None
[ "Establish", "a", "connection", "to", "the", "device", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L385-L457
train
1,123
NetworkAutomation/jaide
jaide/core.py
Jaide._copy_status
def _copy_status(self, filename, size, sent): """ Echo status of an SCP operation. Purpose: Callback function for an SCP operation. Used to show | the progress of an actively running copy. This directly | prints to stdout, one line for each file as it's copied. | The parameters received by this function are those received | from the scp.put or scp.get function, as explained in the | python scp module docs. @param filename: The filename of file being copied. @type filename: str @param size: The total size of the current file being copied. @type size: str or float @param sent: The amount of data sent for the current file being copied. @type sent: str or float @returns: None """ output = "Transferred %.0f%% of the file %s" % ( (float(sent) / float(size) * 100), path.normpath(filename)) output += (' ' * (120 - len(output))) if filename != self._filename: if self._filename is not None: print('') self._filename = filename print(output, end='\r')
python
def _copy_status(self, filename, size, sent): """ Echo status of an SCP operation. Purpose: Callback function for an SCP operation. Used to show | the progress of an actively running copy. This directly | prints to stdout, one line for each file as it's copied. | The parameters received by this function are those received | from the scp.put or scp.get function, as explained in the | python scp module docs. @param filename: The filename of file being copied. @type filename: str @param size: The total size of the current file being copied. @type size: str or float @param sent: The amount of data sent for the current file being copied. @type sent: str or float @returns: None """ output = "Transferred %.0f%% of the file %s" % ( (float(sent) / float(size) * 100), path.normpath(filename)) output += (' ' * (120 - len(output))) if filename != self._filename: if self._filename is not None: print('') self._filename = filename print(output, end='\r')
[ "def", "_copy_status", "(", "self", ",", "filename", ",", "size", ",", "sent", ")", ":", "output", "=", "\"Transferred %.0f%% of the file %s\"", "%", "(", "(", "float", "(", "sent", ")", "/", "float", "(", "size", ")", "*", "100", ")", ",", "path", ".", "normpath", "(", "filename", ")", ")", "output", "+=", "(", "' '", "*", "(", "120", "-", "len", "(", "output", ")", ")", ")", "if", "filename", "!=", "self", ".", "_filename", ":", "if", "self", ".", "_filename", "is", "not", "None", ":", "print", "(", "''", ")", "self", ".", "_filename", "=", "filename", "print", "(", "output", ",", "end", "=", "'\\r'", ")" ]
Echo status of an SCP operation. Purpose: Callback function for an SCP operation. Used to show | the progress of an actively running copy. This directly | prints to stdout, one line for each file as it's copied. | The parameters received by this function are those received | from the scp.put or scp.get function, as explained in the | python scp module docs. @param filename: The filename of file being copied. @type filename: str @param size: The total size of the current file being copied. @type size: str or float @param sent: The amount of data sent for the current file being copied. @type sent: str or float @returns: None
[ "Echo", "status", "of", "an", "SCP", "operation", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L459-L485
train
1,124
NetworkAutomation/jaide
jaide/core.py
Jaide.device_info
def device_info(self): """ Pull basic device information. Purpose: This function grabs the hostname, model, running version, and | serial number of the device. @returns: The output that should be shown to the user. @rtype: str """ # get hostname, model, and version from 'show version' resp = self._session.get_software_information(format='xml') hostname = resp.xpath('//software-information/host-name')[0].text model = resp.xpath('//software-information/product-model')[0].text version = 'Unknown' if resp.xpath('//junos-version'): """ case: <junos-version>15.1</junos-version> """ try: version = resp.xpath('//junos-version')[0].text except IndexError: pass elif resp.xpath("//package-information[name = 'junos-version']"): """ case: <package-information> <name>junos-version</name> <comment>Junos: 14.2R4</comment> </package-information> """ try: version = (resp.xpath( "//package-information[name = 'junos-version']/comment" )[0].text).split()[1] except IndexError: pass else: """ case: <package-information> <name>junos</name> <comment>JUNOS Base OS boot [12.3R5]</comment> </package-information> """ try: version = ((resp.xpath( '//software-information/package-information/comment' )[0].text.split('[')[1].split(']')[0])) except IndexError: pass # try looking for 'junos-version' for >= 14.2 # for element in resp.xpath('//software-information'): # version = element.findtext('junos-version') # if not version: # try: # version = ((resp.xpath( # '//software-information/package-information/comment') # [0].text.split('[')[1].split(']')[0])) # except IndexError: # version = 'Unknown' # get uptime from 'show system uptime' resp = self._session.get_system_uptime_information(format='xml') try: current_time = resp.xpath('//current-time/date-time')[0].text except IndexError: current_time = 'Unknown' try: uptime = resp.xpath('//uptime-information/up-time')[0].text except IndexError: uptime = 'Unknown' # get serial number from 'show chassis hardware' show_hardware = self._session.get_chassis_inventory(format='xml') # If we're hitting an EX, grab each Routing Engine Serial number # to get all RE SNs in a VC try: chassis_module = show_hardware.xpath( '//chassis-inventory/chassis/chassis-module/description' )[0].text except IndexError: chassis_module = 'Unknown' if ('EX' or 'ex' or 'Ex') in chassis_module: serial_num = '' for eng in show_hardware.xpath( '//chassis-inventory/chassis/chassis-module'): if 'Routing Engine' in eng.xpath('name')[0].text: serial_num += (eng.xpath('name')[0].text + ' Serial #: ' + eng.xpath('serial-number')[0].text) else: # Any other device type, just grab chassis SN try: serial_num = ('Chassis Serial Number: ' + show_hardware.xpath( '//chassis-inventory/chassis/serial-number')[0].text) except IndexError: serial_num = 'Chassis Serial Number: ' \ + 'Unknown (virtual machine?)' return ('Hostname: %s\nModel: %s\nJunos Version: %s\n%s\nCurrent Time:' ' %s\nUptime: %s\n' % (hostname, model, version, serial_num, current_time, uptime))
python
def device_info(self): """ Pull basic device information. Purpose: This function grabs the hostname, model, running version, and | serial number of the device. @returns: The output that should be shown to the user. @rtype: str """ # get hostname, model, and version from 'show version' resp = self._session.get_software_information(format='xml') hostname = resp.xpath('//software-information/host-name')[0].text model = resp.xpath('//software-information/product-model')[0].text version = 'Unknown' if resp.xpath('//junos-version'): """ case: <junos-version>15.1</junos-version> """ try: version = resp.xpath('//junos-version')[0].text except IndexError: pass elif resp.xpath("//package-information[name = 'junos-version']"): """ case: <package-information> <name>junos-version</name> <comment>Junos: 14.2R4</comment> </package-information> """ try: version = (resp.xpath( "//package-information[name = 'junos-version']/comment" )[0].text).split()[1] except IndexError: pass else: """ case: <package-information> <name>junos</name> <comment>JUNOS Base OS boot [12.3R5]</comment> </package-information> """ try: version = ((resp.xpath( '//software-information/package-information/comment' )[0].text.split('[')[1].split(']')[0])) except IndexError: pass # try looking for 'junos-version' for >= 14.2 # for element in resp.xpath('//software-information'): # version = element.findtext('junos-version') # if not version: # try: # version = ((resp.xpath( # '//software-information/package-information/comment') # [0].text.split('[')[1].split(']')[0])) # except IndexError: # version = 'Unknown' # get uptime from 'show system uptime' resp = self._session.get_system_uptime_information(format='xml') try: current_time = resp.xpath('//current-time/date-time')[0].text except IndexError: current_time = 'Unknown' try: uptime = resp.xpath('//uptime-information/up-time')[0].text except IndexError: uptime = 'Unknown' # get serial number from 'show chassis hardware' show_hardware = self._session.get_chassis_inventory(format='xml') # If we're hitting an EX, grab each Routing Engine Serial number # to get all RE SNs in a VC try: chassis_module = show_hardware.xpath( '//chassis-inventory/chassis/chassis-module/description' )[0].text except IndexError: chassis_module = 'Unknown' if ('EX' or 'ex' or 'Ex') in chassis_module: serial_num = '' for eng in show_hardware.xpath( '//chassis-inventory/chassis/chassis-module'): if 'Routing Engine' in eng.xpath('name')[0].text: serial_num += (eng.xpath('name')[0].text + ' Serial #: ' + eng.xpath('serial-number')[0].text) else: # Any other device type, just grab chassis SN try: serial_num = ('Chassis Serial Number: ' + show_hardware.xpath( '//chassis-inventory/chassis/serial-number')[0].text) except IndexError: serial_num = 'Chassis Serial Number: ' \ + 'Unknown (virtual machine?)' return ('Hostname: %s\nModel: %s\nJunos Version: %s\n%s\nCurrent Time:' ' %s\nUptime: %s\n' % (hostname, model, version, serial_num, current_time, uptime))
[ "def", "device_info", "(", "self", ")", ":", "# get hostname, model, and version from 'show version'", "resp", "=", "self", ".", "_session", ".", "get_software_information", "(", "format", "=", "'xml'", ")", "hostname", "=", "resp", ".", "xpath", "(", "'//software-information/host-name'", ")", "[", "0", "]", ".", "text", "model", "=", "resp", ".", "xpath", "(", "'//software-information/product-model'", ")", "[", "0", "]", ".", "text", "version", "=", "'Unknown'", "if", "resp", ".", "xpath", "(", "'//junos-version'", ")", ":", "\"\"\" case:\n <junos-version>15.1</junos-version>\n \"\"\"", "try", ":", "version", "=", "resp", ".", "xpath", "(", "'//junos-version'", ")", "[", "0", "]", ".", "text", "except", "IndexError", ":", "pass", "elif", "resp", ".", "xpath", "(", "\"//package-information[name = 'junos-version']\"", ")", ":", "\"\"\" case:\n <package-information>\n <name>junos-version</name>\n <comment>Junos: 14.2R4</comment>\n </package-information>\n \"\"\"", "try", ":", "version", "=", "(", "resp", ".", "xpath", "(", "\"//package-information[name = 'junos-version']/comment\"", ")", "[", "0", "]", ".", "text", ")", ".", "split", "(", ")", "[", "1", "]", "except", "IndexError", ":", "pass", "else", ":", "\"\"\" case:\n <package-information>\n <name>junos</name>\n <comment>JUNOS Base OS boot [12.3R5]</comment>\n </package-information>\n \"\"\"", "try", ":", "version", "=", "(", "(", "resp", ".", "xpath", "(", "'//software-information/package-information/comment'", ")", "[", "0", "]", ".", "text", ".", "split", "(", "'['", ")", "[", "1", "]", ".", "split", "(", "']'", ")", "[", "0", "]", ")", ")", "except", "IndexError", ":", "pass", "# try looking for 'junos-version' for >= 14.2", "# for element in resp.xpath('//software-information'):", "# version = element.findtext('junos-version')", "# if not version:", "# try:", "# version = ((resp.xpath(", "# '//software-information/package-information/comment')", "# [0].text.split('[')[1].split(']')[0]))", "# except IndexError:", "# version = 'Unknown'", "# get uptime from 'show system uptime'", "resp", "=", "self", ".", "_session", ".", "get_system_uptime_information", "(", "format", "=", "'xml'", ")", "try", ":", "current_time", "=", "resp", ".", "xpath", "(", "'//current-time/date-time'", ")", "[", "0", "]", ".", "text", "except", "IndexError", ":", "current_time", "=", "'Unknown'", "try", ":", "uptime", "=", "resp", ".", "xpath", "(", "'//uptime-information/up-time'", ")", "[", "0", "]", ".", "text", "except", "IndexError", ":", "uptime", "=", "'Unknown'", "# get serial number from 'show chassis hardware'", "show_hardware", "=", "self", ".", "_session", ".", "get_chassis_inventory", "(", "format", "=", "'xml'", ")", "# If we're hitting an EX, grab each Routing Engine Serial number", "# to get all RE SNs in a VC", "try", ":", "chassis_module", "=", "show_hardware", ".", "xpath", "(", "'//chassis-inventory/chassis/chassis-module/description'", ")", "[", "0", "]", ".", "text", "except", "IndexError", ":", "chassis_module", "=", "'Unknown'", "if", "(", "'EX'", "or", "'ex'", "or", "'Ex'", ")", "in", "chassis_module", ":", "serial_num", "=", "''", "for", "eng", "in", "show_hardware", ".", "xpath", "(", "'//chassis-inventory/chassis/chassis-module'", ")", ":", "if", "'Routing Engine'", "in", "eng", ".", "xpath", "(", "'name'", ")", "[", "0", "]", ".", "text", ":", "serial_num", "+=", "(", "eng", ".", "xpath", "(", "'name'", ")", "[", "0", "]", ".", "text", "+", "' Serial #: '", "+", "eng", ".", "xpath", "(", "'serial-number'", ")", "[", "0", "]", ".", "text", ")", "else", ":", "# Any other device type, just grab chassis SN", "try", ":", "serial_num", "=", "(", "'Chassis Serial Number: '", "+", "show_hardware", ".", "xpath", "(", "'//chassis-inventory/chassis/serial-number'", ")", "[", "0", "]", ".", "text", ")", "except", "IndexError", ":", "serial_num", "=", "'Chassis Serial Number: '", "+", "'Unknown (virtual machine?)'", "return", "(", "'Hostname: %s\\nModel: %s\\nJunos Version: %s\\n%s\\nCurrent Time:'", "' %s\\nUptime: %s\\n'", "%", "(", "hostname", ",", "model", ",", "version", ",", "serial_num", ",", "current_time", ",", "uptime", ")", ")" ]
Pull basic device information. Purpose: This function grabs the hostname, model, running version, and | serial number of the device. @returns: The output that should be shown to the user. @rtype: str
[ "Pull", "basic", "device", "information", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L488-L588
train
1,125
NetworkAutomation/jaide
jaide/core.py
Jaide.diff_config
def diff_config(self, second_host, mode='stanza'): """ Generate configuration differences with a second device. Purpose: Open a second ncclient.manager.Manager with second_host, and | and pull the configuration from it. We then use difflib to | get the delta between the two, and yield the results. @param second_host: the IP or hostname of the second device to | compare against. @type second_host: str @param mode: string to signify 'set' mode or 'stanza' mode. @type mode: str @returns: iterable of strings @rtype: str """ second_conn = manager.connect( host=second_host, port=self.port, username=self.username, password=self.password, timeout=self.connect_timeout, device_params={'name': 'junos'}, hostkey_verify=False ) command = 'show configuration' if mode == 'set': command += ' | display set' # get the raw xml config config1 = self._session.command(command, format='text') # for each /configuration-output snippet, turn it to text and join them config1 = ''.join([snippet.text.lstrip('\n') for snippet in config1.xpath('//configuration-output')]) config2 = second_conn.command(command, format='text') config2 = ''.join([snippet.text.lstrip('\n') for snippet in config2.xpath('//configuration-output')]) return difflib.unified_diff(config1.splitlines(), config2.splitlines(), self.host, second_host)
python
def diff_config(self, second_host, mode='stanza'): """ Generate configuration differences with a second device. Purpose: Open a second ncclient.manager.Manager with second_host, and | and pull the configuration from it. We then use difflib to | get the delta between the two, and yield the results. @param second_host: the IP or hostname of the second device to | compare against. @type second_host: str @param mode: string to signify 'set' mode or 'stanza' mode. @type mode: str @returns: iterable of strings @rtype: str """ second_conn = manager.connect( host=second_host, port=self.port, username=self.username, password=self.password, timeout=self.connect_timeout, device_params={'name': 'junos'}, hostkey_verify=False ) command = 'show configuration' if mode == 'set': command += ' | display set' # get the raw xml config config1 = self._session.command(command, format='text') # for each /configuration-output snippet, turn it to text and join them config1 = ''.join([snippet.text.lstrip('\n') for snippet in config1.xpath('//configuration-output')]) config2 = second_conn.command(command, format='text') config2 = ''.join([snippet.text.lstrip('\n') for snippet in config2.xpath('//configuration-output')]) return difflib.unified_diff(config1.splitlines(), config2.splitlines(), self.host, second_host)
[ "def", "diff_config", "(", "self", ",", "second_host", ",", "mode", "=", "'stanza'", ")", ":", "second_conn", "=", "manager", ".", "connect", "(", "host", "=", "second_host", ",", "port", "=", "self", ".", "port", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "timeout", "=", "self", ".", "connect_timeout", ",", "device_params", "=", "{", "'name'", ":", "'junos'", "}", ",", "hostkey_verify", "=", "False", ")", "command", "=", "'show configuration'", "if", "mode", "==", "'set'", ":", "command", "+=", "' | display set'", "# get the raw xml config", "config1", "=", "self", ".", "_session", ".", "command", "(", "command", ",", "format", "=", "'text'", ")", "# for each /configuration-output snippet, turn it to text and join them", "config1", "=", "''", ".", "join", "(", "[", "snippet", ".", "text", ".", "lstrip", "(", "'\\n'", ")", "for", "snippet", "in", "config1", ".", "xpath", "(", "'//configuration-output'", ")", "]", ")", "config2", "=", "second_conn", ".", "command", "(", "command", ",", "format", "=", "'text'", ")", "config2", "=", "''", ".", "join", "(", "[", "snippet", ".", "text", ".", "lstrip", "(", "'\\n'", ")", "for", "snippet", "in", "config2", ".", "xpath", "(", "'//configuration-output'", ")", "]", ")", "return", "difflib", ".", "unified_diff", "(", "config1", ".", "splitlines", "(", ")", ",", "config2", ".", "splitlines", "(", ")", ",", "self", ".", "host", ",", "second_host", ")" ]
Generate configuration differences with a second device. Purpose: Open a second ncclient.manager.Manager with second_host, and | and pull the configuration from it. We then use difflib to | get the delta between the two, and yield the results. @param second_host: the IP or hostname of the second device to | compare against. @type second_host: str @param mode: string to signify 'set' mode or 'stanza' mode. @type mode: str @returns: iterable of strings @rtype: str
[ "Generate", "configuration", "differences", "with", "a", "second", "device", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L592-L633
train
1,126
NetworkAutomation/jaide
jaide/core.py
Jaide._error_parse
def _error_parse(self, interface, face): """ Parse the extensive xml output of an interface and yield errors. Purpose: Takes the xml output of 'show interfaces extensive' for a | given interface and yields the error types that have a | significant number of errors. @param interface: The xml output of the 'sh int ext' command for | the desired interface. @type interface: lxml.etree._Element object @param face: The direction of the errors we're wanting. Either 'input' | or 'output' is accepted. @type face: str @returns: Yields each error that has a significant number @rtype: iterable of strings. """ try: error_list = interface.xpath(face + '-error-list')[0].getchildren() except IndexError: # no error list on this interface pass else: for x in range(len(error_list)): if error_list[x].tag == "carrier-transitions": if int(error_list[x].text.strip()) > 50: yield " has greater than 50 flaps." elif int(error_list[x].text.strip()) > 0: yield " has %s of %s." % (error_list[x].text.strip(), error_list[x].tag.strip())
python
def _error_parse(self, interface, face): """ Parse the extensive xml output of an interface and yield errors. Purpose: Takes the xml output of 'show interfaces extensive' for a | given interface and yields the error types that have a | significant number of errors. @param interface: The xml output of the 'sh int ext' command for | the desired interface. @type interface: lxml.etree._Element object @param face: The direction of the errors we're wanting. Either 'input' | or 'output' is accepted. @type face: str @returns: Yields each error that has a significant number @rtype: iterable of strings. """ try: error_list = interface.xpath(face + '-error-list')[0].getchildren() except IndexError: # no error list on this interface pass else: for x in range(len(error_list)): if error_list[x].tag == "carrier-transitions": if int(error_list[x].text.strip()) > 50: yield " has greater than 50 flaps." elif int(error_list[x].text.strip()) > 0: yield " has %s of %s." % (error_list[x].text.strip(), error_list[x].tag.strip())
[ "def", "_error_parse", "(", "self", ",", "interface", ",", "face", ")", ":", "try", ":", "error_list", "=", "interface", ".", "xpath", "(", "face", "+", "'-error-list'", ")", "[", "0", "]", ".", "getchildren", "(", ")", "except", "IndexError", ":", "# no error list on this interface", "pass", "else", ":", "for", "x", "in", "range", "(", "len", "(", "error_list", ")", ")", ":", "if", "error_list", "[", "x", "]", ".", "tag", "==", "\"carrier-transitions\"", ":", "if", "int", "(", "error_list", "[", "x", "]", ".", "text", ".", "strip", "(", ")", ")", ">", "50", ":", "yield", "\" has greater than 50 flaps.\"", "elif", "int", "(", "error_list", "[", "x", "]", ".", "text", ".", "strip", "(", ")", ")", ">", "0", ":", "yield", "\" has %s of %s.\"", "%", "(", "error_list", "[", "x", "]", ".", "text", ".", "strip", "(", ")", ",", "error_list", "[", "x", "]", ".", "tag", ".", "strip", "(", ")", ")" ]
Parse the extensive xml output of an interface and yield errors. Purpose: Takes the xml output of 'show interfaces extensive' for a | given interface and yields the error types that have a | significant number of errors. @param interface: The xml output of the 'sh int ext' command for | the desired interface. @type interface: lxml.etree._Element object @param face: The direction of the errors we're wanting. Either 'input' | or 'output' is accepted. @type face: str @returns: Yields each error that has a significant number @rtype: iterable of strings.
[ "Parse", "the", "extensive", "xml", "output", "of", "an", "interface", "and", "yield", "errors", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L657-L685
train
1,127
NetworkAutomation/jaide
jaide/core.py
Jaide.health_check
def health_check(self): """ Pull health and alarm information from the device. Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5 | processes, and states if the primary/backup partitions are on | different versions. @returns: The output that should be shown to the user. @rtype: str """ output = 'Chassis Alarms:\n\t' # Grab chassis alarms, system alarms, show chassis routing-engine, # 'show system processes extensive', and also xpath to the # relevant nodes on each. chassis_alarms = self._session.command("show chassis alarms") chassis_alarms = chassis_alarms.xpath('//alarm-detail') system_alarms = self._session.command("show system alarms") system_alarms = system_alarms.xpath('//alarm-detail') chass = self._session.command(command="show chassis routing-engine", format='text').xpath('//output')[0].text proc = self._session.command("show system processes extensive") proc = proc.xpath('output')[0].text.split('\n') if chassis_alarms == []: # Chassis Alarms output += 'No chassis alarms active.\n' else: for i in chassis_alarms: output += (i.xpath('alarm-class')[0].text.strip() + ' Alarm \t' '\t' + i.xpath('alarm-time')[0].text.strip() + '\n\t' + i.xpath('alarm-description')[0].text.strip() + '\n') output += '\nSystem Alarms: \n\t' if system_alarms == []: # System Alarms output += 'No system alarms active.\n' else: for i in system_alarms: output += (i.xpath('alarm-class')[0].text.strip() + ' Alarm ' '\t\t' + i.xpath('alarm-time')[0].text.strip() + '\n\t' + i.xpath('alarm-description')[0].text.strip() + '\n') # add the output of the show chassis routing-engine to the command. output += '\n' + chass # Grabs the top 5 processes and the header line. output += ('\n\nTop 5 busiest processes (high mgd values likely from ' 'script execution):\n') for line_number in range(8, 14): output += proc[line_number] + '\n' return output
python
def health_check(self): """ Pull health and alarm information from the device. Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5 | processes, and states if the primary/backup partitions are on | different versions. @returns: The output that should be shown to the user. @rtype: str """ output = 'Chassis Alarms:\n\t' # Grab chassis alarms, system alarms, show chassis routing-engine, # 'show system processes extensive', and also xpath to the # relevant nodes on each. chassis_alarms = self._session.command("show chassis alarms") chassis_alarms = chassis_alarms.xpath('//alarm-detail') system_alarms = self._session.command("show system alarms") system_alarms = system_alarms.xpath('//alarm-detail') chass = self._session.command(command="show chassis routing-engine", format='text').xpath('//output')[0].text proc = self._session.command("show system processes extensive") proc = proc.xpath('output')[0].text.split('\n') if chassis_alarms == []: # Chassis Alarms output += 'No chassis alarms active.\n' else: for i in chassis_alarms: output += (i.xpath('alarm-class')[0].text.strip() + ' Alarm \t' '\t' + i.xpath('alarm-time')[0].text.strip() + '\n\t' + i.xpath('alarm-description')[0].text.strip() + '\n') output += '\nSystem Alarms: \n\t' if system_alarms == []: # System Alarms output += 'No system alarms active.\n' else: for i in system_alarms: output += (i.xpath('alarm-class')[0].text.strip() + ' Alarm ' '\t\t' + i.xpath('alarm-time')[0].text.strip() + '\n\t' + i.xpath('alarm-description')[0].text.strip() + '\n') # add the output of the show chassis routing-engine to the command. output += '\n' + chass # Grabs the top 5 processes and the header line. output += ('\n\nTop 5 busiest processes (high mgd values likely from ' 'script execution):\n') for line_number in range(8, 14): output += proc[line_number] + '\n' return output
[ "def", "health_check", "(", "self", ")", ":", "output", "=", "'Chassis Alarms:\\n\\t'", "# Grab chassis alarms, system alarms, show chassis routing-engine,", "# 'show system processes extensive', and also xpath to the", "# relevant nodes on each.", "chassis_alarms", "=", "self", ".", "_session", ".", "command", "(", "\"show chassis alarms\"", ")", "chassis_alarms", "=", "chassis_alarms", ".", "xpath", "(", "'//alarm-detail'", ")", "system_alarms", "=", "self", ".", "_session", ".", "command", "(", "\"show system alarms\"", ")", "system_alarms", "=", "system_alarms", ".", "xpath", "(", "'//alarm-detail'", ")", "chass", "=", "self", ".", "_session", ".", "command", "(", "command", "=", "\"show chassis routing-engine\"", ",", "format", "=", "'text'", ")", ".", "xpath", "(", "'//output'", ")", "[", "0", "]", ".", "text", "proc", "=", "self", ".", "_session", ".", "command", "(", "\"show system processes extensive\"", ")", "proc", "=", "proc", ".", "xpath", "(", "'output'", ")", "[", "0", "]", ".", "text", ".", "split", "(", "'\\n'", ")", "if", "chassis_alarms", "==", "[", "]", ":", "# Chassis Alarms", "output", "+=", "'No chassis alarms active.\\n'", "else", ":", "for", "i", "in", "chassis_alarms", ":", "output", "+=", "(", "i", ".", "xpath", "(", "'alarm-class'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "' Alarm \\t'", "'\\t'", "+", "i", ".", "xpath", "(", "'alarm-time'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "'\\n\\t'", "+", "i", ".", "xpath", "(", "'alarm-description'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", ")", "output", "+=", "'\\nSystem Alarms: \\n\\t'", "if", "system_alarms", "==", "[", "]", ":", "# System Alarms", "output", "+=", "'No system alarms active.\\n'", "else", ":", "for", "i", "in", "system_alarms", ":", "output", "+=", "(", "i", ".", "xpath", "(", "'alarm-class'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "' Alarm '", "'\\t\\t'", "+", "i", ".", "xpath", "(", "'alarm-time'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "'\\n\\t'", "+", "i", ".", "xpath", "(", "'alarm-description'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "'\\n'", ")", "# add the output of the show chassis routing-engine to the command.", "output", "+=", "'\\n'", "+", "chass", "# Grabs the top 5 processes and the header line.", "output", "+=", "(", "'\\n\\nTop 5 busiest processes (high mgd values likely from '", "'script execution):\\n'", ")", "for", "line_number", "in", "range", "(", "8", ",", "14", ")", ":", "output", "+=", "proc", "[", "line_number", "]", "+", "'\\n'", "return", "output" ]
Pull health and alarm information from the device. Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5 | processes, and states if the primary/backup partitions are on | different versions. @returns: The output that should be shown to the user. @rtype: str
[ "Pull", "health", "and", "alarm", "information", "from", "the", "device", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L688-L734
train
1,128
NetworkAutomation/jaide
jaide/core.py
Jaide.interface_errors
def interface_errors(self): """ Parse 'show interfaces extensive' and return interfaces with errors. Purpose: This function is called for the -e flag. It will let the user | know if there are any interfaces with errors, and what those | interfaces are. @returns: The output that should be shown to the user. @rtype: str """ output = [] # used to store the list of interfaces with errors. # get a string of each physical and logical interface element dev_response = self._session.command('sh interfaces extensive') ints = dev_response.xpath('//physical-interface') ints += dev_response.xpath('//logical-interface') for i in ints: # Grab the interface name for user output. int_name = i.xpath('name')[0].text.strip() # Only check certain interface types. if (('ge' or 'fe' or 'ae' or 'xe' or 'so' or 'et' or 'vlan' or 'lo0' or 'irb') in int_name): try: status = (i.xpath('admin-status')[0].text.strip() + '/' + i.xpath('oper-status')[0].text.strip()) except IndexError: pass else: for error in self._error_parse(i, "input"): output.append("%s (%s)%s" % (int_name, status, error)) for error in self._error_parse(i, "output"): output.append("%s (%s)%s" % (int_name, status, error)) if output == []: output.append('No interface errors were detected on this device.') return '\n'.join(output) + '\n'
python
def interface_errors(self): """ Parse 'show interfaces extensive' and return interfaces with errors. Purpose: This function is called for the -e flag. It will let the user | know if there are any interfaces with errors, and what those | interfaces are. @returns: The output that should be shown to the user. @rtype: str """ output = [] # used to store the list of interfaces with errors. # get a string of each physical and logical interface element dev_response = self._session.command('sh interfaces extensive') ints = dev_response.xpath('//physical-interface') ints += dev_response.xpath('//logical-interface') for i in ints: # Grab the interface name for user output. int_name = i.xpath('name')[0].text.strip() # Only check certain interface types. if (('ge' or 'fe' or 'ae' or 'xe' or 'so' or 'et' or 'vlan' or 'lo0' or 'irb') in int_name): try: status = (i.xpath('admin-status')[0].text.strip() + '/' + i.xpath('oper-status')[0].text.strip()) except IndexError: pass else: for error in self._error_parse(i, "input"): output.append("%s (%s)%s" % (int_name, status, error)) for error in self._error_parse(i, "output"): output.append("%s (%s)%s" % (int_name, status, error)) if output == []: output.append('No interface errors were detected on this device.') return '\n'.join(output) + '\n'
[ "def", "interface_errors", "(", "self", ")", ":", "output", "=", "[", "]", "# used to store the list of interfaces with errors.", "# get a string of each physical and logical interface element", "dev_response", "=", "self", ".", "_session", ".", "command", "(", "'sh interfaces extensive'", ")", "ints", "=", "dev_response", ".", "xpath", "(", "'//physical-interface'", ")", "ints", "+=", "dev_response", ".", "xpath", "(", "'//logical-interface'", ")", "for", "i", "in", "ints", ":", "# Grab the interface name for user output.", "int_name", "=", "i", ".", "xpath", "(", "'name'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "# Only check certain interface types.", "if", "(", "(", "'ge'", "or", "'fe'", "or", "'ae'", "or", "'xe'", "or", "'so'", "or", "'et'", "or", "'vlan'", "or", "'lo0'", "or", "'irb'", ")", "in", "int_name", ")", ":", "try", ":", "status", "=", "(", "i", ".", "xpath", "(", "'admin-status'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "+", "'/'", "+", "i", ".", "xpath", "(", "'oper-status'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", ")", "except", "IndexError", ":", "pass", "else", ":", "for", "error", "in", "self", ".", "_error_parse", "(", "i", ",", "\"input\"", ")", ":", "output", ".", "append", "(", "\"%s (%s)%s\"", "%", "(", "int_name", ",", "status", ",", "error", ")", ")", "for", "error", "in", "self", ".", "_error_parse", "(", "i", ",", "\"output\"", ")", ":", "output", ".", "append", "(", "\"%s (%s)%s\"", "%", "(", "int_name", ",", "status", ",", "error", ")", ")", "if", "output", "==", "[", "]", ":", "output", ".", "append", "(", "'No interface errors were detected on this device.'", ")", "return", "'\\n'", ".", "join", "(", "output", ")", "+", "'\\n'" ]
Parse 'show interfaces extensive' and return interfaces with errors. Purpose: This function is called for the -e flag. It will let the user | know if there are any interfaces with errors, and what those | interfaces are. @returns: The output that should be shown to the user. @rtype: str
[ "Parse", "show", "interfaces", "extensive", "and", "return", "interfaces", "with", "errors", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L737-L772
train
1,129
NetworkAutomation/jaide
jaide/core.py
Jaide.lock
def lock(self): """ Lock the candidate config. Requires ncclient.manager.Manager. """ if isinstance(self._session, manager.Manager): self._session.lock()
python
def lock(self): """ Lock the candidate config. Requires ncclient.manager.Manager. """ if isinstance(self._session, manager.Manager): self._session.lock()
[ "def", "lock", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_session", ",", "manager", ".", "Manager", ")", ":", "self", ".", "_session", ".", "lock", "(", ")" ]
Lock the candidate config. Requires ncclient.manager.Manager.
[ "Lock", "the", "candidate", "config", ".", "Requires", "ncclient", ".", "manager", ".", "Manager", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L774-L777
train
1,130
NetworkAutomation/jaide
jaide/core.py
Jaide.op_cmd
def op_cmd(self, command, req_format='text', xpath_expr=""): """ Execute an operational mode command. Purpose: Used to send an operational mode command to the connected | device. This requires and uses a paramiko.SSHClient() as | the handler so that we can easily pass and allow all pipe | commands to be used. | | We indiscriminately attach ' | no-more' on the end of | every command so the device doesn't hold output. The | req_format parameter can be set to 'xml' to force raw | xml output in the reply. @param command: The single command that to retrieve output from the | device. Any pipes will be taken into account. @type command: str @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml'. **NOTE**: 'xml' | will still return a string, not a libxml ElementTree @type req_format: str @returns: The reply from the device. @rtype: str """ if not command: raise InvalidCommandError("Parameter 'command' cannot be empty") if req_format.lower() == 'xml' or xpath_expr: command = command.strip() + ' | display xml' command = command.strip() + ' | no-more\n' out = '' # when logging in as root, we use _shell to get the response. if self.username == 'root': self._shell.send(command) time.sleep(3) while self._shell.recv_ready(): out += self._shell.recv(999999) time.sleep(.75) # take off the command being sent and the prompt at the end. out = '\n'.join(out.split('\n')[1:-2]) # not logging in as root, and can grab the output as normal. else: stdin, stdout, stderr = self._session.exec_command(command=command, timeout=float(self.session_timeout)) stdin.close() # read normal output while not stdout.channel.exit_status_ready(): out += stdout.read() stdout.close() # read errors while not stderr.channel.exit_status_ready(): out += stderr.read() stderr.close() return out if not xpath_expr else xpath(out, xpath_expr)
python
def op_cmd(self, command, req_format='text', xpath_expr=""): """ Execute an operational mode command. Purpose: Used to send an operational mode command to the connected | device. This requires and uses a paramiko.SSHClient() as | the handler so that we can easily pass and allow all pipe | commands to be used. | | We indiscriminately attach ' | no-more' on the end of | every command so the device doesn't hold output. The | req_format parameter can be set to 'xml' to force raw | xml output in the reply. @param command: The single command that to retrieve output from the | device. Any pipes will be taken into account. @type command: str @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml'. **NOTE**: 'xml' | will still return a string, not a libxml ElementTree @type req_format: str @returns: The reply from the device. @rtype: str """ if not command: raise InvalidCommandError("Parameter 'command' cannot be empty") if req_format.lower() == 'xml' or xpath_expr: command = command.strip() + ' | display xml' command = command.strip() + ' | no-more\n' out = '' # when logging in as root, we use _shell to get the response. if self.username == 'root': self._shell.send(command) time.sleep(3) while self._shell.recv_ready(): out += self._shell.recv(999999) time.sleep(.75) # take off the command being sent and the prompt at the end. out = '\n'.join(out.split('\n')[1:-2]) # not logging in as root, and can grab the output as normal. else: stdin, stdout, stderr = self._session.exec_command(command=command, timeout=float(self.session_timeout)) stdin.close() # read normal output while not stdout.channel.exit_status_ready(): out += stdout.read() stdout.close() # read errors while not stderr.channel.exit_status_ready(): out += stderr.read() stderr.close() return out if not xpath_expr else xpath(out, xpath_expr)
[ "def", "op_cmd", "(", "self", ",", "command", ",", "req_format", "=", "'text'", ",", "xpath_expr", "=", "\"\"", ")", ":", "if", "not", "command", ":", "raise", "InvalidCommandError", "(", "\"Parameter 'command' cannot be empty\"", ")", "if", "req_format", ".", "lower", "(", ")", "==", "'xml'", "or", "xpath_expr", ":", "command", "=", "command", ".", "strip", "(", ")", "+", "' | display xml'", "command", "=", "command", ".", "strip", "(", ")", "+", "' | no-more\\n'", "out", "=", "''", "# when logging in as root, we use _shell to get the response.", "if", "self", ".", "username", "==", "'root'", ":", "self", ".", "_shell", ".", "send", "(", "command", ")", "time", ".", "sleep", "(", "3", ")", "while", "self", ".", "_shell", ".", "recv_ready", "(", ")", ":", "out", "+=", "self", ".", "_shell", ".", "recv", "(", "999999", ")", "time", ".", "sleep", "(", ".75", ")", "# take off the command being sent and the prompt at the end.", "out", "=", "'\\n'", ".", "join", "(", "out", ".", "split", "(", "'\\n'", ")", "[", "1", ":", "-", "2", "]", ")", "# not logging in as root, and can grab the output as normal.", "else", ":", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "_session", ".", "exec_command", "(", "command", "=", "command", ",", "timeout", "=", "float", "(", "self", ".", "session_timeout", ")", ")", "stdin", ".", "close", "(", ")", "# read normal output", "while", "not", "stdout", ".", "channel", ".", "exit_status_ready", "(", ")", ":", "out", "+=", "stdout", ".", "read", "(", ")", "stdout", ".", "close", "(", ")", "# read errors", "while", "not", "stderr", ".", "channel", ".", "exit_status_ready", "(", ")", ":", "out", "+=", "stderr", ".", "read", "(", ")", "stderr", ".", "close", "(", ")", "return", "out", "if", "not", "xpath_expr", "else", "xpath", "(", "out", ",", "xpath_expr", ")" ]
Execute an operational mode command. Purpose: Used to send an operational mode command to the connected | device. This requires and uses a paramiko.SSHClient() as | the handler so that we can easily pass and allow all pipe | commands to be used. | | We indiscriminately attach ' | no-more' on the end of | every command so the device doesn't hold output. The | req_format parameter can be set to 'xml' to force raw | xml output in the reply. @param command: The single command that to retrieve output from the | device. Any pipes will be taken into account. @type command: str @param req_format: The desired format of the response, defaults to | 'text', but also accepts 'xml'. **NOTE**: 'xml' | will still return a string, not a libxml ElementTree @type req_format: str @returns: The reply from the device. @rtype: str
[ "Execute", "an", "operational", "mode", "command", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L780-L832
train
1,131
NetworkAutomation/jaide
jaide/core.py
Jaide.unlock
def unlock(self): """ Unlock the candidate config. Purpose: Unlocks the candidate configuration, so that other people can | edit the device. Requires the _session private variable to be | a type of a ncclient.manager.Manager. """ if isinstance(self._session, manager.Manager): self._session.unlock()
python
def unlock(self): """ Unlock the candidate config. Purpose: Unlocks the candidate configuration, so that other people can | edit the device. Requires the _session private variable to be | a type of a ncclient.manager.Manager. """ if isinstance(self._session, manager.Manager): self._session.unlock()
[ "def", "unlock", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_session", ",", "manager", ".", "Manager", ")", ":", "self", ".", "_session", ".", "unlock", "(", ")" ]
Unlock the candidate config. Purpose: Unlocks the candidate configuration, so that other people can | edit the device. Requires the _session private variable to be | a type of a ncclient.manager.Manager.
[ "Unlock", "the", "candidate", "config", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L942-L950
train
1,132
Fluxx/exam
exam/helpers.py
intercept
def intercept(obj, methodname, wrapper): """ Wraps an existing method on an object with the provided generator, which will be "sent" the value when it yields control. :: >>> def ensure_primary_key_is_set(): ... assert model.pk is None ... saved = yield ... aasert model is saved ... assert model.pk is not None ... >>> intercept(model, 'save', ensure_primary_key_is_set) >>> model.save() :param obj: the object that has the method to be wrapped :type obj: :class:`object` :param methodname: the name of the method that will be wrapped :type methodname: :class:`str` :param wrapper: the wrapper :type wrapper: generator callable """ original = getattr(obj, methodname) def replacement(*args, **kwargs): wrapfn = wrapper(*args, **kwargs) wrapfn.send(None) result = original(*args, **kwargs) try: wrapfn.send(result) except StopIteration: return result else: raise AssertionError('Generator did not stop') def unwrap(): """ Restores the method to it's original (unwrapped) state. """ setattr(obj, methodname, original) replacement.unwrap = unwrap setattr(obj, methodname, replacement)
python
def intercept(obj, methodname, wrapper): """ Wraps an existing method on an object with the provided generator, which will be "sent" the value when it yields control. :: >>> def ensure_primary_key_is_set(): ... assert model.pk is None ... saved = yield ... aasert model is saved ... assert model.pk is not None ... >>> intercept(model, 'save', ensure_primary_key_is_set) >>> model.save() :param obj: the object that has the method to be wrapped :type obj: :class:`object` :param methodname: the name of the method that will be wrapped :type methodname: :class:`str` :param wrapper: the wrapper :type wrapper: generator callable """ original = getattr(obj, methodname) def replacement(*args, **kwargs): wrapfn = wrapper(*args, **kwargs) wrapfn.send(None) result = original(*args, **kwargs) try: wrapfn.send(result) except StopIteration: return result else: raise AssertionError('Generator did not stop') def unwrap(): """ Restores the method to it's original (unwrapped) state. """ setattr(obj, methodname, original) replacement.unwrap = unwrap setattr(obj, methodname, replacement)
[ "def", "intercept", "(", "obj", ",", "methodname", ",", "wrapper", ")", ":", "original", "=", "getattr", "(", "obj", ",", "methodname", ")", "def", "replacement", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wrapfn", "=", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapfn", ".", "send", "(", "None", ")", "result", "=", "original", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "wrapfn", ".", "send", "(", "result", ")", "except", "StopIteration", ":", "return", "result", "else", ":", "raise", "AssertionError", "(", "'Generator did not stop'", ")", "def", "unwrap", "(", ")", ":", "\"\"\"\n Restores the method to it's original (unwrapped) state.\n \"\"\"", "setattr", "(", "obj", ",", "methodname", ",", "original", ")", "replacement", ".", "unwrap", "=", "unwrap", "setattr", "(", "obj", ",", "methodname", ",", "replacement", ")" ]
Wraps an existing method on an object with the provided generator, which will be "sent" the value when it yields control. :: >>> def ensure_primary_key_is_set(): ... assert model.pk is None ... saved = yield ... aasert model is saved ... assert model.pk is not None ... >>> intercept(model, 'save', ensure_primary_key_is_set) >>> model.save() :param obj: the object that has the method to be wrapped :type obj: :class:`object` :param methodname: the name of the method that will be wrapped :type methodname: :class:`str` :param wrapper: the wrapper :type wrapper: generator callable
[ "Wraps", "an", "existing", "method", "on", "an", "object", "with", "the", "provided", "generator", "which", "will", "be", "sent", "the", "value", "when", "it", "yields", "control", "." ]
27dc53a703349ec09433a6b989d6fc32ad523c0b
https://github.com/Fluxx/exam/blob/27dc53a703349ec09433a6b989d6fc32ad523c0b/exam/helpers.py#L28-L72
train
1,133
mcieslik-mctp/papy
src/numap/NuMap.py
_Weave.next
def next(self): """ Returns the next element or raises ``StopIteration`` if stopped. """ # need new iterable? if self.r == self.repeats: self.i = (self.i + 1) % self.lenght self.r = 0 self.r += 1 if self.stopping and self.i == 0 and self.r == 1: self.stopped = True if self.i == 0 and self.stopped: raise StopIteration else: iterator = self.iterators[self.i] return iterator.next()
python
def next(self): """ Returns the next element or raises ``StopIteration`` if stopped. """ # need new iterable? if self.r == self.repeats: self.i = (self.i + 1) % self.lenght self.r = 0 self.r += 1 if self.stopping and self.i == 0 and self.r == 1: self.stopped = True if self.i == 0 and self.stopped: raise StopIteration else: iterator = self.iterators[self.i] return iterator.next()
[ "def", "next", "(", "self", ")", ":", "# need new iterable?", "if", "self", ".", "r", "==", "self", ".", "repeats", ":", "self", ".", "i", "=", "(", "self", ".", "i", "+", "1", ")", "%", "self", ".", "lenght", "self", ".", "r", "=", "0", "self", ".", "r", "+=", "1", "if", "self", ".", "stopping", "and", "self", ".", "i", "==", "0", "and", "self", ".", "r", "==", "1", ":", "self", ".", "stopped", "=", "True", "if", "self", ".", "i", "==", "0", "and", "self", ".", "stopped", ":", "raise", "StopIteration", "else", ":", "iterator", "=", "self", ".", "iterators", "[", "self", ".", "i", "]", "return", "iterator", ".", "next", "(", ")" ]
Returns the next element or raises ``StopIteration`` if stopped.
[ "Returns", "the", "next", "element", "or", "raises", "StopIteration", "if", "stopped", "." ]
708e50827b5db46bbea081982cb74b9b0e464064
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/numap/NuMap.py#L880-L896
train
1,134
mcieslik-mctp/papy
src/numap/NuMap.py
_NuMapTask.next
def next(self): """ Returns a result if availble within "timeout" else raises a ``TimeoutError`` exception. See documentation for ``NuMap.next``. """ return self.iterator.next(task=self.task, timeout=self.timeout, block=self.block)
python
def next(self): """ Returns a result if availble within "timeout" else raises a ``TimeoutError`` exception. See documentation for ``NuMap.next``. """ return self.iterator.next(task=self.task, timeout=self.timeout, block=self.block)
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "iterator", ".", "next", "(", "task", "=", "self", ".", "task", ",", "timeout", "=", "self", ".", "timeout", ",", "block", "=", "self", ".", "block", ")" ]
Returns a result if availble within "timeout" else raises a ``TimeoutError`` exception. See documentation for ``NuMap.next``.
[ "Returns", "a", "result", "if", "availble", "within", "timeout", "else", "raises", "a", "TimeoutError", "exception", ".", "See", "documentation", "for", "NuMap", ".", "next", "." ]
708e50827b5db46bbea081982cb74b9b0e464064
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/numap/NuMap.py#L919-L925
train
1,135
mcieslik-mctp/papy
src/papy/util/script.py
write_template
def write_template(fn, lang="python"): """ Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language """ with open(fn, "wb") as fh: if lang == "python": fh.write(PY_TEMPLATE) elif lang == "bash": fh.write(SH_TEMPLATE)
python
def write_template(fn, lang="python"): """ Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language """ with open(fn, "wb") as fh: if lang == "python": fh.write(PY_TEMPLATE) elif lang == "bash": fh.write(SH_TEMPLATE)
[ "def", "write_template", "(", "fn", ",", "lang", "=", "\"python\"", ")", ":", "with", "open", "(", "fn", ",", "\"wb\"", ")", "as", "fh", ":", "if", "lang", "==", "\"python\"", ":", "fh", ".", "write", "(", "PY_TEMPLATE", ")", "elif", "lang", "==", "\"bash\"", ":", "fh", ".", "write", "(", "SH_TEMPLATE", ")" ]
Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language
[ "Write", "language", "-", "specific", "script", "template", "to", "file", "." ]
708e50827b5db46bbea081982cb74b9b0e464064
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/script.py#L94-L108
train
1,136
mcieslik-mctp/papy
src/papy/util/script.py
script
def script(inbox, cfg): """ Execute arbitrary scripts. Arguments: - cfg(``dict``) script configuartion dictionary """ script_name = cfg["id"] script_id = str(abs(hash((cfg["id"],) + tuple(inbox[0].values()))))[0:8] # LOG.log(mp.DEFAULT, "@papy;script %s:%s started" % (script_name, script_id)) # LOG.log(mp.SUBDEFAULT, "@papy;%s:%s received: %s" % (script_name, script_id, inbox)) args = {} args["params"] = dict(cfg["params"]) args["in"] = {} for in_port in cfg["in"]: for inin_ports in inbox: in_path = inin_ports.get(in_port, None) if (in_path is not None): # first matching input-output (including type) port is linked remaining ignored args["in"][in_port] = in_path break # check that all input ports are connected if len(args["in"]) < len(cfg["in"]): raise Exception("not all in_ports connected, got: %s" % (args["in"],)) # create output file for out_ports args["out"] = {} out = {} for i, (out_port, out_ext) in enumerate(cfg["out"]): if cfg["in"] == tuple(out_port_ for out_port_, _ in cfg["out"]): pfx = args["in"][cfg["in"][i]].split("/")[-1].split(".")[0] + "_" base = cfg["id"] else: pfx = args["in"][cfg["in"][0]].split("/")[-1].split(".")[0] + "_" base = cfg["id"] + "-" + out_port if out_ext: out_path = cfg["dir"] + "/" + pfx + base + "." + out_ext else: out_path = cfg["dir"] + "/" + pfx + base args["out"][out_port] = out_path out[out_port] = out_path # evaluate and check for errors ret = _eval_script(cfg["evaluator"], cfg["preamble"], cfg["dir"], cfg["executable"], cfg["script"], args) if ret[0] != 0: # LOG.error("@papy;%s:%s %s:%s:%s" % (script_name, script_id, ret[0], # ret[1].replace("\n", "<br>"), # ret[2].replace("\n", "<br>"))) raise Exception(ret[0], cfg["script"], ret[1], ret[2]) #LOG.log(mp.SUBDEFAULT, "@papy;%s:%s produced:%s" % (script_name, script_id, out)) #LOG.log(mp.DEFAULT, "@papy;script %s:%s finished" % (script_name, script_id)) return out
python
def script(inbox, cfg): """ Execute arbitrary scripts. Arguments: - cfg(``dict``) script configuartion dictionary """ script_name = cfg["id"] script_id = str(abs(hash((cfg["id"],) + tuple(inbox[0].values()))))[0:8] # LOG.log(mp.DEFAULT, "@papy;script %s:%s started" % (script_name, script_id)) # LOG.log(mp.SUBDEFAULT, "@papy;%s:%s received: %s" % (script_name, script_id, inbox)) args = {} args["params"] = dict(cfg["params"]) args["in"] = {} for in_port in cfg["in"]: for inin_ports in inbox: in_path = inin_ports.get(in_port, None) if (in_path is not None): # first matching input-output (including type) port is linked remaining ignored args["in"][in_port] = in_path break # check that all input ports are connected if len(args["in"]) < len(cfg["in"]): raise Exception("not all in_ports connected, got: %s" % (args["in"],)) # create output file for out_ports args["out"] = {} out = {} for i, (out_port, out_ext) in enumerate(cfg["out"]): if cfg["in"] == tuple(out_port_ for out_port_, _ in cfg["out"]): pfx = args["in"][cfg["in"][i]].split("/")[-1].split(".")[0] + "_" base = cfg["id"] else: pfx = args["in"][cfg["in"][0]].split("/")[-1].split(".")[0] + "_" base = cfg["id"] + "-" + out_port if out_ext: out_path = cfg["dir"] + "/" + pfx + base + "." + out_ext else: out_path = cfg["dir"] + "/" + pfx + base args["out"][out_port] = out_path out[out_port] = out_path # evaluate and check for errors ret = _eval_script(cfg["evaluator"], cfg["preamble"], cfg["dir"], cfg["executable"], cfg["script"], args) if ret[0] != 0: # LOG.error("@papy;%s:%s %s:%s:%s" % (script_name, script_id, ret[0], # ret[1].replace("\n", "<br>"), # ret[2].replace("\n", "<br>"))) raise Exception(ret[0], cfg["script"], ret[1], ret[2]) #LOG.log(mp.SUBDEFAULT, "@papy;%s:%s produced:%s" % (script_name, script_id, out)) #LOG.log(mp.DEFAULT, "@papy;script %s:%s finished" % (script_name, script_id)) return out
[ "def", "script", "(", "inbox", ",", "cfg", ")", ":", "script_name", "=", "cfg", "[", "\"id\"", "]", "script_id", "=", "str", "(", "abs", "(", "hash", "(", "(", "cfg", "[", "\"id\"", "]", ",", ")", "+", "tuple", "(", "inbox", "[", "0", "]", ".", "values", "(", ")", ")", ")", ")", ")", "[", "0", ":", "8", "]", "# LOG.log(mp.DEFAULT, \"@papy;script %s:%s started\" % (script_name, script_id))", "# LOG.log(mp.SUBDEFAULT, \"@papy;%s:%s received: %s\" % (script_name, script_id, inbox))", "args", "=", "{", "}", "args", "[", "\"params\"", "]", "=", "dict", "(", "cfg", "[", "\"params\"", "]", ")", "args", "[", "\"in\"", "]", "=", "{", "}", "for", "in_port", "in", "cfg", "[", "\"in\"", "]", ":", "for", "inin_ports", "in", "inbox", ":", "in_path", "=", "inin_ports", ".", "get", "(", "in_port", ",", "None", ")", "if", "(", "in_path", "is", "not", "None", ")", ":", "# first matching input-output (including type) port is linked remaining ignored", "args", "[", "\"in\"", "]", "[", "in_port", "]", "=", "in_path", "break", "# check that all input ports are connected", "if", "len", "(", "args", "[", "\"in\"", "]", ")", "<", "len", "(", "cfg", "[", "\"in\"", "]", ")", ":", "raise", "Exception", "(", "\"not all in_ports connected, got: %s\"", "%", "(", "args", "[", "\"in\"", "]", ",", ")", ")", "# create output file for out_ports", "args", "[", "\"out\"", "]", "=", "{", "}", "out", "=", "{", "}", "for", "i", ",", "(", "out_port", ",", "out_ext", ")", "in", "enumerate", "(", "cfg", "[", "\"out\"", "]", ")", ":", "if", "cfg", "[", "\"in\"", "]", "==", "tuple", "(", "out_port_", "for", "out_port_", ",", "_", "in", "cfg", "[", "\"out\"", "]", ")", ":", "pfx", "=", "args", "[", "\"in\"", "]", "[", "cfg", "[", "\"in\"", "]", "[", "i", "]", "]", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ".", "split", "(", "\".\"", ")", "[", "0", "]", "+", "\"_\"", "base", "=", "cfg", "[", "\"id\"", "]", "else", ":", "pfx", "=", "args", "[", "\"in\"", "]", "[", "cfg", "[", "\"in\"", "]", "[", "0", "]", "]", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ".", "split", "(", "\".\"", ")", "[", "0", "]", "+", "\"_\"", "base", "=", "cfg", "[", "\"id\"", "]", "+", "\"-\"", "+", "out_port", "if", "out_ext", ":", "out_path", "=", "cfg", "[", "\"dir\"", "]", "+", "\"/\"", "+", "pfx", "+", "base", "+", "\".\"", "+", "out_ext", "else", ":", "out_path", "=", "cfg", "[", "\"dir\"", "]", "+", "\"/\"", "+", "pfx", "+", "base", "args", "[", "\"out\"", "]", "[", "out_port", "]", "=", "out_path", "out", "[", "out_port", "]", "=", "out_path", "# evaluate and check for errors", "ret", "=", "_eval_script", "(", "cfg", "[", "\"evaluator\"", "]", ",", "cfg", "[", "\"preamble\"", "]", ",", "cfg", "[", "\"dir\"", "]", ",", "cfg", "[", "\"executable\"", "]", ",", "cfg", "[", "\"script\"", "]", ",", "args", ")", "if", "ret", "[", "0", "]", "!=", "0", ":", "# LOG.error(\"@papy;%s:%s %s:%s:%s\" % (script_name, script_id, ret[0], ", "# ret[1].replace(\"\\n\", \"<br>\"), ", "# ret[2].replace(\"\\n\", \"<br>\")))", "raise", "Exception", "(", "ret", "[", "0", "]", ",", "cfg", "[", "\"script\"", "]", ",", "ret", "[", "1", "]", ",", "ret", "[", "2", "]", ")", "#LOG.log(mp.SUBDEFAULT, \"@papy;%s:%s produced:%s\" % (script_name, script_id, out))", "#LOG.log(mp.DEFAULT, \"@papy;script %s:%s finished\" % (script_name, script_id))", "return", "out" ]
Execute arbitrary scripts. Arguments: - cfg(``dict``) script configuartion dictionary
[ "Execute", "arbitrary", "scripts", "." ]
708e50827b5db46bbea081982cb74b9b0e464064
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/script.py#L152-L203
train
1,137
qacafe/cdrouter.py
cdrouter/jobs.py
JobsService.edit
def edit(self, resource): """Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic', 'run_at')) json = self.service.encode(schema, resource) schema = JobSchema() resp = self.service.edit(self.base, resource.name, json) return self.service.decode(schema, resp)
python
def edit(self, resource): """Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic', 'run_at')) json = self.service.encode(schema, resource) schema = JobSchema() resp = self.service.edit(self.base, resource.name, json) return self.service.decode(schema, resp)
[ "def", "edit", "(", "self", ",", "resource", ")", ":", "schema", "=", "JobSchema", "(", "exclude", "=", "(", "'id'", ",", "'status'", ",", "'options'", ",", "'package_name'", ",", "'config_name'", ",", "'device_name'", ",", "'result_id'", ",", "'user_id'", ",", "'created'", ",", "'updated'", ",", "'automatic'", ",", "'run_at'", ")", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "resource", ")", "schema", "=", "JobSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "edit", "(", "self", ".", "base", ",", "resource", ".", "name", ",", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job
[ "Edit", "a", "job", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/jobs.py#L153-L165
train
1,138
qacafe/cdrouter.py
cdrouter/jobs.py
JobsService.launch
def launch(self, resource): """Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic')) json = self.service.encode(schema, resource) schema = JobSchema() resp = self.service.create(self.base, json) return self.service.decode(schema, resp)
python
def launch(self, resource): """Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic')) json = self.service.encode(schema, resource) schema = JobSchema() resp = self.service.create(self.base, json) return self.service.decode(schema, resp)
[ "def", "launch", "(", "self", ",", "resource", ")", ":", "schema", "=", "JobSchema", "(", "exclude", "=", "(", "'id'", ",", "'status'", ",", "'package_name'", ",", "'config_name'", ",", "'device_name'", ",", "'result_id'", ",", "'user_id'", ",", "'created'", ",", "'updated'", ",", "'automatic'", ")", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "resource", ")", "schema", "=", "JobSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "create", "(", "self", ".", "base", ",", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job
[ "Launch", "a", "new", "job", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/jobs.py#L167-L179
train
1,139
qacafe/cdrouter.py
cdrouter/jobs.py
JobsService.bulk_launch
def bulk_launch(self, jobs=None, filter=None, all=False): # pylint: disable=redefined-builtin """Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`. """ json = None if jobs is not None: schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic')) jobs_json = self.service.encode(schema, jobs, many=True) json = {self.RESOURCE: jobs_json} schema = JobSchema() resp = self.service.post(self.base, params={'bulk': 'launch', 'filter': filter, 'all': all}, json=json) return self.service.decode(schema, resp, many=True)
python
def bulk_launch(self, jobs=None, filter=None, all=False): # pylint: disable=redefined-builtin """Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`. """ json = None if jobs is not None: schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic')) jobs_json = self.service.encode(schema, jobs, many=True) json = {self.RESOURCE: jobs_json} schema = JobSchema() resp = self.service.post(self.base, params={'bulk': 'launch', 'filter': filter, 'all': all}, json=json) return self.service.decode(schema, resp, many=True)
[ "def", "bulk_launch", "(", "self", ",", "jobs", "=", "None", ",", "filter", "=", "None", ",", "all", "=", "False", ")", ":", "# pylint: disable=redefined-builtin", "json", "=", "None", "if", "jobs", "is", "not", "None", ":", "schema", "=", "JobSchema", "(", "exclude", "=", "(", "'id'", ",", "'status'", ",", "'package_name'", ",", "'config_name'", ",", "'device_name'", ",", "'result_id'", ",", "'user_id'", ",", "'created'", ",", "'updated'", ",", "'automatic'", ")", ")", "jobs_json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "jobs", ",", "many", "=", "True", ")", "json", "=", "{", "self", ".", "RESOURCE", ":", "jobs_json", "}", "schema", "=", "JobSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", ",", "params", "=", "{", "'bulk'", ":", "'launch'", ",", "'filter'", ":", "filter", ",", "'all'", ":", "all", "}", ",", "json", "=", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ",", "many", "=", "True", ")" ]
Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`.
[ "Bulk", "launch", "a", "set", "of", "jobs", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/jobs.py#L188-L204
train
1,140
qacafe/cdrouter.py
cdrouter/highlights.py
HighlightsService.get
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object """ schema = HighlightSchema() resp = self.service.get_id(self._base(id, seq), line) return self.service.decode(schema, resp)
python
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object """ schema = HighlightSchema() resp = self.service.get_id(self._base(id, seq), line) return self.service.decode(schema, resp)
[ "def", "get", "(", "self", ",", "id", ",", "seq", ",", "line", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "HighlightSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get_id", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ",", "line", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object
[ "Get", "a", "highlight", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L57-L67
train
1,141
qacafe/cdrouter.py
cdrouter/highlights.py
HighlightsService.create_or_edit
def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ schema = HighlightSchema(exclude=('id', 'seq')) json = self.service.encode(schema, resource) schema = HighlightSchema() resp = self.service.edit(self._base(id, seq), resource.line, json) return self.service.decode(schema, resp)
python
def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ schema = HighlightSchema(exclude=('id', 'seq')) json = self.service.encode(schema, resource) schema = HighlightSchema() resp = self.service.edit(self._base(id, seq), resource.line, json) return self.service.decode(schema, resp)
[ "def", "create_or_edit", "(", "self", ",", "id", ",", "seq", ",", "resource", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "HighlightSchema", "(", "exclude", "=", "(", "'id'", ",", "'seq'", ")", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "resource", ")", "schema", "=", "HighlightSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "edit", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ",", "resource", ".", "line", ",", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight
[ "Create", "or", "edit", "a", "highlight", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L69-L83
train
1,142
qacafe/cdrouter.py
cdrouter/highlights.py
HighlightsService.create
def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ return self.create_or_edit(id, seq, resource)
python
def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ return self.create_or_edit(id, seq, resource)
[ "def", "create", "(", "self", ",", "id", ",", "seq", ",", "resource", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "return", "self", ".", "create_or_edit", "(", "id", ",", "seq", ",", "resource", ")" ]
Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight
[ "Create", "a", "highlight", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L85-L94
train
1,143
qacafe/cdrouter.py
cdrouter/highlights.py
HighlightsService.edit
def edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ return self.create_or_edit(id, seq, resource)
python
def edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight """ return self.create_or_edit(id, seq, resource)
[ "def", "edit", "(", "self", ",", "id", ",", "seq", ",", "resource", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "return", "self", ".", "create_or_edit", "(", "id", ",", "seq", ",", "resource", ")" ]
Edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight
[ "Edit", "a", "highlight", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L96-L105
train
1,144
qacafe/cdrouter.py
cdrouter/highlights.py
HighlightsService.delete
def delete(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Delete a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. """ return self.service.delete_id(self._base(id, seq), line)
python
def delete(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Delete a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. """ return self.service.delete_id(self._base(id, seq), line)
[ "def", "delete", "(", "self", ",", "id", ",", "seq", ",", "line", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "return", "self", ".", "service", ".", "delete_id", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ",", "line", ")" ]
Delete a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int.
[ "Delete", "a", "highlight", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L107-L114
train
1,145
inveniosoftware/invenio-oauthclient
invenio_oauthclient/views/client.py
post_ext_init
def post_ext_init(state): """Setup blueprint.""" app = state.app app.config.setdefault( 'OAUTHCLIENT_SITENAME', app.config.get('THEME_SITENAME', 'Invenio')) app.config.setdefault( 'OAUTHCLIENT_BASE_TEMPLATE', app.config.get('BASE_TEMPLATE', 'invenio_oauthclient/base.html')) app.config.setdefault( 'OAUTHCLIENT_COVER_TEMPLATE', app.config.get('COVER_TEMPLATE', 'invenio_oauthclient/base_cover.html')) app.config.setdefault( 'OAUTHCLIENT_SETTINGS_TEMPLATE', app.config.get('SETTINGS_TEMPLATE', 'invenio_oauthclient/settings/base.html'))
python
def post_ext_init(state): """Setup blueprint.""" app = state.app app.config.setdefault( 'OAUTHCLIENT_SITENAME', app.config.get('THEME_SITENAME', 'Invenio')) app.config.setdefault( 'OAUTHCLIENT_BASE_TEMPLATE', app.config.get('BASE_TEMPLATE', 'invenio_oauthclient/base.html')) app.config.setdefault( 'OAUTHCLIENT_COVER_TEMPLATE', app.config.get('COVER_TEMPLATE', 'invenio_oauthclient/base_cover.html')) app.config.setdefault( 'OAUTHCLIENT_SETTINGS_TEMPLATE', app.config.get('SETTINGS_TEMPLATE', 'invenio_oauthclient/settings/base.html'))
[ "def", "post_ext_init", "(", "state", ")", ":", "app", "=", "state", ".", "app", "app", ".", "config", ".", "setdefault", "(", "'OAUTHCLIENT_SITENAME'", ",", "app", ".", "config", ".", "get", "(", "'THEME_SITENAME'", ",", "'Invenio'", ")", ")", "app", ".", "config", ".", "setdefault", "(", "'OAUTHCLIENT_BASE_TEMPLATE'", ",", "app", ".", "config", ".", "get", "(", "'BASE_TEMPLATE'", ",", "'invenio_oauthclient/base.html'", ")", ")", "app", ".", "config", ".", "setdefault", "(", "'OAUTHCLIENT_COVER_TEMPLATE'", ",", "app", ".", "config", ".", "get", "(", "'COVER_TEMPLATE'", ",", "'invenio_oauthclient/base_cover.html'", ")", ")", "app", ".", "config", ".", "setdefault", "(", "'OAUTHCLIENT_SETTINGS_TEMPLATE'", ",", "app", ".", "config", ".", "get", "(", "'SETTINGS_TEMPLATE'", ",", "'invenio_oauthclient/settings/base.html'", ")", ")" ]
Setup blueprint.
[ "Setup", "blueprint", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/client.py#L43-L61
train
1,146
inveniosoftware/invenio-oauthclient
invenio_oauthclient/views/client.py
login
def login(remote_app): """Send user to remote application for authentication.""" oauth = current_app.extensions['oauthlib.client'] if remote_app not in oauth.remote_apps: return abort(404) # Get redirect target in safe manner. next_param = get_safe_redirect_target(arg='next') # Redirect URI - must be registered in the remote service. callback_url = url_for( '.authorized', remote_app=remote_app, _external=True, ) # Create a JSON Web Token that expires after OAUTHCLIENT_STATE_EXPIRES # seconds. state_token = serializer.dumps({ 'app': remote_app, 'next': next_param, 'sid': _create_identifier(), }) return oauth.remote_apps[remote_app].authorize( callback=callback_url, state=state_token, )
python
def login(remote_app): """Send user to remote application for authentication.""" oauth = current_app.extensions['oauthlib.client'] if remote_app not in oauth.remote_apps: return abort(404) # Get redirect target in safe manner. next_param = get_safe_redirect_target(arg='next') # Redirect URI - must be registered in the remote service. callback_url = url_for( '.authorized', remote_app=remote_app, _external=True, ) # Create a JSON Web Token that expires after OAUTHCLIENT_STATE_EXPIRES # seconds. state_token = serializer.dumps({ 'app': remote_app, 'next': next_param, 'sid': _create_identifier(), }) return oauth.remote_apps[remote_app].authorize( callback=callback_url, state=state_token, )
[ "def", "login", "(", "remote_app", ")", ":", "oauth", "=", "current_app", ".", "extensions", "[", "'oauthlib.client'", "]", "if", "remote_app", "not", "in", "oauth", ".", "remote_apps", ":", "return", "abort", "(", "404", ")", "# Get redirect target in safe manner.", "next_param", "=", "get_safe_redirect_target", "(", "arg", "=", "'next'", ")", "# Redirect URI - must be registered in the remote service.", "callback_url", "=", "url_for", "(", "'.authorized'", ",", "remote_app", "=", "remote_app", ",", "_external", "=", "True", ",", ")", "# Create a JSON Web Token that expires after OAUTHCLIENT_STATE_EXPIRES", "# seconds.", "state_token", "=", "serializer", ".", "dumps", "(", "{", "'app'", ":", "remote_app", ",", "'next'", ":", "next_param", ",", "'sid'", ":", "_create_identifier", "(", ")", ",", "}", ")", "return", "oauth", ".", "remote_apps", "[", "remote_app", "]", ".", "authorize", "(", "callback", "=", "callback_url", ",", "state", "=", "state_token", ",", ")" ]
Send user to remote application for authentication.
[ "Send", "user", "to", "remote", "application", "for", "authentication", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/client.py#L65-L93
train
1,147
inveniosoftware/invenio-oauthclient
invenio_oauthclient/views/client.py
authorized
def authorized(remote_app=None): """Authorized handler callback.""" if remote_app not in current_oauthclient.handlers: return abort(404) state_token = request.args.get('state') # Verify state parameter try: assert state_token # Checks authenticity and integrity of state and decodes the value. state = serializer.loads(state_token) # Verify that state is for this session, app and that next parameter # have not been modified. assert state['sid'] == _create_identifier() assert state['app'] == remote_app # Store next URL set_session_next_url(remote_app, state['next']) except (AssertionError, BadData): if current_app.config.get('OAUTHCLIENT_STATE_ENABLED', True) or ( not(current_app.debug or current_app.testing)): abort(403) try: handler = current_oauthclient.handlers[remote_app]() except OAuthException as e: if e.type == 'invalid_response': abort(500) else: raise return handler
python
def authorized(remote_app=None): """Authorized handler callback.""" if remote_app not in current_oauthclient.handlers: return abort(404) state_token = request.args.get('state') # Verify state parameter try: assert state_token # Checks authenticity and integrity of state and decodes the value. state = serializer.loads(state_token) # Verify that state is for this session, app and that next parameter # have not been modified. assert state['sid'] == _create_identifier() assert state['app'] == remote_app # Store next URL set_session_next_url(remote_app, state['next']) except (AssertionError, BadData): if current_app.config.get('OAUTHCLIENT_STATE_ENABLED', True) or ( not(current_app.debug or current_app.testing)): abort(403) try: handler = current_oauthclient.handlers[remote_app]() except OAuthException as e: if e.type == 'invalid_response': abort(500) else: raise return handler
[ "def", "authorized", "(", "remote_app", "=", "None", ")", ":", "if", "remote_app", "not", "in", "current_oauthclient", ".", "handlers", ":", "return", "abort", "(", "404", ")", "state_token", "=", "request", ".", "args", ".", "get", "(", "'state'", ")", "# Verify state parameter", "try", ":", "assert", "state_token", "# Checks authenticity and integrity of state and decodes the value.", "state", "=", "serializer", ".", "loads", "(", "state_token", ")", "# Verify that state is for this session, app and that next parameter", "# have not been modified.", "assert", "state", "[", "'sid'", "]", "==", "_create_identifier", "(", ")", "assert", "state", "[", "'app'", "]", "==", "remote_app", "# Store next URL", "set_session_next_url", "(", "remote_app", ",", "state", "[", "'next'", "]", ")", "except", "(", "AssertionError", ",", "BadData", ")", ":", "if", "current_app", ".", "config", ".", "get", "(", "'OAUTHCLIENT_STATE_ENABLED'", ",", "True", ")", "or", "(", "not", "(", "current_app", ".", "debug", "or", "current_app", ".", "testing", ")", ")", ":", "abort", "(", "403", ")", "try", ":", "handler", "=", "current_oauthclient", ".", "handlers", "[", "remote_app", "]", "(", ")", "except", "OAuthException", "as", "e", ":", "if", "e", ".", "type", "==", "'invalid_response'", ":", "abort", "(", "500", ")", "else", ":", "raise", "return", "handler" ]
Authorized handler callback.
[ "Authorized", "handler", "callback", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/client.py#L97-L128
train
1,148
inveniosoftware/invenio-oauthclient
invenio_oauthclient/views/client.py
signup
def signup(remote_app): """Extra signup step.""" if remote_app not in current_oauthclient.signup_handlers: return abort(404) res = current_oauthclient.signup_handlers[remote_app]['view']() return abort(404) if res is None else res
python
def signup(remote_app): """Extra signup step.""" if remote_app not in current_oauthclient.signup_handlers: return abort(404) res = current_oauthclient.signup_handlers[remote_app]['view']() return abort(404) if res is None else res
[ "def", "signup", "(", "remote_app", ")", ":", "if", "remote_app", "not", "in", "current_oauthclient", ".", "signup_handlers", ":", "return", "abort", "(", "404", ")", "res", "=", "current_oauthclient", ".", "signup_handlers", "[", "remote_app", "]", "[", "'view'", "]", "(", ")", "return", "abort", "(", "404", ")", "if", "res", "is", "None", "else", "res" ]
Extra signup step.
[ "Extra", "signup", "step", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/client.py#L132-L137
train
1,149
inveniosoftware/invenio-oauthclient
invenio_oauthclient/views/client.py
disconnect
def disconnect(remote_app): """Disconnect user from remote application. Removes application as well as associated information. """ if remote_app not in current_oauthclient.disconnect_handlers: return abort(404) ret = current_oauthclient.disconnect_handlers[remote_app]() db.session.commit() return ret
python
def disconnect(remote_app): """Disconnect user from remote application. Removes application as well as associated information. """ if remote_app not in current_oauthclient.disconnect_handlers: return abort(404) ret = current_oauthclient.disconnect_handlers[remote_app]() db.session.commit() return ret
[ "def", "disconnect", "(", "remote_app", ")", ":", "if", "remote_app", "not", "in", "current_oauthclient", ".", "disconnect_handlers", ":", "return", "abort", "(", "404", ")", "ret", "=", "current_oauthclient", ".", "disconnect_handlers", "[", "remote_app", "]", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "ret" ]
Disconnect user from remote application. Removes application as well as associated information.
[ "Disconnect", "user", "from", "remote", "application", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/client.py#L141-L151
train
1,150
dourvaris/nano-python
src/nano/crypto.py
address_checksum
def address_checksum(address): """ Returns the checksum in bytes for an address in bytes """ address_bytes = address h = blake2b(digest_size=5) h.update(address_bytes) checksum = bytearray(h.digest()) checksum.reverse() return checksum
python
def address_checksum(address): """ Returns the checksum in bytes for an address in bytes """ address_bytes = address h = blake2b(digest_size=5) h.update(address_bytes) checksum = bytearray(h.digest()) checksum.reverse() return checksum
[ "def", "address_checksum", "(", "address", ")", ":", "address_bytes", "=", "address", "h", "=", "blake2b", "(", "digest_size", "=", "5", ")", "h", ".", "update", "(", "address_bytes", ")", "checksum", "=", "bytearray", "(", "h", ".", "digest", "(", ")", ")", "checksum", ".", "reverse", "(", ")", "return", "checksum" ]
Returns the checksum in bytes for an address in bytes
[ "Returns", "the", "checksum", "in", "bytes", "for", "an", "address", "in", "bytes" ]
f26b8bc895b997067780f925049a70e82c0c2479
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/crypto.py#L16-L25
train
1,151
dourvaris/nano-python
src/nano/crypto.py
keypair_from_seed
def keypair_from_seed(seed, index=0): """ Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_key } """ h = blake2b(digest_size=32) h.update(seed + struct.pack(">L", index)) priv_key = h.digest() pub_key = private_to_public_key(priv_key) return {'private': priv_key, 'public': pub_key}
python
def keypair_from_seed(seed, index=0): """ Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_key } """ h = blake2b(digest_size=32) h.update(seed + struct.pack(">L", index)) priv_key = h.digest() pub_key = private_to_public_key(priv_key) return {'private': priv_key, 'public': pub_key}
[ "def", "keypair_from_seed", "(", "seed", ",", "index", "=", "0", ")", ":", "h", "=", "blake2b", "(", "digest_size", "=", "32", ")", "h", ".", "update", "(", "seed", "+", "struct", ".", "pack", "(", "\">L\"", ",", "index", ")", ")", "priv_key", "=", "h", ".", "digest", "(", ")", "pub_key", "=", "private_to_public_key", "(", "priv_key", ")", "return", "{", "'private'", ":", "priv_key", ",", "'public'", ":", "pub_key", "}" ]
Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_key }
[ "Generates", "a", "deterministic", "keypair", "from", "seed", "based", "on", "index" ]
f26b8bc895b997067780f925049a70e82c0c2479
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/crypto.py#L38-L58
train
1,152
dourvaris/nano-python
src/nano/crypto.py
verify_signature
def verify_signature(message, signature, public_key): """ Verifies `signature` is correct for a `message` signed with `public_key` :param message: message to check :type message: bytes :param signature: signature to check :type signature: bytes :param public_key: public_key to check :type public_key: bytes :return: True if valid, False otherwise :rtype: bool """ try: ed25519_blake2.checkvalid(signature, message, public_key) except ed25519_blake2.SignatureMismatch: return False return True
python
def verify_signature(message, signature, public_key): """ Verifies `signature` is correct for a `message` signed with `public_key` :param message: message to check :type message: bytes :param signature: signature to check :type signature: bytes :param public_key: public_key to check :type public_key: bytes :return: True if valid, False otherwise :rtype: bool """ try: ed25519_blake2.checkvalid(signature, message, public_key) except ed25519_blake2.SignatureMismatch: return False return True
[ "def", "verify_signature", "(", "message", ",", "signature", ",", "public_key", ")", ":", "try", ":", "ed25519_blake2", ".", "checkvalid", "(", "signature", ",", "message", ",", "public_key", ")", "except", "ed25519_blake2", ".", "SignatureMismatch", ":", "return", "False", "return", "True" ]
Verifies `signature` is correct for a `message` signed with `public_key` :param message: message to check :type message: bytes :param signature: signature to check :type signature: bytes :param public_key: public_key to check :type public_key: bytes :return: True if valid, False otherwise :rtype: bool
[ "Verifies", "signature", "is", "correct", "for", "a", "message", "signed", "with", "public_key" ]
f26b8bc895b997067780f925049a70e82c0c2479
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/crypto.py#L95-L116
train
1,153
dourvaris/nano-python
src/nano/crypto.py
sign_message
def sign_message(message, private_key, public_key=None): """ Signs a `message` using `private_key` and `public_key` .. warning:: Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. :param message: the message to sign :type message: bytes :param private_key: private key used to sign message :type private_key: bytes :param public_key: public key used to sign message :type public_key: bytes :return: the signature of the signed message :rtype: bytes """ if public_key is None: public_key = private_to_public_key(private_key) return ed25519_blake2.signature_unsafe(message, private_key, public_key)
python
def sign_message(message, private_key, public_key=None): """ Signs a `message` using `private_key` and `public_key` .. warning:: Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. :param message: the message to sign :type message: bytes :param private_key: private key used to sign message :type private_key: bytes :param public_key: public key used to sign message :type public_key: bytes :return: the signature of the signed message :rtype: bytes """ if public_key is None: public_key = private_to_public_key(private_key) return ed25519_blake2.signature_unsafe(message, private_key, public_key)
[ "def", "sign_message", "(", "message", ",", "private_key", ",", "public_key", "=", "None", ")", ":", "if", "public_key", "is", "None", ":", "public_key", "=", "private_to_public_key", "(", "private_key", ")", "return", "ed25519_blake2", ".", "signature_unsafe", "(", "message", ",", "private_key", ",", "public_key", ")" ]
Signs a `message` using `private_key` and `public_key` .. warning:: Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. :param message: the message to sign :type message: bytes :param private_key: private key used to sign message :type private_key: bytes :param public_key: public key used to sign message :type public_key: bytes :return: the signature of the signed message :rtype: bytes
[ "Signs", "a", "message", "using", "private_key", "and", "public_key" ]
f26b8bc895b997067780f925049a70e82c0c2479
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/crypto.py#L119-L142
train
1,154
qacafe/cdrouter.py
cdrouter/system.py
SystemService.check_for_lounge_upgrade
def check_for_lounge_upgrade(self, email, password): """Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :return: :class:`system.Release <system.Release>` object :rtype: system.Release """ schema = ReleaseSchema() resp = self.service.post(self.base+'lounge/check/', json={'email': email, 'password': password}) return self.service.decode(schema, resp)
python
def check_for_lounge_upgrade(self, email, password): """Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :return: :class:`system.Release <system.Release>` object :rtype: system.Release """ schema = ReleaseSchema() resp = self.service.post(self.base+'lounge/check/', json={'email': email, 'password': password}) return self.service.decode(schema, resp)
[ "def", "check_for_lounge_upgrade", "(", "self", ",", "email", ",", "password", ")", ":", "schema", "=", "ReleaseSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "'lounge/check/'", ",", "json", "=", "{", "'email'", ":", "email", ",", "'password'", ":", "password", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :return: :class:`system.Release <system.Release>` object :rtype: system.Release
[ "Check", "the", "CDRouter", "Support", "Lounge", "for", "eligible", "upgrades", "using", "your", "Support", "Lounge", "email", "&", "password", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L323-L335
train
1,155
qacafe/cdrouter.py
cdrouter/system.py
SystemService.lounge_upgrade
def lounge_upgrade(self, email, password, release_id): """Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :param release_id: Release ID as an int. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'lounge/upgrade/', json={'email': email, 'password': password, 'release': {'id': int(release_id)}}) return self.service.decode(schema, resp)
python
def lounge_upgrade(self, email, password, release_id): """Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :param release_id: Release ID as an int. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'lounge/upgrade/', json={'email': email, 'password': password, 'release': {'id': int(release_id)}}) return self.service.decode(schema, resp)
[ "def", "lounge_upgrade", "(", "self", ",", "email", ",", "password", ",", "release_id", ")", ":", "schema", "=", "UpgradeSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "'lounge/upgrade/'", ",", "json", "=", "{", "'email'", ":", "email", ",", "'password'", ":", "password", ",", "'release'", ":", "{", "'id'", ":", "int", "(", "release_id", ")", "}", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :param release_id: Release ID as an int. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade
[ "Download", "&", "install", "an", "upgrade", "from", "the", "CDRouter", "Support", "Lounge", "using", "your", "Support", "Lounge", "email", "&", "password", ".", "Please", "note", "that", "any", "running", "tests", "will", "be", "stopped", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L337-L351
train
1,156
qacafe/cdrouter.py
cdrouter/system.py
SystemService.lounge_update_license
def lounge_update_license(self): """Download & install a license for your CDRouter system from the CDRouter Support Lounge. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'license/') return self.service.decode(schema, resp)
python
def lounge_update_license(self): """Download & install a license for your CDRouter system from the CDRouter Support Lounge. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'license/') return self.service.decode(schema, resp)
[ "def", "lounge_update_license", "(", "self", ")", ":", "schema", "=", "UpgradeSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "'license/'", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Download & install a license for your CDRouter system from the CDRouter Support Lounge. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade
[ "Download", "&", "install", "a", "license", "for", "your", "CDRouter", "system", "from", "the", "CDRouter", "Support", "Lounge", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L368-L377
train
1,157
qacafe/cdrouter.py
cdrouter/system.py
SystemService.manual_update_license
def manual_update_license(self, fd, filename='cdrouter.lic'): """Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'license/', files={'file': (filename, fd)}) return self.service.decode(schema, resp)
python
def manual_update_license(self, fd, filename='cdrouter.lic'): """Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self.base+'license/', files={'file': (filename, fd)}) return self.service.decode(schema, resp)
[ "def", "manual_update_license", "(", "self", ",", "fd", ",", "filename", "=", "'cdrouter.lic'", ")", ":", "schema", "=", "UpgradeSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "'license/'", ",", "files", "=", "{", "'file'", ":", "(", "filename", ",", "fd", ")", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade
[ "Update", "the", "license", "on", "your", "CDRouter", "system", "manually", "by", "uploading", "a", ".", "lic", "license", "from", "the", "CDRouter", "Support", "Lounge", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L379-L391
train
1,158
qacafe/cdrouter.py
cdrouter/system.py
SystemService.space
def space(self): """Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space """ schema = SpaceSchema() resp = self.service.get(self.base+'space/') return self.service.decode(schema, resp)
python
def space(self): """Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space """ schema = SpaceSchema() resp = self.service.get(self.base+'space/') return self.service.decode(schema, resp)
[ "def", "space", "(", "self", ")", ":", "schema", "=", "SpaceSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get", "(", "self", ".", "base", "+", "'space/'", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space
[ "Get", "system", "disk", "space", "usage", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L425-L433
train
1,159
qacafe/cdrouter.py
cdrouter/system.py
SystemService.interfaces
def interfaces(self, addresses=False): """Get system interfaces. :param addresses: (optional) If bool `True`, include interface addresses. :return: :class:`system.Interface <system.Interface>` list """ schema = InterfaceSchema() resp = self.service.get(self.base+'interfaces/', params={'addresses': addresses}) return self.service.decode(schema, resp, many=True)
python
def interfaces(self, addresses=False): """Get system interfaces. :param addresses: (optional) If bool `True`, include interface addresses. :return: :class:`system.Interface <system.Interface>` list """ schema = InterfaceSchema() resp = self.service.get(self.base+'interfaces/', params={'addresses': addresses}) return self.service.decode(schema, resp, many=True)
[ "def", "interfaces", "(", "self", ",", "addresses", "=", "False", ")", ":", "schema", "=", "InterfaceSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get", "(", "self", ".", "base", "+", "'interfaces/'", ",", "params", "=", "{", "'addresses'", ":", "addresses", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ",", "many", "=", "True", ")" ]
Get system interfaces. :param addresses: (optional) If bool `True`, include interface addresses. :return: :class:`system.Interface <system.Interface>` list
[ "Get", "system", "interfaces", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L442-L450
train
1,160
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_set_original_fields
def _set_original_fields(instance): """ Save fields value, only for non-m2m fields. """ original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), ForeignKey): # Only get the PK, we don't want to get the object # (which would make an additional request) original_fields[field] = getattr(instance, '{0}_id'.format(field)) else: original_fields[field] = getattr(instance, field) for field in getattr(instance, '_tracked_fields', []): _set_original_field(instance, field) for field in getattr(instance, '_tracked_related_fields', {}).keys(): _set_original_field(instance, field) instance._original_fields = original_fields # Include pk to detect the creation of an object instance._original_fields['pk'] = instance.pk
python
def _set_original_fields(instance): """ Save fields value, only for non-m2m fields. """ original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), ForeignKey): # Only get the PK, we don't want to get the object # (which would make an additional request) original_fields[field] = getattr(instance, '{0}_id'.format(field)) else: original_fields[field] = getattr(instance, field) for field in getattr(instance, '_tracked_fields', []): _set_original_field(instance, field) for field in getattr(instance, '_tracked_related_fields', {}).keys(): _set_original_field(instance, field) instance._original_fields = original_fields # Include pk to detect the creation of an object instance._original_fields['pk'] = instance.pk
[ "def", "_set_original_fields", "(", "instance", ")", ":", "original_fields", "=", "{", "}", "def", "_set_original_field", "(", "instance", ",", "field", ")", ":", "if", "instance", ".", "pk", "is", "None", ":", "original_fields", "[", "field", "]", "=", "None", "else", ":", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "# Only get the PK, we don't want to get the object", "# (which would make an additional request)", "original_fields", "[", "field", "]", "=", "getattr", "(", "instance", ",", "'{0}_id'", ".", "format", "(", "field", ")", ")", "else", ":", "original_fields", "[", "field", "]", "=", "getattr", "(", "instance", ",", "field", ")", "for", "field", "in", "getattr", "(", "instance", ",", "'_tracked_fields'", ",", "[", "]", ")", ":", "_set_original_field", "(", "instance", ",", "field", ")", "for", "field", "in", "getattr", "(", "instance", ",", "'_tracked_related_fields'", ",", "{", "}", ")", ".", "keys", "(", ")", ":", "_set_original_field", "(", "instance", ",", "field", ")", "instance", ".", "_original_fields", "=", "original_fields", "# Include pk to detect the creation of an object", "instance", ".", "_original_fields", "[", "'pk'", "]", "=", "instance", ".", "pk" ]
Save fields value, only for non-m2m fields.
[ "Save", "fields", "value", "only", "for", "non", "-", "m2m", "fields", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L29-L54
train
1,161
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_has_changed
def _has_changed(instance): """ Check if some tracked fields have changed """ for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, '_tracked_fields', []): if isinstance(instance._meta.get_field(field), ForeignKey): if getattr(instance, '{0}_id'.format(field)) != value: return True else: if getattr(instance, field) != value: return True except TypeError: # Can't compare old and new value, should be different. return True return False
python
def _has_changed(instance): """ Check if some tracked fields have changed """ for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, '_tracked_fields', []): if isinstance(instance._meta.get_field(field), ForeignKey): if getattr(instance, '{0}_id'.format(field)) != value: return True else: if getattr(instance, field) != value: return True except TypeError: # Can't compare old and new value, should be different. return True return False
[ "def", "_has_changed", "(", "instance", ")", ":", "for", "field", ",", "value", "in", "instance", ".", "_original_fields", ".", "items", "(", ")", ":", "if", "field", "!=", "'pk'", "and", "not", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "try", ":", "if", "field", "in", "getattr", "(", "instance", ",", "'_tracked_fields'", ",", "[", "]", ")", ":", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "if", "getattr", "(", "instance", ",", "'{0}_id'", ".", "format", "(", "field", ")", ")", "!=", "value", ":", "return", "True", "else", ":", "if", "getattr", "(", "instance", ",", "field", ")", "!=", "value", ":", "return", "True", "except", "TypeError", ":", "# Can't compare old and new value, should be different.", "return", "True", "return", "False" ]
Check if some tracked fields have changed
[ "Check", "if", "some", "tracked", "fields", "have", "changed" ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L57-L75
train
1,162
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_has_changed_related
def _has_changed_related(instance): """ Check if some related tracked fields have changed """ tracked_related_fields = getattr( instance, '_tracked_related_fields', {} ).keys() for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): if field in tracked_related_fields: if isinstance(instance._meta.get_field(field), ForeignKey): if getattr(instance, '{0}_id'.format(field)) != value: return True else: if getattr(instance, field) != value: return True return False
python
def _has_changed_related(instance): """ Check if some related tracked fields have changed """ tracked_related_fields = getattr( instance, '_tracked_related_fields', {} ).keys() for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): if field in tracked_related_fields: if isinstance(instance._meta.get_field(field), ForeignKey): if getattr(instance, '{0}_id'.format(field)) != value: return True else: if getattr(instance, field) != value: return True return False
[ "def", "_has_changed_related", "(", "instance", ")", ":", "tracked_related_fields", "=", "getattr", "(", "instance", ",", "'_tracked_related_fields'", ",", "{", "}", ")", ".", "keys", "(", ")", "for", "field", ",", "value", "in", "instance", ".", "_original_fields", ".", "items", "(", ")", ":", "if", "field", "!=", "'pk'", "and", "not", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "if", "field", "in", "tracked_related_fields", ":", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "if", "getattr", "(", "instance", ",", "'{0}_id'", ".", "format", "(", "field", ")", ")", "!=", "value", ":", "return", "True", "else", ":", "if", "getattr", "(", "instance", ",", "field", ")", "!=", "value", ":", "return", "True", "return", "False" ]
Check if some related tracked fields have changed
[ "Check", "if", "some", "related", "tracked", "fields", "have", "changed" ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L78-L97
train
1,163
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_event
def _create_event(instance, action): """ Create a new event, getting the use if django-cuser is available. """ user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user = None return TrackingEvent.objects.create( action=action, object=instance, object_repr=repr(instance), user=user, user_repr=user_repr, )
python
def _create_event(instance, action): """ Create a new event, getting the use if django-cuser is available. """ user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user = None return TrackingEvent.objects.create( action=action, object=instance, object_repr=repr(instance), user=user, user_repr=user_repr, )
[ "def", "_create_event", "(", "instance", ",", "action", ")", ":", "user", "=", "None", "user_repr", "=", "repr", "(", "user", ")", "if", "CUSER", ":", "user", "=", "CuserMiddleware", ".", "get_user", "(", ")", "user_repr", "=", "repr", "(", "user", ")", "if", "user", "is", "not", "None", "and", "user", ".", "is_anonymous", ":", "user", "=", "None", "return", "TrackingEvent", ".", "objects", ".", "create", "(", "action", "=", "action", ",", "object", "=", "instance", ",", "object_repr", "=", "repr", "(", "instance", ")", ",", "user", "=", "user", ",", "user_repr", "=", "user_repr", ",", ")" ]
Create a new event, getting the use if django-cuser is available.
[ "Create", "a", "new", "event", "getting", "the", "use", "if", "django", "-", "cuser", "is", "available", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L100-L117
train
1,164
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_tracked_field
def _create_tracked_field(event, instance, field, fieldname=None): """ Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: The displayed name for the field. Default to field. """ fieldname = fieldname or field if isinstance(instance._meta.get_field(field), ForeignKey): # We only have the pk, we need to get the actual object model = instance._meta.get_field(field).remote_field.model pk = instance._original_fields[field] try: old_value = model.objects.get(pk=pk) except model.DoesNotExist: old_value = None else: old_value = instance._original_fields[field] return TrackedFieldModification.objects.create( event=event, field=fieldname, old_value=_serialize_field(old_value), new_value=_serialize_field(getattr(instance, field)) )
python
def _create_tracked_field(event, instance, field, fieldname=None): """ Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: The displayed name for the field. Default to field. """ fieldname = fieldname or field if isinstance(instance._meta.get_field(field), ForeignKey): # We only have the pk, we need to get the actual object model = instance._meta.get_field(field).remote_field.model pk = instance._original_fields[field] try: old_value = model.objects.get(pk=pk) except model.DoesNotExist: old_value = None else: old_value = instance._original_fields[field] return TrackedFieldModification.objects.create( event=event, field=fieldname, old_value=_serialize_field(old_value), new_value=_serialize_field(getattr(instance, field)) )
[ "def", "_create_tracked_field", "(", "event", ",", "instance", ",", "field", ",", "fieldname", "=", "None", ")", ":", "fieldname", "=", "fieldname", "or", "field", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "# We only have the pk, we need to get the actual object", "model", "=", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ".", "remote_field", ".", "model", "pk", "=", "instance", ".", "_original_fields", "[", "field", "]", "try", ":", "old_value", "=", "model", ".", "objects", ".", "get", "(", "pk", "=", "pk", ")", "except", "model", ".", "DoesNotExist", ":", "old_value", "=", "None", "else", ":", "old_value", "=", "instance", ".", "_original_fields", "[", "field", "]", "return", "TrackedFieldModification", ".", "objects", ".", "create", "(", "event", "=", "event", ",", "field", "=", "fieldname", ",", "old_value", "=", "_serialize_field", "(", "old_value", ")", ",", "new_value", "=", "_serialize_field", "(", "getattr", "(", "instance", ",", "field", ")", ")", ")" ]
Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: The displayed name for the field. Default to field.
[ "Create", "a", "TrackedFieldModification", "for", "the", "instance", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L145-L170
train
1,165
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_create_tracking_event
def _create_create_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for a CREATE event. """ event = _create_event(instance, CREATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): _create_tracked_field(event, instance, field)
python
def _create_create_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for a CREATE event. """ event = _create_event(instance, CREATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): _create_tracked_field(event, instance, field)
[ "def", "_create_create_tracking_event", "(", "instance", ")", ":", "event", "=", "_create_event", "(", "instance", ",", "CREATE", ")", "for", "field", "in", "instance", ".", "_tracked_fields", ":", "if", "not", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "_create_tracked_field", "(", "event", ",", "instance", ",", "field", ")" ]
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
[ "Create", "a", "TrackingEvent", "and", "TrackedFieldModification", "for", "a", "CREATE", "event", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L173-L180
train
1,166
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_update_tracking_event
def _create_update_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event. """ event = _create_event(instance, UPDATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): try: if isinstance(instance._meta.get_field(field), ForeignKey): # Compare pk value = getattr(instance, '{0}_id'.format(field)) else: value = getattr(instance, field) if instance._original_fields[field] != value: _create_tracked_field(event, instance, field) except TypeError: # Can't compare old and new value, should be different. _create_tracked_field(event, instance, field)
python
def _create_update_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event. """ event = _create_event(instance, UPDATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): try: if isinstance(instance._meta.get_field(field), ForeignKey): # Compare pk value = getattr(instance, '{0}_id'.format(field)) else: value = getattr(instance, field) if instance._original_fields[field] != value: _create_tracked_field(event, instance, field) except TypeError: # Can't compare old and new value, should be different. _create_tracked_field(event, instance, field)
[ "def", "_create_update_tracking_event", "(", "instance", ")", ":", "event", "=", "_create_event", "(", "instance", ",", "UPDATE", ")", "for", "field", "in", "instance", ".", "_tracked_fields", ":", "if", "not", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "try", ":", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "# Compare pk", "value", "=", "getattr", "(", "instance", ",", "'{0}_id'", ".", "format", "(", "field", ")", ")", "else", ":", "value", "=", "getattr", "(", "instance", ",", "field", ")", "if", "instance", ".", "_original_fields", "[", "field", "]", "!=", "value", ":", "_create_tracked_field", "(", "event", ",", "instance", ",", "field", ")", "except", "TypeError", ":", "# Can't compare old and new value, should be different.", "_create_tracked_field", "(", "event", ",", "instance", ",", "field", ")" ]
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
[ "Create", "a", "TrackingEvent", "and", "TrackedFieldModification", "for", "an", "UPDATE", "event", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L183-L200
train
1,167
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_update_tracking_related_event
def _create_update_tracking_related_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model. """ events = {} # Create a dict mapping related model field to modified fields for field, related_fields in instance._tracked_related_fields.items(): if not isinstance(instance._meta.get_field(field), ManyToManyField): if isinstance(instance._meta.get_field(field), ForeignKey): # Compare pk value = getattr(instance, '{0}_id'.format(field)) else: value = getattr(instance, field) if instance._original_fields[field] != value: for related_field in related_fields: events.setdefault(related_field, []).append(field) # Create the events from the events dict for related_field, fields in events.items(): try: related_instances = getattr(instance, related_field[1]) except ObjectDoesNotExist: continue # FIXME: isinstance(related_instances, RelatedManager ?) if hasattr(related_instances, 'all'): related_instances = related_instances.all() else: related_instances = [related_instances] for related_instance in related_instances: event = _create_event(related_instance, UPDATE) for field in fields: fieldname = '{0}__{1}'.format(related_field[0], field) _create_tracked_field( event, instance, field, fieldname=fieldname )
python
def _create_update_tracking_related_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model. """ events = {} # Create a dict mapping related model field to modified fields for field, related_fields in instance._tracked_related_fields.items(): if not isinstance(instance._meta.get_field(field), ManyToManyField): if isinstance(instance._meta.get_field(field), ForeignKey): # Compare pk value = getattr(instance, '{0}_id'.format(field)) else: value = getattr(instance, field) if instance._original_fields[field] != value: for related_field in related_fields: events.setdefault(related_field, []).append(field) # Create the events from the events dict for related_field, fields in events.items(): try: related_instances = getattr(instance, related_field[1]) except ObjectDoesNotExist: continue # FIXME: isinstance(related_instances, RelatedManager ?) if hasattr(related_instances, 'all'): related_instances = related_instances.all() else: related_instances = [related_instances] for related_instance in related_instances: event = _create_event(related_instance, UPDATE) for field in fields: fieldname = '{0}__{1}'.format(related_field[0], field) _create_tracked_field( event, instance, field, fieldname=fieldname )
[ "def", "_create_update_tracking_related_event", "(", "instance", ")", ":", "events", "=", "{", "}", "# Create a dict mapping related model field to modified fields", "for", "field", ",", "related_fields", "in", "instance", ".", "_tracked_related_fields", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "if", "isinstance", "(", "instance", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ForeignKey", ")", ":", "# Compare pk", "value", "=", "getattr", "(", "instance", ",", "'{0}_id'", ".", "format", "(", "field", ")", ")", "else", ":", "value", "=", "getattr", "(", "instance", ",", "field", ")", "if", "instance", ".", "_original_fields", "[", "field", "]", "!=", "value", ":", "for", "related_field", "in", "related_fields", ":", "events", ".", "setdefault", "(", "related_field", ",", "[", "]", ")", ".", "append", "(", "field", ")", "# Create the events from the events dict", "for", "related_field", ",", "fields", "in", "events", ".", "items", "(", ")", ":", "try", ":", "related_instances", "=", "getattr", "(", "instance", ",", "related_field", "[", "1", "]", ")", "except", "ObjectDoesNotExist", ":", "continue", "# FIXME: isinstance(related_instances, RelatedManager ?)", "if", "hasattr", "(", "related_instances", ",", "'all'", ")", ":", "related_instances", "=", "related_instances", ".", "all", "(", ")", "else", ":", "related_instances", "=", "[", "related_instances", "]", "for", "related_instance", "in", "related_instances", ":", "event", "=", "_create_event", "(", "related_instance", ",", "UPDATE", ")", "for", "field", "in", "fields", ":", "fieldname", "=", "'{0}__{1}'", ".", "format", "(", "related_field", "[", "0", "]", ",", "field", ")", "_create_tracked_field", "(", "event", ",", "instance", ",", "field", ",", "fieldname", "=", "fieldname", ")" ]
Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model.
[ "Create", "a", "TrackingEvent", "and", "TrackedFieldModification", "for", "an", "UPDATE", "event", "for", "each", "related", "model", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L203-L239
train
1,168
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_get_m2m_field
def _get_m2m_field(model, sender): """ Get the field name from a model and a sender from m2m_changed signal. """ for field in getattr(model, '_tracked_fields', []): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field for field in getattr(model, '_tracked_related_fields', {}).keys(): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field
python
def _get_m2m_field(model, sender): """ Get the field name from a model and a sender from m2m_changed signal. """ for field in getattr(model, '_tracked_fields', []): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field for field in getattr(model, '_tracked_related_fields', {}).keys(): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field
[ "def", "_get_m2m_field", "(", "model", ",", "sender", ")", ":", "for", "field", "in", "getattr", "(", "model", ",", "'_tracked_fields'", ",", "[", "]", ")", ":", "if", "isinstance", "(", "model", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "if", "getattr", "(", "model", ",", "field", ")", ".", "through", "==", "sender", ":", "return", "field", "for", "field", "in", "getattr", "(", "model", ",", "'_tracked_related_fields'", ",", "{", "}", ")", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "model", ".", "_meta", ".", "get_field", "(", "field", ")", ",", "ManyToManyField", ")", ":", "if", "getattr", "(", "model", ",", "field", ")", ".", "through", "==", "sender", ":", "return", "field" ]
Get the field name from a model and a sender from m2m_changed signal.
[ "Get", "the", "field", "name", "from", "a", "model", "and", "a", "sender", "from", "m2m_changed", "signal", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L249-L260
train
1,169
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
tracking_save
def tracking_save(sender, instance, raw, using, update_fields, **kwargs): """ Post save, detect creation or changes and log them. We need post_save to have the object for a create. """ if _has_changed(instance): if instance._original_fields['pk'] is None: # Create _create_create_tracking_event(instance) else: # Update _create_update_tracking_event(instance) if _has_changed_related(instance): # Because an object need to be saved before being related, # it can only be an update _create_update_tracking_related_event(instance) if _has_changed(instance) or _has_changed_related(instance): _set_original_fields(instance)
python
def tracking_save(sender, instance, raw, using, update_fields, **kwargs): """ Post save, detect creation or changes and log them. We need post_save to have the object for a create. """ if _has_changed(instance): if instance._original_fields['pk'] is None: # Create _create_create_tracking_event(instance) else: # Update _create_update_tracking_event(instance) if _has_changed_related(instance): # Because an object need to be saved before being related, # it can only be an update _create_update_tracking_related_event(instance) if _has_changed(instance) or _has_changed_related(instance): _set_original_fields(instance)
[ "def", "tracking_save", "(", "sender", ",", "instance", ",", "raw", ",", "using", ",", "update_fields", ",", "*", "*", "kwargs", ")", ":", "if", "_has_changed", "(", "instance", ")", ":", "if", "instance", ".", "_original_fields", "[", "'pk'", "]", "is", "None", ":", "# Create", "_create_create_tracking_event", "(", "instance", ")", "else", ":", "# Update", "_create_update_tracking_event", "(", "instance", ")", "if", "_has_changed_related", "(", "instance", ")", ":", "# Because an object need to be saved before being related,", "# it can only be an update", "_create_update_tracking_related_event", "(", "instance", ")", "if", "_has_changed", "(", "instance", ")", "or", "_has_changed_related", "(", "instance", ")", ":", "_set_original_fields", "(", "instance", ")" ]
Post save, detect creation or changes and log them. We need post_save to have the object for a create.
[ "Post", "save", "detect", "creation", "or", "changes", "and", "log", "them", ".", "We", "need", "post_save", "to", "have", "the", "object", "for", "a", "create", "." ]
463313d0f9c0f8107a0413f4d418d1a8c2311981
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L332-L349
train
1,170
andresriancho/w3af-api-client
w3af_api_client/log.py
LogEntry.from_entry_dict
def from_entry_dict(cls, entry_dict): """ This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry. """ # Debug helper # https://circleci.com/gh/andresriancho/w3af-api-docker/30 try: _type = entry_dict['type'] _id = entry_dict['id'] _time = entry_dict['time'] message = entry_dict['message'] severity = entry_dict['severity'] except KeyError: msg = ('Missing expected log entry attribute. Log entry' ' object is:\n\n%s') raise APIException(msg % json.dumps(entry_dict, indent=4)) return cls(_type, message, _time, severity, _id)
python
def from_entry_dict(cls, entry_dict): """ This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry. """ # Debug helper # https://circleci.com/gh/andresriancho/w3af-api-docker/30 try: _type = entry_dict['type'] _id = entry_dict['id'] _time = entry_dict['time'] message = entry_dict['message'] severity = entry_dict['severity'] except KeyError: msg = ('Missing expected log entry attribute. Log entry' ' object is:\n\n%s') raise APIException(msg % json.dumps(entry_dict, indent=4)) return cls(_type, message, _time, severity, _id)
[ "def", "from_entry_dict", "(", "cls", ",", "entry_dict", ")", ":", "# Debug helper", "# https://circleci.com/gh/andresriancho/w3af-api-docker/30", "try", ":", "_type", "=", "entry_dict", "[", "'type'", "]", "_id", "=", "entry_dict", "[", "'id'", "]", "_time", "=", "entry_dict", "[", "'time'", "]", "message", "=", "entry_dict", "[", "'message'", "]", "severity", "=", "entry_dict", "[", "'severity'", "]", "except", "KeyError", ":", "msg", "=", "(", "'Missing expected log entry attribute. Log entry'", "' object is:\\n\\n%s'", ")", "raise", "APIException", "(", "msg", "%", "json", ".", "dumps", "(", "entry_dict", ",", "indent", "=", "4", ")", ")", "return", "cls", "(", "_type", ",", "message", ",", "_time", ",", "severity", ",", "_id", ")" ]
This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry.
[ "This", "is", "a", "constructor", "for", "the", "LogEntry", "class", "." ]
adeb79bad75264d754de69f0bb981b366da96f32
https://github.com/andresriancho/w3af-api-client/blob/adeb79bad75264d754de69f0bb981b366da96f32/w3af_api_client/log.py#L22-L42
train
1,171
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.list
def list(self, id, seq): # pylint: disable=invalid-name,redefined-builtin """Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list """ schema = CaptureSchema(exclude=('id', 'seq')) resp = self.service.list(self._base(id, seq)) return self.service.decode(schema, resp, many=True)
python
def list(self, id, seq): # pylint: disable=invalid-name,redefined-builtin """Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list """ schema = CaptureSchema(exclude=('id', 'seq')) resp = self.service.list(self._base(id, seq)) return self.service.decode(schema, resp, many=True)
[ "def", "list", "(", "self", ",", "id", ",", "seq", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "CaptureSchema", "(", "exclude", "=", "(", "'id'", ",", "'seq'", ")", ")", "resp", "=", "self", ".", "service", ".", "list", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ",", "many", "=", "True", ")" ]
Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list
[ "Get", "a", "list", "of", "captures", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L308-L317
train
1,172
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.get
def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin """Get a capture. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :return: :class:`captures.Capture <captures.Capture>` object :rtype: captures.Capture """ schema = CaptureSchema() resp = self.service.get_id(self._base(id, seq), intf) return self.service.decode(schema, resp)
python
def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin """Get a capture. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :return: :class:`captures.Capture <captures.Capture>` object :rtype: captures.Capture """ schema = CaptureSchema() resp = self.service.get_id(self._base(id, seq), intf) return self.service.decode(schema, resp)
[ "def", "get", "(", "self", ",", "id", ",", "seq", ",", "intf", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "CaptureSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get_id", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ",", "intf", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a capture. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :return: :class:`captures.Capture <captures.Capture>` object :rtype: captures.Capture
[ "Get", "a", "capture", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L319-L330
train
1,173
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.download
def download(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get_id(self._base(id, seq), intf, params={'format': 'cap', 'inline': inline}, stream=True) b = io.BytesIO() stream.stream_response_to_file(resp, path=b) resp.close() b.seek(0) return (b, self.service.filename(resp))
python
def download(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get_id(self._base(id, seq), intf, params={'format': 'cap', 'inline': inline}, stream=True) b = io.BytesIO() stream.stream_response_to_file(resp, path=b) resp.close() b.seek(0) return (b, self.service.filename(resp))
[ "def", "download", "(", "self", ",", "id", ",", "seq", ",", "intf", ",", "inline", "=", "False", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "resp", "=", "self", ".", "service", ".", "get_id", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", ",", "intf", ",", "params", "=", "{", "'format'", ":", "'cap'", ",", "'inline'", ":", "inline", "}", ",", "stream", "=", "True", ")", "b", "=", "io", ".", "BytesIO", "(", ")", "stream", ".", "stream_response_to_file", "(", "resp", ",", "path", "=", "b", ")", "resp", ".", "close", "(", ")", "b", ".", "seek", "(", "0", ")", "return", "(", "b", ",", "self", ".", "service", ".", "filename", "(", "resp", ")", ")" ]
Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :rtype: tuple `(io.BytesIO, 'filename')`
[ "Download", "a", "capture", "as", "a", "PCAP", "file", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L332-L346
train
1,174
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.summary
def summary(self, id, seq, intf, filter=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Summary <captures.Summary>` object :rtype: captures.Summary """ schema = SummarySchema() resp = self.service.get(self._base(id, seq)+str(intf)+'/summary/', params={'filter': filter, 'inline': inline}) return self.service.decode(schema, resp)
python
def summary(self, id, seq, intf, filter=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Summary <captures.Summary>` object :rtype: captures.Summary """ schema = SummarySchema() resp = self.service.get(self._base(id, seq)+str(intf)+'/summary/', params={'filter': filter, 'inline': inline}) return self.service.decode(schema, resp)
[ "def", "summary", "(", "self", ",", "id", ",", "seq", ",", "intf", ",", "filter", "=", "None", ",", "inline", "=", "False", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "SummarySchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", "+", "str", "(", "intf", ")", "+", "'/summary/'", ",", "params", "=", "{", "'filter'", ":", "filter", ",", "'inline'", ":", "inline", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Summary <captures.Summary>` object :rtype: captures.Summary
[ "Get", "a", "capture", "s", "summary", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L348-L362
train
1,175
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.decode
def decode(self, id, seq, intf, filter=None, frame=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param frame: (optional) Frame number to decode. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Decode <captures.Decode>` object :rtype: captures.Decode """ schema = DecodeSchema() resp = self.service.get(self._base(id, seq)+str(intf)+'/decode/', params={'filter': filter, 'frame': frame, 'inline': inline}) return self.service.decode(schema, resp)
python
def decode(self, id, seq, intf, filter=None, frame=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param frame: (optional) Frame number to decode. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Decode <captures.Decode>` object :rtype: captures.Decode """ schema = DecodeSchema() resp = self.service.get(self._base(id, seq)+str(intf)+'/decode/', params={'filter': filter, 'frame': frame, 'inline': inline}) return self.service.decode(schema, resp)
[ "def", "decode", "(", "self", ",", "id", ",", "seq", ",", "intf", ",", "filter", "=", "None", ",", "frame", "=", "None", ",", "inline", "=", "False", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "DecodeSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", "+", "str", "(", "intf", ")", "+", "'/decode/'", ",", "params", "=", "{", "'filter'", ":", "filter", ",", "'frame'", ":", "frame", ",", "'inline'", ":", "inline", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param frame: (optional) Frame number to decode. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.Decode <captures.Decode>` object :rtype: captures.Decode
[ "Get", "a", "capture", "s", "decode", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L364-L379
train
1,176
qacafe/cdrouter.py
cdrouter/captures.py
CapturesService.send_to_cloudshark
def send_to_cloudshark(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.CloudShark <captures.CloudShark>` object :rtype: captures.CloudShark """ schema = CloudSharkSchema() resp = self.service.post(self._base(id, seq)+str(intf)+'/cloudshark/', params={'inline': inline}) return self.service.decode(schema, resp)
python
def send_to_cloudshark(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.CloudShark <captures.CloudShark>` object :rtype: captures.CloudShark """ schema = CloudSharkSchema() resp = self.service.post(self._base(id, seq)+str(intf)+'/cloudshark/', params={'inline': inline}) return self.service.decode(schema, resp)
[ "def", "send_to_cloudshark", "(", "self", ",", "id", ",", "seq", ",", "intf", ",", "inline", "=", "False", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "CloudSharkSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "_base", "(", "id", ",", "seq", ")", "+", "str", "(", "intf", ")", "+", "'/cloudshark/'", ",", "params", "=", "{", "'inline'", ":", "inline", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :return: :class:`captures.CloudShark <captures.CloudShark>` object :rtype: captures.CloudShark
[ "Send", "a", "capture", "to", "a", "CloudShark", "Appliance", ".", "Both", "cloudshark_appliance_url", "and", "cloudshark_appliance_token", "must", "be", "properly", "configured", "via", "system", "preferences", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/captures.py#L398-L412
train
1,177
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/globus.py
get_dict_from_response
def get_dict_from_response(response): """Check for errors in the response and return the resulting JSON.""" if getattr(response, '_resp') and response._resp.code > 400: raise OAuthResponseError( 'Application mis-configuration in Globus', None, response ) return response.data
python
def get_dict_from_response(response): """Check for errors in the response and return the resulting JSON.""" if getattr(response, '_resp') and response._resp.code > 400: raise OAuthResponseError( 'Application mis-configuration in Globus', None, response ) return response.data
[ "def", "get_dict_from_response", "(", "response", ")", ":", "if", "getattr", "(", "response", ",", "'_resp'", ")", "and", "response", ".", "_resp", ".", "code", ">", "400", ":", "raise", "OAuthResponseError", "(", "'Application mis-configuration in Globus'", ",", "None", ",", "response", ")", "return", "response", ".", "data" ]
Check for errors in the response and return the resulting JSON.
[ "Check", "for", "errors", "in", "the", "response", "and", "return", "the", "resulting", "JSON", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/globus.py#L88-L95
train
1,178
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/globus.py
get_user_info
def get_user_info(remote): """Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/ """ response = remote.get(GLOBUS_USER_INFO_URL) user_info = get_dict_from_response(response) response.data['username'] = response.data['preferred_username'] if '@' in response.data['username']: user_info['username'], _ = response.data['username'].split('@') return user_info
python
def get_user_info(remote): """Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/ """ response = remote.get(GLOBUS_USER_INFO_URL) user_info = get_dict_from_response(response) response.data['username'] = response.data['preferred_username'] if '@' in response.data['username']: user_info['username'], _ = response.data['username'].split('@') return user_info
[ "def", "get_user_info", "(", "remote", ")", ":", "response", "=", "remote", ".", "get", "(", "GLOBUS_USER_INFO_URL", ")", "user_info", "=", "get_dict_from_response", "(", "response", ")", "response", ".", "data", "[", "'username'", "]", "=", "response", ".", "data", "[", "'preferred_username'", "]", "if", "'@'", "in", "response", ".", "data", "[", "'username'", "]", ":", "user_info", "[", "'username'", "]", ",", "_", "=", "response", ".", "data", "[", "'username'", "]", ".", "split", "(", "'@'", ")", "return", "user_info" ]
Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/
[ "Get", "user", "information", "from", "Globus", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/globus.py#L98-L109
train
1,179
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/globus.py
get_user_id
def get_user_id(remote, email): """Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/ """ try: url = '{}?usernames={}'.format(GLOBUS_USER_ID_URL, email) user_id = get_dict_from_response(remote.get(url)) return user_id['identities'][0]['id'] except KeyError: # If we got here the response was successful but the data was invalid. # It's likely the URL is wrong but possible the API has changed. raise OAuthResponseError('Failed to fetch user id, likely server ' 'mis-configuration', None, remote)
python
def get_user_id(remote, email): """Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/ """ try: url = '{}?usernames={}'.format(GLOBUS_USER_ID_URL, email) user_id = get_dict_from_response(remote.get(url)) return user_id['identities'][0]['id'] except KeyError: # If we got here the response was successful but the data was invalid. # It's likely the URL is wrong but possible the API has changed. raise OAuthResponseError('Failed to fetch user id, likely server ' 'mis-configuration', None, remote)
[ "def", "get_user_id", "(", "remote", ",", "email", ")", ":", "try", ":", "url", "=", "'{}?usernames={}'", ".", "format", "(", "GLOBUS_USER_ID_URL", ",", "email", ")", "user_id", "=", "get_dict_from_response", "(", "remote", ".", "get", "(", "url", ")", ")", "return", "user_id", "[", "'identities'", "]", "[", "0", "]", "[", "'id'", "]", "except", "KeyError", ":", "# If we got here the response was successful but the data was invalid.", "# It's likely the URL is wrong but possible the API has changed.", "raise", "OAuthResponseError", "(", "'Failed to fetch user id, likely server '", "'mis-configuration'", ",", "None", ",", "remote", ")" ]
Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/
[ "Get", "the", "Globus", "identity", "for", "a", "users", "given", "email", "." ]
2500dc6935738107617aeade79e050d7608004bb
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/globus.py#L112-L127
train
1,180
SylvanasSun/python-common-cache
common_cache/utils.py
get_function_signature
def get_function_signature(func): """ Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: The argument must be a function object: None type is <class 'str'> """ if func is None: return 'Function is None' try: func_name = func.__name__ except AttributeError: func_name = 'None' if not inspect.isfunction(func): raise TypeError('The argument must be a function object: %s type is %s' % (func_name, type(func))) return func_name + str(inspect.signature(func))
python
def get_function_signature(func): """ Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: The argument must be a function object: None type is <class 'str'> """ if func is None: return 'Function is None' try: func_name = func.__name__ except AttributeError: func_name = 'None' if not inspect.isfunction(func): raise TypeError('The argument must be a function object: %s type is %s' % (func_name, type(func))) return func_name + str(inspect.signature(func))
[ "def", "get_function_signature", "(", "func", ")", ":", "if", "func", "is", "None", ":", "return", "'Function is None'", "try", ":", "func_name", "=", "func", ".", "__name__", "except", "AttributeError", ":", "func_name", "=", "'None'", "if", "not", "inspect", ".", "isfunction", "(", "func", ")", ":", "raise", "TypeError", "(", "'The argument must be a function object: %s type is %s'", "%", "(", "func_name", ",", "type", "(", "func", ")", ")", ")", "return", "func_name", "+", "str", "(", "inspect", ".", "signature", "(", "func", ")", ")" ]
Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: The argument must be a function object: None type is <class 'str'>
[ "Return", "the", "signature", "string", "of", "the", "specified", "function", "." ]
f113eb3cd751eed5ab5373e8610a31a444220cf8
https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/utils.py#L10-L34
train
1,181
SylvanasSun/python-common-cache
common_cache/utils.py
RWLock.acquire_reader
def acquire_reader(self): """ Acquire a read lock, several threads can hold this type of lock. """ with self.mutex: while self.rwlock < 0 or self.rwlock == self.max_reader_concurrency or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1
python
def acquire_reader(self): """ Acquire a read lock, several threads can hold this type of lock. """ with self.mutex: while self.rwlock < 0 or self.rwlock == self.max_reader_concurrency or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1
[ "def", "acquire_reader", "(", "self", ")", ":", "with", "self", ".", "mutex", ":", "while", "self", ".", "rwlock", "<", "0", "or", "self", ".", "rwlock", "==", "self", ".", "max_reader_concurrency", "or", "self", ".", "writers_waiting", ":", "self", ".", "readers_ok", ".", "wait", "(", ")", "self", ".", "rwlock", "+=", "1" ]
Acquire a read lock, several threads can hold this type of lock.
[ "Acquire", "a", "read", "lock", "several", "threads", "can", "hold", "this", "type", "of", "lock", "." ]
f113eb3cd751eed5ab5373e8610a31a444220cf8
https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/utils.py#L73-L80
train
1,182
SylvanasSun/python-common-cache
common_cache/utils.py
RWLock.acquire_writer
def acquire_writer(self): """ Acquire a write lock, only one thread can hold this lock and only when no read locks are also held. """ with self.mutex: while self.rwlock != 0: self._writer_wait() self.rwlock = -1
python
def acquire_writer(self): """ Acquire a write lock, only one thread can hold this lock and only when no read locks are also held. """ with self.mutex: while self.rwlock != 0: self._writer_wait() self.rwlock = -1
[ "def", "acquire_writer", "(", "self", ")", ":", "with", "self", ".", "mutex", ":", "while", "self", ".", "rwlock", "!=", "0", ":", "self", ".", "_writer_wait", "(", ")", "self", ".", "rwlock", "=", "-", "1" ]
Acquire a write lock, only one thread can hold this lock and only when no read locks are also held.
[ "Acquire", "a", "write", "lock", "only", "one", "thread", "can", "hold", "this", "lock", "and", "only", "when", "no", "read", "locks", "are", "also", "held", "." ]
f113eb3cd751eed5ab5373e8610a31a444220cf8
https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/utils.py#L82-L90
train
1,183
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.list
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit returned list length. :param page: (optional) Page to return. :return: :class:`packages.Page <packages.Page>` object """ schema = PackageSchema(exclude=('testlist', 'extra_cli_args', 'agent_id', 'options', 'note')) resp = self.service.list(self.base, filter, type, sort, limit, page) ps, l = self.service.decode(schema, resp, many=True, links=True) return Page(ps, l)
python
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit returned list length. :param page: (optional) Page to return. :return: :class:`packages.Page <packages.Page>` object """ schema = PackageSchema(exclude=('testlist', 'extra_cli_args', 'agent_id', 'options', 'note')) resp = self.service.list(self.base, filter, type, sort, limit, page) ps, l = self.service.decode(schema, resp, many=True, links=True) return Page(ps, l)
[ "def", "list", "(", "self", ",", "filter", "=", "None", ",", "type", "=", "None", ",", "sort", "=", "None", ",", "limit", "=", "None", ",", "page", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "schema", "=", "PackageSchema", "(", "exclude", "=", "(", "'testlist'", ",", "'extra_cli_args'", ",", "'agent_id'", ",", "'options'", ",", "'note'", ")", ")", "resp", "=", "self", ".", "service", ".", "list", "(", "self", ".", "base", ",", "filter", ",", "type", ",", "sort", ",", "limit", ",", "page", ")", "ps", ",", "l", "=", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ",", "many", "=", "True", ",", "links", "=", "True", ")", "return", "Page", "(", "ps", ",", "l", ")" ]
Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit returned list length. :param page: (optional) Page to return. :return: :class:`packages.Page <packages.Page>` object
[ "Get", "a", "list", "of", "packages", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L190-L203
train
1,184
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.get
def get(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema() resp = self.service.get_id(self.base, id) return self.service.decode(schema, resp)
python
def get(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema() resp = self.service.get_id(self.base, id) return self.service.decode(schema, resp)
[ "def", "get", "(", "self", ",", "id", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "PackageSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get_id", "(", "self", ".", "base", ",", "id", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
[ "Get", "a", "package", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L218-L227
train
1,185
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.create
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated', 'test_count', 'agent_id', 'result_id')) json = self.service.encode(schema, resource) schema = PackageSchema() resp = self.service.create(self.base, json) return self.service.decode(schema, resp)
python
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated', 'test_count', 'agent_id', 'result_id')) json = self.service.encode(schema, resource) schema = PackageSchema() resp = self.service.create(self.base, json) return self.service.decode(schema, resp)
[ "def", "create", "(", "self", ",", "resource", ")", ":", "schema", "=", "PackageSchema", "(", "exclude", "=", "(", "'id'", ",", "'created'", ",", "'updated'", ",", "'test_count'", ",", "'agent_id'", ",", "'result_id'", ")", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "resource", ")", "schema", "=", "PackageSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "create", "(", "self", ".", "base", ",", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
[ "Create", "a", "new", "package", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L241-L253
train
1,186
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.analyze
def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis """ schema = AnalysisSchema() resp = self.service.post(self.base+str(id)+'/', params={'process': 'analyze'}) return self.service.decode(schema, resp)
python
def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis """ schema = AnalysisSchema() resp = self.service.post(self.base+str(id)+'/', params={'process': 'analyze'}) return self.service.decode(schema, resp)
[ "def", "analyze", "(", "self", ",", "id", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "AnalysisSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "str", "(", "id", ")", "+", "'/'", ",", "params", "=", "{", "'process'", ":", "'analyze'", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis
[ "Get", "a", "list", "of", "tests", "that", "will", "be", "skipped", "for", "a", "package", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L301-L310
train
1,187
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.bulk_copy
def bulk_copy(self, ids): """Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list """ schema = PackageSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
python
def bulk_copy(self, ids): """Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list """ schema = PackageSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
[ "def", "bulk_copy", "(", "self", ",", "ids", ")", ":", "schema", "=", "PackageSchema", "(", ")", "return", "self", ".", "service", ".", "bulk_copy", "(", "self", ".", "base", ",", "self", ".", "RESOURCE", ",", "ids", ",", "schema", ")" ]
Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list
[ "Bulk", "copy", "a", "set", "of", "packages", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L320-L327
train
1,188
qacafe/cdrouter.py
cdrouter/packages.py
PackagesService.bulk_edit
def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply to all if bool `True`. """ schema = PackageSchema(exclude=('id', 'created', 'updated', 'test_count', 'agent_id', 'result_id')) _fields = self.service.encode(schema, _fields, skip_none=True) return self.service.bulk_edit(self.base, self.RESOURCE, _fields, ids=ids, filter=filter, type=type, all=all)
python
def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply to all if bool `True`. """ schema = PackageSchema(exclude=('id', 'created', 'updated', 'test_count', 'agent_id', 'result_id')) _fields = self.service.encode(schema, _fields, skip_none=True) return self.service.bulk_edit(self.base, self.RESOURCE, _fields, ids=ids, filter=filter, type=type, all=all)
[ "def", "bulk_edit", "(", "self", ",", "_fields", ",", "ids", "=", "None", ",", "filter", "=", "None", ",", "type", "=", "None", ",", "all", "=", "False", ")", ":", "# pylint: disable=redefined-builtin", "schema", "=", "PackageSchema", "(", "exclude", "=", "(", "'id'", ",", "'created'", ",", "'updated'", ",", "'test_count'", ",", "'agent_id'", ",", "'result_id'", ")", ")", "_fields", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "_fields", ",", "skip_none", "=", "True", ")", "return", "self", ".", "service", ".", "bulk_edit", "(", "self", ".", "base", ",", "self", ".", "RESOURCE", ",", "_fields", ",", "ids", "=", "ids", ",", "filter", "=", "filter", ",", "type", "=", "type", ",", "all", "=", "all", ")" ]
Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply to all if bool `True`.
[ "Bulk", "edit", "a", "set", "of", "packages", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L329-L341
train
1,189
NetworkAutomation/jaide
jaide/utils.py
clean_lines
def clean_lines(commands): """ Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It | will crop out any comments or blank lines, and yield | individual strings. | | Only strings that do not start with a comment '#', or are not | entirely whitespace will be yielded. This allows a file with | comments and blank lines for formatting neatness to be used | without a problem. @param commands: This can be either a string that is a file | location, a comma separated string of strings | ('x,y,z,1,2,3'), or a python list of strings. @type commands: str or list @returns: Yields each command in order @rtype: iterable of str """ if isinstance(commands, basestring): # if the command argument is a filename, we need to open it. if path.isfile(commands): commands = open(commands, 'rb') # if the command string is a comma separated list, break it up. elif len(commands.split(',')) > 1: commands = commands.split(',') else: # if a single command, need to just be returned. try: if commands.strip()[0] != "#": yield commands.strip() + '\n' return except IndexError: pass elif isinstance(commands, list): pass else: raise TypeError('clean_lines() accepts a \'str\' or \'list\'') for cmd in commands: # exclude commented lines, and skip blank lines (index error) try: if cmd.strip()[0] != "#": yield cmd.strip() + '\n' except IndexError: pass
python
def clean_lines(commands): """ Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It | will crop out any comments or blank lines, and yield | individual strings. | | Only strings that do not start with a comment '#', or are not | entirely whitespace will be yielded. This allows a file with | comments and blank lines for formatting neatness to be used | without a problem. @param commands: This can be either a string that is a file | location, a comma separated string of strings | ('x,y,z,1,2,3'), or a python list of strings. @type commands: str or list @returns: Yields each command in order @rtype: iterable of str """ if isinstance(commands, basestring): # if the command argument is a filename, we need to open it. if path.isfile(commands): commands = open(commands, 'rb') # if the command string is a comma separated list, break it up. elif len(commands.split(',')) > 1: commands = commands.split(',') else: # if a single command, need to just be returned. try: if commands.strip()[0] != "#": yield commands.strip() + '\n' return except IndexError: pass elif isinstance(commands, list): pass else: raise TypeError('clean_lines() accepts a \'str\' or \'list\'') for cmd in commands: # exclude commented lines, and skip blank lines (index error) try: if cmd.strip()[0] != "#": yield cmd.strip() + '\n' except IndexError: pass
[ "def", "clean_lines", "(", "commands", ")", ":", "if", "isinstance", "(", "commands", ",", "basestring", ")", ":", "# if the command argument is a filename, we need to open it.", "if", "path", ".", "isfile", "(", "commands", ")", ":", "commands", "=", "open", "(", "commands", ",", "'rb'", ")", "# if the command string is a comma separated list, break it up.", "elif", "len", "(", "commands", ".", "split", "(", "','", ")", ")", ">", "1", ":", "commands", "=", "commands", ".", "split", "(", "','", ")", "else", ":", "# if a single command, need to just be returned.", "try", ":", "if", "commands", ".", "strip", "(", ")", "[", "0", "]", "!=", "\"#\"", ":", "yield", "commands", ".", "strip", "(", ")", "+", "'\\n'", "return", "except", "IndexError", ":", "pass", "elif", "isinstance", "(", "commands", ",", "list", ")", ":", "pass", "else", ":", "raise", "TypeError", "(", "'clean_lines() accepts a \\'str\\' or \\'list\\''", ")", "for", "cmd", "in", "commands", ":", "# exclude commented lines, and skip blank lines (index error)", "try", ":", "if", "cmd", ".", "strip", "(", ")", "[", "0", "]", "!=", "\"#\"", ":", "yield", "cmd", ".", "strip", "(", ")", "+", "'\\n'", "except", "IndexError", ":", "pass" ]
Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It | will crop out any comments or blank lines, and yield | individual strings. | | Only strings that do not start with a comment '#', or are not | entirely whitespace will be yielded. This allows a file with | comments and blank lines for formatting neatness to be used | without a problem. @param commands: This can be either a string that is a file | location, a comma separated string of strings | ('x,y,z,1,2,3'), or a python list of strings. @type commands: str or list @returns: Yields each command in order @rtype: iterable of str
[ "Generate", "strings", "that", "are", "not", "comments", "or", "lines", "with", "only", "whitespace", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/utils.py#L8-L54
train
1,190
NetworkAutomation/jaide
jaide/utils.py
xpath
def xpath(source_xml, xpath_expr, req_format='string'): """ Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return | an xml object if desired. @param source_xml: Plain text XML that will be filtered @type source_xml: str or lxml.etree.ElementTree.Element object @param xpath_expr: Xpath expression that we will filter the XML by. @type xpath_expr: str @param req_format: the desired format of the response, accepts string or | xml. @type req_format: str @returns: The filtered XML if filtering was successful. Otherwise, | an empty string. @rtype: str or ElementTree """ tree = source_xml if not isinstance(source_xml, ET.Element): tree = objectify.fromstring(source_xml) # clean up the namespace in the tags, as namespaces appear to confuse # xpath method for elem in tree.getiterator(): # beware of factory functions such as Comment if isinstance(elem.tag, basestring): i = elem.tag.find('}') if i >= 0: elem.tag = elem.tag[i+1:] # remove unused namespaces objectify.deannotate(tree, cleanup_namespaces=True) filtered_list = tree.xpath(xpath_expr) # Return string from the list of Elements or pure xml if req_format == 'xml': return filtered_list matches = ''.join(etree.tostring( element, pretty_print=True) for element in filtered_list) return matches if matches else ""
python
def xpath(source_xml, xpath_expr, req_format='string'): """ Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return | an xml object if desired. @param source_xml: Plain text XML that will be filtered @type source_xml: str or lxml.etree.ElementTree.Element object @param xpath_expr: Xpath expression that we will filter the XML by. @type xpath_expr: str @param req_format: the desired format of the response, accepts string or | xml. @type req_format: str @returns: The filtered XML if filtering was successful. Otherwise, | an empty string. @rtype: str or ElementTree """ tree = source_xml if not isinstance(source_xml, ET.Element): tree = objectify.fromstring(source_xml) # clean up the namespace in the tags, as namespaces appear to confuse # xpath method for elem in tree.getiterator(): # beware of factory functions such as Comment if isinstance(elem.tag, basestring): i = elem.tag.find('}') if i >= 0: elem.tag = elem.tag[i+1:] # remove unused namespaces objectify.deannotate(tree, cleanup_namespaces=True) filtered_list = tree.xpath(xpath_expr) # Return string from the list of Elements or pure xml if req_format == 'xml': return filtered_list matches = ''.join(etree.tostring( element, pretty_print=True) for element in filtered_list) return matches if matches else ""
[ "def", "xpath", "(", "source_xml", ",", "xpath_expr", ",", "req_format", "=", "'string'", ")", ":", "tree", "=", "source_xml", "if", "not", "isinstance", "(", "source_xml", ",", "ET", ".", "Element", ")", ":", "tree", "=", "objectify", ".", "fromstring", "(", "source_xml", ")", "# clean up the namespace in the tags, as namespaces appear to confuse", "# xpath method", "for", "elem", "in", "tree", ".", "getiterator", "(", ")", ":", "# beware of factory functions such as Comment", "if", "isinstance", "(", "elem", ".", "tag", ",", "basestring", ")", ":", "i", "=", "elem", ".", "tag", ".", "find", "(", "'}'", ")", "if", "i", ">=", "0", ":", "elem", ".", "tag", "=", "elem", ".", "tag", "[", "i", "+", "1", ":", "]", "# remove unused namespaces", "objectify", ".", "deannotate", "(", "tree", ",", "cleanup_namespaces", "=", "True", ")", "filtered_list", "=", "tree", ".", "xpath", "(", "xpath_expr", ")", "# Return string from the list of Elements or pure xml", "if", "req_format", "==", "'xml'", ":", "return", "filtered_list", "matches", "=", "''", ".", "join", "(", "etree", ".", "tostring", "(", "element", ",", "pretty_print", "=", "True", ")", "for", "element", "in", "filtered_list", ")", "return", "matches", "if", "matches", "else", "\"\"" ]
Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return | an xml object if desired. @param source_xml: Plain text XML that will be filtered @type source_xml: str or lxml.etree.ElementTree.Element object @param xpath_expr: Xpath expression that we will filter the XML by. @type xpath_expr: str @param req_format: the desired format of the response, accepts string or | xml. @type req_format: str @returns: The filtered XML if filtering was successful. Otherwise, | an empty string. @rtype: str or ElementTree
[ "Filter", "xml", "based", "on", "an", "xpath", "expression", "." ]
8571b987a8c24c246dc09f1bcc11cb0f045ec33f
https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/utils.py#L57-L97
train
1,191
crossbario/txaio-etcd
txaioetcd/_client_tx.py
Client.set
def set(self, key, value, lease=None, return_previous=None, timeout=None): """ Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the key, in bytes, to put into the key-value store. :type key: bytes :param value: value is the value, in bytes, to associate with the key in the key-value store. :key value: bytes :param lease: Lease to associate the key in the key-value store with. :type lease: instance of :class:`txaioetcd.Lease` or None :param return_previous: If set, return the previous key-value. :type return_previous: bool or None :param timeout: Request timeout in seconds. :type timeout: int :returns: Revision info :rtype: instance of :class:`txaioetcd.Revision` """ assembler = commons.PutRequestAssembler(self._url, key, value, lease, return_previous) obj = yield self._post(assembler.url, assembler.data, timeout) revision = Revision._parse(obj) returnValue(revision)
python
def set(self, key, value, lease=None, return_previous=None, timeout=None): """ Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the key, in bytes, to put into the key-value store. :type key: bytes :param value: value is the value, in bytes, to associate with the key in the key-value store. :key value: bytes :param lease: Lease to associate the key in the key-value store with. :type lease: instance of :class:`txaioetcd.Lease` or None :param return_previous: If set, return the previous key-value. :type return_previous: bool or None :param timeout: Request timeout in seconds. :type timeout: int :returns: Revision info :rtype: instance of :class:`txaioetcd.Revision` """ assembler = commons.PutRequestAssembler(self._url, key, value, lease, return_previous) obj = yield self._post(assembler.url, assembler.data, timeout) revision = Revision._parse(obj) returnValue(revision)
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "lease", "=", "None", ",", "return_previous", "=", "None", ",", "timeout", "=", "None", ")", ":", "assembler", "=", "commons", ".", "PutRequestAssembler", "(", "self", ".", "_url", ",", "key", ",", "value", ",", "lease", ",", "return_previous", ")", "obj", "=", "yield", "self", ".", "_post", "(", "assembler", ".", "url", ",", "assembler", ".", "data", ",", "timeout", ")", "revision", "=", "Revision", ".", "_parse", "(", "obj", ")", "returnValue", "(", "revision", ")" ]
Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the key, in bytes, to put into the key-value store. :type key: bytes :param value: value is the value, in bytes, to associate with the key in the key-value store. :key value: bytes :param lease: Lease to associate the key in the key-value store with. :type lease: instance of :class:`txaioetcd.Lease` or None :param return_previous: If set, return the previous key-value. :type return_previous: bool or None :param timeout: Request timeout in seconds. :type timeout: int :returns: Revision info :rtype: instance of :class:`txaioetcd.Revision`
[ "Set", "the", "value", "for", "the", "key", "in", "the", "key", "-", "value", "store", "." ]
c9aebff7f288a0b219bffc9d2579d22cf543baa5
https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_client_tx.py#L256-L291
train
1,192
crossbario/txaio-etcd
txaioetcd/_client_tx.py
Client.watch
def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None): """ Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these keys / key sets. :type keys: list of bytes or list of instance of :class:`txaioetcd.KeySet` :param on_watch: The callback to invoke upon receiving a watch event. :type on_watch: callable :param filters: Any filters to apply. :param start_revision: start_revision is an optional revision to watch from (inclusive). No start_revision is "now". :type start_revision: int :param return_previous: Flag to request returning previous values. :returns: A deferred that just fires when watching has started successfully, or which fires with an error in case the watching could not be started. :rtype: twisted.internet.Deferred """ d = self._start_watching(keys, on_watch, filters, start_revision, return_previous) # # ODD: Trying to use a parameter instead of *args errors out as soon as the # parameter is accessed. # def on_err(*args): if args[0].type not in [CancelledError, ResponseFailed]: self.log.warn('etcd watch terminated with "{error}"', error=args[0].type) return args[0] d.addErrback(on_err) return d
python
def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None): """ Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these keys / key sets. :type keys: list of bytes or list of instance of :class:`txaioetcd.KeySet` :param on_watch: The callback to invoke upon receiving a watch event. :type on_watch: callable :param filters: Any filters to apply. :param start_revision: start_revision is an optional revision to watch from (inclusive). No start_revision is "now". :type start_revision: int :param return_previous: Flag to request returning previous values. :returns: A deferred that just fires when watching has started successfully, or which fires with an error in case the watching could not be started. :rtype: twisted.internet.Deferred """ d = self._start_watching(keys, on_watch, filters, start_revision, return_previous) # # ODD: Trying to use a parameter instead of *args errors out as soon as the # parameter is accessed. # def on_err(*args): if args[0].type not in [CancelledError, ResponseFailed]: self.log.warn('etcd watch terminated with "{error}"', error=args[0].type) return args[0] d.addErrback(on_err) return d
[ "def", "watch", "(", "self", ",", "keys", ",", "on_watch", ",", "filters", "=", "None", ",", "start_revision", "=", "None", ",", "return_previous", "=", "None", ")", ":", "d", "=", "self", ".", "_start_watching", "(", "keys", ",", "on_watch", ",", "filters", ",", "start_revision", ",", "return_previous", ")", "#", "# ODD: Trying to use a parameter instead of *args errors out as soon as the", "# parameter is accessed.", "#", "def", "on_err", "(", "*", "args", ")", ":", "if", "args", "[", "0", "]", ".", "type", "not", "in", "[", "CancelledError", ",", "ResponseFailed", "]", ":", "self", ".", "log", ".", "warn", "(", "'etcd watch terminated with \"{error}\"'", ",", "error", "=", "args", "[", "0", "]", ".", "type", ")", "return", "args", "[", "0", "]", "d", ".", "addErrback", "(", "on_err", ")", "return", "d" ]
Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these keys / key sets. :type keys: list of bytes or list of instance of :class:`txaioetcd.KeySet` :param on_watch: The callback to invoke upon receiving a watch event. :type on_watch: callable :param filters: Any filters to apply. :param start_revision: start_revision is an optional revision to watch from (inclusive). No start_revision is "now". :type start_revision: int :param return_previous: Flag to request returning previous values. :returns: A deferred that just fires when watching has started successfully, or which fires with an error in case the watching could not be started. :rtype: twisted.internet.Deferred
[ "Watch", "one", "or", "more", "keys", "or", "key", "sets", "and", "invoke", "a", "callback", "." ]
c9aebff7f288a0b219bffc9d2579d22cf543baa5
https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_client_tx.py#L408-L446
train
1,193
crossbario/txaio-etcd
txaioetcd/_client_tx.py
Client.lease
def lease(self, time_to_live, lease_id=None, timeout=None): """ Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired key generates a delete event in the event history. :param time_to_live: TTL is the advisory time-to-live in seconds. :type time_to_live: int :param lease_id: ID is the requested ID for the lease. If ID is None, the lessor (etcd) chooses an ID. :type lease_id: int or None :param timeout: Request timeout in seconds. :type timeout: int :returns: A lease object representing the created lease. This can be used for refreshing or revoking the least etc. :rtype: instance of :class:`txaioetcd.Lease` """ assembler = commons.LeaseRequestAssembler(self._url, time_to_live, lease_id) obj = yield self._post(assembler.url, assembler.data, timeout) lease = Lease._parse(self, obj) returnValue(lease)
python
def lease(self, time_to_live, lease_id=None, timeout=None): """ Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired key generates a delete event in the event history. :param time_to_live: TTL is the advisory time-to-live in seconds. :type time_to_live: int :param lease_id: ID is the requested ID for the lease. If ID is None, the lessor (etcd) chooses an ID. :type lease_id: int or None :param timeout: Request timeout in seconds. :type timeout: int :returns: A lease object representing the created lease. This can be used for refreshing or revoking the least etc. :rtype: instance of :class:`txaioetcd.Lease` """ assembler = commons.LeaseRequestAssembler(self._url, time_to_live, lease_id) obj = yield self._post(assembler.url, assembler.data, timeout) lease = Lease._parse(self, obj) returnValue(lease)
[ "def", "lease", "(", "self", ",", "time_to_live", ",", "lease_id", "=", "None", ",", "timeout", "=", "None", ")", ":", "assembler", "=", "commons", ".", "LeaseRequestAssembler", "(", "self", ".", "_url", ",", "time_to_live", ",", "lease_id", ")", "obj", "=", "yield", "self", ".", "_post", "(", "assembler", ".", "url", ",", "assembler", ".", "data", ",", "timeout", ")", "lease", "=", "Lease", ".", "_parse", "(", "self", ",", "obj", ")", "returnValue", "(", "lease", ")" ]
Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired key generates a delete event in the event history. :param time_to_live: TTL is the advisory time-to-live in seconds. :type time_to_live: int :param lease_id: ID is the requested ID for the lease. If ID is None, the lessor (etcd) chooses an ID. :type lease_id: int or None :param timeout: Request timeout in seconds. :type timeout: int :returns: A lease object representing the created lease. This can be used for refreshing or revoking the least etc. :rtype: instance of :class:`txaioetcd.Lease`
[ "Creates", "a", "lease", "which", "expires", "if", "the", "server", "does", "not", "receive", "a", "keep", "alive", "within", "a", "given", "time", "to", "live", "period", "." ]
c9aebff7f288a0b219bffc9d2579d22cf543baa5
https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_client_tx.py#L590-L620
train
1,194
qacafe/cdrouter.py
cdrouter/imports.py
ImportsService.stage_import_from_file
def stage_import_from_file(self, fd, filename='upload.gz'): """Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, files={'file': (filename, fd)}) return self.service.decode(schema, resp)
python
def stage_import_from_file(self, fd, filename='upload.gz'): """Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, files={'file': (filename, fd)}) return self.service.decode(schema, resp)
[ "def", "stage_import_from_file", "(", "self", ",", "fd", ",", "filename", "=", "'upload.gz'", ")", ":", "schema", "=", "ImportSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", ",", "files", "=", "{", "'file'", ":", "(", "filename", ",", "fd", ")", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object
[ "Stage", "an", "import", "from", "a", "file", "upload", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/imports.py#L153-L163
train
1,195
qacafe/cdrouter.py
cdrouter/imports.py
ImportsService.stage_import_from_filesystem
def stage_import_from_filesystem(self, filepath): """Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, params={'path': filepath}) return self.service.decode(schema, resp)
python
def stage_import_from_filesystem(self, filepath): """Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, params={'path': filepath}) return self.service.decode(schema, resp)
[ "def", "stage_import_from_filesystem", "(", "self", ",", "filepath", ")", ":", "schema", "=", "ImportSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", ",", "params", "=", "{", "'path'", ":", "filepath", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object
[ "Stage", "an", "import", "from", "a", "filesystem", "path", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/imports.py#L165-L174
train
1,196
qacafe/cdrouter.py
cdrouter/imports.py
ImportsService.stage_import_from_url
def stage_import_from_url(self, url, token=None, username=None, password=None, insecure=False): """Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ system). :param username: (optional) API username to use as string (may be required if importing from a CDRouter 10+ system). :param password: (optional) API password to use as string (may be required if importing from a CDRouter 10+ system). :param insecure: (optional) Allow insecure HTTPS connections if bool `True`. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, params={'url': url, 'token': token, 'username': username, 'password': password, 'insecure': insecure}) return self.service.decode(schema, resp)
python
def stage_import_from_url(self, url, token=None, username=None, password=None, insecure=False): """Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ system). :param username: (optional) API username to use as string (may be required if importing from a CDRouter 10+ system). :param password: (optional) API password to use as string (may be required if importing from a CDRouter 10+ system). :param insecure: (optional) Allow insecure HTTPS connections if bool `True`. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, params={'url': url, 'token': token, 'username': username, 'password': password, 'insecure': insecure}) return self.service.decode(schema, resp)
[ "def", "stage_import_from_url", "(", "self", ",", "url", ",", "token", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "insecure", "=", "False", ")", ":", "schema", "=", "ImportSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", ",", "params", "=", "{", "'url'", ":", "url", ",", "'token'", ":", "token", ",", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "'insecure'", ":", "insecure", "}", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ system). :param username: (optional) API username to use as string (may be required if importing from a CDRouter 10+ system). :param password: (optional) API password to use as string (may be required if importing from a CDRouter 10+ system). :param insecure: (optional) Allow insecure HTTPS connections if bool `True`. :return: :class:`imports.Import <imports.Import>` object
[ "Stage", "an", "import", "from", "a", "URL", "to", "another", "CDRouter", "system", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/imports.py#L176-L189
train
1,197
qacafe/cdrouter.py
cdrouter/imports.py
ImportsService.get_commit_request
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestSchema() resp = self.service.get(self.base+str(id)+'/request/') return self.service.decode(schema, resp)
python
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestSchema() resp = self.service.get(self.base+str(id)+'/request/') return self.service.decode(schema, resp)
[ "def", "get_commit_request", "(", "self", ",", "id", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "RequestSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get", "(", "self", ".", "base", "+", "str", "(", "id", ")", "+", "'/request/'", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
[ "Get", "a", "commit", "request", "for", "a", "staged", "import", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/imports.py#L202-L211
train
1,198
qacafe/cdrouter.py
cdrouter/imports.py
ImportsService.commit
def commit(self, id, impreq): # pylint: disable=invalid-name,redefined-builtin """Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestSchema() json = self.service.encode(schema, impreq) schema = RequestSchema() resp = self.service.post(self.base+str(id)+'/', json=json) return self.service.decode(schema, resp)
python
def commit(self, id, impreq): # pylint: disable=invalid-name,redefined-builtin """Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestSchema() json = self.service.encode(schema, impreq) schema = RequestSchema() resp = self.service.post(self.base+str(id)+'/', json=json) return self.service.decode(schema, resp)
[ "def", "commit", "(", "self", ",", "id", ",", "impreq", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "RequestSchema", "(", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "impreq", ")", "schema", "=", "RequestSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "str", "(", "id", ")", "+", "'/'", ",", "json", "=", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
[ "Commit", "a", "staged", "import", "." ]
aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/imports.py#L213-L226
train
1,199