repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | pagination_for | def pagination_for(context, current_page, page_var="page", exclude_vars=""):
"""
Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``... | python | def pagination_for(context, current_page, page_var="page", exclude_vars=""):
"""
Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``... | [
"def",
"pagination_for",
"(",
"context",
",",
"current_page",
",",
"page_var",
"=",
"\"page\"",
",",
"exclude_vars",
"=",
"\"\"",
")",
":",
"querystring",
"=",
"context",
"[",
"\"request\"",
"]",
".",
"GET",
".",
"copy",
"(",
")",
"exclude_vars",
"=",
"[",... | Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``exclude_vars`` arg. | [
"Include",
"the",
"pagination",
"template",
"and",
"data",
"for",
"persisting",
"querystring",
"in",
"pagination",
"links",
".",
"Can",
"also",
"contain",
"a",
"comma",
"separated",
"string",
"of",
"var",
"names",
"in",
"the",
"current",
"querystring",
"to",
"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L222-L239 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | search_form | def search_form(context, search_model_names=None):
"""
Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case th... | python | def search_form(context, search_model_names=None):
"""
Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case th... | [
"def",
"search_form",
"(",
"context",
",",
"search_model_names",
"=",
"None",
")",
":",
"template_vars",
"=",
"{",
"\"request\"",
":",
"context",
"[",
"\"request\"",
"]",
",",
"}",
"if",
"not",
"search_model_names",
"or",
"not",
"settings",
".",
"SEARCH_MODEL_... | Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case the models defined
by the ``SEARCH_MODEL_CHOICES`` setting wi... | [
"Includes",
"the",
"search",
"form",
"with",
"a",
"list",
"of",
"models",
"to",
"use",
"as",
"choices",
"for",
"filtering",
"the",
"search",
"by",
".",
"Models",
"should",
"be",
"a",
"string",
"with",
"models",
"in",
"the",
"format",
"app_label",
".",
"m... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L243-L270 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | thumbnail | def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
top=.5, padding=False, padding_color="#fff"):
"""
Given the URL to an image, resizes the image using the given width
and height on the first time it is requested, and returns the URL
to the new resized image. If wid... | python | def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
top=.5, padding=False, padding_color="#fff"):
"""
Given the URL to an image, resizes the image using the given width
and height on the first time it is requested, and returns the URL
to the new resized image. If wid... | [
"def",
"thumbnail",
"(",
"image_url",
",",
"width",
",",
"height",
",",
"upscale",
"=",
"True",
",",
"quality",
"=",
"95",
",",
"left",
"=",
".5",
",",
"top",
"=",
".5",
",",
"padding",
"=",
"False",
",",
"padding_color",
"=",
"\"#fff\"",
")",
":",
... | Given the URL to an image, resizes the image using the given width
and height on the first time it is requested, and returns the URL
to the new resized image. If width or height are zero then original
ratio is maintained. When ``upscale`` is False, images smaller than
the given size will not be grown to... | [
"Given",
"the",
"URL",
"to",
"an",
"image",
"resizes",
"the",
"image",
"using",
"the",
"given",
"width",
"and",
"height",
"on",
"the",
"first",
"time",
"it",
"is",
"requested",
"and",
"returns",
"the",
"URL",
"to",
"the",
"new",
"resized",
"image",
".",
... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L274-L438 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | editable_loader | def editable_loader(context):
"""
Set up the required JS/CSS for the in-line editing toolbar and controls.
"""
user = context["request"].user
template_vars = {
"has_site_permission": has_site_permission(user),
"request": context["request"],
}
if (settings.INLINE_EDITING_ENABL... | python | def editable_loader(context):
"""
Set up the required JS/CSS for the in-line editing toolbar and controls.
"""
user = context["request"].user
template_vars = {
"has_site_permission": has_site_permission(user),
"request": context["request"],
}
if (settings.INLINE_EDITING_ENABL... | [
"def",
"editable_loader",
"(",
"context",
")",
":",
"user",
"=",
"context",
"[",
"\"request\"",
"]",
".",
"user",
"template_vars",
"=",
"{",
"\"has_site_permission\"",
":",
"has_site_permission",
"(",
"user",
")",
",",
"\"request\"",
":",
"context",
"[",
"\"re... | Set up the required JS/CSS for the in-line editing toolbar and controls. | [
"Set",
"up",
"the",
"required",
"JS",
"/",
"CSS",
"for",
"the",
"in",
"-",
"line",
"editing",
"toolbar",
"and",
"controls",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L442-L462 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | richtext_filters | def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func... | python | def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func... | [
"def",
"richtext_filters",
"(",
"content",
")",
":",
"for",
"filter_name",
"in",
"settings",
".",
"RICHTEXT_FILTERS",
":",
"filter_func",
"=",
"import_dotted_path",
"(",
"filter_name",
")",
"content",
"=",
"filter_func",
"(",
"content",
")",
"return",
"content"
] | Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting. | [
"Takes",
"a",
"value",
"edited",
"via",
"the",
"WYSIWYG",
"editor",
"and",
"passes",
"it",
"through",
"each",
"of",
"the",
"functions",
"specified",
"by",
"the",
"RICHTEXT_FILTERS",
"setting",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L466-L474 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | editable | def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
mod... | python | def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
mod... | [
"def",
"editable",
"(",
"parsed",
",",
"context",
",",
"token",
")",
":",
"def",
"parse_field",
"(",
"field",
")",
":",
"field",
"=",
"field",
".",
"split",
"(",
"\".\"",
")",
"obj",
"=",
"context",
".",
"get",
"(",
"field",
".",
"pop",
"(",
"0",
... | Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
model. | [
"Add",
"the",
"required",
"HTML",
"to",
"the",
"parsed",
"content",
"for",
"in",
"-",
"line",
"editing",
"such",
"as",
"the",
"icon",
"and",
"edit",
"form",
"if",
"the",
"object",
"is",
"deemed",
"to",
"be",
"editable",
"-",
"either",
"it",
"has",
"an"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L478-L514 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | try_url | def try_url(url_name):
"""
Mimics Django's ``url`` template tag but fails silently. Used for
url names in admin templates as these won't resolve when admin
tests are running.
"""
from warnings import warn
warn("try_url is deprecated, use the url tag with the 'as' arg instead.")
try:
... | python | def try_url(url_name):
"""
Mimics Django's ``url`` template tag but fails silently. Used for
url names in admin templates as these won't resolve when admin
tests are running.
"""
from warnings import warn
warn("try_url is deprecated, use the url tag with the 'as' arg instead.")
try:
... | [
"def",
"try_url",
"(",
"url_name",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"try_url is deprecated, use the url tag with the 'as' arg instead.\"",
")",
"try",
":",
"url",
"=",
"reverse",
"(",
"url_name",
")",
"except",
"NoReverseMatch",
":",
"r... | Mimics Django's ``url`` template tag but fails silently. Used for
url names in admin templates as these won't resolve when admin
tests are running. | [
"Mimics",
"Django",
"s",
"url",
"template",
"tag",
"but",
"fails",
"silently",
".",
"Used",
"for",
"url",
"names",
"in",
"admin",
"templates",
"as",
"these",
"won",
"t",
"resolve",
"when",
"admin",
"tests",
"are",
"running",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L518-L530 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | admin_app_list | def admin_app_list(request):
"""
Adopted from ``django.contrib.admin.sites.AdminSite.index``.
Returns a list of lists of models grouped and ordered according to
``yacms.conf.ADMIN_MENU_ORDER``. Called from the
``admin_dropdown_menu`` template tag as well as the ``app_list``
dashboard widget.
... | python | def admin_app_list(request):
"""
Adopted from ``django.contrib.admin.sites.AdminSite.index``.
Returns a list of lists of models grouped and ordered according to
``yacms.conf.ADMIN_MENU_ORDER``. Called from the
``admin_dropdown_menu`` template tag as well as the ``app_list``
dashboard widget.
... | [
"def",
"admin_app_list",
"(",
"request",
")",
":",
"app_dict",
"=",
"{",
"}",
"# Model or view --> (group index, group title, item index, item title).",
"menu_order",
"=",
"{",
"}",
"for",
"(",
"group_index",
",",
"group",
")",
"in",
"enumerate",
"(",
"settings",
".... | Adopted from ``django.contrib.admin.sites.AdminSite.index``.
Returns a list of lists of models grouped and ordered according to
``yacms.conf.ADMIN_MENU_ORDER``. Called from the
``admin_dropdown_menu`` template tag as well as the ``app_list``
dashboard widget. | [
"Adopted",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"sites",
".",
"AdminSite",
".",
"index",
".",
"Returns",
"a",
"list",
"of",
"lists",
"of",
"models",
"grouped",
"and",
"ordered",
"according",
"to",
"yacms",
".",
"conf",
".",
"ADMIN_MENU_ORDE... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L533-L641 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | admin_dropdown_menu | def admin_dropdown_menu(context):
"""
Renders the app list for the admin dropdown menu navigation.
"""
template_vars = context.flatten()
user = context["request"].user
if user.is_staff:
template_vars["dropdown_menu_app_list"] = admin_app_list(
context["request"])
if u... | python | def admin_dropdown_menu(context):
"""
Renders the app list for the admin dropdown menu navigation.
"""
template_vars = context.flatten()
user = context["request"].user
if user.is_staff:
template_vars["dropdown_menu_app_list"] = admin_app_list(
context["request"])
if u... | [
"def",
"admin_dropdown_menu",
"(",
"context",
")",
":",
"template_vars",
"=",
"context",
".",
"flatten",
"(",
")",
"user",
"=",
"context",
"[",
"\"request\"",
"]",
".",
"user",
"if",
"user",
".",
"is_staff",
":",
"template_vars",
"[",
"\"dropdown_menu_app_list... | Renders the app list for the admin dropdown menu navigation. | [
"Renders",
"the",
"app",
"list",
"for",
"the",
"admin",
"dropdown",
"menu",
"navigation",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L646-L666 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | dashboard_column | def dashboard_column(context, token):
"""
Takes an index for retrieving the sequence of template tags from
``yacms.conf.DASHBOARD_TAGS`` to render into the admin
dashboard.
"""
column_index = int(token.split_contents()[1])
output = []
for tag in settings.DASHBOARD_TAGS[column_index]:
... | python | def dashboard_column(context, token):
"""
Takes an index for retrieving the sequence of template tags from
``yacms.conf.DASHBOARD_TAGS`` to render into the admin
dashboard.
"""
column_index = int(token.split_contents()[1])
output = []
for tag in settings.DASHBOARD_TAGS[column_index]:
... | [
"def",
"dashboard_column",
"(",
"context",
",",
"token",
")",
":",
"column_index",
"=",
"int",
"(",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
"]",
")",
"output",
"=",
"[",
"]",
"for",
"tag",
"in",
"settings",
".",
"DASHBOARD_TAGS",
"[",
"colu... | Takes an index for retrieving the sequence of template tags from
``yacms.conf.DASHBOARD_TAGS`` to render into the admin
dashboard. | [
"Takes",
"an",
"index",
"for",
"retrieving",
"the",
"sequence",
"of",
"template",
"tags",
"from",
"yacms",
".",
"conf",
".",
"DASHBOARD_TAGS",
"to",
"render",
"into",
"the",
"admin",
"dashboard",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L688-L699 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | translate_url | def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context["request"]
except KeyError:
return ""
view = resolve(request.path)
current_language = translation.get_language()
... | python | def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context["request"]
except KeyError:
return ""
view = resolve(request.path)
current_language = translation.get_language()
... | [
"def",
"translate_url",
"(",
"context",
",",
"language",
")",
":",
"try",
":",
"request",
"=",
"context",
"[",
"\"request\"",
"]",
"except",
"KeyError",
":",
"return",
"\"\"",
"view",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
"current_language",
"=... | Translates the current URL for the given language code, eg:
{% translate_url de %} | [
"Translates",
"the",
"current",
"URL",
"for",
"the",
"given",
"language",
"code",
"eg",
":"
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L703-L729 |
mushkevych/synergy_odm | odm/fields.py | BaseField.raise_error | def raise_error(self, message='', errors=None, field_name=None):
"""Raises a ValidationError. """
field_name = field_name if field_name else self.field_name
raise ValidationError(message, errors=errors, field_name=field_name) | python | def raise_error(self, message='', errors=None, field_name=None):
"""Raises a ValidationError. """
field_name = field_name if field_name else self.field_name
raise ValidationError(message, errors=errors, field_name=field_name) | [
"def",
"raise_error",
"(",
"self",
",",
"message",
"=",
"''",
",",
"errors",
"=",
"None",
",",
"field_name",
"=",
"None",
")",
":",
"field_name",
"=",
"field_name",
"if",
"field_name",
"else",
"self",
".",
"field_name",
"raise",
"ValidationError",
"(",
"me... | Raises a ValidationError. | [
"Raises",
"a",
"ValidationError",
"."
] | train | https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L98-L101 |
mushkevych/synergy_odm | odm/fields.py | BaseField.validate | def validate(self, value):
"""Performs validation of the value.
:param value: value to validate
:raise ValidationError if the value is invalid"""
# check choices
if self.choices:
if isinstance(self.choices[0], (list, tuple)):
option_keys = [k for k, v... | python | def validate(self, value):
"""Performs validation of the value.
:param value: value to validate
:raise ValidationError if the value is invalid"""
# check choices
if self.choices:
if isinstance(self.choices[0], (list, tuple)):
option_keys = [k for k, v... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"# check choices",
"if",
"self",
".",
"choices",
":",
"if",
"isinstance",
"(",
"self",
".",
"choices",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"option_keys",
"=",
"[",
"k... | Performs validation of the value.
:param value: value to validate
:raise ValidationError if the value is invalid | [
"Performs",
"validation",
"of",
"the",
"value",
".",
":",
"param",
"value",
":",
"value",
"to",
"validate",
":",
"raise",
"ValidationError",
"if",
"the",
"value",
"is",
"invalid"
] | train | https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L111-L125 |
mushkevych/synergy_odm | odm/fields.py | NestedDocumentField.validate | def validate(self, value):
"""Make sure that value is of the right type """
if not isinstance(value, self.nested_klass):
self.raise_error('NestedClass is of the wrong type: {0} vs expected {1}'
.format(value.__class__.__name__, self.nested_klass.__name__))
... | python | def validate(self, value):
"""Make sure that value is of the right type """
if not isinstance(value, self.nested_klass):
self.raise_error('NestedClass is of the wrong type: {0} vs expected {1}'
.format(value.__class__.__name__, self.nested_klass.__name__))
... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"nested_klass",
")",
":",
"self",
".",
"raise_error",
"(",
"'NestedClass is of the wrong type: {0} vs expected {1}'",
".",
"format",
"(",
"value",
... | Make sure that value is of the right type | [
"Make",
"sure",
"that",
"value",
"is",
"of",
"the",
"right",
"type"
] | train | https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L141-L146 |
mushkevych/synergy_odm | odm/fields.py | ListField.validate | def validate(self, value):
"""Make sure that the inspected value is of type `list` or `tuple` """
if not isinstance(value, (list, tuple)) or isinstance(value, str_types):
self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}'
.forma... | python | def validate(self, value):
"""Make sure that the inspected value is of type `list` or `tuple` """
if not isinstance(value, (list, tuple)) or isinstance(value, str_types):
self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}'
.forma... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"isinstance",
"(",
"value",
",",
"str_types",
")",
":",
"self",
".",
"raise_error",
"(",
"'Only lists and t... | Make sure that the inspected value is of type `list` or `tuple` | [
"Make",
"sure",
"that",
"the",
"inspected",
"value",
"is",
"of",
"type",
"list",
"or",
"tuple"
] | train | https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L156-L161 |
mushkevych/synergy_odm | odm/fields.py | DictField.validate | def validate(self, value):
"""Make sure that the inspected value is of type `dict` """
if not isinstance(value, dict):
self.raise_error('Only Python dict may be used in the DictField vs provided {0}'
.format(type(value).__name__))
super(DictField, self).v... | python | def validate(self, value):
"""Make sure that the inspected value is of type `dict` """
if not isinstance(value, dict):
self.raise_error('Only Python dict may be used in the DictField vs provided {0}'
.format(type(value).__name__))
super(DictField, self).v... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"self",
".",
"raise_error",
"(",
"'Only Python dict may be used in the DictField vs provided {0}'",
".",
"format",
"(",
"type",
"(",
"value",
... | Make sure that the inspected value is of type `dict` | [
"Make",
"sure",
"that",
"the",
"inspected",
"value",
"is",
"of",
"type",
"dict"
] | train | https://github.com/mushkevych/synergy_odm/blob/3a5ac37333fc6391478564ef653a4be38e332f68/odm/fields.py#L172-L177 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric.get | def get(self):
"""
*do the frankenstein magic!*
"""
self.log.info('starting the ``get`` method')
self._copy_folder_and_get_directory_listings()
self._join_all_filenames_and_text()
self._collect_placeholders_required()
self._populate_dynamic_placeholders()... | python | def get(self):
"""
*do the frankenstein magic!*
"""
self.log.info('starting the ``get`` method')
self._copy_folder_and_get_directory_listings()
self._join_all_filenames_and_text()
self._collect_placeholders_required()
self._populate_dynamic_placeholders()... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"self",
".",
"_copy_folder_and_get_directory_listings",
"(",
")",
"self",
".",
"_join_all_filenames_and_text",
"(",
")",
"self",
".",
"_collect_placeho... | *do the frankenstein magic!* | [
"*",
"do",
"the",
"frankenstein",
"magic!",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L61-L77 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._copy_folder_and_get_directory_listings | def _copy_folder_and_get_directory_listings(
self):
"""
*copy template folder to /tmp and get directory listings*
"""
self.log.info(
'starting the ``_copy_folder_and_get_directory_listings`` method')
# COPY TEMPLATE STRUCTURE TO /tmp/
basename = o... | python | def _copy_folder_and_get_directory_listings(
self):
"""
*copy template folder to /tmp and get directory listings*
"""
self.log.info(
'starting the ``_copy_folder_and_get_directory_listings`` method')
# COPY TEMPLATE STRUCTURE TO /tmp/
basename = o... | [
"def",
"_copy_folder_and_get_directory_listings",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_copy_folder_and_get_directory_listings`` method'",
")",
"# COPY TEMPLATE STRUCTURE TO /tmp/",
"basename",
"=",
"os",
".",
"path",
".",
"basename"... | *copy template folder to /tmp and get directory listings* | [
"*",
"copy",
"template",
"folder",
"to",
"/",
"tmp",
"and",
"get",
"directory",
"listings",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L79-L107 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._collect_placeholders_required | def _collect_placeholders_required(
self):
"""
*collect placeholders required from filename etc*
"""
self.log.info('starting the ``_collect_placeholders_required`` method')
phs = self.settings["frankenstein"]["placeholder delimiters"]
phsString = "|".join(phs... | python | def _collect_placeholders_required(
self):
"""
*collect placeholders required from filename etc*
"""
self.log.info('starting the ``_collect_placeholders_required`` method')
phs = self.settings["frankenstein"]["placeholder delimiters"]
phsString = "|".join(phs... | [
"def",
"_collect_placeholders_required",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_collect_placeholders_required`` method'",
")",
"phs",
"=",
"self",
".",
"settings",
"[",
"\"frankenstein\"",
"]",
"[",
"\"placeholder delimiters\"",
... | *collect placeholders required from filename etc* | [
"*",
"collect",
"placeholders",
"required",
"from",
"filename",
"etc",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L109-L133 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._join_all_filenames_and_text | def _join_all_filenames_and_text(
self):
"""
*join all file names, driectory names and text content together*
"""
self.log.info('starting the ``_join_all_filenames_and_text`` method')
contentString = u""
for i in self.directoryContents:
contentStr... | python | def _join_all_filenames_and_text(
self):
"""
*join all file names, driectory names and text content together*
"""
self.log.info('starting the ``_join_all_filenames_and_text`` method')
contentString = u""
for i in self.directoryContents:
contentStr... | [
"def",
"_join_all_filenames_and_text",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_join_all_filenames_and_text`` method'",
")",
"contentString",
"=",
"u\"\"",
"for",
"i",
"in",
"self",
".",
"directoryContents",
":",
"contentString",
... | *join all file names, driectory names and text content together* | [
"*",
"join",
"all",
"file",
"names",
"driectory",
"names",
"and",
"text",
"content",
"together",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L135-L158 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._populate_dynamic_placeholders | def _populate_dynamic_placeholders(
self):
"""
*populate dynamic placeholders - times etc*
"""
self.log.info('starting the ``_populate_dynamic_placeholders`` method')
from datetime import datetime, date, time
now = datetime.now()
dynamicPhs = {
... | python | def _populate_dynamic_placeholders(
self):
"""
*populate dynamic placeholders - times etc*
"""
self.log.info('starting the ``_populate_dynamic_placeholders`` method')
from datetime import datetime, date, time
now = datetime.now()
dynamicPhs = {
... | [
"def",
"_populate_dynamic_placeholders",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_populate_dynamic_placeholders`` method'",
")",
"from",
"datetime",
"import",
"datetime",
",",
"date",
",",
"time",
"now",
"=",
"datetime",
".",
... | *populate dynamic placeholders - times etc* | [
"*",
"populate",
"dynamic",
"placeholders",
"-",
"times",
"etc",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L160-L186 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._fill_placeholders_from_settings | def _fill_placeholders_from_settings(
self):
"""
*fill placeholders from the placeholders in the settings file*
"""
self.log.info(
'starting the ``_fill_placeholders_from_settings`` method')
for k, v in self.phDict.iteritems():
if k in self.se... | python | def _fill_placeholders_from_settings(
self):
"""
*fill placeholders from the placeholders in the settings file*
"""
self.log.info(
'starting the ``_fill_placeholders_from_settings`` method')
for k, v in self.phDict.iteritems():
if k in self.se... | [
"def",
"_fill_placeholders_from_settings",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_fill_placeholders_from_settings`` method'",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"phDict",
".",
"iteritems",
"(",
")",
":",
"if",
... | *fill placeholders from the placeholders in the settings file* | [
"*",
"fill",
"placeholders",
"from",
"the",
"placeholders",
"in",
"the",
"settings",
"file",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L188-L203 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._request_remaining_placeholders | def _request_remaining_placeholders(
self):
"""
*request remaining placeholders needing populated from the user*
"""
self.log.info(
'starting the ``_request_remaining_placeholders`` method')
phNeeded = False
for k, v in self.phDict.iteritems():
... | python | def _request_remaining_placeholders(
self):
"""
*request remaining placeholders needing populated from the user*
"""
self.log.info(
'starting the ``_request_remaining_placeholders`` method')
phNeeded = False
for k, v in self.phDict.iteritems():
... | [
"def",
"_request_remaining_placeholders",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_request_remaining_placeholders`` method'",
")",
"phNeeded",
"=",
"False",
"for",
"k",
",",
"v",
"in",
"self",
".",
"phDict",
".",
"iteritems",
... | *request remaining placeholders needing populated from the user* | [
"*",
"request",
"remaining",
"placeholders",
"needing",
"populated",
"from",
"the",
"user",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L205-L230 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._populate_placeholders_in_files | def _populate_placeholders_in_files(
self):
"""
*populate placeholders in file names, folder names and content*
"""
self.log.info(
'starting the ``_populate_placeholders_in_files`` method')
rev = reversed(self.directoryContents)
phs = self.setting... | python | def _populate_placeholders_in_files(
self):
"""
*populate placeholders in file names, folder names and content*
"""
self.log.info(
'starting the ``_populate_placeholders_in_files`` method')
rev = reversed(self.directoryContents)
phs = self.setting... | [
"def",
"_populate_placeholders_in_files",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_populate_placeholders_in_files`` method'",
")",
"rev",
"=",
"reversed",
"(",
"self",
".",
"directoryContents",
")",
"phs",
"=",
"self",
".",
"s... | *populate placeholders in file names, folder names and content* | [
"*",
"populate",
"placeholders",
"in",
"file",
"names",
"folder",
"names",
"and",
"content",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L232-L325 |
thespacedoctor/frankenstein | frankenstein/electric.py | electric._move_template_to_destination | def _move_template_to_destination(
self,
ignoreExisting=False):
"""
*move template to destination*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _move_template_to_destination met... | python | def _move_template_to_destination(
self,
ignoreExisting=False):
"""
*move template to destination*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _move_template_to_destination met... | [
"def",
"_move_template_to_destination",
"(",
"self",
",",
"ignoreExisting",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_move_template_to_destination`` method'",
")",
"# CREATE DIRECTORY STRUCTURE",
"sourceDirectories",
"=",
"recursive_dir... | *move template to destination*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _move_template_to_destination method
- @review: when complete add logging | [
"*",
"move",
"template",
"to",
"destination",
"*"
] | train | https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L328-L431 |
scraperwiki/data-services-helpers | dshelpers.py | update_status | def update_status(table_name="swdata", date_column="date"):
"""
Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01'
"""
status_text = 'Latest entry: {}'.format(
_get_most_recent_record(table_name, date_column))
L.info(status_text)
scraperwiki.s... | python | def update_status(table_name="swdata", date_column="date"):
"""
Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01'
"""
status_text = 'Latest entry: {}'.format(
_get_most_recent_record(table_name, date_column))
L.info(status_text)
scraperwiki.s... | [
"def",
"update_status",
"(",
"table_name",
"=",
"\"swdata\"",
",",
"date_column",
"=",
"\"date\"",
")",
":",
"status_text",
"=",
"'Latest entry: {}'",
".",
"format",
"(",
"_get_most_recent_record",
"(",
"table_name",
",",
"date_column",
")",
")",
"L",
".",
"info... | Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01' | [
"Set",
"the",
"status",
"endpoint",
"on",
"ScraperWiki",
"to",
"the",
"latest",
"entry",
"e",
".",
"g",
".",
"Latest",
"entry",
":",
"2013",
"-",
"10",
"-",
"01"
] | train | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L79-L88 |
scraperwiki/data-services-helpers | dshelpers.py | install_cache | def install_cache(expire_after=12 * 3600, cache_post=False):
"""
Patches the requests library with requests_cache.
"""
allowable_methods = ['GET']
if cache_post:
allowable_methods.append('POST')
requests_cache.install_cache(
expire_after=expire_after,
allowable_methods=al... | python | def install_cache(expire_after=12 * 3600, cache_post=False):
"""
Patches the requests library with requests_cache.
"""
allowable_methods = ['GET']
if cache_post:
allowable_methods.append('POST')
requests_cache.install_cache(
expire_after=expire_after,
allowable_methods=al... | [
"def",
"install_cache",
"(",
"expire_after",
"=",
"12",
"*",
"3600",
",",
"cache_post",
"=",
"False",
")",
":",
"allowable_methods",
"=",
"[",
"'GET'",
"]",
"if",
"cache_post",
":",
"allowable_methods",
".",
"append",
"(",
"'POST'",
")",
"requests_cache",
".... | Patches the requests library with requests_cache. | [
"Patches",
"the",
"requests",
"library",
"with",
"requests_cache",
"."
] | train | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L97-L106 |
scraperwiki/data-services-helpers | dshelpers.py | download_url | def download_url(url, back_off=True, **kwargs):
"""
Get the content of a URL and return a file-like object.
back_off=True provides retry
"""
if back_off:
return _download_with_backoff(url, as_file=True, **kwargs)
else:
return _download_without_backoff(url, as_file=True, **kwargs) | python | def download_url(url, back_off=True, **kwargs):
"""
Get the content of a URL and return a file-like object.
back_off=True provides retry
"""
if back_off:
return _download_with_backoff(url, as_file=True, **kwargs)
else:
return _download_without_backoff(url, as_file=True, **kwargs) | [
"def",
"download_url",
"(",
"url",
",",
"back_off",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"back_off",
":",
"return",
"_download_with_backoff",
"(",
"url",
",",
"as_file",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",... | Get the content of a URL and return a file-like object.
back_off=True provides retry | [
"Get",
"the",
"content",
"of",
"a",
"URL",
"and",
"return",
"a",
"file",
"-",
"like",
"object",
".",
"back_off",
"=",
"True",
"provides",
"retry"
] | train | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L109-L117 |
scraperwiki/data-services-helpers | dshelpers.py | _download_without_backoff | def _download_without_backoff(url, as_file=True, method='GET', **kwargs):
"""
Get the content of a URL and return a file-like object.
"""
# Make requests consistently hashable for caching.
# 'headers' is handled by requests itself.
# 'cookies' and 'proxies' contributes to headers.
# 'files' ... | python | def _download_without_backoff(url, as_file=True, method='GET', **kwargs):
"""
Get the content of a URL and return a file-like object.
"""
# Make requests consistently hashable for caching.
# 'headers' is handled by requests itself.
# 'cookies' and 'proxies' contributes to headers.
# 'files' ... | [
"def",
"_download_without_backoff",
"(",
"url",
",",
"as_file",
"=",
"True",
",",
"method",
"=",
"'GET'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make requests consistently hashable for caching.",
"# 'headers' is handled by requests itself.",
"# 'cookies' and 'proxies' contribu... | Get the content of a URL and return a file-like object. | [
"Get",
"the",
"content",
"of",
"a",
"URL",
"and",
"return",
"a",
"file",
"-",
"like",
"object",
"."
] | train | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L137-L177 |
scraperwiki/data-services-helpers | dshelpers.py | _is_url_in_cache | def _is_url_in_cache(*args, **kwargs):
""" Return True if request has been cached or False otherwise. """
# Only include allowed arguments for a PreparedRequest.
allowed_args = inspect.getargspec(
requests.models.PreparedRequest.prepare).args
# self is in there as .prepare() is a method.
all... | python | def _is_url_in_cache(*args, **kwargs):
""" Return True if request has been cached or False otherwise. """
# Only include allowed arguments for a PreparedRequest.
allowed_args = inspect.getargspec(
requests.models.PreparedRequest.prepare).args
# self is in there as .prepare() is a method.
all... | [
"def",
"_is_url_in_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Only include allowed arguments for a PreparedRequest.",
"allowed_args",
"=",
"inspect",
".",
"getargspec",
"(",
"requests",
".",
"models",
".",
"PreparedRequest",
".",
"prepare",
")",... | Return True if request has been cached or False otherwise. | [
"Return",
"True",
"if",
"request",
"has",
"been",
"cached",
"or",
"False",
"otherwise",
"."
] | train | https://github.com/scraperwiki/data-services-helpers/blob/a31ea2f40d20fd99d4c0938b87466330679db2c9/dshelpers.py#L195-L215 |
ulf1/oxyba | oxyba/block_idxmat_sets.py | block_idxmat_sets | def block_idxmat_sets(idxmat, b):
"""Reshapes idxmat into the idx vectors for the training set and validation set
Parameters:
-----------
idxmat : ndarray
Matrix with N shuffled row indicies assigned to K blocks/columns
from the oxyba.block_idxmat_shuffle function
b : int
T... | python | def block_idxmat_sets(idxmat, b):
"""Reshapes idxmat into the idx vectors for the training set and validation set
Parameters:
-----------
idxmat : ndarray
Matrix with N shuffled row indicies assigned to K blocks/columns
from the oxyba.block_idxmat_shuffle function
b : int
T... | [
"def",
"block_idxmat_sets",
"(",
"idxmat",
",",
"b",
")",
":",
"import",
"numpy",
"as",
"np",
"idx_train",
"=",
"idxmat",
"[",
":",
",",
"[",
"c",
"for",
"c",
"in",
"range",
"(",
"idxmat",
".",
"shape",
"[",
"1",
"]",
")",
"if",
"c",
"is",
"not",... | Reshapes idxmat into the idx vectors for the training set and validation set
Parameters:
-----------
idxmat : ndarray
Matrix with N shuffled row indicies assigned to K blocks/columns
from the oxyba.block_idxmat_shuffle function
b : int
The id of the current validation block b=[... | [
"Reshapes",
"idxmat",
"into",
"the",
"idx",
"vectors",
"for",
"the",
"training",
"set",
"and",
"validation",
"set"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/block_idxmat_sets.py#L2-L35 |
markpasc/arghlog | arghlog.py | add_logging | def add_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True):
"""Configures the `argparse.ArgumentParser` with arguments to configure
logging.
This adds arguments:
* ``-v`` to increase the log level
* ``-q`` to decrease the log level
* ``--color`` to enable color logging whe... | python | def add_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True):
"""Configures the `argparse.ArgumentParser` with arguments to configure
logging.
This adds arguments:
* ``-v`` to increase the log level
* ``-q`` to decrease the log level
* ``--color`` to enable color logging whe... | [
"def",
"add_logging",
"(",
"parser",
",",
"log_format",
"=",
"LOG_FORMAT",
",",
"log_level",
"=",
"LOG_LEVEL",
",",
"color",
"=",
"True",
")",
":",
"parser",
".",
"set_defaults",
"(",
"log_level",
"=",
"log_level",
")",
"parser",
".",
"add_argument",
"(",
... | Configures the `argparse.ArgumentParser` with arguments to configure
logging.
This adds arguments:
* ``-v`` to increase the log level
* ``-q`` to decrease the log level
* ``--color`` to enable color logging when available
* ``--no-color`` to disable color logging
The root logger is config... | [
"Configures",
"the",
"argparse",
".",
"ArgumentParser",
"with",
"arguments",
"to",
"configure",
"logging",
"."
] | train | https://github.com/markpasc/arghlog/blob/268c5936922b6b5e1f91acaf0390c1bf85d90dd9/arghlog.py#L77-L133 |
amcfague/webunit2 | webunit2/response.py | HttpResponse.assertHeader | def assertHeader(self, name, value=None, *args, **kwargs):
"""
Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise.
"""
return name in self.raw_headers and (
True if value is None else self.raw... | python | def assertHeader(self, name, value=None, *args, **kwargs):
"""
Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise.
"""
return name in self.raw_headers and (
True if value is None else self.raw... | [
"def",
"assertHeader",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"name",
"in",
"self",
".",
"raw_headers",
"and",
"(",
"True",
"if",
"value",
"is",
"None",
"else",
"self",
".... | Returns `True` if ``name`` was in the headers and, if ``value`` is
True, whether or not the values match, or `False` otherwise. | [
"Returns",
"True",
"if",
"name",
"was",
"in",
"the",
"headers",
"and",
"if",
"value",
"is",
"True",
"whether",
"or",
"not",
"the",
"values",
"match",
"or",
"False",
"otherwise",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/response.py#L59-L65 |
amcfague/webunit2 | webunit2/response.py | HttpResponse.assertNotHeader | def assertNotHeader(self, name, value=None, *args, **kwargs):
""" Negation of :meth:`assertHeader`. """
return not self.assertHeader(name, value) | python | def assertNotHeader(self, name, value=None, *args, **kwargs):
""" Negation of :meth:`assertHeader`. """
return not self.assertHeader(name, value) | [
"def",
"assertNotHeader",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"not",
"self",
".",
"assertHeader",
"(",
"name",
",",
"value",
")"
] | Negation of :meth:`assertHeader`. | [
"Negation",
"of",
":",
"meth",
":",
"assertHeader",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/response.py#L67-L69 |
amcfague/webunit2 | webunit2/response.py | HttpResponse.assertCookie | def assertCookie(self, name, value=None, attrs={}, *args, **kwargs):
"""
Returns `True` if:
- the cookie name appears in the response
- if value is not None, the values are equal
- if any of the attributes match
For example, to check to see if the HttpOnly a... | python | def assertCookie(self, name, value=None, attrs={}, *args, **kwargs):
"""
Returns `True` if:
- the cookie name appears in the response
- if value is not None, the values are equal
- if any of the attributes match
For example, to check to see if the HttpOnly a... | [
"def",
"assertCookie",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"not",
"in",
"self",
".",
... | Returns `True` if:
- the cookie name appears in the response
- if value is not None, the values are equal
- if any of the attributes match
For example, to check to see if the HttpOnly and path attribute are set::
assertCookie("cookie_name", attrs={'HttpOnly': T... | [
"Returns",
"True",
"if",
":"
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/response.py#L71-L95 |
amcfague/webunit2 | webunit2/response.py | HttpResponse.assertNotCookie | def assertNotCookie(self, name, value=None, attrs={}, *args, **kwargs):
""" Negation of :meth:`assertCookie`. """
return not self.assertCookie(name, value, attrs) | python | def assertNotCookie(self, name, value=None, attrs={}, *args, **kwargs):
""" Negation of :meth:`assertCookie`. """
return not self.assertCookie(name, value, attrs) | [
"def",
"assertNotCookie",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"not",
"self",
".",
"assertCookie",
"(",
"name",
",",
"value",
",",
"attrs",
... | Negation of :meth:`assertCookie`. | [
"Negation",
"of",
":",
"meth",
":",
"assertCookie",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/response.py#L97-L99 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.ConfigureLazyWorkers | def ConfigureLazyWorkers(self):
""" Lazy workers are instances that are running and reachable but failed to
register with the cldb to join the mapr cluster. This trys to find these
missing workers and add them to the cluster. """
lazy_worker_instances = self.__GetMissingWorkers()
if not lazy_worke... | python | def ConfigureLazyWorkers(self):
""" Lazy workers are instances that are running and reachable but failed to
register with the cldb to join the mapr cluster. This trys to find these
missing workers and add them to the cluster. """
lazy_worker_instances = self.__GetMissingWorkers()
if not lazy_worke... | [
"def",
"ConfigureLazyWorkers",
"(",
"self",
")",
":",
"lazy_worker_instances",
"=",
"self",
".",
"__GetMissingWorkers",
"(",
")",
"if",
"not",
"lazy_worker_instances",
":",
"return",
"reachable_states",
"=",
"self",
".",
"__AreInstancesReachable",
"(",
"lazy_worker_in... | Lazy workers are instances that are running and reachable but failed to
register with the cldb to join the mapr cluster. This trys to find these
missing workers and add them to the cluster. | [
"Lazy",
"workers",
"are",
"instances",
"that",
"are",
"running",
"and",
"reachable",
"but",
"failed",
"to",
"register",
"with",
"the",
"cldb",
"to",
"join",
"the",
"mapr",
"cluster",
".",
"This",
"trys",
"to",
"find",
"these",
"missing",
"workers",
"and",
... | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L289-L301 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.__StartMaster | def __StartMaster(self):
""" Starts a master node, configures it, and starts services. """
num_masters = len(self.cluster.get_instances_in_role("master", "running"))
assert(num_masters < 1)
logging.info( "waiting for masters to start")
if self.config.master_on_spot_instances:
sel... | python | def __StartMaster(self):
""" Starts a master node, configures it, and starts services. """
num_masters = len(self.cluster.get_instances_in_role("master", "running"))
assert(num_masters < 1)
logging.info( "waiting for masters to start")
if self.config.master_on_spot_instances:
sel... | [
"def",
"__StartMaster",
"(",
"self",
")",
":",
"num_masters",
"=",
"len",
"(",
"self",
".",
"cluster",
".",
"get_instances_in_role",
"(",
"\"master\"",
",",
"\"running\"",
")",
")",
"assert",
"(",
"num_masters",
"<",
"1",
")",
"logging",
".",
"info",
"(",
... | Starts a master node, configures it, and starts services. | [
"Starts",
"a",
"master",
"node",
"configures",
"it",
"and",
"starts",
"services",
"."
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L365-L376 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.__AddWorkers | def __AddWorkers(self, num_to_add):
""" Adds workers evenly across all enabled zones."""
# Check preconditions
assert(self.__IsWebUiReady())
zone_to_ips = self.__GetZoneToWorkerIpsTable()
zone_old_new = []
for zone, ips in zone_to_ips.iteritems():
num_nodes_in_zone = le... | python | def __AddWorkers(self, num_to_add):
""" Adds workers evenly across all enabled zones."""
# Check preconditions
assert(self.__IsWebUiReady())
zone_to_ips = self.__GetZoneToWorkerIpsTable()
zone_old_new = []
for zone, ips in zone_to_ips.iteritems():
num_nodes_in_zone = le... | [
"def",
"__AddWorkers",
"(",
"self",
",",
"num_to_add",
")",
":",
"# Check preconditions",
"assert",
"(",
"self",
".",
"__IsWebUiReady",
"(",
")",
")",
"zone_to_ips",
"=",
"self",
".",
"__GetZoneToWorkerIpsTable",
"(",
")",
"zone_old_new",
"=",
"[",
"]",
"for",... | Adds workers evenly across all enabled zones. | [
"Adds",
"workers",
"evenly",
"across",
"all",
"enabled",
"zones",
"."
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L536-L560 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.__IpsToServerIds | def __IpsToServerIds(self):
""" Get list of mapping of ip address into a server id"""
master_instance = self.__GetMasterInstance()
assert(master_instance)
retval, response = self.__RunMaprCli('node list -columns id')
ip_to_id = {}
for line_num, line in enumerate(response.split('\n')):
toke... | python | def __IpsToServerIds(self):
""" Get list of mapping of ip address into a server id"""
master_instance = self.__GetMasterInstance()
assert(master_instance)
retval, response = self.__RunMaprCli('node list -columns id')
ip_to_id = {}
for line_num, line in enumerate(response.split('\n')):
toke... | [
"def",
"__IpsToServerIds",
"(",
"self",
")",
":",
"master_instance",
"=",
"self",
".",
"__GetMasterInstance",
"(",
")",
"assert",
"(",
"master_instance",
")",
"retval",
",",
"response",
"=",
"self",
".",
"__RunMaprCli",
"(",
"'node list -columns id'",
")",
"ip_t... | Get list of mapping of ip address into a server id | [
"Get",
"list",
"of",
"mapping",
"of",
"ip",
"address",
"into",
"a",
"server",
"id"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L995-L1007 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.__CleanUpCoresAlarm | def __CleanUpCoresAlarm(self):
""" Disable core alarm.
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm... | python | def __CleanUpCoresAlarm(self):
""" Disable core alarm.
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm... | [
"def",
"__CleanUpCoresAlarm",
"(",
"self",
")",
":",
"instances",
"=",
"self",
".",
"__GetAllInstances",
"(",
")",
"clean_cores_cmd",
"=",
"\"\"\"sudo sh -c 'rm /opt/cores/*'\"\"\"",
"self",
".",
"__RunCommandOnInstances",
"(",
"clean_cores_cmd",
",",
"instances",
")",
... | Disable core alarm.
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away. | [
"Disable",
"core",
"alarm",
".",
"Mapr",
"signals",
"an",
"alarm",
"in",
"the",
"web",
"ui",
"when",
"there",
"are",
"files",
"in",
"a",
"nodes",
"/",
"opt",
"/",
"cores",
"dir",
".",
"This",
"is",
"anoying",
"because",
"we",
"can",
"t",
"see",
"if",... | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L1021-L1031 |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | MaprCluster.__CleanUpRootPartition | def __CleanUpRootPartition(self):
"""
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away.
... | python | def __CleanUpRootPartition(self):
"""
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away.
... | [
"def",
"__CleanUpRootPartition",
"(",
"self",
")",
":",
"instances",
"=",
"self",
".",
"__GetAllInstances",
"(",
")",
"clean_cores_cmd",
"=",
"\"\"\"sudo sh -c 'rm -rf /opt/mapr/cache/tmp/*'\"\"\"",
"self",
".",
"__RunCommandOnInstances",
"(",
"clean_cores_cmd",
",",
"ins... | Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away. | [
"Mapr",
"signals",
"an",
"alarm",
"in",
"the",
"web",
"ui",
"when",
"there",
"are",
"files",
"in",
"a",
"nodes",
"/",
"opt",
"/",
"cores",
"dir",
".",
"This",
"is",
"anoying",
"because",
"we",
"can",
"t",
"see",
"if",
"there",
"is",
"a",
"real",
"p... | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L1033-L1043 |
mrallen1/pygett | pygett/files.py | GettFile.contents | def contents(self):
"""
This method downloads the contents of the file represented by a `GettFile` object's metadata.
Input:
* None
Output:
* A byte stream
**NOTE**: You are responsible for handling any encoding/decoding which may be necessary.
... | python | def contents(self):
"""
This method downloads the contents of the file represented by a `GettFile` object's metadata.
Input:
* None
Output:
* A byte stream
**NOTE**: You are responsible for handling any encoding/decoding which may be necessary.
... | [
"def",
"contents",
"(",
"self",
")",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/files/%s/%s/blob\"",
"%",
"(",
"self",
".",
"sharename",
",",
"self",
".",
"fileid",
")",
")",
"return",
"response",
".",
"response"
] | This method downloads the contents of the file represented by a `GettFile` object's metadata.
Input:
* None
Output:
* A byte stream
**NOTE**: You are responsible for handling any encoding/decoding which may be necessary.
Example::
file = client.ge... | [
"This",
"method",
"downloads",
"the",
"contents",
"of",
"the",
"file",
"represented",
"by",
"a",
"GettFile",
"object",
"s",
"metadata",
"."
] | train | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L48-L67 |
mrallen1/pygett | pygett/files.py | GettFile.thumbnail | def thumbnail(self):
"""
This method returns a thumbnail representation of the file if the data is a supported graphics format.
Input:
* None
Output:
* A byte stream representing a thumbnail of a support graphics file
Example::
file = clien... | python | def thumbnail(self):
"""
This method returns a thumbnail representation of the file if the data is a supported graphics format.
Input:
* None
Output:
* A byte stream representing a thumbnail of a support graphics file
Example::
file = clien... | [
"def",
"thumbnail",
"(",
"self",
")",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/files/%s/%s/blob/thumb\"",
"%",
"(",
"self",
".",
"sharename",
",",
"self",
".",
"fileid",
")",
")",
"return",
"response",
".",
"response"
] | This method returns a thumbnail representation of the file if the data is a supported graphics format.
Input:
* None
Output:
* A byte stream representing a thumbnail of a support graphics file
Example::
file = client.get_file("4ddfds", 0)
open(... | [
"This",
"method",
"returns",
"a",
"thumbnail",
"representation",
"of",
"the",
"file",
"if",
"the",
"data",
"is",
"a",
"supported",
"graphics",
"format",
"."
] | train | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L69-L86 |
mrallen1/pygett | pygett/files.py | GettFile.upload_url | def upload_url(self):
"""
This method generates URLs which allow overwriting a file's content with new content. The output is suitable
for use in the ``send_data()`` method below.
Input:
* None
Output:
* A URL (string)
Example::
fil... | python | def upload_url(self):
"""
This method generates URLs which allow overwriting a file's content with new content. The output is suitable
for use in the ``send_data()`` method below.
Input:
* None
Output:
* A URL (string)
Example::
fil... | [
"def",
"upload_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"put_upload_url",
":",
"return",
"self",
".",
"put_upload_url",
"else",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/files/%s/%s/upload?accesstoken=%s\"",
"%",
"(",
"self",
... | This method generates URLs which allow overwriting a file's content with new content. The output is suitable
for use in the ``send_data()`` method below.
Input:
* None
Output:
* A URL (string)
Example::
file = client.get_file("4ddfds", 0)
... | [
"This",
"method",
"generates",
"URLs",
"which",
"allow",
"overwriting",
"a",
"file",
"s",
"content",
"with",
"new",
"content",
".",
"The",
"output",
"is",
"suitable",
"for",
"use",
"in",
"the",
"send_data",
"()",
"method",
"below",
"."
] | train | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L108-L130 |
mrallen1/pygett | pygett/files.py | GettFile.send_data | def send_data(self, **kwargs):
"""
This method transmits data to the Gett service.
Input:
* ``put_url`` A PUT url to use when transmitting the data (required)
* ``data`` A byte stream (required)
Output:
* ``True``
Example::
if f... | python | def send_data(self, **kwargs):
"""
This method transmits data to the Gett service.
Input:
* ``put_url`` A PUT url to use when transmitting the data (required)
* ``data`` A byte stream (required)
Output:
* ``True``
Example::
if f... | [
"def",
"send_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"put_url",
"=",
"None",
"if",
"'put_url'",
"in",
"kwargs",
":",
"put_url",
"=",
"kwargs",
"[",
"'put_url'",
"]",
"else",
":",
"put_url",
"=",
"self",
".",
"put_upload_url",
"if",
"'dat... | This method transmits data to the Gett service.
Input:
* ``put_url`` A PUT url to use when transmitting the data (required)
* ``data`` A byte stream (required)
Output:
* ``True``
Example::
if file.send_data(put_url=file.upload_url, data=open("e... | [
"This",
"method",
"transmits",
"data",
"to",
"the",
"Gett",
"service",
"."
] | train | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L155-L189 |
abhinav/reversible | reversible/generator.py | gen | def gen(function):
"""
Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or via :py:func:`reversible.action`. The... | python | def gen(function):
"""
Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or via :py:func:`reversible.action`. The... | [
"def",
"gen",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"# TODO: use wrapt instead?",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"function",
"(",
"*",
"ar... | Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or via :py:func:`reversible.action`. The decorated
function, when c... | [
"Allows",
"using",
"a",
"generator",
"to",
"chain",
"together",
"reversible",
"actions",
"."
] | train | https://github.com/abhinav/reversible/blob/7e28aaf0390f7d4b889c6ac14d7b340f8f314e89/reversible/generator.py#L64-L153 |
spookey/photon | photon/tools/signal.py | Signal.__signal | def __signal(self, sig, verbose=None):
'''
Helper class preventing code duplication..
:param sig:
Signal to use (e.g. "HUP", "ALRM")
:param verbose:
Overwrite :func:`photon.Photon.m`'s `verbose`
:returns:
|kill_return| with specified `pid`
... | python | def __signal(self, sig, verbose=None):
'''
Helper class preventing code duplication..
:param sig:
Signal to use (e.g. "HUP", "ALRM")
:param verbose:
Overwrite :func:`photon.Photon.m`'s `verbose`
:returns:
|kill_return| with specified `pid`
... | [
"def",
"__signal",
"(",
"self",
",",
"sig",
",",
"verbose",
"=",
"None",
")",
":",
"return",
"self",
".",
"m",
"(",
"'killing process %s with \"%s\"'",
"%",
"(",
"self",
".",
"__pid",
",",
"sig",
")",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'%s k... | Helper class preventing code duplication..
:param sig:
Signal to use (e.g. "HUP", "ALRM")
:param verbose:
Overwrite :func:`photon.Photon.m`'s `verbose`
:returns:
|kill_return| with specified `pid`
.. |kill_return| replace::
:func:`photon.... | [
"Helper",
"class",
"preventing",
"code",
"duplication",
".."
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/signal.py#L56-L75 |
ulf1/oxyba | oxyba/linreg_mle.py | linreg_mle | def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False):
"""MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm ... | python | def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False):
"""MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm ... | [
"def",
"linreg_mle",
"(",
"y",
",",
"X",
",",
"algorithm",
"=",
"'Nelder-Mead'",
",",
"debug",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"stats",
"as",
"sstat",
"import",
"scipy",
".",
"optimize",
"as",
"sopt",
"def... | MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm : str
Optional. Default 'Nelder-Mead' (Simplex).
Th... | [
"MLE",
"for",
"Linear",
"Regression",
"Model"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_mle.py#L2-L59 |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.fill | def fill(self, paths):
"""
Initialise the tree.
paths is a list of strings where each string is the relative path to some
file.
"""
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
b... | python | def fill(self, paths):
"""
Initialise the tree.
paths is a list of strings where each string is the relative path to some
file.
"""
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
b... | [
"def",
"fill",
"(",
"self",
",",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"tree",
"=",
"self",
".",
"tree",
"parts",
"=",
"tuple",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
")",
"dir_parts",
"=",
"parts",
"[",
":",
"-",
"1",
"]",... | Initialise the tree.
paths is a list of strings where each string is the relative path to some
file. | [
"Initialise",
"the",
"tree",
"."
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L59-L80 |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.remove | def remove(self, prefix, name):
"""
Remove a path from the tree
prefix is a tuple of the parts in the dirpath
name is a string representing the name of the file itself.
Any empty folders from the point of the file backwards to the root of
the tree is removed.
"... | python | def remove(self, prefix, name):
"""
Remove a path from the tree
prefix is a tuple of the parts in the dirpath
name is a string representing the name of the file itself.
Any empty folders from the point of the file backwards to the root of
the tree is removed.
"... | [
"def",
"remove",
"(",
"self",
",",
"prefix",
",",
"name",
")",
":",
"tree",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"prefix",
",",
"empty",
")",
"if",
"tree",
"is",
"empty",
":",
"return",
"False",
"if",
"name",
"not",
"in",
"tree",
".",
"fil... | Remove a path from the tree
prefix is a tuple of the parts in the dirpath
name is a string representing the name of the file itself.
Any empty folders from the point of the file backwards to the root of
the tree is removed. | [
"Remove",
"a",
"path",
"from",
"the",
"tree"
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L82-L103 |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.remove_folder | def remove_folder(self, tree, prefix):
"""
Used to remove any empty folders
If this folder is empty then it is removed. If the parent is empty as a
result, then the parent is also removed, and so on.
"""
while True:
child = tree
tree = tree.parent... | python | def remove_folder(self, tree, prefix):
"""
Used to remove any empty folders
If this folder is empty then it is removed. If the parent is empty as a
result, then the parent is also removed, and so on.
"""
while True:
child = tree
tree = tree.parent... | [
"def",
"remove_folder",
"(",
"self",
",",
"tree",
",",
"prefix",
")",
":",
"while",
"True",
":",
"child",
"=",
"tree",
"tree",
"=",
"tree",
".",
"parent",
"if",
"not",
"child",
".",
"folders",
"and",
"not",
"child",
".",
"files",
":",
"del",
"self",
... | Used to remove any empty folders
If this folder is empty then it is removed. If the parent is empty as a
result, then the parent is also removed, and so on. | [
"Used",
"to",
"remove",
"any",
"empty",
"folders"
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L105-L122 |
andrewramsay/sk8-drivers | pysk8/pysk8/util.py | fmt_addr_raw | def fmt_addr_raw(addr, reverse=True):
"""Given a string containing a xx:xx:xx:xx:xx:xx address, return as a byte sequence.
Args:
addr (str): Bluetooth address in xx:xx:xx:xx:xx:xx format.
reverse (bool): True if the byte ordering should be reversed in the output.
Returns:
A bytearr... | python | def fmt_addr_raw(addr, reverse=True):
"""Given a string containing a xx:xx:xx:xx:xx:xx address, return as a byte sequence.
Args:
addr (str): Bluetooth address in xx:xx:xx:xx:xx:xx format.
reverse (bool): True if the byte ordering should be reversed in the output.
Returns:
A bytearr... | [
"def",
"fmt_addr_raw",
"(",
"addr",
",",
"reverse",
"=",
"True",
")",
":",
"addr",
"=",
"addr",
".",
"replace",
"(",
"':'",
",",
"''",
")",
"raw_addr",
"=",
"[",
"int",
"(",
"addr",
"[",
"i",
":",
"i",
"+",
"2",
"]",
",",
"16",
")",
"for",
"i... | Given a string containing a xx:xx:xx:xx:xx:xx address, return as a byte sequence.
Args:
addr (str): Bluetooth address in xx:xx:xx:xx:xx:xx format.
reverse (bool): True if the byte ordering should be reversed in the output.
Returns:
A bytearray containing the converted address. | [
"Given",
"a",
"string",
"containing",
"a",
"xx",
":",
"xx",
":",
"xx",
":",
"xx",
":",
"xx",
":",
"xx",
"address",
"return",
"as",
"a",
"byte",
"sequence",
"."
] | train | https://github.com/andrewramsay/sk8-drivers/blob/67347a71762fb421f5ae65a595def5c7879e8b0c/pysk8/pysk8/util.py#L14-L32 |
andrewramsay/sk8-drivers | pysk8/pysk8/util.py | pp_hex | def pp_hex(raw, reverse=True):
"""Return a pretty-printed (hex style) version of a binary string.
Args:
raw (bytes): any sequence of bytes
reverse (bool): True if output should be in reverse order.
Returns:
Hex string corresponding to input byte sequence.
"""
if not reverse... | python | def pp_hex(raw, reverse=True):
"""Return a pretty-printed (hex style) version of a binary string.
Args:
raw (bytes): any sequence of bytes
reverse (bool): True if output should be in reverse order.
Returns:
Hex string corresponding to input byte sequence.
"""
if not reverse... | [
"def",
"pp_hex",
"(",
"raw",
",",
"reverse",
"=",
"True",
")",
":",
"if",
"not",
"reverse",
":",
"return",
"''",
".",
"join",
"(",
"[",
"'{:02x}'",
".",
"format",
"(",
"v",
")",
"for",
"v",
"in",
"bytearray",
"(",
"raw",
")",
"]",
")",
"return",
... | Return a pretty-printed (hex style) version of a binary string.
Args:
raw (bytes): any sequence of bytes
reverse (bool): True if output should be in reverse order.
Returns:
Hex string corresponding to input byte sequence. | [
"Return",
"a",
"pretty",
"-",
"printed",
"(",
"hex",
"style",
")",
"version",
"of",
"a",
"binary",
"string",
"."
] | train | https://github.com/andrewramsay/sk8-drivers/blob/67347a71762fb421f5ae65a595def5c7879e8b0c/pysk8/pysk8/util.py#L34-L46 |
knagra/farnsworth | workshift/utils.py | can_manage | def can_manage(user, semester=None, pool=None, any_pool=False):
"""
Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers.
"""
if semester and user in semester.workshift_managers.all():
... | python | def can_manage(user, semester=None, pool=None, any_pool=False):
"""
Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers.
"""
if semester and user in semester.workshift_managers.all():
... | [
"def",
"can_manage",
"(",
"user",
",",
"semester",
"=",
"None",
",",
"pool",
"=",
"None",
",",
"any_pool",
"=",
"False",
")",
":",
"if",
"semester",
"and",
"user",
"in",
"semester",
".",
"workshift_managers",
".",
"all",
"(",
")",
":",
"return",
"True"... | Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers. | [
"Whether",
"a",
"user",
"is",
"allowed",
"to",
"manage",
"a",
"workshift",
"semester",
".",
"This",
"includes",
"the",
"current",
"workshift",
"managers",
"that",
"semester",
"s",
"workshift",
"managers",
"and",
"site",
"superusers",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L25-L47 |
knagra/farnsworth | workshift/utils.py | get_year_season | def get_year_season(day=None):
"""
Returns a guess of the year and season of the current semester.
"""
if day is None:
day = date.today()
year = day.year
if day.month > 3 and day.month <= 7:
season = Semester.SUMMER
elif day.month > 7 and day.month <= 10:
season = Se... | python | def get_year_season(day=None):
"""
Returns a guess of the year and season of the current semester.
"""
if day is None:
day = date.today()
year = day.year
if day.month > 3 and day.month <= 7:
season = Semester.SUMMER
elif day.month > 7 and day.month <= 10:
season = Se... | [
"def",
"get_year_season",
"(",
"day",
"=",
"None",
")",
":",
"if",
"day",
"is",
"None",
":",
"day",
"=",
"date",
".",
"today",
"(",
")",
"year",
"=",
"day",
".",
"year",
"if",
"day",
".",
"month",
">",
"3",
"and",
"day",
".",
"month",
"<=",
"7"... | Returns a guess of the year and season of the current semester. | [
"Returns",
"a",
"guess",
"of",
"the",
"year",
"and",
"season",
"of",
"the",
"current",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L50-L66 |
knagra/farnsworth | workshift/utils.py | get_semester_start_end | def get_semester_start_end(year, season):
"""
Returns a guess of the start and end dates for given semester.
"""
if season == Semester.SPRING:
start_month, start_day = 1, 20
end_month, end_day = 5, 17
elif season == Semester.SUMMER:
start_month, start_day = 5, 25
end_... | python | def get_semester_start_end(year, season):
"""
Returns a guess of the start and end dates for given semester.
"""
if season == Semester.SPRING:
start_month, start_day = 1, 20
end_month, end_day = 5, 17
elif season == Semester.SUMMER:
start_month, start_day = 5, 25
end_... | [
"def",
"get_semester_start_end",
"(",
"year",
",",
"season",
")",
":",
"if",
"season",
"==",
"Semester",
".",
"SPRING",
":",
"start_month",
",",
"start_day",
"=",
"1",
",",
"20",
"end_month",
",",
"end_day",
"=",
"5",
",",
"17",
"elif",
"season",
"==",
... | Returns a guess of the start and end dates for given semester. | [
"Returns",
"a",
"guess",
"of",
"the",
"start",
"and",
"end",
"dates",
"for",
"given",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L69-L83 |
knagra/farnsworth | workshift/utils.py | is_available | def is_available(workshift_profile, shift):
"""
Check whether a specified user is able to do a specified workshift.
Parameters:
workshift_profile is the workshift profile for a user
shift is a weekly recurring workshift
Returns:
True if the user has enough free time between the s... | python | def is_available(workshift_profile, shift):
"""
Check whether a specified user is able to do a specified workshift.
Parameters:
workshift_profile is the workshift profile for a user
shift is a weekly recurring workshift
Returns:
True if the user has enough free time between the s... | [
"def",
"is_available",
"(",
"workshift_profile",
",",
"shift",
")",
":",
"if",
"shift",
".",
"week_long",
":",
"return",
"True",
"start_time",
"=",
"(",
"shift",
".",
"start_time",
"if",
"shift",
".",
"start_time",
"is",
"not",
"None",
"else",
"time",
"(",... | Check whether a specified user is able to do a specified workshift.
Parameters:
workshift_profile is the workshift profile for a user
shift is a weekly recurring workshift
Returns:
True if the user has enough free time between the shift's start time
and end time to do the shi... | [
"Check",
"whether",
"a",
"specified",
"user",
"is",
"able",
"to",
"do",
"a",
"specified",
"workshift",
".",
"Parameters",
":",
"workshift_profile",
"is",
"the",
"workshift",
"profile",
"for",
"a",
"user",
"shift",
"is",
"a",
"weekly",
"recurring",
"workshift",... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L357-L429 |
knagra/farnsworth | workshift/utils.py | auto_assign_shifts | def auto_assign_shifts(semester=None, pool=None, profiles=None, shifts=None):
"""
Auto-assigns profiles to regular workshifts.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
profiles : list of workshift.models.WorkshiftPr... | python | def auto_assign_shifts(semester=None, pool=None, profiles=None, shifts=None):
"""
Auto-assigns profiles to regular workshifts.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
profiles : list of workshift.models.WorkshiftPr... | [
"def",
"auto_assign_shifts",
"(",
"semester",
"=",
"None",
",",
"pool",
"=",
"None",
",",
"profiles",
"=",
"None",
",",
"shifts",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
... | Auto-assigns profiles to regular workshifts.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
profiles : list of workshift.models.WorkshiftProfile, optional
shifts : list of workshift.models.RegularWorkshift, optional | [
"Auto",
"-",
"assigns",
"profiles",
"to",
"regular",
"workshifts",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L432-L560 |
knagra/farnsworth | workshift/utils.py | randomly_assign_instances | def randomly_assign_instances(semester, pool, profiles=None, instances=None):
"""
Randomly assigns workshift instances to profiles.
Returns
-------
list of workshift.WorkshiftProfile
list of workshift.WorkshiftInstance
"""
if profiles is None:
profiles = WorkshiftProfile.objects... | python | def randomly_assign_instances(semester, pool, profiles=None, instances=None):
"""
Randomly assigns workshift instances to profiles.
Returns
-------
list of workshift.WorkshiftProfile
list of workshift.WorkshiftInstance
"""
if profiles is None:
profiles = WorkshiftProfile.objects... | [
"def",
"randomly_assign_instances",
"(",
"semester",
",",
"pool",
",",
"profiles",
"=",
"None",
",",
"instances",
"=",
"None",
")",
":",
"if",
"profiles",
"is",
"None",
":",
"profiles",
"=",
"WorkshiftProfile",
".",
"objects",
".",
"filter",
"(",
"semester",... | Randomly assigns workshift instances to profiles.
Returns
-------
list of workshift.WorkshiftProfile
list of workshift.WorkshiftInstance | [
"Randomly",
"assigns",
"workshift",
"instances",
"to",
"profiles",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L563-L629 |
knagra/farnsworth | workshift/utils.py | clear_all_assignments | def clear_all_assignments(semester=None, pool=None, shifts=None):
"""
Clears all regular workshift assignments.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
If set, grab workshifts from a specific pool. Otherwise, t... | python | def clear_all_assignments(semester=None, pool=None, shifts=None):
"""
Clears all regular workshift assignments.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
If set, grab workshifts from a specific pool. Otherwise, t... | [
"def",
"clear_all_assignments",
"(",
"semester",
"=",
"None",
",",
"pool",
"=",
"None",
",",
"shifts",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
"get",
"(",
"current",
"=",... | Clears all regular workshift assignments.
Parameters
----------
semester : workshift.models.Semester, optional
pool : workshift.models.WorkshiftPool, optional
If set, grab workshifts from a specific pool. Otherwise, the primary
workshift pool will be used.
shifts : list of workshift... | [
"Clears",
"all",
"regular",
"workshift",
"assignments",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L632-L662 |
knagra/farnsworth | workshift/utils.py | update_standings | def update_standings(semester=None, pool_hours=None, moment=None):
"""
This function acts to update a list of PoolHours objects to adjust their
current standing based on the time in the semester.
Parameters
----------
semester : workshift.models.Semester, optional
pool_hours : list of works... | python | def update_standings(semester=None, pool_hours=None, moment=None):
"""
This function acts to update a list of PoolHours objects to adjust their
current standing based on the time in the semester.
Parameters
----------
semester : workshift.models.Semester, optional
pool_hours : list of works... | [
"def",
"update_standings",
"(",
"semester",
"=",
"None",
",",
"pool_hours",
"=",
"None",
",",
"moment",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
"get",
"(",
"current",
"="... | This function acts to update a list of PoolHours objects to adjust their
current standing based on the time in the semester.
Parameters
----------
semester : workshift.models.Semester, optional
pool_hours : list of workshift.models.PoolHours, optional
If None, runs on all pool hours for sem... | [
"This",
"function",
"acts",
"to",
"update",
"a",
"list",
"of",
"PoolHours",
"objects",
"to",
"adjust",
"their",
"current",
"standing",
"based",
"on",
"the",
"time",
"in",
"the",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L665-L703 |
knagra/farnsworth | workshift/utils.py | reset_standings | def reset_standings(semester=None, pool_hours=None):
"""
Utility function to recalculate workshift standings. This function is meant
to only be called from the manager shell, it is not referenced anywhere
else in the workshift module.
Parameters
----------
semester : workshift.models.Semest... | python | def reset_standings(semester=None, pool_hours=None):
"""
Utility function to recalculate workshift standings. This function is meant
to only be called from the manager shell, it is not referenced anywhere
else in the workshift module.
Parameters
----------
semester : workshift.models.Semest... | [
"def",
"reset_standings",
"(",
"semester",
"=",
"None",
",",
"pool_hours",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
"get",
"(",
"current",
"=",
"True",
")",
"except",
"(",... | Utility function to recalculate workshift standings. This function is meant
to only be called from the manager shell, it is not referenced anywhere
else in the workshift module.
Parameters
----------
semester : workshift.models.Semester, optional
pool_hours : list of workshift.models.PoolHours,... | [
"Utility",
"function",
"to",
"recalculate",
"workshift",
"standings",
".",
"This",
"function",
"is",
"meant",
"to",
"only",
"be",
"called",
"from",
"the",
"manager",
"shell",
"it",
"is",
"not",
"referenced",
"anywhere",
"else",
"in",
"the",
"workshift",
"modul... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L706-L748 |
knagra/farnsworth | workshift/utils.py | calculate_assigned_hours | def calculate_assigned_hours(semester=None, profiles=None):
"""
Utility function to recalculate the assigned workshift hours. This function
is meant to only be called from the manager shell, it is not referenced
anywhere else in the workshift module.
Parameters
----------
semester : workshi... | python | def calculate_assigned_hours(semester=None, profiles=None):
"""
Utility function to recalculate the assigned workshift hours. This function
is meant to only be called from the manager shell, it is not referenced
anywhere else in the workshift module.
Parameters
----------
semester : workshi... | [
"def",
"calculate_assigned_hours",
"(",
"semester",
"=",
"None",
",",
"profiles",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
"get",
"(",
"current",
"=",
"True",
")",
"except",... | Utility function to recalculate the assigned workshift hours. This function
is meant to only be called from the manager shell, it is not referenced
anywhere else in the workshift module.
Parameters
----------
semester : workshift.models.Semester, optional
profiles : list of workshift.models.Wor... | [
"Utility",
"function",
"to",
"recalculate",
"the",
"assigned",
"workshift",
"hours",
".",
"This",
"function",
"is",
"meant",
"to",
"only",
"be",
"called",
"from",
"the",
"manager",
"shell",
"it",
"is",
"not",
"referenced",
"anywhere",
"else",
"in",
"the",
"w... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L751-L778 |
knagra/farnsworth | workshift/utils.py | reset_instance_assignments | def reset_instance_assignments(semester=None, shifts=None):
"""
Utility function to reset instance assignments. This function is meant to
only be called from the manager shell, it is not referenced anywhere else
in the workshift module.
Parameters
----------
semester : workshift.models.Seme... | python | def reset_instance_assignments(semester=None, shifts=None):
"""
Utility function to reset instance assignments. This function is meant to
only be called from the manager shell, it is not referenced anywhere else
in the workshift module.
Parameters
----------
semester : workshift.models.Seme... | [
"def",
"reset_instance_assignments",
"(",
"semester",
"=",
"None",
",",
"shifts",
"=",
"None",
")",
":",
"if",
"semester",
"is",
"None",
":",
"try",
":",
"semester",
"=",
"Semester",
".",
"objects",
".",
"get",
"(",
"current",
"=",
"True",
")",
"except",... | Utility function to reset instance assignments. This function is meant to
only be called from the manager shell, it is not referenced anywhere else
in the workshift module.
Parameters
----------
semester : workshift.models.Semester, optional
shifts : list of workshift.models.RegularWorkshift, o... | [
"Utility",
"function",
"to",
"reset",
"instance",
"assignments",
".",
"This",
"function",
"is",
"meant",
"to",
"only",
"be",
"called",
"from",
"the",
"manager",
"shell",
"it",
"is",
"not",
"referenced",
"anywhere",
"else",
"in",
"the",
"workshift",
"module",
... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/utils.py#L781-L829 |
xtrementl/focus | focus/daemon.py | pid_exists | def pid_exists(pid):
""" Determines if a system process identifer exists in process table.
"""
try:
os.kill(pid, 0)
except OSError as exc:
return exc.errno == errno.EPERM
else:
return True | python | def pid_exists(pid):
""" Determines if a system process identifer exists in process table.
"""
try:
os.kill(pid, 0)
except OSError as exc:
return exc.errno == errno.EPERM
else:
return True | [
"def",
"pid_exists",
"(",
"pid",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"0",
")",
"except",
"OSError",
"as",
"exc",
":",
"return",
"exc",
".",
"errno",
"==",
"errno",
".",
"EPERM",
"else",
":",
"return",
"True"
] | Determines if a system process identifer exists in process table. | [
"Determines",
"if",
"a",
"system",
"process",
"identifer",
"exists",
"in",
"process",
"table",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L54-L62 |
xtrementl/focus | focus/daemon.py | daemonize | def daemonize(pid_file, working_dir, func):
""" Turns the current process into a daemon.
`pid_file`
File path to use as pid lock file for daemon.
`working_dir`
Working directory to switch to when daemon starts.
`func`
Callable to run after daemon is forke... | python | def daemonize(pid_file, working_dir, func):
""" Turns the current process into a daemon.
`pid_file`
File path to use as pid lock file for daemon.
`working_dir`
Working directory to switch to when daemon starts.
`func`
Callable to run after daemon is forke... | [
"def",
"daemonize",
"(",
"pid_file",
",",
"working_dir",
",",
"func",
")",
":",
"def",
"_fork",
"(",
")",
":",
"\"\"\" Fork a child process.\n\n Returns ``False`` if fork failed; otherwise,\n we are inside the new child process.\n \"\"\"",
"try",
":... | Turns the current process into a daemon.
`pid_file`
File path to use as pid lock file for daemon.
`working_dir`
Working directory to switch to when daemon starts.
`func`
Callable to run after daemon is forked. | [
"Turns",
"the",
"current",
"process",
"into",
"a",
"daemon",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L65-L141 |
xtrementl/focus | focus/daemon.py | shell_focusd | def shell_focusd(data_dir):
""" Shells a new instance of a focusd daemon process.
`data_dir`
Home directory for focusd data.
Returns boolean.
* Raises ``ValueError`` if sudo used and all passwords tries failed.
"""
command = 'focusd {0}'.format(data_dir)
# se... | python | def shell_focusd(data_dir):
""" Shells a new instance of a focusd daemon process.
`data_dir`
Home directory for focusd data.
Returns boolean.
* Raises ``ValueError`` if sudo used and all passwords tries failed.
"""
command = 'focusd {0}'.format(data_dir)
# se... | [
"def",
"shell_focusd",
"(",
"data_dir",
")",
":",
"command",
"=",
"'focusd {0}'",
".",
"format",
"(",
"data_dir",
")",
"# see what event hook plugins are registered",
"plugins",
"=",
"registration",
".",
"get_registered",
"(",
"event_hooks",
"=",
"True",
")",
"if",
... | Shells a new instance of a focusd daemon process.
`data_dir`
Home directory for focusd data.
Returns boolean.
* Raises ``ValueError`` if sudo used and all passwords tries failed. | [
"Shells",
"a",
"new",
"instance",
"of",
"a",
"focusd",
"daemon",
"process",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L144-L178 |
xtrementl/focus | focus/daemon.py | focusd | def focusd(task):
""" Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run.
"""
# determine if command server should be started
if registration.get_registered(event_hooks=True, root_access=True):
# root event plugins availabl... | python | def focusd(task):
""" Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run.
"""
# determine if command server should be started
if registration.get_registered(event_hooks=True, root_access=True):
# root event plugins availabl... | [
"def",
"focusd",
"(",
"task",
")",
":",
"# determine if command server should be started",
"if",
"registration",
".",
"get_registered",
"(",
"event_hooks",
"=",
"True",
",",
"root_access",
"=",
"True",
")",
":",
"# root event plugins available",
"start_cmd_srv",
"=",
... | Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run. | [
"Forks",
"the",
"current",
"process",
"as",
"a",
"daemon",
"to",
"run",
"a",
"task",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L181-L197 |
xtrementl/focus | focus/daemon.py | Focusd._reg_sighandlers | def _reg_sighandlers(self):
""" Registers signal handlers to this class.
"""
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) | python | def _reg_sighandlers(self):
""" Registers signal handlers to this class.
"""
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) | [
"def",
"_reg_sighandlers",
"(",
"self",
")",
":",
"# SIGCHLD, so we shutdown when any of the child processes exit",
"_handler",
"=",
"lambda",
"signo",
",",
"frame",
":",
"self",
".",
"shutdown",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGCHLD",
",... | Registers signal handlers to this class. | [
"Registers",
"signal",
"handlers",
"to",
"this",
"class",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L219-L226 |
xtrementl/focus | focus/daemon.py | Focusd._drop_privs | def _drop_privs(self):
""" Reduces effective privileges for this process to that of the task
owner. The umask and environment variables are also modified to
recreate the environment of the user.
"""
uid = self._task.owner
# get pwd database info for task own... | python | def _drop_privs(self):
""" Reduces effective privileges for this process to that of the task
owner. The umask and environment variables are also modified to
recreate the environment of the user.
"""
uid = self._task.owner
# get pwd database info for task own... | [
"def",
"_drop_privs",
"(",
"self",
")",
":",
"uid",
"=",
"self",
".",
"_task",
".",
"owner",
"# get pwd database info for task owner",
"try",
":",
"pwd_info",
"=",
"pwd",
".",
"getpwuid",
"(",
"uid",
")",
"except",
"OSError",
":",
"pwd_info",
"=",
"None",
... | Reduces effective privileges for this process to that of the task
owner. The umask and environment variables are also modified to
recreate the environment of the user. | [
"Reduces",
"effective",
"privileges",
"for",
"this",
"process",
"to",
"that",
"of",
"the",
"task",
"owner",
".",
"The",
"umask",
"and",
"environment",
"variables",
"are",
"also",
"modified",
"to",
"recreate",
"the",
"environment",
"of",
"the",
"user",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L228-L295 |
xtrementl/focus | focus/daemon.py | Focusd.shutdown | def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command... | python | def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_exited",
":",
"self",
".",
"_exited",
"=",
"True",
"# signal task runner to terminate via SIGTERM",
"if",
"self",
".",
"_task_runner",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_task_r... | Shuts down the daemon process. | [
"Shuts",
"down",
"the",
"daemon",
"process",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L297-L316 |
xtrementl/focus | focus/daemon.py | Focusd.run | def run(self, start_command_srv):
""" Setup daemon process, start child forks, and sleep until
events are signalled.
`start_command_srv`
Set to ``True`` if command server should be started.
"""
if start_command_srv:
# note, this must be e... | python | def run(self, start_command_srv):
""" Setup daemon process, start child forks, and sleep until
events are signalled.
`start_command_srv`
Set to ``True`` if command server should be started.
"""
if start_command_srv:
# note, this must be e... | [
"def",
"run",
"(",
"self",
",",
"start_command_srv",
")",
":",
"if",
"start_command_srv",
":",
"# note, this must be established *before* the task runner is forked",
"# so the task runner can communicate with the command server.",
"# fork the command server",
"self",
".",
"_command_s... | Setup daemon process, start child forks, and sleep until
events are signalled.
`start_command_srv`
Set to ``True`` if command server should be started. | [
"Setup",
"daemon",
"process",
"start",
"child",
"forks",
"and",
"sleep",
"until",
"events",
"are",
"signalled",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L318-L348 |
xtrementl/focus | focus/daemon.py | Focusd.running | def running(self):
""" Determines if daemon is active.
Returns boolean.
"""
# check if task is active and pid file exists
return (not self._exited and os.path.isfile(self._pidfile)
and self._task.active) | python | def running(self):
""" Determines if daemon is active.
Returns boolean.
"""
# check if task is active and pid file exists
return (not self._exited and os.path.isfile(self._pidfile)
and self._task.active) | [
"def",
"running",
"(",
"self",
")",
":",
"# check if task is active and pid file exists",
"return",
"(",
"not",
"self",
".",
"_exited",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_pidfile",
")",
"and",
"self",
".",
"_task",
".",
"active",
... | Determines if daemon is active.
Returns boolean. | [
"Determines",
"if",
"daemon",
"is",
"active",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L351-L359 |
xtrementl/focus | focus/daemon.py | TaskProcess._register_sigterm | def _register_sigterm(self):
""" Registers SIGTERM signal handler.
"""
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGTERM, _handler) | python | def _register_sigterm(self):
""" Registers SIGTERM signal handler.
"""
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGTERM, _handler) | [
"def",
"_register_sigterm",
"(",
"self",
")",
":",
"_handler",
"=",
"lambda",
"signo",
",",
"frame",
":",
"self",
".",
"shutdown",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"_handler",
")"
] | Registers SIGTERM signal handler. | [
"Registers",
"SIGTERM",
"signal",
"handler",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L382-L387 |
xtrementl/focus | focus/daemon.py | TaskProcess.run | def run(self):
""" Main process loop.
"""
self._prepare()
while self.running:
if self._run() is False:
break
time.sleep(self._sleep_period)
self.shutdown() | python | def run(self):
""" Main process loop.
"""
self._prepare()
while self.running:
if self._run() is False:
break
time.sleep(self._sleep_period)
self.shutdown() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_prepare",
"(",
")",
"while",
"self",
".",
"running",
":",
"if",
"self",
".",
"_run",
"(",
")",
"is",
"False",
":",
"break",
"time",
".",
"sleep",
"(",
"self",
".",
"_sleep_period",
")",
"self",
... | Main process loop. | [
"Main",
"process",
"loop",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L401-L412 |
xtrementl/focus | focus/daemon.py | TaskProcess.shutdown | def shutdown(self):
""" Shuts down the process.
"""
if not self._exited:
self._exited = True
_shutdown_pipe(self._pipe)
self._task.stop()
raise SystemExit | python | def shutdown(self):
""" Shuts down the process.
"""
if not self._exited:
self._exited = True
_shutdown_pipe(self._pipe)
self._task.stop()
raise SystemExit | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_exited",
":",
"self",
".",
"_exited",
"=",
"True",
"_shutdown_pipe",
"(",
"self",
".",
"_pipe",
")",
"self",
".",
"_task",
".",
"stop",
"(",
")",
"raise",
"SystemExit"
] | Shuts down the process. | [
"Shuts",
"down",
"the",
"process",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L414-L422 |
xtrementl/focus | focus/daemon.py | TaskRunner._setup_root_plugins | def _setup_root_plugins(self):
""" Injects a `run_root` method into the registered root event plugins.
"""
def run_root(_self, command):
""" Executes a shell command as root.
`command`
Shell command string.
Returns boolean.
... | python | def _setup_root_plugins(self):
""" Injects a `run_root` method into the registered root event plugins.
"""
def run_root(_self, command):
""" Executes a shell command as root.
`command`
Shell command string.
Returns boolean.
... | [
"def",
"_setup_root_plugins",
"(",
"self",
")",
":",
"def",
"run_root",
"(",
"_self",
",",
"command",
")",
":",
"\"\"\" Executes a shell command as root.\n\n `command`\n Shell command string.\n\n Returns boolean.\n \"\"\"",
... | Injects a `run_root` method into the registered root event plugins. | [
"Injects",
"a",
"run_root",
"method",
"into",
"the",
"registered",
"root",
"event",
"plugins",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L447-L483 |
xtrementl/focus | focus/daemon.py | TaskRunner._run_events | def _run_events(self, shutdown=False):
""" Runs event hooks for registered event plugins.
`shutdown`
Set to ``True`` to run task_end events;
otherwise, run task_run events.
"""
# run task_start events, if not ran already
if not self._ran_... | python | def _run_events(self, shutdown=False):
""" Runs event hooks for registered event plugins.
`shutdown`
Set to ``True`` to run task_end events;
otherwise, run task_run events.
"""
# run task_start events, if not ran already
if not self._ran_... | [
"def",
"_run_events",
"(",
"self",
",",
"shutdown",
"=",
"False",
")",
":",
"# run task_start events, if not ran already",
"if",
"not",
"self",
".",
"_ran_taskstart",
":",
"self",
".",
"_ran_taskstart",
"=",
"True",
"registration",
".",
"run_event_hooks",
"(",
"'t... | Runs event hooks for registered event plugins.
`shutdown`
Set to ``True`` to run task_end events;
otherwise, run task_run events. | [
"Runs",
"event",
"hooks",
"for",
"registered",
"event",
"plugins",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L485-L506 |
xtrementl/focus | focus/daemon.py | TaskRunner._prepare | def _prepare(self):
""" Setup initial requirements for daemon run.
"""
super(TaskRunner, self)._prepare()
self._setup_root_plugins()
# set the default x-window display for non-mac systems
if not sys.platform.lower().startswith('darwin'):
if not 'DISPLAY'... | python | def _prepare(self):
""" Setup initial requirements for daemon run.
"""
super(TaskRunner, self)._prepare()
self._setup_root_plugins()
# set the default x-window display for non-mac systems
if not sys.platform.lower().startswith('darwin'):
if not 'DISPLAY'... | [
"def",
"_prepare",
"(",
"self",
")",
":",
"super",
"(",
"TaskRunner",
",",
"self",
")",
".",
"_prepare",
"(",
")",
"self",
".",
"_setup_root_plugins",
"(",
")",
"# set the default x-window display for non-mac systems",
"if",
"not",
"sys",
".",
"platform",
".",
... | Setup initial requirements for daemon run. | [
"Setup",
"initial",
"requirements",
"for",
"daemon",
"run",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L508-L518 |
xtrementl/focus | focus/daemon.py | TaskRunner.shutdown | def shutdown(self, skip_hooks=False):
""" Shuts down the process.
`skip_hooks`
Set to ``True`` to skip running task end event plugins.
"""
if not self._exited:
self._exited = True
if not skip_hooks:
self._run_events(shutd... | python | def shutdown(self, skip_hooks=False):
""" Shuts down the process.
`skip_hooks`
Set to ``True`` to skip running task end event plugins.
"""
if not self._exited:
self._exited = True
if not skip_hooks:
self._run_events(shutd... | [
"def",
"shutdown",
"(",
"self",
",",
"skip_hooks",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_exited",
":",
"self",
".",
"_exited",
"=",
"True",
"if",
"not",
"skip_hooks",
":",
"self",
".",
"_run_events",
"(",
"shutdown",
"=",
"True",
")",
"... | Shuts down the process.
`skip_hooks`
Set to ``True`` to skip running task end event plugins. | [
"Shuts",
"down",
"the",
"process",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L530-L545 |
xtrementl/focus | focus/daemon.py | CommandServer._process_commands | def _process_commands(self):
""" Processes commands received and executes them accordingly.
Returns ``True`` if successful, ``False`` if connection closed or
server terminated.
"""
try:
# poll for data, so we don't block forever
if self._cmd_p... | python | def _process_commands(self):
""" Processes commands received and executes them accordingly.
Returns ``True`` if successful, ``False`` if connection closed or
server terminated.
"""
try:
# poll for data, so we don't block forever
if self._cmd_p... | [
"def",
"_process_commands",
"(",
"self",
")",
":",
"try",
":",
"# poll for data, so we don't block forever",
"if",
"self",
".",
"_cmd_pipe",
".",
"poll",
"(",
"1",
")",
":",
"# 1 sec timeout",
"payload",
"=",
"self",
".",
"_cmd_pipe",
".",
"recv_bytes",
"(",
"... | Processes commands received and executes them accordingly.
Returns ``True`` if successful, ``False`` if connection closed or
server terminated. | [
"Processes",
"commands",
"received",
"and",
"executes",
"them",
"accordingly",
".",
"Returns",
"True",
"if",
"successful",
"False",
"if",
"connection",
"closed",
"or",
"server",
"terminated",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L557-L596 |
xtrementl/focus | focus/daemon.py | CommandServer._prepare | def _prepare(self):
""" Setup initial requirements for daemon run.
"""
super(CommandServer, self)._prepare()
# unregister all active plugins
for plugin in registration.get_registered():
registration.disable_plugin_instance(plugin) | python | def _prepare(self):
""" Setup initial requirements for daemon run.
"""
super(CommandServer, self)._prepare()
# unregister all active plugins
for plugin in registration.get_registered():
registration.disable_plugin_instance(plugin) | [
"def",
"_prepare",
"(",
"self",
")",
":",
"super",
"(",
"CommandServer",
",",
"self",
")",
".",
"_prepare",
"(",
")",
"# unregister all active plugins",
"for",
"plugin",
"in",
"registration",
".",
"get_registered",
"(",
")",
":",
"registration",
".",
"disable_... | Setup initial requirements for daemon run. | [
"Setup",
"initial",
"requirements",
"for",
"daemon",
"run",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L598-L606 |
fotonauts/fwissr-python | fwissr/source/mongodb.py | Mongodb.from_settings | def from_settings(cls, settings):
"""Read Mongodb Source configuration from the provided settings"""
if not 'mongodb' in settings or not 'collection' in settings or \
settings['mongodb'] == '' or settings['collection'] == '':
raise Exception(
"Erroneous mongod... | python | def from_settings(cls, settings):
"""Read Mongodb Source configuration from the provided settings"""
if not 'mongodb' in settings or not 'collection' in settings or \
settings['mongodb'] == '' or settings['collection'] == '':
raise Exception(
"Erroneous mongod... | [
"def",
"from_settings",
"(",
"cls",
",",
"settings",
")",
":",
"if",
"not",
"'mongodb'",
"in",
"settings",
"or",
"not",
"'collection'",
"in",
"settings",
"or",
"settings",
"[",
"'mongodb'",
"]",
"==",
"''",
"or",
"settings",
"[",
"'collection'",
"]",
"==",... | Read Mongodb Source configuration from the provided settings | [
"Read",
"Mongodb",
"Source",
"configuration",
"from",
"the",
"provided",
"settings"
] | train | https://github.com/fotonauts/fwissr-python/blob/4314aa53ca45b4534cd312f6343a88596b4416d4/fwissr/source/mongodb.py#L14-L44 |
fred49/linshare-api | linshareapi/cache.py | compute_key | def compute_key(cli, familly, discriminant=None):
"""This function is used to compute a unique key from all connection parametters."""
hash_key = hashlib.sha256()
hash_key.update(familly)
hash_key.update(cli.host)
hash_key.update(cli.user)
hash_key.update(cli.password)
if discriminant:
... | python | def compute_key(cli, familly, discriminant=None):
"""This function is used to compute a unique key from all connection parametters."""
hash_key = hashlib.sha256()
hash_key.update(familly)
hash_key.update(cli.host)
hash_key.update(cli.user)
hash_key.update(cli.password)
if discriminant:
... | [
"def",
"compute_key",
"(",
"cli",
",",
"familly",
",",
"discriminant",
"=",
"None",
")",
":",
"hash_key",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"hash_key",
".",
"update",
"(",
"familly",
")",
"hash_key",
".",
"update",
"(",
"cli",
".",
"host",
")",
... | This function is used to compute a unique key from all connection parametters. | [
"This",
"function",
"is",
"used",
"to",
"compute",
"a",
"unique",
"key",
"from",
"all",
"connection",
"parametters",
"."
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/cache.py#L18-L38 |
fred49/linshare-api | linshareapi/cache.py | Invalid.override_familly | def override_familly(self, args):
"""Look in the current wrapped object to find a cache configuration to
override the current default configuration."""
resourceapi = args[0]
cache_cfg = resourceapi.cache
if cache_cfg.has_key('familly'):
self.familly = cache_cfg['famil... | python | def override_familly(self, args):
"""Look in the current wrapped object to find a cache configuration to
override the current default configuration."""
resourceapi = args[0]
cache_cfg = resourceapi.cache
if cache_cfg.has_key('familly'):
self.familly = cache_cfg['famil... | [
"def",
"override_familly",
"(",
"self",
",",
"args",
")",
":",
"resourceapi",
"=",
"args",
"[",
"0",
"]",
"cache_cfg",
"=",
"resourceapi",
".",
"cache",
"if",
"cache_cfg",
".",
"has_key",
"(",
"'familly'",
")",
":",
"self",
".",
"familly",
"=",
"cache_cf... | Look in the current wrapped object to find a cache configuration to
override the current default configuration. | [
"Look",
"in",
"the",
"current",
"wrapped",
"object",
"to",
"find",
"a",
"cache",
"configuration",
"to",
"override",
"the",
"current",
"default",
"configuration",
"."
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/cache.py#L117-L127 |
jmgilman/Neolib | neolib/HTMLFilter.py | HTMLFilter.handleHTML | def handleHTML(self, record):
""" Saves the given record's page content to a .html file
Attributes
record (Record) -- The log record
"""
# Create a unique file name to identify where this HTML source is coming from
fileName = datetime.today().strftime("Neolib ... | python | def handleHTML(self, record):
""" Saves the given record's page content to a .html file
Attributes
record (Record) -- The log record
"""
# Create a unique file name to identify where this HTML source is coming from
fileName = datetime.today().strftime("Neolib ... | [
"def",
"handleHTML",
"(",
"self",
",",
"record",
")",
":",
"# Create a unique file name to identify where this HTML source is coming from",
"fileName",
"=",
"datetime",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"\"Neolib %Y-%m-%d %H-%M-%S \"",
")",
"+",
"record",
".... | Saves the given record's page content to a .html file
Attributes
record (Record) -- The log record | [
"Saves",
"the",
"given",
"record",
"s",
"page",
"content",
"to",
"a",
".",
"html",
"file",
"Attributes",
"record",
"(",
"Record",
")",
"--",
"The",
"log",
"record"
] | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/HTMLFilter.py#L31-L53 |
djangothon/ab | ab/utils.py | function_from_string | def function_from_string(func_string):
"""
Returns a function object from the function string.
:param the string which needs to be resolved.
"""
func = None
func_string_splitted = func_string.split('.')
module_name = '.'.join(func_string_splitted[:-1])
function_name = func_string_splitt... | python | def function_from_string(func_string):
"""
Returns a function object from the function string.
:param the string which needs to be resolved.
"""
func = None
func_string_splitted = func_string.split('.')
module_name = '.'.join(func_string_splitted[:-1])
function_name = func_string_splitt... | [
"def",
"function_from_string",
"(",
"func_string",
")",
":",
"func",
"=",
"None",
"func_string_splitted",
"=",
"func_string",
".",
"split",
"(",
"'.'",
")",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"func_string_splitted",
"[",
":",
"-",
"1",
"]",
")",
... | Returns a function object from the function string.
:param the string which needs to be resolved. | [
"Returns",
"a",
"function",
"object",
"from",
"the",
"function",
"string",
".",
":",
"param",
"the",
"string",
"which",
"needs",
"to",
"be",
"resolved",
"."
] | train | https://github.com/djangothon/ab/blob/2075d27805ad94b11535a11439027ce8d0c8ab83/ab/utils.py#L4-L17 |
etcher-be/elib_config | elib_config/_utils.py | friendly_type_name | def friendly_type_name(raw_type: typing.Type) -> str:
"""
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
"""
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error('unmanaged value type: %s', raw... | python | def friendly_type_name(raw_type: typing.Type) -> str:
"""
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
"""
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error('unmanaged value type: %s', raw... | [
"def",
"friendly_type_name",
"(",
"raw_type",
":",
"typing",
".",
"Type",
")",
"->",
"str",
":",
"try",
":",
"return",
"_TRANSLATE_TYPE",
"[",
"raw_type",
"]",
"except",
"KeyError",
":",
"LOGGER",
".",
"error",
"(",
"'unmanaged value type: %s'",
",",
"raw_type... | Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string | [
"Returns",
"a",
"user",
"-",
"friendly",
"type",
"name"
] | train | https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_utils.py#L28-L39 |
smartmob-project/dotenvfile | dotenvfile/__init__.py | loads | def loads(content):
"""Loads variable definitions from a string."""
lines = _group_lines(line for line in content.split('\n'))
lines = [
(i, _parse_envfile_line(line))
for i, line in lines if line.strip()
]
errors = []
# Reject files with duplicate variables (no sane default).
... | python | def loads(content):
"""Loads variable definitions from a string."""
lines = _group_lines(line for line in content.split('\n'))
lines = [
(i, _parse_envfile_line(line))
for i, line in lines if line.strip()
]
errors = []
# Reject files with duplicate variables (no sane default).
... | [
"def",
"loads",
"(",
"content",
")",
":",
"lines",
"=",
"_group_lines",
"(",
"line",
"for",
"line",
"in",
"content",
".",
"split",
"(",
"'\\n'",
")",
")",
"lines",
"=",
"[",
"(",
"i",
",",
"_parse_envfile_line",
"(",
"line",
")",
")",
"for",
"i",
"... | Loads variable definitions from a string. | [
"Loads",
"variable",
"definitions",
"from",
"a",
"string",
"."
] | train | https://github.com/smartmob-project/dotenvfile/blob/8a71eddfe73669c8fcd97a0062845257753ad85a/dotenvfile/__init__.py#L73-L92 |
Vesuvium/aratrum | aratrum/Aratrum.py | Aratrum.get | def get(self):
"""
Loads the configuration and returns it as a dictionary
"""
with open(self.filename, 'r') as f:
self.config = ujson.load(f)
return self.config | python | def get(self):
"""
Loads the configuration and returns it as a dictionary
"""
with open(self.filename, 'r') as f:
self.config = ujson.load(f)
return self.config | [
"def",
"get",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"config",
"=",
"ujson",
".",
"load",
"(",
"f",
")",
"return",
"self",
".",
"config"
] | Loads the configuration and returns it as a dictionary | [
"Loads",
"the",
"configuration",
"and",
"returns",
"it",
"as",
"a",
"dictionary"
] | train | https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L17-L23 |
Vesuvium/aratrum | aratrum/Aratrum.py | Aratrum.set | def set(self, option, value):
"""
Sets an option to a value.
"""
if self.config is None:
self.config = {}
self.config[option] = value | python | def set(self, option, value):
"""
Sets an option to a value.
"""
if self.config is None:
self.config = {}
self.config[option] = value | [
"def",
"set",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"if",
"self",
".",
"config",
"is",
"None",
":",
"self",
".",
"config",
"=",
"{",
"}",
"self",
".",
"config",
"[",
"option",
"]",
"=",
"value"
] | Sets an option to a value. | [
"Sets",
"an",
"option",
"to",
"a",
"value",
"."
] | train | https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L31-L37 |
Vesuvium/aratrum | aratrum/Aratrum.py | Aratrum.delete | def delete(self, option):
"""
Deletes an option if exists
"""
if self.config is not None:
if option in self.config:
del self.config[option] | python | def delete(self, option):
"""
Deletes an option if exists
"""
if self.config is not None:
if option in self.config:
del self.config[option] | [
"def",
"delete",
"(",
"self",
",",
"option",
")",
":",
"if",
"self",
".",
"config",
"is",
"not",
"None",
":",
"if",
"option",
"in",
"self",
".",
"config",
":",
"del",
"self",
".",
"config",
"[",
"option",
"]"
] | Deletes an option if exists | [
"Deletes",
"an",
"option",
"if",
"exists"
] | train | https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L39-L45 |
Vesuvium/aratrum | aratrum/Aratrum.py | Aratrum.save | def save(self):
"""
Saves the configuration
"""
with open(self.filename, 'w') as f:
ujson.dump(self.config, f, indent=4) | python | def save(self):
"""
Saves the configuration
"""
with open(self.filename, 'w') as f:
ujson.dump(self.config, f, indent=4) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"ujson",
".",
"dump",
"(",
"self",
".",
"config",
",",
"f",
",",
"indent",
"=",
"4",
")"
] | Saves the configuration | [
"Saves",
"the",
"configuration"
] | train | https://github.com/Vesuvium/aratrum/blob/7d237fe0c2afd615cf758a2a6485e93fa879b7e1/aratrum/Aratrum.py#L47-L52 |
bmweiner/skillful | skillful/validate.py | timestamp | def timestamp(stamp, tolerance=150):
"""Validate timestamp specified by request.
See `validate.request` for additional info.
Args:
stamp: str. Time request was made as ISO 8601 timestamp.
tolerance: int. Number of seconds request remains valid from timestamp.
Returns
bool: Tru... | python | def timestamp(stamp, tolerance=150):
"""Validate timestamp specified by request.
See `validate.request` for additional info.
Args:
stamp: str. Time request was made as ISO 8601 timestamp.
tolerance: int. Number of seconds request remains valid from timestamp.
Returns
bool: Tru... | [
"def",
"timestamp",
"(",
"stamp",
",",
"tolerance",
"=",
"150",
")",
":",
"try",
":",
"tolerance",
"=",
"datetime",
".",
"timedelta",
"(",
"0",
",",
"tolerance",
")",
"timestamp_low",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"stamp",
")",
"ti... | Validate timestamp specified by request.
See `validate.request` for additional info.
Args:
stamp: str. Time request was made as ISO 8601 timestamp.
tolerance: int. Number of seconds request remains valid from timestamp.
Returns
bool: True if valid, False otherwise. | [
"Validate",
"timestamp",
"specified",
"by",
"request",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L21-L41 |
bmweiner/skillful | skillful/validate.py | signature_cert_chain_url | def signature_cert_chain_url(url):
"""Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise.
"""
r = urlparse(url)
if no... | python | def signature_cert_chain_url(url):
"""Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise.
"""
r = urlparse(url)
if no... | [
"def",
"signature_cert_chain_url",
"(",
"url",
")",
":",
"r",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"r",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'https'",
":",
"warnings",
".",
"warn",
"(",
"'Certificate URL scheme is invalid.'",
")",
"retur... | Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise. | [
"Validate",
"URL",
"specified",
"by",
"SignatureCertChainUrl",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L43-L67 |
bmweiner/skillful | skillful/validate.py | retrieve | def retrieve(url):
"""Retrieve and parse PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of ... | python | def retrieve(url):
"""Retrieve and parse PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of ... | [
"def",
"retrieve",
"(",
"url",
")",
":",
"try",
":",
"pem_data",
"=",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
"except",
"(",
"ValueError",
",",
"HTTPError",
")",
":",
"warnings",
".",
"warn",
"(",
"'Certificate URL is invalid.'",
")",
"return"... | Retrieve and parse PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of cryptography.hazmat.backen... | [
"Retrieve",
"and",
"parse",
"PEM",
"-",
"encoded",
"X",
".",
"509",
"certificate",
"chain",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L69-L96 |
bmweiner/skillful | skillful/validate.py | _parse_pem_data | def _parse_pem_data(pem_data):
"""Parse PEM-encoded X.509 certificate chain.
Args:
pem_data: str. PEM file retrieved from SignatureCertChainUrl.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of cryptography.hazmat.backends.openssl.x509._Certifi... | python | def _parse_pem_data(pem_data):
"""Parse PEM-encoded X.509 certificate chain.
Args:
pem_data: str. PEM file retrieved from SignatureCertChainUrl.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of cryptography.hazmat.backends.openssl.x509._Certifi... | [
"def",
"_parse_pem_data",
"(",
"pem_data",
")",
":",
"sep",
"=",
"'-----BEGIN CERTIFICATE-----'",
"cert_chain",
"=",
"[",
"six",
".",
"b",
"(",
"sep",
"+",
"s",
")",
"for",
"s",
"in",
"pem_data",
".",
"split",
"(",
"sep",
")",
"[",
"1",
":",
"]",
"]"... | Parse PEM-encoded X.509 certificate chain.
Args:
pem_data: str. PEM file retrieved from SignatureCertChainUrl.
Returns:
list or bool: If url is valid, returns the certificate chain as a list
of cryptography.hazmat.backends.openssl.x509._Certificate
certificates where ce... | [
"Parse",
"PEM",
"-",
"encoded",
"X",
".",
"509",
"certificate",
"chain",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L98-L121 |
bmweiner/skillful | skillful/validate.py | cert_chain | def cert_chain(certs):
"""Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
See `validate.retrieve` to create c... | python | def cert_chain(certs):
"""Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
See `validate.retrieve` to create c... | [
"def",
"cert_chain",
"(",
"certs",
")",
":",
"if",
"len",
"(",
"certs",
")",
"<",
"2",
":",
"warnings",
".",
"warn",
"(",
"'Certificate chain contains < 3 certificates.'",
")",
"return",
"False",
"cert",
"=",
"certs",
"[",
"0",
"]",
"today",
"=",
"datetime... | Validate PEM-encoded X.509 certificate chain.
See `validate.request` for additional info.
Args:
certs: list. The certificate chain as a list of
cryptography.hazmat.backends.openssl.x509._Certificate certificates.
See `validate.retrieve` to create certs obj.
Returns:
... | [
"Validate",
"PEM",
"-",
"encoded",
"X",
".",
"509",
"certificate",
"chain",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L123-L159 |
bmweiner/skillful | skillful/validate.py | signature | def signature(cert, sig, body):
"""Validate data request signature.
See `validate.request` for additional info.
Args:
cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon
signing certificate.
sig: str. Signature header value sent by request.
body: st... | python | def signature(cert, sig, body):
"""Validate data request signature.
See `validate.request` for additional info.
Args:
cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon
signing certificate.
sig: str. Signature header value sent by request.
body: st... | [
"def",
"signature",
"(",
"cert",
",",
"sig",
",",
"body",
")",
":",
"body",
"=",
"six",
".",
"b",
"(",
"body",
")",
"sig",
"=",
"base64",
".",
"decodestring",
"(",
"sig",
")",
"padder",
"=",
"padding",
".",
"PKCS1v15",
"(",
")",
"public_key",
"=",
... | Validate data request signature.
See `validate.request` for additional info.
Args:
cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon
signing certificate.
sig: str. Signature header value sent by request.
body: str. HTTPS request body.
Returns:
... | [
"Validate",
"data",
"request",
"signature",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L161-L185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.