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 |
|---|---|---|---|---|---|---|---|---|---|---|
aksas/pypo4sel | core/pypo4sel/core/common.py | FindOverride.find_elements | def find_elements(self, by=By.ID, value=None, el_class=None):
"""
usages with ``'one string'`` selector:
- find_elements(by: str) -> PageElementsList[ListElement]
- find_elements(by: str, value: T <= ListElement) -> PageElementsList[T]
usages with ``'webdriver'`` By selector
... | python | def find_elements(self, by=By.ID, value=None, el_class=None):
"""
usages with ``'one string'`` selector:
- find_elements(by: str) -> PageElementsList[ListElement]
- find_elements(by: str, value: T <= ListElement) -> PageElementsList[T]
usages with ``'webdriver'`` By selector
... | [
"def",
"find_elements",
"(",
"self",
",",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"None",
",",
"el_class",
"=",
"None",
")",
":",
"els",
"=",
"self",
".",
"child_elements",
"(",
"by",
",",
"value",
",",
"el_class",
")",
"els",
".",
"reload",... | usages with ``'one string'`` selector:
- find_elements(by: str) -> PageElementsList[ListElement]
- find_elements(by: str, value: T <= ListElement) -> PageElementsList[T]
usages with ``'webdriver'`` By selector
- find_elements(by: str, value: str) -> PageElementsList[ListElement]
... | [
"usages",
"with",
"one",
"string",
"selector",
":",
"-",
"find_elements",
"(",
"by",
":",
"str",
")",
"-",
">",
"PageElementsList",
"[",
"ListElement",
"]",
"-",
"find_elements",
"(",
"by",
":",
"str",
"value",
":",
"T",
"<",
"=",
"ListElement",
")",
"... | train | https://github.com/aksas/pypo4sel/blob/935b5f9bfa6682aefdef8a43ebcbcf274dec752c/core/pypo4sel/core/common.py#L177-L198 |
jck/kya | scripts/link_pyqt.py | link_pyqt | def link_pyqt(sys_python, venv_python):
"""Symlink the systemwide PyQt/sip into the venv."""
real_site = site_dir(sys_python)
venv_site = site_dir(venv_python)
for f in ['sip.so', 'PyQt5']:
(venv_site/f).symlink_to(real_site/f) | python | def link_pyqt(sys_python, venv_python):
"""Symlink the systemwide PyQt/sip into the venv."""
real_site = site_dir(sys_python)
venv_site = site_dir(venv_python)
for f in ['sip.so', 'PyQt5']:
(venv_site/f).symlink_to(real_site/f) | [
"def",
"link_pyqt",
"(",
"sys_python",
",",
"venv_python",
")",
":",
"real_site",
"=",
"site_dir",
"(",
"sys_python",
")",
"venv_site",
"=",
"site_dir",
"(",
"venv_python",
")",
"for",
"f",
"in",
"[",
"'sip.so'",
",",
"'PyQt5'",
"]",
":",
"(",
"venv_site",... | Symlink the systemwide PyQt/sip into the venv. | [
"Symlink",
"the",
"systemwide",
"PyQt",
"/",
"sip",
"into",
"the",
"venv",
"."
] | train | https://github.com/jck/kya/blob/377361a336691612ce1b86cc36dda3ab8b079789/scripts/link_pyqt.py#L16-L22 |
heikomuller/sco-client | scocli/cli.py | SCOCmdLine.eval | def eval(self, cmd):
"""Evaluate a given command. The command is parsed and the output
returned as a list of lines (strings).
Raises a SCOCmdSyntaxError in case the command cannot be parsed.
Parameters
----------
cmd : strings
Command string
Returns... | python | def eval(self, cmd):
"""Evaluate a given command. The command is parsed and the output
returned as a list of lines (strings).
Raises a SCOCmdSyntaxError in case the command cannot be parsed.
Parameters
----------
cmd : strings
Command string
Returns... | [
"def",
"eval",
"(",
"self",
",",
"cmd",
")",
":",
"tokens",
"=",
"cmd",
".",
"upper",
"(",
")",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
"==",
"2",
"and",
"tokens",
"[",
"0",
"]",
"==",
"'LIST'",
":",
"if",
"tokens",
"[",
"1",... | Evaluate a given command. The command is parsed and the output
returned as a list of lines (strings).
Raises a SCOCmdSyntaxError in case the command cannot be parsed.
Parameters
----------
cmd : strings
Command string
Returns
-------
list(st... | [
"Evaluate",
"a",
"given",
"command",
".",
"The",
"command",
"is",
"parsed",
"and",
"the",
"output",
"returned",
"as",
"a",
"list",
"of",
"lines",
"(",
"strings",
")",
"."
] | train | https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/cli.py#L18-L47 |
heikomuller/sco-client | scocli/cli.py | SCOCmdLine.list_objects | def list_objects(self, resources):
"""Generate a listing for a set of resource handles consisting of
resource identifier, name, and timestamp.
Parameters
----------
resources : list(ResourceHandle)
List of resource handles
Returns
-------
lis... | python | def list_objects(self, resources):
"""Generate a listing for a set of resource handles consisting of
resource identifier, name, and timestamp.
Parameters
----------
resources : list(ResourceHandle)
List of resource handles
Returns
-------
lis... | [
"def",
"list_objects",
"(",
"self",
",",
"resources",
")",
":",
"result",
"=",
"[",
"]",
"for",
"res",
"in",
"resources",
":",
"result",
".",
"append",
"(",
"'\\t'",
".",
"join",
"(",
"[",
"res",
".",
"identifier",
",",
"res",
".",
"name",
",",
"st... | Generate a listing for a set of resource handles consisting of
resource identifier, name, and timestamp.
Parameters
----------
resources : list(ResourceHandle)
List of resource handles
Returns
-------
list(string) | [
"Generate",
"a",
"listing",
"for",
"a",
"set",
"of",
"resource",
"handles",
"consisting",
"of",
"resource",
"identifier",
"name",
"and",
"timestamp",
"."
] | train | https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/cli.py#L49-L65 |
klen/muffin-babel | example/__init__.py | set_locale | def set_locale(request):
"""Return locale from GET lang param or automatically."""
return request.query.get('lang', app.ps.babel.select_locale_by_request(request)) | python | def set_locale(request):
"""Return locale from GET lang param or automatically."""
return request.query.get('lang', app.ps.babel.select_locale_by_request(request)) | [
"def",
"set_locale",
"(",
"request",
")",
":",
"return",
"request",
".",
"query",
".",
"get",
"(",
"'lang'",
",",
"app",
".",
"ps",
".",
"babel",
".",
"select_locale_by_request",
"(",
"request",
")",
")"
] | Return locale from GET lang param or automatically. | [
"Return",
"locale",
"from",
"GET",
"lang",
"param",
"or",
"automatically",
"."
] | train | https://github.com/klen/muffin-babel/blob/f48ebbbf7806c6c727f66d8d0df331b29f6ead08/example/__init__.py#L26-L28 |
MitalAshok/objecttools | objecttools/serializable.py | SerializableFunction.value | def value(self):
"""The value of `self` as a (not serializable) `types.FunctionType` object"""
f = types.FunctionType(
self.code.value, self.globals, self.name, self.defaults, self.closure
)
d = self.dict.copy()
for attr in PY3_ATTRS:
try:
... | python | def value(self):
"""The value of `self` as a (not serializable) `types.FunctionType` object"""
f = types.FunctionType(
self.code.value, self.globals, self.name, self.defaults, self.closure
)
d = self.dict.copy()
for attr in PY3_ATTRS:
try:
... | [
"def",
"value",
"(",
"self",
")",
":",
"f",
"=",
"types",
".",
"FunctionType",
"(",
"self",
".",
"code",
".",
"value",
",",
"self",
".",
"globals",
",",
"self",
".",
"name",
",",
"self",
".",
"defaults",
",",
"self",
".",
"closure",
")",
"d",
"="... | The value of `self` as a (not serializable) `types.FunctionType` object | [
"The",
"value",
"of",
"self",
"as",
"a",
"(",
"not",
"serializable",
")",
"types",
".",
"FunctionType",
"object"
] | train | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/serializable.py#L129-L156 |
MitalAshok/objecttools | objecttools/serializable.py | SerializableFunction.globals | def globals(self):
"""Find the globals of `self` by importing `self.module`"""
try:
return vars(__import__(self.module, fromlist=self.module.split('.')))
except ImportError:
if self.warn_import:
warnings.warn(ImportWarning(
'Cannot impo... | python | def globals(self):
"""Find the globals of `self` by importing `self.module`"""
try:
return vars(__import__(self.module, fromlist=self.module.split('.')))
except ImportError:
if self.warn_import:
warnings.warn(ImportWarning(
'Cannot impo... | [
"def",
"globals",
"(",
"self",
")",
":",
"try",
":",
"return",
"vars",
"(",
"__import__",
"(",
"self",
".",
"module",
",",
"fromlist",
"=",
"self",
".",
"module",
".",
"split",
"(",
"'.'",
")",
")",
")",
"except",
"ImportError",
":",
"if",
"self",
... | Find the globals of `self` by importing `self.module` | [
"Find",
"the",
"globals",
"of",
"self",
"by",
"importing",
"self",
".",
"module"
] | train | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/serializable.py#L161-L170 |
MitalAshok/objecttools | objecttools/serializable.py | SerializableConstant.value | def value(self):
"""Import the constant from `self.module`"""
module = __import__(self.module, fromlist=self.module.split('.'))
if self.name is None:
return module
return getattr(module, self.name) | python | def value(self):
"""Import the constant from `self.module`"""
module = __import__(self.module, fromlist=self.module.split('.'))
if self.name is None:
return module
return getattr(module, self.name) | [
"def",
"value",
"(",
"self",
")",
":",
"module",
"=",
"__import__",
"(",
"self",
".",
"module",
",",
"fromlist",
"=",
"self",
".",
"module",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"self",
".",
"name",
"is",
"None",
":",
"return",
"module",
"retu... | Import the constant from `self.module` | [
"Import",
"the",
"constant",
"from",
"self",
".",
"module"
] | train | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/serializable.py#L260-L265 |
emlazzarin/acrylic | acrylic/groupby.py | GroupbyTable.agg | def agg(self, func, *fields, **name):
"""
Calls the aggregation function `func` on each group in the GroubyTable,
and leaves the results in a new column with the name of the aggregation
function.
Call `.agg` with `name='desired_column_name' to choose a column
name for th... | python | def agg(self, func, *fields, **name):
"""
Calls the aggregation function `func` on each group in the GroubyTable,
and leaves the results in a new column with the name of the aggregation
function.
Call `.agg` with `name='desired_column_name' to choose a column
name for th... | [
"def",
"agg",
"(",
"self",
",",
"func",
",",
"*",
"fields",
",",
"*",
"*",
"name",
")",
":",
"if",
"name",
":",
"if",
"len",
"(",
"name",
")",
">",
"1",
"or",
"'name'",
"not",
"in",
"name",
":",
"raise",
"TypeError",
"(",
"\"Unknown keyword args pa... | Calls the aggregation function `func` on each group in the GroubyTable,
and leaves the results in a new column with the name of the aggregation
function.
Call `.agg` with `name='desired_column_name' to choose a column
name for this aggregation. | [
"Calls",
"the",
"aggregation",
"function",
"func",
"on",
"each",
"group",
"in",
"the",
"GroubyTable",
"and",
"leaves",
"the",
"results",
"in",
"a",
"new",
"column",
"with",
"the",
"name",
"of",
"the",
"aggregation",
"function",
"."
] | train | https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/groupby.py#L71-L117 |
emlazzarin/acrylic | acrylic/groupby.py | GroupbyTable.collect | def collect(self):
"""
After adding the desired aggregation columns, `collect`
finalizes the groupby operation by converting the
GroupbyTable into a DataTable.
The first columns of the resulting table are the groupfields,
followed by the aggregation columns specified in ... | python | def collect(self):
"""
After adding the desired aggregation columns, `collect`
finalizes the groupby operation by converting the
GroupbyTable into a DataTable.
The first columns of the resulting table are the groupfields,
followed by the aggregation columns specified in ... | [
"def",
"collect",
"(",
"self",
")",
":",
"# The final order of columns is determined by the",
"# group keys and the aggregation columns",
"final_field_order",
"=",
"list",
"(",
"self",
".",
"__groupfields",
")",
"+",
"self",
".",
"__grouptable",
".",
"fields",
"# Transfor... | After adding the desired aggregation columns, `collect`
finalizes the groupby operation by converting the
GroupbyTable into a DataTable.
The first columns of the resulting table are the groupfields,
followed by the aggregation columns specified in preceeding
`agg` calls. | [
"After",
"adding",
"the",
"desired",
"aggregation",
"columns",
"collect",
"finalizes",
"the",
"groupby",
"operation",
"by",
"converting",
"the",
"GroupbyTable",
"into",
"a",
"DataTable",
"."
] | train | https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/groupby.py#L124-L149 |
azogue/dataweb | dataweb/threadingtasks/__init__.py | procesa_tareas_paralelo | def procesa_tareas_paralelo(lista_tareas, dict_data, func_process,
titulo=None, usar_multithread=True, max_threads=100, verbose=True):
"""
Procesa las tareas diarias en paralelo, limitando a un MAX de nº de threads.
Especialmente útil para realizar requests simultáneos a un servi... | python | def procesa_tareas_paralelo(lista_tareas, dict_data, func_process,
titulo=None, usar_multithread=True, max_threads=100, verbose=True):
"""
Procesa las tareas diarias en paralelo, limitando a un MAX de nº de threads.
Especialmente útil para realizar requests simultáneos a un servi... | [
"def",
"procesa_tareas_paralelo",
"(",
"lista_tareas",
",",
"dict_data",
",",
"func_process",
",",
"titulo",
"=",
"None",
",",
"usar_multithread",
"=",
"True",
",",
"max_threads",
"=",
"100",
",",
"verbose",
"=",
"True",
")",
":",
"num_tareas",
"=",
"len",
"... | Procesa las tareas diarias en paralelo, limitando a un MAX de nº de threads.
Especialmente útil para realizar requests simultáneos a un servidor web concreto.
:param lista_tareas: Recibe una lista de tareas únicas (key_tarea) a realizar
:param dict_data: Diccionario de la forma '{key_tarea : variabl... | [
"Procesa",
"las",
"tareas",
"diarias",
"en",
"paralelo",
"limitando",
"a",
"un",
"MAX",
"de",
"nº",
"de",
"threads",
".",
"Especialmente",
"útil",
"para",
"realizar",
"requests",
"simultáneos",
"a",
"un",
"servidor",
"web",
"concreto",
".",
":",
"param",
"li... | train | https://github.com/azogue/dataweb/blob/085035855df7cef0fe7725bbe9a706832344d946/dataweb/threadingtasks/__init__.py#L19-L61 |
eisensheng/kaviar | kaviar/api.py | kv_format_dict | def kv_format_dict(d, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats the given dictionary ``d``.
For more details see :func:`kv_format`.
:param collections.Mapping d:
Dictionary containing values to format.
:param collections.Iterable keys:
List of keys to extract from the dict.
... | python | def kv_format_dict(d, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats the given dictionary ``d``.
For more details see :func:`kv_format`.
:param collections.Mapping d:
Dictionary containing values to format.
:param collections.Iterable keys:
List of keys to extract from the dict.
... | [
"def",
"kv_format_dict",
"(",
"d",
",",
"keys",
"=",
"None",
",",
"separator",
"=",
"DEFAULT_SEPARATOR",
")",
":",
"return",
"_format_pairs",
"(",
"dump_dict",
"(",
"d",
",",
"keys",
")",
",",
"separator",
"=",
"separator",
")"
] | Formats the given dictionary ``d``.
For more details see :func:`kv_format`.
:param collections.Mapping d:
Dictionary containing values to format.
:param collections.Iterable keys:
List of keys to extract from the dict.
:param str separator:
Value between two pairs.
:return:... | [
"Formats",
"the",
"given",
"dictionary",
"d",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/api.py#L18-L34 |
eisensheng/kaviar | kaviar/api.py | kv_format_object | def kv_format_object(o, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats an object's attributes. Useful for object representation
implementation. Will skip methods or private attributes.
For more details see :func:`kv_format`.
:param o:
Object to format.
:param collections.Sequence ke... | python | def kv_format_object(o, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats an object's attributes. Useful for object representation
implementation. Will skip methods or private attributes.
For more details see :func:`kv_format`.
:param o:
Object to format.
:param collections.Sequence ke... | [
"def",
"kv_format_object",
"(",
"o",
",",
"keys",
"=",
"None",
",",
"separator",
"=",
"DEFAULT_SEPARATOR",
")",
":",
"if",
"keys",
"is",
"None",
":",
"key_values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"(",
"(",
"x",
",",
"getattr",
"(",
"o",
... | Formats an object's attributes. Useful for object representation
implementation. Will skip methods or private attributes.
For more details see :func:`kv_format`.
:param o:
Object to format.
:param collections.Sequence keys:
Explicit list of attributes to format. ``None`` means all p... | [
"Formats",
"an",
"object",
"s",
"attributes",
".",
"Useful",
"for",
"object",
"representation",
"implementation",
".",
"Will",
"skip",
"methods",
"or",
"private",
"attributes",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/api.py#L54-L81 |
eisensheng/kaviar | kaviar/api.py | kv_format | def kv_format(*args, **kwargs):
"""Formats any given list of Key-Value pairs or dictionaries in ``*args``
and any given keyword argument in ``**kwargs``.
Any item within a given list or dictionary will also be visited and
added to the output. Strings will be escaped to prevent leaking binary
data,... | python | def kv_format(*args, **kwargs):
"""Formats any given list of Key-Value pairs or dictionaries in ``*args``
and any given keyword argument in ``**kwargs``.
Any item within a given list or dictionary will also be visited and
added to the output. Strings will be escaped to prevent leaking binary
data,... | [
"def",
"kv_format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pairs",
"=",
"(",
"(",
"dump_dict",
"(",
"arg",
")",
"if",
"isinstance",
"(",
"arg",
",",
"Mapping",
")",
"else",
"(",
"dump_key_values",
"(",
"arg",
")",
"if",
"isinstance",
... | Formats any given list of Key-Value pairs or dictionaries in ``*args``
and any given keyword argument in ``**kwargs``.
Any item within a given list or dictionary will also be visited and
added to the output. Strings will be escaped to prevent leaking binary
data, ambiguous characters or other control ... | [
"Formats",
"any",
"given",
"list",
"of",
"Key",
"-",
"Value",
"pairs",
"or",
"dictionaries",
"in",
"*",
"args",
"and",
"any",
"given",
"keyword",
"argument",
"in",
"**",
"kwargs",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/api.py#L84-L110 |
praekeltfoundation/seed-service-rating | ratings/views.py | InviteSend.post | def post(self, request, *args, **kwargs):
""" Triggers the task that sends invitation messages
"""
status = 201
accepted = {"accepted": True}
send_invite_messages.apply_async()
return Response(accepted, status=status) | python | def post(self, request, *args, **kwargs):
""" Triggers the task that sends invitation messages
"""
status = 201
accepted = {"accepted": True}
send_invite_messages.apply_async()
return Response(accepted, status=status) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"status",
"=",
"201",
"accepted",
"=",
"{",
"\"accepted\"",
":",
"True",
"}",
"send_invite_messages",
".",
"apply_async",
"(",
")",
"return",
"Response",
"... | Triggers the task that sends invitation messages | [
"Triggers",
"the",
"task",
"that",
"sends",
"invitation",
"messages"
] | train | https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/views.py#L59-L65 |
praekeltfoundation/seed-service-rating | ratings/views.py | UserView.post | def post(self, request):
'''Create a user and token, given an email. If user exists just
provide the token.'''
serializer = CreateUserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data.get('email')
try:
u... | python | def post(self, request):
'''Create a user and token, given an email. If user exists just
provide the token.'''
serializer = CreateUserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data.get('email')
try:
u... | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"CreateUserSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"email",
"=",
"serializer",
".",
"valid... | Create a user and token, given an email. If user exists just
provide the token. | [
"Create",
"a",
"user",
"and",
"token",
"given",
"an",
"email",
".",
"If",
"user",
"exists",
"just",
"provide",
"the",
"token",
"."
] | train | https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/views.py#L94-L108 |
djangomini/djangomini | djangomini/controllers.py | Controller.dispatch | def dispatch(self, request, *args, **kwargs):
"""
Redefine parent's method.
Called on each new request from user.
Main difference between Django's approach and ours - we don't push
a 'request' to a method call. We use 'self.request' instead.
"""
# this part copi... | python | def dispatch(self, request, *args, **kwargs):
"""
Redefine parent's method.
Called on each new request from user.
Main difference between Django's approach and ours - we don't push
a 'request' to a method call. We use 'self.request' instead.
"""
# this part copi... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# this part copied from django source code",
"if",
"request",
".",
"method",
".",
"lower",
"(",
")",
"in",
"self",
".",
"http_method_names",
":",
"handler",... | Redefine parent's method.
Called on each new request from user.
Main difference between Django's approach and ours - we don't push
a 'request' to a method call. We use 'self.request' instead. | [
"Redefine",
"parent",
"s",
"method",
"."
] | train | https://github.com/djangomini/djangomini/blob/cfbe2d59acf0e89e5fd442df8952f9a117a63875/djangomini/controllers.py#L21-L37 |
djangomini/djangomini | djangomini/controllers.py | Controller.html | def html(self, data=None, template=None):
"""
Send html document to user.
Args:
- data: Dict to render template, or string with rendered HTML.
- template: Name of template to render HTML document with passed data.
"""
if data is None:
data = {}
... | python | def html(self, data=None, template=None):
"""
Send html document to user.
Args:
- data: Dict to render template, or string with rendered HTML.
- template: Name of template to render HTML document with passed data.
"""
if data is None:
data = {}
... | [
"def",
"html",
"(",
"self",
",",
"data",
"=",
"None",
",",
"template",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"template",
":",
"return",
"render",
"(",
"self",
".",
"request",
",",
"template",
",",
"d... | Send html document to user.
Args:
- data: Dict to render template, or string with rendered HTML.
- template: Name of template to render HTML document with passed data. | [
"Send",
"html",
"document",
"to",
"user",
"."
] | train | https://github.com/djangomini/djangomini/blob/cfbe2d59acf0e89e5fd442df8952f9a117a63875/djangomini/controllers.py#L39-L51 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | by_skills | def by_skills(queryset, skill_string=None):
""" Filter queryset by a comma delimeted skill list """
if skill_string:
operator, items = get_operator_and_items(skill_string)
q_obj = SQ()
for s in items:
if len(s) > 0:
q_obj.add(SQ(skills=s), operator)
queryset = queryset.filter(q_obj)
... | python | def by_skills(queryset, skill_string=None):
""" Filter queryset by a comma delimeted skill list """
if skill_string:
operator, items = get_operator_and_items(skill_string)
q_obj = SQ()
for s in items:
if len(s) > 0:
q_obj.add(SQ(skills=s), operator)
queryset = queryset.filter(q_obj)
... | [
"def",
"by_skills",
"(",
"queryset",
",",
"skill_string",
"=",
"None",
")",
":",
"if",
"skill_string",
":",
"operator",
",",
"items",
"=",
"get_operator_and_items",
"(",
"skill_string",
")",
"q_obj",
"=",
"SQ",
"(",
")",
"for",
"s",
"in",
"items",
":",
"... | Filter queryset by a comma delimeted skill list | [
"Filter",
"queryset",
"by",
"a",
"comma",
"delimeted",
"skill",
"list"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L78-L87 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | by_causes | def by_causes(queryset, cause_string=None):
""" Filter queryset by a comma delimeted cause list """
if cause_string:
operator, items = get_operator_and_items(cause_string)
q_obj = SQ()
for c in items:
if len(c) > 0:
q_obj.add(SQ(causes=c), operator)
queryset = queryset.filter(q_obj)
... | python | def by_causes(queryset, cause_string=None):
""" Filter queryset by a comma delimeted cause list """
if cause_string:
operator, items = get_operator_and_items(cause_string)
q_obj = SQ()
for c in items:
if len(c) > 0:
q_obj.add(SQ(causes=c), operator)
queryset = queryset.filter(q_obj)
... | [
"def",
"by_causes",
"(",
"queryset",
",",
"cause_string",
"=",
"None",
")",
":",
"if",
"cause_string",
":",
"operator",
",",
"items",
"=",
"get_operator_and_items",
"(",
"cause_string",
")",
"q_obj",
"=",
"SQ",
"(",
")",
"for",
"c",
"in",
"items",
":",
"... | Filter queryset by a comma delimeted cause list | [
"Filter",
"queryset",
"by",
"a",
"comma",
"delimeted",
"cause",
"list"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L90-L99 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | by_published | def by_published(queryset, published_string='true'):
""" Filter queryset by publish status """
if published_string == 'true':
queryset = queryset.filter(published=1)
elif published_string == 'false':
queryset = queryset.filter(published=0)
# Any other value will return both published and unpublished
r... | python | def by_published(queryset, published_string='true'):
""" Filter queryset by publish status """
if published_string == 'true':
queryset = queryset.filter(published=1)
elif published_string == 'false':
queryset = queryset.filter(published=0)
# Any other value will return both published and unpublished
r... | [
"def",
"by_published",
"(",
"queryset",
",",
"published_string",
"=",
"'true'",
")",
":",
"if",
"published_string",
"==",
"'true'",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"published",
"=",
"1",
")",
"elif",
"published_string",
"==",
"'false'",
... | Filter queryset by publish status | [
"Filter",
"queryset",
"by",
"publish",
"status"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L102-L109 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | by_name | def by_name(queryset, name=None):
""" Filter queryset by name, with word wide auto-completion """
if name:
queryset = queryset.filter(name=name)
return queryset | python | def by_name(queryset, name=None):
""" Filter queryset by name, with word wide auto-completion """
if name:
queryset = queryset.filter(name=name)
return queryset | [
"def",
"by_name",
"(",
"queryset",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"name",
"=",
"name",
")",
"return",
"queryset"
] | Filter queryset by name, with word wide auto-completion | [
"Filter",
"queryset",
"by",
"name",
"with",
"word",
"wide",
"auto",
"-",
"completion"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L112-L116 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | by_address | def by_address(queryset, address='', project=False):
"""
Filter queryset by publish status.
If project=True, we also apply a project exclusive filter
"""
if address:
address = json.loads(address)
if u'address_components' in address:
q_objs = []
"""
Caribbean filter
"""
... | python | def by_address(queryset, address='', project=False):
"""
Filter queryset by publish status.
If project=True, we also apply a project exclusive filter
"""
if address:
address = json.loads(address)
if u'address_components' in address:
q_objs = []
"""
Caribbean filter
"""
... | [
"def",
"by_address",
"(",
"queryset",
",",
"address",
"=",
"''",
",",
"project",
"=",
"False",
")",
":",
"if",
"address",
":",
"address",
"=",
"json",
".",
"loads",
"(",
"address",
")",
"if",
"u'address_components'",
"in",
"address",
":",
"q_objs",
"=",
... | Filter queryset by publish status.
If project=True, we also apply a project exclusive filter | [
"Filter",
"queryset",
"by",
"publish",
"status",
"."
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L119-L161 |
OpenVolunteeringPlatform/django-ovp-search | ovp_search/filters.py | filter_out | def filter_out(queryset, setting_name):
"""
Remove unwanted results from queryset
"""
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset | python | def filter_out(queryset, setting_name):
"""
Remove unwanted results from queryset
"""
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset | [
"def",
"filter_out",
"(",
"queryset",
",",
"setting_name",
")",
":",
"kwargs",
"=",
"helpers",
".",
"get_settings",
"(",
")",
".",
"get",
"(",
"setting_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"'FILTER_OUT'",
",",
"{",
"}",
")",
"queryset",
"=",
"... | Remove unwanted results from queryset | [
"Remove",
"unwanted",
"results",
"from",
"queryset"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/filters.py#L163-L169 |
20tab/twentytab-tree | tree/models.py | list_apps | def list_apps():
"""
It returns a list of application contained in PROJECT_APPS
"""
return [(d.split('.')[-1], d.split('.')[-1]) for d in os.listdir(
os.getcwd()) if is_app(u"{}/{}".format(os.getcwd(), d))] | python | def list_apps():
"""
It returns a list of application contained in PROJECT_APPS
"""
return [(d.split('.')[-1], d.split('.')[-1]) for d in os.listdir(
os.getcwd()) if is_app(u"{}/{}".format(os.getcwd(), d))] | [
"def",
"list_apps",
"(",
")",
":",
"return",
"[",
"(",
"d",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
",",
"d",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"for",
"d",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"getc... | It returns a list of application contained in PROJECT_APPS | [
"It",
"returns",
"a",
"list",
"of",
"application",
"contained",
"in",
"PROJECT_APPS"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L291-L296 |
20tab/twentytab-tree | tree/models.py | Node.slug | def slug(self):
"""
It returns node's slug
"""
if self.is_root_node():
return ""
if self.slugable and self.parent.parent:
if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node():
return u"{0}/{1}".for... | python | def slug(self):
"""
It returns node's slug
"""
if self.is_root_node():
return ""
if self.slugable and self.parent.parent:
if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node():
return u"{0}/{1}".for... | [
"def",
"slug",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_root_node",
"(",
")",
":",
"return",
"\"\"",
"if",
"self",
".",
"slugable",
"and",
"self",
".",
"parent",
".",
"parent",
":",
"if",
"not",
"self",
".",
"page",
".",
"regex",
"or",
"(",
... | It returns node's slug | [
"It",
"returns",
"node",
"s",
"slug"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L97-L117 |
20tab/twentytab-tree | tree/models.py | Node.slugable | def slugable(self):
"""
A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and no... | python | def slugable(self):
"""
A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and no... | [
"def",
"slugable",
"(",
"self",
")",
":",
"if",
"self",
".",
"page",
":",
"if",
"self",
".",
"is_leaf_node",
"(",
")",
":",
"return",
"True",
"if",
"not",
"self",
".",
"is_leaf_node",
"(",
")",
"and",
"not",
"self",
".",
"page",
".",
"regex",
":",
... | A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and node has a default value for regex.
... | [
"A",
"node",
"is",
"slugable",
"in",
"following",
"cases",
":",
"1",
"-",
"Node",
"doesn",
"t",
"have",
"children",
".",
"2",
"-",
"Node",
"has",
"children",
"but",
"its",
"page",
"doesn",
"t",
"have",
"a",
"regex",
".",
"3",
"-",
"Node",
"has",
"c... | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L120-L140 |
20tab/twentytab-tree | tree/models.py | Node.get_pattern | def get_pattern(self):
"""
It returns its url pattern
"""
if self.is_root_node():
return ""
else:
parent_pattern = self.parent.get_pattern()
if parent_pattern != "":
parent_pattern = u"{}".format(parent_pattern)
if n... | python | def get_pattern(self):
"""
It returns its url pattern
"""
if self.is_root_node():
return ""
else:
parent_pattern = self.parent.get_pattern()
if parent_pattern != "":
parent_pattern = u"{}".format(parent_pattern)
if n... | [
"def",
"get_pattern",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_root_node",
"(",
")",
":",
"return",
"\"\"",
"else",
":",
"parent_pattern",
"=",
"self",
".",
"parent",
".",
"get_pattern",
"(",
")",
"if",
"parent_pattern",
"!=",
"\"\"",
":",
"parent_p... | It returns its url pattern | [
"It",
"returns",
"its",
"url",
"pattern"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L142-L165 |
20tab/twentytab-tree | tree/models.py | Node.presentation_type | def presentation_type(self):
"""
It returns page's presentation_type
"""
if self.page and self.page.presentation_type:
return self.page.presentation_type
return "" | python | def presentation_type(self):
"""
It returns page's presentation_type
"""
if self.page and self.page.presentation_type:
return self.page.presentation_type
return "" | [
"def",
"presentation_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"page",
"and",
"self",
".",
"page",
".",
"presentation_type",
":",
"return",
"self",
".",
"page",
".",
"presentation_type",
"return",
"\"\""
] | It returns page's presentation_type | [
"It",
"returns",
"page",
"s",
"presentation_type"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L174-L180 |
20tab/twentytab-tree | tree/models.py | Page.view_path | def view_path(self):
"""
It returns view's view path
"""
if self.scheme_name is None or self.scheme_name == "":
return self.view.view_path
else:
return self.scheme_name | python | def view_path(self):
"""
It returns view's view path
"""
if self.scheme_name is None or self.scheme_name == "":
return self.view.view_path
else:
return self.scheme_name | [
"def",
"view_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"scheme_name",
"is",
"None",
"or",
"self",
".",
"scheme_name",
"==",
"\"\"",
":",
"return",
"self",
".",
"view",
".",
"view_path",
"else",
":",
"return",
"self",
".",
"scheme_name"
] | It returns view's view path | [
"It",
"returns",
"view",
"s",
"view",
"path"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L238-L245 |
20tab/twentytab-tree | tree/models.py | Page.get_absolute_url | def get_absolute_url(self):
"""
It returns absolute url defined by node related to this page
"""
try:
node = Node.objects.select_related().filter(page=self)[0]
return node.get_absolute_url()
except Exception, e:
raise ValueError(u"Error in {0}.... | python | def get_absolute_url(self):
"""
It returns absolute url defined by node related to this page
"""
try:
node = Node.objects.select_related().filter(page=self)[0]
return node.get_absolute_url()
except Exception, e:
raise ValueError(u"Error in {0}.... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"node",
"=",
"Node",
".",
"objects",
".",
"select_related",
"(",
")",
".",
"filter",
"(",
"page",
"=",
"self",
")",
"[",
"0",
"]",
"return",
"node",
".",
"get_absolute_url",
"(",
")",
"exc... | It returns absolute url defined by node related to this page | [
"It",
"returns",
"absolute",
"url",
"defined",
"by",
"node",
"related",
"to",
"this",
"page"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L247-L256 |
20tab/twentytab-tree | tree/models.py | Page.check_static_vars | def check_static_vars(self, node):
"""
This function check if a Page has static vars
"""
if self.static_vars == "" and hasattr(self, "template"):
self.static_vars = {
'upy_context': {
'template_name': u"{}/{}".format(self.template.app_name,... | python | def check_static_vars(self, node):
"""
This function check if a Page has static vars
"""
if self.static_vars == "" and hasattr(self, "template"):
self.static_vars = {
'upy_context': {
'template_name': u"{}/{}".format(self.template.app_name,... | [
"def",
"check_static_vars",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"static_vars",
"==",
"\"\"",
"and",
"hasattr",
"(",
"self",
",",
"\"template\"",
")",
":",
"self",
".",
"static_vars",
"=",
"{",
"'upy_context'",
":",
"{",
"'template_name'"... | This function check if a Page has static vars | [
"This",
"function",
"check",
"if",
"a",
"Page",
"has",
"static",
"vars"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L258-L274 |
20tab/twentytab-tree | tree/models.py | View.view_path | def view_path(self):
"""
It returns view_path as string like: 'app_name.module_mane.func_name'
"""
return u"{0}.{1}.{2}".format(self.app_name, self.module_name, self.func_name) | python | def view_path(self):
"""
It returns view_path as string like: 'app_name.module_mane.func_name'
"""
return u"{0}.{1}.{2}".format(self.app_name, self.module_name, self.func_name) | [
"def",
"view_path",
"(",
"self",
")",
":",
"return",
"u\"{0}.{1}.{2}\"",
".",
"format",
"(",
"self",
".",
"app_name",
",",
"self",
".",
"module_name",
",",
"self",
".",
"func_name",
")"
] | It returns view_path as string like: 'app_name.module_mane.func_name' | [
"It",
"returns",
"view_path",
"as",
"string",
"like",
":",
"app_name",
".",
"module_mane",
".",
"func_name"
] | train | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/models.py#L373-L377 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.away | def away(self, msg=''):
"""
Sets/unsets your away status.
Optional arguments:
* msg='' - Away reason.
"""
with self.lock:
self.send('AWAY :%s' % msg)
if self.readable():
msg = self._recv(expected_replies=('306', '305'))
... | python | def away(self, msg=''):
"""
Sets/unsets your away status.
Optional arguments:
* msg='' - Away reason.
"""
with self.lock:
self.send('AWAY :%s' % msg)
if self.readable():
msg = self._recv(expected_replies=('306', '305'))
... | [
"def",
"away",
"(",
"self",
",",
"msg",
"=",
"''",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'AWAY :%s'",
"%",
"msg",
")",
"if",
"self",
".",
"readable",
"(",
")",
":",
"msg",
"=",
"self",
".",
"_recv",
"(",
"expect... | Sets/unsets your away status.
Optional arguments:
* msg='' - Away reason. | [
"Sets",
"/",
"unsets",
"your",
"away",
"status",
".",
"Optional",
"arguments",
":",
"*",
"msg",
"=",
"-",
"Away",
"reason",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L24-L37 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.rehash | def rehash(self):
"""
Rehashes the IRCd's configuration file.
"""
with self.lock:
self.send('REHASH')
if self.readable():
msg = self._recv(expected_replies=('382',))
if msg[0] == '382':
pass | python | def rehash(self):
"""
Rehashes the IRCd's configuration file.
"""
with self.lock:
self.send('REHASH')
if self.readable():
msg = self._recv(expected_replies=('382',))
if msg[0] == '382':
pass | [
"def",
"rehash",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'REHASH'",
")",
"if",
"self",
".",
"readable",
"(",
")",
":",
"msg",
"=",
"self",
".",
"_recv",
"(",
"expected_replies",
"=",
"(",
"'382'",
",",
... | Rehashes the IRCd's configuration file. | [
"Rehashes",
"the",
"IRCd",
"s",
"configuration",
"file",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L39-L48 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.die | def die(self, password=''):
"""
Tells the IRCd to die.
Optional arguments:
* password='' - Die command password.
"""
with self.lock:
self.send('DIE :%s' % password, error_check=True) | python | def die(self, password=''):
"""
Tells the IRCd to die.
Optional arguments:
* password='' - Die command password.
"""
with self.lock:
self.send('DIE :%s' % password, error_check=True) | [
"def",
"die",
"(",
"self",
",",
"password",
"=",
"''",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'DIE :%s'",
"%",
"password",
",",
"error_check",
"=",
"True",
")"
] | Tells the IRCd to die.
Optional arguments:
* password='' - Die command password. | [
"Tells",
"the",
"IRCd",
"to",
"die",
".",
"Optional",
"arguments",
":",
"*",
"password",
"=",
"-",
"Die",
"command",
"password",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L50-L57 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.restart | def restart(self, password=''):
"""
Tells the IRCd to restart.
Optional arguments:
* password='' - Restart command password.
"""
with self.lock:
self.send('RESTART :%s' % password, error_check=True) | python | def restart(self, password=''):
"""
Tells the IRCd to restart.
Optional arguments:
* password='' - Restart command password.
"""
with self.lock:
self.send('RESTART :%s' % password, error_check=True) | [
"def",
"restart",
"(",
"self",
",",
"password",
"=",
"''",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'RESTART :%s'",
"%",
"password",
",",
"error_check",
"=",
"True",
")"
] | Tells the IRCd to restart.
Optional arguments:
* password='' - Restart command password. | [
"Tells",
"the",
"IRCd",
"to",
"restart",
".",
"Optional",
"arguments",
":",
"*",
"password",
"=",
"-",
"Restart",
"command",
"password",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L59-L66 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.userhost | def userhost(self, nicks):
"""
Runs a userhost on a nick.
Required arguments:
* nick - Nick to run a userhost on.
"""
with self.lock:
self.send('USERHOST :%s' % nicks)
userhosts = []
if self.readable():
msg = self._recv(... | python | def userhost(self, nicks):
"""
Runs a userhost on a nick.
Required arguments:
* nick - Nick to run a userhost on.
"""
with self.lock:
self.send('USERHOST :%s' % nicks)
userhosts = []
if self.readable():
msg = self._recv(... | [
"def",
"userhost",
"(",
"self",
",",
"nicks",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'USERHOST :%s'",
"%",
"nicks",
")",
"userhosts",
"=",
"[",
"]",
"if",
"self",
".",
"readable",
"(",
")",
":",
"msg",
"=",
"self",
... | Runs a userhost on a nick.
Required arguments:
* nick - Nick to run a userhost on. | [
"Runs",
"a",
"userhost",
"on",
"a",
"nick",
".",
"Required",
"arguments",
":",
"*",
"nick",
"-",
"Nick",
"to",
"run",
"a",
"userhost",
"on",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L84-L97 |
jamieleshaw/lurklib | lurklib/optional.py | _Optional.ison | def ison(self, nicks):
"""
Checks if a nick is on or not.
Returns list of nicks online.
Required arguments:
* nick - Nick to check.
"""
with self.lock:
self.send('ISON :%s' % ' '.join(nicks))
online_nicks = []
if self.readable()... | python | def ison(self, nicks):
"""
Checks if a nick is on or not.
Returns list of nicks online.
Required arguments:
* nick - Nick to check.
"""
with self.lock:
self.send('ISON :%s' % ' '.join(nicks))
online_nicks = []
if self.readable()... | [
"def",
"ison",
"(",
"self",
",",
"nicks",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'ISON :%s'",
"%",
"' '",
".",
"join",
"(",
"nicks",
")",
")",
"online_nicks",
"=",
"[",
"]",
"if",
"self",
".",
"readable",
"(",
")",... | Checks if a nick is on or not.
Returns list of nicks online.
Required arguments:
* nick - Nick to check. | [
"Checks",
"if",
"a",
"nick",
"is",
"on",
"or",
"not",
".",
"Returns",
"list",
"of",
"nicks",
"online",
".",
"Required",
"arguments",
":",
"*",
"nick",
"-",
"Nick",
"to",
"check",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/optional.py#L99-L113 |
globocom/globomap-loader-api-client | globomap_loader_api_client/auth.py | Auth.generate_token | def generate_token(self):
"""Make request in API to generate a token."""
response = self._make_request()
self.auth = response
self.token = response['token'] | python | def generate_token(self):
"""Make request in API to generate a token."""
response = self._make_request()
self.auth = response
self.token = response['token'] | [
"def",
"generate_token",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_make_request",
"(",
")",
"self",
".",
"auth",
"=",
"response",
"self",
".",
"token",
"=",
"response",
"[",
"'token'",
"]"
] | Make request in API to generate a token. | [
"Make",
"request",
"in",
"API",
"to",
"generate",
"a",
"token",
"."
] | train | https://github.com/globocom/globomap-loader-api-client/blob/b12347ca77d245de1abd604d1b694162156570e6/globomap_loader_api_client/auth.py#L45-L50 |
ulf1/oxyba | oxyba/linreg_ols_svd.py | linreg_ols_svd | def linreg_ols_svd(y, X, rcond=1e-15):
"""Linear Regression, OLS, inv by SVD
Properties
----------
* Numpy's lstsq is based on LAPACK's _gelsd what applies SVD
* SVD inverse might be slow (complex Landau O)
* speed might decline during forward selection
* no overhead or other computations
... | python | def linreg_ols_svd(y, X, rcond=1e-15):
"""Linear Regression, OLS, inv by SVD
Properties
----------
* Numpy's lstsq is based on LAPACK's _gelsd what applies SVD
* SVD inverse might be slow (complex Landau O)
* speed might decline during forward selection
* no overhead or other computations
... | [
"def",
"linreg_ols_svd",
"(",
"y",
",",
"X",
",",
"rcond",
"=",
"1e-15",
")",
":",
"import",
"numpy",
"as",
"np",
"try",
":",
"# solve OLS formula",
"beta",
",",
"_",
",",
"_",
",",
"singu",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"b",
"=",
... | Linear Regression, OLS, inv by SVD
Properties
----------
* Numpy's lstsq is based on LAPACK's _gelsd what applies SVD
* SVD inverse might be slow (complex Landau O)
* speed might decline during forward selection
* no overhead or other computations
Example:
--------
beta = lin_o... | [
"Linear",
"Regression",
"OLS",
"inv",
"by",
"SVD"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_ols_svd.py#L2-L29 |
b3j0f/conf | b3j0f/conf/parser/resolver/lang/py.py | genrepl | def genrepl(scope):
"""Replacement function with specific scope."""
def repl(match):
"""Internal replacement function."""
name = match.group('name')
value = lookup(name, scope=scope)
result = name.replace('.', '_')
scope[result] = value
return result
ret... | python | def genrepl(scope):
"""Replacement function with specific scope."""
def repl(match):
"""Internal replacement function."""
name = match.group('name')
value = lookup(name, scope=scope)
result = name.replace('.', '_')
scope[result] = value
return result
ret... | [
"def",
"genrepl",
"(",
"scope",
")",
":",
"def",
"repl",
"(",
"match",
")",
":",
"\"\"\"Internal replacement function.\"\"\"",
"name",
"=",
"match",
".",
"group",
"(",
"'name'",
")",
"value",
"=",
"lookup",
"(",
"name",
",",
"scope",
"=",
"scope",
")",
"... | Replacement function with specific scope. | [
"Replacement",
"function",
"with",
"specific",
"scope",
"."
] | train | https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/lang/py.py#L48-L63 |
b3j0f/conf | b3j0f/conf/parser/resolver/lang/py.py | resolvepy | def resolvepy(
expr,
safe=DEFAULT_SAFE, tostr=DEFAULT_TOSTR, scope=DEFAULT_SCOPE,
besteffort=DEFAULT_BESTEFFORT
):
"""Resolve input expression.
:param str expr: configuration expression to resolve in this language.
:param bool safe: safe run execution context (True by default).
... | python | def resolvepy(
expr,
safe=DEFAULT_SAFE, tostr=DEFAULT_TOSTR, scope=DEFAULT_SCOPE,
besteffort=DEFAULT_BESTEFFORT
):
"""Resolve input expression.
:param str expr: configuration expression to resolve in this language.
:param bool safe: safe run execution context (True by default).
... | [
"def",
"resolvepy",
"(",
"expr",
",",
"safe",
"=",
"DEFAULT_SAFE",
",",
"tostr",
"=",
"DEFAULT_TOSTR",
",",
"scope",
"=",
"DEFAULT_SCOPE",
",",
"besteffort",
"=",
"DEFAULT_BESTEFFORT",
")",
":",
"result",
"=",
"None",
"_eval",
"=",
"safe_eval",
"if",
"safe",... | Resolve input expression.
:param str expr: configuration expression to resolve in this language.
:param bool safe: safe run execution context (True by default).
:param bool tostr: format the result.
:param dict scope: execution scope (contains references to expression
objects).
:param bool ... | [
"Resolve",
"input",
"expression",
"."
] | train | https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/lang/py.py#L68-L120 |
bcho/yufou | yufou/radar.py | round_to_5_minutes | def round_to_5_minutes(moment):
'''Round datetime to 5 minutes boundary:
- if moment.minute < 5 -> moment.minute = 0
- if moment.minute >= 5 -> moment.minute = 0
:param moment: a :class:`datetime.datetime` instance.
'''
return moment - timedelta(minutes=moment.minute % 5, seconds=moment.second... | python | def round_to_5_minutes(moment):
'''Round datetime to 5 minutes boundary:
- if moment.minute < 5 -> moment.minute = 0
- if moment.minute >= 5 -> moment.minute = 0
:param moment: a :class:`datetime.datetime` instance.
'''
return moment - timedelta(minutes=moment.minute % 5, seconds=moment.second... | [
"def",
"round_to_5_minutes",
"(",
"moment",
")",
":",
"return",
"moment",
"-",
"timedelta",
"(",
"minutes",
"=",
"moment",
".",
"minute",
"%",
"5",
",",
"seconds",
"=",
"moment",
".",
"second",
")"
] | Round datetime to 5 minutes boundary:
- if moment.minute < 5 -> moment.minute = 0
- if moment.minute >= 5 -> moment.minute = 0
:param moment: a :class:`datetime.datetime` instance. | [
"Round",
"datetime",
"to",
"5",
"minutes",
"boundary",
":"
] | train | https://github.com/bcho/yufou/blob/008e38468f17cf6bc616b30b944bb9395dbaface/yufou/radar.py#L15-L23 |
bcho/yufou | yufou/radar.py | image | def image(radar, at=None):
'''Retrieve a radar image.
:param radar: radar station no.
:param at: stat datetime, defaults to now.
'''
at = round_to_5_minutes(at or datetime.utcnow())
return ''.join([
'http://image.nmc.cn/product',
'/{0}'.format(at.year),
'/{0}'.format(at... | python | def image(radar, at=None):
'''Retrieve a radar image.
:param radar: radar station no.
:param at: stat datetime, defaults to now.
'''
at = round_to_5_minutes(at or datetime.utcnow())
return ''.join([
'http://image.nmc.cn/product',
'/{0}'.format(at.year),
'/{0}'.format(at... | [
"def",
"image",
"(",
"radar",
",",
"at",
"=",
"None",
")",
":",
"at",
"=",
"round_to_5_minutes",
"(",
"at",
"or",
"datetime",
".",
"utcnow",
"(",
")",
")",
"return",
"''",
".",
"join",
"(",
"[",
"'http://image.nmc.cn/product'",
",",
"'/{0}'",
".",
"for... | Retrieve a radar image.
:param radar: radar station no.
:param at: stat datetime, defaults to now. | [
"Retrieve",
"a",
"radar",
"image",
"."
] | train | https://github.com/bcho/yufou/blob/008e38468f17cf6bc616b30b944bb9395dbaface/yufou/radar.py#L26-L42 |
nickmilon/Hellas | Hellas/Olympia.py | pickle_compress | def pickle_compress(obj, print_compression_info=False):
"""pickle and compress an object"""
p = pickle.dumps(obj)
c = zlib.compress(p)
if print_compression_info:
print ("len = {:,d} compr={:,d} ratio:{:.6f}".format(len(p), len(c), float(len(c))/len(p)))
return c | python | def pickle_compress(obj, print_compression_info=False):
"""pickle and compress an object"""
p = pickle.dumps(obj)
c = zlib.compress(p)
if print_compression_info:
print ("len = {:,d} compr={:,d} ratio:{:.6f}".format(len(p), len(c), float(len(c))/len(p)))
return c | [
"def",
"pickle_compress",
"(",
"obj",
",",
"print_compression_info",
"=",
"False",
")",
":",
"p",
"=",
"pickle",
".",
"dumps",
"(",
"obj",
")",
"c",
"=",
"zlib",
".",
"compress",
"(",
"p",
")",
"if",
"print_compression_info",
":",
"print",
"(",
"\"len = ... | pickle and compress an object | [
"pickle",
"and",
"compress",
"an",
"object"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Olympia.py#L9-L15 |
ahobsonsayers/bthomehub5-devicelist | bthomehub5_devicelist/bthomehub5_devicelist.py | get_devicelist | def get_devicelist(home_hub_ip='192.168.1.254'):
"""Retrieve data from BT Home Hub 5 and return parsed result.
"""
url = 'http://{}/'.format(home_hub_ip)
try:
response = requests.get(url, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router tim... | python | def get_devicelist(home_hub_ip='192.168.1.254'):
"""Retrieve data from BT Home Hub 5 and return parsed result.
"""
url = 'http://{}/'.format(home_hub_ip)
try:
response = requests.get(url, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router tim... | [
"def",
"get_devicelist",
"(",
"home_hub_ip",
"=",
"'192.168.1.254'",
")",
":",
"url",
"=",
"'http://{}/'",
".",
"format",
"(",
"home_hub_ip",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"5",
")",
"except",
"... | Retrieve data from BT Home Hub 5 and return parsed result. | [
"Retrieve",
"data",
"from",
"BT",
"Home",
"Hub",
"5",
"and",
"return",
"parsed",
"result",
"."
] | train | https://github.com/ahobsonsayers/bthomehub5-devicelist/blob/941b553fab7ce49b0c7ff7f1e10023d0a212d455/bthomehub5_devicelist/bthomehub5_devicelist.py#L8-L22 |
ahobsonsayers/bthomehub5-devicelist | bthomehub5_devicelist/bthomehub5_devicelist.py | parse_devicelist | def parse_devicelist(data_str):
"""Parse the BT Home Hub 5 data format."""
p = HTMLTableParser()
p.feed(data_str)
known_devices = p.tables[9]
devices = {}
for device in known_devices:
if len(device) == 5 and device[2] != '':
devices[device[2]] = device[1]
return devi... | python | def parse_devicelist(data_str):
"""Parse the BT Home Hub 5 data format."""
p = HTMLTableParser()
p.feed(data_str)
known_devices = p.tables[9]
devices = {}
for device in known_devices:
if len(device) == 5 and device[2] != '':
devices[device[2]] = device[1]
return devi... | [
"def",
"parse_devicelist",
"(",
"data_str",
")",
":",
"p",
"=",
"HTMLTableParser",
"(",
")",
"p",
".",
"feed",
"(",
"data_str",
")",
"known_devices",
"=",
"p",
".",
"tables",
"[",
"9",
"]",
"devices",
"=",
"{",
"}",
"for",
"device",
"in",
"known_device... | Parse the BT Home Hub 5 data format. | [
"Parse",
"the",
"BT",
"Home",
"Hub",
"5",
"data",
"format",
"."
] | train | https://github.com/ahobsonsayers/bthomehub5-devicelist/blob/941b553fab7ce49b0c7ff7f1e10023d0a212d455/bthomehub5_devicelist/bthomehub5_devicelist.py#L25-L39 |
minhhoit/yacms | yacms/generic/templatetags/comment_tags.py | comments_for | def comments_for(context, obj):
"""
Provides a generic context variable name for the object that
comments are being rendered for.
"""
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(context["request"], obj)
context_form = context.get("posted_comment_form", form... | python | def comments_for(context, obj):
"""
Provides a generic context variable name for the object that
comments are being rendered for.
"""
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(context["request"], obj)
context_form = context.get("posted_comment_form", form... | [
"def",
"comments_for",
"(",
"context",
",",
"obj",
")",
":",
"form_class",
"=",
"import_dotted_path",
"(",
"settings",
".",
"COMMENT_FORM_CLASS",
")",
"form",
"=",
"form_class",
"(",
"context",
"[",
"\"request\"",
"]",
",",
"obj",
")",
"context_form",
"=",
"... | Provides a generic context variable name for the object that
comments are being rendered for. | [
"Provides",
"a",
"generic",
"context",
"variable",
"name",
"for",
"the",
"object",
"that",
"comments",
"are",
"being",
"rendered",
"for",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/comment_tags.py#L19-L34 |
minhhoit/yacms | yacms/generic/templatetags/comment_tags.py | comment_thread | def comment_thread(context, parent):
"""
Return a list of child comments for the given parent, storing all
comments in a dict in the context when first called, using parents
as keys for retrieval on subsequent recursive calls from the
comments template.
"""
if "all_comments" not in context:
... | python | def comment_thread(context, parent):
"""
Return a list of child comments for the given parent, storing all
comments in a dict in the context when first called, using parents
as keys for retrieval on subsequent recursive calls from the
comments template.
"""
if "all_comments" not in context:
... | [
"def",
"comment_thread",
"(",
"context",
",",
"parent",
")",
":",
"if",
"\"all_comments\"",
"not",
"in",
"context",
":",
"comments",
"=",
"defaultdict",
"(",
"list",
")",
"if",
"\"request\"",
"in",
"context",
"and",
"context",
"[",
"\"request\"",
"]",
".",
... | Return a list of child comments for the given parent, storing all
comments in a dict in the context when first called, using parents
as keys for retrieval on subsequent recursive calls from the
comments template. | [
"Return",
"a",
"list",
"of",
"child",
"comments",
"for",
"the",
"given",
"parent",
"storing",
"all",
"comments",
"in",
"a",
"dict",
"in",
"the",
"context",
"when",
"first",
"called",
"using",
"parents",
"as",
"keys",
"for",
"retrieval",
"on",
"subsequent",
... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/comment_tags.py#L38-L64 |
minhhoit/yacms | yacms/generic/templatetags/comment_tags.py | recent_comments | def recent_comments(context):
"""
Dashboard widget for displaying recent comments.
"""
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | python | def recent_comments(context):
"""
Dashboard widget for displaying recent comments.
"""
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | [
"def",
"recent_comments",
"(",
"context",
")",
":",
"latest",
"=",
"context",
"[",
"\"settings\"",
"]",
".",
"COMMENTS_NUM_LATEST",
"comments",
"=",
"ThreadedComment",
".",
"objects",
".",
"all",
"(",
")",
".",
"select_related",
"(",
"\"user\"",
")",
"context"... | Dashboard widget for displaying recent comments. | [
"Dashboard",
"widget",
"for",
"displaying",
"recent",
"comments",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/comment_tags.py#L69-L76 |
minhhoit/yacms | yacms/generic/templatetags/comment_tags.py | comment_filter | def comment_filter(comment_text):
"""
Passed comment text to be rendered through the function defined
by the ``COMMENT_FILTER`` setting. If no function is defined
(the default), Django's ``linebreaksbr`` and ``urlize`` filters
are used.
"""
filter_func = settings.COMMENT_FILTER
if not fi... | python | def comment_filter(comment_text):
"""
Passed comment text to be rendered through the function defined
by the ``COMMENT_FILTER`` setting. If no function is defined
(the default), Django's ``linebreaksbr`` and ``urlize`` filters
are used.
"""
filter_func = settings.COMMENT_FILTER
if not fi... | [
"def",
"comment_filter",
"(",
"comment_text",
")",
":",
"filter_func",
"=",
"settings",
".",
"COMMENT_FILTER",
"if",
"not",
"filter_func",
":",
"def",
"filter_func",
"(",
"s",
")",
":",
"return",
"linebreaksbr",
"(",
"urlize",
"(",
"s",
",",
"autoescape",
"=... | Passed comment text to be rendered through the function defined
by the ``COMMENT_FILTER`` setting. If no function is defined
(the default), Django's ``linebreaksbr`` and ``urlize`` filters
are used. | [
"Passed",
"comment",
"text",
"to",
"be",
"rendered",
"through",
"the",
"function",
"defined",
"by",
"the",
"COMMENT_FILTER",
"setting",
".",
"If",
"no",
"function",
"is",
"defined",
"(",
"the",
"default",
")",
"Django",
"s",
"linebreaksbr",
"and",
"urlize",
... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/comment_tags.py#L80-L93 |
kalekundert/nonstdlib | nonstdlib/debug.py | log_level | def log_level(level):
"""
Attempt to convert the given argument into a log level.
Log levels are represented as integers, where higher values are more
severe. If the given level is already an integer, it is simply returned.
If the given level is a string that can be converted into an integer, i... | python | def log_level(level):
"""
Attempt to convert the given argument into a log level.
Log levels are represented as integers, where higher values are more
severe. If the given level is already an integer, it is simply returned.
If the given level is a string that can be converted into an integer, i... | [
"def",
"log_level",
"(",
"level",
")",
":",
"from",
"six",
"import",
"string_types",
"if",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"return",
"level",
"if",
"isinstance",
"(",
"level",
",",
"string_types",
")",
":",
"try",
":",
"return",
"int",
... | Attempt to convert the given argument into a log level.
Log levels are represented as integers, where higher values are more
severe. If the given level is already an integer, it is simply returned.
If the given level is a string that can be converted into an integer, it is
converted and that value... | [
"Attempt",
"to",
"convert",
"the",
"given",
"argument",
"into",
"a",
"log",
"level",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/debug.py#L11-L34 |
kalekundert/nonstdlib | nonstdlib/debug.py | verbosity | def verbosity(verbosity):
"""
Convert the number of times the user specified '-v' on the command-line
into a log level.
"""
verbosity = int(verbosity)
if verbosity == 0:
return logging.WARNING
if verbosity == 1:
return logging.INFO
if verbosity == 2:
return logg... | python | def verbosity(verbosity):
"""
Convert the number of times the user specified '-v' on the command-line
into a log level.
"""
verbosity = int(verbosity)
if verbosity == 0:
return logging.WARNING
if verbosity == 1:
return logging.INFO
if verbosity == 2:
return logg... | [
"def",
"verbosity",
"(",
"verbosity",
")",
":",
"verbosity",
"=",
"int",
"(",
"verbosity",
")",
"if",
"verbosity",
"==",
"0",
":",
"return",
"logging",
".",
"WARNING",
"if",
"verbosity",
"==",
"1",
":",
"return",
"logging",
".",
"INFO",
"if",
"verbosity"... | Convert the number of times the user specified '-v' on the command-line
into a log level. | [
"Convert",
"the",
"number",
"of",
"times",
"the",
"user",
"specified",
"-",
"v",
"on",
"the",
"command",
"-",
"line",
"into",
"a",
"log",
"level",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/debug.py#L36-L52 |
kalekundert/nonstdlib | nonstdlib/debug.py | config | def config(stream=sys.stderr,
level=logging.NOTSET,
format='%(levelname)s [%(name)s:%(lineno)s] %(message)s',
file=None,
file_level=None,
file_format=None):
"""
Configure logging to stream and file concurrently.
Allows setting a file and stream to log ... | python | def config(stream=sys.stderr,
level=logging.NOTSET,
format='%(levelname)s [%(name)s:%(lineno)s] %(message)s',
file=None,
file_level=None,
file_format=None):
"""
Configure logging to stream and file concurrently.
Allows setting a file and stream to log ... | [
"def",
"config",
"(",
"stream",
"=",
"sys",
".",
"stderr",
",",
"level",
"=",
"logging",
".",
"NOTSET",
",",
"format",
"=",
"'%(levelname)s [%(name)s:%(lineno)s] %(message)s'",
",",
"file",
"=",
"None",
",",
"file_level",
"=",
"None",
",",
"file_format",
"=",
... | Configure logging to stream and file concurrently.
Allows setting a file and stream to log to concurrently with differing
level if desired. Must provide either stream or file.
Parameters
----------
stream: File like:
Stream to write file to [Default: sys.stderr]. If none, will not write ... | [
"Configure",
"logging",
"to",
"stream",
"and",
"file",
"concurrently",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/debug.py#L54-L117 |
kalekundert/nonstdlib | nonstdlib/debug.py | _log | def _log(level, message, frame_depth=2, **kwargs):
"""
Log the given message with the given log level using a logger named based
on the scope of the calling code. This saves you time because you will be
able to see where all your log messages are being generated from without
having to type anyth... | python | def _log(level, message, frame_depth=2, **kwargs):
"""
Log the given message with the given log level using a logger named based
on the scope of the calling code. This saves you time because you will be
able to see where all your log messages are being generated from without
having to type anyth... | [
"def",
"_log",
"(",
"level",
",",
"message",
",",
"frame_depth",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"inspect",
"try",
":",
"# Inspect variables two frames up from where we currently are (by ",
"# default). One frame up is assumed to be one of the helper... | Log the given message with the given log level using a logger named based
on the scope of the calling code. This saves you time because you will be
able to see where all your log messages are being generated from without
having to type anything. This function is meant to be called by one or
more w... | [
"Log",
"the",
"given",
"message",
"with",
"the",
"given",
"log",
"level",
"using",
"a",
"logger",
"named",
"based",
"on",
"the",
"scope",
"of",
"the",
"calling",
"code",
".",
"This",
"saves",
"you",
"time",
"because",
"you",
"will",
"be",
"able",
"to",
... | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/debug.py#L145-L206 |
Jayin/ETipsService | service/wyulibrary.py | WyuLibrary.__search_book_html | def __search_book_html(self, anywords, page):
"""
检索图书列表页面
:param anywords: 关键字
:param page: 页码
:return: html code
"""
_params = {
'dt': 'ALL',
'cl': 'ALL',
'dp': '20',
'sf': 'M_PUB_YEAR',
'ob': 'DESC',
... | python | def __search_book_html(self, anywords, page):
"""
检索图书列表页面
:param anywords: 关键字
:param page: 页码
:return: html code
"""
_params = {
'dt': 'ALL',
'cl': 'ALL',
'dp': '20',
'sf': 'M_PUB_YEAR',
'ob': 'DESC',
... | [
"def",
"__search_book_html",
"(",
"self",
",",
"anywords",
",",
"page",
")",
":",
"_params",
"=",
"{",
"'dt'",
":",
"'ALL'",
",",
"'cl'",
":",
"'ALL'",
",",
"'dp'",
":",
"'20'",
",",
"'sf'",
":",
"'M_PUB_YEAR'",
",",
"'ob'",
":",
"'DESC'",
",",
"'sm'... | 检索图书列表页面
:param anywords: 关键字
:param page: 页码
:return: html code | [
"检索图书列表页面",
":",
"param",
"anywords",
":",
"关键字",
":",
"param",
"page",
":",
"页码",
":",
"return",
":",
"html",
"code"
] | train | https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/wyulibrary.py#L15-L46 |
Jayin/ETipsService | service/wyulibrary.py | WyuLibrary.search_book | def search_book(self, anywords, page=1):
"""
检索图书
:param anywords: 检索关键字
:param page: 页码
:return: 图书列表
"""
result = []
html = self.__search_book_html(anywords, page)
soup = BeautifulSoup(html)
tds = soup.select(selector='tbody')[0].select('... | python | def search_book(self, anywords, page=1):
"""
检索图书
:param anywords: 检索关键字
:param page: 页码
:return: 图书列表
"""
result = []
html = self.__search_book_html(anywords, page)
soup = BeautifulSoup(html)
tds = soup.select(selector='tbody')[0].select('... | [
"def",
"search_book",
"(",
"self",
",",
"anywords",
",",
"page",
"=",
"1",
")",
":",
"result",
"=",
"[",
"]",
"html",
"=",
"self",
".",
"__search_book_html",
"(",
"anywords",
",",
"page",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
")",
"tds",
"=... | 检索图书
:param anywords: 检索关键字
:param page: 页码
:return: 图书列表 | [
"检索图书",
":",
"param",
"anywords",
":",
"检索关键字",
":",
"param",
"page",
":",
"页码",
":",
"return",
":",
"图书列表"
] | train | https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/wyulibrary.py#L51-L89 |
Jayin/ETipsService | service/wyulibrary.py | WyuLibrary.__book_status_html | def __book_status_html(self, ctrlno):
"""
获取图书借阅页面
:param ctrlno:
:return:
"""
_params = {
'ctrlno': ctrlno
}
_headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-E... | python | def __book_status_html(self, ctrlno):
"""
获取图书借阅页面
:param ctrlno:
:return:
"""
_params = {
'ctrlno': ctrlno
}
_headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-E... | [
"def",
"__book_status_html",
"(",
"self",
",",
"ctrlno",
")",
":",
"_params",
"=",
"{",
"'ctrlno'",
":",
"ctrlno",
"}",
"_headers",
"=",
"{",
"'Accept'",
":",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'",
",",
"'Accept-Encoding'",
":",
... | 获取图书借阅页面
:param ctrlno:
:return: | [
"获取图书借阅页面",
":",
"param",
"ctrlno",
":",
":",
"return",
":"
] | train | https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/wyulibrary.py#L91-L109 |
Jayin/ETipsService | service/wyulibrary.py | WyuLibrary.__get_isbn | def __get_isbn(self, html):
"""
从图书借阅状态页面中获取isbn
:param html:
:return:
"""
import re
reg = re.compile(r'getBookCover\(".*","(.*)"\);')
res = reg.findall(html)
if len(res) > 0:
return res[0]
else:
return '' | python | def __get_isbn(self, html):
"""
从图书借阅状态页面中获取isbn
:param html:
:return:
"""
import re
reg = re.compile(r'getBookCover\(".*","(.*)"\);')
res = reg.findall(html)
if len(res) > 0:
return res[0]
else:
return '' | [
"def",
"__get_isbn",
"(",
"self",
",",
"html",
")",
":",
"import",
"re",
"reg",
"=",
"re",
".",
"compile",
"(",
"r'getBookCover\\(\".*\",\"(.*)\"\\);'",
")",
"res",
"=",
"reg",
".",
"findall",
"(",
"html",
")",
"if",
"len",
"(",
"res",
")",
">",
"0",
... | 从图书借阅状态页面中获取isbn
:param html:
:return: | [
"从图书借阅状态页面中获取isbn",
":",
"param",
"html",
":",
":",
"return",
":"
] | train | https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/wyulibrary.py#L111-L125 |
Jayin/ETipsService | service/wyulibrary.py | WyuLibrary.book_status | def book_status(self, ctrlno):
"""
查看图书借阅情况
:param ctrlno: 图书馆系统图书唯一标识
:return: {
'isbn': '',
'status_list': [],
}
"""
result = {
'isbn': '',
'status_list': [],
}
html = self.__book_status_html(ctrlno... | python | def book_status(self, ctrlno):
"""
查看图书借阅情况
:param ctrlno: 图书馆系统图书唯一标识
:return: {
'isbn': '',
'status_list': [],
}
"""
result = {
'isbn': '',
'status_list': [],
}
html = self.__book_status_html(ctrlno... | [
"def",
"book_status",
"(",
"self",
",",
"ctrlno",
")",
":",
"result",
"=",
"{",
"'isbn'",
":",
"''",
",",
"'status_list'",
":",
"[",
"]",
",",
"}",
"html",
"=",
"self",
".",
"__book_status_html",
"(",
"ctrlno",
")",
"soup",
"=",
"BeautifulSoup",
"(",
... | 查看图书借阅情况
:param ctrlno: 图书馆系统图书唯一标识
:return: {
'isbn': '',
'status_list': [],
} | [
"查看图书借阅情况",
":",
"param",
"ctrlno",
":",
"图书馆系统图书唯一标识",
":",
"return",
":",
"{",
"isbn",
":",
"status_list",
":",
"[]",
"}"
] | train | https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/wyulibrary.py#L127-L168 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.on_switch_state_changed | def on_switch_state_changed(
self, func: Callable[['BaseUnit', SwitchNumber, Optional[bool]], None]):
"""
Define the switch state changed callback implementation.
Expected signature is:
switch_state_changed_callback(base_unit, switch_number, state)
base_unit: ... | python | def on_switch_state_changed(
self, func: Callable[['BaseUnit', SwitchNumber, Optional[bool]], None]):
"""
Define the switch state changed callback implementation.
Expected signature is:
switch_state_changed_callback(base_unit, switch_number, state)
base_unit: ... | [
"def",
"on_switch_state_changed",
"(",
"self",
",",
"func",
":",
"Callable",
"[",
"[",
"'BaseUnit'",
",",
"SwitchNumber",
",",
"Optional",
"[",
"bool",
"]",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"_on_switch_state_changed",
"=",
"func"
] | Define the switch state changed callback implementation.
Expected signature is:
switch_state_changed_callback(base_unit, switch_number, state)
base_unit: the device instance for this callback
switch_number: the switch whose state has changed
state: True if sw... | [
"Define",
"the",
"switch",
"state",
"changed",
"callback",
"implementation",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L267-L279 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.start | def start(self) -> None:
"""
Start monitoring the base unit.
"""
self._shutdown = False
# Start listening (if server) / Open connection (if client)
if isinstance(self._protocol, Server):
self.create_task(self._async_listen)
elif isinstance(self._prot... | python | def start(self) -> None:
"""
Start monitoring the base unit.
"""
self._shutdown = False
# Start listening (if server) / Open connection (if client)
if isinstance(self._protocol, Server):
self.create_task(self._async_listen)
elif isinstance(self._prot... | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_shutdown",
"=",
"False",
"# Start listening (if server) / Open connection (if client)",
"if",
"isinstance",
"(",
"self",
".",
"_protocol",
",",
"Server",
")",
":",
"self",
".",
"create_task",
"(... | Start monitoring the base unit. | [
"Start",
"monitoring",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L285-L298 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.stop | def stop(self) -> None:
"""
Stop monitoring the base unit.
"""
self._shutdown = True
# Close connection if needed
self._protocol.close()
# Cancel any pending tasks
self.cancel_pending_tasks() | python | def stop(self) -> None:
"""
Stop monitoring the base unit.
"""
self._shutdown = True
# Close connection if needed
self._protocol.close()
# Cancel any pending tasks
self.cancel_pending_tasks() | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_shutdown",
"=",
"True",
"# Close connection if needed",
"self",
".",
"_protocol",
".",
"close",
"(",
")",
"# Cancel any pending tasks",
"self",
".",
"cancel_pending_tasks",
"(",
")"
] | Stop monitoring the base unit. | [
"Stop",
"monitoring",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L300-L311 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_clear_status | async def async_clear_status(self, password: str = '') -> None:
"""
Clear the alarm/warning LEDs on base unit and stop siren.
:param password: if specified, will be used instead of the password
property when issuing the command
"""
await self._protocol.... | python | async def async_clear_status(self, password: str = '') -> None:
"""
Clear the alarm/warning LEDs on base unit and stop siren.
:param password: if specified, will be used instead of the password
property when issuing the command
"""
await self._protocol.... | [
"async",
"def",
"async_clear_status",
"(",
"self",
",",
"password",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"ClearStatusCommand",
"(",
")",
",",
"password",
"=",
"password",
")"
] | Clear the alarm/warning LEDs on base unit and stop siren.
:param password: if specified, will be used instead of the password
property when issuing the command | [
"Clear",
"the",
"alarm",
"/",
"warning",
"LEDs",
"on",
"base",
"unit",
"and",
"stop",
"siren",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L313-L323 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_change_device | async def async_change_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags) -> None:
"""
Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:... | python | async def async_change_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags) -> None:
"""
Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:... | [
"async",
"def",
"async_change_device",
"(",
"self",
",",
"device_id",
":",
"int",
",",
"group_number",
":",
"int",
",",
"unit_number",
":",
"int",
",",
"enable_status",
":",
"ESFlags",
",",
"switches",
":",
"SwitchFlags",
")",
"->",
"None",
":",
"# Lookup de... | Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settin... | [
"Change",
"settings",
"for",
"a",
"device",
"on",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L335-L371 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_change_special_device | async def async_change_special_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags,
special_status: SSFlags, high_limit: Optional[Union[int, float]],
low_limit: Optional[Union[int, float]],
control_h... | python | async def async_change_special_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags,
special_status: SSFlags, high_limit: Optional[Union[int, float]],
low_limit: Optional[Union[int, float]],
control_h... | [
"async",
"def",
"async_change_special_device",
"(",
"self",
",",
"device_id",
":",
"int",
",",
"group_number",
":",
"int",
",",
"unit_number",
":",
"int",
",",
"enable_status",
":",
"ESFlags",
",",
"switches",
":",
"SwitchFlags",
",",
"special_status",
":",
"S... | Change settings for a 'Special' device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicat... | [
"Change",
"settings",
"for",
"a",
"Special",
"device",
"on",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L373-L423 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_delete_device | async def async_delete_device(self, device_id: int) -> None:
"""
Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted
"""
# Lookup device using zone to obtain an accurate index, which is
# needed to perform the delete command
... | python | async def async_delete_device(self, device_id: int) -> None:
"""
Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted
"""
# Lookup device using zone to obtain an accurate index, which is
# needed to perform the delete command
... | [
"async",
"def",
"async_delete_device",
"(",
"self",
",",
"device_id",
":",
"int",
")",
"->",
"None",
":",
"# Lookup device using zone to obtain an accurate index, which is",
"# needed to perform the delete command",
"device",
"=",
"self",
".",
"_devices",
"[",
"device_id",
... | Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted | [
"Delete",
"an",
"enrolled",
"device",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L425-L450 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_get_datetime | async def async_get_datetime(self) -> Optional[datetime]:
"""
Get the date/time on the base unit.
:return: the date/time to be set on the base unit.
"""
response = await self._protocol.async_execute(
GetDateTimeCommand())
if isinstance(response, DateTimeResp... | python | async def async_get_datetime(self) -> Optional[datetime]:
"""
Get the date/time on the base unit.
:return: the date/time to be set on the base unit.
"""
response = await self._protocol.async_execute(
GetDateTimeCommand())
if isinstance(response, DateTimeResp... | [
"async",
"def",
"async_get_datetime",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
"]",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetDateTimeCommand",
"(",
")",
")",
"if",
"isinstance",
"(",
"response",
",",... | Get the date/time on the base unit.
:return: the date/time to be set on the base unit. | [
"Get",
"the",
"date",
"/",
"time",
"on",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L452-L463 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_get_event_log | async def async_get_event_log(self, index: int) -> Optional[EventLogResponse]:
"""
Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found.
"""
response = await s... | python | async def async_get_event_log(self, index: int) -> Optional[EventLogResponse]:
"""
Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found.
"""
response = await s... | [
"async",
"def",
"async_get_event_log",
"(",
"self",
",",
"index",
":",
"int",
")",
"->",
"Optional",
"[",
"EventLogResponse",
"]",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetEventLogCommand",
"(",
"index",
")",
")... | Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found. | [
"Get",
"an",
"entry",
"from",
"the",
"event",
"log",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L465-L477 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_get_sensor_log | async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
"""
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
"""
respo... | python | async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
"""
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
"""
respo... | [
"async",
"def",
"async_get_sensor_log",
"(",
"self",
",",
"index",
":",
"int",
")",
"->",
"Optional",
"[",
"SensorLogResponse",
"]",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetSensorLogCommand",
"(",
"index",
")",
... | Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found. | [
"Get",
"an",
"entry",
"from",
"the",
"Special",
"sensor",
"log",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L479-L491 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_set_operation_mode | async def async_set_operation_mode(
self, operation_mode: OperationMode, password: str = '') -> None:
"""
Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
... | python | async def async_set_operation_mode(
self, operation_mode: OperationMode, password: str = '') -> None:
"""
Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
... | [
"async",
"def",
"async_set_operation_mode",
"(",
"self",
",",
"operation_mode",
":",
"OperationMode",
",",
"password",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"SetOpModeCommand",
"(",
"operat... | Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
property when issuing the command | [
"Set",
"the",
"operation",
"mode",
"on",
"the",
"base",
"unit",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L504-L516 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_set_switch_state | async def async_set_switch_state(
self, switch_number: SwitchNumber, state: bool) -> None:
"""
Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off.
"""
await self._protocol.async_execute(
... | python | async def async_set_switch_state(
self, switch_number: SwitchNumber, state: bool) -> None:
"""
Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off.
"""
await self._protocol.async_execute(
... | [
"async",
"def",
"async_set_switch_state",
"(",
"self",
",",
"switch_number",
":",
"SwitchNumber",
",",
"state",
":",
"bool",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"SetSwitchCommand",
"(",
"switch_number",
",",
"S... | Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off. | [
"Turn",
"a",
"switch",
"on",
"or",
"off",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L518-L530 |
rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.as_dict | def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
... | python | def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
... | [
"def",
"as_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"_on_filter",
"(",
"obj",
":",
"Any",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"# Filter out any callbacks",
"if",
"isinstance",
"(",
"obj",
",",
"Base... | Converts to a dict of attributes for easier serialization. | [
"Converts",
"to",
"a",
"dict",
"of",
"attributes",
"for",
"easier",
"serialization",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L539-L548 |
pschmitt/zhue | zhue/model/basemodel.py | HueBaseObject.update | def update(self):
'''
Update our object's data
'''
self._json = self._request(
method='GET',
url=self.API
)._json | python | def update(self):
'''
Update our object's data
'''
self._json = self._request(
method='GET',
url=self.API
)._json | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_json",
"=",
"self",
".",
"_request",
"(",
"method",
"=",
"'GET'",
",",
"url",
"=",
"self",
".",
"API",
")",
".",
"_json"
] | Update our object's data | [
"Update",
"our",
"object",
"s",
"data"
] | train | https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L38-L45 |
pschmitt/zhue | zhue/model/basemodel.py | HueObject.address | def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | python | def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | [
"def",
"address",
"(",
"self",
")",
":",
"return",
"self",
".",
"API",
".",
"replace",
"(",
"'http://{}:{}'",
".",
"format",
"(",
"self",
".",
"_bridge",
".",
"hostname",
",",
"self",
".",
"_bridge",
".",
"port",
")",
",",
"''",
")"
] | Return the address of this "object", minus the scheme, hostname
and port of the bridge | [
"Return",
"the",
"address",
"of",
"this",
"object",
"minus",
"the",
"scheme",
"hostname",
"and",
"port",
"of",
"the",
"bridge"
] | train | https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L65-L75 |
Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._load_bundle_map | def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id.
'''
bundl... | python | def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id.
'''
bundl... | [
"def",
"_load_bundle_map",
"(",
"self",
")",
":",
"bundle_map",
"=",
"{",
"}",
"next_href",
"=",
"None",
"has_next",
"=",
"True",
"while",
"has_next",
":",
"bundles",
"=",
"self",
".",
"clarify_client",
".",
"get_bundle_list",
"(",
"href",
"=",
"next_href",
... | Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id. | [
"Return",
"a",
"map",
"of",
"all",
"bundles",
"in",
"the",
"Clarify",
"app",
"that",
"have",
"an",
"external_id",
"set",
"for",
"them",
".",
"The",
"bundles",
"with",
"external_ids",
"set",
"are",
"assumed",
"to",
"be",
"the",
"ones",
"we",
"have",
"inse... | train | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L29-L49 |
Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._metadata_from_video | def _metadata_from_video(self, video):
'''Generate the searchable metadata that we'll store in the bundle for the video'''
long_desc = video['long_description']
if long_desc is not None:
long_desc = long_desc[:MAX_METADATA_STRING_LEN]
tags = video.get('tags')
metada... | python | def _metadata_from_video(self, video):
'''Generate the searchable metadata that we'll store in the bundle for the video'''
long_desc = video['long_description']
if long_desc is not None:
long_desc = long_desc[:MAX_METADATA_STRING_LEN]
tags = video.get('tags')
metada... | [
"def",
"_metadata_from_video",
"(",
"self",
",",
"video",
")",
":",
"long_desc",
"=",
"video",
"[",
"'long_description'",
"]",
"if",
"long_desc",
"is",
"not",
"None",
":",
"long_desc",
"=",
"long_desc",
"[",
":",
"MAX_METADATA_STRING_LEN",
"]",
"tags",
"=",
... | Generate the searchable metadata that we'll store in the bundle for the video | [
"Generate",
"the",
"searchable",
"metadata",
"that",
"we",
"ll",
"store",
"in",
"the",
"bundle",
"for",
"the",
"video"
] | train | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L51-L68 |
Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._src_media_url_for_video | def _src_media_url_for_video(self, video):
'''Get the url for the video media that we can send to Clarify'''
src_url = None
best_height = 0
best_source = None
# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True
# and if so, u... | python | def _src_media_url_for_video(self, video):
'''Get the url for the video media that we can send to Clarify'''
src_url = None
best_height = 0
best_source = None
# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True
# and if so, u... | [
"def",
"_src_media_url_for_video",
"(",
"self",
",",
"video",
")",
":",
"src_url",
"=",
"None",
"best_height",
"=",
"0",
"best_source",
"=",
"None",
"# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True",
"# and if so, use the src url ... | Get the url for the video media that we can send to Clarify | [
"Get",
"the",
"url",
"for",
"the",
"video",
"media",
"that",
"we",
"can",
"send",
"to",
"Clarify"
] | train | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L70-L88 |
Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._update_metadata_for_video | def _update_metadata_for_video(self, metadata_href, video):
'''
Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated.
'''
current_metadata = self.clarify_client.get_metadata(metadata_href)
cur_data = current_... | python | def _update_metadata_for_video(self, metadata_href, video):
'''
Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated.
'''
current_metadata = self.clarify_client.get_metadata(metadata_href)
cur_data = current_... | [
"def",
"_update_metadata_for_video",
"(",
"self",
",",
"metadata_href",
",",
"video",
")",
":",
"current_metadata",
"=",
"self",
".",
"clarify_client",
".",
"get_metadata",
"(",
"metadata_href",
")",
"cur_data",
"=",
"current_metadata",
".",
"get",
"(",
"'data'",
... | Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated. | [
"Update",
"the",
"metadata",
"for",
"the",
"video",
"if",
"video",
"has",
"been",
"updated",
"in",
"Brightcove",
"since",
"the",
"bundle",
"metadata",
"was",
"last",
"updated",
"."
] | train | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L107-L120 |
storborg/replaylib | replaylib/noseplugin.py | ReplayLibPlugin.options | def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="FILE",
dest="record_filename",
help="Record actions to this... | python | def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="FILE",
dest="record_filename",
help="Record actions to this... | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"parser",
".",
"add_option",
"(",
"\"--%s-record\"",
"%",
"self",
".",
"name",
",",
"action",
"=",
"\"store\"",
",",
"metavar",
"=",
"\"FILE\"",
",",
"dest",... | Add options to nosetests. | [
"Add",
"options",
"to",
"nosetests",
"."
] | train | https://github.com/storborg/replaylib/blob/16bc3752bb992e3fb364fce9bd7c3f95e887a42d/replaylib/noseplugin.py#L14-L25 |
westerncapelabs/django-messaging-subscription | subscription/tasks.py | ingest_csv | def ingest_csv(csv_data, message_set):
""" Expecting data in the following format:
message_id,en,safe,af,safe,zu,safe,xh,safe,ve,safe,tn,safe,ts,safe,ss,safe,st,safe,nso,safe,nr,safe
"""
records = csv.DictReader(csv_data)
for line in records:
for key in line:
# Ignore non-content... | python | def ingest_csv(csv_data, message_set):
""" Expecting data in the following format:
message_id,en,safe,af,safe,zu,safe,xh,safe,ve,safe,tn,safe,ts,safe,ss,safe,st,safe,nso,safe,nr,safe
"""
records = csv.DictReader(csv_data)
for line in records:
for key in line:
# Ignore non-content... | [
"def",
"ingest_csv",
"(",
"csv_data",
",",
"message_set",
")",
":",
"records",
"=",
"csv",
".",
"DictReader",
"(",
"csv_data",
")",
"for",
"line",
"in",
"records",
":",
"for",
"key",
"in",
"line",
":",
"# Ignore non-content keys and empty keys",
"if",
"key",
... | Expecting data in the following format:
message_id,en,safe,af,safe,zu,safe,xh,safe,ve,safe,tn,safe,ts,safe,ss,safe,st,safe,nso,safe,nr,safe | [
"Expecting",
"data",
"in",
"the",
"following",
"format",
":",
"message_id",
"en",
"safe",
"af",
"safe",
"zu",
"safe",
"xh",
"safe",
"ve",
"safe",
"tn",
"safe",
"ts",
"safe",
"ss",
"safe",
"st",
"safe",
"nso",
"safe",
"nr",
"safe"
] | train | https://github.com/westerncapelabs/django-messaging-subscription/blob/7af7021cdd6c02b0dfd4b617b9274401972dbaf8/subscription/tasks.py#L19-L39 |
westerncapelabs/django-messaging-subscription | subscription/tasks.py | ensure_one_subscription | def ensure_one_subscription():
"""
Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily
"""
cursor = connection.cursor()
cursor.execute("UPDATE subscription_subscription SET active = False \
WHERE id NOT IN \
... | python | def ensure_one_subscription():
"""
Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily
"""
cursor = connection.cursor()
cursor.execute("UPDATE subscription_subscription SET active = False \
WHERE id NOT IN \
... | [
"def",
"ensure_one_subscription",
"(",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"UPDATE subscription_subscription SET active = False \\\n WHERE id NOT IN \\\n (SELECT MAX(id) as id FROM \\\n ... | Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily | [
"Fixes",
"issues",
"caused",
"by",
"upstream",
"failures",
"that",
"lead",
"to",
"users",
"having",
"multiple",
"active",
"subscriptions",
"Runs",
"daily"
] | train | https://github.com/westerncapelabs/django-messaging-subscription/blob/7af7021cdd6c02b0dfd4b617b9274401972dbaf8/subscription/tasks.py#L43-L57 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | _get_encoding | def _get_encoding(dom, default="utf-8"):
"""
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given en... | python | def _get_encoding(dom, default="utf-8"):
"""
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given en... | [
"def",
"_get_encoding",
"(",
"dom",
",",
"default",
"=",
"\"utf-8\"",
")",
":",
"encoding",
"=",
"dom",
".",
"find",
"(",
"\"meta\"",
",",
"{",
"\"http-equiv\"",
":",
"\"Content-Type\"",
"}",
")",
"if",
"not",
"encoding",
":",
"return",
"default",
"encodin... | Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given encoding or `default` parameter if not found. | [
"Try",
"to",
"look",
"for",
"meta",
"tag",
"in",
"given",
"dom",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L41-L63 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | handle_encodnig | def handle_encodnig(html):
"""
Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF.
"""
encoding = _get_encoding(
dhtmlparser.parseString(
html.split("</head>")[0]
... | python | def handle_encodnig(html):
"""
Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF.
"""
encoding = _get_encoding(
dhtmlparser.parseString(
html.split("</head>")[0]
... | [
"def",
"handle_encodnig",
"(",
"html",
")",
":",
"encoding",
"=",
"_get_encoding",
"(",
"dhtmlparser",
".",
"parseString",
"(",
"html",
".",
"split",
"(",
"\"</head>\"",
")",
"[",
"0",
"]",
")",
")",
"if",
"encoding",
"==",
"\"utf-8\"",
":",
"return",
"h... | Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF. | [
"Look",
"for",
"encoding",
"in",
"given",
"html",
".",
"Try",
"to",
"convert",
"html",
"to",
"utf",
"-",
"8",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L66-L85 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | is_equal_tag | def is_equal_tag(element, tag_name, params, content):
"""
Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Par... | python | def is_equal_tag(element, tag_name, params, content):
"""
Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Par... | [
"def",
"is_equal_tag",
"(",
"element",
",",
"tag_name",
",",
"params",
",",
"content",
")",
":",
"if",
"tag_name",
"and",
"tag_name",
"!=",
"element",
".",
"getTagName",
"(",
")",
":",
"return",
"False",
"if",
"params",
"and",
"not",
"element",
".",
"con... | Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Parameters of the tag.
content (str): Content of the tag.
... | [
"Check",
"is",
"element",
"object",
"match",
"rest",
"of",
"the",
"parameters",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L88-L112 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | has_neigh | def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this param... | python | def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this param... | [
"def",
"has_neigh",
"(",
"tag_name",
",",
"params",
"=",
"None",
",",
"content",
"=",
"None",
",",
"left",
"=",
"True",
")",
":",
"def",
"has_neigh_closure",
"(",
"element",
")",
":",
"if",
"not",
"element",
".",
"parent",
"or",
"not",
"(",
"element",
... | This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
... | [
"This",
"function",
"generates",
"functions",
"which",
"matches",
"all",
"tags",
"with",
"neighbours",
"defined",
"by",
"parameters",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L115-L158 |
AnnAnnFryingPan/data_hub_call | build/lib/data_hub_call/dataHubCallTriangulum.py | DataHubCallTriangulum.call_api_fetch | def call_api_fetch(self, params, get_latest_only=True):
"""
GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1
Host: myserver
Accept: application / json"""
output_format = 'application/json'
... | python | def call_api_fetch(self, params, get_latest_only=True):
"""
GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1
Host: myserver
Accept: application / json"""
output_format = 'application/json'
... | [
"def",
"call_api_fetch",
"(",
"self",
",",
"params",
",",
"get_latest_only",
"=",
"True",
")",
":",
"output_format",
"=",
"'application/json'",
"url_string",
"=",
"self",
".",
"request_info",
".",
"url_string",
"(",
")",
"# passing the username and required output for... | GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1
Host: myserver
Accept: application / json | [
"GET",
"https",
":",
"//",
"myserver",
"/",
"piwebapi",
"/",
"assetdatabases",
"/",
"D0NxzXSxtlKkGzAhZfHOB",
"-",
"KAQLhZ5wrU",
"-",
"UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg",
"HTTP",
"/",
"1",
".",
"1",
"Host",
":",
"myserver",
"Accept",
":",
"application",
"/",
"j... | train | https://github.com/AnnAnnFryingPan/data_hub_call/blob/907a481bb2adfff86d311bdf5a4fa352fd7e90be/build/lib/data_hub_call/dataHubCallTriangulum.py#L63-L134 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/__init__.py | reactToAMQPMessage | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | python | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"send_back",
")",
":",
"_hnas_protection",
"(",
")",
"if",
"_instanceof",
"(",
"message",
",",
"SaveRequest",
")",
":",
"# Tree",
"if",
"_instanceof",
"(",
"message",
".",
"record",
",",
"Tree",
")",
":",
"... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference)... | [
"React",
"to",
"given",
"(",
"AMQP",
")",
"message",
".",
"message",
"is",
"expected",
"to",
"be",
":",
"py",
":",
"func",
":",
"collections",
".",
"namedtuple",
"structure",
"from",
":",
"mod",
":",
".",
"structures",
"filled",
"with",
"all",
"necessary... | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/__init__.py#L66-L133 |
majek/rons | rons/parse_url.py | parse_redis_url | def parse_redis_url(redis_url):
'''
>>> parse_redis_url('redis://:pass%20@localhost:1234/selecteddb%20')
('localhost', 1234, 'pass ', 'selecteddb ')
>>> parse_redis_url('redis://:pass%20@localhost:1234/')
('localhost', 1234, 'pass ', None)
>>> parse_redis_url('redis://localhost:1234/')
('loc... | python | def parse_redis_url(redis_url):
'''
>>> parse_redis_url('redis://:pass%20@localhost:1234/selecteddb%20')
('localhost', 1234, 'pass ', 'selecteddb ')
>>> parse_redis_url('redis://:pass%20@localhost:1234/')
('localhost', 1234, 'pass ', None)
>>> parse_redis_url('redis://localhost:1234/')
('loc... | [
"def",
"parse_redis_url",
"(",
"redis_url",
")",
":",
"(",
"use",
",",
"pas",
",",
"hos",
",",
"por",
",",
"pat",
")",
"=",
"_parse_url",
"(",
"redis_url",
",",
"'redis://'",
",",
"def_port",
"=",
"6379",
")",
"return",
"(",
"hos",
",",
"por",
",",
... | >>> parse_redis_url('redis://:pass%20@localhost:1234/selecteddb%20')
('localhost', 1234, 'pass ', 'selecteddb ')
>>> parse_redis_url('redis://:pass%20@localhost:1234/')
('localhost', 1234, 'pass ', None)
>>> parse_redis_url('redis://localhost:1234/')
('localhost', 1234, None, None)
>>> parse_red... | [
">>>",
"parse_redis_url",
"(",
"redis",
":",
"//",
":",
"pass%20"
] | train | https://github.com/majek/rons/blob/0d375b5e99ade7989dfaf376b8718650ef70e7e9/rons/parse_url.py#L4-L22 |
radjkarl/appBase | setup.py | read | def read(*paths):
"""Build a file path from *paths* and return the contents."""
p = os.path.join(*paths)
if os.path.exists(p):
with open(p, 'r') as f:
return f.read()
return '' | python | def read(*paths):
"""Build a file path from *paths* and return the contents."""
p = os.path.join(*paths)
if os.path.exists(p):
with open(p, 'r') as f:
return f.read()
return '' | [
"def",
"read",
"(",
"*",
"paths",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"paths",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
":",
"with",
"open",
"(",
"p",
",",
"'r'",
")",
"as",
"f",
":",
"return",
... | Build a file path from *paths* and return the contents. | [
"Build",
"a",
"file",
"path",
"from",
"*",
"paths",
"*",
"and",
"return",
"the",
"contents",
"."
] | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/setup.py#L36-L42 |
cfobel/clutter-webcam-viewer | clutter_webcam_viewer/pipeline_manager.py | RecordPipeline.run | def run(self, output_path, device_config=None, bitrate=350 << 3 << 10,
sink=None):
'''
Run webcam pipeline and optionally record the video to the specified
output file path.
__NB__ The output file container is determined based on the extension
of the output file path... | python | def run(self, output_path, device_config=None, bitrate=350 << 3 << 10,
sink=None):
'''
Run webcam pipeline and optionally record the video to the specified
output file path.
__NB__ The output file container is determined based on the extension
of the output file path... | [
"def",
"run",
"(",
"self",
",",
"output_path",
",",
"device_config",
"=",
"None",
",",
"bitrate",
"=",
"350",
"<<",
"3",
"<<",
"10",
",",
"sink",
"=",
"None",
")",
":",
"# Create GStreamer pipeline",
"self",
".",
"pipeline",
"=",
"Gst",
".",
"Pipeline",
... | Run webcam pipeline and optionally record the video to the specified
output file path.
__NB__ The output file container is determined based on the extension
of the output file path. Supported containers are `avi` and `mp4`. In
either case, the video is encoded in MPEG4 format.
... | [
"Run",
"webcam",
"pipeline",
"and",
"optionally",
"record",
"the",
"video",
"to",
"the",
"specified",
"output",
"file",
"path",
"."
] | train | https://github.com/cfobel/clutter-webcam-viewer/blob/b227d2ae02d750194e65c13bcf178550755c3afc/clutter_webcam_viewer/pipeline_manager.py#L50-L145 |
kshlm/gant | gant/main.py | gant | def gant(ctx, conf, basedir, basetag, maintag, prefix, verbose):
"""
GAnt : The Gluster helper ant\n
Creates GlusterFS development and testing environments using Docker
"""
ctx.obj.initConf(basetag, maintag, basedir, prefix, verbose)
ctx.obj.gd.setConf(ctx.obj.conf) | python | def gant(ctx, conf, basedir, basetag, maintag, prefix, verbose):
"""
GAnt : The Gluster helper ant\n
Creates GlusterFS development and testing environments using Docker
"""
ctx.obj.initConf(basetag, maintag, basedir, prefix, verbose)
ctx.obj.gd.setConf(ctx.obj.conf) | [
"def",
"gant",
"(",
"ctx",
",",
"conf",
",",
"basedir",
",",
"basetag",
",",
"maintag",
",",
"prefix",
",",
"verbose",
")",
":",
"ctx",
".",
"obj",
".",
"initConf",
"(",
"basetag",
",",
"maintag",
",",
"basedir",
",",
"prefix",
",",
"verbose",
")",
... | GAnt : The Gluster helper ant\n
Creates GlusterFS development and testing environments using Docker | [
"GAnt",
":",
"The",
"Gluster",
"helper",
"ant",
"\\",
"n",
"Creates",
"GlusterFS",
"development",
"and",
"testing",
"environments",
"using",
"Docker"
] | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/main.py#L76-L82 |
mitakas/wallpaper | wallpaper/wallpaper.py | Wallpaper.paint | def paint(self):
"""
Saves the wallpaper as the specified filename.
"""
# nice blue color
self.image = Image.new(mode='RGB', size=(self.width, self.height),
color=(47, 98, 135))
self.paint_pattern()
self.image.save(fp=self.filename) | python | def paint(self):
"""
Saves the wallpaper as the specified filename.
"""
# nice blue color
self.image = Image.new(mode='RGB', size=(self.width, self.height),
color=(47, 98, 135))
self.paint_pattern()
self.image.save(fp=self.filename) | [
"def",
"paint",
"(",
"self",
")",
":",
"# nice blue color",
"self",
".",
"image",
"=",
"Image",
".",
"new",
"(",
"mode",
"=",
"'RGB'",
",",
"size",
"=",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
",",
"color",
"=",
"(",
"47",
","... | Saves the wallpaper as the specified filename. | [
"Saves",
"the",
"wallpaper",
"as",
"the",
"specified",
"filename",
"."
] | train | https://github.com/mitakas/wallpaper/blob/83d90f56cf888d39c98aeb84e0e64d1289e4d0c0/wallpaper/wallpaper.py#L37-L46 |
seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.cdn_get_conf | def cdn_get_conf(self, cname, environment):
"""
Returns the existing origin configuration and token from the CDN
"""
response = self.client.service.cdn_get_conf(cname, environment)
cdn_config = CotendoCDN(response)
return cdn_config | python | def cdn_get_conf(self, cname, environment):
"""
Returns the existing origin configuration and token from the CDN
"""
response = self.client.service.cdn_get_conf(cname, environment)
cdn_config = CotendoCDN(response)
return cdn_config | [
"def",
"cdn_get_conf",
"(",
"self",
",",
"cname",
",",
"environment",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"service",
".",
"cdn_get_conf",
"(",
"cname",
",",
"environment",
")",
"cdn_config",
"=",
"CotendoCDN",
"(",
"response",
")",
"retu... | Returns the existing origin configuration and token from the CDN | [
"Returns",
"the",
"existing",
"origin",
"configuration",
"and",
"token",
"from",
"the",
"CDN"
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L67-L73 |
seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.cdn_set_conf | def cdn_set_conf(self, cname, originConf, environment, token):
"""
The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the parameters.
... | python | def cdn_set_conf(self, cname, originConf, environment, token):
"""
The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the parameters.
... | [
"def",
"cdn_set_conf",
"(",
"self",
",",
"cname",
",",
"originConf",
",",
"environment",
",",
"token",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"cdn_set_conf",
"(",
"cname",
",",
"originConf",
",",
"environment",
",",
"token",
")"
] | The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the parameters.
The set action is valid only if the token returned is equal to
the ... | [
"The",
"cdn_set_conf",
"method",
"enables",
"the",
"user",
"to",
"update",
"an",
"existing",
"origin",
"configuration",
"in",
"the",
"CDN",
"."
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L81-L93 |
seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.dns_get_conf | def dns_get_conf(self, domainName, environment):
"""
Returns the existing domain configuration and token from the ADNS
"""
response = self.client.service.dns_get_conf(domainName, environment)
dns_config = CotendoDNS(response)
return dns_config | python | def dns_get_conf(self, domainName, environment):
"""
Returns the existing domain configuration and token from the ADNS
"""
response = self.client.service.dns_get_conf(domainName, environment)
dns_config = CotendoDNS(response)
return dns_config | [
"def",
"dns_get_conf",
"(",
"self",
",",
"domainName",
",",
"environment",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"service",
".",
"dns_get_conf",
"(",
"domainName",
",",
"environment",
")",
"dns_config",
"=",
"CotendoDNS",
"(",
"response",
")... | Returns the existing domain configuration and token from the ADNS | [
"Returns",
"the",
"existing",
"domain",
"configuration",
"and",
"token",
"from",
"the",
"ADNS"
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L95-L101 |
seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.dns_set_conf | def dns_set_conf(self, domainName, domainConf, environment, token):
"""
The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the paramete... | python | def dns_set_conf(self, domainName, domainConf, environment, token):
"""
The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the paramete... | [
"def",
"dns_set_conf",
"(",
"self",
",",
"domainName",
",",
"domainConf",
",",
"environment",
",",
"token",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"dns_set_conf",
"(",
"domainName",
",",
"domainConf",
",",
"environment",
",",
"token"... | The cdn_set_conf method enables the user to update an existing
origin configuration in the CDN.
The cdn_get_conf returns the token in the response and the
cdn_set_conf requires a token as one of the parameters.
The set action is valid only if the token returned is equal to
the ... | [
"The",
"cdn_set_conf",
"method",
"enables",
"the",
"user",
"to",
"update",
"an",
"existing",
"origin",
"configuration",
"in",
"the",
"CDN",
"."
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L109-L121 |
seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.doFlush | def doFlush(self, cname, flushExpression, flushType):
"""
doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). *
"""
... | python | def doFlush(self, cname, flushExpression, flushType):
"""
doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). *
"""
... | [
"def",
"doFlush",
"(",
"self",
",",
"cname",
",",
"flushExpression",
",",
"flushType",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"doFlush",
"(",
"cname",
",",
"flushExpression",
",",
"flushType",
")"
] | doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). * | [
"doFlush",
"method",
"enables",
"specific",
"content",
"to",
"be",
"flushed",
"from",
"the",
"cache",
"servers",
"."
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L129-L138 |
seryl/Python-Cotendo | cotendo/__init__.py | CotendoHelper.UpdateDNS | def UpdateDNS(self, domain, environment):
"""Pushes DNS updates"""
self.dns_set_conf(domain, self.dns.config,
environment, self.dns.token) | python | def UpdateDNS(self, domain, environment):
"""Pushes DNS updates"""
self.dns_set_conf(domain, self.dns.config,
environment, self.dns.token) | [
"def",
"UpdateDNS",
"(",
"self",
",",
"domain",
",",
"environment",
")",
":",
"self",
".",
"dns_set_conf",
"(",
"domain",
",",
"self",
".",
"dns",
".",
"config",
",",
"environment",
",",
"self",
".",
"dns",
".",
"token",
")"
] | Pushes DNS updates | [
"Pushes",
"DNS",
"updates"
] | train | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L193-L196 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.