id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,000 | ucfopen/canvasapi | canvasapi/requester.py | Requester._get_request | def _get_request(self, url, headers, params=None):
"""
Issue a GET request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param params: dict
"""
return self._session.get(url, headers=headers, params=params) | python | def _get_request(self, url, headers, params=None):
return self._session.get(url, headers=headers, params=params) | [
"def",
"_get_request",
"(",
"self",
",",
"url",
",",
"headers",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"params",
")"
] | Issue a GET request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param params: dict | [
"Issue",
"a",
"GET",
"request",
"to",
"the",
"specified",
"endpoint",
"with",
"the",
"data",
"provided",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/requester.py#L117-L125 |
232,001 | ucfopen/canvasapi | canvasapi/requester.py | Requester._post_request | def _post_request(self, url, headers, data=None):
"""
Issue a POST request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
# Grab file from data.
files = None
for field, value in data:
if field == 'file':
if isinstance(value, dict):
files = value
else:
files = {'file': value}
break
# Remove file entry from data.
data[:] = [tup for tup in data if tup[0] != 'file']
return self._session.post(url, headers=headers, data=data, files=files) | python | def _post_request(self, url, headers, data=None):
# Grab file from data.
files = None
for field, value in data:
if field == 'file':
if isinstance(value, dict):
files = value
else:
files = {'file': value}
break
# Remove file entry from data.
data[:] = [tup for tup in data if tup[0] != 'file']
return self._session.post(url, headers=headers, data=data, files=files) | [
"def",
"_post_request",
"(",
"self",
",",
"url",
",",
"headers",
",",
"data",
"=",
"None",
")",
":",
"# Grab file from data.",
"files",
"=",
"None",
"for",
"field",
",",
"value",
"in",
"data",
":",
"if",
"field",
"==",
"'file'",
":",
"if",
"isinstance",
... | Issue a POST request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict | [
"Issue",
"a",
"POST",
"request",
"to",
"the",
"specified",
"endpoint",
"with",
"the",
"data",
"provided",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/requester.py#L127-L149 |
232,002 | ucfopen/canvasapi | canvasapi/requester.py | Requester._delete_request | def _delete_request(self, url, headers, data=None):
"""
Issue a DELETE request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
return self._session.delete(url, headers=headers, data=data) | python | def _delete_request(self, url, headers, data=None):
return self._session.delete(url, headers=headers, data=data) | [
"def",
"_delete_request",
"(",
"self",
",",
"url",
",",
"headers",
",",
"data",
"=",
"None",
")",
":",
"return",
"self",
".",
"_session",
".",
"delete",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
")"
] | Issue a DELETE request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict | [
"Issue",
"a",
"DELETE",
"request",
"to",
"the",
"specified",
"endpoint",
"with",
"the",
"data",
"provided",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/requester.py#L151-L159 |
232,003 | ucfopen/canvasapi | canvasapi/requester.py | Requester._put_request | def _put_request(self, url, headers, data=None):
"""
Issue a PUT request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
return self._session.put(url, headers=headers, data=data) | python | def _put_request(self, url, headers, data=None):
return self._session.put(url, headers=headers, data=data) | [
"def",
"_put_request",
"(",
"self",
",",
"url",
",",
"headers",
",",
"data",
"=",
"None",
")",
":",
"return",
"self",
".",
"_session",
".",
"put",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
")"
] | Issue a PUT request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict | [
"Issue",
"a",
"PUT",
"request",
"to",
"the",
"specified",
"endpoint",
"with",
"the",
"data",
"provided",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/requester.py#L161-L169 |
232,004 | ucfopen/canvasapi | canvasapi/upload.py | Uploader.request_upload_token | def request_upload_token(self, file):
"""
Request an upload token.
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
and the JSON response from the API.
:rtype: tuple
"""
self.kwargs['name'] = os.path.basename(file.name)
self.kwargs['size'] = os.fstat(file.fileno()).st_size
response = self._requester.request(
'POST',
self.url,
_kwargs=combine_kwargs(**self.kwargs)
)
return self.upload(response, file) | python | def request_upload_token(self, file):
self.kwargs['name'] = os.path.basename(file.name)
self.kwargs['size'] = os.fstat(file.fileno()).st_size
response = self._requester.request(
'POST',
self.url,
_kwargs=combine_kwargs(**self.kwargs)
)
return self.upload(response, file) | [
"def",
"request_upload_token",
"(",
"self",
",",
"file",
")",
":",
"self",
".",
"kwargs",
"[",
"'name'",
"]",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
".",
"name",
")",
"self",
".",
"kwargs",
"[",
"'size'",
"]",
"=",
"os",
".",
"fstat"... | Request an upload token.
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
and the JSON response from the API.
:rtype: tuple | [
"Request",
"an",
"upload",
"token",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/upload.py#L52-L70 |
232,005 | ucfopen/canvasapi | canvasapi/upload.py | Uploader.upload | def upload(self, response, file):
"""
Upload the file.
:param response: The response from the upload request.
:type response: dict
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
and the JSON response from the API.
:rtype: tuple
"""
response = response.json()
if not response.get('upload_url'):
raise ValueError('Bad API response. No upload_url.')
if not response.get('upload_params'):
raise ValueError('Bad API response. No upload_params.')
kwargs = response.get('upload_params')
response = self._requester.request(
'POST',
use_auth=False,
_url=response.get('upload_url'),
file=file,
_kwargs=combine_kwargs(**kwargs)
)
# remove `while(1);` that may appear at the top of a response
response_json = json.loads(response.text.lstrip('while(1);'))
return ('url' in response_json, response_json) | python | def upload(self, response, file):
response = response.json()
if not response.get('upload_url'):
raise ValueError('Bad API response. No upload_url.')
if not response.get('upload_params'):
raise ValueError('Bad API response. No upload_params.')
kwargs = response.get('upload_params')
response = self._requester.request(
'POST',
use_auth=False,
_url=response.get('upload_url'),
file=file,
_kwargs=combine_kwargs(**kwargs)
)
# remove `while(1);` that may appear at the top of a response
response_json = json.loads(response.text.lstrip('while(1);'))
return ('url' in response_json, response_json) | [
"def",
"upload",
"(",
"self",
",",
"response",
",",
"file",
")",
":",
"response",
"=",
"response",
".",
"json",
"(",
")",
"if",
"not",
"response",
".",
"get",
"(",
"'upload_url'",
")",
":",
"raise",
"ValueError",
"(",
"'Bad API response. No upload_url.'",
... | Upload the file.
:param response: The response from the upload request.
:type response: dict
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
and the JSON response from the API.
:rtype: tuple | [
"Upload",
"the",
"file",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/upload.py#L72-L103 |
232,006 | ucfopen/canvasapi | canvasapi/canvas_object.py | CanvasObject.set_attributes | def set_attributes(self, attributes):
"""
Load this object with attributes.
This method attempts to detect special types based on the field's content
and will create an additional attribute of that type.
Consider a JSON response with the following fields::
{
"name": "New course name",
"course_code": "COURSE-001",
"start_at": "2012-05-05T00:00:00Z",
"end_at": "2012-08-05T23:59:59Z",
"sis_course_id": "12345"
}
The `start_at` and `end_at` fields match a date in ISO8601 format,
so two additional datetime attributes are created, `start_at_date`
and `end_at_date`.
:param attributes: The JSON object to build this object with.
:type attributes: dict
"""
self.attributes = attributes
for attribute, value in attributes.items():
self.__setattr__(attribute, value)
# datetime field
if DATE_PATTERN.match(text_type(value)):
naive = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
aware = naive.replace(tzinfo=pytz.utc)
self.__setattr__(attribute + '_date', aware) | python | def set_attributes(self, attributes):
self.attributes = attributes
for attribute, value in attributes.items():
self.__setattr__(attribute, value)
# datetime field
if DATE_PATTERN.match(text_type(value)):
naive = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
aware = naive.replace(tzinfo=pytz.utc)
self.__setattr__(attribute + '_date', aware) | [
"def",
"set_attributes",
"(",
"self",
",",
"attributes",
")",
":",
"self",
".",
"attributes",
"=",
"attributes",
"for",
"attribute",
",",
"value",
"in",
"attributes",
".",
"items",
"(",
")",
":",
"self",
".",
"__setattr__",
"(",
"attribute",
",",
"value",
... | Load this object with attributes.
This method attempts to detect special types based on the field's content
and will create an additional attribute of that type.
Consider a JSON response with the following fields::
{
"name": "New course name",
"course_code": "COURSE-001",
"start_at": "2012-05-05T00:00:00Z",
"end_at": "2012-08-05T23:59:59Z",
"sis_course_id": "12345"
}
The `start_at` and `end_at` fields match a date in ISO8601 format,
so two additional datetime attributes are created, `start_at_date`
and `end_at_date`.
:param attributes: The JSON object to build this object with.
:type attributes: dict | [
"Load",
"this",
"object",
"with",
"attributes",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas_object.py#L42-L75 |
232,007 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.create_account | def create_account(self, **kwargs):
"""
Create a new root account.
:calls: `POST /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_
:rtype: :class:`canvasapi.account.Account`
"""
response = self.__requester.request(
'POST',
'accounts',
_kwargs=combine_kwargs(**kwargs)
)
return Account(self.__requester, response.json()) | python | def create_account(self, **kwargs):
response = self.__requester.request(
'POST',
'accounts',
_kwargs=combine_kwargs(**kwargs)
)
return Account(self.__requester, response.json()) | [
"def",
"create_account",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'POST'",
",",
"'accounts'",
",",
"_kwargs",
"=",
"combine_kwargs",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
... | Create a new root account.
:calls: `POST /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_
:rtype: :class:`canvasapi.account.Account` | [
"Create",
"a",
"new",
"root",
"account",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L53-L67 |
232,008 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_account | def get_account(self, account, use_sis_id=False, **kwargs):
"""
Retrieve information on an individual account.
:calls: `GET /api/v1/accounts/:id \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.show>`_
:param account: The object or ID of the account to retrieve.
:type account: int, str or :class:`canvasapi.account.Account`
:param use_sis_id: Whether or not account_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.account.Account`
"""
if use_sis_id:
account_id = account
uri_str = 'accounts/sis_account_id:{}'
else:
account_id = obj_or_id(account, "account", (Account,))
uri_str = 'accounts/{}'
response = self.__requester.request(
'GET',
uri_str.format(account_id),
_kwargs=combine_kwargs(**kwargs)
)
return Account(self.__requester, response.json()) | python | def get_account(self, account, use_sis_id=False, **kwargs):
if use_sis_id:
account_id = account
uri_str = 'accounts/sis_account_id:{}'
else:
account_id = obj_or_id(account, "account", (Account,))
uri_str = 'accounts/{}'
response = self.__requester.request(
'GET',
uri_str.format(account_id),
_kwargs=combine_kwargs(**kwargs)
)
return Account(self.__requester, response.json()) | [
"def",
"get_account",
"(",
"self",
",",
"account",
",",
"use_sis_id",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"use_sis_id",
":",
"account_id",
"=",
"account",
"uri_str",
"=",
"'accounts/sis_account_id:{}'",
"else",
":",
"account_id",
"=",
"obj... | Retrieve information on an individual account.
:calls: `GET /api/v1/accounts/:id \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.show>`_
:param account: The object or ID of the account to retrieve.
:type account: int, str or :class:`canvasapi.account.Account`
:param use_sis_id: Whether or not account_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.account.Account` | [
"Retrieve",
"information",
"on",
"an",
"individual",
"account",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L69-L96 |
232,009 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_accounts | def get_accounts(self, **kwargs):
"""
List accounts that the current user can view or manage.
Typically, students and teachers will get an empty list in
response. Only account admins can view the accounts that they
are in.
:calls: `GET /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.account.Account`
"""
return PaginatedList(
Account,
self.__requester,
'GET',
'accounts',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_accounts(self, **kwargs):
return PaginatedList(
Account,
self.__requester,
'GET',
'accounts',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_accounts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"PaginatedList",
"(",
"Account",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'accounts'",
",",
"_kwargs",
"=",
"combine_kwargs",
"(",
"*",
"*",
"kwargs",
")",
")"
] | List accounts that the current user can view or manage.
Typically, students and teachers will get an empty list in
response. Only account admins can view the accounts that they
are in.
:calls: `GET /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.account.Account` | [
"List",
"accounts",
"that",
"the",
"current",
"user",
"can",
"view",
"or",
"manage",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L98-L118 |
232,010 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_course | def get_course(self, course, use_sis_id=False, **kwargs):
"""
Retrieve a course by its ID.
:calls: `GET /api/v1/courses/:id \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.show>`_
:param course: The object or ID of the course to retrieve.
:type course: int, str or :class:`canvasapi.course.Course`
:param use_sis_id: Whether or not course_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.course.Course`
"""
if use_sis_id:
course_id = course
uri_str = 'courses/sis_course_id:{}'
else:
course_id = obj_or_id(course, "course", (Course,))
uri_str = 'courses/{}'
response = self.__requester.request(
'GET',
uri_str.format(course_id),
_kwargs=combine_kwargs(**kwargs)
)
return Course(self.__requester, response.json()) | python | def get_course(self, course, use_sis_id=False, **kwargs):
if use_sis_id:
course_id = course
uri_str = 'courses/sis_course_id:{}'
else:
course_id = obj_or_id(course, "course", (Course,))
uri_str = 'courses/{}'
response = self.__requester.request(
'GET',
uri_str.format(course_id),
_kwargs=combine_kwargs(**kwargs)
)
return Course(self.__requester, response.json()) | [
"def",
"get_course",
"(",
"self",
",",
"course",
",",
"use_sis_id",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"use_sis_id",
":",
"course_id",
"=",
"course",
"uri_str",
"=",
"'courses/sis_course_id:{}'",
"else",
":",
"course_id",
"=",
"obj_or_id"... | Retrieve a course by its ID.
:calls: `GET /api/v1/courses/:id \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.show>`_
:param course: The object or ID of the course to retrieve.
:type course: int, str or :class:`canvasapi.course.Course`
:param use_sis_id: Whether or not course_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.course.Course` | [
"Retrieve",
"a",
"course",
"by",
"its",
"ID",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L141-L168 |
232,011 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_user | def get_user(self, user, id_type=None):
"""
Retrieve a user by their ID. `id_type` denotes which endpoint to try as there are
several different IDs that can pull the same user record from Canvas.
Refer to API documentation's
`User <https://canvas.instructure.com/doc/api/users.html#User>`_
example to see the ID types a user can be retrieved with.
:calls: `GET /api/v1/users/:id \
<https://canvas.instructure.com/doc/api/users.html#method.users.api_show>`_
:param user: The user's object or ID.
:type user: :class:`canvasapi.user.User` or int
:param id_type: The ID type.
:type id_type: str
:rtype: :class:`canvasapi.user.User`
"""
if id_type:
uri = 'users/{}:{}'.format(id_type, user)
elif user == 'self':
uri = 'users/self'
else:
user_id = obj_or_id(user, "user", (User,))
uri = 'users/{}'.format(user_id)
response = self.__requester.request(
'GET',
uri
)
return User(self.__requester, response.json()) | python | def get_user(self, user, id_type=None):
if id_type:
uri = 'users/{}:{}'.format(id_type, user)
elif user == 'self':
uri = 'users/self'
else:
user_id = obj_or_id(user, "user", (User,))
uri = 'users/{}'.format(user_id)
response = self.__requester.request(
'GET',
uri
)
return User(self.__requester, response.json()) | [
"def",
"get_user",
"(",
"self",
",",
"user",
",",
"id_type",
"=",
"None",
")",
":",
"if",
"id_type",
":",
"uri",
"=",
"'users/{}:{}'",
".",
"format",
"(",
"id_type",
",",
"user",
")",
"elif",
"user",
"==",
"'self'",
":",
"uri",
"=",
"'users/self'",
"... | Retrieve a user by their ID. `id_type` denotes which endpoint to try as there are
several different IDs that can pull the same user record from Canvas.
Refer to API documentation's
`User <https://canvas.instructure.com/doc/api/users.html#User>`_
example to see the ID types a user can be retrieved with.
:calls: `GET /api/v1/users/:id \
<https://canvas.instructure.com/doc/api/users.html#method.users.api_show>`_
:param user: The user's object or ID.
:type user: :class:`canvasapi.user.User` or int
:param id_type: The ID type.
:type id_type: str
:rtype: :class:`canvasapi.user.User` | [
"Retrieve",
"a",
"user",
"by",
"their",
"ID",
".",
"id_type",
"denotes",
"which",
"endpoint",
"to",
"try",
"as",
"there",
"are",
"several",
"different",
"IDs",
"that",
"can",
"pull",
"the",
"same",
"user",
"record",
"from",
"Canvas",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L170-L201 |
232,012 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_courses | def get_courses(self, **kwargs):
"""
Return a list of active courses for the current user.
:calls: `GET /api/v1/courses \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.course.Course`
"""
return PaginatedList(
Course,
self.__requester,
'GET',
'courses',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_courses(self, **kwargs):
return PaginatedList(
Course,
self.__requester,
'GET',
'courses',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_courses",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"PaginatedList",
"(",
"Course",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'courses'",
",",
"_kwargs",
"=",
"combine_kwargs",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Return a list of active courses for the current user.
:calls: `GET /api/v1/courses \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.course.Course` | [
"Return",
"a",
"list",
"of",
"active",
"courses",
"for",
"the",
"current",
"user",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L206-L222 |
232,013 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_section | def get_section(self, section, use_sis_id=False, **kwargs):
"""
Get details about a specific section.
:calls: `GET /api/v1/sections/:id \
<https://canvas.instructure.com/doc/api/sections.html#method.sections.show>`_
:param section: The object or ID of the section to get.
:type section: :class:`canvasapi.section.Section` or int
:param use_sis_id: Whether or not section_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.section.Section`
"""
if use_sis_id:
section_id = section
uri_str = 'sections/sis_section_id:{}'
else:
section_id = obj_or_id(section, "section", (Section,))
uri_str = 'sections/{}'
response = self.__requester.request(
'GET',
uri_str.format(section_id),
_kwargs=combine_kwargs(**kwargs)
)
return Section(self.__requester, response.json()) | python | def get_section(self, section, use_sis_id=False, **kwargs):
if use_sis_id:
section_id = section
uri_str = 'sections/sis_section_id:{}'
else:
section_id = obj_or_id(section, "section", (Section,))
uri_str = 'sections/{}'
response = self.__requester.request(
'GET',
uri_str.format(section_id),
_kwargs=combine_kwargs(**kwargs)
)
return Section(self.__requester, response.json()) | [
"def",
"get_section",
"(",
"self",
",",
"section",
",",
"use_sis_id",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"use_sis_id",
":",
"section_id",
"=",
"section",
"uri_str",
"=",
"'sections/sis_section_id:{}'",
"else",
":",
"section_id",
"=",
"obj... | Get details about a specific section.
:calls: `GET /api/v1/sections/:id \
<https://canvas.instructure.com/doc/api/sections.html#method.sections.show>`_
:param section: The object or ID of the section to get.
:type section: :class:`canvasapi.section.Section` or int
:param use_sis_id: Whether or not section_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.section.Section` | [
"Get",
"details",
"about",
"a",
"specific",
"section",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L311-L338 |
232,014 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.set_course_nickname | def set_course_nickname(self, course, nickname):
"""
Set a nickname for the given course. This will replace the
course's name in the output of subsequent API calls, as
well as in selected places in the Canvas web user interface.
:calls: `PUT /api/v1/users/self/course_nicknames/:course_id \
<https://canvas.instructure.com/doc/api/users.html#method.course_nicknames.update>`_
:param course: The ID of the course.
:type course: :class:`canvasapi.course.Course` or int
:param nickname: The nickname for the course.
:type nickname: str
:rtype: :class:`canvasapi.course.CourseNickname`
"""
from canvasapi.course import CourseNickname
course_id = obj_or_id(course, "course", (Course,))
response = self.__requester.request(
'PUT',
'users/self/course_nicknames/{}'.format(course_id),
nickname=nickname
)
return CourseNickname(self.__requester, response.json()) | python | def set_course_nickname(self, course, nickname):
from canvasapi.course import CourseNickname
course_id = obj_or_id(course, "course", (Course,))
response = self.__requester.request(
'PUT',
'users/self/course_nicknames/{}'.format(course_id),
nickname=nickname
)
return CourseNickname(self.__requester, response.json()) | [
"def",
"set_course_nickname",
"(",
"self",
",",
"course",
",",
"nickname",
")",
":",
"from",
"canvasapi",
".",
"course",
"import",
"CourseNickname",
"course_id",
"=",
"obj_or_id",
"(",
"course",
",",
"\"course\"",
",",
"(",
"Course",
",",
")",
")",
"response... | Set a nickname for the given course. This will replace the
course's name in the output of subsequent API calls, as
well as in selected places in the Canvas web user interface.
:calls: `PUT /api/v1/users/self/course_nicknames/:course_id \
<https://canvas.instructure.com/doc/api/users.html#method.course_nicknames.update>`_
:param course: The ID of the course.
:type course: :class:`canvasapi.course.Course` or int
:param nickname: The nickname for the course.
:type nickname: str
:rtype: :class:`canvasapi.course.CourseNickname` | [
"Set",
"a",
"nickname",
"for",
"the",
"given",
"course",
".",
"This",
"will",
"replace",
"the",
"course",
"s",
"name",
"in",
"the",
"output",
"of",
"subsequent",
"API",
"calls",
"as",
"well",
"as",
"in",
"selected",
"places",
"in",
"the",
"Canvas",
"web"... | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L340-L365 |
232,015 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.search_accounts | def search_accounts(self, **kwargs):
"""
Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.search>`_
:rtype: dict
"""
response = self.__requester.request(
'GET',
'accounts/search',
_kwargs=combine_kwargs(**kwargs)
)
return response.json() | python | def search_accounts(self, **kwargs):
response = self.__requester.request(
'GET',
'accounts/search',
_kwargs=combine_kwargs(**kwargs)
)
return response.json() | [
"def",
"search_accounts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
",",
"'accounts/search'",
",",
"_kwargs",
"=",
"combine_kwargs",
"(",
"*",
"*",
"kwargs",
")",
")",
"retu... | Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.search>`_
:rtype: dict | [
"Return",
"a",
"list",
"of",
"up",
"to",
"5",
"matching",
"account",
"domains",
".",
"Partial",
"matches",
"on",
"name",
"and",
"domain",
"are",
"supported",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L385-L400 |
232,016 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_group | def get_group(self, group, use_sis_id=False, **kwargs):
"""
Return the data for a single group. If the caller does not
have permission to view the group a 401 will be returned.
:calls: `GET /api/v1/groups/:group_id \
<https://canvas.instructure.com/doc/api/groups.html#method.groups.show>`_
:param group: The object or ID of the group to get.
:type group: :class:`canvasapi.group.Group` or int
:param use_sis_id: Whether or not group_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.group.Group`
"""
if use_sis_id:
group_id = group
uri_str = 'groups/sis_group_id:{}'
else:
group_id = obj_or_id(group, "group", (Group,))
uri_str = 'groups/{}'
response = self.__requester.request(
'GET',
uri_str.format(group_id),
_kwargs=combine_kwargs(**kwargs)
)
return Group(self.__requester, response.json()) | python | def get_group(self, group, use_sis_id=False, **kwargs):
if use_sis_id:
group_id = group
uri_str = 'groups/sis_group_id:{}'
else:
group_id = obj_or_id(group, "group", (Group,))
uri_str = 'groups/{}'
response = self.__requester.request(
'GET',
uri_str.format(group_id),
_kwargs=combine_kwargs(**kwargs)
)
return Group(self.__requester, response.json()) | [
"def",
"get_group",
"(",
"self",
",",
"group",
",",
"use_sis_id",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"use_sis_id",
":",
"group_id",
"=",
"group",
"uri_str",
"=",
"'groups/sis_group_id:{}'",
"else",
":",
"group_id",
"=",
"obj_or_id",
"("... | Return the data for a single group. If the caller does not
have permission to view the group a 401 will be returned.
:calls: `GET /api/v1/groups/:group_id \
<https://canvas.instructure.com/doc/api/groups.html#method.groups.show>`_
:param group: The object or ID of the group to get.
:type group: :class:`canvasapi.group.Group` or int
:param use_sis_id: Whether or not group_id is an sis ID.
Defaults to `False`.
:type use_sis_id: bool
:rtype: :class:`canvasapi.group.Group` | [
"Return",
"the",
"data",
"for",
"a",
"single",
"group",
".",
"If",
"the",
"caller",
"does",
"not",
"have",
"permission",
"to",
"view",
"the",
"group",
"a",
"401",
"will",
"be",
"returned",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L418-L448 |
232,017 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_group_category | def get_group_category(self, category):
"""
Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
:type category: :class:`canvasapi.group.GroupCategory` or int
:rtype: :class:`canvasapi.group.GroupCategory`
"""
category_id = obj_or_id(category, "category", (GroupCategory,))
response = self.__requester.request(
'GET',
'group_categories/{}'.format(category_id)
)
return GroupCategory(self.__requester, response.json()) | python | def get_group_category(self, category):
category_id = obj_or_id(category, "category", (GroupCategory,))
response = self.__requester.request(
'GET',
'group_categories/{}'.format(category_id)
)
return GroupCategory(self.__requester, response.json()) | [
"def",
"get_group_category",
"(",
"self",
",",
"category",
")",
":",
"category_id",
"=",
"obj_or_id",
"(",
"category",
",",
"\"category\"",
",",
"(",
"GroupCategory",
",",
")",
")",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
... | Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
:type category: :class:`canvasapi.group.GroupCategory` or int
:rtype: :class:`canvasapi.group.GroupCategory` | [
"Get",
"a",
"single",
"group",
"category",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L450-L468 |
232,018 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.create_conversation | def create_conversation(self, recipients, body, **kwargs):
"""
Create a new Conversation.
:calls: `POST /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.create>`_
:param recipients: An array of recipient ids.
These may be user ids or course/group ids prefixed
with 'course\\_' or 'group\\_' respectively,
e.g. recipients=['1', '2', 'course_3']
:type recipients: `list` of `str`
:param body: The body of the message being added.
:type body: `str`
:rtype: list of :class:`canvasapi.conversation.Conversation`
"""
from canvasapi.conversation import Conversation
kwargs['recipients'] = recipients
kwargs['body'] = body
response = self.__requester.request(
'POST',
'conversations',
_kwargs=combine_kwargs(**kwargs)
)
return [Conversation(self.__requester, convo) for convo in response.json()] | python | def create_conversation(self, recipients, body, **kwargs):
from canvasapi.conversation import Conversation
kwargs['recipients'] = recipients
kwargs['body'] = body
response = self.__requester.request(
'POST',
'conversations',
_kwargs=combine_kwargs(**kwargs)
)
return [Conversation(self.__requester, convo) for convo in response.json()] | [
"def",
"create_conversation",
"(",
"self",
",",
"recipients",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"conversation",
"import",
"Conversation",
"kwargs",
"[",
"'recipients'",
"]",
"=",
"recipients",
"kwargs",
"[",
"'body'",
... | Create a new Conversation.
:calls: `POST /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.create>`_
:param recipients: An array of recipient ids.
These may be user ids or course/group ids prefixed
with 'course\\_' or 'group\\_' respectively,
e.g. recipients=['1', '2', 'course_3']
:type recipients: `list` of `str`
:param body: The body of the message being added.
:type body: `str`
:rtype: list of :class:`canvasapi.conversation.Conversation` | [
"Create",
"a",
"new",
"Conversation",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L470-L496 |
232,019 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_conversation | def get_conversation(self, conversation, **kwargs):
"""
Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
:type conversation: :class:`canvasapi.conversation.Conversation` or int
:rtype: :class:`canvasapi.conversation.Conversation`
"""
from canvasapi.conversation import Conversation
conversation_id = obj_or_id(conversation, "conversation", (Conversation,))
response = self.__requester.request(
'GET',
'conversations/{}'.format(conversation_id),
_kwargs=combine_kwargs(**kwargs)
)
return Conversation(self.__requester, response.json()) | python | def get_conversation(self, conversation, **kwargs):
from canvasapi.conversation import Conversation
conversation_id = obj_or_id(conversation, "conversation", (Conversation,))
response = self.__requester.request(
'GET',
'conversations/{}'.format(conversation_id),
_kwargs=combine_kwargs(**kwargs)
)
return Conversation(self.__requester, response.json()) | [
"def",
"get_conversation",
"(",
"self",
",",
"conversation",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"conversation",
"import",
"Conversation",
"conversation_id",
"=",
"obj_or_id",
"(",
"conversation",
",",
"\"conversation\"",
",",
"(",
"Conv... | Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
:type conversation: :class:`canvasapi.conversation.Conversation` or int
:rtype: :class:`canvasapi.conversation.Conversation` | [
"Return",
"single",
"Conversation"
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L498-L519 |
232,020 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_conversations | def get_conversations(self, **kwargs):
"""
Return list of conversations for the current user, most resent ones first.
:calls: `GET /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of \
:class:`canvasapi.conversation.Conversation`
"""
from canvasapi.conversation import Conversation
return PaginatedList(
Conversation,
self.__requester,
'GET',
'conversations',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_conversations(self, **kwargs):
from canvasapi.conversation import Conversation
return PaginatedList(
Conversation,
self.__requester,
'GET',
'conversations',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_conversations",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"conversation",
"import",
"Conversation",
"return",
"PaginatedList",
"(",
"Conversation",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'conversations'",... | Return list of conversations for the current user, most resent ones first.
:calls: `GET /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of \
:class:`canvasapi.conversation.Conversation` | [
"Return",
"list",
"of",
"conversations",
"for",
"the",
"current",
"user",
"most",
"resent",
"ones",
"first",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L521-L539 |
232,021 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.create_calendar_event | def create_calendar_event(self, calendar_event, **kwargs):
"""
Create a new Calendar Event.
:calls: `POST /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.create>`_
:param calendar_event: The attributes of the calendar event.
:type calendar_event: `dict`
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
from canvasapi.calendar_event import CalendarEvent
if isinstance(calendar_event, dict) and 'context_code' in calendar_event:
kwargs['calendar_event'] = calendar_event
else:
raise RequiredFieldMissing(
"Dictionary with key 'context_codes' is required."
)
response = self.__requester.request(
'POST',
'calendar_events',
_kwargs=combine_kwargs(**kwargs)
)
return CalendarEvent(self.__requester, response.json()) | python | def create_calendar_event(self, calendar_event, **kwargs):
from canvasapi.calendar_event import CalendarEvent
if isinstance(calendar_event, dict) and 'context_code' in calendar_event:
kwargs['calendar_event'] = calendar_event
else:
raise RequiredFieldMissing(
"Dictionary with key 'context_codes' is required."
)
response = self.__requester.request(
'POST',
'calendar_events',
_kwargs=combine_kwargs(**kwargs)
)
return CalendarEvent(self.__requester, response.json()) | [
"def",
"create_calendar_event",
"(",
"self",
",",
"calendar_event",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"calendar_event",
"import",
"CalendarEvent",
"if",
"isinstance",
"(",
"calendar_event",
",",
"dict",
")",
"and",
"'context_code'",
"i... | Create a new Calendar Event.
:calls: `POST /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.create>`_
:param calendar_event: The attributes of the calendar event.
:type calendar_event: `dict`
:rtype: :class:`canvasapi.calendar_event.CalendarEvent` | [
"Create",
"a",
"new",
"Calendar",
"Event",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L645-L671 |
232,022 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_calendar_events | def get_calendar_events(self, **kwargs):
"""
List calendar events.
:calls: `GET /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.calendar_event.CalendarEvent`
"""
from canvasapi.calendar_event import CalendarEvent
return PaginatedList(
CalendarEvent,
self.__requester,
'GET',
'calendar_events',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_calendar_events(self, **kwargs):
from canvasapi.calendar_event import CalendarEvent
return PaginatedList(
CalendarEvent,
self.__requester,
'GET',
'calendar_events',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_calendar_events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"calendar_event",
"import",
"CalendarEvent",
"return",
"PaginatedList",
"(",
"CalendarEvent",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'calendar_e... | List calendar events.
:calls: `GET /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.calendar_event.CalendarEvent` | [
"List",
"calendar",
"events",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L695-L713 |
232,023 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_appointment_groups | def get_appointment_groups(self, **kwargs):
"""
List appointment groups.
:calls: `GET /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.appointment_group.AppointmentGroup`
"""
from canvasapi.appointment_group import AppointmentGroup
return PaginatedList(
AppointmentGroup,
self.__requester,
'GET',
'appointment_groups',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_appointment_groups(self, **kwargs):
from canvasapi.appointment_group import AppointmentGroup
return PaginatedList(
AppointmentGroup,
self.__requester,
'GET',
'appointment_groups',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_appointment_groups",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"appointment_group",
"import",
"AppointmentGroup",
"return",
"PaginatedList",
"(",
"AppointmentGroup",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
... | List appointment groups.
:calls: `GET /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.appointment_group.AppointmentGroup` | [
"List",
"appointment",
"groups",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L792-L810 |
232,024 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_appointment_group | def get_appointment_group(self, appointment_group):
"""
Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the appointment group.
:type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int
:rtype: :class:`canvasapi.appointment_group.AppointmentGroup`
"""
from canvasapi.appointment_group import AppointmentGroup
appointment_group_id = obj_or_id(
appointment_group, "appointment_group", (AppointmentGroup,)
)
response = self.__requester.request(
'GET',
'appointment_groups/{}'.format(appointment_group_id)
)
return AppointmentGroup(self.__requester, response.json()) | python | def get_appointment_group(self, appointment_group):
from canvasapi.appointment_group import AppointmentGroup
appointment_group_id = obj_or_id(
appointment_group, "appointment_group", (AppointmentGroup,)
)
response = self.__requester.request(
'GET',
'appointment_groups/{}'.format(appointment_group_id)
)
return AppointmentGroup(self.__requester, response.json()) | [
"def",
"get_appointment_group",
"(",
"self",
",",
"appointment_group",
")",
":",
"from",
"canvasapi",
".",
"appointment_group",
"import",
"AppointmentGroup",
"appointment_group_id",
"=",
"obj_or_id",
"(",
"appointment_group",
",",
"\"appointment_group\"",
",",
"(",
"App... | Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the appointment group.
:type appointment_group: :class:`canvasapi.appointment_group.AppointmentGroup` or int
:rtype: :class:`canvasapi.appointment_group.AppointmentGroup` | [
"Return",
"single",
"Appointment",
"Group",
"by",
"id"
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L812-L834 |
232,025 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.create_appointment_group | def create_appointment_group(self, appointment_group, **kwargs):
"""
Create a new Appointment Group.
:calls: `POST /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.create>`_
:param appointment_group: The attributes of the appointment group.
:type appointment_group: `dict`
:param title: The title of the appointment group.
:type title: `str`
:rtype: :class:`canvasapi.appointment_group.AppointmentGroup`
"""
from canvasapi.appointment_group import AppointmentGroup
if (
isinstance(appointment_group, dict) and
'context_codes' in appointment_group and
'title' in appointment_group
):
kwargs['appointment_group'] = appointment_group
elif (
isinstance(appointment_group, dict) and
'context_codes' not in appointment_group
):
raise RequiredFieldMissing(
"Dictionary with key 'context_codes' is missing."
)
elif isinstance(appointment_group, dict) and 'title' not in appointment_group:
raise RequiredFieldMissing("Dictionary with key 'title' is missing.")
response = self.__requester.request(
'POST',
'appointment_groups',
_kwargs=combine_kwargs(**kwargs)
)
return AppointmentGroup(self.__requester, response.json()) | python | def create_appointment_group(self, appointment_group, **kwargs):
from canvasapi.appointment_group import AppointmentGroup
if (
isinstance(appointment_group, dict) and
'context_codes' in appointment_group and
'title' in appointment_group
):
kwargs['appointment_group'] = appointment_group
elif (
isinstance(appointment_group, dict) and
'context_codes' not in appointment_group
):
raise RequiredFieldMissing(
"Dictionary with key 'context_codes' is missing."
)
elif isinstance(appointment_group, dict) and 'title' not in appointment_group:
raise RequiredFieldMissing("Dictionary with key 'title' is missing.")
response = self.__requester.request(
'POST',
'appointment_groups',
_kwargs=combine_kwargs(**kwargs)
)
return AppointmentGroup(self.__requester, response.json()) | [
"def",
"create_appointment_group",
"(",
"self",
",",
"appointment_group",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"appointment_group",
"import",
"AppointmentGroup",
"if",
"(",
"isinstance",
"(",
"appointment_group",
",",
"dict",
")",
"and",
... | Create a new Appointment Group.
:calls: `POST /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.create>`_
:param appointment_group: The attributes of the appointment group.
:type appointment_group: `dict`
:param title: The title of the appointment group.
:type title: `str`
:rtype: :class:`canvasapi.appointment_group.AppointmentGroup` | [
"Create",
"a",
"new",
"Appointment",
"Group",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L836-L875 |
232,026 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_file | def get_file(self, file, **kwargs):
"""
Return the standard attachment json object for a file.
:calls: `GET /api/v1/files/:id \
<https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_
:param file: The object or ID of the file to retrieve.
:type file: :class:`canvasapi.file.File` or int
:rtype: :class:`canvasapi.file.File`
"""
file_id = obj_or_id(file, "file", (File,))
response = self.__requester.request(
'GET',
'files/{}'.format(file_id),
_kwargs=combine_kwargs(**kwargs)
)
return File(self.__requester, response.json()) | python | def get_file(self, file, **kwargs):
file_id = obj_or_id(file, "file", (File,))
response = self.__requester.request(
'GET',
'files/{}'.format(file_id),
_kwargs=combine_kwargs(**kwargs)
)
return File(self.__requester, response.json()) | [
"def",
"get_file",
"(",
"self",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"file_id",
"=",
"obj_or_id",
"(",
"file",
",",
"\"file\"",
",",
"(",
"File",
",",
")",
")",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
"... | Return the standard attachment json object for a file.
:calls: `GET /api/v1/files/:id \
<https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_
:param file: The object or ID of the file to retrieve.
:type file: :class:`canvasapi.file.File` or int
:rtype: :class:`canvasapi.file.File` | [
"Return",
"the",
"standard",
"attachment",
"json",
"object",
"for",
"a",
"file",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L979-L998 |
232,027 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_folder | def get_folder(self, folder):
"""
Return the details for a folder
:calls: `GET /api/v1/folders/:id \
<https://canvas.instructure.com/doc/api/files.html#method.folders.show>`_
:param folder: The object or ID of the folder to retrieve.
:type folder: :class:`canvasapi.folder.Folder` or int
:rtype: :class:`canvasapi.folder.Folder`
"""
folder_id = obj_or_id(folder, "folder", (Folder,))
response = self.__requester.request(
'GET',
'folders/{}'.format(folder_id)
)
return Folder(self.__requester, response.json()) | python | def get_folder(self, folder):
folder_id = obj_or_id(folder, "folder", (Folder,))
response = self.__requester.request(
'GET',
'folders/{}'.format(folder_id)
)
return Folder(self.__requester, response.json()) | [
"def",
"get_folder",
"(",
"self",
",",
"folder",
")",
":",
"folder_id",
"=",
"obj_or_id",
"(",
"folder",
",",
"\"folder\"",
",",
"(",
"Folder",
",",
")",
")",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
",",
"'folders/{}'",... | Return the details for a folder
:calls: `GET /api/v1/folders/:id \
<https://canvas.instructure.com/doc/api/files.html#method.folders.show>`_
:param folder: The object or ID of the folder to retrieve.
:type folder: :class:`canvasapi.folder.Folder` or int
:rtype: :class:`canvasapi.folder.Folder` | [
"Return",
"the",
"details",
"for",
"a",
"folder"
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1000-L1018 |
232,028 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_outcome | def get_outcome(self, outcome):
"""
Returns the details of the outcome with the given id.
:calls: `GET /api/v1/outcomes/:id \
<https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_
:param outcome: The outcome object or ID to return.
:type outcome: :class:`canvasapi.outcome.Outcome` or int
:returns: An Outcome object.
:rtype: :class:`canvasapi.outcome.Outcome`
"""
from canvasapi.outcome import Outcome
outcome_id = obj_or_id(outcome, "outcome", (Outcome,))
response = self.__requester.request(
'GET',
'outcomes/{}'.format(outcome_id)
)
return Outcome(self.__requester, response.json()) | python | def get_outcome(self, outcome):
from canvasapi.outcome import Outcome
outcome_id = obj_or_id(outcome, "outcome", (Outcome,))
response = self.__requester.request(
'GET',
'outcomes/{}'.format(outcome_id)
)
return Outcome(self.__requester, response.json()) | [
"def",
"get_outcome",
"(",
"self",
",",
"outcome",
")",
":",
"from",
"canvasapi",
".",
"outcome",
"import",
"Outcome",
"outcome_id",
"=",
"obj_or_id",
"(",
"outcome",
",",
"\"outcome\"",
",",
"(",
"Outcome",
",",
")",
")",
"response",
"=",
"self",
".",
"... | Returns the details of the outcome with the given id.
:calls: `GET /api/v1/outcomes/:id \
<https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_
:param outcome: The outcome object or ID to return.
:type outcome: :class:`canvasapi.outcome.Outcome` or int
:returns: An Outcome object.
:rtype: :class:`canvasapi.outcome.Outcome` | [
"Returns",
"the",
"details",
"of",
"the",
"outcome",
"with",
"the",
"given",
"id",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1058-L1078 |
232,029 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_root_outcome_group | def get_root_outcome_group(self):
"""
Redirect to root outcome group for context
:calls: `GET /api/v1/global/root_outcome_group \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.redirect>`_
:returns: The OutcomeGroup of the context.
:rtype: :class:`canvasapi.outcome.OutcomeGroup`
"""
from canvasapi.outcome import OutcomeGroup
response = self.__requester.request(
'GET',
'global/root_outcome_group'
)
return OutcomeGroup(self.__requester, response.json()) | python | def get_root_outcome_group(self):
from canvasapi.outcome import OutcomeGroup
response = self.__requester.request(
'GET',
'global/root_outcome_group'
)
return OutcomeGroup(self.__requester, response.json()) | [
"def",
"get_root_outcome_group",
"(",
"self",
")",
":",
"from",
"canvasapi",
".",
"outcome",
"import",
"OutcomeGroup",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
",",
"'global/root_outcome_group'",
")",
"return",
"OutcomeGroup",
"("... | Redirect to root outcome group for context
:calls: `GET /api/v1/global/root_outcome_group \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.redirect>`_
:returns: The OutcomeGroup of the context.
:rtype: :class:`canvasapi.outcome.OutcomeGroup` | [
"Redirect",
"to",
"root",
"outcome",
"group",
"for",
"context"
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1080-L1096 |
232,030 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_outcome_group | def get_outcome_group(self, group):
"""
Returns the details of the Outcome Group with the given id.
:calls: `GET /api/v1/global/outcome_groups/:id \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.show>`_
:param group: The outcome group object or ID to return.
:type group: :class:`canvasapi.outcome.OutcomeGroup` or int
:returns: An outcome group object.
:rtype: :class:`canvasapi.outcome.OutcomeGroup`
"""
from canvasapi.outcome import OutcomeGroup
outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,))
response = self.__requester.request(
'GET',
'global/outcome_groups/{}'.format(outcome_group_id)
)
return OutcomeGroup(self.__requester, response.json()) | python | def get_outcome_group(self, group):
from canvasapi.outcome import OutcomeGroup
outcome_group_id = obj_or_id(group, "group", (OutcomeGroup,))
response = self.__requester.request(
'GET',
'global/outcome_groups/{}'.format(outcome_group_id)
)
return OutcomeGroup(self.__requester, response.json()) | [
"def",
"get_outcome_group",
"(",
"self",
",",
"group",
")",
":",
"from",
"canvasapi",
".",
"outcome",
"import",
"OutcomeGroup",
"outcome_group_id",
"=",
"obj_or_id",
"(",
"group",
",",
"\"group\"",
",",
"(",
"OutcomeGroup",
",",
")",
")",
"response",
"=",
"s... | Returns the details of the Outcome Group with the given id.
:calls: `GET /api/v1/global/outcome_groups/:id \
<https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.show>`_
:param group: The outcome group object or ID to return.
:type group: :class:`canvasapi.outcome.OutcomeGroup` or int
:returns: An outcome group object.
:rtype: :class:`canvasapi.outcome.OutcomeGroup` | [
"Returns",
"the",
"details",
"of",
"the",
"Outcome",
"Group",
"with",
"the",
"given",
"id",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1098-L1120 |
232,031 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_progress | def get_progress(self, progress, **kwargs):
"""
Get a specific progress.
:calls: `GET /api/v1/progress/:id
<https://canvas.instructure.com/doc/api/progress.html#method.progress.show>`_
:param progress: The object or ID of the progress to retrieve.
:type progress: int, str or :class:`canvasapi.progress.Progress`
:rtype: :class:`canvasapi.progress.Progress`
"""
from canvasapi.progress import Progress
progress_id = obj_or_id(progress, "progress", (Progress,))
response = self.__requester.request(
'GET',
'progress/{}'.format(progress_id),
_kwargs=combine_kwargs(**kwargs)
)
return Progress(self.__requester, response.json()) | python | def get_progress(self, progress, **kwargs):
from canvasapi.progress import Progress
progress_id = obj_or_id(progress, "progress", (Progress,))
response = self.__requester.request(
'GET',
'progress/{}'.format(progress_id),
_kwargs=combine_kwargs(**kwargs)
)
return Progress(self.__requester, response.json()) | [
"def",
"get_progress",
"(",
"self",
",",
"progress",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"progress",
"import",
"Progress",
"progress_id",
"=",
"obj_or_id",
"(",
"progress",
",",
"\"progress\"",
",",
"(",
"Progress",
",",
")",
")",
... | Get a specific progress.
:calls: `GET /api/v1/progress/:id
<https://canvas.instructure.com/doc/api/progress.html#method.progress.show>`_
:param progress: The object or ID of the progress to retrieve.
:type progress: int, str or :class:`canvasapi.progress.Progress`
:rtype: :class:`canvasapi.progress.Progress` | [
"Get",
"a",
"specific",
"progress",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1122-L1144 |
232,032 | ucfopen/canvasapi | canvasapi/canvas.py | Canvas.get_announcements | def get_announcements(self, **kwargs):
"""
List announcements.
:calls: `GET /api/v1/announcements \
<https://canvas.instructure.com/doc/api/announcements.html#method.announcements_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.discussion_topic.DiscussionTopic`
"""
from canvasapi.discussion_topic import DiscussionTopic
return PaginatedList(
DiscussionTopic,
self.__requester,
'GET',
'announcements',
_kwargs=combine_kwargs(**kwargs)
) | python | def get_announcements(self, **kwargs):
from canvasapi.discussion_topic import DiscussionTopic
return PaginatedList(
DiscussionTopic,
self.__requester,
'GET',
'announcements',
_kwargs=combine_kwargs(**kwargs)
) | [
"def",
"get_announcements",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"discussion_topic",
"import",
"DiscussionTopic",
"return",
"PaginatedList",
"(",
"DiscussionTopic",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'announ... | List announcements.
:calls: `GET /api/v1/announcements \
<https://canvas.instructure.com/doc/api/announcements.html#method.announcements_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.discussion_topic.DiscussionTopic` | [
"List",
"announcements",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1146-L1163 |
232,033 | ucfopen/canvasapi | canvasapi/util.py | is_multivalued | def is_multivalued(value):
"""
Determine whether the given value should be treated as a sequence
of multiple values when used as a request parameter.
In general anything that is iterable is multivalued. For example,
`list` and `tuple` instances are multivalued. Generators are
multivalued, as are the iterable objects returned by `zip`,
`itertools.chain`, etc. However, a simple `int` is single-valued.
`str` and `bytes` are special cases: although these are iterable,
we treat each as a single value rather than as a sequence of
isolated characters or bytes.
"""
# special cases: iterable, but not multivalued
if isinstance(value, (string_types, binary_type)):
return False
# general rule: multivalued if iterable
return isinstance(value, Iterable) | python | def is_multivalued(value):
# special cases: iterable, but not multivalued
if isinstance(value, (string_types, binary_type)):
return False
# general rule: multivalued if iterable
return isinstance(value, Iterable) | [
"def",
"is_multivalued",
"(",
"value",
")",
":",
"# special cases: iterable, but not multivalued",
"if",
"isinstance",
"(",
"value",
",",
"(",
"string_types",
",",
"binary_type",
")",
")",
":",
"return",
"False",
"# general rule: multivalued if iterable",
"return",
"isi... | Determine whether the given value should be treated as a sequence
of multiple values when used as a request parameter.
In general anything that is iterable is multivalued. For example,
`list` and `tuple` instances are multivalued. Generators are
multivalued, as are the iterable objects returned by `zip`,
`itertools.chain`, etc. However, a simple `int` is single-valued.
`str` and `bytes` are special cases: although these are iterable,
we treat each as a single value rather than as a sequence of
isolated characters or bytes. | [
"Determine",
"whether",
"the",
"given",
"value",
"should",
"be",
"treated",
"as",
"a",
"sequence",
"of",
"multiple",
"values",
"when",
"used",
"as",
"a",
"request",
"parameter",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/util.py#L9-L28 |
232,034 | ucfopen/canvasapi | canvasapi/util.py | combine_kwargs | def combine_kwargs(**kwargs):
"""
Flatten a series of keyword arguments from complex combinations of
dictionaries and lists into a list of tuples representing
properly-formatted parameters to pass to the Requester object.
:param kwargs: A dictionary containing keyword arguments to be
flattened into properly-formatted parameters.
:type kwargs: dict
:returns: A list of tuples that represent flattened kwargs. The
first element is a string representing the key. The second
element is the value.
:rtype: `list` of `tuple`
"""
combined_kwargs = []
# Loop through all kwargs provided
for kw, arg in kwargs.items():
if isinstance(arg, dict):
for k, v in arg.items():
for tup in flatten_kwarg(k, v):
combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))
elif is_multivalued(arg):
for i in arg:
for tup in flatten_kwarg('', i):
combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))
else:
combined_kwargs.append((text_type(kw), arg))
return combined_kwargs | python | def combine_kwargs(**kwargs):
combined_kwargs = []
# Loop through all kwargs provided
for kw, arg in kwargs.items():
if isinstance(arg, dict):
for k, v in arg.items():
for tup in flatten_kwarg(k, v):
combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))
elif is_multivalued(arg):
for i in arg:
for tup in flatten_kwarg('', i):
combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))
else:
combined_kwargs.append((text_type(kw), arg))
return combined_kwargs | [
"def",
"combine_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"combined_kwargs",
"=",
"[",
"]",
"# Loop through all kwargs provided",
"for",
"kw",
",",
"arg",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":... | Flatten a series of keyword arguments from complex combinations of
dictionaries and lists into a list of tuples representing
properly-formatted parameters to pass to the Requester object.
:param kwargs: A dictionary containing keyword arguments to be
flattened into properly-formatted parameters.
:type kwargs: dict
:returns: A list of tuples that represent flattened kwargs. The
first element is a string representing the key. The second
element is the value.
:rtype: `list` of `tuple` | [
"Flatten",
"a",
"series",
"of",
"keyword",
"arguments",
"from",
"complex",
"combinations",
"of",
"dictionaries",
"and",
"lists",
"into",
"a",
"list",
"of",
"tuples",
"representing",
"properly",
"-",
"formatted",
"parameters",
"to",
"pass",
"to",
"the",
"Requeste... | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/util.py#L31-L61 |
232,035 | ucfopen/canvasapi | canvasapi/util.py | flatten_kwarg | def flatten_kwarg(key, obj):
"""
Recursive call to flatten sections of a kwarg to be combined
:param key: The partial keyword to add to the full keyword
:type key: str
:param obj: The object to translate into a kwarg. If the type is
`dict`, the key parameter will be added to the keyword between
square brackets and recursively call this function. If the type
is `list`, or `tuple`, a set of empty brackets will be appended
to the keyword and recursively call this function. Otherwise,
the function returns with the final keyword and value.
:returns: A list of tuples that represent flattened kwargs. The
first element is a string representing the key. The second
element is the value.
:rtype: `list` of `tuple`
"""
if isinstance(obj, dict):
# Add the word (e.g. "[key]")
new_list = []
for k, v in obj.items():
for tup in flatten_kwarg(k, v):
new_list.append(('[{}]{}'.format(key, tup[0]), tup[1]))
return new_list
elif is_multivalued(obj):
# Add empty brackets (i.e. "[]")
new_list = []
for i in obj:
for tup in flatten_kwarg(key + '][', i):
new_list.append((tup[0], tup[1]))
return new_list
else:
# Base case. Return list with tuple containing the value
return [('[{}]'.format(text_type(key)), obj)] | python | def flatten_kwarg(key, obj):
if isinstance(obj, dict):
# Add the word (e.g. "[key]")
new_list = []
for k, v in obj.items():
for tup in flatten_kwarg(k, v):
new_list.append(('[{}]{}'.format(key, tup[0]), tup[1]))
return new_list
elif is_multivalued(obj):
# Add empty brackets (i.e. "[]")
new_list = []
for i in obj:
for tup in flatten_kwarg(key + '][', i):
new_list.append((tup[0], tup[1]))
return new_list
else:
# Base case. Return list with tuple containing the value
return [('[{}]'.format(text_type(key)), obj)] | [
"def",
"flatten_kwarg",
"(",
"key",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"# Add the word (e.g. \"[key]\")",
"new_list",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
":",
"for",
"tup... | Recursive call to flatten sections of a kwarg to be combined
:param key: The partial keyword to add to the full keyword
:type key: str
:param obj: The object to translate into a kwarg. If the type is
`dict`, the key parameter will be added to the keyword between
square brackets and recursively call this function. If the type
is `list`, or `tuple`, a set of empty brackets will be appended
to the keyword and recursively call this function. Otherwise,
the function returns with the final keyword and value.
:returns: A list of tuples that represent flattened kwargs. The
first element is a string representing the key. The second
element is the value.
:rtype: `list` of `tuple` | [
"Recursive",
"call",
"to",
"flatten",
"sections",
"of",
"a",
"kwarg",
"to",
"be",
"combined"
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/util.py#L64-L99 |
232,036 | ucfopen/canvasapi | canvasapi/util.py | get_institution_url | def get_institution_url(base_url):
"""
Clean up a given base URL.
:param base_url: The base URL of the API.
:type base_url: str
:rtype: str
"""
base_url = base_url.rstrip('/')
index = base_url.find('/api/v1')
if index != -1:
return base_url[0:index]
return base_url | python | def get_institution_url(base_url):
base_url = base_url.rstrip('/')
index = base_url.find('/api/v1')
if index != -1:
return base_url[0:index]
return base_url | [
"def",
"get_institution_url",
"(",
"base_url",
")",
":",
"base_url",
"=",
"base_url",
".",
"rstrip",
"(",
"'/'",
")",
"index",
"=",
"base_url",
".",
"find",
"(",
"'/api/v1'",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"return",
"base_url",
"[",
"0",
":",... | Clean up a given base URL.
:param base_url: The base URL of the API.
:type base_url: str
:rtype: str | [
"Clean",
"up",
"a",
"given",
"base",
"URL",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/util.py#L135-L149 |
232,037 | ucfopen/canvasapi | canvasapi/util.py | file_or_path | def file_or_path(file):
"""
Open a file and return the handler if a path is given.
If a file handler is given, return it directly.
:param file: A file handler or path to a file.
:returns: A tuple with the open file handler and whether it was a path.
:rtype: (file, bool)
"""
is_path = False
if isinstance(file, string_types):
if not os.path.exists(file):
raise IOError('File at path ' + file + ' does not exist.')
file = open(file, 'rb')
is_path = True
return file, is_path | python | def file_or_path(file):
is_path = False
if isinstance(file, string_types):
if not os.path.exists(file):
raise IOError('File at path ' + file + ' does not exist.')
file = open(file, 'rb')
is_path = True
return file, is_path | [
"def",
"file_or_path",
"(",
"file",
")",
":",
"is_path",
"=",
"False",
"if",
"isinstance",
"(",
"file",
",",
"string_types",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"raise",
"IOError",
"(",
"'File at path '",
"+"... | Open a file and return the handler if a path is given.
If a file handler is given, return it directly.
:param file: A file handler or path to a file.
:returns: A tuple with the open file handler and whether it was a path.
:rtype: (file, bool) | [
"Open",
"a",
"file",
"and",
"return",
"the",
"handler",
"if",
"a",
"path",
"is",
"given",
".",
"If",
"a",
"file",
"handler",
"is",
"given",
"return",
"it",
"directly",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/util.py#L152-L170 |
232,038 | ucfopen/canvasapi | canvasapi/calendar_event.py | CalendarEvent.delete | def delete(self, **kwargs):
"""
Delete this calendar event.
:calls: `DELETE /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.destroy>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
response = self._requester.request(
'DELETE',
'calendar_events/{}'.format(self.id),
_kwargs=combine_kwargs(**kwargs)
)
return CalendarEvent(self._requester, response.json()) | python | def delete(self, **kwargs):
response = self._requester.request(
'DELETE',
'calendar_events/{}'.format(self.id),
_kwargs=combine_kwargs(**kwargs)
)
return CalendarEvent(self._requester, response.json()) | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_requester",
".",
"request",
"(",
"'DELETE'",
",",
"'calendar_events/{}'",
".",
"format",
"(",
"self",
".",
"id",
")",
",",
"_kwargs",
"=",
"combine_kwargs",
... | Delete this calendar event.
:calls: `DELETE /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.destroy>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent` | [
"Delete",
"this",
"calendar",
"event",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/calendar_event.py#L12-L26 |
232,039 | ucfopen/canvasapi | canvasapi/calendar_event.py | CalendarEvent.edit | def edit(self, **kwargs):
"""
Modify this calendar event.
:calls: `PUT /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.update>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
response = self._requester.request(
'PUT',
'calendar_events/{}'.format(self.id),
_kwargs=combine_kwargs(**kwargs)
)
if 'title' in response.json():
super(CalendarEvent, self).set_attributes(response.json())
return CalendarEvent(self._requester, response.json()) | python | def edit(self, **kwargs):
response = self._requester.request(
'PUT',
'calendar_events/{}'.format(self.id),
_kwargs=combine_kwargs(**kwargs)
)
if 'title' in response.json():
super(CalendarEvent, self).set_attributes(response.json())
return CalendarEvent(self._requester, response.json()) | [
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_requester",
".",
"request",
"(",
"'PUT'",
",",
"'calendar_events/{}'",
".",
"format",
"(",
"self",
".",
"id",
")",
",",
"_kwargs",
"=",
"combine_kwargs",
"("... | Modify this calendar event.
:calls: `PUT /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.update>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent` | [
"Modify",
"this",
"calendar",
"event",
"."
] | 319064b5fc97ba54250af683eb98723ef3f76cf8 | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/calendar_event.py#L28-L46 |
232,040 | CyberZHG/keras-transformer | keras_transformer/transformer.py | _wrap_layer | def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
"""Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the output tensor.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer.
"""
build_output = build_func(input_layer)
if dropout_rate > 0.0:
dropout_layer = keras.layers.Dropout(
rate=dropout_rate,
name='%s-Dropout' % name,
)(build_output)
else:
dropout_layer = build_output
if isinstance(input_layer, list):
input_layer = input_layer[0]
add_layer = keras.layers.Add(name='%s-Add' % name)([input_layer, dropout_layer])
normal_layer = LayerNormalization(
trainable=trainable,
name='%s-Norm' % name,
)(add_layer)
return normal_layer | python | def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
build_output = build_func(input_layer)
if dropout_rate > 0.0:
dropout_layer = keras.layers.Dropout(
rate=dropout_rate,
name='%s-Dropout' % name,
)(build_output)
else:
dropout_layer = build_output
if isinstance(input_layer, list):
input_layer = input_layer[0]
add_layer = keras.layers.Add(name='%s-Add' % name)([input_layer, dropout_layer])
normal_layer = LayerNormalization(
trainable=trainable,
name='%s-Norm' % name,
)(add_layer)
return normal_layer | [
"def",
"_wrap_layer",
"(",
"name",
",",
"input_layer",
",",
"build_func",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"=",
"True",
")",
":",
"build_output",
"=",
"build_func",
"(",
"input_layer",
")",
"if",
"dropout_rate",
">",
"0.0",
":",
"dropout_la... | Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the output tensor.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer. | [
"Wrap",
"layers",
"with",
"residual",
"normalization",
"and",
"dropout",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L27-L52 |
232,041 | CyberZHG/keras-transformer | keras_transformer/transformer.py | attention_builder | def attention_builder(name, head_num, activation, history_only, trainable=True):
"""Get multi-head self-attention builder.
:param name: Prefix of names for internal layers.
:param head_num: Number of heads in multi-head self-attention.
:param activation: Activation for multi-head self-attention.
:param history_only: Only use history data.
:param trainable: Whether the layer is trainable.
:return:
"""
def _attention_builder(x):
return MultiHeadAttention(
head_num=head_num,
activation=activation,
history_only=history_only,
trainable=trainable,
name=name,
)(x)
return _attention_builder | python | def attention_builder(name, head_num, activation, history_only, trainable=True):
def _attention_builder(x):
return MultiHeadAttention(
head_num=head_num,
activation=activation,
history_only=history_only,
trainable=trainable,
name=name,
)(x)
return _attention_builder | [
"def",
"attention_builder",
"(",
"name",
",",
"head_num",
",",
"activation",
",",
"history_only",
",",
"trainable",
"=",
"True",
")",
":",
"def",
"_attention_builder",
"(",
"x",
")",
":",
"return",
"MultiHeadAttention",
"(",
"head_num",
"=",
"head_num",
",",
... | Get multi-head self-attention builder.
:param name: Prefix of names for internal layers.
:param head_num: Number of heads in multi-head self-attention.
:param activation: Activation for multi-head self-attention.
:param history_only: Only use history data.
:param trainable: Whether the layer is trainable.
:return: | [
"Get",
"multi",
"-",
"head",
"self",
"-",
"attention",
"builder",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L55-L73 |
232,042 | CyberZHG/keras-transformer | keras_transformer/transformer.py | feed_forward_builder | def feed_forward_builder(name, hidden_dim, activation, trainable=True):
"""Get position-wise feed-forward layer builder.
:param name: Prefix of names for internal layers.
:param hidden_dim: Hidden dimension of feed forward layer.
:param activation: Activation for feed-forward layer.
:param trainable: Whether the layer is trainable.
:return:
"""
def _feed_forward_builder(x):
return FeedForward(
units=hidden_dim,
activation=activation,
trainable=trainable,
name=name,
)(x)
return _feed_forward_builder | python | def feed_forward_builder(name, hidden_dim, activation, trainable=True):
def _feed_forward_builder(x):
return FeedForward(
units=hidden_dim,
activation=activation,
trainable=trainable,
name=name,
)(x)
return _feed_forward_builder | [
"def",
"feed_forward_builder",
"(",
"name",
",",
"hidden_dim",
",",
"activation",
",",
"trainable",
"=",
"True",
")",
":",
"def",
"_feed_forward_builder",
"(",
"x",
")",
":",
"return",
"FeedForward",
"(",
"units",
"=",
"hidden_dim",
",",
"activation",
"=",
"... | Get position-wise feed-forward layer builder.
:param name: Prefix of names for internal layers.
:param hidden_dim: Hidden dimension of feed forward layer.
:param activation: Activation for feed-forward layer.
:param trainable: Whether the layer is trainable.
:return: | [
"Get",
"position",
"-",
"wise",
"feed",
"-",
"forward",
"layer",
"builder",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L76-L92 |
232,043 | CyberZHG/keras-transformer | keras_transformer/transformer.py | get_encoder_component | def get_encoder_component(name,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Multi-head self-attention and feed-forward layer.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer.
"""
attention_name = '%s-MultiHeadSelfAttention' % name
feed_forward_name = '%s-FeedForward' % name
attention_layer = _wrap_layer(
name=attention_name,
input_layer=input_layer,
build_func=attention_builder(
name=attention_name,
head_num=head_num,
activation=attention_activation,
history_only=False,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
feed_forward_layer = _wrap_layer(
name=feed_forward_name,
input_layer=attention_layer,
build_func=feed_forward_builder(
name=feed_forward_name,
hidden_dim=hidden_dim,
activation=feed_forward_activation,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
return feed_forward_layer | python | def get_encoder_component(name,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
attention_name = '%s-MultiHeadSelfAttention' % name
feed_forward_name = '%s-FeedForward' % name
attention_layer = _wrap_layer(
name=attention_name,
input_layer=input_layer,
build_func=attention_builder(
name=attention_name,
head_num=head_num,
activation=attention_activation,
history_only=False,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
feed_forward_layer = _wrap_layer(
name=feed_forward_name,
input_layer=attention_layer,
build_func=feed_forward_builder(
name=feed_forward_name,
hidden_dim=hidden_dim,
activation=feed_forward_activation,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
return feed_forward_layer | [
"def",
"get_encoder_component",
"(",
"name",
",",
"input_layer",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"=",
"True",
")",
":"... | Multi-head self-attention and feed-forward layer.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer. | [
"Multi",
"-",
"head",
"self",
"-",
"attention",
"and",
"feed",
"-",
"forward",
"layer",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L95-L142 |
232,044 | CyberZHG/keras-transformer | keras_transformer/transformer.py | get_decoder_component | def get_decoder_component(name,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Multi-head self-attention, multi-head query attention and feed-forward layer.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param encoded_layer: Encoded layer from encoder.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer.
"""
self_attention_name = '%s-MultiHeadSelfAttention' % name
query_attention_name = '%s-MultiHeadQueryAttention' % name
feed_forward_name = '%s-FeedForward' % name
self_attention_layer = _wrap_layer(
name=self_attention_name,
input_layer=input_layer,
build_func=attention_builder(
name=self_attention_name,
head_num=head_num,
activation=attention_activation,
history_only=True,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
query_attention_layer = _wrap_layer(
name=query_attention_name,
input_layer=[self_attention_layer, encoded_layer, encoded_layer],
build_func=attention_builder(
name=query_attention_name,
head_num=head_num,
activation=attention_activation,
history_only=False,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
feed_forward_layer = _wrap_layer(
name=feed_forward_name,
input_layer=query_attention_layer,
build_func=feed_forward_builder(
name=feed_forward_name,
hidden_dim=hidden_dim,
activation=feed_forward_activation,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
return feed_forward_layer | python | def get_decoder_component(name,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
self_attention_name = '%s-MultiHeadSelfAttention' % name
query_attention_name = '%s-MultiHeadQueryAttention' % name
feed_forward_name = '%s-FeedForward' % name
self_attention_layer = _wrap_layer(
name=self_attention_name,
input_layer=input_layer,
build_func=attention_builder(
name=self_attention_name,
head_num=head_num,
activation=attention_activation,
history_only=True,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
query_attention_layer = _wrap_layer(
name=query_attention_name,
input_layer=[self_attention_layer, encoded_layer, encoded_layer],
build_func=attention_builder(
name=query_attention_name,
head_num=head_num,
activation=attention_activation,
history_only=False,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
feed_forward_layer = _wrap_layer(
name=feed_forward_name,
input_layer=query_attention_layer,
build_func=feed_forward_builder(
name=feed_forward_name,
hidden_dim=hidden_dim,
activation=feed_forward_activation,
trainable=trainable,
),
dropout_rate=dropout_rate,
trainable=trainable,
)
return feed_forward_layer | [
"def",
"get_decoder_component",
"(",
"name",
",",
"input_layer",
",",
"encoded_layer",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"... | Multi-head self-attention, multi-head query attention and feed-forward layer.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param encoded_layer: Encoded layer from encoder.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer. | [
"Multi",
"-",
"head",
"self",
"-",
"attention",
"multi",
"-",
"head",
"query",
"attention",
"and",
"feed",
"-",
"forward",
"layer",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L145-L208 |
232,045 | CyberZHG/keras-transformer | keras_transformer/transformer.py | get_encoders | def get_encoders(encoder_num,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Get encoders.
:param encoder_num: Number of encoder components.
:param input_layer: Input layer.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer.
"""
last_layer = input_layer
for i in range(encoder_num):
last_layer = get_encoder_component(
name='Encoder-%d' % (i + 1),
input_layer=last_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
return last_layer | python | def get_encoders(encoder_num,
input_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
last_layer = input_layer
for i in range(encoder_num):
last_layer = get_encoder_component(
name='Encoder-%d' % (i + 1),
input_layer=last_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
return last_layer | [
"def",
"get_encoders",
"(",
"encoder_num",
",",
"input_layer",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"=",
"True",
")",
":",
... | Get encoders.
:param encoder_num: Number of encoder components.
:param input_layer: Input layer.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer. | [
"Get",
"encoders",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L211-L243 |
232,046 | CyberZHG/keras-transformer | keras_transformer/transformer.py | get_decoders | def get_decoders(decoder_num,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
"""Get decoders.
:param decoder_num: Number of decoder components.
:param input_layer: Input layer.
:param encoded_layer: Encoded layer from encoder.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer.
"""
last_layer = input_layer
for i in range(decoder_num):
last_layer = get_decoder_component(
name='Decoder-%d' % (i + 1),
input_layer=last_layer,
encoded_layer=encoded_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
return last_layer | python | def get_decoders(decoder_num,
input_layer,
encoded_layer,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
trainable=True):
last_layer = input_layer
for i in range(decoder_num):
last_layer = get_decoder_component(
name='Decoder-%d' % (i + 1),
input_layer=last_layer,
encoded_layer=encoded_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
return last_layer | [
"def",
"get_decoders",
"(",
"decoder_num",
",",
"input_layer",
",",
"encoded_layer",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"trainable",
"="... | Get decoders.
:param decoder_num: Number of decoder components.
:param input_layer: Input layer.
:param encoded_layer: Encoded layer from encoder.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param trainable: Whether the layers are trainable.
:return: Output layer. | [
"Get",
"decoders",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L246-L281 |
232,047 | CyberZHG/keras-transformer | keras_transformer/transformer.py | get_model | def get_model(token_num,
embed_dim,
encoder_num,
decoder_num,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
use_same_embed=True,
embed_weights=None,
embed_trainable=None,
trainable=True):
"""Get full model without compilation.
:param token_num: Number of distinct tokens.
:param embed_dim: Dimension of token embedding.
:param encoder_num: Number of encoder components.
:param decoder_num: Number of decoder components.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param use_same_embed: Whether to use the same token embedding layer. `token_num`, `embed_weights` and
`embed_trainable` should be lists of two elements if it is False.
:param embed_weights: Initial weights of token embedding.
:param embed_trainable: Whether the token embedding is trainable. It will automatically set to False if the given
value is None when embedding weights has been provided.
:param trainable: Whether the layers are trainable.
:return: Keras model.
"""
if not isinstance(token_num, list):
token_num = [token_num, token_num]
encoder_token_num, decoder_token_num = token_num
if not isinstance(embed_weights, list):
embed_weights = [embed_weights, embed_weights]
encoder_embed_weights, decoder_embed_weights = embed_weights
if encoder_embed_weights is not None:
encoder_embed_weights = [encoder_embed_weights]
if decoder_embed_weights is not None:
decoder_embed_weights = [decoder_embed_weights]
if not isinstance(embed_trainable, list):
embed_trainable = [embed_trainable, embed_trainable]
encoder_embed_trainable, decoder_embed_trainable = embed_trainable
if encoder_embed_trainable is None:
encoder_embed_trainable = encoder_embed_weights is None
if decoder_embed_trainable is None:
decoder_embed_trainable = decoder_embed_weights is None
if use_same_embed:
encoder_embed_layer = decoder_embed_layer = EmbeddingRet(
input_dim=encoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=encoder_embed_weights,
trainable=encoder_embed_trainable,
name='Token-Embedding',
)
else:
encoder_embed_layer = EmbeddingRet(
input_dim=encoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=encoder_embed_weights,
trainable=encoder_embed_trainable,
name='Encoder-Token-Embedding',
)
decoder_embed_layer = EmbeddingRet(
input_dim=decoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=decoder_embed_weights,
trainable=decoder_embed_trainable,
name='Decoder-Token-Embedding',
)
encoder_input = keras.layers.Input(shape=(None,), name='Encoder-Input')
encoder_embed = TrigPosEmbedding(
mode=TrigPosEmbedding.MODE_ADD,
name='Encoder-Embedding',
)(encoder_embed_layer(encoder_input)[0])
encoded_layer = get_encoders(
encoder_num=encoder_num,
input_layer=encoder_embed,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
decoder_input = keras.layers.Input(shape=(None,), name='Decoder-Input')
decoder_embed, decoder_embed_weights = decoder_embed_layer(decoder_input)
decoder_embed = TrigPosEmbedding(
mode=TrigPosEmbedding.MODE_ADD,
name='Decoder-Embedding',
)(decoder_embed)
decoded_layer = get_decoders(
decoder_num=decoder_num,
input_layer=decoder_embed,
encoded_layer=encoded_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
dense_layer = EmbeddingSim(
trainable=trainable,
name='Output',
)([decoded_layer, decoder_embed_weights])
return keras.models.Model(inputs=[encoder_input, decoder_input], outputs=dense_layer) | python | def get_model(token_num,
embed_dim,
encoder_num,
decoder_num,
head_num,
hidden_dim,
attention_activation=None,
feed_forward_activation='relu',
dropout_rate=0.0,
use_same_embed=True,
embed_weights=None,
embed_trainable=None,
trainable=True):
if not isinstance(token_num, list):
token_num = [token_num, token_num]
encoder_token_num, decoder_token_num = token_num
if not isinstance(embed_weights, list):
embed_weights = [embed_weights, embed_weights]
encoder_embed_weights, decoder_embed_weights = embed_weights
if encoder_embed_weights is not None:
encoder_embed_weights = [encoder_embed_weights]
if decoder_embed_weights is not None:
decoder_embed_weights = [decoder_embed_weights]
if not isinstance(embed_trainable, list):
embed_trainable = [embed_trainable, embed_trainable]
encoder_embed_trainable, decoder_embed_trainable = embed_trainable
if encoder_embed_trainable is None:
encoder_embed_trainable = encoder_embed_weights is None
if decoder_embed_trainable is None:
decoder_embed_trainable = decoder_embed_weights is None
if use_same_embed:
encoder_embed_layer = decoder_embed_layer = EmbeddingRet(
input_dim=encoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=encoder_embed_weights,
trainable=encoder_embed_trainable,
name='Token-Embedding',
)
else:
encoder_embed_layer = EmbeddingRet(
input_dim=encoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=encoder_embed_weights,
trainable=encoder_embed_trainable,
name='Encoder-Token-Embedding',
)
decoder_embed_layer = EmbeddingRet(
input_dim=decoder_token_num,
output_dim=embed_dim,
mask_zero=True,
weights=decoder_embed_weights,
trainable=decoder_embed_trainable,
name='Decoder-Token-Embedding',
)
encoder_input = keras.layers.Input(shape=(None,), name='Encoder-Input')
encoder_embed = TrigPosEmbedding(
mode=TrigPosEmbedding.MODE_ADD,
name='Encoder-Embedding',
)(encoder_embed_layer(encoder_input)[0])
encoded_layer = get_encoders(
encoder_num=encoder_num,
input_layer=encoder_embed,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
decoder_input = keras.layers.Input(shape=(None,), name='Decoder-Input')
decoder_embed, decoder_embed_weights = decoder_embed_layer(decoder_input)
decoder_embed = TrigPosEmbedding(
mode=TrigPosEmbedding.MODE_ADD,
name='Decoder-Embedding',
)(decoder_embed)
decoded_layer = get_decoders(
decoder_num=decoder_num,
input_layer=decoder_embed,
encoded_layer=encoded_layer,
head_num=head_num,
hidden_dim=hidden_dim,
attention_activation=attention_activation,
feed_forward_activation=feed_forward_activation,
dropout_rate=dropout_rate,
trainable=trainable,
)
dense_layer = EmbeddingSim(
trainable=trainable,
name='Output',
)([decoded_layer, decoder_embed_weights])
return keras.models.Model(inputs=[encoder_input, decoder_input], outputs=dense_layer) | [
"def",
"get_model",
"(",
"token_num",
",",
"embed_dim",
",",
"encoder_num",
",",
"decoder_num",
",",
"head_num",
",",
"hidden_dim",
",",
"attention_activation",
"=",
"None",
",",
"feed_forward_activation",
"=",
"'relu'",
",",
"dropout_rate",
"=",
"0.0",
",",
"us... | Get full model without compilation.
:param token_num: Number of distinct tokens.
:param embed_dim: Dimension of token embedding.
:param encoder_num: Number of encoder components.
:param decoder_num: Number of decoder components.
:param head_num: Number of heads in multi-head self-attention.
:param hidden_dim: Hidden dimension of feed forward layer.
:param attention_activation: Activation for multi-head self-attention.
:param feed_forward_activation: Activation for feed-forward layer.
:param dropout_rate: Dropout rate.
:param use_same_embed: Whether to use the same token embedding layer. `token_num`, `embed_weights` and
`embed_trainable` should be lists of two elements if it is False.
:param embed_weights: Initial weights of token embedding.
:param embed_trainable: Whether the token embedding is trainable. It will automatically set to False if the given
value is None when embedding weights has been provided.
:param trainable: Whether the layers are trainable.
:return: Keras model. | [
"Get",
"full",
"model",
"without",
"compilation",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L284-L398 |
232,048 | CyberZHG/keras-transformer | keras_transformer/transformer.py | decode | def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
"""Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sentence.
:param end_token: The token that represents the end of a sentence.
:param pad_token: The token that represents padding.
:param max_len: Maximum length of decoded list.
:param max_repeat: Maximum number of repeating blocks.
:param max_repeat_block: Maximum length of the repeating block.
:return: Decoded tokens.
"""
is_single = not isinstance(tokens[0], list)
if is_single:
tokens = [tokens]
batch_size = len(tokens)
decoder_inputs = [[start_token] for _ in range(batch_size)]
outputs = [None for _ in range(batch_size)]
output_len = 1
while len(list(filter(lambda x: x is None, outputs))) > 0:
output_len += 1
batch_inputs, batch_outputs = [], []
max_input_len = 0
index_map = {}
for i in range(batch_size):
if outputs[i] is None:
index_map[len(batch_inputs)] = i
batch_inputs.append(tokens[i][:])
batch_outputs.append(decoder_inputs[i])
max_input_len = max(max_input_len, len(tokens[i]))
for i in range(len(batch_inputs)):
batch_inputs[i] += [pad_token] * (max_input_len - len(batch_inputs[i]))
predicts = model.predict([np.asarray(batch_inputs), np.asarray(batch_outputs)])
for i in range(len(predicts)):
last_token = np.argmax(predicts[i][-1])
decoder_inputs[index_map[i]].append(last_token)
if last_token == end_token or\
(max_len is not None and output_len >= max_len) or\
_get_max_suffix_repeat_times(decoder_inputs, max_repeat * max_repeat_block) >= max_repeat:
outputs[index_map[i]] = decoder_inputs[index_map[i]]
if is_single:
outputs = outputs[0]
return outputs | python | def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
is_single = not isinstance(tokens[0], list)
if is_single:
tokens = [tokens]
batch_size = len(tokens)
decoder_inputs = [[start_token] for _ in range(batch_size)]
outputs = [None for _ in range(batch_size)]
output_len = 1
while len(list(filter(lambda x: x is None, outputs))) > 0:
output_len += 1
batch_inputs, batch_outputs = [], []
max_input_len = 0
index_map = {}
for i in range(batch_size):
if outputs[i] is None:
index_map[len(batch_inputs)] = i
batch_inputs.append(tokens[i][:])
batch_outputs.append(decoder_inputs[i])
max_input_len = max(max_input_len, len(tokens[i]))
for i in range(len(batch_inputs)):
batch_inputs[i] += [pad_token] * (max_input_len - len(batch_inputs[i]))
predicts = model.predict([np.asarray(batch_inputs), np.asarray(batch_outputs)])
for i in range(len(predicts)):
last_token = np.argmax(predicts[i][-1])
decoder_inputs[index_map[i]].append(last_token)
if last_token == end_token or\
(max_len is not None and output_len >= max_len) or\
_get_max_suffix_repeat_times(decoder_inputs, max_repeat * max_repeat_block) >= max_repeat:
outputs[index_map[i]] = decoder_inputs[index_map[i]]
if is_single:
outputs = outputs[0]
return outputs | [
"def",
"decode",
"(",
"model",
",",
"tokens",
",",
"start_token",
",",
"end_token",
",",
"pad_token",
",",
"max_len",
"=",
"10000",
",",
"max_repeat",
"=",
"10",
",",
"max_repeat_block",
"=",
"10",
")",
":",
"is_single",
"=",
"not",
"isinstance",
"(",
"t... | Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sentence.
:param end_token: The token that represents the end of a sentence.
:param pad_token: The token that represents padding.
:param max_len: Maximum length of decoded list.
:param max_repeat: Maximum number of repeating blocks.
:param max_repeat_block: Maximum length of the repeating block.
:return: Decoded tokens. | [
"Decode",
"with",
"the",
"given",
"model",
"and",
"input",
"tokens",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L418-L461 |
232,049 | CyberZHG/keras-transformer | keras_transformer/gelu.py | gelu | def gelu(x):
"""An approximation of gelu.
See: https://arxiv.org/pdf/1606.08415.pdf
"""
return 0.5 * x * (1.0 + K.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * K.pow(x, 3)))) | python | def gelu(x):
return 0.5 * x * (1.0 + K.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * K.pow(x, 3)))) | [
"def",
"gelu",
"(",
"x",
")",
":",
"return",
"0.5",
"*",
"x",
"*",
"(",
"1.0",
"+",
"K",
".",
"tanh",
"(",
"math",
".",
"sqrt",
"(",
"2.0",
"/",
"math",
".",
"pi",
")",
"*",
"(",
"x",
"+",
"0.044715",
"*",
"K",
".",
"pow",
"(",
"x",
",",
... | An approximation of gelu.
See: https://arxiv.org/pdf/1606.08415.pdf | [
"An",
"approximation",
"of",
"gelu",
"."
] | 4c42baa030539c62ef5ace92df0408b13f26d928 | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/gelu.py#L5-L10 |
232,050 | sloria/environs | environs.py | Env.prefixed | def prefixed(self, prefix):
"""Context manager for parsing envvars with a common prefix."""
old_prefix = self._prefix
if old_prefix is None:
self._prefix = prefix
else:
self._prefix = "{}{}".format(old_prefix, prefix)
yield self
self._prefix = old_prefix | python | def prefixed(self, prefix):
old_prefix = self._prefix
if old_prefix is None:
self._prefix = prefix
else:
self._prefix = "{}{}".format(old_prefix, prefix)
yield self
self._prefix = old_prefix | [
"def",
"prefixed",
"(",
"self",
",",
"prefix",
")",
":",
"old_prefix",
"=",
"self",
".",
"_prefix",
"if",
"old_prefix",
"is",
"None",
":",
"self",
".",
"_prefix",
"=",
"prefix",
"else",
":",
"self",
".",
"_prefix",
"=",
"\"{}{}\"",
".",
"format",
"(",
... | Context manager for parsing envvars with a common prefix. | [
"Context",
"manager",
"for",
"parsing",
"envvars",
"with",
"a",
"common",
"prefix",
"."
] | cf0b5e865b0ce96ce77d459124a1dba84c9deda7 | https://github.com/sloria/environs/blob/cf0b5e865b0ce96ce77d459124a1dba84c9deda7/environs.py#L213-L221 |
232,051 | sloria/environs | environs.py | Env.add_parser | def add_parser(self, name, func):
"""Register a new parser method with the name ``name``. ``func`` must
receive the input value for an environment variable.
"""
self.__parser_map__[name] = _func2method(func, method_name=name)
return None | python | def add_parser(self, name, func):
self.__parser_map__[name] = _func2method(func, method_name=name)
return None | [
"def",
"add_parser",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"self",
".",
"__parser_map__",
"[",
"name",
"]",
"=",
"_func2method",
"(",
"func",
",",
"method_name",
"=",
"name",
")",
"return",
"None"
] | Register a new parser method with the name ``name``. ``func`` must
receive the input value for an environment variable. | [
"Register",
"a",
"new",
"parser",
"method",
"with",
"the",
"name",
"name",
".",
"func",
"must",
"receive",
"the",
"input",
"value",
"for",
"an",
"environment",
"variable",
"."
] | cf0b5e865b0ce96ce77d459124a1dba84c9deda7 | https://github.com/sloria/environs/blob/cf0b5e865b0ce96ce77d459124a1dba84c9deda7/environs.py#L229-L234 |
232,052 | sloria/environs | environs.py | Env.parser_for | def parser_for(self, name):
"""Decorator that registers a new parser method with the name ``name``.
The decorated function must receive the input value for an environment variable.
"""
def decorator(func):
self.add_parser(name, func)
return func
return decorator | python | def parser_for(self, name):
def decorator(func):
self.add_parser(name, func)
return func
return decorator | [
"def",
"parser_for",
"(",
"self",
",",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"self",
".",
"add_parser",
"(",
"name",
",",
"func",
")",
"return",
"func",
"return",
"decorator"
] | Decorator that registers a new parser method with the name ``name``.
The decorated function must receive the input value for an environment variable. | [
"Decorator",
"that",
"registers",
"a",
"new",
"parser",
"method",
"with",
"the",
"name",
"name",
".",
"The",
"decorated",
"function",
"must",
"receive",
"the",
"input",
"value",
"for",
"an",
"environment",
"variable",
"."
] | cf0b5e865b0ce96ce77d459124a1dba84c9deda7 | https://github.com/sloria/environs/blob/cf0b5e865b0ce96ce77d459124a1dba84c9deda7/environs.py#L236-L245 |
232,053 | sloria/environs | environs.py | Env.add_parser_from_field | def add_parser_from_field(self, name, field_cls):
"""Register a new parser method with name ``name``, given a marshmallow ``Field``."""
self.__parser_map__[name] = _field2method(field_cls, method_name=name) | python | def add_parser_from_field(self, name, field_cls):
self.__parser_map__[name] = _field2method(field_cls, method_name=name) | [
"def",
"add_parser_from_field",
"(",
"self",
",",
"name",
",",
"field_cls",
")",
":",
"self",
".",
"__parser_map__",
"[",
"name",
"]",
"=",
"_field2method",
"(",
"field_cls",
",",
"method_name",
"=",
"name",
")"
] | Register a new parser method with name ``name``, given a marshmallow ``Field``. | [
"Register",
"a",
"new",
"parser",
"method",
"with",
"name",
"name",
"given",
"a",
"marshmallow",
"Field",
"."
] | cf0b5e865b0ce96ce77d459124a1dba84c9deda7 | https://github.com/sloria/environs/blob/cf0b5e865b0ce96ce77d459124a1dba84c9deda7/environs.py#L247-L249 |
232,054 | Knio/pynmea2 | pynmea2/nmea_file.py | NMEAFile.open | def open(self, fp, mode='r'):
"""
Open the NMEAFile.
"""
self._file = open(fp, mode=mode)
return self._file | python | def open(self, fp, mode='r'):
self._file = open(fp, mode=mode)
return self._file | [
"def",
"open",
"(",
"self",
",",
"fp",
",",
"mode",
"=",
"'r'",
")",
":",
"self",
".",
"_file",
"=",
"open",
"(",
"fp",
",",
"mode",
"=",
"mode",
")",
"return",
"self",
".",
"_file"
] | Open the NMEAFile. | [
"Open",
"the",
"NMEAFile",
"."
] | c4fc66c6a13dd85ad862b15c516245af6e571456 | https://github.com/Knio/pynmea2/blob/c4fc66c6a13dd85ad862b15c516245af6e571456/pynmea2/nmea_file.py#L23-L28 |
232,055 | williballenthin/python-evtx | scripts/evtx_filter_records.py | xml_records | def xml_records(filename):
"""
If the second return value is not None, then it is an
Exception encountered during parsing. The first return value
will be the XML string.
@type filename str
@rtype: generator of (etree.Element or str), (None or Exception)
"""
with Evtx(filename) as evtx:
for xml, record in evtx_file_xml_view(evtx.get_file_header()):
try:
yield to_lxml(xml), None
except etree.XMLSyntaxError as e:
yield xml, e | python | def xml_records(filename):
with Evtx(filename) as evtx:
for xml, record in evtx_file_xml_view(evtx.get_file_header()):
try:
yield to_lxml(xml), None
except etree.XMLSyntaxError as e:
yield xml, e | [
"def",
"xml_records",
"(",
"filename",
")",
":",
"with",
"Evtx",
"(",
"filename",
")",
"as",
"evtx",
":",
"for",
"xml",
",",
"record",
"in",
"evtx_file_xml_view",
"(",
"evtx",
".",
"get_file_header",
"(",
")",
")",
":",
"try",
":",
"yield",
"to_lxml",
... | If the second return value is not None, then it is an
Exception encountered during parsing. The first return value
will be the XML string.
@type filename str
@rtype: generator of (etree.Element or str), (None or Exception) | [
"If",
"the",
"second",
"return",
"value",
"is",
"not",
"None",
"then",
"it",
"is",
"an",
"Exception",
"encountered",
"during",
"parsing",
".",
"The",
"first",
"return",
"value",
"will",
"be",
"the",
"XML",
"string",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/scripts/evtx_filter_records.py#L18-L32 |
232,056 | williballenthin/python-evtx | Evtx/Nodes.py | RootNode.template_instance | def template_instance(self):
'''
parse the template instance node.
this is used to compute the location of the template definition structure.
Returns:
TemplateInstanceNode: the template instance.
'''
ofs = self.offset()
if self.unpack_byte(0x0) & 0x0F == 0xF:
ofs += 4
return TemplateInstanceNode(self._buf, ofs, self._chunk, self) | python | def template_instance(self):
'''
parse the template instance node.
this is used to compute the location of the template definition structure.
Returns:
TemplateInstanceNode: the template instance.
'''
ofs = self.offset()
if self.unpack_byte(0x0) & 0x0F == 0xF:
ofs += 4
return TemplateInstanceNode(self._buf, ofs, self._chunk, self) | [
"def",
"template_instance",
"(",
"self",
")",
":",
"ofs",
"=",
"self",
".",
"offset",
"(",
")",
"if",
"self",
".",
"unpack_byte",
"(",
"0x0",
")",
"&",
"0x0F",
"==",
"0xF",
":",
"ofs",
"+=",
"4",
"return",
"TemplateInstanceNode",
"(",
"self",
".",
"_... | parse the template instance node.
this is used to compute the location of the template definition structure.
Returns:
TemplateInstanceNode: the template instance. | [
"parse",
"the",
"template",
"instance",
"node",
".",
"this",
"is",
"used",
"to",
"compute",
"the",
"location",
"of",
"the",
"template",
"definition",
"structure",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Nodes.py#L967-L978 |
232,057 | williballenthin/python-evtx | Evtx/Nodes.py | RootNode.template | def template(self):
'''
parse the template referenced by this root node.
note, this template structure is not guaranteed to be located within the root node's boundaries.
Returns:
TemplateNode: the template.
'''
instance = self.template_instance()
offset = self._chunk.offset() + instance.template_offset()
node = TemplateNode(self._buf, offset, self._chunk, instance)
return node | python | def template(self):
'''
parse the template referenced by this root node.
note, this template structure is not guaranteed to be located within the root node's boundaries.
Returns:
TemplateNode: the template.
'''
instance = self.template_instance()
offset = self._chunk.offset() + instance.template_offset()
node = TemplateNode(self._buf, offset, self._chunk, instance)
return node | [
"def",
"template",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"template_instance",
"(",
")",
"offset",
"=",
"self",
".",
"_chunk",
".",
"offset",
"(",
")",
"+",
"instance",
".",
"template_offset",
"(",
")",
"node",
"=",
"TemplateNode",
"(",
"... | parse the template referenced by this root node.
note, this template structure is not guaranteed to be located within the root node's boundaries.
Returns:
TemplateNode: the template. | [
"parse",
"the",
"template",
"referenced",
"by",
"this",
"root",
"node",
".",
"note",
"this",
"template",
"structure",
"is",
"not",
"guaranteed",
"to",
"be",
"located",
"within",
"the",
"root",
"node",
"s",
"boundaries",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Nodes.py#L980-L991 |
232,058 | williballenthin/python-evtx | Evtx/Views.py | evtx_chunk_xml_view | def evtx_chunk_xml_view(chunk):
"""
Generate XML representations of the records in an EVTX chunk.
Does not include the XML <?xml... header.
Records are ordered by chunk.records()
Args:
chunk (Evtx.Chunk): the chunk to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML document and the raw record.
"""
for record in chunk.records():
record_str = evtx_record_xml_view(record)
yield record_str, record | python | def evtx_chunk_xml_view(chunk):
for record in chunk.records():
record_str = evtx_record_xml_view(record)
yield record_str, record | [
"def",
"evtx_chunk_xml_view",
"(",
"chunk",
")",
":",
"for",
"record",
"in",
"chunk",
".",
"records",
"(",
")",
":",
"record_str",
"=",
"evtx_record_xml_view",
"(",
"record",
")",
"yield",
"record_str",
",",
"record"
] | Generate XML representations of the records in an EVTX chunk.
Does not include the XML <?xml... header.
Records are ordered by chunk.records()
Args:
chunk (Evtx.Chunk): the chunk to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML document and the raw record. | [
"Generate",
"XML",
"representations",
"of",
"the",
"records",
"in",
"an",
"EVTX",
"chunk",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Views.py#L207-L222 |
232,059 | williballenthin/python-evtx | Evtx/Views.py | evtx_file_xml_view | def evtx_file_xml_view(file_header):
"""
Generate XML representations of the records in an EVTX file.
Does not include the XML <?xml... header.
Records are ordered by file_header.chunks(), and then by chunk.records()
Args:
chunk (Evtx.FileHeader): the file header to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML document and the raw record.
"""
for chunk in file_header.chunks():
for record in chunk.records():
record_str = evtx_record_xml_view(record)
yield record_str, record | python | def evtx_file_xml_view(file_header):
for chunk in file_header.chunks():
for record in chunk.records():
record_str = evtx_record_xml_view(record)
yield record_str, record | [
"def",
"evtx_file_xml_view",
"(",
"file_header",
")",
":",
"for",
"chunk",
"in",
"file_header",
".",
"chunks",
"(",
")",
":",
"for",
"record",
"in",
"chunk",
".",
"records",
"(",
")",
":",
"record_str",
"=",
"evtx_record_xml_view",
"(",
"record",
")",
"yie... | Generate XML representations of the records in an EVTX file.
Does not include the XML <?xml... header.
Records are ordered by file_header.chunks(), and then by chunk.records()
Args:
chunk (Evtx.FileHeader): the file header to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML document and the raw record. | [
"Generate",
"XML",
"representations",
"of",
"the",
"records",
"in",
"an",
"EVTX",
"file",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Views.py#L225-L241 |
232,060 | williballenthin/python-evtx | Evtx/Evtx.py | FileHeader.get_record | def get_record(self, record_num):
"""
Get a Record by record number.
@type record_num: int
@param record_num: The record number of the the record to fetch.
@rtype Record or None
@return The record request by record number, or None if the
record is not found.
"""
for chunk in self.chunks():
first_record = chunk.log_first_record_number()
last_record = chunk.log_last_record_number()
if not (first_record <= record_num <= last_record):
continue
for record in chunk.records():
if record.record_num() == record_num:
return record
return None | python | def get_record(self, record_num):
for chunk in self.chunks():
first_record = chunk.log_first_record_number()
last_record = chunk.log_last_record_number()
if not (first_record <= record_num <= last_record):
continue
for record in chunk.records():
if record.record_num() == record_num:
return record
return None | [
"def",
"get_record",
"(",
"self",
",",
"record_num",
")",
":",
"for",
"chunk",
"in",
"self",
".",
"chunks",
"(",
")",
":",
"first_record",
"=",
"chunk",
".",
"log_first_record_number",
"(",
")",
"last_record",
"=",
"chunk",
".",
"log_last_record_number",
"("... | Get a Record by record number.
@type record_num: int
@param record_num: The record number of the the record to fetch.
@rtype Record or None
@return The record request by record number, or None if the
record is not found. | [
"Get",
"a",
"Record",
"by",
"record",
"number",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Evtx.py#L243-L261 |
232,061 | williballenthin/python-evtx | Evtx/Evtx.py | Record.data | def data(self):
"""
Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record.
"""
return self._buf[self.offset():self.offset() + self.size()] | python | def data(self):
return self._buf[self.offset():self.offset() + self.size()] | [
"def",
"data",
"(",
"self",
")",
":",
"return",
"self",
".",
"_buf",
"[",
"self",
".",
"offset",
"(",
")",
":",
"self",
".",
"offset",
"(",
")",
"+",
"self",
".",
"size",
"(",
")",
"]"
] | Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record. | [
"Return",
"the",
"raw",
"data",
"block",
"which",
"makes",
"up",
"this",
"record",
"as",
"a",
"bytestring",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Evtx.py#L480-L488 |
232,062 | williballenthin/python-evtx | Evtx/Evtx.py | Record.lxml | def lxml(self):
'''
render the record into a lxml document.
this is useful for querying data from the record using xpath, etc.
note: lxml must be installed.
Returns:
lxml.etree.ElementTree: the rendered and parsed xml document.
Raises:
ImportError: if lxml is not installed.
'''
import lxml.etree
return lxml.etree.fromstring((e_views.XML_HEADER + self.xml()).encode('utf-8')) | python | def lxml(self):
'''
render the record into a lxml document.
this is useful for querying data from the record using xpath, etc.
note: lxml must be installed.
Returns:
lxml.etree.ElementTree: the rendered and parsed xml document.
Raises:
ImportError: if lxml is not installed.
'''
import lxml.etree
return lxml.etree.fromstring((e_views.XML_HEADER + self.xml()).encode('utf-8')) | [
"def",
"lxml",
"(",
"self",
")",
":",
"import",
"lxml",
".",
"etree",
"return",
"lxml",
".",
"etree",
".",
"fromstring",
"(",
"(",
"e_views",
".",
"XML_HEADER",
"+",
"self",
".",
"xml",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | render the record into a lxml document.
this is useful for querying data from the record using xpath, etc.
note: lxml must be installed.
Returns:
lxml.etree.ElementTree: the rendered and parsed xml document.
Raises:
ImportError: if lxml is not installed. | [
"render",
"the",
"record",
"into",
"a",
"lxml",
"document",
".",
"this",
"is",
"useful",
"for",
"querying",
"data",
"from",
"the",
"record",
"using",
"xpath",
"etc",
"."
] | 4e9e29544adde64c79ff9b743269ecb18c677eb4 | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Evtx.py#L500-L514 |
232,063 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/users.py | UserList.get | def get(self):
"""List all users"""
self.reqparse.add_argument('page', type=int, default=1, required=True)
self.reqparse.add_argument('count', type=int, default=50, choices=[25, 50, 100])
self.reqparse.add_argument('authSystem', type=str, default=None, action='append')
args = self.reqparse.parse_args()
qry = db.User.order_by(User.username)
if args['authSystem']:
qry = qry.filter(User.auth_system.in_(args['authSystem']))
total = qry.count()
qry = qry.limit(args['count'])
if (args['page'] - 1) > 0:
offset = (args['page'] - 1) * args['count']
qry = qry.offset(offset)
users = qry.all()
return self.make_response({
'users': [x.to_json() for x in users],
'userCount': total,
'authSystems': list(current_app.available_auth_systems.keys()),
'activeAuthSystem': current_app.active_auth_system.name
}) | python | def get(self):
self.reqparse.add_argument('page', type=int, default=1, required=True)
self.reqparse.add_argument('count', type=int, default=50, choices=[25, 50, 100])
self.reqparse.add_argument('authSystem', type=str, default=None, action='append')
args = self.reqparse.parse_args()
qry = db.User.order_by(User.username)
if args['authSystem']:
qry = qry.filter(User.auth_system.in_(args['authSystem']))
total = qry.count()
qry = qry.limit(args['count'])
if (args['page'] - 1) > 0:
offset = (args['page'] - 1) * args['count']
qry = qry.offset(offset)
users = qry.all()
return self.make_response({
'users': [x.to_json() for x in users],
'userCount': total,
'authSystems': list(current_app.available_auth_systems.keys()),
'activeAuthSystem': current_app.active_auth_system.name
}) | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"reqparse",
".",
"add_argument",
"(",
"'page'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1",
",",
"required",
"=",
"True",
")",
"self",
".",
"reqparse",
".",
"add_argument",
"(",
"'count'",
",",... | List all users | [
"List",
"all",
"users"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/users.py#L31-L55 |
232,064 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/users.py | UserList.options | def options(self):
"""Returns metadata information required for User Creation"""
roles = db.Role.all()
return self.make_response({
'roles': roles,
'authSystems': list(current_app.available_auth_systems.keys()),
'activeAuthSystem': current_app.active_auth_system.name
}) | python | def options(self):
roles = db.Role.all()
return self.make_response({
'roles': roles,
'authSystems': list(current_app.available_auth_systems.keys()),
'activeAuthSystem': current_app.active_auth_system.name
}) | [
"def",
"options",
"(",
"self",
")",
":",
"roles",
"=",
"db",
".",
"Role",
".",
"all",
"(",
")",
"return",
"self",
".",
"make_response",
"(",
"{",
"'roles'",
":",
"roles",
",",
"'authSystems'",
":",
"list",
"(",
"current_app",
".",
"available_auth_systems... | Returns metadata information required for User Creation | [
"Returns",
"metadata",
"information",
"required",
"for",
"User",
"Creation"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/users.py#L124-L132 |
232,065 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/users.py | UserDetails.get | def get(self, user_id):
"""Returns a specific user"""
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_response({
'user': user.to_json(),
'roles': roles
}, HTTP.OK) | python | def get(self, user_id):
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_response({
'user': user.to_json(),
'roles': roles
}, HTTP.OK) | [
"def",
"get",
"(",
"self",
",",
"user_id",
")",
":",
"user",
"=",
"db",
".",
"User",
".",
"find_one",
"(",
"User",
".",
"user_id",
"==",
"user_id",
")",
"roles",
"=",
"db",
".",
"Role",
".",
"all",
"(",
")",
"if",
"not",
"user",
":",
"return",
... | Returns a specific user | [
"Returns",
"a",
"specific",
"user"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/users.py#L140-L151 |
232,066 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/views/users.py | UserDetails.put | def put(self, user_id):
"""Update a user object"""
self.reqparse.add_argument('roles', type=str, action='append')
args = self.reqparse.parse_args()
auditlog(event='user.create', actor=session['user'].username, data=args)
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.find(Role.name.in_(args['roles']))
if not user:
return self.make_response('No such user found: {}'.format(user_id), HTTP.NOT_FOUND)
if user.username == 'admin' and user.auth_system == 'builtin':
return self.make_response('You cannot modify the built-in admin user', HTTP.FORBIDDEN)
user.roles = []
for role in roles:
if role in args['roles']:
user.roles.append(role)
db.session.add(user)
db.session.commit()
return self.make_response({'message': 'User roles updated'}, HTTP.OK) | python | def put(self, user_id):
self.reqparse.add_argument('roles', type=str, action='append')
args = self.reqparse.parse_args()
auditlog(event='user.create', actor=session['user'].username, data=args)
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.find(Role.name.in_(args['roles']))
if not user:
return self.make_response('No such user found: {}'.format(user_id), HTTP.NOT_FOUND)
if user.username == 'admin' and user.auth_system == 'builtin':
return self.make_response('You cannot modify the built-in admin user', HTTP.FORBIDDEN)
user.roles = []
for role in roles:
if role in args['roles']:
user.roles.append(role)
db.session.add(user)
db.session.commit()
return self.make_response({'message': 'User roles updated'}, HTTP.OK) | [
"def",
"put",
"(",
"self",
",",
"user_id",
")",
":",
"self",
".",
"reqparse",
".",
"add_argument",
"(",
"'roles'",
",",
"type",
"=",
"str",
",",
"action",
"=",
"'append'",
")",
"args",
"=",
"self",
".",
"reqparse",
".",
"parse_args",
"(",
")",
"audit... | Update a user object | [
"Update",
"a",
"user",
"object"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/users.py#L155-L177 |
232,067 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-domain-hijacking/cinq_auditor_domain_hijacking/__init__.py | DomainHijackAuditor.return_resource_name | def return_resource_name(self, record, resource_type):
""" Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..)
"""
try:
if resource_type == 's3':
regex = re.compile('.*(\.(?:s3-|s3){1}(?:.*)?\.amazonaws\.com)')
bucket_name = record.replace(regex.match(record).group(1), '')
return bucket_name
except Exception as e:
self.log.error('Unable to parse DNS record {} for resource type {}/{}'.format(record, resource_type, e))
return record | python | def return_resource_name(self, record, resource_type):
try:
if resource_type == 's3':
regex = re.compile('.*(\.(?:s3-|s3){1}(?:.*)?\.amazonaws\.com)')
bucket_name = record.replace(regex.match(record).group(1), '')
return bucket_name
except Exception as e:
self.log.error('Unable to parse DNS record {} for resource type {}/{}'.format(record, resource_type, e))
return record | [
"def",
"return_resource_name",
"(",
"self",
",",
"record",
",",
"resource_type",
")",
":",
"try",
":",
"if",
"resource_type",
"==",
"'s3'",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"'.*(\\.(?:s3-|s3){1}(?:.*)?\\.amazonaws\\.com)'",
")",
"bucket_name",
"=",
... | Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..) | [
"Removes",
"the",
"trailing",
"AWS",
"domain",
"from",
"a",
"DNS",
"record",
"to",
"return",
"the",
"resource",
"name"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-domain-hijacking/cinq_auditor_domain_hijacking/__init__.py#L197-L216 |
232,068 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/accounts.py | BaseAccount.to_json | def to_json(self, is_admin=False):
"""Returns a dict representation of the object
Args:
is_admin (`bool`): If true, include information about the account that should be avaiable only to admins
Returns:
`dict`
"""
if is_admin:
return {
'accountId': self.account_id,
'accountName': self.account_name,
'accountType': self.account_type,
'contacts': self.contacts,
'enabled': True if self.enabled == 1 else False,
'requiredRoles': self.required_roles,
'properties': {to_camelcase(prop.name): prop.value for prop in self.account.properties}
}
else:
return {
'accountId': self.account_id,
'accountName': self.account_name,
'contacts': self.contacts
} | python | def to_json(self, is_admin=False):
if is_admin:
return {
'accountId': self.account_id,
'accountName': self.account_name,
'accountType': self.account_type,
'contacts': self.contacts,
'enabled': True if self.enabled == 1 else False,
'requiredRoles': self.required_roles,
'properties': {to_camelcase(prop.name): prop.value for prop in self.account.properties}
}
else:
return {
'accountId': self.account_id,
'accountName': self.account_name,
'contacts': self.contacts
} | [
"def",
"to_json",
"(",
"self",
",",
"is_admin",
"=",
"False",
")",
":",
"if",
"is_admin",
":",
"return",
"{",
"'accountId'",
":",
"self",
".",
"account_id",
",",
"'accountName'",
":",
"self",
".",
"account_name",
",",
"'accountType'",
":",
"self",
".",
"... | Returns a dict representation of the object
Args:
is_admin (`bool`): If true, include information about the account that should be avaiable only to admins
Returns:
`dict` | [
"Returns",
"a",
"dict",
"representation",
"of",
"the",
"object"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/accounts.py#L90-L114 |
232,069 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/accounts.py | BaseAccount.get | def get(account):
"""Returns the class object identified by `account_id`
Args:
account (`int`, `str`): Unique ID of the account to load from database
Returns:
`Account` object if found, else None
"""
account = Account.get(account)
if not account:
return None
acct_type = AccountType.get(account.account_type_id).account_type
account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], acct_type)
return account_class(account) | python | def get(account):
account = Account.get(account)
if not account:
return None
acct_type = AccountType.get(account.account_type_id).account_type
account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], acct_type)
return account_class(account) | [
"def",
"get",
"(",
"account",
")",
":",
"account",
"=",
"Account",
".",
"get",
"(",
"account",
")",
"if",
"not",
"account",
":",
"return",
"None",
"acct_type",
"=",
"AccountType",
".",
"get",
"(",
"account",
".",
"account_type_id",
")",
".",
"account_typ... | Returns the class object identified by `account_id`
Args:
account (`int`, `str`): Unique ID of the account to load from database
Returns:
`Account` object if found, else None | [
"Returns",
"the",
"class",
"object",
"identified",
"by",
"account_id"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/accounts.py#L193-L209 |
232,070 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/accounts.py | BaseAccount.get_all | def get_all(cls, include_disabled=True):
"""Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects
"""
if cls == BaseAccount:
raise InquisitorError('get_all on BaseAccount is not supported')
account_type_id = db.AccountType.find_one(account_type=cls.account_type).account_type_id
qry = db.Account.order_by(desc(Account.enabled), Account.account_type_id, Account.account_name)
if not include_disabled:
qry = qry.filter(Account.enabled == 1)
accounts = qry.find(Account.account_type_id == account_type_id)
return {res.account_id: cls(res) for res in accounts} | python | def get_all(cls, include_disabled=True):
if cls == BaseAccount:
raise InquisitorError('get_all on BaseAccount is not supported')
account_type_id = db.AccountType.find_one(account_type=cls.account_type).account_type_id
qry = db.Account.order_by(desc(Account.enabled), Account.account_type_id, Account.account_name)
if not include_disabled:
qry = qry.filter(Account.enabled == 1)
accounts = qry.find(Account.account_type_id == account_type_id)
return {res.account_id: cls(res) for res in accounts} | [
"def",
"get_all",
"(",
"cls",
",",
"include_disabled",
"=",
"True",
")",
":",
"if",
"cls",
"==",
"BaseAccount",
":",
"raise",
"InquisitorError",
"(",
"'get_all on BaseAccount is not supported'",
")",
"account_type_id",
"=",
"db",
".",
"AccountType",
".",
"find_one... | Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects | [
"Returns",
"a",
"list",
"of",
"all",
"accounts",
"of",
"a",
"given",
"type"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/accounts.py#L243-L263 |
232,071 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/accounts.py | BaseAccount.search | def search(*, include_disabled=True, account_ids=None, account_type_id=None, properties=None, return_query=False):
"""Search for accounts based on the provided filters
Args:
include_disabled (`bool`): Include disabled accounts (default: True)
account_ids: (`list` of `int`): List of account IDs
account_type_id (`int`): Account Type ID to limit results to
properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list
of strings, in which case a boolean OR search is performed on the values
return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for
sub-classes to amend the search feature with extra conditions. The calling function must handle pagination
on its own
Returns:
`list` of `Account`, `sqlalchemy.orm.Query`
"""
qry = db.Account.order_by(desc(Account.enabled), Account.account_type_id, Account.account_name)
if not include_disabled:
qry = qry.filter(Account.enabled == 1)
if account_ids:
if type(account_ids) not in (list, tuple):
account_ids = [account_ids]
qry = qry.filter(Account.account_id.in_(account_ids))
if account_type_id:
qry = qry.filter(Account.account_type_id == account_type_id)
if properties:
for prop_name, value in properties.items():
alias = aliased(AccountProperty)
qry = qry.join(alias, Account.account_id == alias.account_id)
if type(value) == list:
where_clause = []
for item in value:
where_clause.append(alias.value == item)
qry = qry.filter(
and_(
alias.name == prop_name,
or_(*where_clause)
).self_group()
)
else:
qry = qry.filter(
and_(
alias.name == prop_name,
alias.value == value
).self_group()
)
if return_query:
return qry
total = qry.count()
return total, list(map(BaseAccount.get_typed_account, qry.all())) | python | def search(*, include_disabled=True, account_ids=None, account_type_id=None, properties=None, return_query=False):
qry = db.Account.order_by(desc(Account.enabled), Account.account_type_id, Account.account_name)
if not include_disabled:
qry = qry.filter(Account.enabled == 1)
if account_ids:
if type(account_ids) not in (list, tuple):
account_ids = [account_ids]
qry = qry.filter(Account.account_id.in_(account_ids))
if account_type_id:
qry = qry.filter(Account.account_type_id == account_type_id)
if properties:
for prop_name, value in properties.items():
alias = aliased(AccountProperty)
qry = qry.join(alias, Account.account_id == alias.account_id)
if type(value) == list:
where_clause = []
for item in value:
where_clause.append(alias.value == item)
qry = qry.filter(
and_(
alias.name == prop_name,
or_(*where_clause)
).self_group()
)
else:
qry = qry.filter(
and_(
alias.name == prop_name,
alias.value == value
).self_group()
)
if return_query:
return qry
total = qry.count()
return total, list(map(BaseAccount.get_typed_account, qry.all())) | [
"def",
"search",
"(",
"*",
",",
"include_disabled",
"=",
"True",
",",
"account_ids",
"=",
"None",
",",
"account_type_id",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"return_query",
"=",
"False",
")",
":",
"qry",
"=",
"db",
".",
"Account",
".",
"... | Search for accounts based on the provided filters
Args:
include_disabled (`bool`): Include disabled accounts (default: True)
account_ids: (`list` of `int`): List of account IDs
account_type_id (`int`): Account Type ID to limit results to
properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list
of strings, in which case a boolean OR search is performed on the values
return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for
sub-classes to amend the search feature with extra conditions. The calling function must handle pagination
on its own
Returns:
`list` of `Account`, `sqlalchemy.orm.Query` | [
"Search",
"for",
"accounts",
"based",
"on",
"the",
"provided",
"filters"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/accounts.py#L266-L323 |
232,072 | RiotGames/cloud-inquisitor | plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py | SQSScheduler.execute_scheduler | def execute_scheduler(self):
"""Main entry point for the scheduler. This method will start two scheduled jobs, `schedule_jobs` which takes
care of scheduling the actual SQS messaging and `process_status_queue` which will track the current status
of the jobs as workers are executing them
Returns:
`None`
"""
try:
# Schedule periodic scheduling of jobs
self.scheduler.add_job(
self.schedule_jobs,
trigger='interval',
name='schedule_jobs',
minutes=15,
start_date=datetime.now() + timedelta(seconds=1)
)
self.scheduler.add_job(
self.process_status_queue,
trigger='interval',
name='process_status_queue',
seconds=30,
start_date=datetime.now() + timedelta(seconds=5),
max_instances=1
)
self.scheduler.start()
except KeyboardInterrupt:
self.scheduler.shutdown() | python | def execute_scheduler(self):
try:
# Schedule periodic scheduling of jobs
self.scheduler.add_job(
self.schedule_jobs,
trigger='interval',
name='schedule_jobs',
minutes=15,
start_date=datetime.now() + timedelta(seconds=1)
)
self.scheduler.add_job(
self.process_status_queue,
trigger='interval',
name='process_status_queue',
seconds=30,
start_date=datetime.now() + timedelta(seconds=5),
max_instances=1
)
self.scheduler.start()
except KeyboardInterrupt:
self.scheduler.shutdown() | [
"def",
"execute_scheduler",
"(",
"self",
")",
":",
"try",
":",
"# Schedule periodic scheduling of jobs",
"self",
".",
"scheduler",
".",
"add_job",
"(",
"self",
".",
"schedule_jobs",
",",
"trigger",
"=",
"'interval'",
",",
"name",
"=",
"'schedule_jobs'",
",",
"mi... | Main entry point for the scheduler. This method will start two scheduled jobs, `schedule_jobs` which takes
care of scheduling the actual SQS messaging and `process_status_queue` which will track the current status
of the jobs as workers are executing them
Returns:
`None` | [
"Main",
"entry",
"point",
"for",
"the",
"scheduler",
".",
"This",
"method",
"will",
"start",
"two",
"scheduled",
"jobs",
"schedule_jobs",
"which",
"takes",
"care",
"of",
"scheduling",
"the",
"actual",
"SQS",
"messaging",
"and",
"process_status_queue",
"which",
"... | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py#L51-L81 |
232,073 | RiotGames/cloud-inquisitor | plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py | SQSScheduler.list_current_jobs | def list_current_jobs(self):
"""Return a list of the currently scheduled jobs in APScheduler
Returns:
`dict` of `str`: :obj:`apscheduler/job:Job`
"""
jobs = {}
for job in self.scheduler.get_jobs():
if job.name not in ('schedule_jobs', 'process_status_queue'):
jobs[job.name] = job
return jobs | python | def list_current_jobs(self):
jobs = {}
for job in self.scheduler.get_jobs():
if job.name not in ('schedule_jobs', 'process_status_queue'):
jobs[job.name] = job
return jobs | [
"def",
"list_current_jobs",
"(",
"self",
")",
":",
"jobs",
"=",
"{",
"}",
"for",
"job",
"in",
"self",
".",
"scheduler",
".",
"get_jobs",
"(",
")",
":",
"if",
"job",
".",
"name",
"not",
"in",
"(",
"'schedule_jobs'",
",",
"'process_status_queue'",
")",
"... | Return a list of the currently scheduled jobs in APScheduler
Returns:
`dict` of `str`: :obj:`apscheduler/job:Job` | [
"Return",
"a",
"list",
"of",
"the",
"currently",
"scheduled",
"jobs",
"in",
"APScheduler"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py#L83-L94 |
232,074 | RiotGames/cloud-inquisitor | plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py | SQSScheduler.send_worker_queue_message | def send_worker_queue_message(self, *, batch_id, job_name, entry_point, worker_args, retry_count=0):
"""Send a message to the `worker_queue` for a worker to execute the requests job
Args:
batch_id (`str`): Unique ID of the batch the job belongs to
job_name (`str`): Non-unique ID of the job. This is used to ensure that the same job is only scheduled
a single time per batch
entry_point (`dict`): A dictionary providing the entry point information for the worker to load the class
worker_args (`dict`): A dictionary with the arguments required by the worker class (if any, can be an
empty dictionary)
retry_count (`int`): The number of times this one job has been attempted to be executed. If a job fails to
execute after 3 retries it will be marked as failed
Returns:
`None`
"""
try:
job_id = str(uuid4())
self.job_queue.send_message(
MessageBody=json.dumps({
'batch_id': batch_id,
'job_id': job_id,
'job_name': job_name,
'entry_point': entry_point,
'worker_args': worker_args,
}),
MessageDeduplicationId=job_id,
MessageGroupId=batch_id,
MessageAttributes={
'RetryCount': {
'StringValue': str(retry_count),
'DataType': 'Number'
}
}
)
if retry_count == 0:
job = SchedulerJob()
job.job_id = job_id
job.batch_id = batch_id
job.status = SchedulerStatus.PENDING
job.data = worker_args
db.session.add(job)
db.session.commit()
except:
self.log.exception('Error when processing worker task') | python | def send_worker_queue_message(self, *, batch_id, job_name, entry_point, worker_args, retry_count=0):
try:
job_id = str(uuid4())
self.job_queue.send_message(
MessageBody=json.dumps({
'batch_id': batch_id,
'job_id': job_id,
'job_name': job_name,
'entry_point': entry_point,
'worker_args': worker_args,
}),
MessageDeduplicationId=job_id,
MessageGroupId=batch_id,
MessageAttributes={
'RetryCount': {
'StringValue': str(retry_count),
'DataType': 'Number'
}
}
)
if retry_count == 0:
job = SchedulerJob()
job.job_id = job_id
job.batch_id = batch_id
job.status = SchedulerStatus.PENDING
job.data = worker_args
db.session.add(job)
db.session.commit()
except:
self.log.exception('Error when processing worker task') | [
"def",
"send_worker_queue_message",
"(",
"self",
",",
"*",
",",
"batch_id",
",",
"job_name",
",",
"entry_point",
",",
"worker_args",
",",
"retry_count",
"=",
"0",
")",
":",
"try",
":",
"job_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"self",
".",
"jo... | Send a message to the `worker_queue` for a worker to execute the requests job
Args:
batch_id (`str`): Unique ID of the batch the job belongs to
job_name (`str`): Non-unique ID of the job. This is used to ensure that the same job is only scheduled
a single time per batch
entry_point (`dict`): A dictionary providing the entry point information for the worker to load the class
worker_args (`dict`): A dictionary with the arguments required by the worker class (if any, can be an
empty dictionary)
retry_count (`int`): The number of times this one job has been attempted to be executed. If a job fails to
execute after 3 retries it will be marked as failed
Returns:
`None` | [
"Send",
"a",
"message",
"to",
"the",
"worker_queue",
"for",
"a",
"worker",
"to",
"execute",
"the",
"requests",
"job"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py#L235-L282 |
232,075 | RiotGames/cloud-inquisitor | plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py | SQSScheduler.send_status_message | def send_status_message(self, object_id, status):
"""Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of the job
Returns:
`bool`
"""
try:
body = json.dumps({
'id': object_id,
'status': status
})
self.status_queue.send_message(
MessageBody=body,
MessageGroupId='job_status',
MessageDeduplicationId=get_hash((object_id, status))
)
return True
except Exception as ex:
print(ex)
return False | python | def send_status_message(self, object_id, status):
try:
body = json.dumps({
'id': object_id,
'status': status
})
self.status_queue.send_message(
MessageBody=body,
MessageGroupId='job_status',
MessageDeduplicationId=get_hash((object_id, status))
)
return True
except Exception as ex:
print(ex)
return False | [
"def",
"send_status_message",
"(",
"self",
",",
"object_id",
",",
"status",
")",
":",
"try",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"{",
"'id'",
":",
"object_id",
",",
"'status'",
":",
"status",
"}",
")",
"self",
".",
"status_queue",
".",
"send_m... | Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of the job
Returns:
`bool` | [
"Send",
"a",
"message",
"to",
"the",
"status_queue",
"to",
"update",
"a",
"job",
"s",
"status",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py#L355-L381 |
232,076 | RiotGames/cloud-inquisitor | plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py | SQSScheduler.process_status_queue | def process_status_queue(self):
"""Process all messages in the `status_queue` and check for any batches that needs to change status
Returns:
`None`
"""
self.log.debug('Start processing status queue')
while True:
messages = self.status_queue.receive_messages(MaxNumberOfMessages=10)
if not messages:
break
for message in messages:
data = json.loads(message.body)
job = SchedulerJob.get(data['id'])
try:
if job and job.update_status(data['status']):
db.session.commit()
except SchedulerError as ex:
if hasattr(ex, 'message') and ex.message == 'Attempting to update already completed job':
pass
message.delete()
# Close any batch that is now complete
open_batches = db.SchedulerBatch.find(SchedulerBatch.status < SchedulerStatus.COMPLETED)
for batch in open_batches:
open_jobs = list(filter(lambda x: x.status < SchedulerStatus.COMPLETED, batch.jobs))
if not open_jobs:
open_batches.remove(batch)
batch.update_status(SchedulerStatus.COMPLETED)
self.log.debug('Closed completed batch {}'.format(batch.batch_id))
else:
started_jobs = list(filter(lambda x: x.status > SchedulerStatus.PENDING, open_jobs))
if batch.status == SchedulerStatus.PENDING and len(started_jobs) > 0:
batch.update_status(SchedulerStatus.STARTED)
self.log.debug('Started batch manually {}'.format(batch.batch_id))
# Check for stale batches / jobs
for batch in open_batches:
if batch.started < datetime.now() - timedelta(hours=2):
self.log.warning('Closing a stale scheduler batch: {}'.format(batch.batch_id))
for job in batch.jobs:
if job.status < SchedulerStatus.COMPLETED:
job.update_status(SchedulerStatus.ABORTED)
batch.update_status(SchedulerStatus.ABORTED)
db.session.commit() | python | def process_status_queue(self):
self.log.debug('Start processing status queue')
while True:
messages = self.status_queue.receive_messages(MaxNumberOfMessages=10)
if not messages:
break
for message in messages:
data = json.loads(message.body)
job = SchedulerJob.get(data['id'])
try:
if job and job.update_status(data['status']):
db.session.commit()
except SchedulerError as ex:
if hasattr(ex, 'message') and ex.message == 'Attempting to update already completed job':
pass
message.delete()
# Close any batch that is now complete
open_batches = db.SchedulerBatch.find(SchedulerBatch.status < SchedulerStatus.COMPLETED)
for batch in open_batches:
open_jobs = list(filter(lambda x: x.status < SchedulerStatus.COMPLETED, batch.jobs))
if not open_jobs:
open_batches.remove(batch)
batch.update_status(SchedulerStatus.COMPLETED)
self.log.debug('Closed completed batch {}'.format(batch.batch_id))
else:
started_jobs = list(filter(lambda x: x.status > SchedulerStatus.PENDING, open_jobs))
if batch.status == SchedulerStatus.PENDING and len(started_jobs) > 0:
batch.update_status(SchedulerStatus.STARTED)
self.log.debug('Started batch manually {}'.format(batch.batch_id))
# Check for stale batches / jobs
for batch in open_batches:
if batch.started < datetime.now() - timedelta(hours=2):
self.log.warning('Closing a stale scheduler batch: {}'.format(batch.batch_id))
for job in batch.jobs:
if job.status < SchedulerStatus.COMPLETED:
job.update_status(SchedulerStatus.ABORTED)
batch.update_status(SchedulerStatus.ABORTED)
db.session.commit() | [
"def",
"process_status_queue",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Start processing status queue'",
")",
"while",
"True",
":",
"messages",
"=",
"self",
".",
"status_queue",
".",
"receive_messages",
"(",
"MaxNumberOfMessages",
"=",
"10... | Process all messages in the `status_queue` and check for any batches that needs to change status
Returns:
`None` | [
"Process",
"all",
"messages",
"in",
"the",
"status_queue",
"and",
"check",
"for",
"any",
"batches",
"that",
"needs",
"to",
"change",
"status"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-scheduler-sqs/cinq_scheduler_sqs/__init__.py#L384-L431 |
232,077 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py | IAMAuditor.run | def run(self, *args, **kwargs):
"""Iterate through all AWS accounts and apply roles and policies from Github
Args:
*args: Optional list of arguments
**kwargs: Optional list of keyword arguments
Returns:
`None`
"""
accounts = list(AWSAccount.get_all(include_disabled=False).values())
self.manage_policies(accounts) | python | def run(self, *args, **kwargs):
accounts = list(AWSAccount.get_all(include_disabled=False).values())
self.manage_policies(accounts) | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"accounts",
"=",
"list",
"(",
"AWSAccount",
".",
"get_all",
"(",
"include_disabled",
"=",
"False",
")",
".",
"values",
"(",
")",
")",
"self",
".",
"manage_policies",
"(",... | Iterate through all AWS accounts and apply roles and policies from Github
Args:
*args: Optional list of arguments
**kwargs: Optional list of keyword arguments
Returns:
`None` | [
"Iterate",
"through",
"all",
"AWS",
"accounts",
"and",
"apply",
"roles",
"and",
"policies",
"from",
"Github"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L44-L55 |
232,078 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py | IAMAuditor.get_policies_from_git | def get_policies_from_git(self):
"""Retrieve policies from the Git repo. Returns a dictionary containing all the roles and policies
Returns:
:obj:`dict` of `str`: `dict`
"""
fldr = mkdtemp()
try:
url = 'https://{token}:x-oauth-basic@{server}/{repo}'.format(**{
'token': self.dbconfig.get('git_auth_token', self.ns),
'server': self.dbconfig.get('git_server', self.ns),
'repo': self.dbconfig.get('git_repo', self.ns)
})
policies = {'GLOBAL': {}}
if self.dbconfig.get('git_no_ssl_verify', self.ns, False):
os.environ['GIT_SSL_NO_VERIFY'] = '1'
repo = Repo.clone_from(url, fldr)
for obj in repo.head.commit.tree:
name, ext = os.path.splitext(obj.name)
# Read the standard policies
if ext == '.json':
policies['GLOBAL'][name] = obj.data_stream.read()
# Read any account role specific policies
if name == 'roles' and obj.type == 'tree':
for account in [x for x in obj.trees]:
for role in [x for x in account.trees]:
role_policies = {policy.name.replace('.json', ''): policy.data_stream.read() for policy in
role.blobs if
policy.name.endswith('.json')}
if account.name in policies:
if role.name in policies[account.name]:
policies[account.name][role.name] += role_policies
else:
policies[account.name][role.name] = role_policies
else:
policies[account.name] = {
role.name: role_policies
}
return policies
finally:
if os.path.exists(fldr) and os.path.isdir(fldr):
shutil.rmtree(fldr) | python | def get_policies_from_git(self):
fldr = mkdtemp()
try:
url = 'https://{token}:x-oauth-basic@{server}/{repo}'.format(**{
'token': self.dbconfig.get('git_auth_token', self.ns),
'server': self.dbconfig.get('git_server', self.ns),
'repo': self.dbconfig.get('git_repo', self.ns)
})
policies = {'GLOBAL': {}}
if self.dbconfig.get('git_no_ssl_verify', self.ns, False):
os.environ['GIT_SSL_NO_VERIFY'] = '1'
repo = Repo.clone_from(url, fldr)
for obj in repo.head.commit.tree:
name, ext = os.path.splitext(obj.name)
# Read the standard policies
if ext == '.json':
policies['GLOBAL'][name] = obj.data_stream.read()
# Read any account role specific policies
if name == 'roles' and obj.type == 'tree':
for account in [x for x in obj.trees]:
for role in [x for x in account.trees]:
role_policies = {policy.name.replace('.json', ''): policy.data_stream.read() for policy in
role.blobs if
policy.name.endswith('.json')}
if account.name in policies:
if role.name in policies[account.name]:
policies[account.name][role.name] += role_policies
else:
policies[account.name][role.name] = role_policies
else:
policies[account.name] = {
role.name: role_policies
}
return policies
finally:
if os.path.exists(fldr) and os.path.isdir(fldr):
shutil.rmtree(fldr) | [
"def",
"get_policies_from_git",
"(",
"self",
")",
":",
"fldr",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"url",
"=",
"'https://{token}:x-oauth-basic@{server}/{repo}'",
".",
"format",
"(",
"*",
"*",
"{",
"'token'",
":",
"self",
".",
"dbconfig",
".",
"get",
"(",
... | Retrieve policies from the Git repo. Returns a dictionary containing all the roles and policies
Returns:
:obj:`dict` of `str`: `dict` | [
"Retrieve",
"policies",
"from",
"the",
"Git",
"repo",
".",
"Returns",
"a",
"dictionary",
"containing",
"all",
"the",
"roles",
"and",
"policies"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L287-L334 |
232,079 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py | IAMAuditor.get_policies_from_aws | def get_policies_from_aws(client, scope='Local'):
"""Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str`): The policy scope to use. Default: Local
Returns:
:obj:`list` of `dict`
"""
done = False
marker = None
policies = []
while not done:
if marker:
response = client.list_policies(Marker=marker, Scope=scope)
else:
response = client.list_policies(Scope=scope)
policies += response['Policies']
if response['IsTruncated']:
marker = response['Marker']
else:
done = True
return policies | python | def get_policies_from_aws(client, scope='Local'):
done = False
marker = None
policies = []
while not done:
if marker:
response = client.list_policies(Marker=marker, Scope=scope)
else:
response = client.list_policies(Scope=scope)
policies += response['Policies']
if response['IsTruncated']:
marker = response['Marker']
else:
done = True
return policies | [
"def",
"get_policies_from_aws",
"(",
"client",
",",
"scope",
"=",
"'Local'",
")",
":",
"done",
"=",
"False",
"marker",
"=",
"None",
"policies",
"=",
"[",
"]",
"while",
"not",
"done",
":",
"if",
"marker",
":",
"response",
"=",
"client",
".",
"list_policie... | Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str`): The policy scope to use. Default: Local
Returns:
:obj:`list` of `dict` | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"policies",
"currently",
"applied",
"to",
"an",
"AWS",
"Account",
".",
"Returns",
"a",
"list",
"containing",
"all",
"the",
"policies",
"for",
"the",
"specified",
"scope"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L337-L365 |
232,080 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py | IAMAuditor.get_roles | def get_roles(client):
"""Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict`
"""
done = False
marker = None
roles = []
while not done:
if marker:
response = client.list_roles(Marker=marker)
else:
response = client.list_roles()
roles += response['Roles']
if response['IsTruncated']:
marker = response['Marker']
else:
done = True
return roles | python | def get_roles(client):
done = False
marker = None
roles = []
while not done:
if marker:
response = client.list_roles(Marker=marker)
else:
response = client.list_roles()
roles += response['Roles']
if response['IsTruncated']:
marker = response['Marker']
else:
done = True
return roles | [
"def",
"get_roles",
"(",
"client",
")",
":",
"done",
"=",
"False",
"marker",
"=",
"None",
"roles",
"=",
"[",
"]",
"while",
"not",
"done",
":",
"if",
"marker",
":",
"response",
"=",
"client",
".",
"list_roles",
"(",
"Marker",
"=",
"marker",
")",
"else... | Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict` | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"roles",
"for",
"an",
"account",
".",
"Returns",
"a",
"list",
"containing",
"all",
"the",
"roles",
"for",
"the",
"account",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L368-L394 |
232,081 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py | IAMAuditor.create_policy | def create_policy(self, account, client, document, name, arn=None):
"""Create a new IAM policy.
If the policy already exists, a new version will be added and if needed the oldest policy version not in use
will be removed. Returns a dictionary containing the policy or version information
Args:
account (:obj:`Account`): Account to create the policy on
client (:obj:`boto3.client`): A boto3 client object
document (`str`): Policy document
name (`str`): Name of the policy to create / update
arn (`str`): Optional ARN for the policy to update
Returns:
`dict`
"""
if not arn and not name:
raise ValueError('create_policy must be called with either arn or name in the argument list')
if arn:
response = client.list_policy_versions(PolicyArn=arn)
# If we're at the max of the 5 possible versions, remove the oldest version that is not
# the currently active policy
if len(response['Versions']) >= 5:
version = [x for x in sorted(
response['Versions'],
key=lambda k: k['CreateDate']
) if not x['IsDefaultVersion']][0]
self.log.info('Deleting oldest IAM Policy version {}/{}'.format(arn, version['VersionId']))
client.delete_policy_version(PolicyArn=arn, VersionId=version['VersionId'])
auditlog(
event='iam.check_roles.delete_policy_version',
actor=self.ns,
data={
'account': account.account_name,
'policyName': name,
'policyArn': arn,
'versionId': version['VersionId']
}
)
res = client.create_policy_version(
PolicyArn=arn,
PolicyDocument=document,
SetAsDefault=True
)
else:
res = client.create_policy(
PolicyName=name,
PolicyDocument=document
)
auditlog(
event='iam.check_roles.create_policy',
actor=self.ns,
data={
'account': account.account_name,
'policyName': name,
'policyArn': arn
}
)
return res | python | def create_policy(self, account, client, document, name, arn=None):
if not arn and not name:
raise ValueError('create_policy must be called with either arn or name in the argument list')
if arn:
response = client.list_policy_versions(PolicyArn=arn)
# If we're at the max of the 5 possible versions, remove the oldest version that is not
# the currently active policy
if len(response['Versions']) >= 5:
version = [x for x in sorted(
response['Versions'],
key=lambda k: k['CreateDate']
) if not x['IsDefaultVersion']][0]
self.log.info('Deleting oldest IAM Policy version {}/{}'.format(arn, version['VersionId']))
client.delete_policy_version(PolicyArn=arn, VersionId=version['VersionId'])
auditlog(
event='iam.check_roles.delete_policy_version',
actor=self.ns,
data={
'account': account.account_name,
'policyName': name,
'policyArn': arn,
'versionId': version['VersionId']
}
)
res = client.create_policy_version(
PolicyArn=arn,
PolicyDocument=document,
SetAsDefault=True
)
else:
res = client.create_policy(
PolicyName=name,
PolicyDocument=document
)
auditlog(
event='iam.check_roles.create_policy',
actor=self.ns,
data={
'account': account.account_name,
'policyName': name,
'policyArn': arn
}
)
return res | [
"def",
"create_policy",
"(",
"self",
",",
"account",
",",
"client",
",",
"document",
",",
"name",
",",
"arn",
"=",
"None",
")",
":",
"if",
"not",
"arn",
"and",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"'create_policy must be called with either arn or na... | Create a new IAM policy.
If the policy already exists, a new version will be added and if needed the oldest policy version not in use
will be removed. Returns a dictionary containing the policy or version information
Args:
account (:obj:`Account`): Account to create the policy on
client (:obj:`boto3.client`): A boto3 client object
document (`str`): Policy document
name (`str`): Name of the policy to create / update
arn (`str`): Optional ARN for the policy to update
Returns:
`dict` | [
"Create",
"a",
"new",
"IAM",
"policy",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L396-L459 |
232,082 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/notifiers/slack.py | SlackNotifier.notify | def notify(self, subsystem, recipient, subject, body_html, body_text):
"""You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notification
recipient (`str`): Recipient
subject (`str`): Subject / title of the notification, not used for this notifier
body_html (`str)`: HTML formatted version of the message, not used for this notifier
body_text (`str`): Text formatted version of the message
Returns:
`None`
"""
if not re.match(self.validation, recipient, re.I):
raise ValueError('Invalid recipient provided')
if recipient.startswith('#'):
target_type = 'channel'
elif recipient.find('@') != -1:
target_type = 'user'
else:
self.log.error('Unknown contact type for Slack: {}'.format(recipient))
return
try:
self._send_message(
target_type=target_type,
target=recipient,
message=body_text,
title=subject
)
except SlackError as ex:
self.log.error('Failed sending message to {}: {}'.format(recipient, ex)) | python | def notify(self, subsystem, recipient, subject, body_html, body_text):
if not re.match(self.validation, recipient, re.I):
raise ValueError('Invalid recipient provided')
if recipient.startswith('#'):
target_type = 'channel'
elif recipient.find('@') != -1:
target_type = 'user'
else:
self.log.error('Unknown contact type for Slack: {}'.format(recipient))
return
try:
self._send_message(
target_type=target_type,
target=recipient,
message=body_text,
title=subject
)
except SlackError as ex:
self.log.error('Failed sending message to {}: {}'.format(recipient, ex)) | [
"def",
"notify",
"(",
"self",
",",
"subsystem",
",",
"recipient",
",",
"subject",
",",
"body_html",
",",
"body_text",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"self",
".",
"validation",
",",
"recipient",
",",
"re",
".",
"I",
")",
":",
"raise",... | You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notification
recipient (`str`): Recipient
subject (`str`): Subject / title of the notification, not used for this notifier
body_html (`str)`: HTML formatted version of the message, not used for this notifier
body_text (`str`): Text formatted version of the message
Returns:
`None` | [
"You",
"can",
"send",
"messages",
"either",
"to",
"channels",
"and",
"private",
"groups",
"by",
"using",
"the",
"following",
"formats"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/notifiers/slack.py#L94-L131 |
232,083 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/notifiers/slack.py | SlackNotifier.send_message | def send_message(contacts, message):
"""List of contacts the send the message to. You can send messages either to channels and private groups by
using the following formats
#channel-name
@username-direct-message
If the channel is the name of a private group / channel, you must first invite the bot to the channel to ensure
it is allowed to send messages to the group.
Returns true if the message was sent, else `False`
Args:
contacts (:obj:`list` of `str`,`str`): List of contacts
message (str): Message to send
Returns:
`bool`
"""
if type(contacts) == str:
contacts = [contacts]
recipients = list(set(contacts))
send_notification(
subsystem='UNKNOWN',
recipients=[NotificationContact('slack', x) for x in recipients],
subject=None,
body_html=message,
body_text=message
) | python | def send_message(contacts, message):
if type(contacts) == str:
contacts = [contacts]
recipients = list(set(contacts))
send_notification(
subsystem='UNKNOWN',
recipients=[NotificationContact('slack', x) for x in recipients],
subject=None,
body_html=message,
body_text=message
) | [
"def",
"send_message",
"(",
"contacts",
",",
"message",
")",
":",
"if",
"type",
"(",
"contacts",
")",
"==",
"str",
":",
"contacts",
"=",
"[",
"contacts",
"]",
"recipients",
"=",
"list",
"(",
"set",
"(",
"contacts",
")",
")",
"send_notification",
"(",
"... | List of contacts the send the message to. You can send messages either to channels and private groups by
using the following formats
#channel-name
@username-direct-message
If the channel is the name of a private group / channel, you must first invite the bot to the channel to ensure
it is allowed to send messages to the group.
Returns true if the message was sent, else `False`
Args:
contacts (:obj:`list` of `str`,`str`): List of contacts
message (str): Message to send
Returns:
`bool` | [
"List",
"of",
"contacts",
"the",
"send",
"the",
"message",
"to",
".",
"You",
"can",
"send",
"messages",
"either",
"to",
"channels",
"and",
"private",
"groups",
"by",
"using",
"the",
"following",
"formats"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/notifiers/slack.py#L135-L165 |
232,084 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | _register_default_option | def _register_default_option(nsobj, opt):
""" Register default ConfigOption value if it doesn't exist. If does exist, update the description if needed """
item = ConfigItem.get(nsobj.namespace_prefix, opt.name)
if not item:
logger.info('Adding {} ({}) = {} to {}'.format(
opt.name,
opt.type,
opt.default_value,
nsobj.namespace_prefix
))
item = ConfigItem()
item.namespace_prefix = nsobj.namespace_prefix
item.key = opt.name
item.value = opt.default_value
item.type = opt.type
item.description = opt.description
nsobj.config_items.append(item)
else:
if item.description != opt.description:
logger.info('Updating description of {} / {}'.format(item.namespace_prefix, item.key))
item.description = opt.description
db.session.add(item) | python | def _register_default_option(nsobj, opt):
item = ConfigItem.get(nsobj.namespace_prefix, opt.name)
if not item:
logger.info('Adding {} ({}) = {} to {}'.format(
opt.name,
opt.type,
opt.default_value,
nsobj.namespace_prefix
))
item = ConfigItem()
item.namespace_prefix = nsobj.namespace_prefix
item.key = opt.name
item.value = opt.default_value
item.type = opt.type
item.description = opt.description
nsobj.config_items.append(item)
else:
if item.description != opt.description:
logger.info('Updating description of {} / {}'.format(item.namespace_prefix, item.key))
item.description = opt.description
db.session.add(item) | [
"def",
"_register_default_option",
"(",
"nsobj",
",",
"opt",
")",
":",
"item",
"=",
"ConfigItem",
".",
"get",
"(",
"nsobj",
".",
"namespace_prefix",
",",
"opt",
".",
"name",
")",
"if",
"not",
"item",
":",
"logger",
".",
"info",
"(",
"'Adding {} ({}) = {} t... | Register default ConfigOption value if it doesn't exist. If does exist, update the description if needed | [
"Register",
"default",
"ConfigOption",
"value",
"if",
"it",
"doesn",
"t",
"exist",
".",
"If",
"does",
"exist",
"update",
"the",
"description",
"if",
"needed"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L40-L61 |
232,085 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | _import_templates | def _import_templates(force=False):
"""Import templates from disk into database
Reads all templates from disk and adds them to the database. By default, any template that has been modified by
the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
to be imported regardless of status
Args:
force (`bool`): Force overwrite any templates with local changes made. Default: `False`
Returns:
`None`
"""
tmplpath = os.path.join(resource_filename('cloud_inquisitor', 'data'), 'templates')
disk_templates = {f: os.path.join(root, f) for root, directory, files in os.walk(tmplpath) for f in files}
db_templates = {tmpl.template_name: tmpl for tmpl in db.Template.find()}
for name, template_file in disk_templates.items():
with open(template_file, 'r') as f:
body = f.read()
disk_hash = get_hash(body)
if name not in db_templates:
template = Template()
template.template_name = name
template.template = body
db.session.add(template)
auditlog(
event='template.import',
actor='init',
data={
'template_name': name,
'template': body
}
)
logger.info('Imported template {}'.format(name))
else:
template = db_templates[name]
db_hash = get_hash(template.template)
if db_hash != disk_hash:
if force or not db_templates[name].is_modified:
template.template = body
db.session.add(template)
auditlog(
event='template.update',
actor='init',
data={
'template_name': name,
'template_diff': diff(template.template, body)
}
)
logger.info('Updated template {}'.format(name))
else:
logger.warning(
'Updated template available for {}. Will not import as it would'
' overwrite user edited content and force is not enabled'.format(name)
) | python | def _import_templates(force=False):
tmplpath = os.path.join(resource_filename('cloud_inquisitor', 'data'), 'templates')
disk_templates = {f: os.path.join(root, f) for root, directory, files in os.walk(tmplpath) for f in files}
db_templates = {tmpl.template_name: tmpl for tmpl in db.Template.find()}
for name, template_file in disk_templates.items():
with open(template_file, 'r') as f:
body = f.read()
disk_hash = get_hash(body)
if name not in db_templates:
template = Template()
template.template_name = name
template.template = body
db.session.add(template)
auditlog(
event='template.import',
actor='init',
data={
'template_name': name,
'template': body
}
)
logger.info('Imported template {}'.format(name))
else:
template = db_templates[name]
db_hash = get_hash(template.template)
if db_hash != disk_hash:
if force or not db_templates[name].is_modified:
template.template = body
db.session.add(template)
auditlog(
event='template.update',
actor='init',
data={
'template_name': name,
'template_diff': diff(template.template, body)
}
)
logger.info('Updated template {}'.format(name))
else:
logger.warning(
'Updated template available for {}. Will not import as it would'
' overwrite user edited content and force is not enabled'.format(name)
) | [
"def",
"_import_templates",
"(",
"force",
"=",
"False",
")",
":",
"tmplpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"resource_filename",
"(",
"'cloud_inquisitor'",
",",
"'data'",
")",
",",
"'templates'",
")",
"disk_templates",
"=",
"{",
"f",
":",
"os",... | Import templates from disk into database
Reads all templates from disk and adds them to the database. By default, any template that has been modified by
the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
to be imported regardless of status
Args:
force (`bool`): Force overwrite any templates with local changes made. Default: `False`
Returns:
`None` | [
"Import",
"templates",
"from",
"disk",
"into",
"database"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L78-L137 |
232,086 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | initialize | def initialize():
"""Initialize the application configuration, adding any missing default configuration or roles
Returns:
`None`
"""
global __initialized
if __initialized:
return
# Setup all the default base settings
try:
for data in DEFAULT_CONFIG_OPTIONS:
nsobj = _get_config_namespace(data['prefix'], data['name'], sort_order=data['sort_order'])
for opt in data['options']:
_register_default_option(nsobj, opt)
db.session.add(nsobj)
# Iterate over all of our plugins and setup their defaults
for ns, info in CINQ_PLUGINS.items():
if info['name'] == 'commands':
continue
for entry_point in info['plugins']:
_cls = entry_point.load()
if hasattr(_cls, 'ns'):
ns_name = '{}: {}'.format(info['name'].capitalize(), _cls.name)
if not isinstance(_cls.options, abstractproperty):
nsobj = _get_config_namespace(_cls.ns, ns_name)
if _cls.options:
for opt in _cls.options:
_register_default_option(nsobj, opt)
db.session.add(nsobj)
# Create the default roles if they are missing and import any missing or updated templates,
# if they havent been modified by the user
_add_default_roles()
_import_templates()
db.session.commit()
dbconfig.reload_data()
__initialized = True
except ProgrammingError as ex:
if str(ex).find('1146') != -1:
logging.getLogger('cloud_inquisitor').error(
'Missing required tables, please make sure you run `cloud-inquisitor db upgrade`'
) | python | def initialize():
global __initialized
if __initialized:
return
# Setup all the default base settings
try:
for data in DEFAULT_CONFIG_OPTIONS:
nsobj = _get_config_namespace(data['prefix'], data['name'], sort_order=data['sort_order'])
for opt in data['options']:
_register_default_option(nsobj, opt)
db.session.add(nsobj)
# Iterate over all of our plugins and setup their defaults
for ns, info in CINQ_PLUGINS.items():
if info['name'] == 'commands':
continue
for entry_point in info['plugins']:
_cls = entry_point.load()
if hasattr(_cls, 'ns'):
ns_name = '{}: {}'.format(info['name'].capitalize(), _cls.name)
if not isinstance(_cls.options, abstractproperty):
nsobj = _get_config_namespace(_cls.ns, ns_name)
if _cls.options:
for opt in _cls.options:
_register_default_option(nsobj, opt)
db.session.add(nsobj)
# Create the default roles if they are missing and import any missing or updated templates,
# if they havent been modified by the user
_add_default_roles()
_import_templates()
db.session.commit()
dbconfig.reload_data()
__initialized = True
except ProgrammingError as ex:
if str(ex).find('1146') != -1:
logging.getLogger('cloud_inquisitor').error(
'Missing required tables, please make sure you run `cloud-inquisitor db upgrade`'
) | [
"def",
"initialize",
"(",
")",
":",
"global",
"__initialized",
"if",
"__initialized",
":",
"return",
"# Setup all the default base settings",
"try",
":",
"for",
"data",
"in",
"DEFAULT_CONFIG_OPTIONS",
":",
"nsobj",
"=",
"_get_config_namespace",
"(",
"data",
"[",
"'p... | Initialize the application configuration, adding any missing default configuration or roles
Returns:
`None` | [
"Initialize",
"the",
"application",
"configuration",
"adding",
"any",
"missing",
"default",
"configuration",
"or",
"roles"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L141-L189 |
232,087 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | before_request | def before_request():
"""Checks to ensure that the session is valid and validates the users CSRF token is present
Returns:
`None`
"""
if not request.path.startswith('/saml') and not request.path.startswith('/auth'):
# Validate the session has the items we need
if 'accounts' not in session:
logger.debug('Missing \'accounts\' from session object, sending user to login page')
return BaseView.make_unauth_response()
# Require the CSRF token to be present if we are performing a change action (add, delete or modify objects)
# but exclude the SAML endpoints from the CSRF check
if request.method in ('POST', 'PUT', 'DELETE',):
if session['csrf_token'] != request.headers.get('X-Csrf-Token'):
logger.info('CSRF Token is missing or incorrect, sending user to login page')
abort(403) | python | def before_request():
if not request.path.startswith('/saml') and not request.path.startswith('/auth'):
# Validate the session has the items we need
if 'accounts' not in session:
logger.debug('Missing \'accounts\' from session object, sending user to login page')
return BaseView.make_unauth_response()
# Require the CSRF token to be present if we are performing a change action (add, delete or modify objects)
# but exclude the SAML endpoints from the CSRF check
if request.method in ('POST', 'PUT', 'DELETE',):
if session['csrf_token'] != request.headers.get('X-Csrf-Token'):
logger.info('CSRF Token is missing or incorrect, sending user to login page')
abort(403) | [
"def",
"before_request",
"(",
")",
":",
"if",
"not",
"request",
".",
"path",
".",
"startswith",
"(",
"'/saml'",
")",
"and",
"not",
"request",
".",
"path",
".",
"startswith",
"(",
"'/auth'",
")",
":",
"# Validate the session has the items we need",
"if",
"'acco... | Checks to ensure that the session is valid and validates the users CSRF token is present
Returns:
`None` | [
"Checks",
"to",
"ensure",
"that",
"the",
"session",
"is",
"valid",
"and",
"validates",
"the",
"users",
"CSRF",
"token",
"is",
"present"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L339-L356 |
232,088 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | after_request | def after_request(response):
"""Modifies the response object prior to sending it to the client. Used to add CORS headers to the request
Args:
response (response): Flask response object
Returns:
`None`
"""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response | python | def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response | [
"def",
"after_request",
"(",
"response",
")",
":",
"response",
".",
"headers",
".",
"add",
"(",
"'Access-Control-Allow-Origin'",
",",
"'*'",
")",
"response",
".",
"headers",
".",
"add",
"(",
"'Access-Control-Allow-Headers'",
",",
"'Content-Type,Authorization'",
")",... | Modifies the response object prior to sending it to the client. Used to add CORS headers to the request
Args:
response (response): Flask response object
Returns:
`None` | [
"Modifies",
"the",
"response",
"object",
"prior",
"to",
"sending",
"it",
"to",
"the",
"client",
".",
"Used",
"to",
"add",
"CORS",
"headers",
"to",
"the",
"request"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L359-L371 |
232,089 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | CINQFlask.register_auth_system | def register_auth_system(self, auth_system):
"""Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered
as the active auth system, else `False`
Args:
auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to register
Returns:
`bool`
"""
auth_system_settings = dbconfig.get('auth_system')
if auth_system.name not in auth_system_settings['available']:
auth_system_settings['available'].append(auth_system.name)
dbconfig.set('default', 'auth_system', DBCChoice(auth_system_settings))
if auth_system.name == auth_system_settings['enabled'][0]:
self.active_auth_system = auth_system
auth_system().bootstrap()
logger.debug('Registered {} as the active auth system'.format(auth_system.name))
return True
else:
logger.debug('Not trying to load the {} auth system as it is disabled by config'.format(auth_system.name))
return False | python | def register_auth_system(self, auth_system):
auth_system_settings = dbconfig.get('auth_system')
if auth_system.name not in auth_system_settings['available']:
auth_system_settings['available'].append(auth_system.name)
dbconfig.set('default', 'auth_system', DBCChoice(auth_system_settings))
if auth_system.name == auth_system_settings['enabled'][0]:
self.active_auth_system = auth_system
auth_system().bootstrap()
logger.debug('Registered {} as the active auth system'.format(auth_system.name))
return True
else:
logger.debug('Not trying to load the {} auth system as it is disabled by config'.format(auth_system.name))
return False | [
"def",
"register_auth_system",
"(",
"self",
",",
"auth_system",
")",
":",
"auth_system_settings",
"=",
"dbconfig",
".",
"get",
"(",
"'auth_system'",
")",
"if",
"auth_system",
".",
"name",
"not",
"in",
"auth_system_settings",
"[",
"'available'",
"]",
":",
"auth_s... | Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered
as the active auth system, else `False`
Args:
auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to register
Returns:
`bool` | [
"Register",
"a",
"given",
"authentication",
"system",
"with",
"the",
"framework",
".",
"Returns",
"True",
"if",
"the",
"auth_system",
"is",
"registered",
"as",
"the",
"active",
"auth",
"system",
"else",
"False"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L227-L251 |
232,090 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | CINQFlask.register_menu_item | def register_menu_item(self, items):
"""Registers a views menu items into the metadata for the application. Skip if the item is already present
Args:
items (`list` of `MenuItem`): A list of `MenuItem`s
Returns:
`None`
"""
for itm in items:
if itm.group in self.menu_items:
# Only add the menu item if we don't already have it registered
if itm not in self.menu_items[itm.group]['items']:
self.menu_items[itm.group]['items'].append(itm)
else:
logger.warning('Tried registering menu item to unknown group {}'.format(itm.group)) | python | def register_menu_item(self, items):
for itm in items:
if itm.group in self.menu_items:
# Only add the menu item if we don't already have it registered
if itm not in self.menu_items[itm.group]['items']:
self.menu_items[itm.group]['items'].append(itm)
else:
logger.warning('Tried registering menu item to unknown group {}'.format(itm.group)) | [
"def",
"register_menu_item",
"(",
"self",
",",
"items",
")",
":",
"for",
"itm",
"in",
"items",
":",
"if",
"itm",
".",
"group",
"in",
"self",
".",
"menu_items",
":",
"# Only add the menu item if we don't already have it registered",
"if",
"itm",
"not",
"in",
"sel... | Registers a views menu items into the metadata for the application. Skip if the item is already present
Args:
items (`list` of `MenuItem`): A list of `MenuItem`s
Returns:
`None` | [
"Registers",
"a",
"views",
"menu",
"items",
"into",
"the",
"metadata",
"for",
"the",
"application",
".",
"Skip",
"if",
"the",
"item",
"is",
"already",
"present"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L253-L268 |
232,091 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | CINQFlask.__register_types | def __register_types(self):
"""Iterates all entry points for resource types and registers a `resource_type_id` to class mapping
Returns:
`None`
"""
try:
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
cls = entry_point.load()
self.types[ResourceType.get(cls.resource_type).resource_type_id] = cls
logger.debug('Registered resource type {}'.format(cls.__name__))
except SQLAlchemyError as ex:
logger.warning('Failed loading type information: {}'.format(ex)) | python | def __register_types(self):
try:
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
cls = entry_point.load()
self.types[ResourceType.get(cls.resource_type).resource_type_id] = cls
logger.debug('Registered resource type {}'.format(cls.__name__))
except SQLAlchemyError as ex:
logger.warning('Failed loading type information: {}'.format(ex)) | [
"def",
"__register_types",
"(",
"self",
")",
":",
"try",
":",
"for",
"entry_point",
"in",
"CINQ_PLUGINS",
"[",
"'cloud_inquisitor.plugins.types'",
"]",
"[",
"'plugins'",
"]",
":",
"cls",
"=",
"entry_point",
".",
"load",
"(",
")",
"self",
".",
"types",
"[",
... | Iterates all entry points for resource types and registers a `resource_type_id` to class mapping
Returns:
`None` | [
"Iterates",
"all",
"entry",
"points",
"for",
"resource",
"types",
"and",
"registers",
"a",
"resource_type_id",
"to",
"class",
"mapping"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L271-L283 |
232,092 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | CINQFlask.__register_notifiers | def __register_notifiers(self):
"""Lists all notifiers to be able to provide metadata for the frontend
Returns:
`list` of `dict`
"""
notifiers = {}
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.notifiers']['plugins']:
cls = entry_point.load()
notifiers[cls.notifier_type] = cls.validation
return notifiers | python | def __register_notifiers(self):
notifiers = {}
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.notifiers']['plugins']:
cls = entry_point.load()
notifiers[cls.notifier_type] = cls.validation
return notifiers | [
"def",
"__register_notifiers",
"(",
"self",
")",
":",
"notifiers",
"=",
"{",
"}",
"for",
"entry_point",
"in",
"CINQ_PLUGINS",
"[",
"'cloud_inquisitor.plugins.notifiers'",
"]",
"[",
"'plugins'",
"]",
":",
"cls",
"=",
"entry_point",
".",
"load",
"(",
")",
"notif... | Lists all notifiers to be able to provide metadata for the frontend
Returns:
`list` of `dict` | [
"Lists",
"all",
"notifiers",
"to",
"be",
"able",
"to",
"provide",
"metadata",
"for",
"the",
"frontend"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L285-L296 |
232,093 | RiotGames/cloud-inquisitor | backend/cloud_inquisitor/app.py | CINQApi.register_views | def register_views(self, app):
"""Iterates all entry points for views and auth systems and dynamically load and register the routes with Flask
Args:
app (`CINQFlask`): CINQFlask object to register views for
Returns:
`None`
"""
self.add_resource(LoginRedirectView, '/auth/login')
self.add_resource(LogoutRedirectView, '/auth/logout')
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auth']['plugins']:
cls = entry_point.load()
app.available_auth_systems[cls.name] = cls
if app.register_auth_system(cls):
for vcls in cls.views:
self.add_resource(vcls, *vcls.URLS)
logger.debug('Registered auth system view {} for paths: {}'.format(
cls.__name__,
', '.join(vcls.URLS)
))
if not app.active_auth_system:
logger.error('No auth systems active, please enable an auth system and then start the system again')
sys.exit(-1)
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.views']['plugins']:
view = entry_point.load()
self.add_resource(view, *view.URLS)
app.register_menu_item(view.MENU_ITEMS)
logger.debug('Registered view {} for paths: {}'.format(view.__name__, ', '.join(view.URLS))) | python | def register_views(self, app):
self.add_resource(LoginRedirectView, '/auth/login')
self.add_resource(LogoutRedirectView, '/auth/logout')
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auth']['plugins']:
cls = entry_point.load()
app.available_auth_systems[cls.name] = cls
if app.register_auth_system(cls):
for vcls in cls.views:
self.add_resource(vcls, *vcls.URLS)
logger.debug('Registered auth system view {} for paths: {}'.format(
cls.__name__,
', '.join(vcls.URLS)
))
if not app.active_auth_system:
logger.error('No auth systems active, please enable an auth system and then start the system again')
sys.exit(-1)
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.views']['plugins']:
view = entry_point.load()
self.add_resource(view, *view.URLS)
app.register_menu_item(view.MENU_ITEMS)
logger.debug('Registered view {} for paths: {}'.format(view.__name__, ', '.join(view.URLS))) | [
"def",
"register_views",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"add_resource",
"(",
"LoginRedirectView",
",",
"'/auth/login'",
")",
"self",
".",
"add_resource",
"(",
"LogoutRedirectView",
",",
"'/auth/logout'",
")",
"for",
"entry_point",
"in",
"CINQ_PL... | Iterates all entry points for views and auth systems and dynamically load and register the routes with Flask
Args:
app (`CINQFlask`): CINQFlask object to register views for
Returns:
`None` | [
"Iterates",
"all",
"entry",
"points",
"for",
"views",
"and",
"auth",
"systems",
"and",
"dynamically",
"load",
"and",
"register",
"the",
"routes",
"with",
"Flask"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L303-L336 |
232,094 | RiotGames/cloud-inquisitor | plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py | DNSCollector.get_axfr_records | def get_axfr_records(self, server, domains):
"""Return a `list` of `dict`s containing the zones and their records, obtained from the DNS server
Returns:
:obj:`list` of `dict`
"""
zones = []
for zoneName in domains:
try:
zone = {
'zone_id': get_resource_id('axfrz', zoneName),
'name': zoneName,
'source': 'AXFR',
'comment': None,
'tags': {},
'records': []
}
z = dns_zone.from_xfr(query.xfr(server, zoneName))
rdata_fields = ('name', 'ttl', 'rdata')
for rr in [dict(zip(rdata_fields, x)) for x in z.iterate_rdatas()]:
record_name = rr['name'].derelativize(z.origin).to_text()
zone['records'].append(
{
'id': get_resource_id('axfrr', record_name, ['{}={}'.format(k, str(v)) for k, v in rr.items()]),
'zone_id': zone['zone_id'],
'name': record_name,
'value': sorted([rr['rdata'].to_text()]),
'type': type_to_text(rr['rdata'].rdtype)
})
if len(zone['records']) > 0:
zones.append(zone)
except Exception as ex:
self.log.exception('Failed fetching DNS zone information for {}: {}'.format(zoneName, ex))
raise
return zones | python | def get_axfr_records(self, server, domains):
zones = []
for zoneName in domains:
try:
zone = {
'zone_id': get_resource_id('axfrz', zoneName),
'name': zoneName,
'source': 'AXFR',
'comment': None,
'tags': {},
'records': []
}
z = dns_zone.from_xfr(query.xfr(server, zoneName))
rdata_fields = ('name', 'ttl', 'rdata')
for rr in [dict(zip(rdata_fields, x)) for x in z.iterate_rdatas()]:
record_name = rr['name'].derelativize(z.origin).to_text()
zone['records'].append(
{
'id': get_resource_id('axfrr', record_name, ['{}={}'.format(k, str(v)) for k, v in rr.items()]),
'zone_id': zone['zone_id'],
'name': record_name,
'value': sorted([rr['rdata'].to_text()]),
'type': type_to_text(rr['rdata'].rdtype)
})
if len(zone['records']) > 0:
zones.append(zone)
except Exception as ex:
self.log.exception('Failed fetching DNS zone information for {}: {}'.format(zoneName, ex))
raise
return zones | [
"def",
"get_axfr_records",
"(",
"self",
",",
"server",
",",
"domains",
")",
":",
"zones",
"=",
"[",
"]",
"for",
"zoneName",
"in",
"domains",
":",
"try",
":",
"zone",
"=",
"{",
"'zone_id'",
":",
"get_resource_id",
"(",
"'axfrz'",
",",
"zoneName",
")",
"... | Return a `list` of `dict`s containing the zones and their records, obtained from the DNS server
Returns:
:obj:`list` of `dict` | [
"Return",
"a",
"list",
"of",
"dict",
"s",
"containing",
"the",
"zones",
"and",
"their",
"records",
"obtained",
"from",
"the",
"DNS",
"server"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L155-L193 |
232,095 | RiotGames/cloud-inquisitor | plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py | DNSCollector.get_cloudflare_records | def get_cloudflare_records(self, *, account):
"""Return a `list` of `dict`s containing the zones and their records, obtained from the CloudFlare API
Returns:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
:obj:`list` of `dict`
"""
zones = []
for zobj in self.__cloudflare_list_zones(account=account):
try:
self.log.debug('Processing DNS zone CloudFlare/{}'.format(zobj['name']))
zone = {
'zone_id': get_resource_id('cfz', zobj['name']),
'name': zobj['name'],
'source': 'CloudFlare',
'comment': None,
'tags': {},
'records': []
}
for record in self.__cloudflare_list_zone_records(account=account, zoneID=zobj['id']):
zone['records'].append({
'id': get_resource_id('cfr', zobj['id'], ['{}={}'.format(k, v) for k, v in record.items()]),
'zone_id': zone['zone_id'],
'name': record['name'],
'value': record['value'],
'type': record['type']
})
if len(zone['records']) > 0:
zones.append(zone)
except CloudFlareError:
self.log.exception('Failed getting records for CloudFlare zone {}'.format(zobj['name']))
return zones | python | def get_cloudflare_records(self, *, account):
zones = []
for zobj in self.__cloudflare_list_zones(account=account):
try:
self.log.debug('Processing DNS zone CloudFlare/{}'.format(zobj['name']))
zone = {
'zone_id': get_resource_id('cfz', zobj['name']),
'name': zobj['name'],
'source': 'CloudFlare',
'comment': None,
'tags': {},
'records': []
}
for record in self.__cloudflare_list_zone_records(account=account, zoneID=zobj['id']):
zone['records'].append({
'id': get_resource_id('cfr', zobj['id'], ['{}={}'.format(k, v) for k, v in record.items()]),
'zone_id': zone['zone_id'],
'name': record['name'],
'value': record['value'],
'type': record['type']
})
if len(zone['records']) > 0:
zones.append(zone)
except CloudFlareError:
self.log.exception('Failed getting records for CloudFlare zone {}'.format(zobj['name']))
return zones | [
"def",
"get_cloudflare_records",
"(",
"self",
",",
"*",
",",
"account",
")",
":",
"zones",
"=",
"[",
"]",
"for",
"zobj",
"in",
"self",
".",
"__cloudflare_list_zones",
"(",
"account",
"=",
"account",
")",
":",
"try",
":",
"self",
".",
"log",
".",
"debug... | Return a `list` of `dict`s containing the zones and their records, obtained from the CloudFlare API
Returns:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
:obj:`list` of `dict` | [
"Return",
"a",
"list",
"of",
"dict",
"s",
"containing",
"the",
"zones",
"and",
"their",
"records",
"obtained",
"from",
"the",
"CloudFlare",
"API"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L195-L230 |
232,096 | RiotGames/cloud-inquisitor | plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py | DNSCollector.__cloudflare_request | def __cloudflare_request(self, *, account, path, args=None):
"""Helper function to interact with the CloudFlare API.
Args:
account (:obj:`CloudFlareAccount`): CloudFlare Account object
path (`str`): URL endpoint to communicate with
args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume
Returns:
`dict`
"""
if not args:
args = {}
if not self.cloudflare_initialized[account.account_id]:
self.cloudflare_session[account.account_id] = requests.Session()
self.cloudflare_session[account.account_id].headers.update({
'X-Auth-Email': account.email,
'X-Auth-Key': account.api_key,
'Content-Type': 'application/json'
})
self.cloudflare_initialized[account.account_id] = True
if 'per_page' not in args:
args['per_page'] = 100
response = self.cloudflare_session[account.account_id].get(account.endpoint + path, params=args)
if response.status_code != 200:
raise CloudFlareError('Request failed: {}'.format(response.text))
return response.json() | python | def __cloudflare_request(self, *, account, path, args=None):
if not args:
args = {}
if not self.cloudflare_initialized[account.account_id]:
self.cloudflare_session[account.account_id] = requests.Session()
self.cloudflare_session[account.account_id].headers.update({
'X-Auth-Email': account.email,
'X-Auth-Key': account.api_key,
'Content-Type': 'application/json'
})
self.cloudflare_initialized[account.account_id] = True
if 'per_page' not in args:
args['per_page'] = 100
response = self.cloudflare_session[account.account_id].get(account.endpoint + path, params=args)
if response.status_code != 200:
raise CloudFlareError('Request failed: {}'.format(response.text))
return response.json() | [
"def",
"__cloudflare_request",
"(",
"self",
",",
"*",
",",
"account",
",",
"path",
",",
"args",
"=",
"None",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"cloudflare_initialized",
"[",
"account",
".",
"account_id... | Helper function to interact with the CloudFlare API.
Args:
account (:obj:`CloudFlareAccount`): CloudFlare Account object
path (`str`): URL endpoint to communicate with
args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume
Returns:
`dict` | [
"Helper",
"function",
"to",
"interact",
"with",
"the",
"CloudFlare",
"API",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L233-L263 |
232,097 | RiotGames/cloud-inquisitor | plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py | DNSCollector.__cloudflare_list_zones | def __cloudflare_list_zones(self, *, account, **kwargs):
"""Helper function to list all zones registered in the CloudFlare system. Returns a `list` of the zones
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
**kwargs (`dict`): Extra arguments to pass to the API endpoint
Returns:
`list` of `dict`
"""
done = False
zones = []
page = 1
while not done:
kwargs['page'] = page
response = self.__cloudflare_request(account=account, path='/zones', args=kwargs)
info = response['result_info']
if 'total_pages' not in info or page == info['total_pages']:
done = True
else:
page += 1
zones += response['result']
return zones | python | def __cloudflare_list_zones(self, *, account, **kwargs):
done = False
zones = []
page = 1
while not done:
kwargs['page'] = page
response = self.__cloudflare_request(account=account, path='/zones', args=kwargs)
info = response['result_info']
if 'total_pages' not in info or page == info['total_pages']:
done = True
else:
page += 1
zones += response['result']
return zones | [
"def",
"__cloudflare_list_zones",
"(",
"self",
",",
"*",
",",
"account",
",",
"*",
"*",
"kwargs",
")",
":",
"done",
"=",
"False",
"zones",
"=",
"[",
"]",
"page",
"=",
"1",
"while",
"not",
"done",
":",
"kwargs",
"[",
"'page'",
"]",
"=",
"page",
"res... | Helper function to list all zones registered in the CloudFlare system. Returns a `list` of the zones
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
**kwargs (`dict`): Extra arguments to pass to the API endpoint
Returns:
`list` of `dict` | [
"Helper",
"function",
"to",
"list",
"all",
"zones",
"registered",
"in",
"the",
"CloudFlare",
"system",
".",
"Returns",
"a",
"list",
"of",
"the",
"zones"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L265-L291 |
232,098 | RiotGames/cloud-inquisitor | plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py | DNSCollector.__cloudflare_list_zone_records | def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):
"""Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and
their information.
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
zoneID (`int`): Internal CloudFlare ID of the DNS zone
**kwargs (`dict`): Additional arguments to be consumed by the API endpoint
Returns:
:obj:`dict` of `str`: `dict`
"""
done = False
records = {}
page = 1
while not done:
kwargs['page'] = page
response = self.__cloudflare_request(
account=account,
path='/zones/{}/dns_records'.format(zoneID),
args=kwargs
)
info = response['result_info']
# Check if we have received all records, and if not iterate over the result set
if 'total_pages' not in info or page >= info['total_pages']:
done = True
else:
page += 1
for record in response['result']:
if record['name'] in records:
records[record['name']]['value'] = sorted(records[record['name']]['value'] + [record['content']])
else:
records[record['name']] = {
'name': record['name'],
'value': sorted([record['content']]),
'type': record['type']
}
return list(records.values()) | python | def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):
done = False
records = {}
page = 1
while not done:
kwargs['page'] = page
response = self.__cloudflare_request(
account=account,
path='/zones/{}/dns_records'.format(zoneID),
args=kwargs
)
info = response['result_info']
# Check if we have received all records, and if not iterate over the result set
if 'total_pages' not in info or page >= info['total_pages']:
done = True
else:
page += 1
for record in response['result']:
if record['name'] in records:
records[record['name']]['value'] = sorted(records[record['name']]['value'] + [record['content']])
else:
records[record['name']] = {
'name': record['name'],
'value': sorted([record['content']]),
'type': record['type']
}
return list(records.values()) | [
"def",
"__cloudflare_list_zone_records",
"(",
"self",
",",
"*",
",",
"account",
",",
"zoneID",
",",
"*",
"*",
"kwargs",
")",
":",
"done",
"=",
"False",
"records",
"=",
"{",
"}",
"page",
"=",
"1",
"while",
"not",
"done",
":",
"kwargs",
"[",
"'page'",
... | Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and
their information.
Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
zoneID (`int`): Internal CloudFlare ID of the DNS zone
**kwargs (`dict`): Additional arguments to be consumed by the API endpoint
Returns:
:obj:`dict` of `str`: `dict` | [
"Helper",
"function",
"to",
"list",
"all",
"records",
"on",
"a",
"CloudFlare",
"DNS",
"Zone",
".",
"Returns",
"a",
"dict",
"containing",
"the",
"records",
"and",
"their",
"information",
"."
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L293-L334 |
232,099 | RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py | CloudTrailAuditor.run | def run(self, *args, **kwargs):
"""Entry point for the scheduler
Args:
*args: Optional arguments
**kwargs: Optional keyword arguments
Returns:
None
"""
accounts = list(AWSAccount.get_all(include_disabled=False).values())
# S3 Bucket config
s3_acl = get_template('cloudtrail_s3_bucket_policy.json')
s3_bucket_name = self.dbconfig.get('bucket_name', self.ns)
s3_bucket_region = self.dbconfig.get('bucket_region', self.ns, 'us-west-2')
s3_bucket_account = AWSAccount.get(self.dbconfig.get('bucket_account', self.ns))
CloudTrail.create_s3_bucket(s3_bucket_name, s3_bucket_region, s3_bucket_account, s3_acl)
self.validate_sqs_policy(accounts)
for account in accounts:
ct = CloudTrail(account, s3_bucket_name, s3_bucket_region, self.log)
ct.run() | python | def run(self, *args, **kwargs):
accounts = list(AWSAccount.get_all(include_disabled=False).values())
# S3 Bucket config
s3_acl = get_template('cloudtrail_s3_bucket_policy.json')
s3_bucket_name = self.dbconfig.get('bucket_name', self.ns)
s3_bucket_region = self.dbconfig.get('bucket_region', self.ns, 'us-west-2')
s3_bucket_account = AWSAccount.get(self.dbconfig.get('bucket_account', self.ns))
CloudTrail.create_s3_bucket(s3_bucket_name, s3_bucket_region, s3_bucket_account, s3_acl)
self.validate_sqs_policy(accounts)
for account in accounts:
ct = CloudTrail(account, s3_bucket_name, s3_bucket_region, self.log)
ct.run() | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"accounts",
"=",
"list",
"(",
"AWSAccount",
".",
"get_all",
"(",
"include_disabled",
"=",
"False",
")",
".",
"values",
"(",
")",
")",
"# S3 Bucket config",
"s3_acl",
"=",
... | Entry point for the scheduler
Args:
*args: Optional arguments
**kwargs: Optional keyword arguments
Returns:
None | [
"Entry",
"point",
"for",
"the",
"scheduler"
] | 181dc2566ca59fc855f695b7fcc2c3b934e6ee9f | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L50-L73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.