INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return list of sections including students for the passed course ID. | 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"] = ... |
Return list of sections including students for the passed sis ID. | 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(... |
Create a canvas section in the given course id. | 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": {"na... |
Update a canvas section with the given section id. | 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": {}}
... |
List quizzes for a given course | 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:
... |
Return account resource for given canvas account id. | 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)) |
Return list of subaccounts within the account with the passed canvas id. | 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"
... |
Update the passed account. Returns the updated account. | 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}}
... |
Updates the SIS ID for the account identified by the passed account ID. | 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(... |
Return the authentication settings for the passed account_id. | 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) + "/ss... |
Update the authentication settings for the passed account_id. | 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.forma... |
Calculates the settlement of a shallow foundation ( Schmertmann 19XX ). | def settlement_schmertmann(sp, fd, load, youngs_modulus_soil, **kwargs):
"""
Calculates the settlement of a shallow foundation (Schmertmann, 19XX).
:param sp: Soil Profile object
:param fd: Foundation object
:param load:
:param youngs_modulus_soil: The Young's modulus of the soil.
:param kw... |
Return all of the terms in the account. https:// canvas. instructure. com/ doc/ api/ enrollment_terms. html#method. terms_api. index | def get_all_terms(self):
"""
Return all of the terms in the account.
https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index
"""
if not self._canvas_account_id:
raise MissingAccountID()
params = {"workflow_state": 'all', 'per_page'... |
Return a term resource for the passed SIS ID. | 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 |
Update an existing enrollment term for the passed SIS ID. https:// canvas. instructure. com/ doc/ api/ enrollment_terms. html#method. terms. update | def update_term_overrides(self, sis_term_id, overrides={}):
"""
Update an existing enrollment term for the passed SIS ID.
https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms.update
"""
if not self._canvas_account_id:
raise MissingAccountID()
... |
Produces console output.: param out_str: Output string: param o2: Additional output string: param o3: Additional output string: param o4: Additional output string: return: None | def log(out_str, o2="", o3="", o4=""):
"""
Produces console output.
:param out_str: Output string
:param o2: Additional output string
:param o3: Additional output string
:param o4: Additional output string
:return: None
"""
print(out_str, o2, o3, o4) |
Imports a CSV string. | 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_IMPO... |
Imports a directory of CSV files. | 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... |
Get the status of an already created SIS import. | 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_A... |
Creates a zip archive from files in path. | 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)
... |
List assignments for a given course | 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 = []
... |
Modify an existing assignment. | 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)
... |
Returns the list of reports for the canvas account id. | 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_typ... |
Shows all reports of the passed report_type that have been run for the canvas account id. | 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(ac... |
Generates a report instance for the canvas account id. | 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["enrollm... |
Convenience method for create_report for creating a course provisioning report. | 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(ReportTy... |
Convenience method for create_report for creating a course sis export report. | 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... |
Convenience method for create_report for creating an unused courses report. | 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) |
Returns a completed report as a list of csv strings. | 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 ... |
Returns the status of a report. | 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):
rai... |
Deletes a generated report instance. | 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... |
Crop an image given the top left corner.: param img: The image: param start_y: The top left corner y coord: param start_x: The top left corner x coord: param h: The result height: param w: The result width: return: The cropped image. | def crop_image(img, start_y, start_x, h, w):
"""
Crop an image given the top left corner.
:param img: The image
:param start_y: The top left corner y coord
:param start_x: The top left corner x coord
:param h: The result height
:param w: The result width
:return: The cropped image.
"... |
Move detections in direction dx dy. | 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.st... |
Horizontally flip detections according to an image flip. | 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"):
detec... |
Augment the detection dataset. | def augment_detections(hyper_params, feature, label):
"""
Augment the detection dataset.
In your hyper_parameters.problem.augmentation add configurations to enable features.
Supports "enable_horizontal_flip", "enable_micro_translation", "random_crop" : {"shape": { "width", "height" }}
and "enable_t... |
Edit to get the dict even when the object is a GenericRelatedObjectManager. Added the try except. | 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('... |
Get the arguments given to the template tag element and complete these with the ones from the settings. py if necessary. | 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)
... |
Get the text to display when the field is empty. | 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_... |
Usage: { % eval % } 1 + 1 { % endeval % } | def do_eval(parser, token):
"Usage: {% eval %}1 + 1{% endeval %}"
nodelist = parser.parse(('endeval',))
class EvalNode(template.Node):
def render(self, context):
return template.Template(nodelist.render(context)).render(template.Context(context))
parser.delete_first_token()
ret... |
Parse uniformly args and kwargs from a templatetag | 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 = ... |
Create and register metrics from a list of MetricConfigs. | 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) |
Setup logging for the application and aiohttp. | 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_logg... |
Configure the MetricRegistry. | def _configure_registry(self, include_process_stats: bool = False):
"""Configure the MetricRegistry."""
if include_process_stats:
self.registry.register_additional_collector(
ProcessCollector(registry=None)) |
Return a: class: PrometheusExporter configured with args. | def _get_exporter(self, args: argparse.Namespace) -> PrometheusExporter:
"""Return a :class:`PrometheusExporter` configured with args."""
exporter = PrometheusExporter(
self.name, self.description, args.host, args.port, self.registry)
exporter.app.on_startup.append(self.on_applicatio... |
Create Prometheus metrics from a list of MetricConfigs. | 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
}
s... |
Return a metric optionally configured with labels. | 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 |
Run the: class: aiohttp. web. Application for the exporter. | def run(self):
"""Run the :class:`aiohttp.web.Application` for the exporter."""
run_app(
self.app,
host=self.host,
port=self.port,
print=lambda *args, **kargs: None,
access_log_format='%a "%r" %s %b "%{Referrer}i" "%{User-Agent}i"') |
Setup an: class: aiohttp. web. Application. | def _make_application(self) -> Application:
"""Setup an :class:`aiohttp.web.Application`."""
app = Application()
app['exporter'] = self
app.router.add_get('/', self._handle_home)
app.router.add_get('/metrics', self._handle_metrics)
app.on_startup.append(self._log_startup_... |
Home page request handler. | 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>
<... |
Handler for metrics. | 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
... |
A free - text query resolver by Wolfram|Alpha. Returns the first result if available. | 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 2 uses a deprecated method signature and doesn t provide the forward compatibility. Add it. | 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 |
Query Wolfram|Alpha using the v2. 0 API | 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 assum... |
The pods assumptions and warnings of this result. | def info(self):
"""
The pods, assumptions, and warnings of this result.
"""
return itertools.chain(self.pods, self.assumptions, self.warnings) |
The pods that hold the response to a simple discrete query. | 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'
) |
Add request content data to request body set Content - type header. | 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:
... |
Call API. | 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:
... |
Call the API with a GET request. | 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 the API with a DELETE request. | 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.
"""
retur... |
Call the API with a PUT request. | 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.
... |
Call the API with a POST request. | 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.
... |
Process query recursively if the text is too long it is split and processed bit a bit. | 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 req... |
Split sentences in groups given a specific group length. | 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 group... |
Call the disambiguation service in order to process a pdf file. | 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 ... |
Call the disambiguation service in order to get meanings. | def disambiguate_terms(self, terms, language="en", entities=None):
""" Call the disambiguation service in order to get meanings.
Args:
terms (obj): list of objects of term, weight
language (str): language of text, english if not specified
entities (li... |
Call the disambiguation service in order to get meanings. | def disambiguate_text(self, text, language=None, entities=None):
""" Call the disambiguation service in order to get meanings.
Args:
text (str): Text to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be ... |
Call the disambiguation service in order to disambiguate a search query. | 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 ... |
Call the segmenter in order to split text in sentences. | 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 cod... |
Recognise the language of the text in input | 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.
"""
... |
Fetch the concept from the Knowledge base | 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 inte... |
Constructs the MDR ensemble from the provided training data | 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
... |
Estimates the accuracy of the predictions from the MDR ensemble | 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-l... |
Constructs the MDR feature map from the provided training data. | 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
... |
Convenience function that fits the provided data then constructs a new feature from the provided features. | def fit_transform(self, features, class_labels):
"""Convenience function that fits the provided data then constructs a new feature from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {... |
Convenience function that fits the provided data then constructs predictions from the provided features. | 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_sa... |
Estimates the accuracy of the predictions from the constructed feature. | 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
cla... |
Constructs the Continuous MDR feature map from the provided training data. | 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 pre... |
Uses the Continuous MDR feature map to construct a new feature from the provided features. | 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:... |
Convenience function that fits the provided data then constructs a new feature from the provided features. | def fit_transform(self, features, targets):
"""Convenience function that fits the provided data then constructs a new feature from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
targets: array-like {n_samples}... |
Estimates the quality of the ContinuousMDR model using a t - statistic. | 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 tar... |
Calculates the entropy H ( X ) in the given base | def entropy(X, base=2):
"""Calculates the entropy, H(X), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the entropy
base: integer (default: 2)
The base in which to calculate entropy
Returns
----------
entropy: f... |
Calculates the joint entropy H ( X Y ) in the given base | def joint_entropy(X, Y, base=2):
"""Calculates the joint entropy, H(X,Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the joint entropy
Y: array-like (# samples)
An array of values for which to compute the joint entropy
... |
Calculates the conditional entropy H ( X|Y ) in the given base | def conditional_entropy(X, Y, base=2):
"""Calculates the conditional entropy, H(X|Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the conditional entropy
Y: array-like (# samples)
An array of values for which to compute t... |
Calculates the mutual information between two variables I ( X ; Y ) in the given base | def mutual_information(X, Y, base=2):
"""Calculates the mutual information between two variables, I(X;Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the mutual information
Y: array-like (# samples)
An array of values for... |
Calculates the two - way information gain between three variables I ( X ; Y ; Z ) in the given base | def two_way_information_gain(X, Y, Z, base=2):
"""Calculates the two-way information gain between three variables, I(X;Y;Z), in the given base
IG(X;Y;Z) indicates the information gained about variable Z by the joint variable X_Y, after removing
the information that X and Y have about Z individually. Thus, ... |
Calculates the three - way information gain between three variables I ( W ; X ; Y ; Z ) in the given base | def three_way_information_gain(W, X, Y, Z, base=2):
"""Calculates the three-way information gain between three variables, I(W;X;Y;Z), in the given base
IG(W;X;Y;Z) indicates the information gained about variable Z by the joint variable W_X_Y, after removing
the information that W, X, and Y have about Z ind... |
Fits a MDR model to variables X and Y with the given labels then returns the resulting predictions | 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 f... |
Calculates the MDR entropy H ( XY ) in the given base | def mdr_entropy(X, Y, labels, base=2):
"""Calculates the MDR entropy, H(XY), in the given base
MDR entropy is calculated by combining variables X and Y into a single MDR model then calculating
the entropy of the resulting model's predictions.
Parameters
----------
X: array-like (# samples)
... |
Calculates the MDR conditional entropy H ( XY|labels ) in the given base | def mdr_conditional_entropy(X, Y, labels, base=2):
"""Calculates the MDR conditional entropy, H(XY|labels), in the given base
MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating
the entropy of the resulting model's predictions conditional on the pro... |
Calculates the MDR mutual information I ( XY ; labels ) in the given base | def mdr_mutual_information(X, Y, labels, base=2):
"""Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictions and the l... |
Fits a MDR model to all n - way combinations of the features in X. | 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: obje... |
Visualizes the MDR grid of a given fitted MDR instance. Only works for 2 - way MDR models. This function is currently incomplete. | 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
----------
... |
等价于 django makemigrations 操作 | def makemigrations(migrations_root):
"""等价于 django makemigrations 操作"""
from flask_migrate import (Migrate, init as migrate_init,
migrate as migrate_exec)
migrations_root = migrations_root or os.path.join(
os.environ.get('FANTASY_MIGRATION_PATH',
... |
等价于 django migrate 操作 | def migrate(migrations_root):
"""等价于 django migrate 操作"""
from flask_migrate import Migrate, upgrade as migrate_upgrade
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.engine.url import make_url
from sqlalchemy_utils import database_exists, create_database
db = SQLAlchemy()
dsn = ma... |
编译全新依赖文件 | def requirements(work_dir, hive_root, with_requirements,
with_dockerfile, active_module, active_module_file):
"""编译全新依赖文件"""
import sys
sys.path.insert(0, hive_root)
hive_root = os.path.abspath(os.path.expanduser(hive_root))
work_dir = work_dir or os.path.join(
os.environ.... |
启动队列服务 [ 开发中 ] | def queue(celery_arguments):
"""启动队列服务[开发中]"""
if not app.celery:
return click.echo(
click.style('No celery config found,skip start...', fg='yellow'))
celery = app.celery
celery.autodiscover_tasks()
argv = celery_arguments.split()
argv.insert(0, 'worker')
argv.insert(0... |
尝试对数据库做初始化操作 | def smart_database(app):
"""尝试对数据库做初始化操作"""
from sqlalchemy.engine.url import make_url
from sqlalchemy_utils import database_exists, create_database
# 如果数据库不存在,则尝试创建数据
dsn = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
if not database_exists(dsn):
create_database(dsn)
pass
... |
如果存在migration且指定为primary_node则执行migrate操作 | def smart_migrate(app, migrations_root):
"""如果存在migration且指定为primary_node则执行migrate操作"""
db = app.db
if os.path.exists(migrations_root) and \
os.environ['FANTASY_PRIMARY_NODE'] != 'no':
from flask_migrate import (Migrate,
upgrade as migrate_upgrade)
... |
尝试使用内置方式构建账户 | def smart_account(app):
"""尝试使用内置方式构建账户"""
if os.environ['FANTASY_ACTIVE_ACCOUNT'] == 'no':
return
from flask_security import SQLAlchemyUserDatastore, Security
account_module_name, account_class_name = os.environ[
'FANTASY_ACCOUNT_MODEL'].rsplit('.', 1)
account_module = importlib.... |
装载任务,解决celery无法自动装载的问题 | def load_tasks(app, entry_file=None):
"""装载任务,解决celery无法自动装载的问题"""
from celery import Task
tasks_txt = os.path.join(os.path.dirname(entry_file), 'migrations',
'tasks.txt')
if not os.path.exists(tasks_txt):
import sys
print('Tasks file not found:%s' % tasks_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.