_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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 | 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(";")
| 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):
| 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.
"""
| 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 = {}
| 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)
| 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)
| 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 = | 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 = []
| 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)),
| 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.
""" | 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 | 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.
| 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 = {
| 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 | 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.
"""
| 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 = []
| 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.
"""
| 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:
| 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.
"""
| 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
| 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": {}}
| 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
| 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 | 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
| 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 | 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 | 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
| 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 | 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.
"""
| 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 = | 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 = | 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()
| 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)
| 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)
| 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
| 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 = []
| 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)
| 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"] = | 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 | 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"] = | 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 | 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 | 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 | 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 | 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():
| 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"):
| 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]
| 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:
# | 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:
| 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 = | python | {
"resource": ""
} |
q274551 | PrometheusExporterScript.create_metrics | test | def create_metrics(
self, metric_configs: Iterable[MetricConfig]) -> Dict[str, Metric]:
| 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',
| python | {
"resource": ""
} |
q274553 | PrometheusExporterScript._configure_registry | test | def _configure_registry(self, include_process_stats: bool = False):
"""Configure the MetricRegistry."""
if include_process_stats:
| 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] = {
| python | {
"resource": ""
} |
q274555 | MetricsRegistry.get_metric | test | def get_metric(
self, name: str,
labels: Union[Dict[str, str], None] = None) -> Metric:
"""Return | 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>
| 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 = | 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 | 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:
| 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(
| python | {
"resource": ""
} |
q274561 | Result.info | test | def info(self):
"""
The pods, assumptions, and warnings of this result.
"""
| python | {
"resource": ""
} |
q274562 | Result.results | test | def results(self):
"""
The pods that hold the response to a simple, discrete query.
"""
return (
pod
| 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.
| 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 | 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:
| 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:
| 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.
| 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.
| 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:
| 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 | 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',
| 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 = {
| 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.
| 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.
"""
| 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.
| 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)
| 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
| 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])) / | 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}
| 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
"""
| 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])
| 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]):
| 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 | 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 | 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 | 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([])
| 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 | 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 | python | {
"resource": ""
} |
q274589 | vector | test | def vector(members: Iterable[T], meta: Optional[IPersistentMap] = None) -> Vector[T]:
"""Creates a | python | {
"resource": ""
} |
q274590 | v | test | def v(*members: T, meta: Optional[IPersistentMap] = None) -> Vector[T]:
"""Creates a new vector from | 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 | 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, | 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 | 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))
| 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,
},
)
| python | {
"resource": ""
} |
q274596 | multifn | test | def multifn(dispatch: DispatchFunction, default=None) -> MultiFunction[T]:
"""Decorator function which can be used to make Python multi functions."""
| python | {
"resource": ""
} |
q274597 | MultiFunction.__add_method | test | def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map:
"""Swap | python | {
"resource": ""
} |
q274598 | MultiFunction.add_method | test | def add_method(self, key: T, method: Method) -> None:
"""Add a new method to this function which | 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 | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.