_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q274500 | Users.update_user_login | test | def update_user_login(self, login, account_id=None):
"""
Update an existing login for a user in the given account.
https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.update
"""
if account_id is None:
account_id = self._canvas_account_id
if account_id is None:
raise MissingAccountID
login_id = login.login_id
url = ACCOUNTS_API.format(account_id) + "/logins/{}".format(login_id)
data = self._put_resource(url, login.put_data())
return Login(data=data) | python | {
"resource": ""
} |
q274501 | Canvas._next_page | test | def _next_page(self, response):
"""
return url path to next page of paginated data
"""
for link in response.getheader("link", "").split(","):
try:
(url, rel) = link.split(";")
if "next" in rel:
return url.lstrip("<").rstrip(">")
except Exception:
return | python | {
"resource": ""
} |
q274502 | Canvas._get_resource_url | test | def _get_resource_url(self, url, auto_page, data_key):
"""
Canvas GET method on a full url. Return representation of the
requested resource, chasing pagination links to coalesce resources
if indicated.
"""
headers = {'Accept': 'application/json',
'Connection': 'keep-alive'}
response = DAO.getURL(url, headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
data = json.loads(response.data)
self.next_page_url = self._next_page(response)
if auto_page and self.next_page_url:
if isinstance(data, list):
data.extend(self._get_resource_url(self.next_page_url, True,
data_key))
elif isinstance(data, dict) and data_key is not None:
data[data_key].extend(self._get_resource_url(
self.next_page_url, True, data_key)[data_key])
return data | python | {
"resource": ""
} |
q274503 | Canvas._get_paged_resource | test | def _get_paged_resource(self, url, params=None, data_key=None):
"""
Canvas GET method. Return representation of the requested paged
resource, either the requested page, or chase pagination links to
coalesce resources.
"""
if not params:
params = {}
self._set_as_user(params)
auto_page = not ('page' in params or 'per_page' in params)
if 'per_page' not in params and self._per_page != DEFAULT_PAGINATION:
params["per_page"] = self._per_page
full_url = url + self._params(params)
return self._get_resource_url(full_url, auto_page, data_key) | python | {
"resource": ""
} |
q274504 | Canvas._get_resource | test | def _get_resource(self, url, params=None, data_key=None):
"""
Canvas GET method. Return representation of the requested resource.
"""
if not params:
params = {}
self._set_as_user(params)
full_url = url + self._params(params)
return self._get_resource_url(full_url, True, data_key) | python | {
"resource": ""
} |
q274505 | Canvas._put_resource | test | def _put_resource(self, url, body):
"""
Canvas PUT method.
"""
params = {}
self._set_as_user(params)
headers = {'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive'}
url = url + self._params(params)
response = DAO.putURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q274506 | Canvas._post_resource | test | def _post_resource(self, url, body):
"""
Canvas POST method.
"""
params = {}
self._set_as_user(params)
headers = {'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive'}
url = url + self._params(params)
response = DAO.postURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q274507 | Canvas._delete_resource | test | def _delete_resource(self, url):
"""
Canvas DELETE method.
"""
params = {}
self._set_as_user(params)
headers = {'Accept': 'application/json',
'Connection': 'keep-alive'}
url = url + self._params(params)
response = DAO.deleteURL(url, headers)
if not (response.status == 200 or response.status == 204):
raise DataFailureException(url, response.status, response.data)
return response | python | {
"resource": ""
} |
q274508 | Admins.get_admins | test | def get_admins(self, account_id, params={}):
"""
Return a list of the admins in the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.index
"""
url = ADMINS_API.format(account_id)
admins = []
for data in self._get_paged_resource(url, params=params):
admins.append(CanvasAdmin(data=data))
return admins | python | {
"resource": ""
} |
q274509 | Admins.create_admin | test | def create_admin(self, account_id, user_id, role):
"""
Flag an existing user as an admin within the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.create
"""
url = ADMINS_API.format(account_id)
body = {"user_id": unquote(str(user_id)),
"role": role,
"send_confirmation": False}
return CanvasAdmin(data=self._post_resource(url, body)) | python | {
"resource": ""
} |
q274510 | Admins.create_admin_by_sis_id | test | def create_admin_by_sis_id(self, sis_account_id, user_id, role):
"""
Flag an existing user as an admin within the account sis id.
"""
return self.create_admin(self._sis_id(sis_account_id), user_id, role) | python | {
"resource": ""
} |
q274511 | Admins.delete_admin | test | def delete_admin(self, account_id, user_id, role):
"""
Remove an account admin role from a user.
https://canvas.instructure.com/doc/api/admins.html#method.admins.destroy
"""
url = ADMINS_API.format(account_id) + "/{}?role={}".format(
user_id, quote(role))
response = self._delete_resource(url)
return True | python | {
"resource": ""
} |
q274512 | Admins.delete_admin_by_sis_id | test | def delete_admin_by_sis_id(self, sis_account_id, user_id, role):
"""
Remove an account admin role from a user for the account sis id.
"""
return self.delete_admin(self._sis_id(sis_account_id), user_id, role) | python | {
"resource": ""
} |
q274513 | GradingStandards.create_grading_standard_for_course | test | def create_grading_standard_for_course(self, course_id, name,
grading_scheme, creator):
"""
Create a new grading standard for the passed course.
https://canvas.instructure.com/doc/api/grading_standards.html#method.grading_standards_api.create
"""
url = COURSES_API.format(course_id) + "/grading_standards"
body = {
"title": name,
"grading_scheme_entry": grading_scheme,
"as_user_id": creator
}
return GradingStandard(data=self._post_resource(url, body)) | python | {
"resource": ""
} |
q274514 | Sections.get_section | test | def get_section(self, section_id, params={}):
"""
Return section resource for given canvas section id.
https://canvas.instructure.com/doc/api/sections.html#method.sections.show
"""
url = SECTIONS_API.format(section_id)
return CanvasSection(data=self._get_resource(url, params=params)) | python | {
"resource": ""
} |
q274515 | Sections.get_section_by_sis_id | test | def get_section_by_sis_id(self, sis_section_id, params={}):
"""
Return section resource for given sis id.
"""
return self.get_section(
self._sis_id(sis_section_id, sis_field="section"), params) | python | {
"resource": ""
} |
q274516 | Sections.get_sections_in_course | test | def get_sections_in_course(self, course_id, params={}):
"""
Return list of sections for the passed course ID.
https://canvas.instructure.com/doc/api/sections.html#method.sections.index
"""
url = COURSES_API.format(course_id) + "/sections"
sections = []
for data in self._get_paged_resource(url, params=params):
sections.append(CanvasSection(data=data))
return sections | python | {
"resource": ""
} |
q274517 | Sections.get_sections_in_course_by_sis_id | test | def get_sections_in_course_by_sis_id(self, sis_course_id, params={}):
"""
Return list of sections for the passed course SIS ID.
"""
return self.get_sections_in_course(
self._sis_id(sis_course_id, sis_field="course"), params) | python | {
"resource": ""
} |
q274518 | Sections.get_sections_with_students_in_course | test | def get_sections_with_students_in_course(self, course_id, params={}):
"""
Return list of sections including students for the passed course ID.
"""
include = params.get("include", [])
if "students" not in include:
include.append("students")
params["include"] = include
return self.get_sections_in_course(course_id, params) | python | {
"resource": ""
} |
q274519 | Sections.get_sections_with_students_in_course_by_sis_id | test | def get_sections_with_students_in_course_by_sis_id(self, sis_course_id,
params={}):
"""
Return list of sections including students for the passed sis ID.
"""
return self.get_sections_with_students_in_course(
self._sis_id(sis_course_id, sis_field="course"), params) | python | {
"resource": ""
} |
q274520 | Sections.create_section | test | def create_section(self, course_id, name, sis_section_id):
"""
Create a canvas section in the given course id.
https://canvas.instructure.com/doc/api/sections.html#method.sections.create
"""
url = COURSES_API.format(course_id) + "/sections"
body = {"course_section": {"name": name,
"sis_section_id": sis_section_id}}
return CanvasSection(data=self._post_resource(url, body)) | python | {
"resource": ""
} |
q274521 | Sections.update_section | test | def update_section(self, section_id, name, sis_section_id):
"""
Update a canvas section with the given section id.
https://canvas.instructure.com/doc/api/sections.html#method.sections.update
"""
url = SECTIONS_API.format(section_id)
body = {"course_section": {}}
if name:
body["course_section"]["name"] = name
if sis_section_id:
body["course_section"]["sis_section_id"] = sis_section_id
return CanvasSection(data=self._put_resource(url, body)) | python | {
"resource": ""
} |
q274522 | Quizzes.get_quizzes | test | def get_quizzes(self, course_id):
"""
List quizzes for a given course
https://canvas.instructure.com/doc/api/quizzes.html#method.quizzes_api.index
"""
url = QUIZZES_API.format(course_id)
data = self._get_resource(url)
quizzes = []
for datum in data:
quizzes.append(Quiz(data=datum))
return quizzes | python | {
"resource": ""
} |
q274523 | Accounts.get_account | test | def get_account(self, account_id):
"""
Return account resource for given canvas account id.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.show
"""
url = ACCOUNTS_API.format(account_id)
return CanvasAccount(data=self._get_resource(url)) | python | {
"resource": ""
} |
q274524 | Accounts.get_sub_accounts | test | def get_sub_accounts(self, account_id, params={}):
"""
Return list of subaccounts within the account with the passed
canvas id.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.sub_accounts
"""
url = ACCOUNTS_API.format(account_id) + "/sub_accounts"
accounts = []
for datum in self._get_paged_resource(url, params=params):
accounts.append(CanvasAccount(data=datum))
return accounts | python | {
"resource": ""
} |
q274525 | Accounts.update_account | test | def update_account(self, account):
"""
Update the passed account. Returns the updated account.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update
"""
url = ACCOUNTS_API.format(account.account_id)
body = {"account": {"name": account.name}}
return CanvasAccount(data=self._put_resource(url, body)) | python | {
"resource": ""
} |
q274526 | Accounts.update_sis_id | test | def update_sis_id(self, account_id, sis_account_id):
"""
Updates the SIS ID for the account identified by the passed account ID.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update
"""
if account_id == self._canvas_account_id:
raise Exception("SIS ID cannot be updated for the root account")
url = ACCOUNTS_API.format(account_id)
body = {"account": {"sis_account_id": sis_account_id}}
return CanvasAccount(data=self._put_resource(url, body)) | python | {
"resource": ""
} |
q274527 | Accounts.get_auth_settings | test | def get_auth_settings(self, account_id):
"""
Return the authentication settings for the passed account_id.
https://canvas.instructure.com/doc/api/authentication_providers.html#method.account_authorization_configs.show_sso_settings
"""
url = ACCOUNTS_API.format(account_id) + "/sso_settings"
return CanvasSSOSettings(data=self._get_resource(url)) | python | {
"resource": ""
} |
q274528 | Accounts.update_auth_settings | test | def update_auth_settings(self, account_id, auth_settings):
"""
Update the authentication settings for the passed account_id.
https://canvas.instructure.com/doc/api/authentication_providers.html#method.account_authorization_configs.update_sso_settings
"""
url = ACCOUNTS_API.format(account_id) + "/sso_settings"
data = self._put_resource(url, auth_settings.json_data())
return CanvasSSOSettings(data=data) | python | {
"resource": ""
} |
q274529 | Terms.get_term_by_sis_id | test | def get_term_by_sis_id(self, sis_term_id):
"""
Return a term resource for the passed SIS ID.
"""
for term in self.get_all_terms():
if term.sis_term_id == sis_term_id:
return term | python | {
"resource": ""
} |
q274530 | SISImport.import_str | test | def import_str(self, csv, params={}):
"""
Imports a CSV string.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create
"""
if not self._canvas_account_id:
raise MissingAccountID()
params["import_type"] = SISImportModel.CSV_IMPORT_TYPE
url = SIS_IMPORTS_API.format(
self._canvas_account_id) + ".json{}".format(self._params(params))
headers = {"Content-Type": "text/csv"}
return SISImportModel(data=self._post_resource(url, headers, csv)) | python | {
"resource": ""
} |
q274531 | SISImport.import_dir | test | def import_dir(self, dir_path, params={}):
"""
Imports a directory of CSV files.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create
"""
if not self._canvas_account_id:
raise MissingAccountID()
body = self._build_archive(dir_path)
params["import_type"] = SISImportModel.CSV_IMPORT_TYPE
url = SIS_IMPORTS_API.format(
self._canvas_account_id) + ".json{}".format(self._params(params))
headers = {"Content-Type": "application/zip"}
return SISImportModel(data=self._post_resource(url, headers, body)) | python | {
"resource": ""
} |
q274532 | SISImport.get_import_status | test | def get_import_status(self, sis_import):
"""
Get the status of an already created SIS import.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.show
"""
if not self._canvas_account_id:
raise MissingAccountID()
url = SIS_IMPORTS_API.format(
self._canvas_account_id) + "/{}.json".format(sis_import.import_id)
return SISImportModel(data=self._get_resource(url)) | python | {
"resource": ""
} |
q274533 | SISImport._build_archive | test | def _build_archive(self, dir_path):
"""
Creates a zip archive from files in path.
"""
zip_path = os.path.join(dir_path, "import.zip")
archive = zipfile.ZipFile(zip_path, "w")
for filename in CSV_FILES:
filepath = os.path.join(dir_path, filename)
if os.path.exists(filepath):
archive.write(filepath, filename, zipfile.ZIP_DEFLATED)
archive.close()
with open(zip_path, "rb") as f:
body = f.read()
return body | python | {
"resource": ""
} |
q274534 | Assignments.get_assignments | test | def get_assignments(self, course_id):
"""
List assignments for a given course
https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.index
"""
url = ASSIGNMENTS_API.format(course_id)
data = self._get_resource(url)
assignments = []
for datum in data:
assignments.append(Assignment(data=datum))
return assignments | python | {
"resource": ""
} |
q274535 | Assignments.update_assignment | test | def update_assignment(self, assignment):
"""
Modify an existing assignment.
https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update
"""
url = ASSIGNMENTS_API.format(assignment.course_id) + "/{}".format(
assignment.assignment_id)
data = self._put_resource(url, assignment.json_data())
return Assignment(data=data) | python | {
"resource": ""
} |
q274536 | Reports.get_available_reports | test | def get_available_reports(self, account_id):
"""
Returns the list of reports for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.available_reports
"""
url = ACCOUNTS_API.format(account_id) + "/reports"
report_types = []
for datum in self._get_resource(url):
report_types.append(ReportType(data=datum, account_id=account_id))
return report_types | python | {
"resource": ""
} |
q274537 | Reports.get_reports_by_type | test | def get_reports_by_type(self, account_id, report_type):
"""
Shows all reports of the passed report_type that have been run
for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.index
"""
url = ACCOUNTS_API.format(account_id) + "/reports/{}".format(
report_type)
reports = []
for datum in self._get_resource(url):
datum["account_id"] = account_id
reports.append(Report(data=datum))
return reports | python | {
"resource": ""
} |
q274538 | Reports.create_report | test | def create_report(self, report_type, account_id, term_id=None, params={}):
"""
Generates a report instance for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.create
"""
if term_id is not None:
params["enrollment_term_id"] = term_id
url = ACCOUNTS_API.format(account_id) + "/reports/{}".format(
report_type)
body = {"parameters": params}
data = self._post_resource(url, body)
data["account_id"] = account_id
return Report(data=data) | python | {
"resource": ""
} |
q274539 | Reports.create_course_provisioning_report | test | def create_course_provisioning_report(self, account_id, term_id=None,
params={}):
"""
Convenience method for create_report, for creating a course
provisioning report.
"""
params["courses"] = True
return self.create_report(ReportType.PROVISIONING, account_id, term_id,
params) | python | {
"resource": ""
} |
q274540 | Reports.create_course_sis_export_report | test | def create_course_sis_export_report(self, account_id, term_id=None,
params={}):
"""
Convenience method for create_report, for creating a course sis export
report.
"""
params["courses"] = True
return self.create_report(ReportType.SIS_EXPORT, account_id, term_id,
params) | python | {
"resource": ""
} |
q274541 | Reports.create_unused_courses_report | test | def create_unused_courses_report(self, account_id, term_id=None):
"""
Convenience method for create_report, for creating an unused courses
report.
"""
return self.create_report(ReportType.UNUSED_COURSES, account_id,
term_id) | python | {
"resource": ""
} |
q274542 | Reports.get_report_data | test | def get_report_data(self, report):
"""
Returns a completed report as a list of csv strings.
"""
if report.report_id is None or report.status is None:
raise ReportFailureException(report)
interval = getattr(settings, 'CANVAS_REPORT_POLLING_INTERVAL', 5)
while report.status != "complete":
if report.status == "error":
raise ReportFailureException(report)
sleep(interval)
report = self.get_report_status(report)
if report.attachment is None or report.attachment.url is None:
return
data = self._get_report_file(report.attachment.url)
return data.split("\n") | python | {
"resource": ""
} |
q274543 | Reports.get_report_status | test | def get_report_status(self, report):
"""
Returns the status of a report.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show
"""
if (report.account_id is None or report.type is None or
report.report_id is None):
raise ReportFailureException(report)
url = ACCOUNTS_API.format(report.account_id) + "/reports/{}/{}".format(
report.type, report.report_id)
data = self._get_resource(url)
data["account_id"] = report.account_id
return Report(data=data) | python | {
"resource": ""
} |
q274544 | Reports.delete_report | test | def delete_report(self, report):
"""
Deletes a generated report instance.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.destroy
"""
url = ACCOUNTS_API.format(report.account_id) + "/reports/{}/{}".format(
report.type, report.report_id)
response = self._delete_resource(url)
return True | python | {
"resource": ""
} |
q274545 | move_detections | test | def move_detections(label, dy, dx):
"""
Move detections in direction dx, dy.
:param label: The label dict containing all detection lists.
:param dy: The delta in y direction as a number.
:param dx: The delta in x direction as a number.
:return:
"""
for k in label.keys():
if k.startswith("detection"):
detections = label[k]
for detection in detections:
detection.move_image(-dx, -dy) | python | {
"resource": ""
} |
q274546 | hflip_detections | test | def hflip_detections(label, w):
"""
Horizontally flip detections according to an image flip.
:param label: The label dict containing all detection lists.
:param w: The width of the image as a number.
:return:
"""
for k in label.keys():
if k.startswith("detection"):
detections = label[k]
for detection in detections:
detection.cx = w - detection.cx
if k == "detections_2.5d":
detection.theta = math.pi - detection.theta | python | {
"resource": ""
} |
q274547 | get_dict_from_obj | test | def get_dict_from_obj(obj):
'''
Edit to get the dict even when the object is a GenericRelatedObjectManager.
Added the try except.
'''
obj_dict = obj.__dict__
obj_dict_result = obj_dict.copy()
for key, value in obj_dict.items():
if key.endswith('_id'):
key2 = key.replace('_id', '')
try:
field, model, direct, m2m = obj._meta.get_field_by_name(key2)
if isinstance(field, ForeignKey):
obj_dict_result[key2] = obj_dict_result[key]
del obj_dict_result[key]
except FieldDoesNotExist:
pass
manytomany_list = obj._meta.many_to_many
for manytomany in manytomany_list:
pks = [obj_rel.pk for obj_rel in manytomany.value_from_object(obj).select_related()]
if pks:
obj_dict_result[manytomany.name] = pks
return obj_dict_result | python | {
"resource": ""
} |
q274548 | BaseAdaptorField.get_config | test | def get_config(self, request, **kwargs):
"""
Get the arguments given to the template tag element and complete these
with the ones from the settings.py if necessary.
"""
config = kwargs
config_from_settings = deepcopy(inplace_settings.DEFAULT_INPLACE_EDIT_OPTIONS)
config_one_by_one = inplace_settings.DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE
if not config_one_by_one:
# Solution 1: Using default config only if none specified.
if not config and config_from_settings:
config = config_from_settings
else:
# Solution 2: Updating the configured config with the default one.
config = dict(config_from_settings, **config)
return config | python | {
"resource": ""
} |
q274549 | BaseAdaptorField.empty_value | test | def empty_value(self):
'''
Get the text to display when the field is empty.
'''
edit_empty_value = self.config.get('edit_empty_value', False)
if edit_empty_value:
return edit_empty_value
else:
return unicode(inplace_settings.INPLACEEDIT_EDIT_EMPTY_VALUE) | python | {
"resource": ""
} |
q274550 | parse_args_kwargs | test | def parse_args_kwargs(parser, token):
"""
Parse uniformly args and kwargs from a templatetag
Usage::
For parsing a template like this:
{% footag my_contents,height=10,zoom=20 as myvar %}
You simply do this:
@register.tag
def footag(parser, token):
args, kwargs = parse_args_kwargs(parser, token)
"""
bits = token.contents.split(' ')
if len(bits) <= 1:
raise template.TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
if token.contents[13] == '"':
end_quote = token.contents.index('"', 14) + 1
args = [template.Variable(token.contents[13:end_quote])]
kwargs_start = end_quote
else:
try:
next_space = token.contents.index(' ', 14)
kwargs_start = next_space + 1
except ValueError:
next_space = None
kwargs_start = None
args = [template.Variable(token.contents[13:next_space])]
kwargs = {}
kwargs_list = token.contents[kwargs_start:].split(',')
for kwargs_item in kwargs_list:
if '=' in kwargs_item:
k, v = kwargs_item.split('=', 1)
k = k.strip()
kwargs[k] = template.Variable(v)
return args, kwargs | python | {
"resource": ""
} |
q274551 | PrometheusExporterScript.create_metrics | test | def create_metrics(
self, metric_configs: Iterable[MetricConfig]) -> Dict[str, Metric]:
"""Create and register metrics from a list of MetricConfigs."""
return self.registry.create_metrics(metric_configs) | python | {
"resource": ""
} |
q274552 | PrometheusExporterScript._setup_logging | test | def _setup_logging(self, log_level: str):
"""Setup logging for the application and aiohttp."""
level = getattr(logging, log_level)
names = (
'aiohttp.access', 'aiohttp.internal', 'aiohttp.server',
'aiohttp.web', self.name)
for name in names:
setup_logger(name=name, stream=sys.stderr, level=level) | python | {
"resource": ""
} |
q274553 | PrometheusExporterScript._configure_registry | test | def _configure_registry(self, include_process_stats: bool = False):
"""Configure the MetricRegistry."""
if include_process_stats:
self.registry.register_additional_collector(
ProcessCollector(registry=None)) | python | {
"resource": ""
} |
q274554 | MetricsRegistry.create_metrics | test | def create_metrics(self,
configs: Iterable[MetricConfig]) -> Dict[str, Metric]:
"""Create Prometheus metrics from a list of MetricConfigs."""
metrics: Dict[str, Metric] = {
config.name: self._register_metric(config)
for config in configs
}
self._metrics.update(metrics)
return metrics | python | {
"resource": ""
} |
q274555 | MetricsRegistry.get_metric | test | def get_metric(
self, name: str,
labels: Union[Dict[str, str], None] = None) -> Metric:
"""Return a metric, optionally configured with labels."""
metric = self._metrics[name]
if labels:
return metric.labels(**labels)
return metric | python | {
"resource": ""
} |
q274556 | PrometheusExporter._handle_home | test | async def _handle_home(self, request: Request) -> Response:
"""Home page request handler."""
if self.description:
title = f'{self.name} - {self.description}'
else:
title = self.name
text = dedent(
f'''<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<p>
Metric are exported at the
<a href="/metrics">/metrics</a> endpoint.
</p>
</body>
</html>
''')
return Response(content_type='text/html', text=text) | python | {
"resource": ""
} |
q274557 | PrometheusExporter._handle_metrics | test | async def _handle_metrics(self, request: Request) -> Response:
"""Handler for metrics."""
if self._update_handler:
await self._update_handler(self.registry.get_metrics())
response = Response(body=self.registry.generate_metrics())
response.content_type = CONTENT_TYPE_LATEST
return response | python | {
"resource": ""
} |
q274558 | wa | test | def wa(client, event, channel, nick, rest):
"""
A free-text query resolver by Wolfram|Alpha. Returns the first
result, if available.
"""
client = wolframalpha.Client(pmxbot.config['Wolfram|Alpha API key'])
res = client.query(rest)
return next(res.results).text | python | {
"resource": ""
} |
q274559 | fix_HTTPMessage | test | def fix_HTTPMessage():
"""
Python 2 uses a deprecated method signature and doesn't provide the
forward compatibility.
Add it.
"""
if six.PY3:
return
http_client.HTTPMessage.get_content_type = http_client.HTTPMessage.gettype
http_client.HTTPMessage.get_param = http_client.HTTPMessage.getparam | python | {
"resource": ""
} |
q274560 | Client.query | test | def query(self, input, params=(), **kwargs):
"""
Query Wolfram|Alpha using the v2.0 API
Allows for arbitrary parameters to be passed in
the query. For example, to pass assumptions:
client.query(input='pi', assumption='*C.pi-_*NamedConstant-')
To pass multiple assumptions, pass multiple items
as params:
params = (
('assumption', '*C.pi-_*NamedConstant-'),
('assumption', 'DateOrder_**Day.Month.Year--'),
)
client.query(input='pi', params=params)
For more details on Assumptions, see
https://products.wolframalpha.com/api/documentation.html#6
"""
data = dict(
input=input,
appid=self.app_id,
)
data = itertools.chain(params, data.items(), kwargs.items())
query = urllib.parse.urlencode(tuple(data))
url = 'https://api.wolframalpha.com/v2/query?' + query
resp = urllib.request.urlopen(url)
assert resp.headers.get_content_type() == 'text/xml'
assert resp.headers.get_param('charset') == 'utf-8'
return Result(resp) | python | {
"resource": ""
} |
q274561 | Result.info | test | def info(self):
"""
The pods, assumptions, and warnings of this result.
"""
return itertools.chain(self.pods, self.assumptions, self.warnings) | python | {
"resource": ""
} |
q274562 | Result.results | test | def results(self):
"""
The pods that hold the response to a simple, discrete query.
"""
return (
pod
for pod in self.pods
if pod.primary
or pod.title == 'Result'
) | python | {
"resource": ""
} |
q274563 | ApiClient.encode | test | def encode(request, data):
""" Add request content data to request body, set Content-type header.
Should be overridden by subclasses if not using JSON encoding.
Args:
request (HTTPRequest): The request object.
data (dict, None): Data to be encoded.
Returns:
HTTPRequest: The request object.
"""
if data is None:
return request
request.add_header('Content-Type', 'application/json')
request.data = json.dumps(data)
return request | python | {
"resource": ""
} |
q274564 | ApiClient.call_api | test | def call_api(
self,
method,
url,
headers=None,
params=None,
data=None,
files=None,
timeout=None,
):
""" Call API.
This returns object containing data, with error details if applicable.
Args:
method (str): The HTTP method to use.
url (str): Resource location relative to the base URL.
headers (dict or None): Extra request headers to set.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents for POST or PUT requests.
files (dict or None: Files to be passed to the request.
timeout (int): Maximum time before timing out.
Returns:
ResultParser or ErrorParser.
"""
method = method.upper()
headers = deepcopy(headers) or {}
headers['Accept'] = self.accept_type
params = deepcopy(params) or {}
data = data or {}
files = files or {}
if self.username and self.api_key:
params.update(self.get_credentials())
url = urljoin(self.base_url, url)
r = requests.request(
method,
url,
headers=headers,
params=params,
files=files,
data=data,
timeout=timeout,
)
return r, r.status_code | python | {
"resource": ""
} |
q274565 | ApiClient.get | test | def get(self, url, params=None, **kwargs):
""" Call the API with a GET request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser.
"""
return self.call_api(
"GET",
url,
params=params,
**kwargs
) | python | {
"resource": ""
} |
q274566 | ApiClient.delete | test | def delete(self, url, params=None, **kwargs):
""" Call the API with a DELETE request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser.
"""
return self.call_api(
"DELETE",
url,
params=params,
**kwargs
) | python | {
"resource": ""
} |
q274567 | ApiClient.put | test | def put(self, url, params=None, data=None, files=None, **kwargs):
""" Call the API with a PUT request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents.
files (dict or None: Files to be passed to the request.
Returns:
An instance of ResultParser or ErrorParser.
"""
return self.call_api(
"PUT",
url,
params=params,
data=data,
files=files,
**kwargs
) | python | {
"resource": ""
} |
q274568 | ApiClient.post | test | def post(self, url, params=None, data=None, files=None, **kwargs):
""" Call the API with a POST request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents.
files (dict or None: Files to be passed to the request.
Returns:
An instance of ResultParser or ErrorParser.
"""
return self.call_api(
"POST",
url,
params=params,
data=data,
files=files,
**kwargs
) | python | {
"resource": ""
} |
q274569 | NerdClient._process_query | test | def _process_query(self, query, prepared=False):
""" Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST request.
Returns:
str: Body ready to be submitted to the API.
"""
# Exit condition and POST
if prepared is True:
files = {'query': str(query)}
logger.debug('About to submit the following query {}'.format(query))
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status == 200:
return self.decode(res), status
else:
logger.debug('Disambiguation failed.')
return None, status
text = query['text']
sentence_coordinates = [
{
"offsetStart": 0,
"offsetEnd": len(text)
}
]
total_nb_sentences = len(sentence_coordinates) # Sentences from text.
sentences_groups = []
if len(text) > self.max_text_length:
res, status_code = self.segment(text)
if status_code == 200:
sentence_coordinates = res['sentences']
total_nb_sentences = len(sentence_coordinates)
else:
logger.error('Error during the segmentation of the text.')
logger.debug(
'Text too long, split in {} sentences; building groups of {} '
'sentences.'.format(
total_nb_sentences, self.sentences_per_group
)
)
sentences_groups = self._group_sentences(
total_nb_sentences,
self.sentences_per_group
)
else:
query['sentence'] = "true"
if total_nb_sentences > 1:
query['sentences'] = sentence_coordinates
if len(sentences_groups) > 0:
for group in sentences_groups:
query['processSentence'] = group
res, status_code = self._process_query(query, prepared=True)
if status_code == 200:
if 'entities' in res:
query['entities'] = res[u'entities']
query['language'] = res[u'language']
else:
logger.error(
"Error when processing the query {}".format(query)
)
return None, status_code
else:
res, status_code = self._process_query(query, prepared=True)
if status_code == 200:
query['language'] = res[u'language']
if 'entities' in res:
query['entities'] = res[u'entities']
else:
logger.error("Error when processing the query {}".format(query))
return None, status_code
return query, status_code | python | {
"resource": ""
} |
q274570 | NerdClient._group_sentences | test | def _group_sentences(total_nb_sentences, group_length):
""" Split sentences in groups, given a specific group length.
Args:
total_nb_sentences (int): Total available sentences.
group_length (int): Limit of length for each group.
Returns:
list: Contains groups (lists) of sentences.
"""
sentences_groups = []
current_sentence_group = []
for i in range(0, total_nb_sentences):
if i % group_length == 0:
if len(current_sentence_group) > 0:
sentences_groups.append(current_sentence_group)
current_sentence_group = [i]
else:
current_sentence_group.append(i)
if len(current_sentence_group) > 0:
sentences_groups.append(current_sentence_group)
return sentences_groups | python | {
"resource": ""
} |
q274571 | NerdClient.disambiguate_pdf | test | def disambiguate_pdf(self, file, language=None, entities=None):
""" Call the disambiguation service in order to process a pdf file .
Args:
pdf (file): PDF file to be disambiguated.
language (str): language of text (if known)
Returns:
dict, int: API response and API status.
"""
body = {
"customisation": "generic"
}
if language:
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
files = {
'query': str(body),
'file': (
file,
open(file, 'rb'),
'application/pdf',
{'Expires': '0'}
)
}
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status != 200:
logger.debug('Disambiguation failed with error ' + str(status))
return self.decode(res), status | python | {
"resource": ""
} |
q274572 | NerdClient.disambiguate_query | test | def disambiguate_query(self, query, language=None, entities=None):
""" Call the disambiguation service in order to disambiguate a search query.
Args:
text (str): Query to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be supplied by
the user.
Returns:
dict, int: API response and API status.
"""
body = {
"shortText": query,
"entities": [],
"onlyNER": "false",
"customisation": "generic"
}
if language:
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
files = {'query': str(body)}
logger.debug('About to submit the following query {}'.format(body))
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status == 200:
return self.decode(res), status
else:
logger.debug('Disambiguation failed.')
return None, status | python | {
"resource": ""
} |
q274573 | NerdClient.segment | test | def segment(self, text):
""" Call the segmenter in order to split text in sentences.
Args:
text (str): Text to be segmented.
Returns:
dict, int: A dict containing a list of dicts with the offsets of
each sentence; an integer representing the response code.
"""
files = {'text': text}
res, status_code = self.post(self.segmentation_service, files=files)
if status_code != 200:
logger.debug('Segmentation failed.')
return self.decode(res), status_code | python | {
"resource": ""
} |
q274574 | NerdClient.get_language | test | def get_language(self, text):
""" Recognise the language of the text in input
Args:
id (str): The text whose the language needs to be recognised
Returns:
dict, int: A dict containing the recognised language and the
confidence score.
"""
files = {'text': text}
res, status_code = self.post(self.language_service, files=files)
if status_code != 200:
logger.debug('Language recognition failed.')
return self.decode(res), status_code | python | {
"resource": ""
} |
q274575 | NerdClient.get_concept | test | def get_concept(self, conceptId, lang='en'):
""" Fetch the concept from the Knowledge base
Args:
id (str): The concept id to be fetched, it can be Wikipedia
page id or Wikiedata id.
Returns:
dict, int: A dict containing the concept information; an integer
representing the response code.
"""
url = urljoin(self.concept_service + '/', conceptId)
res, status_code = self.get(url, params={'lang': lang})
if status_code != 200:
logger.debug('Fetch concept failed.')
return self.decode(res), status_code | python | {
"resource": ""
} |
q274576 | MDREnsemble.fit | test | def fit(self, features, classes):
"""Constructs the MDR ensemble from the provided training data
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
classes: array-like {n_samples}
List of class labels for prediction
Returns
-------
None
"""
self.ensemble.fit(features, classes)
# Construct the feature map from the ensemble predictions
unique_rows = list(set([tuple(row) for row in features]))
for row in unique_rows:
self.feature_map[row] = self.ensemble.predict([row])[0] | python | {
"resource": ""
} |
q274577 | MDREnsemble.score | test | def score(self, features, classes, scoring_function=None, **scoring_function_kwargs):
"""Estimates the accuracy of the predictions from the MDR ensemble
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix to predict from
classes: array-like {n_samples}
List of true class labels
Returns
-------
accuracy_score: float
The estimated accuracy based on the constructed feature
"""
new_feature = self.ensemble.predict(features)
if scoring_function is None:
return accuracy_score(classes, new_feature)
else:
return scoring_function(classes, new_feature, **scoring_function_kwargs) | python | {
"resource": ""
} |
q274578 | MDRBase.fit | test | def fit(self, features, class_labels):
"""Constructs the MDR feature map from the provided training data.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {n_samples}
List of true class labels
Returns
-------
self: A copy of the fitted model
"""
unique_labels = sorted(np.unique(class_labels))
if len(unique_labels) != 2:
raise ValueError('MDR only supports binary endpoints.')
# Count the distribution of classes that fall into each MDR grid cell
self.class_count_matrix = defaultdict(lambda: defaultdict(int))
for row_i in range(features.shape[0]):
feature_instance = tuple(features[row_i])
self.class_count_matrix[feature_instance][class_labels[row_i]] += 1
self.class_count_matrix = dict(self.class_count_matrix)
# Only applies to binary classification
overall_class_fraction = float(sum(class_labels == unique_labels[0])) / class_labels.size
# If one class is more abundant in a MDR grid cell than it is overall, then assign the cell to that class
self.feature_map = {}
for feature_instance in self.class_count_matrix:
counts = self.class_count_matrix[feature_instance]
fraction = float(counts[unique_labels[0]]) / np.sum(list(counts.values()))
if fraction > overall_class_fraction:
self.feature_map[feature_instance] = unique_labels[0]
elif fraction == overall_class_fraction:
self.feature_map[feature_instance] = self.tie_break
else:
self.feature_map[feature_instance] = unique_labels[1]
return self | python | {
"resource": ""
} |
q274579 | MDRClassifier.fit_predict | test | def fit_predict(self, features, class_labels):
"""Convenience function that fits the provided data then constructs predictions from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {n_samples}
List of true class labels
Returns
----------
array-like: {n_samples}
Constructed features from the provided feature matrix
"""
self.fit(features, class_labels)
return self.predict(features) | python | {
"resource": ""
} |
q274580 | MDRClassifier.score | test | def score(self, features, class_labels, scoring_function=None, **scoring_function_kwargs):
"""Estimates the accuracy of the predictions from the constructed feature.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix to predict from
class_labels: array-like {n_samples}
List of true class labels
Returns
-------
accuracy_score: float
The estimated accuracy based on the constructed feature
"""
if self.feature_map is None:
raise ValueError('The MDR model must be fit before score can be called.')
new_feature = self.predict(features)
if scoring_function is None:
return accuracy_score(class_labels, new_feature)
else:
return scoring_function(class_labels, new_feature, **scoring_function_kwargs) | python | {
"resource": ""
} |
q274581 | ContinuousMDR.fit | test | def fit(self, features, targets):
"""Constructs the Continuous MDR feature map from the provided training data.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
targets: array-like {n_samples}
List of target values for prediction
Returns
-------
self: A copy of the fitted model
"""
self.feature_map = defaultdict(lambda: self.default_label)
self.overall_mean_trait_value = np.mean(targets)
self.mdr_matrix_values = defaultdict(list)
for row_i in range(features.shape[0]):
feature_instance = tuple(features[row_i])
self.mdr_matrix_values[feature_instance].append(targets[row_i])
for feature_instance in self.mdr_matrix_values:
grid_mean_trait_value = np.mean(self.mdr_matrix_values[feature_instance])
if grid_mean_trait_value > self.overall_mean_trait_value:
self.feature_map[feature_instance] = 1
elif grid_mean_trait_value == self.overall_mean_trait_value:
self.feature_map[feature_instance] = self.tie_break
else:
self.feature_map[feature_instance] = 0
# Convert defaultdict to dict so CMDR objects can be easily pickled
self.feature_map = dict(self.feature_map)
self.mdr_matrix_values = dict(self.mdr_matrix_values)
return self | python | {
"resource": ""
} |
q274582 | ContinuousMDR.transform | test | def transform(self, features):
"""Uses the Continuous MDR feature map to construct a new feature from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix to transform
Returns
----------
array-like: {n_samples}
Constructed feature from the provided feature matrix
The constructed feature will be a binary variable, taking the values 0 and 1
"""
new_feature = np.zeros(features.shape[0], dtype=np.int)
for row_i in range(features.shape[0]):
feature_instance = tuple(features[row_i])
if feature_instance in self.feature_map:
new_feature[row_i] = self.feature_map[feature_instance]
else:
new_feature[row_i] = self.default_label
return new_feature.reshape(features.shape[0], 1) | python | {
"resource": ""
} |
q274583 | ContinuousMDR.score | test | def score(self, features, targets):
"""Estimates the quality of the ContinuousMDR model using a t-statistic.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix to predict from
targets: array-like {n_samples}
List of true target values
Returns
-------
quality_score: float
The estimated quality of the Continuous MDR model
"""
if self.feature_map is None:
raise ValueError('The Continuous MDR model must be fit before score() can be called.')
group_0_trait_values = []
group_1_trait_values = []
for feature_instance in self.feature_map:
if self.feature_map[feature_instance] == 0:
group_0_trait_values.extend(self.mdr_matrix_values[feature_instance])
else:
group_1_trait_values.extend(self.mdr_matrix_values[feature_instance])
return abs(ttest_ind(group_0_trait_values, group_1_trait_values).statistic) | python | {
"resource": ""
} |
q274584 | _mdr_predict | test | def _mdr_predict(X, Y, labels):
"""Fits a MDR model to variables X and Y with the given labels, then returns the resulting predictions
This is a convenience method that should only be used internally.
Parameters
----------
X: array-like (# samples)
An array of values corresponding to one feature in the MDR model
Y: array-like (# samples)
An array of values corresponding to one feature in the MDR model
labels: array-like (# samples)
The class labels corresponding to features X and Y
Returns
----------
predictions: array-like (# samples)
The predictions from the fitted MDR model
"""
return MDR().fit_predict(np.column_stack((X, Y)), labels) | python | {
"resource": ""
} |
q274585 | n_way_models | test | def n_way_models(mdr_instance, X, y, n=[2], feature_names=None):
"""Fits a MDR model to all n-way combinations of the features in X.
Note that this function performs an exhaustive search through all feature combinations and can be computationally expensive.
Parameters
----------
mdr_instance: object
An instance of the MDR type to use.
X: array-like (# rows, # features)
NumPy matrix containing the features
y: array-like (# rows, 1)
NumPy matrix containing the target values
n: list (default: [2])
The maximum size(s) of the MDR model to generate.
e.g., if n == [3], all 3-way models will be generated.
feature_names: list (default: None)
The corresponding names of the features in X.
If None, then the features will be named according to their order.
Returns
----------
(fitted_model, fitted_model_score, fitted_model_features): tuple of (list, list, list)
fitted_model contains the MDR model fitted to the data.
fitted_model_score contains the training scores corresponding to the fitted MDR model.
fitted_model_features contains a list of the names of the features that were used in the corresponding model.
"""
if feature_names is None:
feature_names = list(range(X.shape[1]))
for cur_n in n:
for features in itertools.combinations(range(X.shape[1]), cur_n):
mdr_model = copy.deepcopy(mdr_instance)
mdr_model.fit(X[:, features], y)
mdr_model_score = mdr_model.score(X[:, features], y)
model_features = [feature_names[feature] for feature in features]
yield mdr_model, mdr_model_score, model_features | python | {
"resource": ""
} |
q274586 | plot_mdr_grid | test | def plot_mdr_grid(mdr_instance):
"""Visualizes the MDR grid of a given fitted MDR instance. Only works for 2-way MDR models.
This function is currently incomplete.
Parameters
----------
mdr_instance: object
A fitted instance of the MDR type to visualize.
Returns
----------
fig: matplotlib.figure
Figure object for the visualized MDR grid.
"""
var1_levels = list(set([variables[0] for variables in mdr_instance.feature_map]))
var2_levels = list(set([variables[1] for variables in mdr_instance.feature_map]))
max_count = np.array(list(mdr_instance.class_count_matrix.values())).flatten().max()
"""
TODO:
- Add common axis labels
- Make sure this scales for smaller and larger record sizes
- Extend to 3-way+ models, e.g., http://4.bp.blogspot.com/-vgKCjEkWFUc/UPwPuHo6XvI/AAAAAAAAAE0/fORHqDcoikE/s1600/model.jpg
"""
fig, splots = plt.subplots(ncols=len(var1_levels), nrows=len(var2_levels), sharey=True, sharex=True)
fig.set_figwidth(6)
fig.set_figheight(6)
for (var1, var2) in itertools.product(var1_levels, var2_levels):
class_counts = mdr_instance.class_count_matrix[(var1, var2)]
splot = splots[var2_levels.index(var2)][var1_levels.index(var1)]
splot.set_yticks([])
splot.set_xticks([])
splot.set_ylim(0, max_count * 1.5)
splot.set_xlim(-0.5, 1.5)
if var2_levels.index(var2) == 0:
splot.set_title('X1 = {}'.format(var1), fontsize=12)
if var1_levels.index(var1) == 0:
splot.set_ylabel('X2 = {}'.format(var2), fontsize=12)
bars = splot.bar(left=range(class_counts.shape[0]),
height=class_counts, width=0.5,
color='black', align='center')
bgcolor = 'lightgrey' if mdr_instance.feature_map[(var1, var2)] == 0 else 'darkgrey'
splot.set_axis_bgcolor(bgcolor)
for index, bar in enumerate(bars):
splot.text(index, class_counts[index] + (max_count * 0.1), class_counts[index], ha='center')
fig.tight_layout()
return fig | python | {
"resource": ""
} |
q274587 | get_config | test | def get_config(app, prefix='hive_'):
"""Conveniently get the security configuration for the specified
application without the annoying 'SECURITY_' prefix.
:param app: The application to inspect
"""
items = app.config.items()
prefix = prefix.upper()
def strip_prefix(tup):
return (tup[0].replace(prefix, ''), tup[1])
return dict([strip_prefix(i) for i in items if i[0].startswith(prefix)]) | python | {
"resource": ""
} |
q274588 | config_value | test | def config_value(key, app=None, default=None, prefix='hive_'):
"""Get a Flask-Security configuration value.
:param key: The configuration key without the prefix `SECURITY_`
:param app: An optional specific application to inspect. Defaults to
Flask's `current_app`
:param default: An optional default value if the value is not set
"""
app = app or current_app
return get_config(app, prefix=prefix).get(key.upper(), default) | python | {
"resource": ""
} |
q274589 | vector | test | def vector(members: Iterable[T], meta: Optional[IPersistentMap] = None) -> Vector[T]:
"""Creates a new vector."""
return Vector(pvector(members), meta=meta) | python | {
"resource": ""
} |
q274590 | v | test | def v(*members: T, meta: Optional[IPersistentMap] = None) -> Vector[T]:
"""Creates a new vector from members."""
return Vector(pvector(members), meta=meta) | python | {
"resource": ""
} |
q274591 | eval_file | test | def eval_file(filename: str, ctx: compiler.CompilerContext, module: types.ModuleType):
"""Evaluate a file with the given name into a Python module AST node."""
last = None
for form in reader.read_file(filename, resolver=runtime.resolve_alias):
last = compiler.compile_and_exec_form(form, ctx, module)
return last | python | {
"resource": ""
} |
q274592 | eval_stream | test | def eval_stream(stream, ctx: compiler.CompilerContext, module: types.ModuleType):
"""Evaluate the forms in stdin into a Python module AST node."""
last = None
for form in reader.read(stream, resolver=runtime.resolve_alias):
last = compiler.compile_and_exec_form(form, ctx, module)
return last | python | {
"resource": ""
} |
q274593 | eval_str | test | def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any):
"""Evaluate the forms in a string into a Python module AST node."""
last = eof
for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof):
last = compiler.compile_and_exec_form(form, ctx, module)
return last | python | {
"resource": ""
} |
q274594 | bootstrap_repl | test | def bootstrap_repl(which_ns: str) -> types.ModuleType:
"""Bootstrap the REPL with a few useful vars and returned the
bootstrapped module so it's functions can be used by the REPL
command."""
repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl"))
ns = runtime.Namespace.get_or_create(sym.symbol(which_ns))
repl_module = importlib.import_module("basilisp.repl")
ns.add_alias(sym.symbol("basilisp.repl"), repl_ns)
ns.refer_all(repl_ns)
return repl_module | python | {
"resource": ""
} |
q274595 | run | test | def run( # pylint: disable=too-many-arguments
file_or_code,
code,
in_ns,
use_var_indirection,
warn_on_shadowed_name,
warn_on_shadowed_var,
warn_on_var_indirection,
):
"""Run a Basilisp script or a line of code, if it is provided."""
basilisp.init()
ctx = compiler.CompilerContext(
filename=CLI_INPUT_FILE_PATH
if code
else (
STDIN_INPUT_FILE_PATH if file_or_code == STDIN_FILE_NAME else file_or_code
),
opts={
compiler.WARN_ON_SHADOWED_NAME: warn_on_shadowed_name,
compiler.WARN_ON_SHADOWED_VAR: warn_on_shadowed_var,
compiler.USE_VAR_INDIRECTION: use_var_indirection,
compiler.WARN_ON_VAR_INDIRECTION: warn_on_var_indirection,
},
)
eof = object()
with runtime.ns_bindings(in_ns) as ns:
if code:
print(runtime.lrepr(eval_str(file_or_code, ctx, ns.module, eof)))
elif file_or_code == STDIN_FILE_NAME:
print(
runtime.lrepr(
eval_stream(click.get_text_stream("stdin"), ctx, ns.module)
)
)
else:
print(runtime.lrepr(eval_file(file_or_code, ctx, ns.module))) | python | {
"resource": ""
} |
q274596 | multifn | test | def multifn(dispatch: DispatchFunction, default=None) -> MultiFunction[T]:
"""Decorator function which can be used to make Python multi functions."""
name = sym.symbol(dispatch.__qualname__, ns=dispatch.__module__)
return MultiFunction(name, dispatch, default) | python | {
"resource": ""
} |
q274597 | MultiFunction.__add_method | test | def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map:
"""Swap the methods atom to include method with key."""
return m.assoc(key, method) | python | {
"resource": ""
} |
q274598 | MultiFunction.add_method | test | def add_method(self, key: T, method: Method) -> None:
"""Add a new method to this function which will respond for
key returned from the dispatch function."""
self._methods.swap(MultiFunction.__add_method, key, method) | python | {
"resource": ""
} |
q274599 | MultiFunction.get_method | test | def get_method(self, key: T) -> Optional[Method]:
"""Return the method which would handle this dispatch key or
None if no method defined for this key and no default."""
method_cache = self.methods
# The 'type: ignore' comment below silences a spurious MyPy error
# about having a return statement in a method which does not return.
return Maybe(method_cache.entry(key, None)).or_else(
lambda: method_cache.entry(self._default, None) # type: ignore
) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.