repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_organization
def create_organization(self, auth, owner_name, org_name, full_name=None, description=None, website=None, location=None): """ Creates a new organization, and returns the created organization. :param auth.Authentication auth: authentication object, must be admin-level :param str owner_name: Username of organization owner :param str org_name: Organization name :param str full_name: Full name of organization :param str description: Description of the organization :param str website: Official website :param str location: Organization location :return: a representation of the created organization :rtype: GogsOrg :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "username": org_name, "full_name": full_name, "description": description, "website": website, "location": location } url = "/admin/users/{u}/orgs".format(u=owner_name) response = self.post(url, auth=auth, data=data) return GogsOrg.from_json(response.json())
python
def create_organization(self, auth, owner_name, org_name, full_name=None, description=None, website=None, location=None): """ Creates a new organization, and returns the created organization. :param auth.Authentication auth: authentication object, must be admin-level :param str owner_name: Username of organization owner :param str org_name: Organization name :param str full_name: Full name of organization :param str description: Description of the organization :param str website: Official website :param str location: Organization location :return: a representation of the created organization :rtype: GogsOrg :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "username": org_name, "full_name": full_name, "description": description, "website": website, "location": location } url = "/admin/users/{u}/orgs".format(u=owner_name) response = self.post(url, auth=auth, data=data) return GogsOrg.from_json(response.json())
[ "def", "create_organization", "(", "self", ",", "auth", ",", "owner_name", ",", "org_name", ",", "full_name", "=", "None", ",", "description", "=", "None", ",", "website", "=", "None", ",", "location", "=", "None", ")", ":", "data", "=", "{", "\"username...
Creates a new organization, and returns the created organization. :param auth.Authentication auth: authentication object, must be admin-level :param str owner_name: Username of organization owner :param str org_name: Organization name :param str full_name: Full name of organization :param str description: Description of the organization :param str website: Official website :param str location: Organization location :return: a representation of the created organization :rtype: GogsOrg :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "organization", "and", "returns", "the", "created", "organization", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L462-L489
train
49,000
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_organization_team
def create_organization_team(self, auth, org_name, name, description=None, permission="read"): """ Creates a new team of the organization. :param auth.Authentication auth: authentication object, must be admin-level :param str org_name: Organization user name :param str name: Full name of the team :param str description: Description of the team :param str permission: Team permission, can be read, write or admin, default is read :return: a representation of the created team :rtype: GogsTeam :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "name": name, "description": description, "permission": permission } url = "/admin/orgs/{o}/teams".format(o=org_name) response = self.post(url, auth=auth, data=data) return GogsTeam.from_json(response.json())
python
def create_organization_team(self, auth, org_name, name, description=None, permission="read"): """ Creates a new team of the organization. :param auth.Authentication auth: authentication object, must be admin-level :param str org_name: Organization user name :param str name: Full name of the team :param str description: Description of the team :param str permission: Team permission, can be read, write or admin, default is read :return: a representation of the created team :rtype: GogsTeam :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "name": name, "description": description, "permission": permission } url = "/admin/orgs/{o}/teams".format(o=org_name) response = self.post(url, auth=auth, data=data) return GogsTeam.from_json(response.json())
[ "def", "create_organization_team", "(", "self", ",", "auth", ",", "org_name", ",", "name", ",", "description", "=", "None", ",", "permission", "=", "\"read\"", ")", ":", "data", "=", "{", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", ...
Creates a new team of the organization. :param auth.Authentication auth: authentication object, must be admin-level :param str org_name: Organization user name :param str name: Full name of the team :param str description: Description of the team :param str permission: Team permission, can be read, write or admin, default is read :return: a representation of the created team :rtype: GogsTeam :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "team", "of", "the", "organization", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L491-L513
train
49,001
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.add_team_membership
def add_team_membership(self, auth, team_id, username): """ Add user to team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be added to team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username) self.put(url, auth=auth)
python
def add_team_membership(self, auth, team_id, username): """ Add user to team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be added to team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username) self.put(url, auth=auth)
[ "def", "add_team_membership", "(", "self", ",", "auth", ",", "team_id", ",", "username", ")", ":", "url", "=", "\"/admin/teams/{t}/members/{u}\"", ".", "format", "(", "t", "=", "team_id", ",", "u", "=", "username", ")", "self", ".", "put", "(", "url", ",...
Add user to team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be added to team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Add", "user", "to", "team", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L515-L526
train
49,002
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.remove_team_membership
def remove_team_membership(self, auth, team_id, username): """ Remove user from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username) self.delete(url, auth=auth)
python
def remove_team_membership(self, auth, team_id, username): """ Remove user from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username) self.delete(url, auth=auth)
[ "def", "remove_team_membership", "(", "self", ",", "auth", ",", "team_id", ",", "username", ")", ":", "url", "=", "\"/admin/teams/{t}/members/{u}\"", ".", "format", "(", "t", "=", "team_id", ",", "u", "=", "username", ")", "self", ".", "delete", "(", "url"...
Remove user from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Remove", "user", "from", "team", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L528-L539
train
49,003
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.add_repo_to_team
def add_repo_to_team(self, auth, team_id, repo_name): """ Add or update repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be added to the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/repos/{r}".format(t=team_id, r=repo_name) self.put(url, auth=auth)
python
def add_repo_to_team(self, auth, team_id, repo_name): """ Add or update repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be added to the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ url = "/admin/teams/{t}/repos/{r}".format(t=team_id, r=repo_name) self.put(url, auth=auth)
[ "def", "add_repo_to_team", "(", "self", ",", "auth", ",", "team_id", ",", "repo_name", ")", ":", "url", "=", "\"/admin/teams/{t}/repos/{r}\"", ".", "format", "(", "t", "=", "team_id", ",", "r", "=", "repo_name", ")", "self", ".", "put", "(", "url", ",", ...
Add or update repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be added to the team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Add", "or", "update", "repo", "from", "team", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L541-L552
train
49,004
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.list_deploy_keys
def list_deploy_keys(self, auth, username, repo_name): """ List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of deploy keys for the repo :rtype: List[GogsRepo.DeployKey] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth) return [GogsRepo.DeployKey.from_json(key_json) for key_json in response.json()]
python
def list_deploy_keys(self, auth, username, repo_name): """ List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of deploy keys for the repo :rtype: List[GogsRepo.DeployKey] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth) return [GogsRepo.DeployKey.from_json(key_json) for key_json in response.json()]
[ "def", "list_deploy_keys", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "response", "=", "self", ".", "get", "(", "\"/repos/{u}/{r}/keys\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", ",", "auth",...
List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of deploy keys for the repo :rtype: List[GogsRepo.DeployKey] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "List", "deploy", "keys", "for", "the", "specified", "repo", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L567-L580
train
49,005
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_deploy_key
def get_deploy_key(self, auth, username, repo_name, key_id): """ Get a deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :return: the deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth) return GogsRepo.DeployKey.from_json(response.json())
python
def get_deploy_key(self, auth, username, repo_name, key_id): """ Get a deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :return: the deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth) return GogsRepo.DeployKey.from_json(response.json())
[ "def", "get_deploy_key", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ",", "key_id", ")", ":", "response", "=", "self", ".", "get", "(", "\"/repos/{u}/{r}/keys/{k}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ...
Get a deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :return: the deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Get", "a", "deploy", "key", "for", "the", "specified", "repo", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L582-L596
train
49,006
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.add_deploy_key
def add_deploy_key(self, auth, username, repo_name, title, key_content): """ Add a deploy key to the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param str title: title of the key to add :param str key_content: content of the key to add :return: a representation of the added deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "title": title, "key": key_content } response = self.post("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth, data=data) return GogsRepo.DeployKey.from_json(response.json())
python
def add_deploy_key(self, auth, username, repo_name, title, key_content): """ Add a deploy key to the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param str title: title of the key to add :param str key_content: content of the key to add :return: a representation of the added deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ data = { "title": title, "key": key_content } response = self.post("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth, data=data) return GogsRepo.DeployKey.from_json(response.json())
[ "def", "add_deploy_key", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ",", "title", ",", "key_content", ")", ":", "data", "=", "{", "\"title\"", ":", "title", ",", "\"key\"", ":", "key_content", "}", "response", "=", "self", ".", "post", ...
Add a deploy key to the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param str title: title of the key to add :param str key_content: content of the key to add :return: a representation of the added deploy key :rtype: GogsRepo.DeployKey :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Add", "a", "deploy", "key", "to", "the", "specified", "repo", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L598-L617
train
49,007
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.delete_deploy_key
def delete_deploy_key(self, auth, username, repo_name, key_id): """ Remove deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ self.delete("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth)
python
def delete_deploy_key(self, auth, username, repo_name, key_id): """ Remove deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ self.delete("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth)
[ "def", "delete_deploy_key", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ",", "key_id", ")", ":", "self", ".", "delete", "(", "\"/repos/{u}/{r}/keys/{k}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ",", "k", "...
Remove deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Remove", "deploy", "key", "for", "the", "specified", "repo", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L619-L630
train
49,008
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.delete
def delete(self, path, auth=None, **kwargs): """ Manually make a DELETE request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._delete(path, auth=auth, **kwargs))
python
def delete(self, path, auth=None, **kwargs): """ Manually make a DELETE request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._delete(path, auth=auth, **kwargs))
[ "def", "delete", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_delete", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
Manually make a DELETE request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Manually", "make", "a", "DELETE", "request", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L642-L653
train
49,009
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get
def get(self, path, auth=None, **kwargs): """ Manually make a GET request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._get(path, auth=auth, **kwargs))
python
def get(self, path, auth=None, **kwargs): """ Manually make a GET request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._get(path, auth=auth, **kwargs))
[ "def", "get", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_get", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
Manually make a GET request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Manually", "make", "a", "GET", "request", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L663-L674
train
49,010
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.patch
def patch(self, path, auth=None, **kwargs): """ Manually make a PATCH request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._patch(path, auth=auth, **kwargs))
python
def patch(self, path, auth=None, **kwargs): """ Manually make a PATCH request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._patch(path, auth=auth, **kwargs))
[ "def", "patch", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_patch", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
Manually make a PATCH request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Manually", "make", "a", "PATCH", "request", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L684-L695
train
49,011
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.post
def post(self, path, auth=None, **kwargs): """ Manually make a POST request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._post(path, auth=auth, **kwargs))
python
def post(self, path, auth=None, **kwargs): """ Manually make a POST request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._post(path, auth=auth, **kwargs))
[ "def", "post", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_post", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
Manually make a POST request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Manually", "make", "a", "POST", "request", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L705-L716
train
49,012
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.put
def put(self, path, auth=None, **kwargs): """ Manually make a PUT request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._put(path, auth=auth, **kwargs))
python
def put(self, path, auth=None, **kwargs): """ Manually make a PUT request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ return self._check_ok(self._put(path, auth=auth, **kwargs))
[ "def", "put", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_put", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
Manually make a PUT request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.org/>`_ library. :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Manually", "make", "a", "PUT", "request", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L726-L737
train
49,013
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi._fail
def _fail(response): """ Raise an ApiFailure pertaining to the given response """ message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url) try: message += ", message:{}".format(response.json()["message"]) except (ValueError, KeyError): pass raise ApiFailure(message, response.status_code)
python
def _fail(response): """ Raise an ApiFailure pertaining to the given response """ message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url) try: message += ", message:{}".format(response.json()["message"]) except (ValueError, KeyError): pass raise ApiFailure(message, response.status_code)
[ "def", "_fail", "(", "response", ")", ":", "message", "=", "\"Status code: {}-{}, url: {}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "reason", ",", "response", ".", "url", ")", "try", ":", "message", "+=", "\", message:{}\"",...
Raise an ApiFailure pertaining to the given response
[ "Raise", "an", "ApiFailure", "pertaining", "to", "the", "given", "response" ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L749-L758
train
49,014
peterldowns/lggr
lggr/__init__.py
Printer
def Printer(open_file=sys.stdout, closing=False): """ Prints items with a timestamp. """ try: while True: logstr = (yield) open_file.write(logstr) open_file.write('\n') # new line except GeneratorExit: if closing: try: open_file.close() except: pass
python
def Printer(open_file=sys.stdout, closing=False): """ Prints items with a timestamp. """ try: while True: logstr = (yield) open_file.write(logstr) open_file.write('\n') # new line except GeneratorExit: if closing: try: open_file.close() except: pass
[ "def", "Printer", "(", "open_file", "=", "sys", ".", "stdout", ",", "closing", "=", "False", ")", ":", "try", ":", "while", "True", ":", "logstr", "=", "(", "yield", ")", "open_file", ".", "write", "(", "logstr", ")", "open_file", ".", "write", "(", ...
Prints items with a timestamp.
[ "Prints", "items", "with", "a", "timestamp", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L322-L332
train
49,015
peterldowns/lggr
lggr/__init__.py
FilePrinter
def FilePrinter(filename, mode='a', closing=True): path = os.path.abspath(os.path.expanduser(filename)) """ Opens the given file and returns a printer to it. """ f = open(path, mode) return Printer(f, closing)
python
def FilePrinter(filename, mode='a', closing=True): path = os.path.abspath(os.path.expanduser(filename)) """ Opens the given file and returns a printer to it. """ f = open(path, mode) return Printer(f, closing)
[ "def", "FilePrinter", "(", "filename", ",", "mode", "=", "'a'", ",", "closing", "=", "True", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "f", "=", "open", "(", "p...
Opens the given file and returns a printer to it.
[ "Opens", "the", "given", "file", "and", "returns", "a", "printer", "to", "it", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L338-L342
train
49,016
peterldowns/lggr
lggr/__init__.py
Emailer
def Emailer(recipients, sender=None): """ Sends messages as emails to the given list of recipients. """ import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib.SMTP('localhost') try: while True: logstr = (yield) try: smtp.sendmail(sender, recipients, logstr) except smtplib.SMTPException: pass except GeneratorExit: smtp.quit()
python
def Emailer(recipients, sender=None): """ Sends messages as emails to the given list of recipients. """ import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib.SMTP('localhost') try: while True: logstr = (yield) try: smtp.sendmail(sender, recipients, logstr) except smtplib.SMTPException: pass except GeneratorExit: smtp.quit()
[ "def", "Emailer", "(", "recipients", ",", "sender", "=", "None", ")", ":", "import", "smtplib", "hostname", "=", "socket", ".", "gethostname", "(", ")", "if", "not", "sender", ":", "sender", "=", "'lggr@{0}'", ".", "format", "(", "hostname", ")", "smtp",...
Sends messages as emails to the given list of recipients.
[ "Sends", "messages", "as", "emails", "to", "the", "given", "list", "of", "recipients", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L363-L379
train
49,017
peterldowns/lggr
lggr/__init__.py
GMailer
def GMailer(recipients, username, password, subject='Log message from lggr.py'): """ Sends messages as emails to the given list of recipients, from a GMail account. """ import smtplib srvr = smtplib.SMTP('smtp.gmail.com', 587) srvr.ehlo() srvr.starttls() srvr.ehlo() srvr.login(username, password) if not (isinstance(recipients, list) or isinstance(recipients, tuple)): recipients = [recipients] gmail_sender = '{0}@gmail.com'.format(username) msg = 'To: {0}\nFrom: '+gmail_sender+'\nSubject: '+subject+'\n' msg = msg + '\n{1}\n\n' try: while True: logstr = (yield) for rcp in recipients: message = msg.format(rcp, logstr) srvr.sendmail(gmail_sender, rcp, message) except GeneratorExit: srvr.quit()
python
def GMailer(recipients, username, password, subject='Log message from lggr.py'): """ Sends messages as emails to the given list of recipients, from a GMail account. """ import smtplib srvr = smtplib.SMTP('smtp.gmail.com', 587) srvr.ehlo() srvr.starttls() srvr.ehlo() srvr.login(username, password) if not (isinstance(recipients, list) or isinstance(recipients, tuple)): recipients = [recipients] gmail_sender = '{0}@gmail.com'.format(username) msg = 'To: {0}\nFrom: '+gmail_sender+'\nSubject: '+subject+'\n' msg = msg + '\n{1}\n\n' try: while True: logstr = (yield) for rcp in recipients: message = msg.format(rcp, logstr) srvr.sendmail(gmail_sender, rcp, message) except GeneratorExit: srvr.quit()
[ "def", "GMailer", "(", "recipients", ",", "username", ",", "password", ",", "subject", "=", "'Log message from lggr.py'", ")", ":", "import", "smtplib", "srvr", "=", "smtplib", ".", "SMTP", "(", "'smtp.gmail.com'", ",", "587", ")", "srvr", ".", "ehlo", "(", ...
Sends messages as emails to the given list of recipients, from a GMail account.
[ "Sends", "messages", "as", "emails", "to", "the", "given", "list", "of", "recipients", "from", "a", "GMail", "account", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L382-L407
train
49,018
peterldowns/lggr
lggr/__init__.py
Lggr.add
def add(self, levels, logger): """ Given a list or tuple of logging levels, add a logger instance to each. """ if isinstance(levels, (list, tuple)): for lvl in levels: self.config[lvl].add(logger) else: self.config[levels].add(logger)
python
def add(self, levels, logger): """ Given a list or tuple of logging levels, add a logger instance to each. """ if isinstance(levels, (list, tuple)): for lvl in levels: self.config[lvl].add(logger) else: self.config[levels].add(logger)
[ "def", "add", "(", "self", ",", "levels", ",", "logger", ")", ":", "if", "isinstance", "(", "levels", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "lvl", "in", "levels", ":", "self", ".", "config", "[", "lvl", "]", ".", "add", "(", "lo...
Given a list or tuple of logging levels, add a logger instance to each.
[ "Given", "a", "list", "or", "tuple", "of", "logging", "levels", "add", "a", "logger", "instance", "to", "each", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L84-L91
train
49,019
peterldowns/lggr
lggr/__init__.py
Lggr.remove
def remove(self, level, logger): """ Given a level, remove a given logger function if it is a member of that level, closing the logger function either way.""" self.config[level].discard(logger) logger.close()
python
def remove(self, level, logger): """ Given a level, remove a given logger function if it is a member of that level, closing the logger function either way.""" self.config[level].discard(logger) logger.close()
[ "def", "remove", "(", "self", ",", "level", ",", "logger", ")", ":", "self", ".", "config", "[", "level", "]", ".", "discard", "(", "logger", ")", "logger", ".", "close", "(", ")" ]
Given a level, remove a given logger function if it is a member of that level, closing the logger function either way.
[ "Given", "a", "level", "remove", "a", "given", "logger", "function", "if", "it", "is", "a", "member", "of", "that", "level", "closing", "the", "logger", "function", "either", "way", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L93-L98
train
49,020
peterldowns/lggr
lggr/__init__.py
Lggr.clear
def clear(self, level): """ Remove all logger functions from a given level. """ for item in self.config[level]: item.close() self.config[level].clear()
python
def clear(self, level): """ Remove all logger functions from a given level. """ for item in self.config[level]: item.close() self.config[level].clear()
[ "def", "clear", "(", "self", ",", "level", ")", ":", "for", "item", "in", "self", ".", "config", "[", "level", "]", ":", "item", ".", "close", "(", ")", "self", ".", "config", "[", "level", "]", ".", "clear", "(", ")" ]
Remove all logger functions from a given level.
[ "Remove", "all", "logger", "functions", "from", "a", "given", "level", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L100-L104
train
49,021
peterldowns/lggr
lggr/__init__.py
Lggr._log
def _log(self, level, fmt, args=None, extra=None, exc_info=None, inc_stackinfo=False, inc_multiproc=False): """ Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance's history. """ if not self.enabled: return # Fail silently so that logging can easily be removed log_record = self._make_record( level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc) logstr = log_record['defaultfmt'].format(**log_record) #whoah. if self.keep_history: self.history.append(logstr) log_funcs = self.config[level] to_remove = [] for lf in log_funcs: try: lf.send(logstr) except StopIteration: # in the case that the log function is already closed, add it # to the list of functions to be deleted. to_remove.append(lf) for lf in to_remove: self.remove(level, lf) self.info('Logging function {} removed from level {}', lf, level)
python
def _log(self, level, fmt, args=None, extra=None, exc_info=None, inc_stackinfo=False, inc_multiproc=False): """ Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance's history. """ if not self.enabled: return # Fail silently so that logging can easily be removed log_record = self._make_record( level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc) logstr = log_record['defaultfmt'].format(**log_record) #whoah. if self.keep_history: self.history.append(logstr) log_funcs = self.config[level] to_remove = [] for lf in log_funcs: try: lf.send(logstr) except StopIteration: # in the case that the log function is already closed, add it # to the list of functions to be deleted. to_remove.append(lf) for lf in to_remove: self.remove(level, lf) self.info('Logging function {} removed from level {}', lf, level)
[ "def", "_log", "(", "self", ",", "level", ",", "fmt", ",", "args", "=", "None", ",", "extra", "=", "None", ",", "exc_info", "=", "None", ",", "inc_stackinfo", "=", "False", ",", "inc_multiproc", "=", "False", ")", ":", "if", "not", "self", ".", "en...
Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance's history.
[ "Send", "a", "log", "message", "to", "all", "of", "the", "logging", "functions", "for", "a", "given", "level", "as", "well", "as", "adding", "the", "message", "to", "this", "logger", "instance", "s", "history", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L201-L234
train
49,022
peterldowns/lggr
lggr/__init__.py
Lggr.log
def log(self, *args, **kwargs): """ Do logging, but handle error suppression. """ if self.suppress_errors: try: self._log(*args, **kwargs) return True except: return False else: self._log(*args, **kwargs) return True
python
def log(self, *args, **kwargs): """ Do logging, but handle error suppression. """ if self.suppress_errors: try: self._log(*args, **kwargs) return True except: return False else: self._log(*args, **kwargs) return True
[ "def", "log", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "suppress_errors", ":", "try", ":", "self", ".", "_log", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "True", "except", ":", "return",...
Do logging, but handle error suppression.
[ "Do", "logging", "but", "handle", "error", "suppression", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L236-L246
train
49,023
peterldowns/lggr
lggr/__init__.py
Lggr.debug
def debug(self, msg, *args, **kwargs): """ Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included. """ kwargs.setdefault('inc_stackinfo', True) self.log(DEBUG, msg, args, **kwargs)
python
def debug(self, msg, *args, **kwargs): """ Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included. """ kwargs.setdefault('inc_stackinfo', True) self.log(DEBUG, msg, args, **kwargs)
[ "def", "debug", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'inc_stackinfo'", ",", "True", ")", "self", ".", "log", "(", "DEBUG", ",", "msg", ",", "args", ",", "*", "*", "kwargs...
Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included.
[ "Log", "a", "message", "with", "DEBUG", "level", ".", "Automatically", "includes", "stack", "info", "unless", "it", "is", "specifically", "not", "included", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L257-L261
train
49,024
peterldowns/lggr
lggr/__init__.py
Lggr.error
def error(self, msg, *args, **kwargs): """ Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included. """ kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(ERROR, msg, args, **kwargs)
python
def error(self, msg, *args, **kwargs): """ Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included. """ kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(ERROR, msg, args, **kwargs)
[ "def", "error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'inc_stackinfo'", ",", "True", ")", "kwargs", ".", "setdefault", "(", "'inc_multiproc'", ",", "True", ")", "self", ".", "...
Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included.
[ "Log", "a", "message", "with", "ERROR", "level", ".", "Automatically", "includes", "stack", "and", "process", "info", "unless", "they", "are", "specifically", "not", "included", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L263-L268
train
49,025
peterldowns/lggr
lggr/__init__.py
Lggr.critical
def critical(self, msg, *args, **kwargs): """ Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included. """ kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(CRITICAL, msg, args, **kwargs)
python
def critical(self, msg, *args, **kwargs): """ Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included. """ kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(CRITICAL, msg, args, **kwargs)
[ "def", "critical", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'inc_stackinfo'", ",", "True", ")", "kwargs", ".", "setdefault", "(", "'inc_multiproc'", ",", "True", ")", "self", ".", ...
Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included.
[ "Log", "a", "message", "with", "CRITICAL", "level", ".", "Automatically", "includes", "stack", "and", "process", "info", "unless", "they", "are", "specifically", "not", "included", "." ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L270-L275
train
49,026
peterldowns/lggr
lggr/__init__.py
Lggr.multi
def multi(self, lvl_list, msg, *args, **kwargs): """ Log a message at multiple levels""" for level in lvl_list: self.log(level, msg, args, **kwargs)
python
def multi(self, lvl_list, msg, *args, **kwargs): """ Log a message at multiple levels""" for level in lvl_list: self.log(level, msg, args, **kwargs)
[ "def", "multi", "(", "self", ",", "lvl_list", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "level", "in", "lvl_list", ":", "self", ".", "log", "(", "level", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
Log a message at multiple levels
[ "Log", "a", "message", "at", "multiple", "levels" ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L277-L280
train
49,027
peterldowns/lggr
lggr/__init__.py
Lggr.all
def all(self, msg, *args, **kwargs): """ Log a message at every known log level """ self.multi(ALL, msg, args, **kwargs)
python
def all(self, msg, *args, **kwargs): """ Log a message at every known log level """ self.multi(ALL, msg, args, **kwargs)
[ "def", "all", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "multi", "(", "ALL", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
Log a message at every known log level
[ "Log", "a", "message", "at", "every", "known", "log", "level" ]
622968f17133e02d9a46a4900dd20fb3b19fe961
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L282-L284
train
49,028
jakewins/neo4jdb-python
neo4j/cursor.py
Cursor._map_value
def _map_value(self, value): ''' Maps a raw deserialized row to proper types ''' # TODO: Once we've gotten here, we've done the following: # -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1) # -> Copy all the data into a String (copy 2) # -> Deserialize that string (copy 3) # -> Map the deserialized JSON to our response format (copy 4, what we are doing in this method) # This should not bee needed. Technically, this mapping from transport format to python types should require exactly one copy, # from the network buffer into the python VM. if isinstance(value, list): out = [] for c in value: out.append(self._map_value( c )) return out elif isinstance(value, dict) and 'metadata' in value and 'labels' in value['metadata'] and 'self' in value: return neo4j.Node(ustr(value['metadata']['id']), value['metadata']['labels'], value['data']) elif isinstance(value, dict) and 'metadata' in value and 'type' in value and 'self' in value: return neo4j.Relationship(ustr(value['metadata']['id']), value['type'], value['start'].split('/')[-1], value['end'].split('/')[-1], value['data']) elif isinstance(value, dict): out = {} for k,v in value.items(): out[k] = self._map_value( v ) return out elif isinstance(value, str): return ustr(value) else: return value
python
def _map_value(self, value): ''' Maps a raw deserialized row to proper types ''' # TODO: Once we've gotten here, we've done the following: # -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1) # -> Copy all the data into a String (copy 2) # -> Deserialize that string (copy 3) # -> Map the deserialized JSON to our response format (copy 4, what we are doing in this method) # This should not bee needed. Technically, this mapping from transport format to python types should require exactly one copy, # from the network buffer into the python VM. if isinstance(value, list): out = [] for c in value: out.append(self._map_value( c )) return out elif isinstance(value, dict) and 'metadata' in value and 'labels' in value['metadata'] and 'self' in value: return neo4j.Node(ustr(value['metadata']['id']), value['metadata']['labels'], value['data']) elif isinstance(value, dict) and 'metadata' in value and 'type' in value and 'self' in value: return neo4j.Relationship(ustr(value['metadata']['id']), value['type'], value['start'].split('/')[-1], value['end'].split('/')[-1], value['data']) elif isinstance(value, dict): out = {} for k,v in value.items(): out[k] = self._map_value( v ) return out elif isinstance(value, str): return ustr(value) else: return value
[ "def", "_map_value", "(", "self", ",", "value", ")", ":", "# TODO: Once we've gotten here, we've done the following:", "# -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1)", "# -> Copy all the data into a String (copy 2)", "# -> Deserialize that string (co...
Maps a raw deserialized row to proper types
[ "Maps", "a", "raw", "deserialized", "row", "to", "proper", "types" ]
cd78cb8397885f219500fb1080d301f0c900f7be
https://github.com/jakewins/neo4jdb-python/blob/cd78cb8397885f219500fb1080d301f0c900f7be/neo4j/cursor.py#L123-L149
train
49,029
jeremymcrae/denovonear
denovonear/load_gene.py
get_deprecated_gene_ids
def get_deprecated_gene_ids(filename): """ gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs """ deprecated = {} with open(filename) as handle: for line in handle: line = line.strip().split() old = line[0] new = line[1] deprecated[old] = new return deprecated
python
def get_deprecated_gene_ids(filename): """ gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs """ deprecated = {} with open(filename) as handle: for line in handle: line = line.strip().split() old = line[0] new = line[1] deprecated[old] = new return deprecated
[ "def", "get_deprecated_gene_ids", "(", "filename", ")", ":", "deprecated", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "handle", ":", "for", "line", "in", "handle", ":", "line", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "...
gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs
[ "gets", "a", "dict", "of", "the", "gene", "IDs", "used", "during", "in", "DDD", "datasets", "that", "have", "been", "deprecated", "in", "favour", "of", "other", "gene", "IDs" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/load_gene.py#L7-L20
train
49,030
ReadabilityHoldings/python-readability-api
readability/core.py
required_from_env
def required_from_env(key): """ Retrieve a required variable from the current environment variables. Raises a ValueError if the env variable is not found or has no value. """ val = os.environ.get(key) if not val: raise ValueError( "Required argument '{}' not supplied and not found in environment variables".format(key)) return val
python
def required_from_env(key): """ Retrieve a required variable from the current environment variables. Raises a ValueError if the env variable is not found or has no value. """ val = os.environ.get(key) if not val: raise ValueError( "Required argument '{}' not supplied and not found in environment variables".format(key)) return val
[ "def", "required_from_env", "(", "key", ")", ":", "val", "=", "os", ".", "environ", ".", "get", "(", "key", ")", "if", "not", "val", ":", "raise", "ValueError", "(", "\"Required argument '{}' not supplied and not found in environment variables\"", ".", "format", "...
Retrieve a required variable from the current environment variables. Raises a ValueError if the env variable is not found or has no value.
[ "Retrieve", "a", "required", "variable", "from", "the", "current", "environment", "variables", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/core.py#L4-L15
train
49,031
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get
def get(self, url): """ Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. """ logger.debug('Making GET request to %s', url) return self.oauth_session.get(url)
python
def get(self, url): """ Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. """ logger.debug('Making GET request to %s', url) return self.oauth_session.get(url)
[ "def", "get", "(", "self", ",", "url", ")", ":", "logger", ".", "debug", "(", "'Making GET request to %s'", ",", "url", ")", "return", "self", ".", "oauth_session", ".", "get", "(", "url", ")" ]
Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request.
[ "Make", "a", "HTTP", "GET", "request", "to", "the", "Reader", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L75-L82
train
49,032
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.post
def post(self, url, post_params=None): """ Make a HTTP POST request to the Reader API. :param url: url to which to make a POST request. :param post_params: parameters to be sent in the request's body. """ params = urlencode(post_params) logger.debug('Making POST request to %s with body %s', url, params) return self.oauth_session.post(url, data=params)
python
def post(self, url, post_params=None): """ Make a HTTP POST request to the Reader API. :param url: url to which to make a POST request. :param post_params: parameters to be sent in the request's body. """ params = urlencode(post_params) logger.debug('Making POST request to %s with body %s', url, params) return self.oauth_session.post(url, data=params)
[ "def", "post", "(", "self", ",", "url", ",", "post_params", "=", "None", ")", ":", "params", "=", "urlencode", "(", "post_params", ")", "logger", ".", "debug", "(", "'Making POST request to %s with body %s'", ",", "url", ",", "params", ")", "return", "self",...
Make a HTTP POST request to the Reader API. :param url: url to which to make a POST request. :param post_params: parameters to be sent in the request's body.
[ "Make", "a", "HTTP", "POST", "request", "to", "the", "Reader", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L84-L93
train
49,033
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.delete
def delete(self, url): """ Make a HTTP DELETE request to the Readability API. :param url: The url to which to send a DELETE request. """ logger.debug('Making DELETE request to %s', url) return self.oauth_session.delete(url)
python
def delete(self, url): """ Make a HTTP DELETE request to the Readability API. :param url: The url to which to send a DELETE request. """ logger.debug('Making DELETE request to %s', url) return self.oauth_session.delete(url)
[ "def", "delete", "(", "self", ",", "url", ")", ":", "logger", ".", "debug", "(", "'Making DELETE request to %s'", ",", "url", ")", "return", "self", ".", "oauth_session", ".", "delete", "(", "url", ")" ]
Make a HTTP DELETE request to the Readability API. :param url: The url to which to send a DELETE request.
[ "Make", "a", "HTTP", "DELETE", "request", "to", "the", "Readability", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L95-L102
train
49,034
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get_article
def get_article(self, article_id): """ Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve. """ url = self._generate_url('articles/{0}'.format(article_id)) return self.get(url)
python
def get_article(self, article_id): """ Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve. """ url = self._generate_url('articles/{0}'.format(article_id)) return self.get(url)
[ "def", "get_article", "(", "self", ",", "article_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'articles/{0}'", ".", "format", "(", "article_id", ")", ")", "return", "self", ".", "get", "(", "url", ")" ]
Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve.
[ "Get", "a", "single", "article", "represented", "by", "article_id", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L119-L126
train
49,035
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get_bookmarks
def get_bookmarks(self, **filters): """ Get Bookmarks for the current user. Filters: :param archive: Filter Bookmarks returned by archived status. :param favorite: Filter Bookmarks returned by favorite status. :param domain: Filter Bookmarks returned by a domain. :param added_since: Filter bookmarks by date added (since this date). :param added_until: Filter bookmarks by date added (until this date). :param opened_since: Filter bookmarks by date opened (since this date). :param opened_until: Filter bookmarks by date opened (until this date). :param archived_since: Filter bookmarks by date archived (since this date.) :param archived_until: Filter bookmarks by date archived (until this date.) :param updated_since: Filter bookmarks by date updated (since this date.) :param updated_until: Filter bookmarks by date updated (until this date.) :param page: What page of results to return. Default is 1. :param per_page: How many results to return per page. Default is 20, max is 50. :param only_deleted: Return only bookmarks that this user has deleted. :param tags: Comma separated string of tags to filter bookmarks. """ filter_dict = filter_args_to_dict(filters, ACCEPTED_BOOKMARK_FILTERS) url = self._generate_url('bookmarks', query_params=filter_dict) return self.get(url)
python
def get_bookmarks(self, **filters): """ Get Bookmarks for the current user. Filters: :param archive: Filter Bookmarks returned by archived status. :param favorite: Filter Bookmarks returned by favorite status. :param domain: Filter Bookmarks returned by a domain. :param added_since: Filter bookmarks by date added (since this date). :param added_until: Filter bookmarks by date added (until this date). :param opened_since: Filter bookmarks by date opened (since this date). :param opened_until: Filter bookmarks by date opened (until this date). :param archived_since: Filter bookmarks by date archived (since this date.) :param archived_until: Filter bookmarks by date archived (until this date.) :param updated_since: Filter bookmarks by date updated (since this date.) :param updated_until: Filter bookmarks by date updated (until this date.) :param page: What page of results to return. Default is 1. :param per_page: How many results to return per page. Default is 20, max is 50. :param only_deleted: Return only bookmarks that this user has deleted. :param tags: Comma separated string of tags to filter bookmarks. """ filter_dict = filter_args_to_dict(filters, ACCEPTED_BOOKMARK_FILTERS) url = self._generate_url('bookmarks', query_params=filter_dict) return self.get(url)
[ "def", "get_bookmarks", "(", "self", ",", "*", "*", "filters", ")", ":", "filter_dict", "=", "filter_args_to_dict", "(", "filters", ",", "ACCEPTED_BOOKMARK_FILTERS", ")", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks'", ",", "query_params", "=", "...
Get Bookmarks for the current user. Filters: :param archive: Filter Bookmarks returned by archived status. :param favorite: Filter Bookmarks returned by favorite status. :param domain: Filter Bookmarks returned by a domain. :param added_since: Filter bookmarks by date added (since this date). :param added_until: Filter bookmarks by date added (until this date). :param opened_since: Filter bookmarks by date opened (since this date). :param opened_until: Filter bookmarks by date opened (until this date). :param archived_since: Filter bookmarks by date archived (since this date.) :param archived_until: Filter bookmarks by date archived (until this date.) :param updated_since: Filter bookmarks by date updated (since this date.) :param updated_until: Filter bookmarks by date updated (until this date.) :param page: What page of results to return. Default is 1. :param per_page: How many results to return per page. Default is 20, max is 50. :param only_deleted: Return only bookmarks that this user has deleted. :param tags: Comma separated string of tags to filter bookmarks.
[ "Get", "Bookmarks", "for", "the", "current", "user", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L128-L152
train
49,036
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get_bookmark
def get_bookmark(self, bookmark_id): """ Get a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to retrieve. """ url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) return self.get(url)
python
def get_bookmark(self, bookmark_id): """ Get a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to retrieve. """ url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) return self.get(url)
[ "def", "get_bookmark", "(", "self", ",", "bookmark_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}'", ".", "format", "(", "bookmark_id", ")", ")", "return", "self", ".", "get", "(", "url", ")" ]
Get a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to retrieve.
[ "Get", "a", "single", "bookmark", "represented", "by", "bookmark_id", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L154-L163
train
49,037
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.add_bookmark
def add_bookmark(self, url, favorite=False, archive=False, allow_duplicates=True): """ Adds given bookmark to the authenticated user. :param url: URL of the article to bookmark :param favorite: whether or not the bookmark should be favorited :param archive: whether or not the bookmark should be archived :param allow_duplicates: whether or not to allow duplicate bookmarks to be created for a given url """ rdb_url = self._generate_url('bookmarks') params = { "url": url, "favorite": int(favorite), "archive": int(archive), "allow_duplicates": int(allow_duplicates) } return self.post(rdb_url, params)
python
def add_bookmark(self, url, favorite=False, archive=False, allow_duplicates=True): """ Adds given bookmark to the authenticated user. :param url: URL of the article to bookmark :param favorite: whether or not the bookmark should be favorited :param archive: whether or not the bookmark should be archived :param allow_duplicates: whether or not to allow duplicate bookmarks to be created for a given url """ rdb_url = self._generate_url('bookmarks') params = { "url": url, "favorite": int(favorite), "archive": int(archive), "allow_duplicates": int(allow_duplicates) } return self.post(rdb_url, params)
[ "def", "add_bookmark", "(", "self", ",", "url", ",", "favorite", "=", "False", ",", "archive", "=", "False", ",", "allow_duplicates", "=", "True", ")", ":", "rdb_url", "=", "self", ".", "_generate_url", "(", "'bookmarks'", ")", "params", "=", "{", "\"url...
Adds given bookmark to the authenticated user. :param url: URL of the article to bookmark :param favorite: whether or not the bookmark should be favorited :param archive: whether or not the bookmark should be archived :param allow_duplicates: whether or not to allow duplicate bookmarks to be created for a given url
[ "Adds", "given", "bookmark", "to", "the", "authenticated", "user", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L165-L182
train
49,038
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.update_bookmark
def update_bookmark(self, bookmark_id, favorite=None, archive=None, read_percent=None): """ Updates given bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to update. :param favorite (optional): Whether this article is favorited or not. :param archive (optional): Whether this article is archived or not. :param read_percent (optional): The read progress made in this article, where 1.0 means the bottom and 0.0 means the very top. """ rdb_url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) params = {} if favorite is not None: params['favorite'] = 1 if favorite == True else 0 if archive is not None: params['archive'] = 1 if archive == True else 0 if read_percent is not None: try: params['read_percent'] = float(read_percent) except ValueError: pass return self.post(rdb_url, params)
python
def update_bookmark(self, bookmark_id, favorite=None, archive=None, read_percent=None): """ Updates given bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to update. :param favorite (optional): Whether this article is favorited or not. :param archive (optional): Whether this article is archived or not. :param read_percent (optional): The read progress made in this article, where 1.0 means the bottom and 0.0 means the very top. """ rdb_url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) params = {} if favorite is not None: params['favorite'] = 1 if favorite == True else 0 if archive is not None: params['archive'] = 1 if archive == True else 0 if read_percent is not None: try: params['read_percent'] = float(read_percent) except ValueError: pass return self.post(rdb_url, params)
[ "def", "update_bookmark", "(", "self", ",", "bookmark_id", ",", "favorite", "=", "None", ",", "archive", "=", "None", ",", "read_percent", "=", "None", ")", ":", "rdb_url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}'", ".", "format", "(", "boo...
Updates given bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to update. :param favorite (optional): Whether this article is favorited or not. :param archive (optional): Whether this article is archived or not. :param read_percent (optional): The read progress made in this article, where 1.0 means the bottom and 0.0 means the very top.
[ "Updates", "given", "bookmark", ".", "The", "requested", "bookmark", "must", "belong", "to", "the", "current", "user", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L184-L206
train
49,039
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.delete_bookmark
def delete_bookmark(self, bookmark_id): """ Delete a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) return self.delete(url)
python
def delete_bookmark(self, bookmark_id): """ Delete a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) return self.delete(url)
[ "def", "delete_bookmark", "(", "self", ",", "bookmark_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}'", ".", "format", "(", "bookmark_id", ")", ")", "return", "self", ".", "delete", "(", "url", ")" ]
Delete a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete.
[ "Delete", "a", "single", "bookmark", "represented", "by", "bookmark_id", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L237-L246
train
49,040
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get_bookmark_tags
def get_bookmark_tags(self, bookmark_id): """ Retrieve tags that have been applied to a bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id)) return self.get(url)
python
def get_bookmark_tags(self, bookmark_id): """ Retrieve tags that have been applied to a bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id)) return self.get(url)
[ "def", "get_bookmark_tags", "(", "self", ",", "bookmark_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}/tags'", ".", "format", "(", "bookmark_id", ")", ")", "return", "self", ".", "get", "(", "url", ")" ]
Retrieve tags that have been applied to a bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete.
[ "Retrieve", "tags", "that", "have", "been", "applied", "to", "a", "bookmark", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L248-L257
train
49,041
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.add_tags_to_bookmark
def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. """ url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id)) params = dict(tags=tags) return self.post(url, params)
python
def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. """ url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id)) params = dict(tags=tags) return self.post(url, params)
[ "def", "add_tags_to_bookmark", "(", "self", ",", "bookmark_id", ",", "tags", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}/tags'", ".", "format", "(", "bookmark_id", ")", ")", "params", "=", "dict", "(", "tags", "=", "tags", ")",...
Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied.
[ "Add", "tags", "to", "to", "a", "bookmark", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L259-L270
train
49,042
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.delete_tag_from_bookmark
def delete_tag_from_bookmark(self, bookmark_id, tag_id): """ Remove a single tag from a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}/tags/{1}'.format( bookmark_id, tag_id)) return self.delete(url)
python
def delete_tag_from_bookmark(self, bookmark_id, tag_id): """ Remove a single tag from a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}/tags/{1}'.format( bookmark_id, tag_id)) return self.delete(url)
[ "def", "delete_tag_from_bookmark", "(", "self", ",", "bookmark_id", ",", "tag_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'bookmarks/{0}/tags/{1}'", ".", "format", "(", "bookmark_id", ",", "tag_id", ")", ")", "return", "self", ".", "delete",...
Remove a single tag from a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete.
[ "Remove", "a", "single", "tag", "from", "a", "bookmark", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L272-L282
train
49,043
ReadabilityHoldings/python-readability-api
readability/clients.py
ReaderClient.get_tag
def get_tag(self, tag_id): """ Get a single tag represented by `tag_id`. The requested tag must belong to the current user. :param tag_id: ID fo the tag to retrieve. """ url = self._generate_url('tags/{0}'.format(tag_id)) return self.get(url)
python
def get_tag(self, tag_id): """ Get a single tag represented by `tag_id`. The requested tag must belong to the current user. :param tag_id: ID fo the tag to retrieve. """ url = self._generate_url('tags/{0}'.format(tag_id)) return self.get(url)
[ "def", "get_tag", "(", "self", ",", "tag_id", ")", ":", "url", "=", "self", ".", "_generate_url", "(", "'tags/{0}'", ".", "format", "(", "tag_id", ")", ")", "return", "self", ".", "get", "(", "url", ")" ]
Get a single tag represented by `tag_id`. The requested tag must belong to the current user. :param tag_id: ID fo the tag to retrieve.
[ "Get", "a", "single", "tag", "represented", "by", "tag_id", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L284-L293
train
49,044
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient.post
def post(self, url, post_params=None): """ Make an HTTP POST request to the Parser API. :param url: url to which to make the request :param post_params: POST data to send along. Expected to be a dict. """ post_params['token'] = self.token params = urlencode(post_params) logger.debug('Making POST request to %s with body %s', url, params) return requests.post(url, data=params)
python
def post(self, url, post_params=None): """ Make an HTTP POST request to the Parser API. :param url: url to which to make the request :param post_params: POST data to send along. Expected to be a dict. """ post_params['token'] = self.token params = urlencode(post_params) logger.debug('Making POST request to %s with body %s', url, params) return requests.post(url, data=params)
[ "def", "post", "(", "self", ",", "url", ",", "post_params", "=", "None", ")", ":", "post_params", "[", "'token'", "]", "=", "self", ".", "token", "params", "=", "urlencode", "(", "post_params", ")", "logger", ".", "debug", "(", "'Making POST request to %s ...
Make an HTTP POST request to the Parser API. :param url: url to which to make the request :param post_params: POST data to send along. Expected to be a dict.
[ "Make", "an", "HTTP", "POST", "request", "to", "the", "Parser", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L350-L360
train
49,045
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient._generate_url
def _generate_url(self, resource, query_params=None): """ Build the url to resource. :param resource: Name of the resource that is being called. Options are `''` (empty string) for root resource, `'parser'`, `'confidence'`. :param query_params: Data to be passed as query parameters. """ resource = '{resource}?token={token}'.format(resource=resource, token=self.token) if query_params: resource += "&{}".format(urlencode(query_params)) return self.base_url_template.format(resource)
python
def _generate_url(self, resource, query_params=None): """ Build the url to resource. :param resource: Name of the resource that is being called. Options are `''` (empty string) for root resource, `'parser'`, `'confidence'`. :param query_params: Data to be passed as query parameters. """ resource = '{resource}?token={token}'.format(resource=resource, token=self.token) if query_params: resource += "&{}".format(urlencode(query_params)) return self.base_url_template.format(resource)
[ "def", "_generate_url", "(", "self", ",", "resource", ",", "query_params", "=", "None", ")", ":", "resource", "=", "'{resource}?token={token}'", ".", "format", "(", "resource", "=", "resource", ",", "token", "=", "self", ".", "token", ")", "if", "query_param...
Build the url to resource. :param resource: Name of the resource that is being called. Options are `''` (empty string) for root resource, `'parser'`, `'confidence'`. :param query_params: Data to be passed as query parameters.
[ "Build", "the", "url", "to", "resource", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L362-L373
train
49,046
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient.get_article
def get_article(self, url=None, article_id=None, max_pages=25): """ Send a GET request to the `parser` endpoint of the parser API to get back the representation of an article. The article can be identified by either a URL or an id that exists in Readability. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. :param max_pages: The maximum number of pages to parse and combine. The default is 25. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id query_params['max_pages'] = max_pages url = self._generate_url('parser', query_params=query_params) return self.get(url)
python
def get_article(self, url=None, article_id=None, max_pages=25): """ Send a GET request to the `parser` endpoint of the parser API to get back the representation of an article. The article can be identified by either a URL or an id that exists in Readability. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. :param max_pages: The maximum number of pages to parse and combine. The default is 25. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id query_params['max_pages'] = max_pages url = self._generate_url('parser', query_params=query_params) return self.get(url)
[ "def", "get_article", "(", "self", ",", "url", "=", "None", ",", "article_id", "=", "None", ",", "max_pages", "=", "25", ")", ":", "query_params", "=", "{", "}", "if", "url", "is", "not", "None", ":", "query_params", "[", "'url'", "]", "=", "url", ...
Send a GET request to the `parser` endpoint of the parser API to get back the representation of an article. The article can be identified by either a URL or an id that exists in Readability. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. :param max_pages: The maximum number of pages to parse and combine. The default is 25.
[ "Send", "a", "GET", "request", "to", "the", "parser", "endpoint", "of", "the", "parser", "API", "to", "get", "back", "the", "representation", "of", "an", "article", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L382-L405
train
49,047
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient.post_article_content
def post_article_content(self, content, url, max_pages=25): """ POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine. Default is 25. """ params = { 'doc': content, 'max_pages': max_pages } url = self._generate_url('parser', {"url": url}) return self.post(url, post_params=params)
python
def post_article_content(self, content, url, max_pages=25): """ POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine. Default is 25. """ params = { 'doc': content, 'max_pages': max_pages } url = self._generate_url('parser', {"url": url}) return self.post(url, post_params=params)
[ "def", "post_article_content", "(", "self", ",", "content", ",", "url", ",", "max_pages", "=", "25", ")", ":", "params", "=", "{", "'doc'", ":", "content", ",", "'max_pages'", ":", "max_pages", "}", "url", "=", "self", ".", "_generate_url", "(", "'parser...
POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine. Default is 25.
[ "POST", "content", "to", "be", "parsed", "to", "the", "Parser", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L407-L423
train
49,048
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient.get_article_status
def get_article_status(self, url=None, article_id=None): """ Send a HEAD request to the `parser` endpoint to the parser API to get the articles status. Returned is a `requests.Response` object. The id and status for the article can be extracted from the `X-Article-Id` and `X-Article-Status` headers. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url = self._generate_url('parser', query_params=query_params) return self.head(url)
python
def get_article_status(self, url=None, article_id=None): """ Send a HEAD request to the `parser` endpoint to the parser API to get the articles status. Returned is a `requests.Response` object. The id and status for the article can be extracted from the `X-Article-Id` and `X-Article-Status` headers. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url = self._generate_url('parser', query_params=query_params) return self.head(url)
[ "def", "get_article_status", "(", "self", ",", "url", "=", "None", ",", "article_id", "=", "None", ")", ":", "query_params", "=", "{", "}", "if", "url", "is", "not", "None", ":", "query_params", "[", "'url'", "]", "=", "url", "if", "article_id", "is", ...
Send a HEAD request to the `parser` endpoint to the parser API to get the articles status. Returned is a `requests.Response` object. The id and status for the article can be extracted from the `X-Article-Id` and `X-Article-Status` headers. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted.
[ "Send", "a", "HEAD", "request", "to", "the", "parser", "endpoint", "to", "the", "parser", "API", "to", "get", "the", "articles", "status", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L425-L446
train
49,049
ReadabilityHoldings/python-readability-api
readability/clients.py
ParserClient.get_confidence
def get_confidence(self, url=None, article_id=None): """ Send a GET request to the `confidence` endpoint of the Parser API. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url = self._generate_url('confidence', query_params=query_params) return self.get(url)
python
def get_confidence(self, url=None, article_id=None): """ Send a GET request to the `confidence` endpoint of the Parser API. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted. """ query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url = self._generate_url('confidence', query_params=query_params) return self.get(url)
[ "def", "get_confidence", "(", "self", ",", "url", "=", "None", ",", "article_id", "=", "None", ")", ":", "query_params", "=", "{", "}", "if", "url", "is", "not", "None", ":", "query_params", "[", "'url'", "]", "=", "url", "if", "article_id", "is", "n...
Send a GET request to the `confidence` endpoint of the Parser API. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system whose content is wanted.
[ "Send", "a", "GET", "request", "to", "the", "confidence", "endpoint", "of", "the", "Parser", "API", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L448-L464
train
49,050
koreyou/word_embedding_loader
word_embedding_loader/saver/glove.py
save
def save(f, arr, vocab): """ Save word embedding file. Args: f (File): File to write the vectors. File should be open for writing ascii. arr (numpy.array): Numpy array with ``float`` dtype. vocab (iterable): Each element is pair of a word (``bytes``) and ``arr`` index (``int``). Word should be encoded to str apriori. """ itr = iter(vocab) # Avoid empty line at the end word, idx = next(itr) _write_line(f, arr[idx], word) for word, idx in itr: f.write(b'\n') _write_line(f, arr[idx], word)
python
def save(f, arr, vocab): """ Save word embedding file. Args: f (File): File to write the vectors. File should be open for writing ascii. arr (numpy.array): Numpy array with ``float`` dtype. vocab (iterable): Each element is pair of a word (``bytes``) and ``arr`` index (``int``). Word should be encoded to str apriori. """ itr = iter(vocab) # Avoid empty line at the end word, idx = next(itr) _write_line(f, arr[idx], word) for word, idx in itr: f.write(b'\n') _write_line(f, arr[idx], word)
[ "def", "save", "(", "f", ",", "arr", ",", "vocab", ")", ":", "itr", "=", "iter", "(", "vocab", ")", "# Avoid empty line at the end", "word", ",", "idx", "=", "next", "(", "itr", ")", "_write_line", "(", "f", ",", "arr", "[", "idx", "]", ",", "word"...
Save word embedding file. Args: f (File): File to write the vectors. File should be open for writing ascii. arr (numpy.array): Numpy array with ``float`` dtype. vocab (iterable): Each element is pair of a word (``bytes``) and ``arr`` index (``int``). Word should be encoded to str apriori.
[ "Save", "word", "embedding", "file", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/saver/glove.py#L18-L35
train
49,051
koreyou/word_embedding_loader
word_embedding_loader/cli.py
convert
def convert(outputfile, inputfile, to_format, from_format): """ Convert pretrained word embedding file in one format to another. """ emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], binary=_input_choices[from_format][2]) emb.save(outputfile, format=_output_choices[to_format][1], binary=_output_choices[to_format][2])
python
def convert(outputfile, inputfile, to_format, from_format): """ Convert pretrained word embedding file in one format to another. """ emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], binary=_input_choices[from_format][2]) emb.save(outputfile, format=_output_choices[to_format][1], binary=_output_choices[to_format][2])
[ "def", "convert", "(", "outputfile", ",", "inputfile", ",", "to_format", ",", "from_format", ")", ":", "emb", "=", "word_embedding", ".", "WordEmbedding", ".", "load", "(", "inputfile", ",", "format", "=", "_input_choices", "[", "from_format", "]", "[", "1",...
Convert pretrained word embedding file in one format to another.
[ "Convert", "pretrained", "word", "embedding", "file", "in", "one", "format", "to", "another", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/cli.py#L39-L47
train
49,052
koreyou/word_embedding_loader
word_embedding_loader/cli.py
check_format
def check_format(inputfile): """ Check format of inputfile. """ t = word_embedding.classify_format(inputfile) if t == word_embedding._glove: _echo_format_result('glove') elif t == word_embedding._word2vec_bin: _echo_format_result('word2vec-binary') elif t == word_embedding._word2vec_text: _echo_format_result('word2vec-text') else: assert not "Should not get here!"
python
def check_format(inputfile): """ Check format of inputfile. """ t = word_embedding.classify_format(inputfile) if t == word_embedding._glove: _echo_format_result('glove') elif t == word_embedding._word2vec_bin: _echo_format_result('word2vec-binary') elif t == word_embedding._word2vec_text: _echo_format_result('word2vec-text') else: assert not "Should not get here!"
[ "def", "check_format", "(", "inputfile", ")", ":", "t", "=", "word_embedding", ".", "classify_format", "(", "inputfile", ")", "if", "t", "==", "word_embedding", ".", "_glove", ":", "_echo_format_result", "(", "'glove'", ")", "elif", "t", "==", "word_embedding"...
Check format of inputfile.
[ "Check", "format", "of", "inputfile", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/cli.py#L56-L68
train
49,053
koreyou/word_embedding_loader
word_embedding_loader/cli.py
list
def list(): """ List available format. """ choice_len = max(map(len, _input_choices.keys())) tmpl = " {:<%d}: {}\n" % choice_len text = ''.join(map( lambda k_v: tmpl.format(k_v[0], k_v[1][0]), six.iteritems(_input_choices))) click.echo(text)
python
def list(): """ List available format. """ choice_len = max(map(len, _input_choices.keys())) tmpl = " {:<%d}: {}\n" % choice_len text = ''.join(map( lambda k_v: tmpl.format(k_v[0], k_v[1][0]), six.iteritems(_input_choices))) click.echo(text)
[ "def", "list", "(", ")", ":", "choice_len", "=", "max", "(", "map", "(", "len", ",", "_input_choices", ".", "keys", "(", ")", ")", ")", "tmpl", "=", "\" {:<%d}: {}\\n\"", "%", "choice_len", "text", "=", "''", ".", "join", "(", "map", "(", "lambda", ...
List available format.
[ "List", "available", "format", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/cli.py#L72-L80
train
49,054
Parsely/birding
src/birding/twitter.py
main
def main(): """Do the default action of `twitter` command.""" from twitter.cmdline import Action, OPTIONS twitter = Twitter.from_oauth_file() Action()(twitter, OPTIONS)
python
def main(): """Do the default action of `twitter` command.""" from twitter.cmdline import Action, OPTIONS twitter = Twitter.from_oauth_file() Action()(twitter, OPTIONS)
[ "def", "main", "(", ")", ":", "from", "twitter", ".", "cmdline", "import", "Action", ",", "OPTIONS", "twitter", "=", "Twitter", ".", "from_oauth_file", "(", ")", "Action", "(", ")", "(", "twitter", ",", "OPTIONS", ")" ]
Do the default action of `twitter` command.
[ "Do", "the", "default", "action", "of", "twitter", "command", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/twitter.py#L106-L110
train
49,055
Parsely/birding
src/birding/twitter.py
Twitter.from_oauth_file
def from_oauth_file(cls, filepath=None): """Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully run, even just one time, you will have a credential file at ~/.twitter_oauth. This factory function reuses your credential file to get a `Twitter` object. (Really, this code is just lifted from the `twitter.cmdline` module to minimize OAuth dancing.) """ if filepath is None: # Use default OAuth filepath from `twitter` command-line program. home = os.environ.get('HOME', os.environ.get('USERPROFILE', '')) filepath = os.path.join(home, '.twitter_oauth') oauth_token, oauth_token_secret = read_token_file(filepath) twitter = cls( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1.1', domain='api.twitter.com') return twitter
python
def from_oauth_file(cls, filepath=None): """Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully run, even just one time, you will have a credential file at ~/.twitter_oauth. This factory function reuses your credential file to get a `Twitter` object. (Really, this code is just lifted from the `twitter.cmdline` module to minimize OAuth dancing.) """ if filepath is None: # Use default OAuth filepath from `twitter` command-line program. home = os.environ.get('HOME', os.environ.get('USERPROFILE', '')) filepath = os.path.join(home, '.twitter_oauth') oauth_token, oauth_token_secret = read_token_file(filepath) twitter = cls( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1.1', domain='api.twitter.com') return twitter
[ "def", "from_oauth_file", "(", "cls", ",", "filepath", "=", "None", ")", ":", "if", "filepath", "is", "None", ":", "# Use default OAuth filepath from `twitter` command-line program.", "home", "=", "os", ".", "environ", ".", "get", "(", "'HOME'", ",", "os", ".", ...
Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully run, even just one time, you will have a credential file at ~/.twitter_oauth. This factory function reuses your credential file to get a `Twitter` object. (Really, this code is just lifted from the `twitter.cmdline` module to minimize OAuth dancing.)
[ "Get", "an", "object", "bound", "to", "the", "Twitter", "API", "using", "your", "own", "credentials", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/twitter.py#L17-L43
train
49,056
Parsely/birding
setup.py
get_version
def get_version(filepath='src/birding/version.py'): """Get version without import, which avoids dependency issues.""" with open(get_abspath(filepath)) as version_file: return re.search( r"""__version__\s+=\s+(['"])(?P<version>.+?)\1""", version_file.read()).group('version')
python
def get_version(filepath='src/birding/version.py'): """Get version without import, which avoids dependency issues.""" with open(get_abspath(filepath)) as version_file: return re.search( r"""__version__\s+=\s+(['"])(?P<version>.+?)\1""", version_file.read()).group('version')
[ "def", "get_version", "(", "filepath", "=", "'src/birding/version.py'", ")", ":", "with", "open", "(", "get_abspath", "(", "filepath", ")", ")", "as", "version_file", ":", "return", "re", ".", "search", "(", "r\"\"\"__version__\\s+=\\s+(['\"])(?P<version>.+?)\\1\"\"\"...
Get version without import, which avoids dependency issues.
[ "Get", "version", "without", "import", "which", "avoids", "dependency", "issues", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/setup.py#L72-L77
train
49,057
Parsely/birding
src/birding/gnip.py
Gnip.search
def search(self, q, **kw): """Search Gnip for given query, returning deserialized response.""" url = '{base_url}/search/{stream}'.format(**vars(self)) params = { 'q': q, } params.update(self.params) params.update(kw) response = self.session.get(url, params=params) response.raise_for_status() return response.json()
python
def search(self, q, **kw): """Search Gnip for given query, returning deserialized response.""" url = '{base_url}/search/{stream}'.format(**vars(self)) params = { 'q': q, } params.update(self.params) params.update(kw) response = self.session.get(url, params=params) response.raise_for_status() return response.json()
[ "def", "search", "(", "self", ",", "q", ",", "*", "*", "kw", ")", ":", "url", "=", "'{base_url}/search/{stream}'", ".", "format", "(", "*", "*", "vars", "(", "self", ")", ")", "params", "=", "{", "'q'", ":", "q", ",", "}", "params", ".", "update"...
Search Gnip for given query, returning deserialized response.
[ "Search", "Gnip", "for", "given", "query", "returning", "deserialized", "response", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/gnip.py#L38-L50
train
49,058
Parsely/birding
src/birding/gnip.py
GnipSearchManager.dump
def dump(result): """Dump result into a string, useful for debugging.""" if isinstance(result, dict): # Result is a search result. statuses = result['results'] else: # Result is a lookup result. statuses = result status_str_list = [] for status in statuses: status_str_list.append(textwrap.dedent(u""" @{screen_name} -- https://twitter.com/{screen_name} {text} """).strip().format( screen_name=status['actor']['preferredUsername'], text=status['body'])) return u'\n\n'.join(status_str_list)
python
def dump(result): """Dump result into a string, useful for debugging.""" if isinstance(result, dict): # Result is a search result. statuses = result['results'] else: # Result is a lookup result. statuses = result status_str_list = [] for status in statuses: status_str_list.append(textwrap.dedent(u""" @{screen_name} -- https://twitter.com/{screen_name} {text} """).strip().format( screen_name=status['actor']['preferredUsername'], text=status['body'])) return u'\n\n'.join(status_str_list)
[ "def", "dump", "(", "result", ")", ":", "if", "isinstance", "(", "result", ",", "dict", ")", ":", "# Result is a search result.", "statuses", "=", "result", "[", "'results'", "]", "else", ":", "# Result is a lookup result.", "statuses", "=", "result", "status_st...
Dump result into a string, useful for debugging.
[ "Dump", "result", "into", "a", "string", "useful", "for", "debugging", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/gnip.py#L75-L91
train
49,059
Parsely/birding
src/birding/shelf.py
shelf_from_config
def shelf_from_config(config, **default_init): """Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as defined in :mod:`birding.config`. """ shelf_cls = import_name(config['shelf_class'], default_ns='birding.shelf') init = {} init.update(default_init) init.update(config['shelf_init']) shelf = shelf_cls(**init) if hasattr(shelf, 'set_expiration') and 'shelf_expiration' in config: shelf.set_expiration(config['shelf_expiration']) return shelf
python
def shelf_from_config(config, **default_init): """Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as defined in :mod:`birding.config`. """ shelf_cls = import_name(config['shelf_class'], default_ns='birding.shelf') init = {} init.update(default_init) init.update(config['shelf_init']) shelf = shelf_cls(**init) if hasattr(shelf, 'set_expiration') and 'shelf_expiration' in config: shelf.set_expiration(config['shelf_expiration']) return shelf
[ "def", "shelf_from_config", "(", "config", ",", "*", "*", "default_init", ")", ":", "shelf_cls", "=", "import_name", "(", "config", "[", "'shelf_class'", "]", ",", "default_ns", "=", "'birding.shelf'", ")", "init", "=", "{", "}", "init", ".", "update", "("...
Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as defined in :mod:`birding.config`.
[ "Get", "a", "Shelf", "instance", "dynamically", "based", "on", "config", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/shelf.py#L16-L29
train
49,060
Parsely/birding
src/birding/shelf.py
FreshPacker.unpack
def unpack(self, key, value): """Unpack and return value only if it is fresh.""" value, freshness = value if not self.is_fresh(freshness): raise KeyError('{} (stale)'.format(key)) return value
python
def unpack(self, key, value): """Unpack and return value only if it is fresh.""" value, freshness = value if not self.is_fresh(freshness): raise KeyError('{} (stale)'.format(key)) return value
[ "def", "unpack", "(", "self", ",", "key", ",", "value", ")", ":", "value", ",", "freshness", "=", "value", "if", "not", "self", ".", "is_fresh", "(", "freshness", ")", ":", "raise", "KeyError", "(", "'{} (stale)'", ".", "format", "(", "key", ")", ")"...
Unpack and return value only if it is fresh.
[ "Unpack", "and", "return", "value", "only", "if", "it", "is", "fresh", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/shelf.py#L97-L102
train
49,061
Parsely/birding
src/birding/shelf.py
FreshPacker.is_fresh
def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
python
def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
[ "def", "is_fresh", "(", "self", ",", "freshness", ")", ":", "if", "self", ".", "expire_after", "is", "None", ":", "return", "True", "return", "self", ".", "freshness", "(", ")", "-", "freshness", "<=", "self", ".", "expire_after" ]
Return False if given freshness value has expired, else True.
[ "Return", "False", "if", "given", "freshness", "value", "has", "expired", "else", "True", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/shelf.py#L116-L120
train
49,062
ministryofjustice/money-to-prisoners-common
mtp_common/stack.py
is_first_instance_aws
def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. """ try: # get instance id and aws region instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', timeout=5).json() instance_id = instance_details['instanceId'] instance_region = instance_details['region'] except (requests.RequestException, ValueError, KeyError) as e: raise StackInterrogationException(e) try: # get instance's autoscaling group autoscaling_client = boto3.client('autoscaling', region_name=instance_region) response = autoscaling_client.describe_auto_scaling_instances(InstanceIds=[instance_id]) assert len(response['AutoScalingInstances']) == 1 autoscaling_group = response['AutoScalingInstances'][0]['AutoScalingGroupName'] except ClientError as e: raise StackInterrogationException(e) except AssertionError: raise InstanceNotInAsgException() try: # list in-service instances in autoscaling group # instances being launched or terminated should not be considered response = autoscaling_client.describe_auto_scaling_groups(AutoScalingGroupNames=[autoscaling_group]) assert len(response['AutoScalingGroups']) == 1 autoscaling_group_instance_ids = sorted( instance['InstanceId'] for instance in response['AutoScalingGroups'][0]['Instances'] if instance['LifecycleState'] == 'InService' ) except (ClientError, AssertionError) as e: raise StackInterrogationException(e) return bool(autoscaling_group_instance_ids and autoscaling_group_instance_ids[0] == instance_id)
python
def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. """ try: # get instance id and aws region instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', timeout=5).json() instance_id = instance_details['instanceId'] instance_region = instance_details['region'] except (requests.RequestException, ValueError, KeyError) as e: raise StackInterrogationException(e) try: # get instance's autoscaling group autoscaling_client = boto3.client('autoscaling', region_name=instance_region) response = autoscaling_client.describe_auto_scaling_instances(InstanceIds=[instance_id]) assert len(response['AutoScalingInstances']) == 1 autoscaling_group = response['AutoScalingInstances'][0]['AutoScalingGroupName'] except ClientError as e: raise StackInterrogationException(e) except AssertionError: raise InstanceNotInAsgException() try: # list in-service instances in autoscaling group # instances being launched or terminated should not be considered response = autoscaling_client.describe_auto_scaling_groups(AutoScalingGroupNames=[autoscaling_group]) assert len(response['AutoScalingGroups']) == 1 autoscaling_group_instance_ids = sorted( instance['InstanceId'] for instance in response['AutoScalingGroups'][0]['Instances'] if instance['LifecycleState'] == 'InService' ) except (ClientError, AssertionError) as e: raise StackInterrogationException(e) return bool(autoscaling_group_instance_ids and autoscaling_group_instance_ids[0] == instance_id)
[ "def", "is_first_instance_aws", "(", ")", ":", "try", ":", "# get instance id and aws region", "instance_details", "=", "requests", ".", "get", "(", "'http://169.254.169.254/latest/dynamic/instance-identity/document'", ",", "timeout", "=", "5", ")", ".", "json", "(", ")...
Returns True if the current instance is the first instance in the ASG group, sorted by instance_id.
[ "Returns", "True", "if", "the", "current", "instance", "is", "the", "first", "instance", "in", "the", "ASG", "group", "sorted", "by", "instance_id", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/stack.py#L33-L71
train
49,063
ministryofjustice/money-to-prisoners-common
mtp_common/stack.py
is_first_instance_k8s
def is_first_instance_k8s(current_pod_name=None): """ Returns True if the current pod is the first replica in Kubernetes cluster. """ current_pod_name = current_pod_name or os.environ.get('POD_NAME') if not current_pod_name: raise StackInterrogationException('Pod name not known') namespace = 'money-to-prisoners-%s' % settings.ENVIRONMENT try: load_incluster_config() except ConfigException as e: raise StackInterrogationException(e) try: response = k8s_client.CoreV1Api().list_namespaced_pod( namespace=namespace, label_selector='app=%s' % settings.APP, watch=False, ) except ApiException as e: raise StackInterrogationException(e) pod_names = sorted(pod.metadata.name for pod in filter(lambda pod: pod.status.phase == 'Running', response.items)) return bool(pod_names and pod_names[0] == current_pod_name)
python
def is_first_instance_k8s(current_pod_name=None): """ Returns True if the current pod is the first replica in Kubernetes cluster. """ current_pod_name = current_pod_name or os.environ.get('POD_NAME') if not current_pod_name: raise StackInterrogationException('Pod name not known') namespace = 'money-to-prisoners-%s' % settings.ENVIRONMENT try: load_incluster_config() except ConfigException as e: raise StackInterrogationException(e) try: response = k8s_client.CoreV1Api().list_namespaced_pod( namespace=namespace, label_selector='app=%s' % settings.APP, watch=False, ) except ApiException as e: raise StackInterrogationException(e) pod_names = sorted(pod.metadata.name for pod in filter(lambda pod: pod.status.phase == 'Running', response.items)) return bool(pod_names and pod_names[0] == current_pod_name)
[ "def", "is_first_instance_k8s", "(", "current_pod_name", "=", "None", ")", ":", "current_pod_name", "=", "current_pod_name", "or", "os", ".", "environ", ".", "get", "(", "'POD_NAME'", ")", "if", "not", "current_pod_name", ":", "raise", "StackInterrogationException",...
Returns True if the current pod is the first replica in Kubernetes cluster.
[ "Returns", "True", "if", "the", "current", "pod", "is", "the", "first", "replica", "in", "Kubernetes", "cluster", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/stack.py#L74-L96
train
49,064
harvard-nrg/yaxil
scripts/ArcGet.py
splitarg
def splitarg(args): ''' This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool ''' if not args: return args split = list() for arg in args: if ',' in arg: split.extend([x for x in arg.split(',') if x]) elif arg: split.append(arg) return split
python
def splitarg(args): ''' This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool ''' if not args: return args split = list() for arg in args: if ',' in arg: split.extend([x for x in arg.split(',') if x]) elif arg: split.append(arg) return split
[ "def", "splitarg", "(", "args", ")", ":", "if", "not", "args", ":", "return", "args", "split", "=", "list", "(", ")", "for", "arg", "in", "args", ":", "if", "','", "in", "arg", ":", "split", ".", "extend", "(", "[", "x", "for", "x", "in", "arg"...
This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool
[ "This", "function", "will", "split", "arguments", "separated", "by", "spaces", "or", "commas", "to", "be", "backwards", "compatible", "with", "the", "original", "ArcGet", "command", "line", "tool" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/scripts/ArcGet.py#L152-L165
train
49,065
ministryofjustice/money-to-prisoners-common
mtp_common/auth/views.py
logout
def logout(request, template_name=None, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user. """ auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out') } if extra_context is not None: context.update(extra_context) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)
python
def logout(request, template_name=None, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user. """ auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out') } if extra_context is not None: context.update(extra_context) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)
[ "def", "logout", "(", "request", ",", "template_name", "=", "None", ",", "next_page", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "current_app", "=", "None", ",", "extra_context", "=", "None", ")", ":", "auth_logout", "(", "reques...
Logs out the user.
[ "Logs", "out", "the", "user", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/views.py#L82-L118
train
49,066
Parsely/birding
src/birding/config.py
get_config
def get_config(filepath=None, default_loader=None, on_missing=None): """Get a dict for the current birding configuration. The resulting dictionary is fully populated with defaults, such that all valid keys will resolve to valid values. Invalid and extra values in the configuration result in an exception. See :ref:`config` (module-level docstring) for discussion on how birding configuration works, including filepath loading. Note that a non-default filepath set via env results in a :py:exc:`OSError` when the file is missing, but the default filepath is ignored when missing. This function caches its return values as to only parse configuration once per set of inputs. As such, treat the resulting dictionary as read-only as not to accidentally write values which will be seen by other handles of the dictionary. Args: filepath (str): path to birding configuration YAML file. default_loader (callable): callable which returns file descriptor with YAML data of default configuration values on_missing (callable): callback to call when file is missing. Returns: dict: dict of current birding configuration; treat as read-only. """ # Handle cache lookup explicitly in order to support keyword arguments. cache_key = (filepath, default_loader, on_missing) if CACHE.get(cache_key) is not None: return CACHE.get(cache_key) logger = logging.getLogger('birding') if filepath is None: filepath = BIRDING_CONF if default_loader is None: default_loader = get_defaults_file if on_missing is None: on_missing = logger.info logger.info( 'Looking for configuration file: {}'.format(os.path.abspath(filepath))) if not os.path.exists(filepath): # Log a message if filepath is default; raise error if not default. on_missing('No {} configuration file found.'.format(filepath)) if filepath != BIRDING_CONF_DEFAULT: # Stat the missing file to result in OSError. os.stat(filepath) config = yaml.safe_load(default_loader()) tv.validate(SCHEMA, config) if os.path.exists(filepath): file_config = yaml.safe_load(open(filepath)) if file_config: config = overlay(file_config, config) tv.validate(SCHEMA, config) CACHE.put(cache_key, config) return config
python
def get_config(filepath=None, default_loader=None, on_missing=None): """Get a dict for the current birding configuration. The resulting dictionary is fully populated with defaults, such that all valid keys will resolve to valid values. Invalid and extra values in the configuration result in an exception. See :ref:`config` (module-level docstring) for discussion on how birding configuration works, including filepath loading. Note that a non-default filepath set via env results in a :py:exc:`OSError` when the file is missing, but the default filepath is ignored when missing. This function caches its return values as to only parse configuration once per set of inputs. As such, treat the resulting dictionary as read-only as not to accidentally write values which will be seen by other handles of the dictionary. Args: filepath (str): path to birding configuration YAML file. default_loader (callable): callable which returns file descriptor with YAML data of default configuration values on_missing (callable): callback to call when file is missing. Returns: dict: dict of current birding configuration; treat as read-only. """ # Handle cache lookup explicitly in order to support keyword arguments. cache_key = (filepath, default_loader, on_missing) if CACHE.get(cache_key) is not None: return CACHE.get(cache_key) logger = logging.getLogger('birding') if filepath is None: filepath = BIRDING_CONF if default_loader is None: default_loader = get_defaults_file if on_missing is None: on_missing = logger.info logger.info( 'Looking for configuration file: {}'.format(os.path.abspath(filepath))) if not os.path.exists(filepath): # Log a message if filepath is default; raise error if not default. on_missing('No {} configuration file found.'.format(filepath)) if filepath != BIRDING_CONF_DEFAULT: # Stat the missing file to result in OSError. os.stat(filepath) config = yaml.safe_load(default_loader()) tv.validate(SCHEMA, config) if os.path.exists(filepath): file_config = yaml.safe_load(open(filepath)) if file_config: config = overlay(file_config, config) tv.validate(SCHEMA, config) CACHE.put(cache_key, config) return config
[ "def", "get_config", "(", "filepath", "=", "None", ",", "default_loader", "=", "None", ",", "on_missing", "=", "None", ")", ":", "# Handle cache lookup explicitly in order to support keyword arguments.", "cache_key", "=", "(", "filepath", ",", "default_loader", ",", "...
Get a dict for the current birding configuration. The resulting dictionary is fully populated with defaults, such that all valid keys will resolve to valid values. Invalid and extra values in the configuration result in an exception. See :ref:`config` (module-level docstring) for discussion on how birding configuration works, including filepath loading. Note that a non-default filepath set via env results in a :py:exc:`OSError` when the file is missing, but the default filepath is ignored when missing. This function caches its return values as to only parse configuration once per set of inputs. As such, treat the resulting dictionary as read-only as not to accidentally write values which will be seen by other handles of the dictionary. Args: filepath (str): path to birding configuration YAML file. default_loader (callable): callable which returns file descriptor with YAML data of default configuration values on_missing (callable): callback to call when file is missing. Returns: dict: dict of current birding configuration; treat as read-only.
[ "Get", "a", "dict", "for", "the", "current", "birding", "configuration", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/config.py#L108-L168
train
49,067
Parsely/birding
src/birding/config.py
get_defaults_file
def get_defaults_file(*a, **kw): """Get a file object with YAML data of configuration defaults. Arguments are passed through to :func:`get_defaults_str`. """ fd = StringIO() fd.write(get_defaults_str(*a, **kw)) fd.seek(0) return fd
python
def get_defaults_file(*a, **kw): """Get a file object with YAML data of configuration defaults. Arguments are passed through to :func:`get_defaults_str`. """ fd = StringIO() fd.write(get_defaults_str(*a, **kw)) fd.seek(0) return fd
[ "def", "get_defaults_file", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "fd", "=", "StringIO", "(", ")", "fd", ".", "write", "(", "get_defaults_str", "(", "*", "a", ",", "*", "*", "kw", ")", ")", "fd", ".", "seek", "(", "0", ")", "return", ...
Get a file object with YAML data of configuration defaults. Arguments are passed through to :func:`get_defaults_str`.
[ "Get", "a", "file", "object", "with", "YAML", "data", "of", "configuration", "defaults", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/config.py#L171-L179
train
49,068
Parsely/birding
src/birding/config.py
get_defaults_str
def get_defaults_str(raw=None, after='Defaults::'): """Get the string YAML representation of configuration defaults.""" if raw is None: raw = __doc__ return unicode(textwrap.dedent(raw.split(after)[-1]).strip())
python
def get_defaults_str(raw=None, after='Defaults::'): """Get the string YAML representation of configuration defaults.""" if raw is None: raw = __doc__ return unicode(textwrap.dedent(raw.split(after)[-1]).strip())
[ "def", "get_defaults_str", "(", "raw", "=", "None", ",", "after", "=", "'Defaults::'", ")", ":", "if", "raw", "is", "None", ":", "raw", "=", "__doc__", "return", "unicode", "(", "textwrap", ".", "dedent", "(", "raw", ".", "split", "(", "after", ")", ...
Get the string YAML representation of configuration defaults.
[ "Get", "the", "string", "YAML", "representation", "of", "configuration", "defaults", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/config.py#L182-L186
train
49,069
Parsely/birding
src/birding/config.py
overlay
def overlay(upper, lower): """Return the overlay of `upper` dict onto `lower` dict. This operation is similar to `dict.update`, but recurses when it encounters a dict/mapping, as to allow nested leaf values in the lower collection which are not in the upper collection. Whenever the upper collection has a value, its value is used. >>> overlay({'a': 0}, {}) {'a': 0} >>> abc = {'a': 0, 'b': 1, 'c': 2} >>> abc == overlay({'a': 0, 'c': 2}, {'a': None, 'b': 1}) True >>> result = {' ': None, '_': abc} >>> result == overlay( ... {'_': {'a': 0, 'c': 2}, ' ': None}, ... {'_': {'a': None, 'b': 1}}) ... True >>> """ result = {} for key in upper: if is_mapping(upper[key]): lower_value = lower.get(key, {}) if not is_mapping(lower_value): msg = 'Attempting to overlay a mapping on a non-mapping: {}' raise ValueError(msg.format(key)) result[key] = overlay(upper[key], lower_value) else: result[key] = upper[key] for key in lower: if key in result: continue result[key] = lower[key] return result
python
def overlay(upper, lower): """Return the overlay of `upper` dict onto `lower` dict. This operation is similar to `dict.update`, but recurses when it encounters a dict/mapping, as to allow nested leaf values in the lower collection which are not in the upper collection. Whenever the upper collection has a value, its value is used. >>> overlay({'a': 0}, {}) {'a': 0} >>> abc = {'a': 0, 'b': 1, 'c': 2} >>> abc == overlay({'a': 0, 'c': 2}, {'a': None, 'b': 1}) True >>> result = {' ': None, '_': abc} >>> result == overlay( ... {'_': {'a': 0, 'c': 2}, ' ': None}, ... {'_': {'a': None, 'b': 1}}) ... True >>> """ result = {} for key in upper: if is_mapping(upper[key]): lower_value = lower.get(key, {}) if not is_mapping(lower_value): msg = 'Attempting to overlay a mapping on a non-mapping: {}' raise ValueError(msg.format(key)) result[key] = overlay(upper[key], lower_value) else: result[key] = upper[key] for key in lower: if key in result: continue result[key] = lower[key] return result
[ "def", "overlay", "(", "upper", ",", "lower", ")", ":", "result", "=", "{", "}", "for", "key", "in", "upper", ":", "if", "is_mapping", "(", "upper", "[", "key", "]", ")", ":", "lower_value", "=", "lower", ".", "get", "(", "key", ",", "{", "}", ...
Return the overlay of `upper` dict onto `lower` dict. This operation is similar to `dict.update`, but recurses when it encounters a dict/mapping, as to allow nested leaf values in the lower collection which are not in the upper collection. Whenever the upper collection has a value, its value is used. >>> overlay({'a': 0}, {}) {'a': 0} >>> abc = {'a': 0, 'b': 1, 'c': 2} >>> abc == overlay({'a': 0, 'c': 2}, {'a': None, 'b': 1}) True >>> result = {' ': None, '_': abc} >>> result == overlay( ... {'_': {'a': 0, 'c': 2}, ' ': None}, ... {'_': {'a': None, 'b': 1}}) ... True >>>
[ "Return", "the", "overlay", "of", "upper", "dict", "onto", "lower", "dict", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/config.py#L189-L224
train
49,070
Parsely/birding
src/birding/config.py
import_name
def import_name(name, default_ns=None): """Import an object based on the dotted string. >>> import_name('textwrap') # doctest: +ELLIPSIS <module 'textwrap' from '...'> >>> import_name('birding.config') # doctest: +ELLIPSIS <module 'birding.config' from '...'> >>> import_name('birding.config.get_config') # doctest: +ELLIPSIS <function get_config at ...> >>> If `ns` is provided, use it as the namespace if `name` does not have a dot. >>> ns = 'birding.config' >>> x = import_name('birding.config.get_config') >>> x # doctest: +ELLIPSIS <function get_config at ...> >>> x == import_name('get_config', default_ns=ns) True >>> x == import_name('birding.config.get_config', default_ns=ns) True >>> """ if '.' not in name: if default_ns is None: return importlib.import_module(name) else: name = default_ns + '.' + name module_name, object_name = name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, object_name)
python
def import_name(name, default_ns=None): """Import an object based on the dotted string. >>> import_name('textwrap') # doctest: +ELLIPSIS <module 'textwrap' from '...'> >>> import_name('birding.config') # doctest: +ELLIPSIS <module 'birding.config' from '...'> >>> import_name('birding.config.get_config') # doctest: +ELLIPSIS <function get_config at ...> >>> If `ns` is provided, use it as the namespace if `name` does not have a dot. >>> ns = 'birding.config' >>> x = import_name('birding.config.get_config') >>> x # doctest: +ELLIPSIS <function get_config at ...> >>> x == import_name('get_config', default_ns=ns) True >>> x == import_name('birding.config.get_config', default_ns=ns) True >>> """ if '.' not in name: if default_ns is None: return importlib.import_module(name) else: name = default_ns + '.' + name module_name, object_name = name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, object_name)
[ "def", "import_name", "(", "name", ",", "default_ns", "=", "None", ")", ":", "if", "'.'", "not", "in", "name", ":", "if", "default_ns", "is", "None", ":", "return", "importlib", ".", "import_module", "(", "name", ")", "else", ":", "name", "=", "default...
Import an object based on the dotted string. >>> import_name('textwrap') # doctest: +ELLIPSIS <module 'textwrap' from '...'> >>> import_name('birding.config') # doctest: +ELLIPSIS <module 'birding.config' from '...'> >>> import_name('birding.config.get_config') # doctest: +ELLIPSIS <function get_config at ...> >>> If `ns` is provided, use it as the namespace if `name` does not have a dot. >>> ns = 'birding.config' >>> x = import_name('birding.config.get_config') >>> x # doctest: +ELLIPSIS <function get_config at ...> >>> x == import_name('get_config', default_ns=ns) True >>> x == import_name('birding.config.get_config', default_ns=ns) True >>>
[ "Import", "an", "object", "based", "on", "the", "dotted", "string", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/config.py#L231-L261
train
49,071
Parsely/birding
src/birding/follow.py
follow_topic_from_config
def follow_topic_from_config(): """Read kafka config, then dispatch to `follow_topic`.""" config = get_config()['ResultTopicBolt'] kafka_class = import_name(config['kafka_class']) return follow_topic(kafka_class, config['topic'], **config['kafka_init'])
python
def follow_topic_from_config(): """Read kafka config, then dispatch to `follow_topic`.""" config = get_config()['ResultTopicBolt'] kafka_class = import_name(config['kafka_class']) return follow_topic(kafka_class, config['topic'], **config['kafka_init'])
[ "def", "follow_topic_from_config", "(", ")", ":", "config", "=", "get_config", "(", ")", "[", "'ResultTopicBolt'", "]", "kafka_class", "=", "import_name", "(", "config", "[", "'kafka_class'", "]", ")", "return", "follow_topic", "(", "kafka_class", ",", "config",...
Read kafka config, then dispatch to `follow_topic`.
[ "Read", "kafka", "config", "then", "dispatch", "to", "follow_topic", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L23-L27
train
49,072
Parsely/birding
src/birding/follow.py
follow_topic
def follow_topic(kafka_class, name, retry_interval=1, **kafka_init): """Dump each message from kafka topic to stdio.""" while True: try: client = kafka_class(**kafka_init) topic = client.topics[name] consumer = topic.get_simple_consumer(reset_offset_on_start=True) except Exception as e: if not should_try_kafka_again(e): raise with flushing(sys.stderr): print( 'Failed attempt to connect to Kafka. Will retry ...', file=sys.stderr) sleep(retry_interval) else: with flushing(sys.stdout): print('Connected to Kafka.') break dump = Dump() for message in consumer: with flushing(sys.stdout, sys.stderr): status = load(message.value) if status: dump(status)
python
def follow_topic(kafka_class, name, retry_interval=1, **kafka_init): """Dump each message from kafka topic to stdio.""" while True: try: client = kafka_class(**kafka_init) topic = client.topics[name] consumer = topic.get_simple_consumer(reset_offset_on_start=True) except Exception as e: if not should_try_kafka_again(e): raise with flushing(sys.stderr): print( 'Failed attempt to connect to Kafka. Will retry ...', file=sys.stderr) sleep(retry_interval) else: with flushing(sys.stdout): print('Connected to Kafka.') break dump = Dump() for message in consumer: with flushing(sys.stdout, sys.stderr): status = load(message.value) if status: dump(status)
[ "def", "follow_topic", "(", "kafka_class", ",", "name", ",", "retry_interval", "=", "1", ",", "*", "*", "kafka_init", ")", ":", "while", "True", ":", "try", ":", "client", "=", "kafka_class", "(", "*", "*", "kafka_init", ")", "topic", "=", "client", "....
Dump each message from kafka topic to stdio.
[ "Dump", "each", "message", "from", "kafka", "topic", "to", "stdio", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L30-L55
train
49,073
Parsely/birding
src/birding/follow.py
follow_fd
def follow_fd(fd): """Dump each line of input to stdio.""" dump = Dump() for line in fd: if not line.strip(): continue with flushing(sys.stdout, sys.stderr): status = load(line) if status: dump(status)
python
def follow_fd(fd): """Dump each line of input to stdio.""" dump = Dump() for line in fd: if not line.strip(): continue with flushing(sys.stdout, sys.stderr): status = load(line) if status: dump(status)
[ "def", "follow_fd", "(", "fd", ")", ":", "dump", "=", "Dump", "(", ")", "for", "line", "in", "fd", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "with", "flushing", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ")", ...
Dump each line of input to stdio.
[ "Dump", "each", "line", "of", "input", "to", "stdio", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L58-L68
train
49,074
Parsely/birding
src/birding/follow.py
should_try_kafka_again
def should_try_kafka_again(error): """Determine if the error means to retry or fail, True to retry.""" msg = 'Unable to retrieve' return isinstance(error, KafkaException) and str(error).startswith(msg)
python
def should_try_kafka_again(error): """Determine if the error means to retry or fail, True to retry.""" msg = 'Unable to retrieve' return isinstance(error, KafkaException) and str(error).startswith(msg)
[ "def", "should_try_kafka_again", "(", "error", ")", ":", "msg", "=", "'Unable to retrieve'", "return", "isinstance", "(", "error", ",", "KafkaException", ")", "and", "str", "(", "error", ")", ".", "startswith", "(", "msg", ")" ]
Determine if the error means to retry or fail, True to retry.
[ "Determine", "if", "the", "error", "means", "to", "retry", "or", "fail", "True", "to", "retry", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L97-L100
train
49,075
koreyou/word_embedding_loader
word_embedding_loader/loader/glove.py
check_valid
def check_valid(line0, line1): """ Check if a file is valid Glove format. Args: line0 (bytes): First line of the file line1 (bytes): Second line of the file Returns: boo: ``True`` if it is valid. ``False`` if it is invalid. """ data = line0.strip().split(b' ') if len(data) <= 2: return False # check if data[2:] is float values try: map(float, data[2:]) except: return False return True
python
def check_valid(line0, line1): """ Check if a file is valid Glove format. Args: line0 (bytes): First line of the file line1 (bytes): Second line of the file Returns: boo: ``True`` if it is valid. ``False`` if it is invalid. """ data = line0.strip().split(b' ') if len(data) <= 2: return False # check if data[2:] is float values try: map(float, data[2:]) except: return False return True
[ "def", "check_valid", "(", "line0", ",", "line1", ")", ":", "data", "=", "line0", ".", "strip", "(", ")", ".", "split", "(", "b' '", ")", "if", "len", "(", "data", ")", "<=", "2", ":", "return", "False", "# check if data[2:] is float values", "try", ":...
Check if a file is valid Glove format. Args: line0 (bytes): First line of the file line1 (bytes): Second line of the file Returns: boo: ``True`` if it is valid. ``False`` if it is invalid.
[ "Check", "if", "a", "file", "is", "valid", "Glove", "format", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L17-L37
train
49,076
koreyou/word_embedding_loader
word_embedding_loader/loader/glove.py
load_with_vocab
def load_with_vocab(fin, vocab, dtype=np.float32): """ Load word embedding file with predefined vocabulary Args: fin (File): File object to read. File should be open for reading ascii. vocab (dict): Mapping from words (``bytes``) to vector indices (``int``). dtype (numpy.dtype): Element data type to use for the array. Returns: numpy.ndarray: Word embedding representation vectors """ arr = None for line in fin: try: token, v = _parse_line(line, dtype) except (ValueError, IndexError): raise ParseError(b'Parsing error in line: ' + line) if token in vocab: if arr is None: arr = np.empty((len(vocab), len(v)), dtype=dtype) arr.fill(np.NaN) elif arr.shape[1] != len(v): raise ParseError(b'Vector size did not match in line: ' + line) arr[vocab[token], :] = np.array(v, dtype=dtype).reshape(1, -1) return arr
python
def load_with_vocab(fin, vocab, dtype=np.float32): """ Load word embedding file with predefined vocabulary Args: fin (File): File object to read. File should be open for reading ascii. vocab (dict): Mapping from words (``bytes``) to vector indices (``int``). dtype (numpy.dtype): Element data type to use for the array. Returns: numpy.ndarray: Word embedding representation vectors """ arr = None for line in fin: try: token, v = _parse_line(line, dtype) except (ValueError, IndexError): raise ParseError(b'Parsing error in line: ' + line) if token in vocab: if arr is None: arr = np.empty((len(vocab), len(v)), dtype=dtype) arr.fill(np.NaN) elif arr.shape[1] != len(v): raise ParseError(b'Vector size did not match in line: ' + line) arr[vocab[token], :] = np.array(v, dtype=dtype).reshape(1, -1) return arr
[ "def", "load_with_vocab", "(", "fin", ",", "vocab", ",", "dtype", "=", "np", ".", "float32", ")", ":", "arr", "=", "None", "for", "line", "in", "fin", ":", "try", ":", "token", ",", "v", "=", "_parse_line", "(", "line", ",", "dtype", ")", "except",...
Load word embedding file with predefined vocabulary Args: fin (File): File object to read. File should be open for reading ascii. vocab (dict): Mapping from words (``bytes``) to vector indices (``int``). dtype (numpy.dtype): Element data type to use for the array. Returns: numpy.ndarray: Word embedding representation vectors
[ "Load", "word", "embedding", "file", "with", "predefined", "vocabulary" ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L47-L73
train
49,077
koreyou/word_embedding_loader
word_embedding_loader/loader/glove.py
load
def load(fin, dtype=np.float32, max_vocab=None): """ Load word embedding file. Args: fin (File): File object to read. File should be open for reading ascii. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. Returns: numpy.ndarray: Word embedding representation vectors dict: Mapping from words to vector indices. """ vocab = {} arr = None i = 0 for line in fin: if max_vocab is not None and i >= max_vocab: break try: token, v = _parse_line(line, dtype) except (ValueError, IndexError): raise ParseError(b'Parsing error in line: ' + line) if token in vocab: parse_warn(b'Duplicated vocabulary ' + token) continue if arr is None: arr = np.array(v, dtype=dtype).reshape(1, -1) else: if arr.shape[1] != len(v): raise ParseError(b'Vector size did not match in line: ' + line) arr = np.append(arr, [v], axis=0) vocab[token] = i i += 1 return arr, vocab
python
def load(fin, dtype=np.float32, max_vocab=None): """ Load word embedding file. Args: fin (File): File object to read. File should be open for reading ascii. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. Returns: numpy.ndarray: Word embedding representation vectors dict: Mapping from words to vector indices. """ vocab = {} arr = None i = 0 for line in fin: if max_vocab is not None and i >= max_vocab: break try: token, v = _parse_line(line, dtype) except (ValueError, IndexError): raise ParseError(b'Parsing error in line: ' + line) if token in vocab: parse_warn(b'Duplicated vocabulary ' + token) continue if arr is None: arr = np.array(v, dtype=dtype).reshape(1, -1) else: if arr.shape[1] != len(v): raise ParseError(b'Vector size did not match in line: ' + line) arr = np.append(arr, [v], axis=0) vocab[token] = i i += 1 return arr, vocab
[ "def", "load", "(", "fin", ",", "dtype", "=", "np", ".", "float32", ",", "max_vocab", "=", "None", ")", ":", "vocab", "=", "{", "}", "arr", "=", "None", "i", "=", "0", "for", "line", "in", "fin", ":", "if", "max_vocab", "is", "not", "None", "an...
Load word embedding file. Args: fin (File): File object to read. File should be open for reading ascii. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. Returns: numpy.ndarray: Word embedding representation vectors dict: Mapping from words to vector indices.
[ "Load", "word", "embedding", "file", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L76-L111
train
49,078
ministryofjustice/money-to-prisoners-common
build_tasks.py
set_version
def set_version(context: Context, version=None, bump=False): """ Updates the version of MTP-common """ if bump and version: raise TaskError('You cannot bump and set a specific version') if bump: from mtp_common import VERSION version = list(VERSION) version[-1] += 1 else: try: version = list(map(int, version.split('.'))) assert len(version) == 3 except (AttributeError, ValueError, AssertionError): raise TaskError('Version must be in the form N.N.N') dotted_version = '.'.join(map(str, version)) replacements = [ (r'^VERSION =.*$', 'VERSION = (%s)' % ', '.join(map(str, version)), 'mtp_common/__init__.py'), (r'^ "version":.*$', ' "version": "%s",' % dotted_version, 'package.json'), ] for search, replacement, path in replacements: with open(os.path.join(root_path, path)) as f: content = f.read() content = re.sub(search, replacement, content, flags=re.MULTILINE) with open(os.path.join(root_path, path), 'w') as f: f.write(content) context.debug('Updated version to %s' % dotted_version)
python
def set_version(context: Context, version=None, bump=False): """ Updates the version of MTP-common """ if bump and version: raise TaskError('You cannot bump and set a specific version') if bump: from mtp_common import VERSION version = list(VERSION) version[-1] += 1 else: try: version = list(map(int, version.split('.'))) assert len(version) == 3 except (AttributeError, ValueError, AssertionError): raise TaskError('Version must be in the form N.N.N') dotted_version = '.'.join(map(str, version)) replacements = [ (r'^VERSION =.*$', 'VERSION = (%s)' % ', '.join(map(str, version)), 'mtp_common/__init__.py'), (r'^ "version":.*$', ' "version": "%s",' % dotted_version, 'package.json'), ] for search, replacement, path in replacements: with open(os.path.join(root_path, path)) as f: content = f.read() content = re.sub(search, replacement, content, flags=re.MULTILINE) with open(os.path.join(root_path, path), 'w') as f: f.write(content) context.debug('Updated version to %s' % dotted_version)
[ "def", "set_version", "(", "context", ":", "Context", ",", "version", "=", "None", ",", "bump", "=", "False", ")", ":", "if", "bump", "and", "version", ":", "raise", "TaskError", "(", "'You cannot bump and set a specific version'", ")", "if", "bump", ":", "f...
Updates the version of MTP-common
[ "Updates", "the", "version", "of", "MTP", "-", "common" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L140-L173
train
49,079
ministryofjustice/money-to-prisoners-common
build_tasks.py
docs
def docs(context: Context): """ Generates static documentation """ try: from sphinx.application import Sphinx except ImportError: context.pip_command('install', 'Sphinx') from sphinx.application import Sphinx context.shell('cp', 'README.rst', 'docs/README.rst') app = Sphinx('docs', 'docs', 'docs/build', 'docs/build/.doctrees', buildername='html', parallel=True, verbosity=context.verbosity) app.build()
python
def docs(context: Context): """ Generates static documentation """ try: from sphinx.application import Sphinx except ImportError: context.pip_command('install', 'Sphinx') from sphinx.application import Sphinx context.shell('cp', 'README.rst', 'docs/README.rst') app = Sphinx('docs', 'docs', 'docs/build', 'docs/build/.doctrees', buildername='html', parallel=True, verbosity=context.verbosity) app.build()
[ "def", "docs", "(", "context", ":", "Context", ")", ":", "try", ":", "from", "sphinx", ".", "application", "import", "Sphinx", "except", "ImportError", ":", "context", ".", "pip_command", "(", "'install'", ",", "'Sphinx'", ")", "from", "sphinx", ".", "appl...
Generates static documentation
[ "Generates", "static", "documentation" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L177-L190
train
49,080
ministryofjustice/money-to-prisoners-common
mtp_common/auth/backends.py
MojBackend.authenticate
def authenticate(self, username=None, password=None): """ Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong. """ data = api_client.authenticate(username, password) if not data: return return User( data.get('pk'), data.get('token'), data.get('user_data') )
python
def authenticate(self, username=None, password=None): """ Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong. """ data = api_client.authenticate(username, password) if not data: return return User( data.get('pk'), data.get('token'), data.get('user_data') )
[ "def", "authenticate", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "data", "=", "api_client", ".", "authenticate", "(", "username", ",", "password", ")", "if", "not", "data", ":", "return", "return", "User", "(", ...
Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong.
[ "Returns", "a", "valid", "MojUser", "if", "the", "authentication", "is", "successful", "or", "None", "if", "the", "credentials", "were", "wrong", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/backends.py#L17-L28
train
49,081
ministryofjustice/money-to-prisoners-common
mtp_common/nomis.py
get_client_token
def get_client_token(): """ Requests and stores the NOMIS API client token from mtp-api """ if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''): return settings.NOMIS_API_CLIENT_TOKEN global client_token if not client_token or client_token['expires'] and client_token['expires'] - now() < datetime.timedelta(days=1): session = None try: session = api_client.get_authenticated_api_session(settings.TOKEN_RETRIEVAL_USERNAME, settings.TOKEN_RETRIEVAL_PASSWORD) client_token = session.get('/tokens/nomis/').json() except (requests.RequestException, HttpNotFoundError, ValueError, AttributeError): logger.exception('Cannot load NOMIS API client token') return None finally: if session and getattr(session, 'access_token', None): api_client.revoke_token(session.access_token) if client_token.get('expires'): client_token['expires'] = parse_datetime(client_token['expires']) if client_token['expires'] < now(): logger.error('NOMIS API client token from mtp-api had expired') return None return client_token['token']
python
def get_client_token(): """ Requests and stores the NOMIS API client token from mtp-api """ if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''): return settings.NOMIS_API_CLIENT_TOKEN global client_token if not client_token or client_token['expires'] and client_token['expires'] - now() < datetime.timedelta(days=1): session = None try: session = api_client.get_authenticated_api_session(settings.TOKEN_RETRIEVAL_USERNAME, settings.TOKEN_RETRIEVAL_PASSWORD) client_token = session.get('/tokens/nomis/').json() except (requests.RequestException, HttpNotFoundError, ValueError, AttributeError): logger.exception('Cannot load NOMIS API client token') return None finally: if session and getattr(session, 'access_token', None): api_client.revoke_token(session.access_token) if client_token.get('expires'): client_token['expires'] = parse_datetime(client_token['expires']) if client_token['expires'] < now(): logger.error('NOMIS API client token from mtp-api had expired') return None return client_token['token']
[ "def", "get_client_token", "(", ")", ":", "if", "getattr", "(", "settings", ",", "'NOMIS_API_CLIENT_TOKEN'", ",", "''", ")", ":", "return", "settings", ".", "NOMIS_API_CLIENT_TOKEN", "global", "client_token", "if", "not", "client_token", "or", "client_token", "[",...
Requests and stores the NOMIS API client token from mtp-api
[ "Requests", "and", "stores", "the", "NOMIS", "API", "client", "token", "from", "mtp", "-", "api" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/nomis.py#L29-L53
train
49,082
chrisseto/django-include
include/query.py
IncludeQuerySet.include
def include(self, *fields, **kwargs): """ Return a new QuerySet instance that will include related objects. If fields are specified, they must be non-hidden relationships. If select_related(None) is called, clear the list. """ clone = self._clone() # Preserve the stickiness of related querysets # NOTE: by default _clone will clear this attribute # .include does not modify the actual query, so we # should not clear `filter_is_sticky` if self.query.filter_is_sticky: clone.query.filter_is_sticky = True clone._include_limit = kwargs.pop('limit_includes', None) assert not kwargs, '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7' # Copy the behavior of .select_related(None) if fields == (None, ): for field in clone._includes.keys(): clone.query._annotations.pop('__{}'.format(field.name), None) clone._includes.clear() return clone # Parse everything the way django handles joins/select related # Including multiple child fields ie .include(field1__field2, field1__field3) # turns into {field1: {field2: {}, field3: {}} for name in fields: ctx, model = clone._includes, clone.model for spl in name.split('__'): field = model._meta.get_field(spl) if isinstance(field, ForeignObjectRel) and field.is_hidden(): raise ValueError('Hidden field "{!r}" has no descriptor and therefore cannot be included'.format(field)) model = field.related_model ctx = ctx.setdefault(field, OrderedDict()) for field in clone._includes.keys(): clone._include(field) return clone
python
def include(self, *fields, **kwargs): """ Return a new QuerySet instance that will include related objects. If fields are specified, they must be non-hidden relationships. If select_related(None) is called, clear the list. """ clone = self._clone() # Preserve the stickiness of related querysets # NOTE: by default _clone will clear this attribute # .include does not modify the actual query, so we # should not clear `filter_is_sticky` if self.query.filter_is_sticky: clone.query.filter_is_sticky = True clone._include_limit = kwargs.pop('limit_includes', None) assert not kwargs, '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7' # Copy the behavior of .select_related(None) if fields == (None, ): for field in clone._includes.keys(): clone.query._annotations.pop('__{}'.format(field.name), None) clone._includes.clear() return clone # Parse everything the way django handles joins/select related # Including multiple child fields ie .include(field1__field2, field1__field3) # turns into {field1: {field2: {}, field3: {}} for name in fields: ctx, model = clone._includes, clone.model for spl in name.split('__'): field = model._meta.get_field(spl) if isinstance(field, ForeignObjectRel) and field.is_hidden(): raise ValueError('Hidden field "{!r}" has no descriptor and therefore cannot be included'.format(field)) model = field.related_model ctx = ctx.setdefault(field, OrderedDict()) for field in clone._includes.keys(): clone._include(field) return clone
[ "def", "include", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "# Preserve the stickiness of related querysets", "# NOTE: by default _clone will clear this attribute", "# .include does not modify the ac...
Return a new QuerySet instance that will include related objects. If fields are specified, they must be non-hidden relationships. If select_related(None) is called, clear the list.
[ "Return", "a", "new", "QuerySet", "instance", "that", "will", "include", "related", "objects", "." ]
0cf095f9e827d8be406c16f2ec0c17b6c4c301ba
https://github.com/chrisseto/django-include/blob/0cf095f9e827d8be406c16f2ec0c17b6c4c301ba/include/query.py#L93-L135
train
49,083
ministryofjustice/money-to-prisoners-common
mtp_common/auth/api_client.py
revoke_token
def revoke_token(access_token): """ Instructs the API to delete this access token and associated refresh token """ response = requests.post( get_revoke_token_url(), data={ 'token': access_token, 'client_id': settings.API_CLIENT_ID, 'client_secret': settings.API_CLIENT_SECRET, }, timeout=15 ) return response.status_code == 200
python
def revoke_token(access_token): """ Instructs the API to delete this access token and associated refresh token """ response = requests.post( get_revoke_token_url(), data={ 'token': access_token, 'client_id': settings.API_CLIENT_ID, 'client_secret': settings.API_CLIENT_SECRET, }, timeout=15 ) return response.status_code == 200
[ "def", "revoke_token", "(", "access_token", ")", ":", "response", "=", "requests", ".", "post", "(", "get_revoke_token_url", "(", ")", ",", "data", "=", "{", "'token'", ":", "access_token", ",", "'client_id'", ":", "settings", ".", "API_CLIENT_ID", ",", "'cl...
Instructs the API to delete this access token and associated refresh token
[ "Instructs", "the", "API", "to", "delete", "this", "access", "token", "and", "associated", "refresh", "token" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/api_client.py#L120-L133
train
49,084
harvard-nrg/yaxil
yaxil/functools/__init__.py
lru_cache
def lru_cache(fn): ''' Memoization wrapper that can handle function attributes, mutable arguments, and can be applied either as a decorator or at runtime. :param fn: Function :type fn: function :returns: Memoized function :rtype: function ''' @wraps(fn) def memoized_fn(*args): pargs = pickle.dumps(args) if pargs not in memoized_fn.cache: memoized_fn.cache[pargs] = fn(*args) return memoized_fn.cache[pargs] # propagate function attributes in the event that # this is applied as a function and not a decorator for attr, value in iter(fn.__dict__.items()): setattr(memoized_fn, attr, value) memoized_fn.cache = {} return memoized_fn
python
def lru_cache(fn): ''' Memoization wrapper that can handle function attributes, mutable arguments, and can be applied either as a decorator or at runtime. :param fn: Function :type fn: function :returns: Memoized function :rtype: function ''' @wraps(fn) def memoized_fn(*args): pargs = pickle.dumps(args) if pargs not in memoized_fn.cache: memoized_fn.cache[pargs] = fn(*args) return memoized_fn.cache[pargs] # propagate function attributes in the event that # this is applied as a function and not a decorator for attr, value in iter(fn.__dict__.items()): setattr(memoized_fn, attr, value) memoized_fn.cache = {} return memoized_fn
[ "def", "lru_cache", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "memoized_fn", "(", "*", "args", ")", ":", "pargs", "=", "pickle", ".", "dumps", "(", "args", ")", "if", "pargs", "not", "in", "memoized_fn", ".", "cache", ":", "memoized...
Memoization wrapper that can handle function attributes, mutable arguments, and can be applied either as a decorator or at runtime. :param fn: Function :type fn: function :returns: Memoized function :rtype: function
[ "Memoization", "wrapper", "that", "can", "handle", "function", "attributes", "mutable", "arguments", "and", "can", "be", "applied", "either", "as", "a", "decorator", "or", "at", "runtime", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/functools/__init__.py#L4-L25
train
49,085
harvard-nrg/yaxil
yaxil/__init__.py
auth
def auth(alias=None, url=None, cfg="~/.xnat_auth"): ''' Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :param alias: XNAT alias :type alias: str :param url: XNAT URL :type url: str :param cfg: Configuration file :type cfg: str :returns: Named tuple of (url, username, password) :rtype: :mod:`yaxil.XnatAuth` ''' if not alias and not url: raise ValueError('you must provide an alias or url argument') if alias and url: raise ValueError('cannot provide both alias and url arguments') # check and parse config file cfg = os.path.expanduser(cfg) if not os.path.exists(cfg): raise AuthError("could not locate auth file %s" % cfg) tree = etree.parse(os.path.expanduser(cfg)) # search by alias or url res = None if alias: res = tree.findall("./%s" % alias) if url: res = tree.findall("./*/[url='%s']" % url) if not res: raise AuthError("failed to locate xnat credentials within %s" % cfg) elif len(res) > 1: raise AuthError("found too many sets of credentials within %s" % cfg) res = res.pop() # get url url = res.findall("url") if not url: raise AuthError("no url for %s in %s" % (alias, cfg)) elif len(url) > 1: raise AuthError("too many urls for %s in %s" % (alias, cfg)) # get username username = res.findall("username") if not username: raise AuthError("no username for %s in %s" % (alias, cfg)) elif len(username) > 1: raise AuthError("too many usernames for %s in %s" % (alias, cfg)) # get password password = res.findall("password") if not password: raise AuthError("no password for %s in %s" % (alias, cfg)) elif len(password) > 1: raise AuthError("too many passwords for %s in %s" % (alias, cfg)) return XnatAuth(url=url.pop().text, username=username.pop().text, password=password.pop().text)
python
def auth(alias=None, url=None, cfg="~/.xnat_auth"): ''' Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :param alias: XNAT alias :type alias: str :param url: XNAT URL :type url: str :param cfg: Configuration file :type cfg: str :returns: Named tuple of (url, username, password) :rtype: :mod:`yaxil.XnatAuth` ''' if not alias and not url: raise ValueError('you must provide an alias or url argument') if alias and url: raise ValueError('cannot provide both alias and url arguments') # check and parse config file cfg = os.path.expanduser(cfg) if not os.path.exists(cfg): raise AuthError("could not locate auth file %s" % cfg) tree = etree.parse(os.path.expanduser(cfg)) # search by alias or url res = None if alias: res = tree.findall("./%s" % alias) if url: res = tree.findall("./*/[url='%s']" % url) if not res: raise AuthError("failed to locate xnat credentials within %s" % cfg) elif len(res) > 1: raise AuthError("found too many sets of credentials within %s" % cfg) res = res.pop() # get url url = res.findall("url") if not url: raise AuthError("no url for %s in %s" % (alias, cfg)) elif len(url) > 1: raise AuthError("too many urls for %s in %s" % (alias, cfg)) # get username username = res.findall("username") if not username: raise AuthError("no username for %s in %s" % (alias, cfg)) elif len(username) > 1: raise AuthError("too many usernames for %s in %s" % (alias, cfg)) # get password password = res.findall("password") if not password: raise AuthError("no password for %s in %s" % (alias, cfg)) elif len(password) > 1: raise AuthError("too many passwords for %s in %s" % (alias, cfg)) return XnatAuth(url=url.pop().text, username=username.pop().text, password=password.pop().text)
[ "def", "auth", "(", "alias", "=", "None", ",", "url", "=", "None", ",", "cfg", "=", "\"~/.xnat_auth\"", ")", ":", "if", "not", "alias", "and", "not", "url", ":", "raise", "ValueError", "(", "'you must provide an alias or url argument'", ")", "if", "alias", ...
Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :param alias: XNAT alias :type alias: str :param url: XNAT URL :type url: str :param cfg: Configuration file :type cfg: str :returns: Named tuple of (url, username, password) :rtype: :mod:`yaxil.XnatAuth`
[ "Read", "connection", "details", "from", "an", "xnat_auth", "XML", "file" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L80-L138
train
49,086
harvard-nrg/yaxil
yaxil/__init__.py
accession
def accession(auth, label, project=None): ''' Get the Accession ID for any Experiment label. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.accession(auth, 'AB1234C') u'XNAT_E00001' :param auth: XNAT authentication :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT Experiment label :type label: str :param project: XNAT Experiment Project :type project: str :returns: Accession ID :rtype: str ''' return list(experiments(auth, label, project))[0].id
python
def accession(auth, label, project=None): ''' Get the Accession ID for any Experiment label. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.accession(auth, 'AB1234C') u'XNAT_E00001' :param auth: XNAT authentication :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT Experiment label :type label: str :param project: XNAT Experiment Project :type project: str :returns: Accession ID :rtype: str ''' return list(experiments(auth, label, project))[0].id
[ "def", "accession", "(", "auth", ",", "label", ",", "project", "=", "None", ")", ":", "return", "list", "(", "experiments", "(", "auth", ",", "label", ",", "project", ")", ")", "[", "0", "]", ".", "id" ]
Get the Accession ID for any Experiment label. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.accession(auth, 'AB1234C') u'XNAT_E00001' :param auth: XNAT authentication :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT Experiment label :type label: str :param project: XNAT Experiment Project :type project: str :returns: Accession ID :rtype: str
[ "Get", "the", "Accession", "ID", "for", "any", "Experiment", "label", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L292-L311
train
49,087
harvard-nrg/yaxil
yaxil/__init__.py
extract
def extract(zf, content, out_dir='.'): ''' Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zipfile.ZipFile :param out_dir: Output directory :type out_dir: str ''' previous_header_offset = 0 compensation = Namespace(value=2**32, factor=0) for i,member in enumerate(zf.infolist()): ''' Right... so when Java 1.6 produces a Zip filesystem that exceeds 2^32 bytes, the Central Directory local file header offsets after the 2^32 byte appear to overflow. The Python zipfile module then adds any unexpected bytes to each header offset thereafter. This attempts to fix that. My guess is that this comment might make perfect sense now, but will make aboslutely no sense in about a year. ''' # undo concat padding added from zipfile.py:819 if i == 0: concat = member.header_offset member.header_offset -= concat # if a header offset moves backward, add 2^32 bytes * factor if previous_header_offset > member.header_offset: compensation.factor += 1 previous_header_offset = member.header_offset member.header_offset += compensation.value * compensation.factor # read the archive member into a bytes file-like object try: bio = io.BytesIO(zf.read(member.filename)) except zipfile.BadZipfile: with tf.NamedTemporaryFile(dir=out_dir, prefix="xnat", suffix=".zip", delete=False) as fo: content.seek(0) fo.write(content.read()) raise DownloadError("bad zip file, written to %s" % fo.name) # xnat archives may contain files that are gzipped without the .gz if not member.filename.endswith(".gz"): try: gz = gzip.GzipFile(fileobj=bio, mode="rb") gz.read() bio = gz except IOError: pass # write the file out to the filesystem bio.seek(0) f = os.path.join(out_dir, os.path.basename(member.filename)) with open(f, "wb") as fo: fo.write(bio.read())
python
def extract(zf, content, out_dir='.'): ''' Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zipfile.ZipFile :param out_dir: Output directory :type out_dir: str ''' previous_header_offset = 0 compensation = Namespace(value=2**32, factor=0) for i,member in enumerate(zf.infolist()): ''' Right... so when Java 1.6 produces a Zip filesystem that exceeds 2^32 bytes, the Central Directory local file header offsets after the 2^32 byte appear to overflow. The Python zipfile module then adds any unexpected bytes to each header offset thereafter. This attempts to fix that. My guess is that this comment might make perfect sense now, but will make aboslutely no sense in about a year. ''' # undo concat padding added from zipfile.py:819 if i == 0: concat = member.header_offset member.header_offset -= concat # if a header offset moves backward, add 2^32 bytes * factor if previous_header_offset > member.header_offset: compensation.factor += 1 previous_header_offset = member.header_offset member.header_offset += compensation.value * compensation.factor # read the archive member into a bytes file-like object try: bio = io.BytesIO(zf.read(member.filename)) except zipfile.BadZipfile: with tf.NamedTemporaryFile(dir=out_dir, prefix="xnat", suffix=".zip", delete=False) as fo: content.seek(0) fo.write(content.read()) raise DownloadError("bad zip file, written to %s" % fo.name) # xnat archives may contain files that are gzipped without the .gz if not member.filename.endswith(".gz"): try: gz = gzip.GzipFile(fileobj=bio, mode="rb") gz.read() bio = gz except IOError: pass # write the file out to the filesystem bio.seek(0) f = os.path.join(out_dir, os.path.basename(member.filename)) with open(f, "wb") as fo: fo.write(bio.read())
[ "def", "extract", "(", "zf", ",", "content", ",", "out_dir", "=", "'.'", ")", ":", "previous_header_offset", "=", "0", "compensation", "=", "Namespace", "(", "value", "=", "2", "**", "32", ",", "factor", "=", "0", ")", "for", "i", ",", "member", "in"...
Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zipfile.ZipFile :param out_dir: Output directory :type out_dir: str
[ "Extracting", "a", "Java", "1", ".", "6", "XNAT", "ZIP", "archive", "in", "Python", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L414-L464
train
49,088
harvard-nrg/yaxil
yaxil/__init__.py
__quick_validate
def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')): ''' Quick validation of JSON result set returned by XNAT. :param r: Result set data in JSON format :type r: dict :param check: Fields to check :type check: tuple :returns: Result set is valid :rtype: bool ''' if 'ResultSet' in check and 'ResultSet' not in r: raise ResultSetError('no ResultSet in server response') if 'Result' in check and 'Result' not in r['ResultSet']: raise ResultSetError('no Result in server response') if 'totalRecords' in check and 'totalRecords' not in r['ResultSet']: raise ResultSetError('no totalRecords in server response') return True
python
def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')): ''' Quick validation of JSON result set returned by XNAT. :param r: Result set data in JSON format :type r: dict :param check: Fields to check :type check: tuple :returns: Result set is valid :rtype: bool ''' if 'ResultSet' in check and 'ResultSet' not in r: raise ResultSetError('no ResultSet in server response') if 'Result' in check and 'Result' not in r['ResultSet']: raise ResultSetError('no Result in server response') if 'totalRecords' in check and 'totalRecords' not in r['ResultSet']: raise ResultSetError('no totalRecords in server response') return True
[ "def", "__quick_validate", "(", "r", ",", "check", "=", "(", "'ResultSet'", ",", "'Result'", ",", "'totalRecords'", ")", ")", ":", "if", "'ResultSet'", "in", "check", "and", "'ResultSet'", "not", "in", "r", ":", "raise", "ResultSetError", "(", "'no ResultSet...
Quick validation of JSON result set returned by XNAT. :param r: Result set data in JSON format :type r: dict :param check: Fields to check :type check: tuple :returns: Result set is valid :rtype: bool
[ "Quick", "validation", "of", "JSON", "result", "set", "returned", "by", "XNAT", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L466-L483
train
49,089
harvard-nrg/yaxil
yaxil/__init__.py
scansearch
def scansearch(auth, label, filt, project=None, aid=None): ''' Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ... 'eor2': "note LIKE %EOR2%", ... 'mpr': "series_description='T1_MEMPRAGE RMS' OR note LIKE %ANAT%" ... } >>> yaxil.scansearch(auth, 'AB1234C', query) {"mpr": [4], "eor1": [13], "eor2": [14]} :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param filt: Scan search filter/query :type filt: dict :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Same dictionary that was passed in, but values are now matching scans :rtype: dict ''' if not aid: aid = accession(auth, label, project) # get scans for accession as a csv url = "%s/data/experiments/%s/scans?format=csv" % (auth.url.rstrip('/'), aid) logger.debug("issuing http request %s", url) r = requests.get(url, auth=(auth.username, auth.password), verify=CHECK_CERTIFICATE) if r.status_code != requests.codes.ok: raise ScanSearchError("response not ok (%s) from %s" % (r.status_code, r.url)) if not r.content: raise ScanSearchError("response is empty from %s" % r.url) # read the result into a csv reader reader = csv.reader(io.StringIO(r.content.decode())) columns = next(reader) # create an in-memory database conn = sqlite3.connect(":memory:") c = conn.cursor() # create scans table and insert data c.execute("CREATE TABLE scans (%s)" % ','.join(columns)) query = "INSERT INTO scans VALUES (%s)" % ','.join('?' * len(columns)) for row in reader: c.execute(query, [x for x in row]) conn.commit() # run the user supplied filters and return result result = col.defaultdict(list) for token,filt in iter(filt.items()): try: result[token] = [x[0] for x in c.execute("SELECT ID FROM scans where %s" % filt)] except sqlite3.OperationalError: logger.critical("something is wrong with the filter: %s", filt) raise return result
python
def scansearch(auth, label, filt, project=None, aid=None): ''' Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ... 'eor2': "note LIKE %EOR2%", ... 'mpr': "series_description='T1_MEMPRAGE RMS' OR note LIKE %ANAT%" ... } >>> yaxil.scansearch(auth, 'AB1234C', query) {"mpr": [4], "eor1": [13], "eor2": [14]} :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param filt: Scan search filter/query :type filt: dict :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Same dictionary that was passed in, but values are now matching scans :rtype: dict ''' if not aid: aid = accession(auth, label, project) # get scans for accession as a csv url = "%s/data/experiments/%s/scans?format=csv" % (auth.url.rstrip('/'), aid) logger.debug("issuing http request %s", url) r = requests.get(url, auth=(auth.username, auth.password), verify=CHECK_CERTIFICATE) if r.status_code != requests.codes.ok: raise ScanSearchError("response not ok (%s) from %s" % (r.status_code, r.url)) if not r.content: raise ScanSearchError("response is empty from %s" % r.url) # read the result into a csv reader reader = csv.reader(io.StringIO(r.content.decode())) columns = next(reader) # create an in-memory database conn = sqlite3.connect(":memory:") c = conn.cursor() # create scans table and insert data c.execute("CREATE TABLE scans (%s)" % ','.join(columns)) query = "INSERT INTO scans VALUES (%s)" % ','.join('?' * len(columns)) for row in reader: c.execute(query, [x for x in row]) conn.commit() # run the user supplied filters and return result result = col.defaultdict(list) for token,filt in iter(filt.items()): try: result[token] = [x[0] for x in c.execute("SELECT ID FROM scans where %s" % filt)] except sqlite3.OperationalError: logger.critical("something is wrong with the filter: %s", filt) raise return result
[ "def", "scansearch", "(", "auth", ",", "label", ",", "filt", ",", "project", "=", "None", ",", "aid", "=", "None", ")", ":", "if", "not", "aid", ":", "aid", "=", "accession", "(", "auth", ",", "label", ",", "project", ")", "# get scans for accession as...
Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ... 'eor2': "note LIKE %EOR2%", ... 'mpr': "series_description='T1_MEMPRAGE RMS' OR note LIKE %ANAT%" ... } >>> yaxil.scansearch(auth, 'AB1234C', query) {"mpr": [4], "eor1": [13], "eor2": [14]} :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param filt: Scan search filter/query :type filt: dict :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Same dictionary that was passed in, but values are now matching scans :rtype: dict
[ "Search", "for", "scans", "by", "supplying", "a", "set", "of", "SQL", "-", "based", "conditionals", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L485-L543
train
49,090
harvard-nrg/yaxil
yaxil/__init__.py
scans
def scans(auth, label=None, scan_ids=None, project=None, experiment=None): ''' Get scan information for a MR Session as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for scan in yaxil.scans2(auth, 'AB1234C'): ... print(json.dumps(scan, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param experiment: YAXIL Experiment :type experiment: :mod:`yaxil.Experiment` :returns: Generator of scan data dictionaries :rtype: dict ''' if experiment and (label or project): raise ValueError('cannot supply experiment with label or project') if experiment: label,project = experiment.label,experiment.project aid = accession(auth, label, project) path = '/data/experiments' params = { 'xsiType': 'xnat:mrSessionData', 'columns': ','.join(scans.columns.keys()) } params['xnat:mrSessionData/ID'] = aid _,result = _get(auth, path, 'json', autobox=True, params=params) for result in result['ResultSet']['Result']: if scan_ids == None or result['xnat:mrscandata/id'] in scan_ids: data = dict() for k,v in iter(scans.columns.items()): data[v] = result[k] yield data
python
def scans(auth, label=None, scan_ids=None, project=None, experiment=None): ''' Get scan information for a MR Session as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for scan in yaxil.scans2(auth, 'AB1234C'): ... print(json.dumps(scan, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param experiment: YAXIL Experiment :type experiment: :mod:`yaxil.Experiment` :returns: Generator of scan data dictionaries :rtype: dict ''' if experiment and (label or project): raise ValueError('cannot supply experiment with label or project') if experiment: label,project = experiment.label,experiment.project aid = accession(auth, label, project) path = '/data/experiments' params = { 'xsiType': 'xnat:mrSessionData', 'columns': ','.join(scans.columns.keys()) } params['xnat:mrSessionData/ID'] = aid _,result = _get(auth, path, 'json', autobox=True, params=params) for result in result['ResultSet']['Result']: if scan_ids == None or result['xnat:mrscandata/id'] in scan_ids: data = dict() for k,v in iter(scans.columns.items()): data[v] = result[k] yield data
[ "def", "scans", "(", "auth", ",", "label", "=", "None", ",", "scan_ids", "=", "None", ",", "project", "=", "None", ",", "experiment", "=", "None", ")", ":", "if", "experiment", "and", "(", "label", "or", "project", ")", ":", "raise", "ValueError", "(...
Get scan information for a MR Session as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for scan in yaxil.scans2(auth, 'AB1234C'): ... print(json.dumps(scan, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param experiment: YAXIL Experiment :type experiment: :mod:`yaxil.Experiment` :returns: Generator of scan data dictionaries :rtype: dict
[ "Get", "scan", "information", "for", "a", "MR", "Session", "as", "a", "sequence", "of", "dictionaries", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L545-L586
train
49,091
harvard-nrg/yaxil
yaxil/__init__.py
extendedboldqc
def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None): ''' Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C') ... print(json.dumps(eqc, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Generator of scan data dictionaries :rtype: :mod:`dict` ''' if not aid: aid = accession(auth, label, project) path = '/data/experiments' params = { 'xsiType': 'neuroinfo:extendedboldqc', 'columns': ','.join(extendedboldqc.columns.keys()) } if project: params['project'] = project params['xnat:mrSessionData/ID'] = aid _,result = _get(auth, path, 'json', autobox=True, params=params) for result in result['ResultSet']['Result']: if scan_ids == None or result['neuroinfo:extendedboldqc/scan/scan_id'] in scan_ids: data = dict() for k,v in iter(extendedboldqc.columns.items()): data[v] = result[k] yield data
python
def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None): ''' Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C') ... print(json.dumps(eqc, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Generator of scan data dictionaries :rtype: :mod:`dict` ''' if not aid: aid = accession(auth, label, project) path = '/data/experiments' params = { 'xsiType': 'neuroinfo:extendedboldqc', 'columns': ','.join(extendedboldqc.columns.keys()) } if project: params['project'] = project params['xnat:mrSessionData/ID'] = aid _,result = _get(auth, path, 'json', autobox=True, params=params) for result in result['ResultSet']['Result']: if scan_ids == None or result['neuroinfo:extendedboldqc/scan/scan_id'] in scan_ids: data = dict() for k,v in iter(extendedboldqc.columns.items()): data[v] = result[k] yield data
[ "def", "extendedboldqc", "(", "auth", ",", "label", ",", "scan_ids", "=", "None", ",", "project", "=", "None", ",", "aid", "=", "None", ")", ":", "if", "not", "aid", ":", "aid", "=", "accession", "(", "auth", ",", "label", ",", "project", ")", "pat...
Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C') ... print(json.dumps(eqc, indent=2)) :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param label: XNAT MR Session label :type label: str :param scan_ids: Scan numbers to return :type scan_ids: list :param project: XNAT MR Session project :type project: str :param aid: XNAT Accession ID :type aid: str :returns: Generator of scan data dictionaries :rtype: :mod:`dict`
[ "Get", "ExtendedBOLDQC", "data", "as", "a", "sequence", "of", "dictionaries", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L626-L666
train
49,092
harvard-nrg/yaxil
yaxil/__init__.py
_autobox
def _autobox(content, format): ''' Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader ''' if format == Format.JSON: return json.loads(content) elif format == Format.XML: return etree.fromstring(content) elif format == Format.CSV: try: return csv.reader(io.BytesIO(content)) except TypeError: # as per https://docs.python.org/2/library/csv.html#examples def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') return unicode_csv_reader(io.StringIO(content)) else: raise AutoboxError("unknown autobox format %s" % format)
python
def _autobox(content, format): ''' Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader ''' if format == Format.JSON: return json.loads(content) elif format == Format.XML: return etree.fromstring(content) elif format == Format.CSV: try: return csv.reader(io.BytesIO(content)) except TypeError: # as per https://docs.python.org/2/library/csv.html#examples def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') return unicode_csv_reader(io.StringIO(content)) else: raise AutoboxError("unknown autobox format %s" % format)
[ "def", "_autobox", "(", "content", ",", "format", ")", ":", "if", "format", "==", "Format", ".", "JSON", ":", "return", "json", ".", "loads", "(", "content", ")", "elif", "format", "==", "Format", ".", "XML", ":", "return", "etree", ".", "fromstring", ...
Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader
[ "Autobox", "response", "content", "." ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L778-L810
train
49,093
ministryofjustice/money-to-prisoners-common
mtp_common/auth/middleware.py
get_user
def get_user(request): """ Returns a cached copy of the user if it exists or calls `auth_get_user` otherwise. """ if not hasattr(request, '_cached_user'): request._cached_user = auth_get_user(request) return request._cached_user
python
def get_user(request): """ Returns a cached copy of the user if it exists or calls `auth_get_user` otherwise. """ if not hasattr(request, '_cached_user'): request._cached_user = auth_get_user(request) return request._cached_user
[ "def", "get_user", "(", "request", ")", ":", "if", "not", "hasattr", "(", "request", ",", "'_cached_user'", ")", ":", "request", ".", "_cached_user", "=", "auth_get_user", "(", "request", ")", "return", "request", ".", "_cached_user" ]
Returns a cached copy of the user if it exists or calls `auth_get_user` otherwise.
[ "Returns", "a", "cached", "copy", "of", "the", "user", "if", "it", "exists", "or", "calls", "auth_get_user", "otherwise", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/middleware.py#L11-L18
train
49,094
ministryofjustice/money-to-prisoners-common
mtp_common/user_admin/views.py
ensure_compatible_admin
def ensure_compatible_admin(view): """ Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. """ def wrapper(request, *args, **kwargs): user_roles = request.user.user_data.get('roles', []) if len(user_roles) != 1: context = { 'message': 'I need to be able to manage user accounts. ' 'My username is %s' % request.user.username } return render(request, 'mtp_common/user_admin/incompatible-admin.html', context=context) return view(request, *args, **kwargs) return wrapper
python
def ensure_compatible_admin(view): """ Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. """ def wrapper(request, *args, **kwargs): user_roles = request.user.user_data.get('roles', []) if len(user_roles) != 1: context = { 'message': 'I need to be able to manage user accounts. ' 'My username is %s' % request.user.username } return render(request, 'mtp_common/user_admin/incompatible-admin.html', context=context) return view(request, *args, **kwargs) return wrapper
[ "def", "ensure_compatible_admin", "(", "view", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_roles", "=", "request", ".", "user", ".", "user_data", ".", "get", "(", "'roles'", ",", "[", "]", ")...
Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role.
[ "Ensures", "that", "the", "user", "is", "in", "exactly", "one", "role", ".", "Other", "checks", "could", "be", "added", "such", "as", "requiring", "one", "prison", "if", "in", "prison", "-", "clerk", "role", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/user_admin/views.py#L31-L47
train
49,095
Parsely/birding
src/birding/bolt.py
fault_barrier
def fault_barrier(fn): """Method decorator to catch and log errors, then send fail message.""" @functools.wraps(fn) def process(self, tup): try: return fn(self, tup) except Exception as e: if isinstance(e, KeyboardInterrupt): return print(str(e), file=sys.stderr) self.fail(tup) return process
python
def fault_barrier(fn): """Method decorator to catch and log errors, then send fail message.""" @functools.wraps(fn) def process(self, tup): try: return fn(self, tup) except Exception as e: if isinstance(e, KeyboardInterrupt): return print(str(e), file=sys.stderr) self.fail(tup) return process
[ "def", "fault_barrier", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "process", "(", "self", ",", "tup", ")", ":", "try", ":", "return", "fn", "(", "self", ",", "tup", ")", "except", "Exception", "as", "e", ":", "if...
Method decorator to catch and log errors, then send fail message.
[ "Method", "decorator", "to", "catch", "and", "log", "errors", "then", "send", "fail", "message", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L16-L27
train
49,096
Parsely/birding
src/birding/search.py
search_manager_from_config
def search_manager_from_config(config, **default_init): """Get a `SearchManager` instance dynamically based on config. `config` is a dictionary containing ``class`` and ``init`` keys as defined in :mod:`birding.config`. """ manager_cls = import_name(config['class'], default_ns='birding.search') init = {} init.update(default_init) init.update(config['init']) manager = manager_cls(**init) return manager
python
def search_manager_from_config(config, **default_init): """Get a `SearchManager` instance dynamically based on config. `config` is a dictionary containing ``class`` and ``init`` keys as defined in :mod:`birding.config`. """ manager_cls = import_name(config['class'], default_ns='birding.search') init = {} init.update(default_init) init.update(config['init']) manager = manager_cls(**init) return manager
[ "def", "search_manager_from_config", "(", "config", ",", "*", "*", "default_init", ")", ":", "manager_cls", "=", "import_name", "(", "config", "[", "'class'", "]", ",", "default_ns", "=", "'birding.search'", ")", "init", "=", "{", "}", "init", ".", "update",...
Get a `SearchManager` instance dynamically based on config. `config` is a dictionary containing ``class`` and ``init`` keys as defined in :mod:`birding.config`.
[ "Get", "a", "SearchManager", "instance", "dynamically", "based", "on", "config", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/search.py#L8-L19
train
49,097
harvard-nrg/yaxil
yaxil/bids/__init__.py
bids_from_config
def bids_from_config(sess, scans_metadata, config, out_base): ''' Create a BIDS output directory from configuration file ''' # get session and subject labels from scan metadata _item = next(iter(scans_metadata)) session,subject = _item['session_label'],_item['subject_label'] # bids and sourcedata base directories sourcedata_base = os.path.join( out_base, 'sourcedata', 'sub-{0}'.format(legal.sub('', subject)), 'ses-{0}'.format(legal.sub('', session)) ) bids_base = os.path.join( out_base, 'sub-{0}'.format(legal.sub('', subject)), 'ses-{0}'.format(legal.sub('', session)) ) # put arguments in a struct args = commons.struct( xnat=sess, subject=subject, session=session, bids=bids_base, sourcedata=sourcedata_base ) # process func, anat, and fmap func_refs = proc_func(config, args) anat_refs = proc_anat(config, args) fmap_refs = proc_fmap(config, args, func_refs)
python
def bids_from_config(sess, scans_metadata, config, out_base): ''' Create a BIDS output directory from configuration file ''' # get session and subject labels from scan metadata _item = next(iter(scans_metadata)) session,subject = _item['session_label'],_item['subject_label'] # bids and sourcedata base directories sourcedata_base = os.path.join( out_base, 'sourcedata', 'sub-{0}'.format(legal.sub('', subject)), 'ses-{0}'.format(legal.sub('', session)) ) bids_base = os.path.join( out_base, 'sub-{0}'.format(legal.sub('', subject)), 'ses-{0}'.format(legal.sub('', session)) ) # put arguments in a struct args = commons.struct( xnat=sess, subject=subject, session=session, bids=bids_base, sourcedata=sourcedata_base ) # process func, anat, and fmap func_refs = proc_func(config, args) anat_refs = proc_anat(config, args) fmap_refs = proc_fmap(config, args, func_refs)
[ "def", "bids_from_config", "(", "sess", ",", "scans_metadata", ",", "config", ",", "out_base", ")", ":", "# get session and subject labels from scan metadata", "_item", "=", "next", "(", "iter", "(", "scans_metadata", ")", ")", "session", ",", "subject", "=", "_it...
Create a BIDS output directory from configuration file
[ "Create", "a", "BIDS", "output", "directory", "from", "configuration", "file" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L14-L44
train
49,098
harvard-nrg/yaxil
yaxil/bids/__init__.py
proc_anat
def proc_anat(config, args): ''' Download anatomical data and convert to BIDS ''' refs = dict() for scan in iterconfig(config, 'anat'): ref = scan.get('id', None) templ = 'sub-${sub}_ses-${ses}' if 'acquisition' in scan: templ += '_acq-${acquisition}' if 'run' in scan: templ += '_run-${run}' templ += '_${modality}' templ = string.Template(templ) fbase = templ.safe_substitute( sub=legal.sub('', args.subject), ses=legal.sub('', args.session), acquisition=scan.get('acquisition', None), run=scan.get('run', None), modality=scan.get('modality', None), ) # download data to bids sourcedata directory sourcedata_dir = os.path.join(args.sourcedata, scan['type']) if not os.path.exists(sourcedata_dir): os.makedirs(sourcedata_dir) dicom_dir = os.path.join(sourcedata_dir, '{0}.dicom'.format(fbase)) logger.info('downloading session=%s, scan=%s, loc=%s', args.session, scan['scan'], dicom_dir) args.xnat.download(args.session, [scan['scan']], out_dir=dicom_dir) # convert to nifti fname = '{0}.nii.gz'.format(fbase) refs[ref] = os.path.join(scan['type'], fname) fullfile = os.path.join(args.bids, scan['type'], fname) logger.info('converting %s to %s', dicom_dir, fullfile) convert(dicom_dir, fullfile) return refs
python
def proc_anat(config, args): ''' Download anatomical data and convert to BIDS ''' refs = dict() for scan in iterconfig(config, 'anat'): ref = scan.get('id', None) templ = 'sub-${sub}_ses-${ses}' if 'acquisition' in scan: templ += '_acq-${acquisition}' if 'run' in scan: templ += '_run-${run}' templ += '_${modality}' templ = string.Template(templ) fbase = templ.safe_substitute( sub=legal.sub('', args.subject), ses=legal.sub('', args.session), acquisition=scan.get('acquisition', None), run=scan.get('run', None), modality=scan.get('modality', None), ) # download data to bids sourcedata directory sourcedata_dir = os.path.join(args.sourcedata, scan['type']) if not os.path.exists(sourcedata_dir): os.makedirs(sourcedata_dir) dicom_dir = os.path.join(sourcedata_dir, '{0}.dicom'.format(fbase)) logger.info('downloading session=%s, scan=%s, loc=%s', args.session, scan['scan'], dicom_dir) args.xnat.download(args.session, [scan['scan']], out_dir=dicom_dir) # convert to nifti fname = '{0}.nii.gz'.format(fbase) refs[ref] = os.path.join(scan['type'], fname) fullfile = os.path.join(args.bids, scan['type'], fname) logger.info('converting %s to %s', dicom_dir, fullfile) convert(dicom_dir, fullfile) return refs
[ "def", "proc_anat", "(", "config", ",", "args", ")", ":", "refs", "=", "dict", "(", ")", "for", "scan", "in", "iterconfig", "(", "config", ",", "'anat'", ")", ":", "ref", "=", "scan", ".", "get", "(", "'id'", ",", "None", ")", "templ", "=", "'sub...
Download anatomical data and convert to BIDS
[ "Download", "anatomical", "data", "and", "convert", "to", "BIDS" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L86-L120
train
49,099