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 |
|---|---|---|---|---|---|---|---|---|---|---|
foliant-docs/foliantcontrib.flags | foliant/preprocessors/flags.py | Preprocessor.process_flagged_blocks | def process_flagged_blocks(self, content: str) -> str:
'''Replace flagged blocks either with their contents or nothing, depending on the value
of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value.
:param content: Markdown content
:returns: Markdown content without flagg... | python | def process_flagged_blocks(self, content: str) -> str:
'''Replace flagged blocks either with their contents or nothing, depending on the value
of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value.
:param content: Markdown content
:returns: Markdown content without flagg... | [
"def",
"process_flagged_blocks",
"(",
"self",
",",
"content",
":",
"str",
")",
"->",
"str",
":",
"def",
"_sub",
"(",
"flagged_block",
")",
":",
"options",
"=",
"self",
".",
"get_options",
"(",
"flagged_block",
".",
"group",
"(",
"'options'",
")",
")",
"r... | Replace flagged blocks either with their contents or nothing, depending on the value
of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value.
:param content: Markdown content
:returns: Markdown content without flagged blocks | [
"Replace",
"flagged",
"blocks",
"either",
"with",
"their",
"contents",
"or",
"nothing",
"depending",
"on",
"the",
"value",
"of",
"FOLIANT_FLAGS",
"environment",
"variable",
"and",
"flags",
"config",
"value",
"."
] | train | https://github.com/foliant-docs/foliantcontrib.flags/blob/467b46eb77b341ba989c6165f8d3bcae9532df6d/foliant/preprocessors/flags.py#L16-L64 |
hvishwanath/libpaas | libpaas/drivers/openshift.py | Openshift.getInstance | def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = Openshift(*args)
return cls.__singleton | python | def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = Openshift(*args)
return cls.__singleton | [
"def",
"getInstance",
"(",
"cls",
",",
"*",
"args",
")",
":",
"if",
"not",
"cls",
".",
"__singleton",
":",
"cls",
".",
"__singleton",
"=",
"Openshift",
"(",
"*",
"args",
")",
"return",
"cls",
".",
"__singleton"
] | Returns a singleton instance of the class | [
"Returns",
"a",
"singleton",
"instance",
"of",
"the",
"class"
] | train | https://github.com/hvishwanath/libpaas/blob/3df07adca59c003ee754c4e919cf506c13953be1/libpaas/drivers/openshift.py#L76-L82 |
hvishwanath/libpaas | libpaas/drivers/openshift.py | Openshift._verify_or_create_domain | def _verify_or_create_domain(self):
"""
Verify that a domain with the name self.domain exists. Else create it.
:return:
"""
# Get all domains registered with the user
r = requests.get(
url=self.server + "/domains",
auth=(self.username, self.passwo... | python | def _verify_or_create_domain(self):
"""
Verify that a domain with the name self.domain exists. Else create it.
:return:
"""
# Get all domains registered with the user
r = requests.get(
url=self.server + "/domains",
auth=(self.username, self.passwo... | [
"def",
"_verify_or_create_domain",
"(",
"self",
")",
":",
"# Get all domains registered with the user",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"self",
".",
"server",
"+",
"\"/domains\"",
",",
"auth",
"=",
"(",
"self",
".",
"username",
",",
"self",
... | Verify that a domain with the name self.domain exists. Else create it.
:return: | [
"Verify",
"that",
"a",
"domain",
"with",
"the",
"name",
"self",
".",
"domain",
"exists",
".",
"Else",
"create",
"it",
".",
":",
"return",
":"
] | train | https://github.com/hvishwanath/libpaas/blob/3df07adca59c003ee754c4e919cf506c13953be1/libpaas/drivers/openshift.py#L85-L131 |
abe-winter/pg13-py | pg13/treepath.py | sub_slots | def sub_slots(x,match_fn,path=(),arr=None,match=False,recurse_into_matches=True):
"""given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN).
return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match.
"""
# todo: rename match to topmatch for clari... | python | def sub_slots(x,match_fn,path=(),arr=None,match=False,recurse_into_matches=True):
"""given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN).
return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match.
"""
# todo: rename match to topmatch for clari... | [
"def",
"sub_slots",
"(",
"x",
",",
"match_fn",
",",
"path",
"=",
"(",
")",
",",
"arr",
"=",
"None",
",",
"match",
"=",
"False",
",",
"recurse_into_matches",
"=",
"True",
")",
":",
"# todo: rename match to topmatch for clarity",
"# todo: profiling suggests this get... | given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN).
return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match. | [
"given",
"a",
"BaseX",
"in",
"x",
"explore",
"its",
"ATTRS",
"(",
"doing",
"the",
"right",
"thing",
"for",
"VARLEN",
")",
".",
"return",
"a",
"list",
"of",
"tree",
"-",
"paths",
"(",
"i",
".",
"e",
".",
"tuples",
")",
"for",
"tree",
"children",
"th... | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/treepath.py#L36-L57 |
abe-winter/pg13-py | pg13/treepath.py | flatten_tree | def flatten_tree(test, enumerator, exp):
"""test is function(exp) >> bool.
mapper is function(expression) >> list of subexpressions.
returns [subexpression, ...].
"""
return sum((flatten_tree(test, enumerator, subx) for subx in enumerator(exp)), []) if test(exp) else [exp] | python | def flatten_tree(test, enumerator, exp):
"""test is function(exp) >> bool.
mapper is function(expression) >> list of subexpressions.
returns [subexpression, ...].
"""
return sum((flatten_tree(test, enumerator, subx) for subx in enumerator(exp)), []) if test(exp) else [exp] | [
"def",
"flatten_tree",
"(",
"test",
",",
"enumerator",
",",
"exp",
")",
":",
"return",
"sum",
"(",
"(",
"flatten_tree",
"(",
"test",
",",
"enumerator",
",",
"subx",
")",
"for",
"subx",
"in",
"enumerator",
"(",
"exp",
")",
")",
",",
"[",
"]",
")",
"... | test is function(exp) >> bool.
mapper is function(expression) >> list of subexpressions.
returns [subexpression, ...]. | [
"test",
"is",
"function",
"(",
"exp",
")",
">>",
"bool",
".",
"mapper",
"is",
"function",
"(",
"expression",
")",
">>",
"list",
"of",
"subexpressions",
".",
"returns",
"[",
"subexpression",
"...",
"]",
"."
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/treepath.py#L59-L64 |
abe-winter/pg13-py | pg13/treepath.py | PathTree.child | def child(self,index):
"helper for __getitem__/__setitem__"
if isinstance(index,tuple):
attr,i = index
return getattr(self,attr)[i]
else: return getattr(self,index) | python | def child(self,index):
"helper for __getitem__/__setitem__"
if isinstance(index,tuple):
attr,i = index
return getattr(self,attr)[i]
else: return getattr(self,index) | [
"def",
"child",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"tuple",
")",
":",
"attr",
",",
"i",
"=",
"index",
"return",
"getattr",
"(",
"self",
",",
"attr",
")",
"[",
"i",
"]",
"else",
":",
"return",
"getattr",
"(... | helper for __getitem__/__setitem__ | [
"helper",
"for",
"__getitem__",
"/",
"__setitem__"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/treepath.py#L9-L14 |
cogniteev/docido-python-sdk | docido_sdk/index/pipeline.py | IndexPipelineProvider.get_index_api | def get_index_api(self, service, docido_user_id, account_login, config):
""" Create a pipeline of :py:class:`docido_sdk.index.IndexAPIProcessor`
based on:
- The :py:class:`docido_sdk.index.IndexAPIConfigurationProvider`
which provides configuration to created
:py:class:`doci... | python | def get_index_api(self, service, docido_user_id, account_login, config):
""" Create a pipeline of :py:class:`docido_sdk.index.IndexAPIProcessor`
based on:
- The :py:class:`docido_sdk.index.IndexAPIConfigurationProvider`
which provides configuration to created
:py:class:`doci... | [
"def",
"get_index_api",
"(",
"self",
",",
"service",
",",
"docido_user_id",
",",
"account_login",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"config",
".",
"get_index_api_conf",
"(",
"service",
",",
"docido_user_id",
",",
"account_login",
",",
"confi... | Create a pipeline of :py:class:`docido_sdk.index.IndexAPIProcessor`
based on:
- The :py:class:`docido_sdk.index.IndexAPIConfigurationProvider`
which provides configuration to created
:py:class:`docido_sdk.index.IndexAPIProcessor`
- The :py:class:`docido_sdk.index.IndexPipeli... | [
"Create",
"a",
"pipeline",
"of",
":",
"py",
":",
"class",
":",
"docido_sdk",
".",
"index",
".",
"IndexAPIProcessor",
"based",
"on",
":"
] | train | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/index/pipeline.py#L24-L56 |
sternoru/goscalecms | goscale/views.py | form | def form(request):
""" Ajax handler for Google Form submition
"""
if request.method == 'POST':
url = request.POST['url']
submit_url = '%s%shl=%s' % (
url,
'&' if '?' in url else '?',
request.LANGUAGE_CODE
)
params = urllib.urlencode(request... | python | def form(request):
""" Ajax handler for Google Form submition
"""
if request.method == 'POST':
url = request.POST['url']
submit_url = '%s%shl=%s' % (
url,
'&' if '?' in url else '?',
request.LANGUAGE_CODE
)
params = urllib.urlencode(request... | [
"def",
"form",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"url",
"=",
"request",
".",
"POST",
"[",
"'url'",
"]",
"submit_url",
"=",
"'%s%shl=%s'",
"%",
"(",
"url",
",",
"'&'",
"if",
"'?'",
"in",
"url",
"else",
"'... | Ajax handler for Google Form submition | [
"Ajax",
"handler",
"for",
"Google",
"Form",
"submition"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/views.py#L18-L35 |
sternoru/goscalecms | goscale/views.py | signup | def signup(request, **kwargs):
"""
Overrides allauth.account.views.signup
"""
if not ALLAUTH:
return http.HttpResponse(_('allauth not installed...'))
if request.method == "POST" and 'login' in request.POST:
form_class = LoginForm
form = form_class(request.POST)
redire... | python | def signup(request, **kwargs):
"""
Overrides allauth.account.views.signup
"""
if not ALLAUTH:
return http.HttpResponse(_('allauth not installed...'))
if request.method == "POST" and 'login' in request.POST:
form_class = LoginForm
form = form_class(request.POST)
redire... | [
"def",
"signup",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"ALLAUTH",
":",
"return",
"http",
".",
"HttpResponse",
"(",
"_",
"(",
"'allauth not installed...'",
")",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
"and",
"'logi... | Overrides allauth.account.views.signup | [
"Overrides",
"allauth",
".",
"account",
".",
"views",
".",
"signup"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/views.py#L38-L52 |
veltzer/pypitools | pypitools/scripts/install_from_local.py | main | def main():
"""
Install a package from the local folder
:return:
"""
common.setup_main()
config = common.ConfigData()
dist_folder = 'dist'
if os.path.isdir(dist_folder):
shutil.rmtree(dist_folder)
args = [
'{}'.format(config.python),
'setup.py',
'sdis... | python | def main():
"""
Install a package from the local folder
:return:
"""
common.setup_main()
config = common.ConfigData()
dist_folder = 'dist'
if os.path.isdir(dist_folder):
shutil.rmtree(dist_folder)
args = [
'{}'.format(config.python),
'setup.py',
'sdis... | [
"def",
"main",
"(",
")",
":",
"common",
".",
"setup_main",
"(",
")",
"config",
"=",
"common",
".",
"ConfigData",
"(",
")",
"dist_folder",
"=",
"'dist'",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dist_folder",
")",
":",
"shutil",
".",
"rmtree",
"("... | Install a package from the local folder
:return: | [
"Install",
"a",
"package",
"from",
"the",
"local",
"folder",
":",
"return",
":"
] | train | https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/scripts/install_from_local.py#L14-L59 |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_panel.py | gp_panel | def gp_panel(version, skip):
"""example for a panel plot using QM12 data (see gp_xfac)
.. image:: pics/panelQM12.png
:width: 700 px
:param version: plot version / input subdir name
:type version: str
"""
scale = { # QM14 (19 GeV skip later, factor here only informational)
'19': 1.0340571932983775... | python | def gp_panel(version, skip):
"""example for a panel plot using QM12 data (see gp_xfac)
.. image:: pics/panelQM12.png
:width: 700 px
:param version: plot version / input subdir name
:type version: str
"""
scale = { # QM14 (19 GeV skip later, factor here only informational)
'19': 1.0340571932983775... | [
"def",
"gp_panel",
"(",
"version",
",",
"skip",
")",
":",
"scale",
"=",
"{",
"# QM14 (19 GeV skip later, factor here only informational)",
"'19'",
":",
"1.0340571932983775",
",",
"'200'",
":",
"1.0",
",",
"'39'",
":",
"0.7776679085382481",
",",
"'27'",
":",
"0.641... | example for a panel plot using QM12 data (see gp_xfac)
.. image:: pics/panelQM12.png
:width: 700 px
:param version: plot version / input subdir name
:type version: str | [
"example",
"for",
"a",
"panel",
"plot",
"using",
"QM12",
"data",
"(",
"see",
"gp_xfac",
")"
] | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_panel.py#L10-L100 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.execute_operation | def execute_operation(self, method="GET", ops_path="", payload=""):
"""
Executes a Kubernetes operation using the specified method against a path.
This is part of the low-level API.
:Parameters:
- `method`: The HTTP method to use, defaults to `GET`
- `ops_path`: Th... | python | def execute_operation(self, method="GET", ops_path="", payload=""):
"""
Executes a Kubernetes operation using the specified method against a path.
This is part of the low-level API.
:Parameters:
- `method`: The HTTP method to use, defaults to `GET`
- `ops_path`: Th... | [
"def",
"execute_operation",
"(",
"self",
",",
"method",
"=",
"\"GET\"",
",",
"ops_path",
"=",
"\"\"",
",",
"payload",
"=",
"\"\"",
")",
":",
"operation_path_URL",
"=",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"api_server",
",",
"ops_path",
"]",
")",
... | Executes a Kubernetes operation using the specified method against a path.
This is part of the low-level API.
:Parameters:
- `method`: The HTTP method to use, defaults to `GET`
- `ops_path`: The path of the operation, for example, `/api/v1/events` which would result in an overall:... | [
"Executes",
"a",
"Kubernetes",
"operation",
"using",
"the",
"specified",
"method",
"against",
"a",
"path",
".",
"This",
"is",
"part",
"of",
"the",
"low",
"-",
"level",
"API",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L40-L58 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.describe_resource | def describe_resource(self, resource_path):
"""
Describes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to describe, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc`
... | python | def describe_resource(self, resource_path):
"""
Describes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to describe, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc`
... | [
"def",
"describe_resource",
"(",
"self",
",",
"resource_path",
")",
":",
"res",
"=",
"self",
".",
"execute_operation",
"(",
"method",
"=",
"\"GET\"",
",",
"ops_path",
"=",
"resource_path",
")",
"return",
"res"
] | Describes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to describe, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc` | [
"Describes",
"a",
"resource",
"based",
"on",
"its",
"resource",
"path",
"(",
"the",
"URL",
"path",
"modulo",
"host",
"part",
")",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L60-L68 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.delete_resource | def delete_resource(self, resource_path):
"""
Deletes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to delete, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc`
"""
... | python | def delete_resource(self, resource_path):
"""
Deletes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to delete, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc`
"""
... | [
"def",
"delete_resource",
"(",
"self",
",",
"resource_path",
")",
":",
"res",
"=",
"self",
".",
"execute_operation",
"(",
"method",
"=",
"\"DELETE\"",
",",
"ops_path",
"=",
"resource_path",
")",
"logging",
".",
"info",
"(",
"\"Deleted resource %s\"",
"%",
"(",... | Deletes a resource based on its resource path (the URL path modulo host part).
:Parameters:
- `resource_path`: The path of the resource to delete, for example, `/api/v1/namespaces/default/replicationcontrollers/webserver-rc` | [
"Deletes",
"a",
"resource",
"based",
"on",
"its",
"resource",
"path",
"(",
"the",
"URL",
"path",
"modulo",
"host",
"part",
")",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L70-L79 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.create_rc | def create_rc(self, manifest_filename, namespace="default"):
"""
Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In whic... | python | def create_rc(self, manifest_filename, namespace="default"):
"""
Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In whic... | [
"def",
"create_rc",
"(",
"self",
",",
"manifest_filename",
",",
"namespace",
"=",
"\"default\"",
")",
":",
"rc_manifest",
",",
"rc_manifest_json",
"=",
"util",
".",
"load_yaml",
"(",
"filename",
"=",
"manifest_filename",
")",
"logging",
".",
"debug",
"(",
"\"%... | Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In which namespace the RC should be created, defaults to, well, `default` | [
"Creates",
"an",
"RC",
"based",
"on",
"a",
"manifest",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L81-L98 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.scale_rc | def scale_rc(self, manifest_filename, namespace="default", num_replicas=0):
"""
Changes the replicas of an RC based on a manifest.
Note that it defaults to 0, meaning to effectively disable this RC.
:Parameters:
- `manifest_filename`: The manifest file containing the Replicat... | python | def scale_rc(self, manifest_filename, namespace="default", num_replicas=0):
"""
Changes the replicas of an RC based on a manifest.
Note that it defaults to 0, meaning to effectively disable this RC.
:Parameters:
- `manifest_filename`: The manifest file containing the Replicat... | [
"def",
"scale_rc",
"(",
"self",
",",
"manifest_filename",
",",
"namespace",
"=",
"\"default\"",
",",
"num_replicas",
"=",
"0",
")",
":",
"rc_manifest",
",",
"rc_manifest_json",
"=",
"util",
".",
"load_yaml",
"(",
"filename",
"=",
"manifest_filename",
")",
"log... | Changes the replicas of an RC based on a manifest.
Note that it defaults to 0, meaning to effectively disable this RC.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespac... | [
"Changes",
"the",
"replicas",
"of",
"an",
"RC",
"based",
"on",
"a",
"manifest",
".",
"Note",
"that",
"it",
"defaults",
"to",
"0",
"meaning",
"to",
"effectively",
"disable",
"this",
"RC",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L100-L120 |
kubernauts/pyk | pyk/toolkit.py | KubeHTTPClient.create_svc | def create_svc(self, manifest_filename, namespace="default"):
"""
Creates a service based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml`
- `namespace`: In which namespace th... | python | def create_svc(self, manifest_filename, namespace="default"):
"""
Creates a service based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml`
- `namespace`: In which namespace th... | [
"def",
"create_svc",
"(",
"self",
",",
"manifest_filename",
",",
"namespace",
"=",
"\"default\"",
")",
":",
"svc_manifest",
",",
"svc_manifest_json",
"=",
"util",
".",
"load_yaml",
"(",
"filename",
"=",
"manifest_filename",
")",
"logging",
".",
"debug",
"(",
"... | Creates a service based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml`
- `namespace`: In which namespace the service should be created, defaults to, well, `default` | [
"Creates",
"a",
"service",
"based",
"on",
"a",
"manifest",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L122-L139 |
minhhoit/yacms | yacms/core/views.py | set_device | def set_device(request, device=""):
"""
Sets a device name in a cookie when a user explicitly wants to go
to the site for a particular device (eg mobile).
"""
response = redirect(add_cache_bypass(next_url(request) or "/"))
set_cookie(response, "yacms-device", device, 60 * 60 * 24 * 365)
retu... | python | def set_device(request, device=""):
"""
Sets a device name in a cookie when a user explicitly wants to go
to the site for a particular device (eg mobile).
"""
response = redirect(add_cache_bypass(next_url(request) or "/"))
set_cookie(response, "yacms-device", device, 60 * 60 * 24 * 365)
retu... | [
"def",
"set_device",
"(",
"request",
",",
"device",
"=",
"\"\"",
")",
":",
"response",
"=",
"redirect",
"(",
"add_cache_bypass",
"(",
"next_url",
"(",
"request",
")",
"or",
"\"/\"",
")",
")",
"set_cookie",
"(",
"response",
",",
"\"yacms-device\"",
",",
"de... | Sets a device name in a cookie when a user explicitly wants to go
to the site for a particular device (eg mobile). | [
"Sets",
"a",
"device",
"name",
"in",
"a",
"cookie",
"when",
"a",
"user",
"explicitly",
"wants",
"to",
"go",
"to",
"the",
"site",
"for",
"a",
"particular",
"device",
"(",
"eg",
"mobile",
")",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L42-L49 |
minhhoit/yacms | yacms/core/views.py | set_site | def set_site(request):
"""
Put the selected site ID into the session - posted to from
the "Select site" drop-down in the header of the admin. The
site ID is then used in favour of the current request's
domain in ``yacms.core.managers.CurrentSiteManager``.
"""
site_id = int(request.GET["site_... | python | def set_site(request):
"""
Put the selected site ID into the session - posted to from
the "Select site" drop-down in the header of the admin. The
site ID is then used in favour of the current request's
domain in ``yacms.core.managers.CurrentSiteManager``.
"""
site_id = int(request.GET["site_... | [
"def",
"set_site",
"(",
"request",
")",
":",
"site_id",
"=",
"int",
"(",
"request",
".",
"GET",
"[",
"\"site_id\"",
"]",
")",
"if",
"not",
"request",
".",
"user",
".",
"is_superuser",
":",
"try",
":",
"SitePermission",
".",
"objects",
".",
"get",
"(",
... | Put the selected site ID into the session - posted to from
the "Select site" drop-down in the header of the admin. The
site ID is then used in favour of the current request's
domain in ``yacms.core.managers.CurrentSiteManager``. | [
"Put",
"the",
"selected",
"site",
"ID",
"into",
"the",
"session",
"-",
"posted",
"to",
"from",
"the",
"Select",
"site",
"drop",
"-",
"down",
"in",
"the",
"header",
"of",
"the",
"admin",
".",
"The",
"site",
"ID",
"is",
"then",
"used",
"in",
"favour",
... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L53-L75 |
minhhoit/yacms | yacms/core/views.py | direct_to_template | def direct_to_template(request, template, extra_context=None, **kwargs):
"""
Replacement for Django's ``direct_to_template`` that uses
``TemplateResponse`` via ``yacms.utils.views.render``.
"""
context = extra_context or {}
context["params"] = kwargs
for (key, value) in context.items():
... | python | def direct_to_template(request, template, extra_context=None, **kwargs):
"""
Replacement for Django's ``direct_to_template`` that uses
``TemplateResponse`` via ``yacms.utils.views.render``.
"""
context = extra_context or {}
context["params"] = kwargs
for (key, value) in context.items():
... | [
"def",
"direct_to_template",
"(",
"request",
",",
"template",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"extra_context",
"or",
"{",
"}",
"context",
"[",
"\"params\"",
"]",
"=",
"kwargs",
"for",
"(",
"key",
",",... | Replacement for Django's ``direct_to_template`` that uses
``TemplateResponse`` via ``yacms.utils.views.render``. | [
"Replacement",
"for",
"Django",
"s",
"direct_to_template",
"that",
"uses",
"TemplateResponse",
"via",
"yacms",
".",
"utils",
".",
"views",
".",
"render",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L78-L88 |
minhhoit/yacms | yacms/core/views.py | edit | def edit(request):
"""
Process the inline editing form.
"""
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
if ... | python | def edit(request):
"""
Process the inline editing form.
"""
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
if ... | [
"def",
"edit",
"(",
"request",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"request",
".",
"POST",
"[",
"\"app\"",
"]",
",",
"request",
".",
"POST",
"[",
"\"model\"",
"]",
")",
"obj",
"=",
"model",
".",
"objects",
".",
"get",
"(",
"id",
... | Process the inline editing form. | [
"Process",
"the",
"inline",
"editing",
"form",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L92-L110 |
minhhoit/yacms | yacms/core/views.py | search | def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
... | python | def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
... | [
"def",
"search",
"(",
"request",
",",
"template",
"=",
"\"search_results.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"q\"",
",",
"\"\"",
")",
"page",
"=",
"request",
".",
"GET",
".",
"ge... | Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model. | [
"Display",
"search",
"results",
".",
"Takes",
"an",
"optional",
"contenttype",
"GET",
"parameter",
"in",
"the",
"form",
"app",
"-",
"name",
".",
"ModelName",
"to",
"limit",
"search",
"results",
"to",
"a",
"single",
"model",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L113-L136 |
minhhoit/yacms | yacms/core/views.py | static_proxy | def static_proxy(request):
"""
Serves TinyMCE plugins inside the inline popups and the uploadify
SWF, as these are normally static files, and will break with
cross-domain JavaScript errors if ``STATIC_URL`` is an external
host. URL for the file is passed in via querystring in the inline
popup pl... | python | def static_proxy(request):
"""
Serves TinyMCE plugins inside the inline popups and the uploadify
SWF, as these are normally static files, and will break with
cross-domain JavaScript errors if ``STATIC_URL`` is an external
host. URL for the file is passed in via querystring in the inline
popup pl... | [
"def",
"static_proxy",
"(",
"request",
")",
":",
"normalize",
"=",
"lambda",
"u",
":",
"(",
"\"//\"",
"+",
"u",
".",
"split",
"(",
"\"://\"",
")",
"[",
"-",
"1",
"]",
")",
"if",
"\"://\"",
"in",
"u",
"else",
"u",
"url",
"=",
"normalize",
"(",
"re... | Serves TinyMCE plugins inside the inline popups and the uploadify
SWF, as these are normally static files, and will break with
cross-domain JavaScript errors if ``STATIC_URL`` is an external
host. URL for the file is passed in via querystring in the inline
popup plugin template, and we then attempt to p... | [
"Serves",
"TinyMCE",
"plugins",
"inside",
"the",
"inline",
"popups",
"and",
"the",
"uploadify",
"SWF",
"as",
"these",
"are",
"normally",
"static",
"files",
"and",
"will",
"break",
"with",
"cross",
"-",
"domain",
"JavaScript",
"errors",
"if",
"STATIC_URL",
"is"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L140-L180 |
minhhoit/yacms | yacms/core/views.py | displayable_links_js | def displayable_links_js(request):
"""
Renders a list of url/title pairs for all ``Displayable`` subclass
instances into JSON that's used to populate a list of links in
TinyMCE.
"""
links = []
if "yacms.pages" in settings.INSTALLED_APPS:
from yacms.pages.models import Page
is... | python | def displayable_links_js(request):
"""
Renders a list of url/title pairs for all ``Displayable`` subclass
instances into JSON that's used to populate a list of links in
TinyMCE.
"""
links = []
if "yacms.pages" in settings.INSTALLED_APPS:
from yacms.pages.models import Page
is... | [
"def",
"displayable_links_js",
"(",
"request",
")",
":",
"links",
"=",
"[",
"]",
"if",
"\"yacms.pages\"",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"from",
"yacms",
".",
"pages",
".",
"models",
"import",
"Page",
"is_page",
"=",
"lambda",
"obj",
":",
"i... | Renders a list of url/title pairs for all ``Displayable`` subclass
instances into JSON that's used to populate a list of links in
TinyMCE. | [
"Renders",
"a",
"list",
"of",
"url",
"/",
"title",
"pairs",
"for",
"all",
"Displayable",
"subclass",
"instances",
"into",
"JSON",
"that",
"s",
"used",
"to",
"populate",
"a",
"list",
"of",
"links",
"in",
"TinyMCE",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L183-L207 |
minhhoit/yacms | yacms/core/views.py | page_not_found | def page_not_found(request, template_name="errors/404.html"):
"""
Mimics Django's 404 handler but with a different template path.
"""
context = {
"STATIC_URL": settings.STATIC_URL,
"request_path": request.path,
}
t = get_template(template_name)
return HttpResponseNotFound(t.r... | python | def page_not_found(request, template_name="errors/404.html"):
"""
Mimics Django's 404 handler but with a different template path.
"""
context = {
"STATIC_URL": settings.STATIC_URL,
"request_path": request.path,
}
t = get_template(template_name)
return HttpResponseNotFound(t.r... | [
"def",
"page_not_found",
"(",
"request",
",",
"template_name",
"=",
"\"errors/404.html\"",
")",
":",
"context",
"=",
"{",
"\"STATIC_URL\"",
":",
"settings",
".",
"STATIC_URL",
",",
"\"request_path\"",
":",
"request",
".",
"path",
",",
"}",
"t",
"=",
"get_templ... | Mimics Django's 404 handler but with a different template path. | [
"Mimics",
"Django",
"s",
"404",
"handler",
"but",
"with",
"a",
"different",
"template",
"path",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L211-L220 |
minhhoit/yacms | yacms/core/views.py | server_error | def server_error(request, template_name="errors/500.html"):
"""
Mimics Django's error handler but adds ``STATIC_URL`` to the
context.
"""
context = {"STATIC_URL": settings.STATIC_URL}
t = get_template(template_name)
return HttpResponseServerError(t.render(context, request)) | python | def server_error(request, template_name="errors/500.html"):
"""
Mimics Django's error handler but adds ``STATIC_URL`` to the
context.
"""
context = {"STATIC_URL": settings.STATIC_URL}
t = get_template(template_name)
return HttpResponseServerError(t.render(context, request)) | [
"def",
"server_error",
"(",
"request",
",",
"template_name",
"=",
"\"errors/500.html\"",
")",
":",
"context",
"=",
"{",
"\"STATIC_URL\"",
":",
"settings",
".",
"STATIC_URL",
"}",
"t",
"=",
"get_template",
"(",
"template_name",
")",
"return",
"HttpResponseServerErr... | Mimics Django's error handler but adds ``STATIC_URL`` to the
context. | [
"Mimics",
"Django",
"s",
"error",
"handler",
"but",
"adds",
"STATIC_URL",
"to",
"the",
"context",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L224-L231 |
jribbens/hg-autohooks | hgautohooks.py | uisetup | def uisetup(ui):
"""Setup pre-/post- hooks"""
for hooktype in PREPOST_HOOKS:
ui.setconfig("hooks", "pre-" + hooktype + ".autohooks", autohook)
ui.setconfig("hooks", "post-" + hooktype + ".autohooks", autohook) | python | def uisetup(ui):
"""Setup pre-/post- hooks"""
for hooktype in PREPOST_HOOKS:
ui.setconfig("hooks", "pre-" + hooktype + ".autohooks", autohook)
ui.setconfig("hooks", "post-" + hooktype + ".autohooks", autohook) | [
"def",
"uisetup",
"(",
"ui",
")",
":",
"for",
"hooktype",
"in",
"PREPOST_HOOKS",
":",
"ui",
".",
"setconfig",
"(",
"\"hooks\"",
",",
"\"pre-\"",
"+",
"hooktype",
"+",
"\".autohooks\"",
",",
"autohook",
")",
"ui",
".",
"setconfig",
"(",
"\"hooks\"",
",",
... | Setup pre-/post- hooks | [
"Setup",
"pre",
"-",
"/",
"post",
"-",
"hooks"
] | train | https://github.com/jribbens/hg-autohooks/blob/4ade9b7d95cfa8ac58a5abb27f2c37634f869182/hgautohooks.py#L34-L38 |
jribbens/hg-autohooks | hgautohooks.py | _runhook | def _runhook(ui, repo, hooktype, filename, kwargs):
"""Run the hook in `filename` and return its result."""
hname = hooktype + ".autohooks." + os.path.basename(filename)
if filename.lower().endswith(".py"):
try:
mod = mercurial.extensions.loadpath(filename,
"hghook.%s" % ... | python | def _runhook(ui, repo, hooktype, filename, kwargs):
"""Run the hook in `filename` and return its result."""
hname = hooktype + ".autohooks." + os.path.basename(filename)
if filename.lower().endswith(".py"):
try:
mod = mercurial.extensions.loadpath(filename,
"hghook.%s" % ... | [
"def",
"_runhook",
"(",
"ui",
",",
"repo",
",",
"hooktype",
",",
"filename",
",",
"kwargs",
")",
":",
"hname",
"=",
"hooktype",
"+",
"\".autohooks.\"",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"if",
"filename",
".",
"lower",
"(",
... | Run the hook in `filename` and return its result. | [
"Run",
"the",
"hook",
"in",
"filename",
"and",
"return",
"its",
"result",
"."
] | train | https://github.com/jribbens/hg-autohooks/blob/4ade9b7d95cfa8ac58a5abb27f2c37634f869182/hgautohooks.py#L48-L62 |
jribbens/hg-autohooks | hgautohooks.py | autohook | def autohook(ui, repo, hooktype, **kwargs):
"""Look for hooks inside the repository to run."""
cmd = hooktype.replace("-", "_")
if not repo or not cmd.replace("_", "").isalpha():
return False
result = False
trusted = ui.configlist("autohooks", "trusted")
if "" not in trusted:
def... | python | def autohook(ui, repo, hooktype, **kwargs):
"""Look for hooks inside the repository to run."""
cmd = hooktype.replace("-", "_")
if not repo or not cmd.replace("_", "").isalpha():
return False
result = False
trusted = ui.configlist("autohooks", "trusted")
if "" not in trusted:
def... | [
"def",
"autohook",
"(",
"ui",
",",
"repo",
",",
"hooktype",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"hooktype",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"if",
"not",
"repo",
"or",
"not",
"cmd",
".",
"replace",
"(",
"\"_\"",
",",
"\... | Look for hooks inside the repository to run. | [
"Look",
"for",
"hooks",
"inside",
"the",
"repository",
"to",
"run",
"."
] | train | https://github.com/jribbens/hg-autohooks/blob/4ade9b7d95cfa8ac58a5abb27f2c37634f869182/hgautohooks.py#L65-L90 |
johnwlockwood/iter_karld_tools | iter_karld_tools/__init__.py | i_batch | def i_batch(max_size, iterable):
"""
Generator that iteratively batches items
to a max size and consumes the items iterable
as each batch is yielded.
:param max_size: Max size of each batch.
:type max_size: int
:param iterable: An iterable
:type iterable: iter
"""
iterable_items... | python | def i_batch(max_size, iterable):
"""
Generator that iteratively batches items
to a max size and consumes the items iterable
as each batch is yielded.
:param max_size: Max size of each batch.
:type max_size: int
:param iterable: An iterable
:type iterable: iter
"""
iterable_items... | [
"def",
"i_batch",
"(",
"max_size",
",",
"iterable",
")",
":",
"iterable_items",
"=",
"iter",
"(",
"iterable",
")",
"for",
"items_batch",
"in",
"iter",
"(",
"lambda",
":",
"tuple",
"(",
"islice",
"(",
"iterable_items",
",",
"max_size",
")",
")",
",",
"tup... | Generator that iteratively batches items
to a max size and consumes the items iterable
as each batch is yielded.
:param max_size: Max size of each batch.
:type max_size: int
:param iterable: An iterable
:type iterable: iter | [
"Generator",
"that",
"iteratively",
"batches",
"items",
"to",
"a",
"max",
"size",
"and",
"consumes",
"the",
"items",
"iterable",
"as",
"each",
"batch",
"is",
"yielded",
"."
] | train | https://github.com/johnwlockwood/iter_karld_tools/blob/7baaa94244c4a4959f55d4018a8899781ff111b0/iter_karld_tools/__init__.py#L41-L55 |
cogniteev/docido-python-sdk | docido_sdk/toolbox/http_ext.py | delayed_request.open | def open(self, session=None):
"""
:param requests.Session session:
Optional requests session
:return:
file-like object over the decoded bytes
"""
self.__kwargs.update(stream=True)
session = session or requests
resp = session.request(self.__me... | python | def open(self, session=None):
"""
:param requests.Session session:
Optional requests session
:return:
file-like object over the decoded bytes
"""
self.__kwargs.update(stream=True)
session = session or requests
resp = session.request(self.__me... | [
"def",
"open",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"__kwargs",
".",
"update",
"(",
"stream",
"=",
"True",
")",
"session",
"=",
"session",
"or",
"requests",
"resp",
"=",
"session",
".",
"request",
"(",
"self",
".",
"__meth... | :param requests.Session session:
Optional requests session
:return:
file-like object over the decoded bytes | [
":",
"param",
"requests",
".",
"Session",
"session",
":",
"Optional",
"requests",
"session"
] | train | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/http_ext.py#L49-L64 |
cogniteev/docido-python-sdk | docido_sdk/toolbox/http_ext.py | HttpSessionPreparer.mount_rate_limit_adapters | def mount_rate_limit_adapters(cls, session=None,
rls_config=None, **kwargs):
"""Mount rate-limits adapters on the specified `requests.Session`
object.
:param py:class:`requests.Session` session:
Session to mount. If not specified, then use the global
... | python | def mount_rate_limit_adapters(cls, session=None,
rls_config=None, **kwargs):
"""Mount rate-limits adapters on the specified `requests.Session`
object.
:param py:class:`requests.Session` session:
Session to mount. If not specified, then use the global
... | [
"def",
"mount_rate_limit_adapters",
"(",
"cls",
",",
"session",
"=",
"None",
",",
"rls_config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"session",
"or",
"HTTP_SESSION",
"if",
"rls_config",
"is",
"None",
":",
"rls_config",
"=",
"Rate... | Mount rate-limits adapters on the specified `requests.Session`
object.
:param py:class:`requests.Session` session:
Session to mount. If not specified, then use the global
`HTTP_SESSION`.
:param dict rls_config:
Rate-limits configuration. If not specified, then
... | [
"Mount",
"rate",
"-",
"limits",
"adapters",
"on",
"the",
"specified",
"requests",
".",
"Session",
"object",
"."
] | train | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/http_ext.py#L75-L102 |
ulf1/oxyba | oxyba/clean_add_strdec.py | clean_add_strdec | def clean_add_strdec(*args, prec=28):
"""add two columns that contain numbers as strings"""
# load modules
import pandas as pd
import numpy as np
import re
from decimal import Decimal, getcontext
getcontext().prec = prec
# initialize result as 0.0
def proc_elem(*args):
t = ... | python | def clean_add_strdec(*args, prec=28):
"""add two columns that contain numbers as strings"""
# load modules
import pandas as pd
import numpy as np
import re
from decimal import Decimal, getcontext
getcontext().prec = prec
# initialize result as 0.0
def proc_elem(*args):
t = ... | [
"def",
"clean_add_strdec",
"(",
"*",
"args",
",",
"prec",
"=",
"28",
")",
":",
"# load modules",
"import",
"pandas",
"as",
"pd",
"import",
"numpy",
"as",
"np",
"import",
"re",
"from",
"decimal",
"import",
"Decimal",
",",
"getcontext",
"getcontext",
"(",
")... | add two columns that contain numbers as strings | [
"add",
"two",
"columns",
"that",
"contain",
"numbers",
"as",
"strings"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_add_strdec.py#L2-L39 |
markomanninen/abnum | abnum/search.py | find_cumulative_indices | def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
"""
u = 0
y = 0
result = []
for idx, val in enumerate(list_of_numbers):
y += list_of_numbers[idx]
while y >=... | python | def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
"""
u = 0
y = 0
result = []
for idx, val in enumerate(list_of_numbers):
y += list_of_numbers[idx]
while y >=... | [
"def",
"find_cumulative_indices",
"(",
"list_of_numbers",
",",
"search_sum",
")",
":",
"u",
"=",
"0",
"y",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"list_of_numbers",
")",
":",
"y",
"+=",
"list_of_numbers",
"["... | find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]] | [
"find_cumulative_indices",
"(",
"[",
"70",
"58",
"81",
"909",
"70",
"215",
"70",
"1022",
"580",
"930",
"898",
"]",
"285",
")",
"-",
">",
"[[",
"4",
"5",
"]",
"[",
"5",
"6",
"]]"
] | train | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/abnum/search.py#L5-L22 |
nimbusproject/pidantic | pidantic/pyon/pyon.py | Pyon.load_module | def load_module(self, module, module_uri=None):
"""load_module
Attempts to load module by name, if it is not available,
loads it by url
"""
# Check to see that module isn't availble in python path
try:
import_module(module)
except ImportError, e:
... | python | def load_module(self, module, module_uri=None):
"""load_module
Attempts to load module by name, if it is not available,
loads it by url
"""
# Check to see that module isn't availble in python path
try:
import_module(module)
except ImportError, e:
... | [
"def",
"load_module",
"(",
"self",
",",
"module",
",",
"module_uri",
"=",
"None",
")",
":",
"# Check to see that module isn't availble in python path",
"try",
":",
"import_module",
"(",
"module",
")",
"except",
"ImportError",
",",
"e",
":",
"if",
"module_uri",
"is... | load_module
Attempts to load module by name, if it is not available,
loads it by url | [
"load_module"
] | train | https://github.com/nimbusproject/pidantic/blob/7d98dcbf449d0458279144d07a7b82dc933905cc/pidantic/pyon/pyon.py#L147-L179 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler._ps_extract_pid | def _ps_extract_pid(self, line):
"""
Extract PID and parent PID from an output line from the PS command
"""
this_pid = self.regex['pid'].sub(r'\g<1>', line)
this_parent = self.regex['parent'].sub(r'\g<1>', line)
# Return the main / parent PIDs
return this... | python | def _ps_extract_pid(self, line):
"""
Extract PID and parent PID from an output line from the PS command
"""
this_pid = self.regex['pid'].sub(r'\g<1>', line)
this_parent = self.regex['parent'].sub(r'\g<1>', line)
# Return the main / parent PIDs
return this... | [
"def",
"_ps_extract_pid",
"(",
"self",
",",
"line",
")",
":",
"this_pid",
"=",
"self",
".",
"regex",
"[",
"'pid'",
"]",
".",
"sub",
"(",
"r'\\g<1>'",
",",
"line",
")",
"this_parent",
"=",
"self",
".",
"regex",
"[",
"'parent'",
"]",
".",
"sub",
"(",
... | Extract PID and parent PID from an output line from the PS command | [
"Extract",
"PID",
"and",
"parent",
"PID",
"from",
"an",
"output",
"line",
"from",
"the",
"PS",
"command"
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L33-L41 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.ps | def ps(self):
"""
Get the process information from the system PS command.
"""
# Get the process ID
pid = self.get()
# Parent / child processes
parent = None
children = []
# If the process is running
if pid:
... | python | def ps(self):
"""
Get the process information from the system PS command.
"""
# Get the process ID
pid = self.get()
# Parent / child processes
parent = None
children = []
# If the process is running
if pid:
... | [
"def",
"ps",
"(",
"self",
")",
":",
"# Get the process ID",
"pid",
"=",
"self",
".",
"get",
"(",
")",
"# Parent / child processes",
"parent",
"=",
"None",
"children",
"=",
"[",
"]",
"# If the process is running",
"if",
"pid",
":",
"proc",
"=",
"Popen",
"(",
... | Get the process information from the system PS command. | [
"Get",
"the",
"process",
"information",
"from",
"the",
"system",
"PS",
"command",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L43-L78 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.age | def age(self):
"""
Get the age of the PID file.
"""
# Created timestamp
created = self.created()
# Age in seconds / minutes / hours / days
age_secs = time() - created
age_mins = 0 if (age_secs < 60) else (age_secs / 60)
age_hour... | python | def age(self):
"""
Get the age of the PID file.
"""
# Created timestamp
created = self.created()
# Age in seconds / minutes / hours / days
age_secs = time() - created
age_mins = 0 if (age_secs < 60) else (age_secs / 60)
age_hour... | [
"def",
"age",
"(",
"self",
")",
":",
"# Created timestamp",
"created",
"=",
"self",
".",
"created",
"(",
")",
"# Age in seconds / minutes / hours / days",
"age_secs",
"=",
"time",
"(",
")",
"-",
"created",
"age_mins",
"=",
"0",
"if",
"(",
"age_secs",
"<",
"6... | Get the age of the PID file. | [
"Get",
"the",
"age",
"of",
"the",
"PID",
"file",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L86-L106 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.birthday | def birthday(self):
"""
Return a string representing the age of the process.
"""
if isfile(self.pid_file):
# Timestamp / timezone string
tstamp = datetime.fromtimestamp(self.created())
tzone = tzname[0]
weekday = WEEKDAY[ts... | python | def birthday(self):
"""
Return a string representing the age of the process.
"""
if isfile(self.pid_file):
# Timestamp / timezone string
tstamp = datetime.fromtimestamp(self.created())
tzone = tzname[0]
weekday = WEEKDAY[ts... | [
"def",
"birthday",
"(",
"self",
")",
":",
"if",
"isfile",
"(",
"self",
".",
"pid_file",
")",
":",
"# Timestamp / timezone string",
"tstamp",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"created",
"(",
")",
")",
"tzone",
"=",
"tzname",
"[",
"... | Return a string representing the age of the process. | [
"Return",
"a",
"string",
"representing",
"the",
"age",
"of",
"the",
"process",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L108-L128 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.make | def make(self, pnum):
"""
Make a PID file and populate with PID number.
"""
try:
# Create the PID file
self.mkfile(self.pid_file, pnum)
except Exception as e:
self.die('Failed to generate PID file: {}'.format(str(e))) | python | def make(self, pnum):
"""
Make a PID file and populate with PID number.
"""
try:
# Create the PID file
self.mkfile(self.pid_file, pnum)
except Exception as e:
self.die('Failed to generate PID file: {}'.format(str(e))) | [
"def",
"make",
"(",
"self",
",",
"pnum",
")",
":",
"try",
":",
"# Create the PID file",
"self",
".",
"mkfile",
"(",
"self",
".",
"pid_file",
",",
"pnum",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"die",
"(",
"'Failed to generate PID file: {}... | Make a PID file and populate with PID number. | [
"Make",
"a",
"PID",
"file",
"and",
"populate",
"with",
"PID",
"number",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L138-L147 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.remove | def remove(self):
"""
Remove the PID file.
"""
if isfile(self.pid_file):
try:
remove(self.pid_file)
except Exception as e:
self.die('Failed to remove PID file: {}'.format(str(e)))
else:
return True | python | def remove(self):
"""
Remove the PID file.
"""
if isfile(self.pid_file):
try:
remove(self.pid_file)
except Exception as e:
self.die('Failed to remove PID file: {}'.format(str(e)))
else:
return True | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"isfile",
"(",
"self",
".",
"pid_file",
")",
":",
"try",
":",
"remove",
"(",
"self",
".",
"pid_file",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"die",
"(",
"'Failed to remove PID file: {}'",
... | Remove the PID file. | [
"Remove",
"the",
"PID",
"file",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L149-L159 |
djtaylor/python-lsbinit | lsbinit/pid.py | _LSBPIDHandler.kill | def kill(self):
"""
Kill the running process and remove the PID/lock file.
"""
try:
kill(int(self.get()), 9)
# Failed to kill the process
except Exception as e:
self.die('Failed to kill process: {}'.format(str(e)))
... | python | def kill(self):
"""
Kill the running process and remove the PID/lock file.
"""
try:
kill(int(self.get()), 9)
# Failed to kill the process
except Exception as e:
self.die('Failed to kill process: {}'.format(str(e)))
... | [
"def",
"kill",
"(",
"self",
")",
":",
"try",
":",
"kill",
"(",
"int",
"(",
"self",
".",
"get",
"(",
")",
")",
",",
"9",
")",
"# Failed to kill the process",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"die",
"(",
"'Failed to kill process: {}'",
... | Kill the running process and remove the PID/lock file. | [
"Kill",
"the",
"running",
"process",
"and",
"remove",
"the",
"PID",
"/",
"lock",
"file",
"."
] | train | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L161-L173 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search.get | def get(self):
"""
*get the results from the the sdss square search*
**Return:**
- ``sdss_square_search``
.. todo::
"""
self.log.info('starting the ``get`` method')
self._execute_sql_query()
self._append_separations_to_results()
sel... | python | def get(self):
"""
*get the results from the the sdss square search*
**Return:**
- ``sdss_square_search``
.. todo::
"""
self.log.info('starting the ``get`` method')
self._execute_sql_query()
self._append_separations_to_results()
sel... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"self",
".",
"_execute_sql_query",
"(",
")",
"self",
".",
"_append_separations_to_results",
"(",
")",
"self",
".",
"_generate_sdss_object_name",
"(",... | *get the results from the the sdss square search*
**Return:**
- ``sdss_square_search``
.. todo:: | [
"*",
"get",
"the",
"results",
"from",
"the",
"the",
"sdss",
"square",
"search",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L90-L107 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search._calculate_search_limits | def _calculate_search_limits(
self):
"""
*calculate search limits for the square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_calculate_search_limits`` method')
# TR... | python | def _calculate_search_limits(
self):
"""
*calculate search limits for the square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_calculate_search_limits`` method')
# TR... | [
"def",
"_calculate_search_limits",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_calculate_search_limits`` method'",
")",
"# TRANSLATE COORDINATES ACROSS SKY",
"self",
".",
"ra1",
",",
"self",
".",
"dec1",
"=",
"translate",
"(",
"log... | *calculate search limits for the square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: | [
"*",
"calculate",
"search",
"limits",
"for",
"the",
"square",
"search",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L109-L144 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search._build_sql_query | def _build_sql_query(
self):
"""
*build sql query for the sdss square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_build_sql_query`` method')
ra1, ra2, dec1, dec2 = ... | python | def _build_sql_query(
self):
"""
*build sql query for the sdss square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_build_sql_query`` method')
ra1, ra2, dec1, dec2 = ... | [
"def",
"_build_sql_query",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_build_sql_query`` method'",
")",
"ra1",
",",
"ra2",
",",
"dec1",
",",
"dec2",
"=",
"self",
".",
"ra1",
",",
"self",
".",
"ra2",
",",
"self",
".",
... | *build sql query for the sdss square search*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: | [
"*",
"build",
"sql",
"query",
"for",
"the",
"sdss",
"square",
"search",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L146-L196 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search._execute_sql_query | def _execute_sql_query(
self):
"""
*execute sql query using the sdss API*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_execute_sql_query`` method')
# generate the api call u... | python | def _execute_sql_query(
self):
"""
*execute sql query using the sdss API*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_execute_sql_query`` method')
# generate the api call u... | [
"def",
"_execute_sql_query",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_execute_sql_query`` method'",
")",
"# generate the api call url",
"params",
"=",
"urllib",
".",
"urlencode",
"(",
"{",
"'cmd'",
":",
"self",
".",
"sqlQuery"... | *execute sql query using the sdss API*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: | [
"*",
"execute",
"sql",
"query",
"using",
"the",
"sdss",
"API",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L198-L238 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search._append_separations_to_results | def _append_separations_to_results(
self):
"""
*append angular separations to results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_append_separations_to_results`` method')
... | python | def _append_separations_to_results(
self):
"""
*append angular separations to results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_append_separations_to_results`` method')
... | [
"def",
"_append_separations_to_results",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_append_separations_to_results`` method'",
")",
"for",
"row",
"in",
"self",
".",
"results",
":",
"if",
"\"ra\"",
"not",
"in",
"row",
":",
"prin... | *append angular separations to results*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: | [
"*",
"append",
"angular",
"separations",
"to",
"results",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L240-L277 |
thespacedoctor/sloancone | build/lib/sloancone/sdss_square_search.py | sdss_square_search._generate_sdss_object_name | def _generate_sdss_object_name(
self):
"""
*generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_generate_sdss_object_name`` method')
con... | python | def _generate_sdss_object_name(
self):
"""
*generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_generate_sdss_object_name`` method')
con... | [
"def",
"_generate_sdss_object_name",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_generate_sdss_object_name`` method'",
")",
"converter",
"=",
"unit_conversion",
"(",
"log",
"=",
"self",
".",
"log",
")",
"# Names should be of the form... | *generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: | [
"*",
"generate",
"sdss",
"object",
"names",
"for",
"the",
"results",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/sdss_square_search.py#L279-L322 |
ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/views.py | SharingView.role_settings | def role_settings(self):
""" Filter out unwanted to show groups """
result = super(SharingView, self).role_settings()
uid = self.context.UID()
filter_func = lambda x: not any((
x["id"].endswith(uid),
x["id"] == "AuthenticatedUsers",
x["id"] == INTRANET... | python | def role_settings(self):
""" Filter out unwanted to show groups """
result = super(SharingView, self).role_settings()
uid = self.context.UID()
filter_func = lambda x: not any((
x["id"].endswith(uid),
x["id"] == "AuthenticatedUsers",
x["id"] == INTRANET... | [
"def",
"role_settings",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
"SharingView",
",",
"self",
")",
".",
"role_settings",
"(",
")",
"uid",
"=",
"self",
".",
"context",
".",
"UID",
"(",
")",
"filter_func",
"=",
"lambda",
"x",
":",
"not",
"any... | Filter out unwanted to show groups | [
"Filter",
"out",
"unwanted",
"to",
"show",
"groups"
] | train | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/views.py#L47-L56 |
ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/views.py | SharingView.user_search_results | def user_search_results(self):
""" Add [member] to a user title if user is a member
of current workspace
"""
results = super(SharingView, self).user_search_results()
ws = IWorkspace(self.context)
roles_mapping = ws.available_groups
roles = roles_mapping.get(self.c... | python | def user_search_results(self):
""" Add [member] to a user title if user is a member
of current workspace
"""
results = super(SharingView, self).user_search_results()
ws = IWorkspace(self.context)
roles_mapping = ws.available_groups
roles = roles_mapping.get(self.c... | [
"def",
"user_search_results",
"(",
"self",
")",
":",
"results",
"=",
"super",
"(",
"SharingView",
",",
"self",
")",
".",
"user_search_results",
"(",
")",
"ws",
"=",
"IWorkspace",
"(",
"self",
".",
"context",
")",
"roles_mapping",
"=",
"ws",
".",
"available... | Add [member] to a user title if user is a member
of current workspace | [
"Add",
"[",
"member",
"]",
"to",
"a",
"user",
"title",
"if",
"user",
"is",
"a",
"member",
"of",
"current",
"workspace"
] | train | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/views.py#L58-L79 |
dcramer/peek | peek/runner.py | run_python_file | def run_python_file(filename, args, package=None, collector=None):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, including the first
element naming t... | python | def run_python_file(filename, args, package=None, collector=None):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, including the first
element naming t... | [
"def",
"run_python_file",
"(",
"filename",
",",
"args",
",",
"package",
"=",
"None",
",",
"collector",
"=",
"None",
")",
":",
"# Create a module to serve as __main__",
"old_main_mod",
"=",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"main_mod",
"=",
"imp",
... | Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, including the first
element naming the file being executed. `package` is the name of the
enclosing packag... | [
"Run",
"a",
"python",
"file",
"as",
"if",
"it",
"were",
"the",
"main",
"program",
"on",
"the",
"command",
"line",
"."
] | train | https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/runner.py#L27-L93 |
hirokiky/uiro | uiro/db.py | initdb | def initdb(config):
""" Initializing database settings by using config from .ini file.
"""
engine = sa.engine_from_config(config, 'sqlalchemy.')
Session.configure(bind=engine) | python | def initdb(config):
""" Initializing database settings by using config from .ini file.
"""
engine = sa.engine_from_config(config, 'sqlalchemy.')
Session.configure(bind=engine) | [
"def",
"initdb",
"(",
"config",
")",
":",
"engine",
"=",
"sa",
".",
"engine_from_config",
"(",
"config",
",",
"'sqlalchemy.'",
")",
"Session",
".",
"configure",
"(",
"bind",
"=",
"engine",
")"
] | Initializing database settings by using config from .ini file. | [
"Initializing",
"database",
"settings",
"by",
"using",
"config",
"from",
".",
"ini",
"file",
"."
] | train | https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/db.py#L13-L17 |
jamieleshaw/lurklib | example.py | HelloBot.on_chanmsg | def on_chanmsg(self, from_, channel, message):
""" Event handler for channel messages. """
if message == 'hello':
self.privmsg(channel, 'Hello, %s!' % from_[0])
print('%s said hello!' % from_[0])
elif message == '!quit':
self.quit('Bye!') | python | def on_chanmsg(self, from_, channel, message):
""" Event handler for channel messages. """
if message == 'hello':
self.privmsg(channel, 'Hello, %s!' % from_[0])
print('%s said hello!' % from_[0])
elif message == '!quit':
self.quit('Bye!') | [
"def",
"on_chanmsg",
"(",
"self",
",",
"from_",
",",
"channel",
",",
"message",
")",
":",
"if",
"message",
"==",
"'hello'",
":",
"self",
".",
"privmsg",
"(",
"channel",
",",
"'Hello, %s!'",
"%",
"from_",
"[",
"0",
"]",
")",
"print",
"(",
"'%s said hell... | Event handler for channel messages. | [
"Event",
"handler",
"for",
"channel",
"messages",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/example.py#L30-L36 |
nir0s/serv | setup.py | _get_package_data | def _get_package_data():
"""Iterate over the `init` dir for directories and returns
all files within them.
Only files within `binaries` and `templates` will be added.
"""
from os import listdir as ls
from os.path import join as jn
x = 'init'
b = jn('serv', x)
dr = ['binaries', 'tem... | python | def _get_package_data():
"""Iterate over the `init` dir for directories and returns
all files within them.
Only files within `binaries` and `templates` will be added.
"""
from os import listdir as ls
from os.path import join as jn
x = 'init'
b = jn('serv', x)
dr = ['binaries', 'tem... | [
"def",
"_get_package_data",
"(",
")",
":",
"from",
"os",
"import",
"listdir",
"as",
"ls",
"from",
"os",
".",
"path",
"import",
"join",
"as",
"jn",
"x",
"=",
"'init'",
"b",
"=",
"jn",
"(",
"'serv'",
",",
"x",
")",
"dr",
"=",
"[",
"'binaries'",
",",
... | Iterate over the `init` dir for directories and returns
all files within them.
Only files within `binaries` and `templates` will be added. | [
"Iterate",
"over",
"the",
"init",
"dir",
"for",
"directories",
"and",
"returns",
"all",
"files",
"within",
"them",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/setup.py#L12-L24 |
minhhoit/yacms | yacms/utils/importing.py | path_for_import | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | [
"def",
"path_for_import",
"(",
"name",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"import_module",
"(",
"name",
")",
".",
"__file__",
")",
")"
] | Returns the directory path for the given package or module. | [
"Returns",
"the",
"directory",
"path",
"for",
"the",
"given",
"package",
"or",
"module",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/importing.py#L9-L13 |
roaet/wafflehaus.neutron | wafflehaus/neutron/nova_interaction/common.py | BaseConnection._make_the_call | def _make_the_call(self, method, url, body=None):
"""Note that a request response is being used here, not webob."""
self.log.debug("%s call to %s with body = %s" % (method, url, body))
params = {"url": url, "headers": self.headers, "verify": self.verify}
if body is not None:
... | python | def _make_the_call(self, method, url, body=None):
"""Note that a request response is being used here, not webob."""
self.log.debug("%s call to %s with body = %s" % (method, url, body))
params = {"url": url, "headers": self.headers, "verify": self.verify}
if body is not None:
... | [
"def",
"_make_the_call",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"%s call to %s with body = %s\"",
"%",
"(",
"method",
",",
"url",
",",
"body",
")",
")",
"params",
"=",
"{",
... | Note that a request response is being used here, not webob. | [
"Note",
"that",
"a",
"request",
"response",
"is",
"being",
"used",
"here",
"not",
"webob",
"."
] | train | https://github.com/roaet/wafflehaus.neutron/blob/01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c/wafflehaus/neutron/nova_interaction/common.py#L34-L50 |
KnowledgeLinks/rdfframework | rdfframework/utilities/formattingfunctions.py | reduce_multiline | def reduce_multiline(string):
"""
reduces a multiline string to a single line of text.
args:
string: the text to reduce
"""
string = str(string)
return " ".join([item.strip()
for item in string.split("\n")
if item.strip()]) | python | def reduce_multiline(string):
"""
reduces a multiline string to a single line of text.
args:
string: the text to reduce
"""
string = str(string)
return " ".join([item.strip()
for item in string.split("\n")
if item.strip()]) | [
"def",
"reduce_multiline",
"(",
"string",
")",
":",
"string",
"=",
"str",
"(",
"string",
")",
"return",
"\" \"",
".",
"join",
"(",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"item",
... | reduces a multiline string to a single line of text.
args:
string: the text to reduce | [
"reduces",
"a",
"multiline",
"string",
"to",
"a",
"single",
"line",
"of",
"text",
"."
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L166-L177 |
KnowledgeLinks/rdfframework | rdfframework/utilities/formattingfunctions.py | format_multiline | def format_multiline(text, params={}, **kwargs):
"""
Takes a list or multline text string and formats it.
* multiline text strings get converted to a single line
* list entries are joined by a carriage return
* params are passed into the sting with a python format call
args:
... | python | def format_multiline(text, params={}, **kwargs):
"""
Takes a list or multline text string and formats it.
* multiline text strings get converted to a single line
* list entries are joined by a carriage return
* params are passed into the sting with a python format call
args:
... | [
"def",
"format_multiline",
"(",
"text",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"format_kwargs",
"(",
"text",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"params",
":",
"if",
"isinstance",
... | Takes a list or multline text string and formats it.
* multiline text strings get converted to a single line
* list entries are joined by a carriage return
* params are passed into the sting with a python format call
args:
text: list or string to format
params: argments for ... | [
"Takes",
"a",
"list",
"or",
"multline",
"text",
"string",
"and",
"formats",
"it",
".",
"*",
"multiline",
"text",
"strings",
"get",
"converted",
"to",
"a",
"single",
"line",
"*",
"list",
"entries",
"are",
"joined",
"by",
"a",
"carriage",
"return",
"*",
"p... | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L179-L222 |
KnowledgeLinks/rdfframework | rdfframework/utilities/formattingfunctions.py | format_max_width | def format_max_width(text, max_width=None, **kwargs):
"""
Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the st... | python | def format_max_width(text, max_width=None, **kwargs):
"""
Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the st... | [
"def",
"format_max_width",
"(",
"text",
",",
"max_width",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ind",
"=",
"''",
"if",
"kwargs",
".",
"get",
"(",
"\"indent\"",
")",
":",
"ind",
"=",
"''",
".",
"ljust",
"(",
"kwargs",
"[",
"'indent'",
"]"... | Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the start of each line | [
"Takes",
"a",
"string",
"and",
"formats",
"it",
"to",
"a",
"max",
"width",
"seperated",
"by",
"carriage",
"returns"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L224-L298 |
jut-io/jut-python-tools | jut/api/environment.py | get_details | def get_details(app_url=defaults.APP_URL):
"""
returns environment details for the app url specified
"""
url = '%s/environment' % app_url
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
raise JutException('Unable to retrieve environ... | python | def get_details(app_url=defaults.APP_URL):
"""
returns environment details for the app url specified
"""
url = '%s/environment' % app_url
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
raise JutException('Unable to retrieve environ... | [
"def",
"get_details",
"(",
"app_url",
"=",
"defaults",
".",
"APP_URL",
")",
":",
"url",
"=",
"'%s/environment'",
"%",
"app_url",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"... | returns environment details for the app url specified | [
"returns",
"environment",
"details",
"for",
"the",
"app",
"url",
"specified"
] | train | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/environment.py#L14-L26 |
radjkarl/appBase | appbase/dialogs/FirstStart.py | FirstStart.accept | def accept(self, evt):
"""
write setting to the preferences
"""
# determine if application is a script file or frozen exe (pyinstaller)
frozen = getattr(sys, 'frozen', False)
if frozen:
app_file = sys.executable
else:
app_file = Pa... | python | def accept(self, evt):
"""
write setting to the preferences
"""
# determine if application is a script file or frozen exe (pyinstaller)
frozen = getattr(sys, 'frozen', False)
if frozen:
app_file = sys.executable
else:
app_file = Pa... | [
"def",
"accept",
"(",
"self",
",",
"evt",
")",
":",
"# determine if application is a script file or frozen exe (pyinstaller)\r",
"frozen",
"=",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
"if",
"frozen",
":",
"app_file",
"=",
"sys",
".",
"executable... | write setting to the preferences | [
"write",
"setting",
"to",
"the",
"preferences"
] | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/dialogs/FirstStart.py#L56-L92 |
openbermuda/ripl | ripl/md2slides.py | Mark2Slide.hash_count | def hash_count(self, line, pound=None):
""" Count hashes (or other run of chars) at start of line
>>> x = Mark2Slide()
>>> x.hash_count('### hello')
3
>>> x = Mark2Slide()
>>> x.hash_count(' hello', ' ')
1
"""
if pound is None:
pound... | python | def hash_count(self, line, pound=None):
""" Count hashes (or other run of chars) at start of line
>>> x = Mark2Slide()
>>> x.hash_count('### hello')
3
>>> x = Mark2Slide()
>>> x.hash_count(' hello', ' ')
1
"""
if pound is None:
pound... | [
"def",
"hash_count",
"(",
"self",
",",
"line",
",",
"pound",
"=",
"None",
")",
":",
"if",
"pound",
"is",
"None",
":",
"pound",
"=",
"'#'",
"count",
"=",
"0",
"for",
"c",
"in",
"line",
":",
"if",
"c",
"!=",
"pound",
":",
"break",
"count",
"+=",
... | Count hashes (or other run of chars) at start of line
>>> x = Mark2Slide()
>>> x.hash_count('### hello')
3
>>> x = Mark2Slide()
>>> x.hash_count(' hello', ' ')
1 | [
"Count",
"hashes",
"(",
"or",
"other",
"run",
"of",
"chars",
")",
"at",
"start",
"of",
"line"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/md2slides.py#L21-L42 |
openbermuda/ripl | ripl/md2slides.py | Mark2Slide.generate_lines | def generate_lines(self, infile):
""" Split file into lines
return dict with line=input, depth=n
"""
pound = '#'
for line in infile:
heading = self.hash_count(line)
indent = self.hash_count(line, pound=' ')
yield dict(line=line.str... | python | def generate_lines(self, infile):
""" Split file into lines
return dict with line=input, depth=n
"""
pound = '#'
for line in infile:
heading = self.hash_count(line)
indent = self.hash_count(line, pound=' ')
yield dict(line=line.str... | [
"def",
"generate_lines",
"(",
"self",
",",
"infile",
")",
":",
"pound",
"=",
"'#'",
"for",
"line",
"in",
"infile",
":",
"heading",
"=",
"self",
".",
"hash_count",
"(",
"line",
")",
"indent",
"=",
"self",
".",
"hash_count",
"(",
"line",
",",
"pound",
... | Split file into lines
return dict with line=input, depth=n | [
"Split",
"file",
"into",
"lines"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/md2slides.py#L44-L59 |
openbermuda/ripl | ripl/md2slides.py | Mark2Slide.generate_slides | def generate_slides(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
# each slide is a dict
slide = {}
last_heading = 0
for item in self.generate_lines(infile):
line = item['line']
heading = item['heading']
... | python | def generate_slides(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
# each slide is a dict
slide = {}
last_heading = 0
for item in self.generate_lines(infile):
line = item['line']
heading = item['heading']
... | [
"def",
"generate_slides",
"(",
"self",
",",
"infile",
")",
":",
"state",
"=",
"0",
"# each slide is a dict",
"slide",
"=",
"{",
"}",
"last_heading",
"=",
"0",
"for",
"item",
"in",
"self",
".",
"generate_lines",
"(",
"infile",
")",
":",
"line",
"=",
"item... | Process a file of rest and yield dictionaries | [
"Process",
"a",
"file",
"of",
"rest",
"and",
"yield",
"dictionaries"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/md2slides.py#L62-L109 |
openbermuda/ripl | ripl/md2slides.py | Mark2Slide.build_row | def build_row(self, line):
""" Line describes an image or images to show
Returns a dict with a list of dicts of image names or text items
Examples:
# A single image to display
>>> x.build_row('foo.png')
[{'image': 'foo.png'}]
# Two images with text in between:... | python | def build_row(self, line):
""" Line describes an image or images to show
Returns a dict with a list of dicts of image names or text items
Examples:
# A single image to display
>>> x.build_row('foo.png')
[{'image': 'foo.png'}]
# Two images with text in between:... | [
"def",
"build_row",
"(",
"self",
",",
"line",
")",
":",
"items",
"=",
"[",
"]",
"row",
"=",
"dict",
"(",
"items",
"=",
"items",
")",
"fields",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"image_exts",
"=",
"[",
"'.png'",
",",
"'.jpg'",
"]",
"# no... | Line describes an image or images to show
Returns a dict with a list of dicts of image names or text items
Examples:
# A single image to display
>>> x.build_row('foo.png')
[{'image': 'foo.png'}]
# Two images with text in between:
>>> x.build_row('foo.png or ba... | [
"Line",
"describes",
"an",
"image",
"or",
"images",
"to",
"show"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/md2slides.py#L114-L152 |
sternoru/goscalecms | goscale/models.py | Post.dict | def dict(self):
""" Returns dictionary of post fields and attributes
"""
post_dict = {
'id': self.id,
'link': self.link,
'permalink': self.permalink,
'content_type': self.content_type,
'slug': self.slug,
'updated': self.upda... | python | def dict(self):
""" Returns dictionary of post fields and attributes
"""
post_dict = {
'id': self.id,
'link': self.link,
'permalink': self.permalink,
'content_type': self.content_type,
'slug': self.slug,
'updated': self.upda... | [
"def",
"dict",
"(",
"self",
")",
":",
"post_dict",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'link'",
":",
"self",
".",
"link",
",",
"'permalink'",
":",
"self",
".",
"permalink",
",",
"'content_type'",
":",
"self",
".",
"content_type",
",",
"'s... | Returns dictionary of post fields and attributes | [
"Returns",
"dictionary",
"of",
"post",
"fields",
"and",
"attributes"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L66-L86 |
sternoru/goscalecms | goscale/models.py | Post.json | def json(self, dict=None, indent=None):
""" Returns post JSON representation
"""
if not dict:
dict = self.dict()
for key, value in dict.iteritems():
if type(value) == datetime.datetime:
dict[key] = value.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT)
... | python | def json(self, dict=None, indent=None):
""" Returns post JSON representation
"""
if not dict:
dict = self.dict()
for key, value in dict.iteritems():
if type(value) == datetime.datetime:
dict[key] = value.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT)
... | [
"def",
"json",
"(",
"self",
",",
"dict",
"=",
"None",
",",
"indent",
"=",
"None",
")",
":",
"if",
"not",
"dict",
":",
"dict",
"=",
"self",
".",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"dict",
".",
"iteritems",
"(",
")",
":",
"if",
... | Returns post JSON representation | [
"Returns",
"post",
"JSON",
"representation"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L88-L96 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin.get_cache_key | def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''):
""" The return of Get
"""
return hashlib.sha1(
'.'.join([
str(self._get_data_source_url()),
str(offset),
str(limit),
str(order),
str(p... | python | def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''):
""" The return of Get
"""
return hashlib.sha1(
'.'.join([
str(self._get_data_source_url()),
str(offset),
str(limit),
str(order),
str(p... | [
"def",
"get_cache_key",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"0",
",",
"order",
"=",
"None",
",",
"post_slug",
"=",
"''",
")",
":",
"return",
"hashlib",
".",
"sha1",
"(",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"self",
".",
... | The return of Get | [
"The",
"return",
"of",
"Get"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L151-L162 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin.get_posts | def get_posts(self, offset=0, limit=1000, order=None, filters=None):
""" This method returns list of Posts for this Data Source starting at a given offset and not more than limit
It will call content-specific methods:
_format() to format output from the DataStore
"""
order =... | python | def get_posts(self, offset=0, limit=1000, order=None, filters=None):
""" This method returns list of Posts for this Data Source starting at a given offset and not more than limit
It will call content-specific methods:
_format() to format output from the DataStore
"""
order =... | [
"def",
"get_posts",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"1000",
",",
"order",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"order",
"=",
"self",
".",
"_get_order",
"(",
"order",
")",
"cache_key",
"=",
"self",
".",
"get_c... | This method returns list of Posts for this Data Source starting at a given offset and not more than limit
It will call content-specific methods:
_format() to format output from the DataStore | [
"This",
"method",
"returns",
"list",
"of",
"Posts",
"for",
"this",
"Data",
"Source",
"starting",
"at",
"a",
"given",
"offset",
"and",
"not",
"more",
"than",
"limit",
"It",
"will",
"call",
"content",
"-",
"specific",
"methods",
":",
"_format",
"()",
"to",
... | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L164-L187 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin.get_post | def get_post(self, slug):
""" This method returns a single post by slug
"""
cache_key = self.get_cache_key(post_slug=slug)
content = cache.get(cache_key)
if not content:
post = Post.objects.get(slug=slug)
content = self._format(post)
cache_dura... | python | def get_post(self, slug):
""" This method returns a single post by slug
"""
cache_key = self.get_cache_key(post_slug=slug)
content = cache.get(cache_key)
if not content:
post = Post.objects.get(slug=slug)
content = self._format(post)
cache_dura... | [
"def",
"get_post",
"(",
"self",
",",
"slug",
")",
":",
"cache_key",
"=",
"self",
".",
"get_cache_key",
"(",
"post_slug",
"=",
"slug",
")",
"content",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"if",
"not",
"content",
":",
"post",
"=",
"Post",
"... | This method returns a single post by slug | [
"This",
"method",
"returns",
"a",
"single",
"post",
"by",
"slug"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L189-L199 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin.up_to_date | def up_to_date(self):
""" Returns True if plugin posts are up to date
Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY
"""
# return False
if not self.updated:
return False
return (utils.get_datetime_now() - self.updated).seconds < conf.GOSCAL... | python | def up_to_date(self):
""" Returns True if plugin posts are up to date
Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY
"""
# return False
if not self.updated:
return False
return (utils.get_datetime_now() - self.updated).seconds < conf.GOSCAL... | [
"def",
"up_to_date",
"(",
"self",
")",
":",
"# return False",
"if",
"not",
"self",
".",
"updated",
":",
"return",
"False",
"return",
"(",
"utils",
".",
"get_datetime_now",
"(",
")",
"-",
"self",
".",
"updated",
")",
".",
"seconds",
"<",
"conf",
".... | Returns True if plugin posts are up to date
Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY | [
"Returns",
"True",
"if",
"plugin",
"posts",
"are",
"up",
"to",
"date"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L201-L209 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin.update | def update(self):
"""This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this D... | python | def update(self):
"""This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this D... | [
"def",
"update",
"(",
"self",
")",
":",
"#get the raw data",
"# self.posts.all().delete() # TODO: handle in update_posts if source changes without deleting every time",
"data",
"=",
"self",
".",
"_get_data",
"(",
")",
"#iterate through them and for each item",
"msg",
"=",
... | This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this Data Source | [
"This",
"method",
"should",
"be",
"called",
"to",
"update",
"associated",
"Posts",
"It",
"will",
"call",
"content",
"-",
"specific",
"methods",
":",
"_get_data",
"()",
"to",
"obtain",
"list",
"of",
"entries",
"_store_post",
"()",
"to",
"store",
"obtained",
"... | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L211-L235 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin._get_query | def _get_query(self, order=None, filters=None):
""" This method is just to evade code duplication in count() and get_content, since they do basically the same thing"""
order = self._get_order(order)
return self.posts.all().order_by(order) | python | def _get_query(self, order=None, filters=None):
""" This method is just to evade code duplication in count() and get_content, since they do basically the same thing"""
order = self._get_order(order)
return self.posts.all().order_by(order) | [
"def",
"_get_query",
"(",
"self",
",",
"order",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"order",
"=",
"self",
".",
"_get_order",
"(",
"order",
")",
"return",
"self",
".",
"posts",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"order",
")"... | This method is just to evade code duplication in count() and get_content, since they do basically the same thing | [
"This",
"method",
"is",
"just",
"to",
"evade",
"code",
"duplication",
"in",
"count",
"()",
"and",
"get_content",
"since",
"they",
"do",
"basically",
"the",
"same",
"thing"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L277-L280 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin._format | def _format(self, posts):
""" This method is called by get_content() method"""
if posts.__class__ == Post:
# format a single post
return posts.dict()
formated_posts = []
for post in posts:
formated_posts.append(post.dict())
return formated_post... | python | def _format(self, posts):
""" This method is called by get_content() method"""
if posts.__class__ == Post:
# format a single post
return posts.dict()
formated_posts = []
for post in posts:
formated_posts.append(post.dict())
return formated_post... | [
"def",
"_format",
"(",
"self",
",",
"posts",
")",
":",
"if",
"posts",
".",
"__class__",
"==",
"Post",
":",
"# format a single post",
"return",
"posts",
".",
"dict",
"(",
")",
"formated_posts",
"=",
"[",
"]",
"for",
"post",
"in",
"posts",
":",
"formated_p... | This method is called by get_content() method | [
"This",
"method",
"is",
"called",
"by",
"get_content",
"()",
"method"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L282-L290 |
sternoru/goscalecms | goscale/models.py | GoscaleCMSPlugin._store_post | def _store_post(self, stored_entry, entry=None):
""" This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME """
# stored_entry.content_type = utils.get_source_setting(ds.type, 'type')
if stored_entry.published is None:
stored_... | python | def _store_post(self, stored_entry, entry=None):
""" This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME """
# stored_entry.content_type = utils.get_source_setting(ds.type, 'type')
if stored_entry.published is None:
stored_... | [
"def",
"_store_post",
"(",
"self",
",",
"stored_entry",
",",
"entry",
"=",
"None",
")",
":",
"# stored_entry.content_type = utils.get_source_setting(ds.type, 'type')",
"if",
"stored_entry",
".",
"published",
"is",
"None",
":",
"stored_entry",
".",
"published",
"=... | This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME | [
"This",
"method",
"formats",
"entry",
"returned",
"by",
"_get_data",
"()",
"and",
"puts",
"to",
"DB",
"create",
"textDesc",
"title",
"and",
"MIME"
] | train | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L292-L304 |
pjuren/pyokit | src/pyokit/scripts/pyokitMain.py | dispatch | def dispatch(args):
"""
Parse the command line and dispatch the appropriate script.
This function just performs dispatch on the command line that a user
provided. Basically, look at the first argument, which specifies the
function the user wants Ribocop to perform, then dispatch to the appropriate
module.
... | python | def dispatch(args):
"""
Parse the command line and dispatch the appropriate script.
This function just performs dispatch on the command line that a user
provided. Basically, look at the first argument, which specifies the
function the user wants Ribocop to perform, then dispatch to the appropriate
module.
... | [
"def",
"dispatch",
"(",
"args",
")",
":",
"prog_name",
"=",
"args",
"[",
"0",
"]",
"if",
"prog_name",
"not",
"in",
"dispatchers",
":",
"raise",
"NoSuchScriptError",
"(",
"\"No such pyokit script: \"",
"+",
"prog_name",
"+",
"\"\\n\"",
")",
"else",
":",
"disp... | Parse the command line and dispatch the appropriate script.
This function just performs dispatch on the command line that a user
provided. Basically, look at the first argument, which specifies the
function the user wants Ribocop to perform, then dispatch to the appropriate
module. | [
"Parse",
"the",
"command",
"line",
"and",
"dispatch",
"the",
"appropriate",
"script",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/pyokitMain.py#L130-L143 |
lehins/python-wepay | wepay/calls/subscription_charge.py | SubscriptionCharge.__refund | def __refund(self, subscription_charge_id, **kwargs):
"""Call documentation: `/subscription_charge/refund
<https://www.wepay.com/developer/reference/subscription_charge#refund>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``a... | python | def __refund(self, subscription_charge_id, **kwargs):
"""Call documentation: `/subscription_charge/refund
<https://www.wepay.com/developer/reference/subscription_charge#refund>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``a... | [
"def",
"__refund",
"(",
"self",
",",
"subscription_charge_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'subscription_charge_id'",
":",
"subscription_charge_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__refund",
",",
"params... | Call documentation: `/subscription_charge/refund
<https://www.wepay.com/developer/reference/subscription_charge#refund>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"subscription_charge",
"/",
"refund",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"subscription_charge#refund",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":"
] | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_charge.py#L62-L84 |
20c/xbahn | xbahn/message.py | Message.export | def export(self, contentType):
"""
Export message to specified contentType via munge
contentType <str> - eg. "json", "yaml"
"""
cls = munge.get_codec(contentType)
codec = cls()
return codec.dumps(self.__dict__()) | python | def export(self, contentType):
"""
Export message to specified contentType via munge
contentType <str> - eg. "json", "yaml"
"""
cls = munge.get_codec(contentType)
codec = cls()
return codec.dumps(self.__dict__()) | [
"def",
"export",
"(",
"self",
",",
"contentType",
")",
":",
"cls",
"=",
"munge",
".",
"get_codec",
"(",
"contentType",
")",
"codec",
"=",
"cls",
"(",
")",
"return",
"codec",
".",
"dumps",
"(",
"self",
".",
"__dict__",
"(",
")",
")"
] | Export message to specified contentType via munge
contentType <str> - eg. "json", "yaml" | [
"Export",
"message",
"to",
"specified",
"contentType",
"via",
"munge"
] | train | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/message.py#L71-L79 |
jthacker/terseparse | terseparse/builders.py | Parser.parse_args | def parse_args(self, args=None, namespace=None, defaults=None):
"""Parse args, returns a tuple of a parser and ParsedArgs object
Args:
args -- sequence of strings representing the arguments to parse
namespace -- object to use for holding arguments
defaults -- la... | python | def parse_args(self, args=None, namespace=None, defaults=None):
"""Parse args, returns a tuple of a parser and ParsedArgs object
Args:
args -- sequence of strings representing the arguments to parse
namespace -- object to use for holding arguments
defaults -- la... | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"epilog",
"=",
"self",
".",
"subparsers_summary",
"(",
")",
"epilog",
"+=",
"self",
".",
"epilog",
"return",
"self",
"(",... | Parse args, returns a tuple of a parser and ParsedArgs object
Args:
args -- sequence of strings representing the arguments to parse
namespace -- object to use for holding arguments
defaults -- lazily loaded dict like object of default arguments
Returns: (parser,... | [
"Parse",
"args",
"returns",
"a",
"tuple",
"of",
"a",
"parser",
"and",
"ParsedArgs",
"object",
"Args",
":",
"args",
"--",
"sequence",
"of",
"strings",
"representing",
"the",
"arguments",
"to",
"parse",
"namespace",
"--",
"object",
"to",
"use",
"for",
"holding... | train | https://github.com/jthacker/terseparse/blob/236a31faf819f3ae9019a545613b8e7a6808f7b2/terseparse/builders.py#L134-L147 |
nens/turn | turn/console.py | get_parser | def get_parser():
""" Return argument parser. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__,
)
# connection to redis server
parser.add_argument('--host', default='localhost')
parser.add_argument('--port', default=6379, t... | python | def get_parser():
""" Return argument parser. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__,
)
# connection to redis server
parser.add_argument('--host', default='localhost')
parser.add_argument('--port', default=6379, t... | [
"def",
"get_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"RawTextHelpFormatter",
",",
"description",
"=",
"__doc__",
",",
")",
"# connection to redis server",
"parser",
".",
"add_argument",
... | Return argument parser. | [
"Return",
"argument",
"parser",
"."
] | train | https://github.com/nens/turn/blob/98e806a0749ada0ddfd04b3c29fb04c15bf5ac18/turn/console.py#L43-L60 |
knagra/farnsworth | managers/ajax.py | build_ajax_votes | def build_ajax_votes(request, user_profile):
"""Build vote information for the request."""
vote_list = ''
for profile in request.upvotes.all():
vote_list += \
'<li><a title="View Profile" href="{url}">{name}</a></li>'.format(
url=reverse(
'member_profi... | python | def build_ajax_votes(request, user_profile):
"""Build vote information for the request."""
vote_list = ''
for profile in request.upvotes.all():
vote_list += \
'<li><a title="View Profile" href="{url}">{name}</a></li>'.format(
url=reverse(
'member_profi... | [
"def",
"build_ajax_votes",
"(",
"request",
",",
"user_profile",
")",
":",
"vote_list",
"=",
"''",
"for",
"profile",
"in",
"request",
".",
"upvotes",
".",
"all",
"(",
")",
":",
"vote_list",
"+=",
"'<li><a title=\"View Profile\" href=\"{url}\">{name}</a></li>'",
".",
... | Build vote information for the request. | [
"Build",
"vote",
"information",
"for",
"the",
"request",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/managers/ajax.py#L13-L30 |
makyo/prose-wc | prose_wc/wc.py | setup | def setup(argv):
"""Sets up the ArgumentParser.
Args:
argv: an array of arguments
"""
parser = argparse.ArgumentParser(
description='Compute Jekyl- and prose-aware wordcounts',
epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)')
parser.add_argument('-S', '--... | python | def setup(argv):
"""Sets up the ArgumentParser.
Args:
argv: an array of arguments
"""
parser = argparse.ArgumentParser(
description='Compute Jekyl- and prose-aware wordcounts',
epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)')
parser.add_argument('-S', '--... | [
"def",
"setup",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Compute Jekyl- and prose-aware wordcounts'",
",",
"epilog",
"=",
"'Accepted filetypes: plaintext, markdown, markdown (Jekyll)'",
")",
"parser",
".",
"add_ar... | Sets up the ArgumentParser.
Args:
argv: an array of arguments | [
"Sets",
"up",
"the",
"ArgumentParser",
"."
] | train | https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L44-L70 |
makyo/prose-wc | prose_wc/wc.py | prose_wc | def prose_wc(args):
"""Processes data provided to print a count object, or update a file.
Args:
args: an ArgumentParser object returned by setup()
"""
if args.file is None:
return 1
if args.split_hyphens:
INTERSTITIAL_PUNCTUATION.append(re.compile(r'-'))
content = args.f... | python | def prose_wc(args):
"""Processes data provided to print a count object, or update a file.
Args:
args: an ArgumentParser object returned by setup()
"""
if args.file is None:
return 1
if args.split_hyphens:
INTERSTITIAL_PUNCTUATION.append(re.compile(r'-'))
content = args.f... | [
"def",
"prose_wc",
"(",
"args",
")",
":",
"if",
"args",
".",
"file",
"is",
"None",
":",
"return",
"1",
"if",
"args",
".",
"split_hyphens",
":",
"INTERSTITIAL_PUNCTUATION",
".",
"append",
"(",
"re",
".",
"compile",
"(",
"r'-'",
")",
")",
"content",
"=",... | Processes data provided to print a count object, or update a file.
Args:
args: an ArgumentParser object returned by setup() | [
"Processes",
"data",
"provided",
"to",
"print",
"a",
"count",
"object",
"or",
"update",
"a",
"file",
"."
] | train | https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L73-L100 |
makyo/prose-wc | prose_wc/wc.py | markdown_to_text | def markdown_to_text(body):
"""Converts markdown to text.
Args:
body: markdown (or plaintext, or maybe HTML) input
Returns:
Plaintext with all tags and frills removed
"""
# Turn our input into HTML
md = markdown.markdown(body, extensions=[
'markdown.extensions.extra'
... | python | def markdown_to_text(body):
"""Converts markdown to text.
Args:
body: markdown (or plaintext, or maybe HTML) input
Returns:
Plaintext with all tags and frills removed
"""
# Turn our input into HTML
md = markdown.markdown(body, extensions=[
'markdown.extensions.extra'
... | [
"def",
"markdown_to_text",
"(",
"body",
")",
":",
"# Turn our input into HTML",
"md",
"=",
"markdown",
".",
"markdown",
"(",
"body",
",",
"extensions",
"=",
"[",
"'markdown.extensions.extra'",
"]",
")",
"# Safely parse HTML so that we don't have to parse it ourselves",
"s... | Converts markdown to text.
Args:
body: markdown (or plaintext, or maybe HTML) input
Returns:
Plaintext with all tags and frills removed | [
"Converts",
"markdown",
"to",
"text",
"."
] | train | https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L103-L121 |
makyo/prose-wc | prose_wc/wc.py | wc | def wc(filename, contents, parsed=None, is_jekyll=False):
"""Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext only
... | python | def wc(filename, contents, parsed=None, is_jekyll=False):
"""Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext only
... | [
"def",
"wc",
"(",
"filename",
",",
"contents",
",",
"parsed",
"=",
"None",
",",
"is_jekyll",
"=",
"False",
")",
":",
"if",
"is_jekyll",
":",
"fmt",
"=",
"'jekyll'",
"else",
":",
"fmt",
"=",
"'md/txt'",
"body",
"=",
"parsed",
".",
"strip",
"(",
")",
... | Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext only
is_jekyll: whether the original contents were from a Jekyl... | [
"Count",
"the",
"words",
"characters",
"and",
"paragraphs",
"in",
"a",
"string",
"."
] | train | https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L138-L182 |
makyo/prose-wc | prose_wc/wc.py | update_file | def update_file(filename, result, content, indent):
"""Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the c... | python | def update_file(filename, result, content, indent):
"""Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the c... | [
"def",
"update_file",
"(",
"filename",
",",
"result",
",",
"content",
",",
"indent",
")",
":",
"# Split the file into frontmatter and content",
"parts",
"=",
"re",
".",
"split",
"(",
"'---+'",
",",
"content",
",",
"2",
")",
"# Load the frontmatter into an object",
... | Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the contents of the original file
indent: the indentatio... | [
"Updates",
"a",
"Jekyll",
"file",
"to",
"contain",
"the",
"counts",
"form",
"an",
"object"
] | train | https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L185-L214 |
opinkerfi/nago | nago/core/__init__.py | log | def log(message, level="info"):
""" Add a new log entry to the nago log.
Arguments:
level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error)
message - Arbritary string, the message that is to be logged.
"""
now = time.time()
entry = {}
entry['level... | python | def log(message, level="info"):
""" Add a new log entry to the nago log.
Arguments:
level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error)
message - Arbritary string, the message that is to be logged.
"""
now = time.time()
entry = {}
entry['level... | [
"def",
"log",
"(",
"message",
",",
"level",
"=",
"\"info\"",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"entry",
"=",
"{",
"}",
"entry",
"[",
"'level'",
"]",
"=",
"level",
"entry",
"[",
"'message'",
"]",
"=",
"message",
"entry",
"[",
"'... | Add a new log entry to the nago log.
Arguments:
level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error)
message - Arbritary string, the message that is to be logged. | [
"Add",
"a",
"new",
"log",
"entry",
"to",
"the",
"nago",
"log",
"."
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L28-L40 |
opinkerfi/nago | nago/core/__init__.py | nago_access | def nago_access(access_required="master", name=None):
""" Decorate other functions with this one to allow access
Arguments:
nago_access -- Type of access required to call this function
By default only master is allowed to make that call
nago_name -- What name this func... | python | def nago_access(access_required="master", name=None):
""" Decorate other functions with this one to allow access
Arguments:
nago_access -- Type of access required to call this function
By default only master is allowed to make that call
nago_name -- What name this func... | [
"def",
"nago_access",
"(",
"access_required",
"=",
"\"master\"",
",",
"name",
"=",
"None",
")",
":",
"def",
"real_decorator",
"(",
"func",
")",
":",
"func",
".",
"nago_access",
"=",
"access_required",
"func",
".",
"nago_name",
"=",
"name",
"or",
"func",
".... | Decorate other functions with this one to allow access
Arguments:
nago_access -- Type of access required to call this function
By default only master is allowed to make that call
nago_name -- What name this function will have to remote api
Default is... | [
"Decorate",
"other",
"functions",
"with",
"this",
"one",
"to",
"allow",
"access"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L45-L63 |
opinkerfi/nago | nago/core/__init__.py | get_nodes | def get_nodes():
""" Returns all nodes in a list of dicts format
"""
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
for section in config.sections():
if section in ['main']:
continue
token = section
n... | python | def get_nodes():
""" Returns all nodes in a list of dicts format
"""
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
for section in config.sections():
if section in ['main']:
continue
token = section
n... | [
"def",
"get_nodes",
"(",
")",
":",
"cfg_file",
"=",
"\"/etc/nago/nago.ini\"",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"cfg_file",
")",
"result",
"=",
"{",
"}",
"for",
"section",
"in",
"config",
".",
"sectio... | Returns all nodes in a list of dicts format | [
"Returns",
"all",
"nodes",
"in",
"a",
"list",
"of",
"dicts",
"format"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L66-L81 |
opinkerfi/nago | nago/core/__init__.py | generate_token | def generate_token():
""" Generate a new random security token.
>>> len(generate_token()) == 50
True
Returns:
string
"""
length = 50
stringset = string.ascii_letters + string.digits
token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]])... | python | def generate_token():
""" Generate a new random security token.
>>> len(generate_token()) == 50
True
Returns:
string
"""
length = 50
stringset = string.ascii_letters + string.digits
token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]])... | [
"def",
"generate_token",
"(",
")",
":",
"length",
"=",
"50",
"stringset",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"token",
"=",
"''",
".",
"join",
"(",
"[",
"stringset",
"[",
"i",
"%",
"len",
"(",
"stringset",
")",
"]",
"fo... | Generate a new random security token.
>>> len(generate_token()) == 50
True
Returns:
string | [
"Generate",
"a",
"new",
"random",
"security",
"token",
"."
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L99-L111 |
opinkerfi/nago | nago/core/__init__.py | get_my_info | def get_my_info():
""" Return general information about this node
"""
result = {}
result['host_name'] = platform.node()
result['real_host_name'] = platform.node()
result['dist'] = platform.dist()
result['nago_version'] = nago.get_version()
return result | python | def get_my_info():
""" Return general information about this node
"""
result = {}
result['host_name'] = platform.node()
result['real_host_name'] = platform.node()
result['dist'] = platform.dist()
result['nago_version'] = nago.get_version()
return result | [
"def",
"get_my_info",
"(",
")",
":",
"result",
"=",
"{",
"}",
"result",
"[",
"'host_name'",
"]",
"=",
"platform",
".",
"node",
"(",
")",
"result",
"[",
"'real_host_name'",
"]",
"=",
"platform",
".",
"node",
"(",
")",
"result",
"[",
"'dist'",
"]",
"="... | Return general information about this node | [
"Return",
"general",
"information",
"about",
"this",
"node"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L232-L240 |
opinkerfi/nago | nago/core/__init__.py | Node.delete | def delete(self):
""" Delete this node from config files """
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
token = self.data.pop("token", self.token)
if token not in config.sections():
raise Exce... | python | def delete(self):
""" Delete this node from config files """
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
token = self.data.pop("token", self.token)
if token not in config.sections():
raise Exce... | [
"def",
"delete",
"(",
"self",
")",
":",
"cfg_file",
"=",
"\"/etc/nago/nago.ini\"",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"cfg_file",
")",
"result",
"=",
"{",
"}",
"token",
"=",
"self",
".",
"data",
".",... | Delete this node from config files | [
"Delete",
"this",
"node",
"from",
"config",
"files"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L138-L149 |
opinkerfi/nago | nago/core/__init__.py | Node.save | def save(self):
""" Save this node (and all its attributes) to config """
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
token = self.data.pop("token", self.token)
if token != self._original_token:
... | python | def save(self):
""" Save this node (and all its attributes) to config """
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
token = self.data.pop("token", self.token)
if token != self._original_token:
... | [
"def",
"save",
"(",
"self",
")",
":",
"cfg_file",
"=",
"\"/etc/nago/nago.ini\"",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"cfg_file",
")",
"result",
"=",
"{",
"}",
"token",
"=",
"self",
".",
"data",
".",
... | Save this node (and all its attributes) to config | [
"Save",
"this",
"node",
"(",
"and",
"all",
"its",
"attributes",
")",
"to",
"config"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L151-L170 |
opinkerfi/nago | nago/core/__init__.py | Node.get_info | def get_info(self, key=None):
""" Return all posted info about this node """
node_data = nago.extensions.info.node_data.get(self.token, {})
if key is None:
return node_data
else:
return node_data.get(key, {}) | python | def get_info(self, key=None):
""" Return all posted info about this node """
node_data = nago.extensions.info.node_data.get(self.token, {})
if key is None:
return node_data
else:
return node_data.get(key, {}) | [
"def",
"get_info",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"node_data",
"=",
"nago",
".",
"extensions",
".",
"info",
".",
"node_data",
".",
"get",
"(",
"self",
".",
"token",
",",
"{",
"}",
")",
"if",
"key",
"is",
"None",
":",
"return",
"n... | Return all posted info about this node | [
"Return",
"all",
"posted",
"info",
"about",
"this",
"node"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L178-L184 |
hirokiky/matcha | matcha.py | include | def include(pattern, matching):
""" Including a other matching, to get as matching pattern's child paths.
"""
matching.matching_records = [
MatchingRecord(
PathTemplate(pattern) + child_path_template,
case,
child_name
) for child_path_template, case, child... | python | def include(pattern, matching):
""" Including a other matching, to get as matching pattern's child paths.
"""
matching.matching_records = [
MatchingRecord(
PathTemplate(pattern) + child_path_template,
case,
child_name
) for child_path_template, case, child... | [
"def",
"include",
"(",
"pattern",
",",
"matching",
")",
":",
"matching",
".",
"matching_records",
"=",
"[",
"MatchingRecord",
"(",
"PathTemplate",
"(",
"pattern",
")",
"+",
"child_path_template",
",",
"case",
",",
"child_name",
")",
"for",
"child_path_template",... | Including a other matching, to get as matching pattern's child paths. | [
"Including",
"a",
"other",
"matching",
"to",
"get",
"as",
"matching",
"pattern",
"s",
"child",
"paths",
"."
] | train | https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L159-L169 |
hirokiky/matcha | matcha.py | make_wsgi_app | def make_wsgi_app(matching, not_found_app=not_found_app):
""" Making a WSGI application from Matching object
registered other WSGI applications on each 'case' argument.
"""
def wsgi_app(environ, start_response):
environ['matcha.matching'] = matching
try:
matched_case, matched... | python | def make_wsgi_app(matching, not_found_app=not_found_app):
""" Making a WSGI application from Matching object
registered other WSGI applications on each 'case' argument.
"""
def wsgi_app(environ, start_response):
environ['matcha.matching'] = matching
try:
matched_case, matched... | [
"def",
"make_wsgi_app",
"(",
"matching",
",",
"not_found_app",
"=",
"not_found_app",
")",
":",
"def",
"wsgi_app",
"(",
"environ",
",",
"start_response",
")",
":",
"environ",
"[",
"'matcha.matching'",
"]",
"=",
"matching",
"try",
":",
"matched_case",
",",
"matc... | Making a WSGI application from Matching object
registered other WSGI applications on each 'case' argument. | [
"Making",
"a",
"WSGI",
"application",
"from",
"Matching",
"object",
"registered",
"other",
"WSGI",
"applications",
"on",
"each",
"case",
"argument",
"."
] | train | https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L177-L190 |
hirokiky/matcha | matcha.py | Matching.reverse | def reverse(self, matching_name, **kwargs):
""" Getting a matching name and URL args and return a corresponded URL
"""
for record in self.matching_records:
if record.name == matching_name:
path_template = record.path_template
break
else:
... | python | def reverse(self, matching_name, **kwargs):
""" Getting a matching name and URL args and return a corresponded URL
"""
for record in self.matching_records:
if record.name == matching_name:
path_template = record.path_template
break
else:
... | [
"def",
"reverse",
"(",
"self",
",",
"matching_name",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"record",
"in",
"self",
".",
"matching_records",
":",
"if",
"record",
".",
"name",
"==",
"matching_name",
":",
"path_template",
"=",
"record",
".",
"path_templat... | Getting a matching name and URL args and return a corresponded URL | [
"Getting",
"a",
"matching",
"name",
"and",
"URL",
"args",
"and",
"return",
"a",
"corresponded",
"URL"
] | train | https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L65-L89 |
laysakura/nextversion | nextversion/__init__.py | nextversion | def nextversion(current_version):
"""Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
... | python | def nextversion(current_version):
"""Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
... | [
"def",
"nextversion",
"(",
"current_version",
")",
":",
"norm_ver",
"=",
"verlib",
".",
"suggest_normalized_version",
"(",
"current_version",
")",
"if",
"norm_ver",
"is",
"None",
":",
"return",
"None",
"norm_ver",
"=",
"verlib",
".",
"NormalizedVersion",
"(",
"n... | Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
`None` is returne... | [
"Returns",
"incremented",
"module",
"version",
"number",
"."
] | train | https://github.com/laysakura/nextversion/blob/49a143dfe64dcb9f83c78ac2ea04774f7df32378/nextversion/__init__.py#L21-L48 |
bobcolner/urlrap | urlrap/urlrap.py | normalize | def normalize(url, strip=False):
"RFC3986 normalize URL & Optionally removing url-query/fragment string"
if strip:
p = _urltools.parse(url)
url = p.scheme + '://' + p.subdomain + p.domain + p.path
return _urltools.normalize(url) | python | def normalize(url, strip=False):
"RFC3986 normalize URL & Optionally removing url-query/fragment string"
if strip:
p = _urltools.parse(url)
url = p.scheme + '://' + p.subdomain + p.domain + p.path
return _urltools.normalize(url) | [
"def",
"normalize",
"(",
"url",
",",
"strip",
"=",
"False",
")",
":",
"if",
"strip",
":",
"p",
"=",
"_urltools",
".",
"parse",
"(",
"url",
")",
"url",
"=",
"p",
".",
"scheme",
"+",
"'://'",
"+",
"p",
".",
"subdomain",
"+",
"p",
".",
"domain",
"... | RFC3986 normalize URL & Optionally removing url-query/fragment string | [
"RFC3986",
"normalize",
"URL",
"&",
"Optionally",
"removing",
"url",
"-",
"query",
"/",
"fragment",
"string"
] | train | https://github.com/bobcolner/urlrap/blob/62edbcb8dd9849ac579d01892baff707a841ff0f/urlrap/urlrap.py#L5-L10 |
bobcolner/urlrap | urlrap/urlrap.py | find_date | def find_date(url):
"Extract date from URL page if exists."
def _clean_split(div_str):
sl = []
for div in div_str.split('/'):
div = div.strip().lower()
if div != '':
sl.append(div)
return sl
url_path = find_path(url)
url_path_parts... | python | def find_date(url):
"Extract date from URL page if exists."
def _clean_split(div_str):
sl = []
for div in div_str.split('/'):
div = div.strip().lower()
if div != '':
sl.append(div)
return sl
url_path = find_path(url)
url_path_parts... | [
"def",
"find_date",
"(",
"url",
")",
":",
"def",
"_clean_split",
"(",
"div_str",
")",
":",
"sl",
"=",
"[",
"]",
"for",
"div",
"in",
"div_str",
".",
"split",
"(",
"'/'",
")",
":",
"div",
"=",
"div",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")"... | Extract date from URL page if exists. | [
"Extract",
"date",
"from",
"URL",
"page",
"if",
"exists",
"."
] | train | https://github.com/bobcolner/urlrap/blob/62edbcb8dd9849ac579d01892baff707a841ff0f/urlrap/urlrap.py#L12-L34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.