id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
239,000
|
mikicz/arca
|
arca/backend/vagrant.py
|
VagrantBackend.run
|
def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path):
""" Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result.
Stops the VM if ``keep_vm_running`` is not set.
"""
from fabric import api
from fabric.exceptions import CommandTimeout
# start up or get running VM
vm_location = self.get_vm_location()
self.ensure_vm_running(vm_location)
logger.info("Running with VM located at %s", vm_location)
# pushes the image to the registry so it can be pulled in the VM
self.check_docker_access() # init client
self.get_image_for_repo(repo, branch, git_repo, repo_path)
requirements_option, requirements_hash = self.get_requirements_information(repo_path)
# getting things needed for execution over SSH
image_tag = self.get_image_tag(requirements_option, requirements_hash, self.get_dependencies())
image_name = self.use_registry_name
task_filename, task_json = self.serialized_task(task)
(vm_location / task_filename).write_text(task_json)
container_name = self.get_container_name(repo, branch, git_repo)
# setting up Fabric
api.env.hosts = [self.vagrant.user_hostname_port()]
api.env.key_filename = self.vagrant.keyfile()
api.env.disable_known_hosts = True # useful for when the vagrant box ip changes.
api.env.abort_exception = BuildError # raises SystemExit otherwise
api.env.shell = "/bin/sh -l -c"
if self.quiet:
api.output.everything = False
else:
api.output.everything = True
# executes the task
try:
res = api.execute(self.fabric_task,
container_name=container_name,
definition_filename=task_filename,
image_name=image_name,
image_tag=image_tag,
repository=str(repo_path.relative_to(Path(self._arca.base_dir).resolve() / 'repos')),
timeout=task.timeout)
return Result(res[self.vagrant.user_hostname_port()].stdout)
except CommandTimeout:
raise BuildTimeoutError(f"The task timeouted after {task.timeout} seconds.")
except BuildError: # can be raised by :meth:`Result.__init__`
raise
except Exception as e:
logger.exception(e)
raise BuildError("The build failed", extra_info={
"exception": e
})
finally:
# stops or destroys the VM if it should not be kept running
if not self.keep_vm_running:
if self.destroy:
self.vagrant.destroy()
shutil.rmtree(self.vagrant.root, ignore_errors=True)
self.vagrant = None
else:
self.vagrant.halt()
|
python
|
def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path):
""" Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result.
Stops the VM if ``keep_vm_running`` is not set.
"""
from fabric import api
from fabric.exceptions import CommandTimeout
# start up or get running VM
vm_location = self.get_vm_location()
self.ensure_vm_running(vm_location)
logger.info("Running with VM located at %s", vm_location)
# pushes the image to the registry so it can be pulled in the VM
self.check_docker_access() # init client
self.get_image_for_repo(repo, branch, git_repo, repo_path)
requirements_option, requirements_hash = self.get_requirements_information(repo_path)
# getting things needed for execution over SSH
image_tag = self.get_image_tag(requirements_option, requirements_hash, self.get_dependencies())
image_name = self.use_registry_name
task_filename, task_json = self.serialized_task(task)
(vm_location / task_filename).write_text(task_json)
container_name = self.get_container_name(repo, branch, git_repo)
# setting up Fabric
api.env.hosts = [self.vagrant.user_hostname_port()]
api.env.key_filename = self.vagrant.keyfile()
api.env.disable_known_hosts = True # useful for when the vagrant box ip changes.
api.env.abort_exception = BuildError # raises SystemExit otherwise
api.env.shell = "/bin/sh -l -c"
if self.quiet:
api.output.everything = False
else:
api.output.everything = True
# executes the task
try:
res = api.execute(self.fabric_task,
container_name=container_name,
definition_filename=task_filename,
image_name=image_name,
image_tag=image_tag,
repository=str(repo_path.relative_to(Path(self._arca.base_dir).resolve() / 'repos')),
timeout=task.timeout)
return Result(res[self.vagrant.user_hostname_port()].stdout)
except CommandTimeout:
raise BuildTimeoutError(f"The task timeouted after {task.timeout} seconds.")
except BuildError: # can be raised by :meth:`Result.__init__`
raise
except Exception as e:
logger.exception(e)
raise BuildError("The build failed", extra_info={
"exception": e
})
finally:
# stops or destroys the VM if it should not be kept running
if not self.keep_vm_running:
if self.destroy:
self.vagrant.destroy()
shutil.rmtree(self.vagrant.root, ignore_errors=True)
self.vagrant = None
else:
self.vagrant.halt()
|
[
"def",
"run",
"(",
"self",
",",
"repo",
":",
"str",
",",
"branch",
":",
"str",
",",
"task",
":",
"Task",
",",
"git_repo",
":",
"Repo",
",",
"repo_path",
":",
"Path",
")",
":",
"from",
"fabric",
"import",
"api",
"from",
"fabric",
".",
"exceptions",
"import",
"CommandTimeout",
"# start up or get running VM",
"vm_location",
"=",
"self",
".",
"get_vm_location",
"(",
")",
"self",
".",
"ensure_vm_running",
"(",
"vm_location",
")",
"logger",
".",
"info",
"(",
"\"Running with VM located at %s\"",
",",
"vm_location",
")",
"# pushes the image to the registry so it can be pulled in the VM",
"self",
".",
"check_docker_access",
"(",
")",
"# init client",
"self",
".",
"get_image_for_repo",
"(",
"repo",
",",
"branch",
",",
"git_repo",
",",
"repo_path",
")",
"requirements_option",
",",
"requirements_hash",
"=",
"self",
".",
"get_requirements_information",
"(",
"repo_path",
")",
"# getting things needed for execution over SSH",
"image_tag",
"=",
"self",
".",
"get_image_tag",
"(",
"requirements_option",
",",
"requirements_hash",
",",
"self",
".",
"get_dependencies",
"(",
")",
")",
"image_name",
"=",
"self",
".",
"use_registry_name",
"task_filename",
",",
"task_json",
"=",
"self",
".",
"serialized_task",
"(",
"task",
")",
"(",
"vm_location",
"/",
"task_filename",
")",
".",
"write_text",
"(",
"task_json",
")",
"container_name",
"=",
"self",
".",
"get_container_name",
"(",
"repo",
",",
"branch",
",",
"git_repo",
")",
"# setting up Fabric",
"api",
".",
"env",
".",
"hosts",
"=",
"[",
"self",
".",
"vagrant",
".",
"user_hostname_port",
"(",
")",
"]",
"api",
".",
"env",
".",
"key_filename",
"=",
"self",
".",
"vagrant",
".",
"keyfile",
"(",
")",
"api",
".",
"env",
".",
"disable_known_hosts",
"=",
"True",
"# useful for when the vagrant box ip changes.",
"api",
".",
"env",
".",
"abort_exception",
"=",
"BuildError",
"# raises SystemExit otherwise",
"api",
".",
"env",
".",
"shell",
"=",
"\"/bin/sh -l -c\"",
"if",
"self",
".",
"quiet",
":",
"api",
".",
"output",
".",
"everything",
"=",
"False",
"else",
":",
"api",
".",
"output",
".",
"everything",
"=",
"True",
"# executes the task",
"try",
":",
"res",
"=",
"api",
".",
"execute",
"(",
"self",
".",
"fabric_task",
",",
"container_name",
"=",
"container_name",
",",
"definition_filename",
"=",
"task_filename",
",",
"image_name",
"=",
"image_name",
",",
"image_tag",
"=",
"image_tag",
",",
"repository",
"=",
"str",
"(",
"repo_path",
".",
"relative_to",
"(",
"Path",
"(",
"self",
".",
"_arca",
".",
"base_dir",
")",
".",
"resolve",
"(",
")",
"/",
"'repos'",
")",
")",
",",
"timeout",
"=",
"task",
".",
"timeout",
")",
"return",
"Result",
"(",
"res",
"[",
"self",
".",
"vagrant",
".",
"user_hostname_port",
"(",
")",
"]",
".",
"stdout",
")",
"except",
"CommandTimeout",
":",
"raise",
"BuildTimeoutError",
"(",
"f\"The task timeouted after {task.timeout} seconds.\"",
")",
"except",
"BuildError",
":",
"# can be raised by :meth:`Result.__init__`",
"raise",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"raise",
"BuildError",
"(",
"\"The build failed\"",
",",
"extra_info",
"=",
"{",
"\"exception\"",
":",
"e",
"}",
")",
"finally",
":",
"# stops or destroys the VM if it should not be kept running",
"if",
"not",
"self",
".",
"keep_vm_running",
":",
"if",
"self",
".",
"destroy",
":",
"self",
".",
"vagrant",
".",
"destroy",
"(",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"vagrant",
".",
"root",
",",
"ignore_errors",
"=",
"True",
")",
"self",
".",
"vagrant",
"=",
"None",
"else",
":",
"self",
".",
"vagrant",
".",
"halt",
"(",
")"
] |
Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result.
Stops the VM if ``keep_vm_running`` is not set.
|
[
"Starts",
"up",
"a",
"VM",
"builds",
"an",
"docker",
"image",
"and",
"gets",
"it",
"to",
"the",
"VM",
"runs",
"the",
"script",
"over",
"SSH",
"returns",
"result",
".",
"Stops",
"the",
"VM",
"if",
"keep_vm_running",
"is",
"not",
"set",
"."
] |
e67fdc00be473ecf8ec16d024e1a3f2c47ca882c
|
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/vagrant.py#L226-L292
|
239,001
|
mikicz/arca
|
arca/backend/vagrant.py
|
VagrantBackend.stop_vm
|
def stop_vm(self):
""" Stops or destroys the VM used to launch tasks.
"""
if self.vagrant is not None:
if self.destroy:
self.vagrant.destroy()
shutil.rmtree(self.vagrant.root, ignore_errors=True)
self.vagrant = None
else:
self.vagrant.halt()
|
python
|
def stop_vm(self):
""" Stops or destroys the VM used to launch tasks.
"""
if self.vagrant is not None:
if self.destroy:
self.vagrant.destroy()
shutil.rmtree(self.vagrant.root, ignore_errors=True)
self.vagrant = None
else:
self.vagrant.halt()
|
[
"def",
"stop_vm",
"(",
"self",
")",
":",
"if",
"self",
".",
"vagrant",
"is",
"not",
"None",
":",
"if",
"self",
".",
"destroy",
":",
"self",
".",
"vagrant",
".",
"destroy",
"(",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"vagrant",
".",
"root",
",",
"ignore_errors",
"=",
"True",
")",
"self",
".",
"vagrant",
"=",
"None",
"else",
":",
"self",
".",
"vagrant",
".",
"halt",
"(",
")"
] |
Stops or destroys the VM used to launch tasks.
|
[
"Stops",
"or",
"destroys",
"the",
"VM",
"used",
"to",
"launch",
"tasks",
"."
] |
e67fdc00be473ecf8ec16d024e1a3f2c47ca882c
|
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/vagrant.py#L299-L308
|
239,002
|
maxzheng/remoteconfig
|
remoteconfig/utils.py
|
url_content
|
def url_content(url, cache_duration=None, from_cache_on_error=False):
"""
Get content for the given URL
:param str url: The URL to get content from
:param int cache_duration: Optionally cache the content for the given duration to avoid downloading too often.
:param bool from_cache_on_error: Return cached content on any HTTP request error if available.
"""
cache_file = _url_content_cache_file(url)
if cache_duration:
if os.path.exists(cache_file):
stat = os.stat(cache_file)
cached_time = stat.st_mtime
if time.time() - cached_time < cache_duration:
with open(cache_file) as fp:
return fp.read()
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
content = response.text
except Exception as e:
if from_cache_on_error and os.path.exists(cache_file):
with open(cache_file) as fp:
return fp.read()
else:
raise e.__class__("An error occurred when getting content for %s: %s" % (url, e))
if cache_duration or from_cache_on_error:
with open(cache_file, 'w') as fp:
fp.write(content)
return content
|
python
|
def url_content(url, cache_duration=None, from_cache_on_error=False):
"""
Get content for the given URL
:param str url: The URL to get content from
:param int cache_duration: Optionally cache the content for the given duration to avoid downloading too often.
:param bool from_cache_on_error: Return cached content on any HTTP request error if available.
"""
cache_file = _url_content_cache_file(url)
if cache_duration:
if os.path.exists(cache_file):
stat = os.stat(cache_file)
cached_time = stat.st_mtime
if time.time() - cached_time < cache_duration:
with open(cache_file) as fp:
return fp.read()
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
content = response.text
except Exception as e:
if from_cache_on_error and os.path.exists(cache_file):
with open(cache_file) as fp:
return fp.read()
else:
raise e.__class__("An error occurred when getting content for %s: %s" % (url, e))
if cache_duration or from_cache_on_error:
with open(cache_file, 'w') as fp:
fp.write(content)
return content
|
[
"def",
"url_content",
"(",
"url",
",",
"cache_duration",
"=",
"None",
",",
"from_cache_on_error",
"=",
"False",
")",
":",
"cache_file",
"=",
"_url_content_cache_file",
"(",
"url",
")",
"if",
"cache_duration",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cache_file",
")",
":",
"stat",
"=",
"os",
".",
"stat",
"(",
"cache_file",
")",
"cached_time",
"=",
"stat",
".",
"st_mtime",
"if",
"time",
".",
"time",
"(",
")",
"-",
"cached_time",
"<",
"cache_duration",
":",
"with",
"open",
"(",
"cache_file",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"read",
"(",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"5",
")",
"response",
".",
"raise_for_status",
"(",
")",
"content",
"=",
"response",
".",
"text",
"except",
"Exception",
"as",
"e",
":",
"if",
"from_cache_on_error",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"cache_file",
")",
":",
"with",
"open",
"(",
"cache_file",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"e",
".",
"__class__",
"(",
"\"An error occurred when getting content for %s: %s\"",
"%",
"(",
"url",
",",
"e",
")",
")",
"if",
"cache_duration",
"or",
"from_cache_on_error",
":",
"with",
"open",
"(",
"cache_file",
",",
"'w'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"content",
")",
"return",
"content"
] |
Get content for the given URL
:param str url: The URL to get content from
:param int cache_duration: Optionally cache the content for the given duration to avoid downloading too often.
:param bool from_cache_on_error: Return cached content on any HTTP request error if available.
|
[
"Get",
"content",
"for",
"the",
"given",
"URL"
] |
6edd0bfb9a507abcb2eb0339c5284deb066548b6
|
https://github.com/maxzheng/remoteconfig/blob/6edd0bfb9a507abcb2eb0339c5284deb066548b6/remoteconfig/utils.py#L12-L46
|
239,003
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
route
|
def route(**kwargs):
"""
Route a request to different views based on http verb.
Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE',
where the first four map to a view to route to for that type of
request method/verb, and 'ELSE' maps to a view to pass the request
to if the given request method/verb was not specified.
"""
def routed(request, *args2, **kwargs2):
method = request.method
if method in kwargs:
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
elif 'ELSE' in kwargs:
return kwargs['ELSE'](request, *args2, **kwargs2)
else:
raise Http404()
return routed
|
python
|
def route(**kwargs):
"""
Route a request to different views based on http verb.
Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE',
where the first four map to a view to route to for that type of
request method/verb, and 'ELSE' maps to a view to pass the request
to if the given request method/verb was not specified.
"""
def routed(request, *args2, **kwargs2):
method = request.method
if method in kwargs:
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
elif 'ELSE' in kwargs:
return kwargs['ELSE'](request, *args2, **kwargs2)
else:
raise Http404()
return routed
|
[
"def",
"route",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"routed",
"(",
"request",
",",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
":",
"method",
"=",
"request",
".",
"method",
"if",
"method",
"in",
"kwargs",
":",
"req_method",
"=",
"kwargs",
"[",
"method",
"]",
"return",
"req_method",
"(",
"request",
",",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
"elif",
"'ELSE'",
"in",
"kwargs",
":",
"return",
"kwargs",
"[",
"'ELSE'",
"]",
"(",
"request",
",",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
"else",
":",
"raise",
"Http404",
"(",
")",
"return",
"routed"
] |
Route a request to different views based on http verb.
Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE',
where the first four map to a view to route to for that type of
request method/verb, and 'ELSE' maps to a view to pass the request
to if the given request method/verb was not specified.
|
[
"Route",
"a",
"request",
"to",
"different",
"views",
"based",
"on",
"http",
"verb",
"."
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L19-L37
|
239,004
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
log
|
def log(message=None, out=sys.stdout):
"""Log a message before passing through to the wrapped function.
This is useful if you want to determine whether wrappers are
passing down the pipeline to the functions they wrap, or exiting
early, usually with some kind of exception.
Example:
example_view = decorate(username_matches_request_user,
log("The username matched"),
json_api_call,
example)
"""
def decorator(view_fn):
@wraps(view_fn)
def f(*args, **kwargs):
print(message, file=out)
return view_fn(*args, **kwargs)
return f
return decorator
|
python
|
def log(message=None, out=sys.stdout):
"""Log a message before passing through to the wrapped function.
This is useful if you want to determine whether wrappers are
passing down the pipeline to the functions they wrap, or exiting
early, usually with some kind of exception.
Example:
example_view = decorate(username_matches_request_user,
log("The username matched"),
json_api_call,
example)
"""
def decorator(view_fn):
@wraps(view_fn)
def f(*args, **kwargs):
print(message, file=out)
return view_fn(*args, **kwargs)
return f
return decorator
|
[
"def",
"log",
"(",
"message",
"=",
"None",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"def",
"decorator",
"(",
"view_fn",
")",
":",
"@",
"wraps",
"(",
"view_fn",
")",
"def",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"message",
",",
"file",
"=",
"out",
")",
"return",
"view_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"f",
"return",
"decorator"
] |
Log a message before passing through to the wrapped function.
This is useful if you want to determine whether wrappers are
passing down the pipeline to the functions they wrap, or exiting
early, usually with some kind of exception.
Example:
example_view = decorate(username_matches_request_user,
log("The username matched"),
json_api_call,
example)
|
[
"Log",
"a",
"message",
"before",
"passing",
"through",
"to",
"the",
"wrapped",
"function",
"."
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L40-L59
|
239,005
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
render_template
|
def render_template(template):
"""
takes a template to render to and returns a function that
takes an object to render the data for this template.
If callable_or_dict is callable, it will be called with
the request and any additional arguments to produce the
template paramaters. This is useful for a view-like function
that returns a dict-like object instead of an HttpResponse.
Otherwise, callable_or_dict is used as the parameters for
the rendered response.
"""
def outer_wrapper(callable_or_dict=None, statuscode=None, **kwargs):
def wrapper(request, *args, **wrapper_kwargs):
if callable(callable_or_dict):
params = callable_or_dict(request, *args, **wrapper_kwargs)
else:
params = callable_or_dict
# If we want to return some other response type we can,
# that simply overrides the default behavior
if params is None or isinstance(params, dict):
resp = render(request, template, params, **kwargs)
else:
resp = params
if statuscode:
resp.status_code = statuscode
return resp
return wrapper
return outer_wrapper
|
python
|
def render_template(template):
"""
takes a template to render to and returns a function that
takes an object to render the data for this template.
If callable_or_dict is callable, it will be called with
the request and any additional arguments to produce the
template paramaters. This is useful for a view-like function
that returns a dict-like object instead of an HttpResponse.
Otherwise, callable_or_dict is used as the parameters for
the rendered response.
"""
def outer_wrapper(callable_or_dict=None, statuscode=None, **kwargs):
def wrapper(request, *args, **wrapper_kwargs):
if callable(callable_or_dict):
params = callable_or_dict(request, *args, **wrapper_kwargs)
else:
params = callable_or_dict
# If we want to return some other response type we can,
# that simply overrides the default behavior
if params is None or isinstance(params, dict):
resp = render(request, template, params, **kwargs)
else:
resp = params
if statuscode:
resp.status_code = statuscode
return resp
return wrapper
return outer_wrapper
|
[
"def",
"render_template",
"(",
"template",
")",
":",
"def",
"outer_wrapper",
"(",
"callable_or_dict",
"=",
"None",
",",
"statuscode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"wrapper_kwargs",
")",
":",
"if",
"callable",
"(",
"callable_or_dict",
")",
":",
"params",
"=",
"callable_or_dict",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"wrapper_kwargs",
")",
"else",
":",
"params",
"=",
"callable_or_dict",
"# If we want to return some other response type we can,",
"# that simply overrides the default behavior",
"if",
"params",
"is",
"None",
"or",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"resp",
"=",
"render",
"(",
"request",
",",
"template",
",",
"params",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"resp",
"=",
"params",
"if",
"statuscode",
":",
"resp",
".",
"status_code",
"=",
"statuscode",
"return",
"resp",
"return",
"wrapper",
"return",
"outer_wrapper"
] |
takes a template to render to and returns a function that
takes an object to render the data for this template.
If callable_or_dict is callable, it will be called with
the request and any additional arguments to produce the
template paramaters. This is useful for a view-like function
that returns a dict-like object instead of an HttpResponse.
Otherwise, callable_or_dict is used as the parameters for
the rendered response.
|
[
"takes",
"a",
"template",
"to",
"render",
"to",
"and",
"returns",
"a",
"function",
"that",
"takes",
"an",
"object",
"to",
"render",
"the",
"data",
"for",
"this",
"template",
"."
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L62-L95
|
239,006
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
json_api_call
|
def json_api_call(req_function):
""" Wrap a view-like function that returns an object that
is convertable from json
"""
@wraps(req_function)
def newreq(request, *args, **kwargs):
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
return outp
else:
return '%s' % json.dumps(outp, cls=LazyEncoder)
return string_to_response("application/json")(newreq)
|
python
|
def json_api_call(req_function):
""" Wrap a view-like function that returns an object that
is convertable from json
"""
@wraps(req_function)
def newreq(request, *args, **kwargs):
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
return outp
else:
return '%s' % json.dumps(outp, cls=LazyEncoder)
return string_to_response("application/json")(newreq)
|
[
"def",
"json_api_call",
"(",
"req_function",
")",
":",
"@",
"wraps",
"(",
"req_function",
")",
"def",
"newreq",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"outp",
"=",
"req_function",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"issubclass",
"(",
"outp",
".",
"__class__",
",",
"HttpResponse",
")",
":",
"return",
"outp",
"else",
":",
"return",
"'%s'",
"%",
"json",
".",
"dumps",
"(",
"outp",
",",
"cls",
"=",
"LazyEncoder",
")",
"return",
"string_to_response",
"(",
"\"application/json\"",
")",
"(",
"newreq",
")"
] |
Wrap a view-like function that returns an object that
is convertable from json
|
[
"Wrap",
"a",
"view",
"-",
"like",
"function",
"that",
"returns",
"an",
"object",
"that",
"is",
"convertable",
"from",
"json"
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L98-L109
|
239,007
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
string_to_response
|
def string_to_response(content_type):
"""
Wrap a view-like function that returns a string and marshalls it into an
HttpResponse with the given Content-Type
If the view raises an HttpBadRequestException, it will be converted into
an HttpResponseBadRequest.
"""
def outer_wrapper(req_function):
@wraps(req_function)
def newreq(request, *args, **kwargs):
try:
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
response = outp
else:
response = HttpResponse()
response.write(outp)
response['Content-Length'] = str(len(response.content))
response['Content-Type'] = content_type
except HttpBadRequestException as bad_request:
response = HttpResponseBadRequest(bad_request.message)
return response
return newreq
return outer_wrapper
|
python
|
def string_to_response(content_type):
"""
Wrap a view-like function that returns a string and marshalls it into an
HttpResponse with the given Content-Type
If the view raises an HttpBadRequestException, it will be converted into
an HttpResponseBadRequest.
"""
def outer_wrapper(req_function):
@wraps(req_function)
def newreq(request, *args, **kwargs):
try:
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
response = outp
else:
response = HttpResponse()
response.write(outp)
response['Content-Length'] = str(len(response.content))
response['Content-Type'] = content_type
except HttpBadRequestException as bad_request:
response = HttpResponseBadRequest(bad_request.message)
return response
return newreq
return outer_wrapper
|
[
"def",
"string_to_response",
"(",
"content_type",
")",
":",
"def",
"outer_wrapper",
"(",
"req_function",
")",
":",
"@",
"wraps",
"(",
"req_function",
")",
"def",
"newreq",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"outp",
"=",
"req_function",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"issubclass",
"(",
"outp",
".",
"__class__",
",",
"HttpResponse",
")",
":",
"response",
"=",
"outp",
"else",
":",
"response",
"=",
"HttpResponse",
"(",
")",
"response",
".",
"write",
"(",
"outp",
")",
"response",
"[",
"'Content-Length'",
"]",
"=",
"str",
"(",
"len",
"(",
"response",
".",
"content",
")",
")",
"response",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"except",
"HttpBadRequestException",
"as",
"bad_request",
":",
"response",
"=",
"HttpResponseBadRequest",
"(",
"bad_request",
".",
"message",
")",
"return",
"response",
"return",
"newreq",
"return",
"outer_wrapper"
] |
Wrap a view-like function that returns a string and marshalls it into an
HttpResponse with the given Content-Type
If the view raises an HttpBadRequestException, it will be converted into
an HttpResponseBadRequest.
|
[
"Wrap",
"a",
"view",
"-",
"like",
"function",
"that",
"returns",
"a",
"string",
"and",
"marshalls",
"it",
"into",
"an",
"HttpResponse",
"with",
"the",
"given",
"Content",
"-",
"Type",
"If",
"the",
"view",
"raises",
"an",
"HttpBadRequestException",
"it",
"will",
"be",
"converted",
"into",
"an",
"HttpResponseBadRequest",
"."
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L112-L138
|
239,008
|
azavea/django-tinsel
|
django_tinsel/decorators.py
|
username_matches_request_user
|
def username_matches_request_user(view_fn):
"""Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
"""
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
User = get_user_model()
user = get_object_or_404(User, username=username)
if user != request.user:
return HttpResponseForbidden()
else:
return view_fn(request, user, *args, **kwargs)
return wrapper
|
python
|
def username_matches_request_user(view_fn):
"""Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
"""
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
User = get_user_model()
user = get_object_or_404(User, username=username)
if user != request.user:
return HttpResponseForbidden()
else:
return view_fn(request, user, *args, **kwargs)
return wrapper
|
[
"def",
"username_matches_request_user",
"(",
"view_fn",
")",
":",
"@",
"wraps",
"(",
"view_fn",
")",
"def",
"wrapper",
"(",
"request",
",",
"username",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"user",
"=",
"get_object_or_404",
"(",
"User",
",",
"username",
"=",
"username",
")",
"if",
"user",
"!=",
"request",
".",
"user",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"else",
":",
"return",
"view_fn",
"(",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
|
[
"Checks",
"if",
"the",
"username",
"matches",
"the",
"request",
"user",
"and",
"if",
"so",
"replaces",
"username",
"with",
"the",
"actual",
"user",
"object",
".",
"Returns",
"404",
"if",
"the",
"username",
"does",
"not",
"exist",
"and",
"403",
"if",
"it",
"doesn",
"t",
"match",
"."
] |
ef9e70750d98907b8f72248c1ba4c4423f04f60f
|
https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L141-L156
|
239,009
|
rvswift/EB
|
EB/builder/postanalysis/postanalysis_io.py
|
ParseArgs.get_boolean
|
def get_boolean(self, input_string):
"""
Return boolean type user input
"""
if input_string in ('--write_roc', '--plot', '--compare'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, args are optional, so return the appropriate default
return False
# the flag was set, so return the True
return True
|
python
|
def get_boolean(self, input_string):
"""
Return boolean type user input
"""
if input_string in ('--write_roc', '--plot', '--compare'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, args are optional, so return the appropriate default
return False
# the flag was set, so return the True
return True
|
[
"def",
"get_boolean",
"(",
"self",
",",
"input_string",
")",
":",
"if",
"input_string",
"in",
"(",
"'--write_roc'",
",",
"'--plot'",
",",
"'--compare'",
")",
":",
"# was the flag set?",
"try",
":",
"index",
"=",
"self",
".",
"args",
".",
"index",
"(",
"input_string",
")",
"+",
"1",
"except",
"ValueError",
":",
"# it wasn't, args are optional, so return the appropriate default",
"return",
"False",
"# the flag was set, so return the True",
"return",
"True"
] |
Return boolean type user input
|
[
"Return",
"boolean",
"type",
"user",
"input"
] |
341880b79faf8147dc9fa6e90438531cd09fabcc
|
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis_io.py#L205-L220
|
239,010
|
rbanffy/appengine-fixture-loader
|
appengine_fixture_loader/loader.py
|
load_fixture
|
def load_fixture(filename, kind, post_processor=None):
"""
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
"""
def _load(od, kind, post_processor, parent=None, presets={}):
"""
Loads a single dictionary (od) into an object, overlays the values in
presets, persists it and
calls itself on the objects in __children__* keys
"""
if hasattr(kind, 'keys'): # kind is a map
objtype = kind[od['__kind__']]
else:
objtype = kind
obj_id = od.get('__id__')
if obj_id is not None:
obj = objtype(id=obj_id, parent=parent)
else:
obj = objtype(parent=parent)
# Iterate over the non-special attributes and overlay the presets
for attribute_name in [k for k in od.keys()
if not k.startswith('__') and
not k.endswith('__')] + presets.keys():
attribute_type = objtype.__dict__[attribute_name]
attribute_value = _sensible_value(attribute_type,
presets.get(
attribute_name,
od.get(attribute_name)))
obj.__dict__['_values'][attribute_name] = attribute_value
if post_processor:
post_processor(obj)
# Saving obj is required to continue with the children
obj.put()
loaded = [obj]
# Process ancestor-based __children__
for item in od.get('__children__', []):
loaded.extend(_load(item, kind, post_processor, parent=obj.key))
# Process other __children__[key]__ items
for child_attribute_name in [k for k in od.keys()
if k.startswith('__children__')
and k != '__children__']:
attribute_name = child_attribute_name.split('__')[-2]
for child in od[child_attribute_name]:
loaded.extend(_load(child, kind, post_processor,
presets={attribute_name: obj.key}))
return loaded
tree = json.load(open(filename))
loaded = []
# Start with the top-level of the tree
for item in tree:
loaded.extend(_load(item, kind, post_processor))
return loaded
|
python
|
def load_fixture(filename, kind, post_processor=None):
"""
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
"""
def _load(od, kind, post_processor, parent=None, presets={}):
"""
Loads a single dictionary (od) into an object, overlays the values in
presets, persists it and
calls itself on the objects in __children__* keys
"""
if hasattr(kind, 'keys'): # kind is a map
objtype = kind[od['__kind__']]
else:
objtype = kind
obj_id = od.get('__id__')
if obj_id is not None:
obj = objtype(id=obj_id, parent=parent)
else:
obj = objtype(parent=parent)
# Iterate over the non-special attributes and overlay the presets
for attribute_name in [k for k in od.keys()
if not k.startswith('__') and
not k.endswith('__')] + presets.keys():
attribute_type = objtype.__dict__[attribute_name]
attribute_value = _sensible_value(attribute_type,
presets.get(
attribute_name,
od.get(attribute_name)))
obj.__dict__['_values'][attribute_name] = attribute_value
if post_processor:
post_processor(obj)
# Saving obj is required to continue with the children
obj.put()
loaded = [obj]
# Process ancestor-based __children__
for item in od.get('__children__', []):
loaded.extend(_load(item, kind, post_processor, parent=obj.key))
# Process other __children__[key]__ items
for child_attribute_name in [k for k in od.keys()
if k.startswith('__children__')
and k != '__children__']:
attribute_name = child_attribute_name.split('__')[-2]
for child in od[child_attribute_name]:
loaded.extend(_load(child, kind, post_processor,
presets={attribute_name: obj.key}))
return loaded
tree = json.load(open(filename))
loaded = []
# Start with the top-level of the tree
for item in tree:
loaded.extend(_load(item, kind, post_processor))
return loaded
|
[
"def",
"load_fixture",
"(",
"filename",
",",
"kind",
",",
"post_processor",
"=",
"None",
")",
":",
"def",
"_load",
"(",
"od",
",",
"kind",
",",
"post_processor",
",",
"parent",
"=",
"None",
",",
"presets",
"=",
"{",
"}",
")",
":",
"\"\"\"\n Loads a single dictionary (od) into an object, overlays the values in\n presets, persists it and\n calls itself on the objects in __children__* keys\n \"\"\"",
"if",
"hasattr",
"(",
"kind",
",",
"'keys'",
")",
":",
"# kind is a map",
"objtype",
"=",
"kind",
"[",
"od",
"[",
"'__kind__'",
"]",
"]",
"else",
":",
"objtype",
"=",
"kind",
"obj_id",
"=",
"od",
".",
"get",
"(",
"'__id__'",
")",
"if",
"obj_id",
"is",
"not",
"None",
":",
"obj",
"=",
"objtype",
"(",
"id",
"=",
"obj_id",
",",
"parent",
"=",
"parent",
")",
"else",
":",
"obj",
"=",
"objtype",
"(",
"parent",
"=",
"parent",
")",
"# Iterate over the non-special attributes and overlay the presets",
"for",
"attribute_name",
"in",
"[",
"k",
"for",
"k",
"in",
"od",
".",
"keys",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"'__'",
")",
"and",
"not",
"k",
".",
"endswith",
"(",
"'__'",
")",
"]",
"+",
"presets",
".",
"keys",
"(",
")",
":",
"attribute_type",
"=",
"objtype",
".",
"__dict__",
"[",
"attribute_name",
"]",
"attribute_value",
"=",
"_sensible_value",
"(",
"attribute_type",
",",
"presets",
".",
"get",
"(",
"attribute_name",
",",
"od",
".",
"get",
"(",
"attribute_name",
")",
")",
")",
"obj",
".",
"__dict__",
"[",
"'_values'",
"]",
"[",
"attribute_name",
"]",
"=",
"attribute_value",
"if",
"post_processor",
":",
"post_processor",
"(",
"obj",
")",
"# Saving obj is required to continue with the children",
"obj",
".",
"put",
"(",
")",
"loaded",
"=",
"[",
"obj",
"]",
"# Process ancestor-based __children__",
"for",
"item",
"in",
"od",
".",
"get",
"(",
"'__children__'",
",",
"[",
"]",
")",
":",
"loaded",
".",
"extend",
"(",
"_load",
"(",
"item",
",",
"kind",
",",
"post_processor",
",",
"parent",
"=",
"obj",
".",
"key",
")",
")",
"# Process other __children__[key]__ items",
"for",
"child_attribute_name",
"in",
"[",
"k",
"for",
"k",
"in",
"od",
".",
"keys",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'__children__'",
")",
"and",
"k",
"!=",
"'__children__'",
"]",
":",
"attribute_name",
"=",
"child_attribute_name",
".",
"split",
"(",
"'__'",
")",
"[",
"-",
"2",
"]",
"for",
"child",
"in",
"od",
"[",
"child_attribute_name",
"]",
":",
"loaded",
".",
"extend",
"(",
"_load",
"(",
"child",
",",
"kind",
",",
"post_processor",
",",
"presets",
"=",
"{",
"attribute_name",
":",
"obj",
".",
"key",
"}",
")",
")",
"return",
"loaded",
"tree",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"filename",
")",
")",
"loaded",
"=",
"[",
"]",
"# Start with the top-level of the tree",
"for",
"item",
"in",
"tree",
":",
"loaded",
".",
"extend",
"(",
"_load",
"(",
"item",
",",
"kind",
",",
"post_processor",
")",
")",
"return",
"loaded"
] |
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
|
[
"Loads",
"a",
"file",
"into",
"entities",
"of",
"a",
"given",
"class",
"run",
"the",
"post_processor",
"on",
"each",
"instance",
"before",
"it",
"s",
"saved"
] |
ae7dc44733ff0ad13411aec21f8badd2b95b90d2
|
https://github.com/rbanffy/appengine-fixture-loader/blob/ae7dc44733ff0ad13411aec21f8badd2b95b90d2/appengine_fixture_loader/loader.py#L30-L96
|
239,011
|
gevious/flask_slither
|
flask_slither/__init__.py
|
register_resource
|
def register_resource(mod, view, **kwargs):
"""Register the resource on the resource name or a custom url"""
resource_name = view.__name__.lower()[:-8]
endpoint = kwargs.get('endpoint', "{}_api".format(resource_name))
plural_resource_name = inflect.engine().plural(resource_name)
path = kwargs.get('url', plural_resource_name).strip('/')
url = '/{}'.format(path)
setattr(view, '_url', url) # need this for 201 location header
view_func = view.as_view(endpoint)
mod.add_url_rule(url, view_func=view_func,
methods=['GET', 'POST', 'OPTIONS'])
mod.add_url_rule('{}/<obj_id>'.format(url),
view_func=view_func,
methods=['GET', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'])
|
python
|
def register_resource(mod, view, **kwargs):
"""Register the resource on the resource name or a custom url"""
resource_name = view.__name__.lower()[:-8]
endpoint = kwargs.get('endpoint', "{}_api".format(resource_name))
plural_resource_name = inflect.engine().plural(resource_name)
path = kwargs.get('url', plural_resource_name).strip('/')
url = '/{}'.format(path)
setattr(view, '_url', url) # need this for 201 location header
view_func = view.as_view(endpoint)
mod.add_url_rule(url, view_func=view_func,
methods=['GET', 'POST', 'OPTIONS'])
mod.add_url_rule('{}/<obj_id>'.format(url),
view_func=view_func,
methods=['GET', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'])
|
[
"def",
"register_resource",
"(",
"mod",
",",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_name",
"=",
"view",
".",
"__name__",
".",
"lower",
"(",
")",
"[",
":",
"-",
"8",
"]",
"endpoint",
"=",
"kwargs",
".",
"get",
"(",
"'endpoint'",
",",
"\"{}_api\"",
".",
"format",
"(",
"resource_name",
")",
")",
"plural_resource_name",
"=",
"inflect",
".",
"engine",
"(",
")",
".",
"plural",
"(",
"resource_name",
")",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
",",
"plural_resource_name",
")",
".",
"strip",
"(",
"'/'",
")",
"url",
"=",
"'/{}'",
".",
"format",
"(",
"path",
")",
"setattr",
"(",
"view",
",",
"'_url'",
",",
"url",
")",
"# need this for 201 location header",
"view_func",
"=",
"view",
".",
"as_view",
"(",
"endpoint",
")",
"mod",
".",
"add_url_rule",
"(",
"url",
",",
"view_func",
"=",
"view_func",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
",",
"'OPTIONS'",
"]",
")",
"mod",
".",
"add_url_rule",
"(",
"'{}/<obj_id>'",
".",
"format",
"(",
"url",
")",
",",
"view_func",
"=",
"view_func",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'PATCH'",
",",
"'PUT'",
",",
"'DELETE'",
",",
"'OPTIONS'",
"]",
")"
] |
Register the resource on the resource name or a custom url
|
[
"Register",
"the",
"resource",
"on",
"the",
"resource",
"name",
"or",
"a",
"custom",
"url"
] |
bf1fd1e58224c19883f4b19c5f727f47ee9857da
|
https://github.com/gevious/flask_slither/blob/bf1fd1e58224c19883f4b19c5f727f47ee9857da/flask_slither/__init__.py#L17-L31
|
239,012
|
uw-it-aca/uw-restclients-catalyst
|
uw_catalyst/gradebook.py
|
get_participants_for_gradebook
|
def get_participants_for_gradebook(gradebook_id, person=None):
"""
Returns a list of gradebook participants for the passed gradebook_id and
person.
"""
if not valid_gradebook_id(gradebook_id):
raise InvalidGradebookID(gradebook_id)
url = "/rest/gradebook/v1/book/{}/participants".format(gradebook_id)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["participants"]:
participants.append(_participant_from_json(pt))
return participants
|
python
|
def get_participants_for_gradebook(gradebook_id, person=None):
"""
Returns a list of gradebook participants for the passed gradebook_id and
person.
"""
if not valid_gradebook_id(gradebook_id):
raise InvalidGradebookID(gradebook_id)
url = "/rest/gradebook/v1/book/{}/participants".format(gradebook_id)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["participants"]:
participants.append(_participant_from_json(pt))
return participants
|
[
"def",
"get_participants_for_gradebook",
"(",
"gradebook_id",
",",
"person",
"=",
"None",
")",
":",
"if",
"not",
"valid_gradebook_id",
"(",
"gradebook_id",
")",
":",
"raise",
"InvalidGradebookID",
"(",
"gradebook_id",
")",
"url",
"=",
"\"/rest/gradebook/v1/book/{}/participants\"",
".",
"format",
"(",
"gradebook_id",
")",
"headers",
"=",
"{",
"}",
"if",
"person",
"is",
"not",
"None",
":",
"headers",
"[",
"\"X-UW-Act-as\"",
"]",
"=",
"person",
".",
"uwnetid",
"data",
"=",
"get_resource",
"(",
"url",
",",
"headers",
")",
"participants",
"=",
"[",
"]",
"for",
"pt",
"in",
"data",
"[",
"\"participants\"",
"]",
":",
"participants",
".",
"append",
"(",
"_participant_from_json",
"(",
"pt",
")",
")",
"return",
"participants"
] |
Returns a list of gradebook participants for the passed gradebook_id and
person.
|
[
"Returns",
"a",
"list",
"of",
"gradebook",
"participants",
"for",
"the",
"passed",
"gradebook_id",
"and",
"person",
"."
] |
17216e1e38d6da05eaed235e9329f62774626d80
|
https://github.com/uw-it-aca/uw-restclients-catalyst/blob/17216e1e38d6da05eaed235e9329f62774626d80/uw_catalyst/gradebook.py#L11-L31
|
239,013
|
uw-it-aca/uw-restclients-catalyst
|
uw_catalyst/gradebook.py
|
get_participants_for_section
|
def get_participants_for_section(section, person=None):
"""
Returns a list of gradebook participants for the passed section and person.
"""
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["participants"]:
participants.append(_participant_from_json(pt))
return participants
|
python
|
def get_participants_for_section(section, person=None):
"""
Returns a list of gradebook participants for the passed section and person.
"""
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["participants"]:
participants.append(_participant_from_json(pt))
return participants
|
[
"def",
"get_participants_for_section",
"(",
"section",
",",
"person",
"=",
"None",
")",
":",
"section_label",
"=",
"encode_section_label",
"(",
"section",
".",
"section_label",
"(",
")",
")",
"url",
"=",
"\"/rest/gradebook/v1/section/{}/participants\"",
".",
"format",
"(",
"section_label",
")",
"headers",
"=",
"{",
"}",
"if",
"person",
"is",
"not",
"None",
":",
"headers",
"[",
"\"X-UW-Act-as\"",
"]",
"=",
"person",
".",
"uwnetid",
"data",
"=",
"get_resource",
"(",
"url",
",",
"headers",
")",
"participants",
"=",
"[",
"]",
"for",
"pt",
"in",
"data",
"[",
"\"participants\"",
"]",
":",
"participants",
".",
"append",
"(",
"_participant_from_json",
"(",
"pt",
")",
")",
"return",
"participants"
] |
Returns a list of gradebook participants for the passed section and person.
|
[
"Returns",
"a",
"list",
"of",
"gradebook",
"participants",
"for",
"the",
"passed",
"section",
"and",
"person",
"."
] |
17216e1e38d6da05eaed235e9329f62774626d80
|
https://github.com/uw-it-aca/uw-restclients-catalyst/blob/17216e1e38d6da05eaed235e9329f62774626d80/uw_catalyst/gradebook.py#L34-L51
|
239,014
|
palankai/pyrs-schema
|
pyrs/schema/types.py
|
Object.to_python
|
def to_python(self, value, context=None):
"""Convert the value to a real python object"""
value = value.copy()
res = {}
errors = []
for field, schema in self._fields.items():
name = schema.get_attr('name', field)
if name in value:
try:
res[field] = schema.to_python(
value.pop(name),
context=context
)
except exceptions.ValidationErrors as ex:
self._update_errors_by_exception(errors, ex, name)
self._raise_exception_when_errors(errors, value)
res.update(value)
return res
|
python
|
def to_python(self, value, context=None):
"""Convert the value to a real python object"""
value = value.copy()
res = {}
errors = []
for field, schema in self._fields.items():
name = schema.get_attr('name', field)
if name in value:
try:
res[field] = schema.to_python(
value.pop(name),
context=context
)
except exceptions.ValidationErrors as ex:
self._update_errors_by_exception(errors, ex, name)
self._raise_exception_when_errors(errors, value)
res.update(value)
return res
|
[
"def",
"to_python",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"value",
".",
"copy",
"(",
")",
"res",
"=",
"{",
"}",
"errors",
"=",
"[",
"]",
"for",
"field",
",",
"schema",
"in",
"self",
".",
"_fields",
".",
"items",
"(",
")",
":",
"name",
"=",
"schema",
".",
"get_attr",
"(",
"'name'",
",",
"field",
")",
"if",
"name",
"in",
"value",
":",
"try",
":",
"res",
"[",
"field",
"]",
"=",
"schema",
".",
"to_python",
"(",
"value",
".",
"pop",
"(",
"name",
")",
",",
"context",
"=",
"context",
")",
"except",
"exceptions",
".",
"ValidationErrors",
"as",
"ex",
":",
"self",
".",
"_update_errors_by_exception",
"(",
"errors",
",",
"ex",
",",
"name",
")",
"self",
".",
"_raise_exception_when_errors",
"(",
"errors",
",",
"value",
")",
"res",
".",
"update",
"(",
"value",
")",
"return",
"res"
] |
Convert the value to a real python object
|
[
"Convert",
"the",
"value",
"to",
"a",
"real",
"python",
"object"
] |
6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f
|
https://github.com/palankai/pyrs-schema/blob/6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f/pyrs/schema/types.py#L297-L314
|
239,015
|
palankai/pyrs-schema
|
pyrs/schema/types.py
|
Object.to_raw
|
def to_raw(self, value, context=None):
"""Convert the value to a JSON compatible value"""
if value is None:
return None
res = {}
value = value.copy()
errors = []
for field in list(set(value) & set(self._fields)):
schema = self._fields.get(field)
name = schema.get_attr('name', field)
try:
res[name] = \
schema.to_raw(value.pop(field), context=context)
except exceptions.ValidationErrors as ex:
self._update_errors_by_exception(errors, ex, name)
self._raise_exception_when_errors(errors, value)
res.update(value)
return res
|
python
|
def to_raw(self, value, context=None):
"""Convert the value to a JSON compatible value"""
if value is None:
return None
res = {}
value = value.copy()
errors = []
for field in list(set(value) & set(self._fields)):
schema = self._fields.get(field)
name = schema.get_attr('name', field)
try:
res[name] = \
schema.to_raw(value.pop(field), context=context)
except exceptions.ValidationErrors as ex:
self._update_errors_by_exception(errors, ex, name)
self._raise_exception_when_errors(errors, value)
res.update(value)
return res
|
[
"def",
"to_raw",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"res",
"=",
"{",
"}",
"value",
"=",
"value",
".",
"copy",
"(",
")",
"errors",
"=",
"[",
"]",
"for",
"field",
"in",
"list",
"(",
"set",
"(",
"value",
")",
"&",
"set",
"(",
"self",
".",
"_fields",
")",
")",
":",
"schema",
"=",
"self",
".",
"_fields",
".",
"get",
"(",
"field",
")",
"name",
"=",
"schema",
".",
"get_attr",
"(",
"'name'",
",",
"field",
")",
"try",
":",
"res",
"[",
"name",
"]",
"=",
"schema",
".",
"to_raw",
"(",
"value",
".",
"pop",
"(",
"field",
")",
",",
"context",
"=",
"context",
")",
"except",
"exceptions",
".",
"ValidationErrors",
"as",
"ex",
":",
"self",
".",
"_update_errors_by_exception",
"(",
"errors",
",",
"ex",
",",
"name",
")",
"self",
".",
"_raise_exception_when_errors",
"(",
"errors",
",",
"value",
")",
"res",
".",
"update",
"(",
"value",
")",
"return",
"res"
] |
Convert the value to a JSON compatible value
|
[
"Convert",
"the",
"value",
"to",
"a",
"JSON",
"compatible",
"value"
] |
6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f
|
https://github.com/palankai/pyrs-schema/blob/6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f/pyrs/schema/types.py#L316-L334
|
239,016
|
palankai/pyrs-schema
|
pyrs/schema/types.py
|
Enum.get_jsonschema
|
def get_jsonschema(self, context=None):
"""Ensure the generic schema, remove `types`
:return: Gives back the schema
:rtype: dict
"""
schema = super(Enum, self).get_jsonschema(context=None)
schema.pop('type')
if self.get_attr('enum'):
schema['enum'] = self.get_attr('enum')
return schema
|
python
|
def get_jsonschema(self, context=None):
"""Ensure the generic schema, remove `types`
:return: Gives back the schema
:rtype: dict
"""
schema = super(Enum, self).get_jsonschema(context=None)
schema.pop('type')
if self.get_attr('enum'):
schema['enum'] = self.get_attr('enum')
return schema
|
[
"def",
"get_jsonschema",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"schema",
"=",
"super",
"(",
"Enum",
",",
"self",
")",
".",
"get_jsonschema",
"(",
"context",
"=",
"None",
")",
"schema",
".",
"pop",
"(",
"'type'",
")",
"if",
"self",
".",
"get_attr",
"(",
"'enum'",
")",
":",
"schema",
"[",
"'enum'",
"]",
"=",
"self",
".",
"get_attr",
"(",
"'enum'",
")",
"return",
"schema"
] |
Ensure the generic schema, remove `types`
:return: Gives back the schema
:rtype: dict
|
[
"Ensure",
"the",
"generic",
"schema",
"remove",
"types"
] |
6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f
|
https://github.com/palankai/pyrs-schema/blob/6bcde02e74d8fc3fa889f00f8e661e6d6af24a4f/pyrs/schema/types.py#L511-L521
|
239,017
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/refer/Referencer.py
|
Referencer.set_references
|
def set_references(references, components):
"""
Sets references to multiple components.
To set references components must implement [[IReferenceable]] interface.
If they don't the call to this method has no effect.
:param references: the references to be set.
:param components: a list of components to set the references to.
"""
if components == None:
return
for component in components:
Referencer.set_references_for_one(references, component)
|
python
|
def set_references(references, components):
"""
Sets references to multiple components.
To set references components must implement [[IReferenceable]] interface.
If they don't the call to this method has no effect.
:param references: the references to be set.
:param components: a list of components to set the references to.
"""
if components == None:
return
for component in components:
Referencer.set_references_for_one(references, component)
|
[
"def",
"set_references",
"(",
"references",
",",
"components",
")",
":",
"if",
"components",
"==",
"None",
":",
"return",
"for",
"component",
"in",
"components",
":",
"Referencer",
".",
"set_references_for_one",
"(",
"references",
",",
"component",
")"
] |
Sets references to multiple components.
To set references components must implement [[IReferenceable]] interface.
If they don't the call to this method has no effect.
:param references: the references to be set.
:param components: a list of components to set the references to.
|
[
"Sets",
"references",
"to",
"multiple",
"components",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/Referencer.py#L36-L51
|
239,018
|
FlaskGuys/Flask-Imagine
|
flask_imagine/filters/watermark.py
|
WatermarkFilter._reduce_opacity
|
def _reduce_opacity(self):
"""
Reduce opacity for watermark image.
"""
if self.image.mode != 'RGBA':
image = self.image.convert('RGBA')
else:
image = self.image.copy()
alpha = image.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity)
image.putalpha(alpha)
self.image = image
|
python
|
def _reduce_opacity(self):
"""
Reduce opacity for watermark image.
"""
if self.image.mode != 'RGBA':
image = self.image.convert('RGBA')
else:
image = self.image.copy()
alpha = image.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity)
image.putalpha(alpha)
self.image = image
|
[
"def",
"_reduce_opacity",
"(",
"self",
")",
":",
"if",
"self",
".",
"image",
".",
"mode",
"!=",
"'RGBA'",
":",
"image",
"=",
"self",
".",
"image",
".",
"convert",
"(",
"'RGBA'",
")",
"else",
":",
"image",
"=",
"self",
".",
"image",
".",
"copy",
"(",
")",
"alpha",
"=",
"image",
".",
"split",
"(",
")",
"[",
"3",
"]",
"alpha",
"=",
"ImageEnhance",
".",
"Brightness",
"(",
"alpha",
")",
".",
"enhance",
"(",
"self",
".",
"opacity",
")",
"image",
".",
"putalpha",
"(",
"alpha",
")",
"self",
".",
"image",
"=",
"image"
] |
Reduce opacity for watermark image.
|
[
"Reduce",
"opacity",
"for",
"watermark",
"image",
"."
] |
f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c
|
https://github.com/FlaskGuys/Flask-Imagine/blob/f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c/flask_imagine/filters/watermark.py#L210-L223
|
239,019
|
klmitch/policies
|
policies/rules.py
|
Rule.instructions
|
def instructions(self):
"""
Retrieve the instructions for the rule.
"""
if self._instructions is None:
# Compile the rule into an Instructions instance; we do
# this lazily to amortize the cost of the compilation,
# then cache that result for efficiency...
self._instructions = parser.parse_rule(self.name, self.text)
return self._instructions
|
python
|
def instructions(self):
"""
Retrieve the instructions for the rule.
"""
if self._instructions is None:
# Compile the rule into an Instructions instance; we do
# this lazily to amortize the cost of the compilation,
# then cache that result for efficiency...
self._instructions = parser.parse_rule(self.name, self.text)
return self._instructions
|
[
"def",
"instructions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instructions",
"is",
"None",
":",
"# Compile the rule into an Instructions instance; we do",
"# this lazily to amortize the cost of the compilation,",
"# then cache that result for efficiency...",
"self",
".",
"_instructions",
"=",
"parser",
".",
"parse_rule",
"(",
"self",
".",
"name",
",",
"self",
".",
"text",
")",
"return",
"self",
".",
"_instructions"
] |
Retrieve the instructions for the rule.
|
[
"Retrieve",
"the",
"instructions",
"for",
"the",
"rule",
"."
] |
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
|
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/rules.py#L53-L64
|
239,020
|
gnullByte/dotcolors
|
dotcolors/getdots.py
|
get_pages
|
def get_pages():
'''returns list of urllib file objects'''
pages =[]
counter = 1
print "Checking for themes..."
while(True):
page = urllib.urlopen('http://dotshare.it/category/terms/colors/p/%d/' % counter)
print "Page%d: %s" % (counter, "OK" if (page.code < 400) else "Fail!")
if page.code >= 400:
break
pages.append(page)
counter += 1
print "Found %d pages." % (counter - 1)
return pages
|
python
|
def get_pages():
'''returns list of urllib file objects'''
pages =[]
counter = 1
print "Checking for themes..."
while(True):
page = urllib.urlopen('http://dotshare.it/category/terms/colors/p/%d/' % counter)
print "Page%d: %s" % (counter, "OK" if (page.code < 400) else "Fail!")
if page.code >= 400:
break
pages.append(page)
counter += 1
print "Found %d pages." % (counter - 1)
return pages
|
[
"def",
"get_pages",
"(",
")",
":",
"pages",
"=",
"[",
"]",
"counter",
"=",
"1",
"print",
"\"Checking for themes...\"",
"while",
"(",
"True",
")",
":",
"page",
"=",
"urllib",
".",
"urlopen",
"(",
"'http://dotshare.it/category/terms/colors/p/%d/'",
"%",
"counter",
")",
"print",
"\"Page%d: %s\"",
"%",
"(",
"counter",
",",
"\"OK\"",
"if",
"(",
"page",
".",
"code",
"<",
"400",
")",
"else",
"\"Fail!\"",
")",
"if",
"page",
".",
"code",
">=",
"400",
":",
"break",
"pages",
".",
"append",
"(",
"page",
")",
"counter",
"+=",
"1",
"print",
"\"Found %d pages.\"",
"%",
"(",
"counter",
"-",
"1",
")",
"return",
"pages"
] |
returns list of urllib file objects
|
[
"returns",
"list",
"of",
"urllib",
"file",
"objects"
] |
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
|
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/getdots.py#L23-L39
|
239,021
|
gnullByte/dotcolors
|
dotcolors/getdots.py
|
get_urls
|
def get_urls(htmlDoc, limit=200):
'''takes in html document as string, returns links to dots'''
soup = BeautifulSoup( htmlDoc )
anchors = soup.findAll( 'a' )
urls = {}
counter = 0
for i,v in enumerate( anchors ):
href = anchors[i].get( 'href' )
if ('dots' in href and counter < limit):
href = href.split('/')[2]
text = anchors[i].text.split(' ')[0].replace('/', '_')
urls[ text ] = href
counter += 1
return urls
|
python
|
def get_urls(htmlDoc, limit=200):
'''takes in html document as string, returns links to dots'''
soup = BeautifulSoup( htmlDoc )
anchors = soup.findAll( 'a' )
urls = {}
counter = 0
for i,v in enumerate( anchors ):
href = anchors[i].get( 'href' )
if ('dots' in href and counter < limit):
href = href.split('/')[2]
text = anchors[i].text.split(' ')[0].replace('/', '_')
urls[ text ] = href
counter += 1
return urls
|
[
"def",
"get_urls",
"(",
"htmlDoc",
",",
"limit",
"=",
"200",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"htmlDoc",
")",
"anchors",
"=",
"soup",
".",
"findAll",
"(",
"'a'",
")",
"urls",
"=",
"{",
"}",
"counter",
"=",
"0",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"anchors",
")",
":",
"href",
"=",
"anchors",
"[",
"i",
"]",
".",
"get",
"(",
"'href'",
")",
"if",
"(",
"'dots'",
"in",
"href",
"and",
"counter",
"<",
"limit",
")",
":",
"href",
"=",
"href",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"text",
"=",
"anchors",
"[",
"i",
"]",
".",
"text",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"urls",
"[",
"text",
"]",
"=",
"href",
"counter",
"+=",
"1",
"return",
"urls"
] |
takes in html document as string, returns links to dots
|
[
"takes",
"in",
"html",
"document",
"as",
"string",
"returns",
"links",
"to",
"dots"
] |
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
|
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/getdots.py#L42-L59
|
239,022
|
gnullByte/dotcolors
|
dotcolors/getdots.py
|
get_themes
|
def get_themes(urls):
'''takes in dict of names and urls, downloads and saves files'''
length = len(urls)
counter = 1
widgets = ['Fetching themes:', Percentage(), ' ',
Bar(marker='-'), ' ', ETA()]
pbar = ProgressBar( widgets=widgets, maxval=length ).start()
for i in urls.keys():
href = 'http://dotshare.it/dots/%s/0/raw/' % urls[i]
theme = urllib.urlopen(href).read()
f = open(THEMEDIR + i, 'w')
f.write(theme)
f.close()
pbar.update(counter)
counter += 1
pbar.finish()
|
python
|
def get_themes(urls):
'''takes in dict of names and urls, downloads and saves files'''
length = len(urls)
counter = 1
widgets = ['Fetching themes:', Percentage(), ' ',
Bar(marker='-'), ' ', ETA()]
pbar = ProgressBar( widgets=widgets, maxval=length ).start()
for i in urls.keys():
href = 'http://dotshare.it/dots/%s/0/raw/' % urls[i]
theme = urllib.urlopen(href).read()
f = open(THEMEDIR + i, 'w')
f.write(theme)
f.close()
pbar.update(counter)
counter += 1
pbar.finish()
|
[
"def",
"get_themes",
"(",
"urls",
")",
":",
"length",
"=",
"len",
"(",
"urls",
")",
"counter",
"=",
"1",
"widgets",
"=",
"[",
"'Fetching themes:'",
",",
"Percentage",
"(",
")",
",",
"' '",
",",
"Bar",
"(",
"marker",
"=",
"'-'",
")",
",",
"' '",
",",
"ETA",
"(",
")",
"]",
"pbar",
"=",
"ProgressBar",
"(",
"widgets",
"=",
"widgets",
",",
"maxval",
"=",
"length",
")",
".",
"start",
"(",
")",
"for",
"i",
"in",
"urls",
".",
"keys",
"(",
")",
":",
"href",
"=",
"'http://dotshare.it/dots/%s/0/raw/'",
"%",
"urls",
"[",
"i",
"]",
"theme",
"=",
"urllib",
".",
"urlopen",
"(",
"href",
")",
".",
"read",
"(",
")",
"f",
"=",
"open",
"(",
"THEMEDIR",
"+",
"i",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"theme",
")",
"f",
".",
"close",
"(",
")",
"pbar",
".",
"update",
"(",
"counter",
")",
"counter",
"+=",
"1",
"pbar",
".",
"finish",
"(",
")"
] |
takes in dict of names and urls, downloads and saves files
|
[
"takes",
"in",
"dict",
"of",
"names",
"and",
"urls",
"downloads",
"and",
"saves",
"files"
] |
4b09ff9862b88b3125fe9cd86aa054694ed3e46e
|
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/getdots.py#L62-L81
|
239,023
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
get_section_path
|
def get_section_path(section):
"""Return a list with keys to access the section from root
:param section: A Section
:type section: Section
:returns: list of strings in the order to access the given section from root
:raises: None
"""
keys = []
p = section
for i in range(section.depth):
keys.insert(0, p.name)
p = p.parent
return keys
|
python
|
def get_section_path(section):
"""Return a list with keys to access the section from root
:param section: A Section
:type section: Section
:returns: list of strings in the order to access the given section from root
:raises: None
"""
keys = []
p = section
for i in range(section.depth):
keys.insert(0, p.name)
p = p.parent
return keys
|
[
"def",
"get_section_path",
"(",
"section",
")",
":",
"keys",
"=",
"[",
"]",
"p",
"=",
"section",
"for",
"i",
"in",
"range",
"(",
"section",
".",
"depth",
")",
":",
"keys",
".",
"insert",
"(",
"0",
",",
"p",
".",
"name",
")",
"p",
"=",
"p",
".",
"parent",
"return",
"keys"
] |
Return a list with keys to access the section from root
:param section: A Section
:type section: Section
:returns: list of strings in the order to access the given section from root
:raises: None
|
[
"Return",
"a",
"list",
"with",
"keys",
"to",
"access",
"the",
"section",
"from",
"root"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L29-L42
|
239,024
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
check_default_values
|
def check_default_values(section, key, validator=None):
"""Raise an MissingDefaultError if a value in section does not have a default values
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:param validator: a Validator object to get the default values
:type validator: Validator
:returns: None
:raises: MissingDefaultError
Use this in conjunction with the walk method of a ConfigObj.
The ConfigObj should be the configspec!
When you want to use a custom validator, try::
configinstance.walk(check_default_values, validator=validatorinstance)
"""
if validator is None:
validator = Validator()
try:
validator.get_default_value(section[key])
except KeyError:
#dv = set(section.default_values.keys()) # set of all defined default values
#scalars = set(section.scalars) # set of all keys
#if dv != scalars:
parents = get_section_path(section)
msg = 'The Key %s in the section %s is missing a default: %s' % (key, parents, section[key])
log.debug(msg)
raise ConfigError(msg)
|
python
|
def check_default_values(section, key, validator=None):
"""Raise an MissingDefaultError if a value in section does not have a default values
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:param validator: a Validator object to get the default values
:type validator: Validator
:returns: None
:raises: MissingDefaultError
Use this in conjunction with the walk method of a ConfigObj.
The ConfigObj should be the configspec!
When you want to use a custom validator, try::
configinstance.walk(check_default_values, validator=validatorinstance)
"""
if validator is None:
validator = Validator()
try:
validator.get_default_value(section[key])
except KeyError:
#dv = set(section.default_values.keys()) # set of all defined default values
#scalars = set(section.scalars) # set of all keys
#if dv != scalars:
parents = get_section_path(section)
msg = 'The Key %s in the section %s is missing a default: %s' % (key, parents, section[key])
log.debug(msg)
raise ConfigError(msg)
|
[
"def",
"check_default_values",
"(",
"section",
",",
"key",
",",
"validator",
"=",
"None",
")",
":",
"if",
"validator",
"is",
"None",
":",
"validator",
"=",
"Validator",
"(",
")",
"try",
":",
"validator",
".",
"get_default_value",
"(",
"section",
"[",
"key",
"]",
")",
"except",
"KeyError",
":",
"#dv = set(section.default_values.keys()) # set of all defined default values",
"#scalars = set(section.scalars) # set of all keys",
"#if dv != scalars:",
"parents",
"=",
"get_section_path",
"(",
"section",
")",
"msg",
"=",
"'The Key %s in the section %s is missing a default: %s'",
"%",
"(",
"key",
",",
"parents",
",",
"section",
"[",
"key",
"]",
")",
"log",
".",
"debug",
"(",
"msg",
")",
"raise",
"ConfigError",
"(",
"msg",
")"
] |
Raise an MissingDefaultError if a value in section does not have a default values
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:param validator: a Validator object to get the default values
:type validator: Validator
:returns: None
:raises: MissingDefaultError
Use this in conjunction with the walk method of a ConfigObj.
The ConfigObj should be the configspec!
When you want to use a custom validator, try::
configinstance.walk(check_default_values, validator=validatorinstance)
|
[
"Raise",
"an",
"MissingDefaultError",
"if",
"a",
"value",
"in",
"section",
"does",
"not",
"have",
"a",
"default",
"values"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L45-L75
|
239,025
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
fix_errors
|
def fix_errors(config, validation):
"""Replace errors with their default values
:param config: a validated ConfigObj to fix
:type config: ConfigObj
:param validation: the resuts of the validation
:type validation: ConfigObj
:returns: The altered config (does alter it in place though)
:raises: None
"""
for e in flatten_errors(config, validation):
sections, key, err = e
sec = config
for section in sections:
sec = sec[section]
if key is not None:
sec[key] = sec.default_values.get(key, sec[key])
else:
sec.walk(set_to_default)
return config
|
python
|
def fix_errors(config, validation):
"""Replace errors with their default values
:param config: a validated ConfigObj to fix
:type config: ConfigObj
:param validation: the resuts of the validation
:type validation: ConfigObj
:returns: The altered config (does alter it in place though)
:raises: None
"""
for e in flatten_errors(config, validation):
sections, key, err = e
sec = config
for section in sections:
sec = sec[section]
if key is not None:
sec[key] = sec.default_values.get(key, sec[key])
else:
sec.walk(set_to_default)
return config
|
[
"def",
"fix_errors",
"(",
"config",
",",
"validation",
")",
":",
"for",
"e",
"in",
"flatten_errors",
"(",
"config",
",",
"validation",
")",
":",
"sections",
",",
"key",
",",
"err",
"=",
"e",
"sec",
"=",
"config",
"for",
"section",
"in",
"sections",
":",
"sec",
"=",
"sec",
"[",
"section",
"]",
"if",
"key",
"is",
"not",
"None",
":",
"sec",
"[",
"key",
"]",
"=",
"sec",
".",
"default_values",
".",
"get",
"(",
"key",
",",
"sec",
"[",
"key",
"]",
")",
"else",
":",
"sec",
".",
"walk",
"(",
"set_to_default",
")",
"return",
"config"
] |
Replace errors with their default values
:param config: a validated ConfigObj to fix
:type config: ConfigObj
:param validation: the resuts of the validation
:type validation: ConfigObj
:returns: The altered config (does alter it in place though)
:raises: None
|
[
"Replace",
"errors",
"with",
"their",
"default",
"values"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L78-L97
|
239,026
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
set_to_default
|
def set_to_default(section, key):
"""Set the value of the given seciton and key to default
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:returns: None
:raises: None
"""
section[key] = section.default_values.get(key, section[key])
|
python
|
def set_to_default(section, key):
"""Set the value of the given seciton and key to default
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:returns: None
:raises: None
"""
section[key] = section.default_values.get(key, section[key])
|
[
"def",
"set_to_default",
"(",
"section",
",",
"key",
")",
":",
"section",
"[",
"key",
"]",
"=",
"section",
".",
"default_values",
".",
"get",
"(",
"key",
",",
"section",
"[",
"key",
"]",
")"
] |
Set the value of the given seciton and key to default
:param section: the section of a configspec
:type section: section
:param key: a key of the section
:type key: str
:returns: None
:raises: None
|
[
"Set",
"the",
"value",
"of",
"the",
"given",
"seciton",
"and",
"key",
"to",
"default"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L100-L110
|
239,027
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
clean_config
|
def clean_config(config):
"""Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All failed values will be replaced
by their default values. If default values are not specified in the spec, a
MissingDefaultError will be raised. If the replaced values still fail validation,
a ValueError is raised. This can occur if the default is of the wrong type.
If the object does not have a config spec, this function does nothing.
You are on your own then.
"""
if config.configspec is None:
return
vld = Validator()
validation = config.validate(vld, copy=True)
config.configspec.walk(check_default_values, validator=vld)
fix_errors(config, validation)
validation = config.validate(vld, copy=True)
if not (validation == True): # NOQA seems unpythonic but this validation evaluates that way only
msg = 'The config could not be fixed. Make sure that all default values have the right type!'
log.debug(msg)
raise ConfigError(msg)
|
python
|
def clean_config(config):
"""Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All failed values will be replaced
by their default values. If default values are not specified in the spec, a
MissingDefaultError will be raised. If the replaced values still fail validation,
a ValueError is raised. This can occur if the default is of the wrong type.
If the object does not have a config spec, this function does nothing.
You are on your own then.
"""
if config.configspec is None:
return
vld = Validator()
validation = config.validate(vld, copy=True)
config.configspec.walk(check_default_values, validator=vld)
fix_errors(config, validation)
validation = config.validate(vld, copy=True)
if not (validation == True): # NOQA seems unpythonic but this validation evaluates that way only
msg = 'The config could not be fixed. Make sure that all default values have the right type!'
log.debug(msg)
raise ConfigError(msg)
|
[
"def",
"clean_config",
"(",
"config",
")",
":",
"if",
"config",
".",
"configspec",
"is",
"None",
":",
"return",
"vld",
"=",
"Validator",
"(",
")",
"validation",
"=",
"config",
".",
"validate",
"(",
"vld",
",",
"copy",
"=",
"True",
")",
"config",
".",
"configspec",
".",
"walk",
"(",
"check_default_values",
",",
"validator",
"=",
"vld",
")",
"fix_errors",
"(",
"config",
",",
"validation",
")",
"validation",
"=",
"config",
".",
"validate",
"(",
"vld",
",",
"copy",
"=",
"True",
")",
"if",
"not",
"(",
"validation",
"==",
"True",
")",
":",
"# NOQA seems unpythonic but this validation evaluates that way only",
"msg",
"=",
"'The config could not be fixed. Make sure that all default values have the right type!'",
"log",
".",
"debug",
"(",
"msg",
")",
"raise",
"ConfigError",
"(",
"msg",
")"
] |
Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All failed values will be replaced
by their default values. If default values are not specified in the spec, a
MissingDefaultError will be raised. If the replaced values still fail validation,
a ValueError is raised. This can occur if the default is of the wrong type.
If the object does not have a config spec, this function does nothing.
You are on your own then.
|
[
"Check",
"if",
"all",
"values",
"have",
"defaults",
"and",
"replace",
"errors",
"with",
"their",
"default",
"value"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L113-L139
|
239,028
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/iniconf.py
|
load_config
|
def load_config(f, spec):
"""Return the ConfigObj for the specified file
:param f: the config file path
:type f: str
:param spec: the path to the configspec
:type spec: str
:returns: the loaded ConfigObj
:rtype: ConfigObj
:raises: ConfigError
"""
dirname = os.path.dirname(f)
if not os.path.exists(dirname):
os.makedirs(dirname)
c = ConfigObj(infile=f, configspec=spec,
interpolation=False, create_empty=True)
try:
clean_config(c)
except ConfigError, e:
msg = "Config %s could not be loaded. Reason: %s" % (c.filename, e)
log.debug(msg)
raise ConfigError(msg)
return c
|
python
|
def load_config(f, spec):
"""Return the ConfigObj for the specified file
:param f: the config file path
:type f: str
:param spec: the path to the configspec
:type spec: str
:returns: the loaded ConfigObj
:rtype: ConfigObj
:raises: ConfigError
"""
dirname = os.path.dirname(f)
if not os.path.exists(dirname):
os.makedirs(dirname)
c = ConfigObj(infile=f, configspec=spec,
interpolation=False, create_empty=True)
try:
clean_config(c)
except ConfigError, e:
msg = "Config %s could not be loaded. Reason: %s" % (c.filename, e)
log.debug(msg)
raise ConfigError(msg)
return c
|
[
"def",
"load_config",
"(",
"f",
",",
"spec",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"c",
"=",
"ConfigObj",
"(",
"infile",
"=",
"f",
",",
"configspec",
"=",
"spec",
",",
"interpolation",
"=",
"False",
",",
"create_empty",
"=",
"True",
")",
"try",
":",
"clean_config",
"(",
"c",
")",
"except",
"ConfigError",
",",
"e",
":",
"msg",
"=",
"\"Config %s could not be loaded. Reason: %s\"",
"%",
"(",
"c",
".",
"filename",
",",
"e",
")",
"log",
".",
"debug",
"(",
"msg",
")",
"raise",
"ConfigError",
"(",
"msg",
")",
"return",
"c"
] |
Return the ConfigObj for the specified file
:param f: the config file path
:type f: str
:param spec: the path to the configspec
:type spec: str
:returns: the loaded ConfigObj
:rtype: ConfigObj
:raises: ConfigError
|
[
"Return",
"the",
"ConfigObj",
"for",
"the",
"specified",
"file"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/iniconf.py#L142-L164
|
239,029
|
mapmyfitness/jtime
|
jtime/configuration.py
|
load_config
|
def load_config():
"""
Validate the config
"""
configuration = MyParser()
configuration.read(_config)
d = configuration.as_dict()
if 'jira' not in d:
raise custom_exceptions.NotConfigured
# Special handling of the boolean for error reporting
d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting')
return d
|
python
|
def load_config():
"""
Validate the config
"""
configuration = MyParser()
configuration.read(_config)
d = configuration.as_dict()
if 'jira' not in d:
raise custom_exceptions.NotConfigured
# Special handling of the boolean for error reporting
d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting')
return d
|
[
"def",
"load_config",
"(",
")",
":",
"configuration",
"=",
"MyParser",
"(",
")",
"configuration",
".",
"read",
"(",
"_config",
")",
"d",
"=",
"configuration",
".",
"as_dict",
"(",
")",
"if",
"'jira'",
"not",
"in",
"d",
":",
"raise",
"custom_exceptions",
".",
"NotConfigured",
"# Special handling of the boolean for error reporting",
"d",
"[",
"'jira'",
"]",
"[",
"'error_reporting'",
"]",
"=",
"configuration",
".",
"getboolean",
"(",
"'jira'",
",",
"'error_reporting'",
")",
"return",
"d"
] |
Validate the config
|
[
"Validate",
"the",
"config"
] |
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
|
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/configuration.py#L14-L29
|
239,030
|
mapmyfitness/jtime
|
jtime/configuration.py
|
_save_config
|
def _save_config(jira_url, username, password, error_reporting):
"""
Saves the username and password to the config
"""
# Delete what is there before we re-write. New user means new everything
os.path.exists(_config) and os.remove(_config)
config = ConfigParser.SafeConfigParser()
config.read(_config)
if not config.has_section('jira'):
config.add_section('jira')
if 'http' not in jira_url:
jira_url = 'http://' + jira_url
try:
resp = urllib.urlopen(jira_url)
url = urlparse.urlparse(resp.url)
jira_url = url.scheme + "://" + url.netloc
except IOError, e:
print "It doesn't appear that {0} is responding to a request.\
Please make sure that you typed the hostname, \
i.e. jira.atlassian.com.\n{1}".format(jira_url, e)
sys.exit(1)
config.set('jira', 'url', jira_url)
config.set('jira', 'username', username)
config.set('jira', 'password', base64.b64encode(password))
config.set('jira', 'error_reporting', str(error_reporting))
with open(_config, 'w') as ini:
os.chmod(_config, 0600)
config.write(ini)
|
python
|
def _save_config(jira_url, username, password, error_reporting):
"""
Saves the username and password to the config
"""
# Delete what is there before we re-write. New user means new everything
os.path.exists(_config) and os.remove(_config)
config = ConfigParser.SafeConfigParser()
config.read(_config)
if not config.has_section('jira'):
config.add_section('jira')
if 'http' not in jira_url:
jira_url = 'http://' + jira_url
try:
resp = urllib.urlopen(jira_url)
url = urlparse.urlparse(resp.url)
jira_url = url.scheme + "://" + url.netloc
except IOError, e:
print "It doesn't appear that {0} is responding to a request.\
Please make sure that you typed the hostname, \
i.e. jira.atlassian.com.\n{1}".format(jira_url, e)
sys.exit(1)
config.set('jira', 'url', jira_url)
config.set('jira', 'username', username)
config.set('jira', 'password', base64.b64encode(password))
config.set('jira', 'error_reporting', str(error_reporting))
with open(_config, 'w') as ini:
os.chmod(_config, 0600)
config.write(ini)
|
[
"def",
"_save_config",
"(",
"jira_url",
",",
"username",
",",
"password",
",",
"error_reporting",
")",
":",
"# Delete what is there before we re-write. New user means new everything",
"os",
".",
"path",
".",
"exists",
"(",
"_config",
")",
"and",
"os",
".",
"remove",
"(",
"_config",
")",
"config",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"_config",
")",
"if",
"not",
"config",
".",
"has_section",
"(",
"'jira'",
")",
":",
"config",
".",
"add_section",
"(",
"'jira'",
")",
"if",
"'http'",
"not",
"in",
"jira_url",
":",
"jira_url",
"=",
"'http://'",
"+",
"jira_url",
"try",
":",
"resp",
"=",
"urllib",
".",
"urlopen",
"(",
"jira_url",
")",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"resp",
".",
"url",
")",
"jira_url",
"=",
"url",
".",
"scheme",
"+",
"\"://\"",
"+",
"url",
".",
"netloc",
"except",
"IOError",
",",
"e",
":",
"print",
"\"It doesn't appear that {0} is responding to a request.\\\n Please make sure that you typed the hostname, \\\n i.e. jira.atlassian.com.\\n{1}\"",
".",
"format",
"(",
"jira_url",
",",
"e",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"config",
".",
"set",
"(",
"'jira'",
",",
"'url'",
",",
"jira_url",
")",
"config",
".",
"set",
"(",
"'jira'",
",",
"'username'",
",",
"username",
")",
"config",
".",
"set",
"(",
"'jira'",
",",
"'password'",
",",
"base64",
".",
"b64encode",
"(",
"password",
")",
")",
"config",
".",
"set",
"(",
"'jira'",
",",
"'error_reporting'",
",",
"str",
"(",
"error_reporting",
")",
")",
"with",
"open",
"(",
"_config",
",",
"'w'",
")",
"as",
"ini",
":",
"os",
".",
"chmod",
"(",
"_config",
",",
"0600",
")",
"config",
".",
"write",
"(",
"ini",
")"
] |
Saves the username and password to the config
|
[
"Saves",
"the",
"username",
"and",
"password",
"to",
"the",
"config"
] |
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
|
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/configuration.py#L36-L68
|
239,031
|
mapmyfitness/jtime
|
jtime/configuration.py
|
_get_cookies_as_dict
|
def _get_cookies_as_dict():
"""
Get cookies as a dict
"""
config = ConfigParser.SafeConfigParser()
config.read(_config)
if config.has_section('cookies'):
cookie_dict = {}
for option in config.options('cookies'):
option_key = option.upper() if option == 'jsessionid' else option
cookie_dict[option_key] = config.get('cookies', option)
return cookie_dict
|
python
|
def _get_cookies_as_dict():
"""
Get cookies as a dict
"""
config = ConfigParser.SafeConfigParser()
config.read(_config)
if config.has_section('cookies'):
cookie_dict = {}
for option in config.options('cookies'):
option_key = option.upper() if option == 'jsessionid' else option
cookie_dict[option_key] = config.get('cookies', option)
return cookie_dict
|
[
"def",
"_get_cookies_as_dict",
"(",
")",
":",
"config",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"_config",
")",
"if",
"config",
".",
"has_section",
"(",
"'cookies'",
")",
":",
"cookie_dict",
"=",
"{",
"}",
"for",
"option",
"in",
"config",
".",
"options",
"(",
"'cookies'",
")",
":",
"option_key",
"=",
"option",
".",
"upper",
"(",
")",
"if",
"option",
"==",
"'jsessionid'",
"else",
"option",
"cookie_dict",
"[",
"option_key",
"]",
"=",
"config",
".",
"get",
"(",
"'cookies'",
",",
"option",
")",
"return",
"cookie_dict"
] |
Get cookies as a dict
|
[
"Get",
"cookies",
"as",
"a",
"dict"
] |
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
|
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/configuration.py#L71-L84
|
239,032
|
karenc/db-migrator
|
dbmigrator/commands/__init__.py
|
load_cli
|
def load_cli(subparsers):
"""Given a parser, load the CLI subcommands"""
for command_name in available_commands():
module = '{}.{}'.format(__package__, command_name)
loader, description = _import_loader(module)
parser = subparsers.add_parser(command_name,
description=description)
command = loader(parser)
if command is None:
raise RuntimeError('Failed to load "{}".'.format(command_name))
parser.set_defaults(cmmd=command)
|
python
|
def load_cli(subparsers):
"""Given a parser, load the CLI subcommands"""
for command_name in available_commands():
module = '{}.{}'.format(__package__, command_name)
loader, description = _import_loader(module)
parser = subparsers.add_parser(command_name,
description=description)
command = loader(parser)
if command is None:
raise RuntimeError('Failed to load "{}".'.format(command_name))
parser.set_defaults(cmmd=command)
|
[
"def",
"load_cli",
"(",
"subparsers",
")",
":",
"for",
"command_name",
"in",
"available_commands",
"(",
")",
":",
"module",
"=",
"'{}.{}'",
".",
"format",
"(",
"__package__",
",",
"command_name",
")",
"loader",
",",
"description",
"=",
"_import_loader",
"(",
"module",
")",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"command_name",
",",
"description",
"=",
"description",
")",
"command",
"=",
"loader",
"(",
"parser",
")",
"if",
"command",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Failed to load \"{}\".'",
".",
"format",
"(",
"command_name",
")",
")",
"parser",
".",
"set_defaults",
"(",
"cmmd",
"=",
"command",
")"
] |
Given a parser, load the CLI subcommands
|
[
"Given",
"a",
"parser",
"load",
"the",
"CLI",
"subcommands"
] |
7a8e0e2f513539638a0371b609e2e89816ba0d36
|
https://github.com/karenc/db-migrator/blob/7a8e0e2f513539638a0371b609e2e89816ba0d36/dbmigrator/commands/__init__.py#L42-L52
|
239,033
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/commands/CommandSet.py
|
CommandSet._build_command_chain
|
def _build_command_chain(self, command):
"""
Builds execution chain including all intercepters and the specified command.
:param command: the command to build a chain.
"""
next = command
for intercepter in reversed(self._intercepters):
next = InterceptedCommand(intercepter, next)
self._commands_by_name[next.get_name()] = next
|
python
|
def _build_command_chain(self, command):
"""
Builds execution chain including all intercepters and the specified command.
:param command: the command to build a chain.
"""
next = command
for intercepter in reversed(self._intercepters):
next = InterceptedCommand(intercepter, next)
self._commands_by_name[next.get_name()] = next
|
[
"def",
"_build_command_chain",
"(",
"self",
",",
"command",
")",
":",
"next",
"=",
"command",
"for",
"intercepter",
"in",
"reversed",
"(",
"self",
".",
"_intercepters",
")",
":",
"next",
"=",
"InterceptedCommand",
"(",
"intercepter",
",",
"next",
")",
"self",
".",
"_commands_by_name",
"[",
"next",
".",
"get_name",
"(",
")",
"]",
"=",
"next"
] |
Builds execution chain including all intercepters and the specified command.
:param command: the command to build a chain.
|
[
"Builds",
"execution",
"chain",
"including",
"all",
"intercepters",
"and",
"the",
"specified",
"command",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/commands/CommandSet.py#L111-L120
|
239,034
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/commands/CommandSet.py
|
CommandSet.notify
|
def notify(self, correlation_id, event, value):
"""
Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be fired.
:param value: the event arguments (parameters).
"""
e = self.find_event(event)
if e != None:
e.notify(correlation_id, value)
|
python
|
def notify(self, correlation_id, event, value):
"""
Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be fired.
:param value: the event arguments (parameters).
"""
e = self.find_event(event)
if e != None:
e.notify(correlation_id, value)
|
[
"def",
"notify",
"(",
"self",
",",
"correlation_id",
",",
"event",
",",
"value",
")",
":",
"e",
"=",
"self",
".",
"find_event",
"(",
"event",
")",
"if",
"e",
"!=",
"None",
":",
"e",
".",
"notify",
"(",
"correlation_id",
",",
"value",
")"
] |
Fires event specified by its name and notifies all registered
IEventListener listeners
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param event: the name of the event that is to be fired.
:param value: the event arguments (parameters).
|
[
"Fires",
"event",
"specified",
"by",
"its",
"name",
"and",
"notifies",
"all",
"registered",
"IEventListener",
"listeners"
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/commands/CommandSet.py#L273-L286
|
239,035
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/convert/BooleanConverter.py
|
BooleanConverter.to_nullable_boolean
|
def to_nullable_boolean(value):
"""
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
"""
# Shortcuts
if value == None:
return None
if type(value) == type(True):
return value
str_value = str(value).lower()
# All true values
if str_value in ['1', 'true', 't', 'yes', 'y']:
return True
# All false values
if str_value in ['0', 'frue', 'f', 'no', 'n']:
return False
# Everything else:
return None
|
python
|
def to_nullable_boolean(value):
"""
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
"""
# Shortcuts
if value == None:
return None
if type(value) == type(True):
return value
str_value = str(value).lower()
# All true values
if str_value in ['1', 'true', 't', 'yes', 'y']:
return True
# All false values
if str_value in ['0', 'frue', 'f', 'no', 'n']:
return False
# Everything else:
return None
|
[
"def",
"to_nullable_boolean",
"(",
"value",
")",
":",
"# Shortcuts",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"if",
"type",
"(",
"value",
")",
"==",
"type",
"(",
"True",
")",
":",
"return",
"value",
"str_value",
"=",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"# All true values",
"if",
"str_value",
"in",
"[",
"'1'",
",",
"'true'",
",",
"'t'",
",",
"'yes'",
",",
"'y'",
"]",
":",
"return",
"True",
"# All false values",
"if",
"str_value",
"in",
"[",
"'0'",
",",
"'frue'",
",",
"'f'",
",",
"'no'",
",",
"'n'",
"]",
":",
"return",
"False",
"# Everything else:",
"return",
"None"
] |
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
|
[
"Converts",
"value",
"into",
"boolean",
"or",
"returns",
"None",
"when",
"conversion",
"is",
"not",
"possible",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/BooleanConverter.py#L26-L49
|
239,036
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/convert/BooleanConverter.py
|
BooleanConverter.to_boolean_with_default
|
def to_boolean_with_default(value, default_value):
"""
Converts value into boolean or returns default value when conversion is not possible
:param value: the value to convert.
:param default_value: the default value
:return: boolean value or default when conversion is not supported.
"""
result = BooleanConverter.to_nullable_boolean(value)
return result if result != None else default_value
|
python
|
def to_boolean_with_default(value, default_value):
"""
Converts value into boolean or returns default value when conversion is not possible
:param value: the value to convert.
:param default_value: the default value
:return: boolean value or default when conversion is not supported.
"""
result = BooleanConverter.to_nullable_boolean(value)
return result if result != None else default_value
|
[
"def",
"to_boolean_with_default",
"(",
"value",
",",
"default_value",
")",
":",
"result",
"=",
"BooleanConverter",
".",
"to_nullable_boolean",
"(",
"value",
")",
"return",
"result",
"if",
"result",
"!=",
"None",
"else",
"default_value"
] |
Converts value into boolean or returns default value when conversion is not possible
:param value: the value to convert.
:param default_value: the default value
:return: boolean value or default when conversion is not supported.
|
[
"Converts",
"value",
"into",
"boolean",
"or",
"returns",
"default",
"value",
"when",
"conversion",
"is",
"not",
"possible"
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/BooleanConverter.py#L63-L74
|
239,037
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.user_lists
|
def user_lists(self, username, member_type="USER"):
"""
Look up all the lists that the user is a member of.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
Returns:
list of strings: names of the lists that this user is a member of
"""
return self.client.service.getUserLists(username, member_type, self.proxy_id)
|
python
|
def user_lists(self, username, member_type="USER"):
"""
Look up all the lists that the user is a member of.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
Returns:
list of strings: names of the lists that this user is a member of
"""
return self.client.service.getUserLists(username, member_type, self.proxy_id)
|
[
"def",
"user_lists",
"(",
"self",
",",
"username",
",",
"member_type",
"=",
"\"USER\"",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"getUserLists",
"(",
"username",
",",
"member_type",
",",
"self",
".",
"proxy_id",
")"
] |
Look up all the lists that the user is a member of.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
Returns:
list of strings: names of the lists that this user is a member of
|
[
"Look",
"up",
"all",
"the",
"lists",
"that",
"the",
"user",
"is",
"a",
"member",
"of",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L36-L47
|
239,038
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.user_list_membership
|
def user_list_membership(self, username, member_type="USER",
recursive=True, max_return_count=999):
"""
Get info for lists a user is a member of.
This is similar to :meth:`user_lists` but with a few differences:
#. It returns list info objects instead of list names.
#. It has an option to fully resolve a user's list hierarchy. That
is, if a user is a member of a nested list, this method can
retrieve both the nested list and the parent lists that contain
the nested list.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
recursive(bool): Whether to fully resolve the list hierarchy
max_return_count(int): limit the number of items returned
Returns:
list of dicts: info dicts, one per list.
"""
return self.client.service.getUserListMembership(
username,
member_type,
recursive,
max_return_count,
self.proxy_id
)
|
python
|
def user_list_membership(self, username, member_type="USER",
recursive=True, max_return_count=999):
"""
Get info for lists a user is a member of.
This is similar to :meth:`user_lists` but with a few differences:
#. It returns list info objects instead of list names.
#. It has an option to fully resolve a user's list hierarchy. That
is, if a user is a member of a nested list, this method can
retrieve both the nested list and the parent lists that contain
the nested list.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
recursive(bool): Whether to fully resolve the list hierarchy
max_return_count(int): limit the number of items returned
Returns:
list of dicts: info dicts, one per list.
"""
return self.client.service.getUserListMembership(
username,
member_type,
recursive,
max_return_count,
self.proxy_id
)
|
[
"def",
"user_list_membership",
"(",
"self",
",",
"username",
",",
"member_type",
"=",
"\"USER\"",
",",
"recursive",
"=",
"True",
",",
"max_return_count",
"=",
"999",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"getUserListMembership",
"(",
"username",
",",
"member_type",
",",
"recursive",
",",
"max_return_count",
",",
"self",
".",
"proxy_id",
")"
] |
Get info for lists a user is a member of.
This is similar to :meth:`user_lists` but with a few differences:
#. It returns list info objects instead of list names.
#. It has an option to fully resolve a user's list hierarchy. That
is, if a user is a member of a nested list, this method can
retrieve both the nested list and the parent lists that contain
the nested list.
Args:
username (str): The MIT username of the user
member_type(str): The type of user, "USER" or "STRING"
recursive(bool): Whether to fully resolve the list hierarchy
max_return_count(int): limit the number of items returned
Returns:
list of dicts: info dicts, one per list.
|
[
"Get",
"info",
"for",
"lists",
"a",
"user",
"is",
"a",
"member",
"of",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L49-L77
|
239,039
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.list_members
|
def list_members(self, name, type="USER", recurse=True, max_results=1000):
"""
Look up all the members of a list.
Args:
name (str): The name of the list
type (str): The type of results to return. "USER" to get users,
"LIST" to get lists.
recurse (bool): Presumably, whether to recurse into member lists
when retrieving users.
max_results (int): Maximum number of results to return.
Returns:
list of strings: names of the members of the list
"""
results = self.client.service.getListMembership(
name, type, recurse, max_results, self.proxy_id,
)
return [item["member"] for item in results]
|
python
|
def list_members(self, name, type="USER", recurse=True, max_results=1000):
"""
Look up all the members of a list.
Args:
name (str): The name of the list
type (str): The type of results to return. "USER" to get users,
"LIST" to get lists.
recurse (bool): Presumably, whether to recurse into member lists
when retrieving users.
max_results (int): Maximum number of results to return.
Returns:
list of strings: names of the members of the list
"""
results = self.client.service.getListMembership(
name, type, recurse, max_results, self.proxy_id,
)
return [item["member"] for item in results]
|
[
"def",
"list_members",
"(",
"self",
",",
"name",
",",
"type",
"=",
"\"USER\"",
",",
"recurse",
"=",
"True",
",",
"max_results",
"=",
"1000",
")",
":",
"results",
"=",
"self",
".",
"client",
".",
"service",
".",
"getListMembership",
"(",
"name",
",",
"type",
",",
"recurse",
",",
"max_results",
",",
"self",
".",
"proxy_id",
",",
")",
"return",
"[",
"item",
"[",
"\"member\"",
"]",
"for",
"item",
"in",
"results",
"]"
] |
Look up all the members of a list.
Args:
name (str): The name of the list
type (str): The type of results to return. "USER" to get users,
"LIST" to get lists.
recurse (bool): Presumably, whether to recurse into member lists
when retrieving users.
max_results (int): Maximum number of results to return.
Returns:
list of strings: names of the members of the list
|
[
"Look",
"up",
"all",
"the",
"members",
"of",
"a",
"list",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L79-L97
|
239,040
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.list_attributes
|
def list_attributes(self, name):
"""
Look up the attributes of a list.
Args:
name (str): The name of the list
Returns:
dict: attributes of the list
"""
result = self.client.service.getListAttributes(name, self.proxy_id)
if isinstance(result, list) and len(result) == 1:
return result[0]
return result
|
python
|
def list_attributes(self, name):
"""
Look up the attributes of a list.
Args:
name (str): The name of the list
Returns:
dict: attributes of the list
"""
result = self.client.service.getListAttributes(name, self.proxy_id)
if isinstance(result, list) and len(result) == 1:
return result[0]
return result
|
[
"def",
"list_attributes",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"getListAttributes",
"(",
"name",
",",
"self",
".",
"proxy_id",
")",
"if",
"isinstance",
"(",
"result",
",",
"list",
")",
"and",
"len",
"(",
"result",
")",
"==",
"1",
":",
"return",
"result",
"[",
"0",
"]",
"return",
"result"
] |
Look up the attributes of a list.
Args:
name (str): The name of the list
Returns:
dict: attributes of the list
|
[
"Look",
"up",
"the",
"attributes",
"of",
"a",
"list",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L99-L112
|
239,041
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.add_member_to_list
|
def add_member_to_list(self, username, listname, member_type="USER"):
"""
Add a member to an existing list.
Args:
username (str): The username of the user to add
listname (str): The name of the list to add the user to
member_type (str): Normally, this should be "USER".
If you are adding a list as a member of another list,
set this to "LIST", instead.
"""
return self.client.service.addMemberToList(
listname, username, member_type, self.proxy_id
)
|
python
|
def add_member_to_list(self, username, listname, member_type="USER"):
"""
Add a member to an existing list.
Args:
username (str): The username of the user to add
listname (str): The name of the list to add the user to
member_type (str): Normally, this should be "USER".
If you are adding a list as a member of another list,
set this to "LIST", instead.
"""
return self.client.service.addMemberToList(
listname, username, member_type, self.proxy_id
)
|
[
"def",
"add_member_to_list",
"(",
"self",
",",
"username",
",",
"listname",
",",
"member_type",
"=",
"\"USER\"",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"addMemberToList",
"(",
"listname",
",",
"username",
",",
"member_type",
",",
"self",
".",
"proxy_id",
")"
] |
Add a member to an existing list.
Args:
username (str): The username of the user to add
listname (str): The name of the list to add the user to
member_type (str): Normally, this should be "USER".
If you are adding a list as a member of another list,
set this to "LIST", instead.
|
[
"Add",
"a",
"member",
"to",
"an",
"existing",
"list",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L126-L139
|
239,042
|
mitodl/mit-moira
|
mit_moira.py
|
Moira.create_list
|
def create_list(
self, name, description="Created by mit_moira client",
is_active=True, is_public=True, is_hidden=True,
is_group=False, is_nfs_group=False,
is_mail_list=False, use_mailman=False, mailman_server=""
):
"""
Create a new list.
Args:
name (str): The name of the new list
description (str): A short description of this list
is_active (bool): Should the new list be active?
An inactive list cannot be used.
is_public (bool): Should the new list be public?
If a list is public, anyone may join without requesting
permission. If not, the owners control entry to the list.
is_hidden (bool): Should the new list be hidden?
Presumably, a hidden list doesn't show up in search queries.
is_group (bool): Something about AFS?
is_nfs_group (bool): Presumably, create an
`NFS group <https://en.wikipedia.org/wiki/Network_File_System>`_
for this group? I don't actually know what this does.
is_mail_list (bool): Presumably, create a mailing list.
use_mailman (bool): Presumably, use
`GNU Mailman <https://en.wikipedia.org/wiki/GNU_Mailman>`_
to manage the mailing list.
mailman_server (str): The Mailman server to use, if ``use_mailman``
is True.
"""
attrs = {
"aceName": "mit_moira",
"aceType": "LIST",
"activeList": is_active,
"description": description,
"gid": "",
"group": is_group,
"hiddenList": is_hidden,
"listName": name,
"mailList": is_mail_list,
"mailman": use_mailman,
"mailmanServer": mailman_server,
"memaceName": "mit_moira",
"memaceType": "USER",
"modby": "",
"modtime": "",
"modwith": "",
"nfsgroup": is_nfs_group,
"publicList": is_public,
}
return self.client.service.createList(attrs, self.proxy_id)
|
python
|
def create_list(
self, name, description="Created by mit_moira client",
is_active=True, is_public=True, is_hidden=True,
is_group=False, is_nfs_group=False,
is_mail_list=False, use_mailman=False, mailman_server=""
):
"""
Create a new list.
Args:
name (str): The name of the new list
description (str): A short description of this list
is_active (bool): Should the new list be active?
An inactive list cannot be used.
is_public (bool): Should the new list be public?
If a list is public, anyone may join without requesting
permission. If not, the owners control entry to the list.
is_hidden (bool): Should the new list be hidden?
Presumably, a hidden list doesn't show up in search queries.
is_group (bool): Something about AFS?
is_nfs_group (bool): Presumably, create an
`NFS group <https://en.wikipedia.org/wiki/Network_File_System>`_
for this group? I don't actually know what this does.
is_mail_list (bool): Presumably, create a mailing list.
use_mailman (bool): Presumably, use
`GNU Mailman <https://en.wikipedia.org/wiki/GNU_Mailman>`_
to manage the mailing list.
mailman_server (str): The Mailman server to use, if ``use_mailman``
is True.
"""
attrs = {
"aceName": "mit_moira",
"aceType": "LIST",
"activeList": is_active,
"description": description,
"gid": "",
"group": is_group,
"hiddenList": is_hidden,
"listName": name,
"mailList": is_mail_list,
"mailman": use_mailman,
"mailmanServer": mailman_server,
"memaceName": "mit_moira",
"memaceType": "USER",
"modby": "",
"modtime": "",
"modwith": "",
"nfsgroup": is_nfs_group,
"publicList": is_public,
}
return self.client.service.createList(attrs, self.proxy_id)
|
[
"def",
"create_list",
"(",
"self",
",",
"name",
",",
"description",
"=",
"\"Created by mit_moira client\"",
",",
"is_active",
"=",
"True",
",",
"is_public",
"=",
"True",
",",
"is_hidden",
"=",
"True",
",",
"is_group",
"=",
"False",
",",
"is_nfs_group",
"=",
"False",
",",
"is_mail_list",
"=",
"False",
",",
"use_mailman",
"=",
"False",
",",
"mailman_server",
"=",
"\"\"",
")",
":",
"attrs",
"=",
"{",
"\"aceName\"",
":",
"\"mit_moira\"",
",",
"\"aceType\"",
":",
"\"LIST\"",
",",
"\"activeList\"",
":",
"is_active",
",",
"\"description\"",
":",
"description",
",",
"\"gid\"",
":",
"\"\"",
",",
"\"group\"",
":",
"is_group",
",",
"\"hiddenList\"",
":",
"is_hidden",
",",
"\"listName\"",
":",
"name",
",",
"\"mailList\"",
":",
"is_mail_list",
",",
"\"mailman\"",
":",
"use_mailman",
",",
"\"mailmanServer\"",
":",
"mailman_server",
",",
"\"memaceName\"",
":",
"\"mit_moira\"",
",",
"\"memaceType\"",
":",
"\"USER\"",
",",
"\"modby\"",
":",
"\"\"",
",",
"\"modtime\"",
":",
"\"\"",
",",
"\"modwith\"",
":",
"\"\"",
",",
"\"nfsgroup\"",
":",
"is_nfs_group",
",",
"\"publicList\"",
":",
"is_public",
",",
"}",
"return",
"self",
".",
"client",
".",
"service",
".",
"createList",
"(",
"attrs",
",",
"self",
".",
"proxy_id",
")"
] |
Create a new list.
Args:
name (str): The name of the new list
description (str): A short description of this list
is_active (bool): Should the new list be active?
An inactive list cannot be used.
is_public (bool): Should the new list be public?
If a list is public, anyone may join without requesting
permission. If not, the owners control entry to the list.
is_hidden (bool): Should the new list be hidden?
Presumably, a hidden list doesn't show up in search queries.
is_group (bool): Something about AFS?
is_nfs_group (bool): Presumably, create an
`NFS group <https://en.wikipedia.org/wiki/Network_File_System>`_
for this group? I don't actually know what this does.
is_mail_list (bool): Presumably, create a mailing list.
use_mailman (bool): Presumably, use
`GNU Mailman <https://en.wikipedia.org/wiki/GNU_Mailman>`_
to manage the mailing list.
mailman_server (str): The Mailman server to use, if ``use_mailman``
is True.
|
[
"Create",
"a",
"new",
"list",
"."
] |
0b73483f2bad49327b77a3eb94a4a9a602ef26ce
|
https://github.com/mitodl/mit-moira/blob/0b73483f2bad49327b77a3eb94a4a9a602ef26ce/mit_moira.py#L141-L191
|
239,043
|
roboogle/gtkmvc3
|
gtkmvco/examples/converter/src/models/currencies.py
|
CurrenciesModel.add
|
def add(self, model):
"""raises an exception if the model cannot be added"""
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
# checks if already existing
self.foreach(foo)
self.append((model,))
return
|
python
|
def add(self, model):
"""raises an exception if the model cannot be added"""
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
# checks if already existing
self.foreach(foo)
self.append((model,))
return
|
[
"def",
"add",
"(",
"self",
",",
"model",
")",
":",
"def",
"foo",
"(",
"m",
",",
"p",
",",
"i",
")",
":",
"if",
"m",
"[",
"i",
"]",
"[",
"0",
"]",
".",
"name",
"==",
"model",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"Model already exists\"",
")",
"return",
"# checks if already existing",
"self",
".",
"foreach",
"(",
"foo",
")",
"self",
".",
"append",
"(",
"(",
"model",
",",
")",
")",
"return"
] |
raises an exception if the model cannot be added
|
[
"raises",
"an",
"exception",
"if",
"the",
"model",
"cannot",
"be",
"added"
] |
63405fd8d2056be26af49103b13a8d5e57fe4dff
|
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/converter/src/models/currencies.py#L56-L66
|
239,044
|
sbarham/dsrt
|
build/lib/dsrt/data/transform/Vectorizer.py
|
Vectorizer.vectorize_dialogues
|
def vectorize_dialogues(self, dialogues):
"""
Take in a list of dialogues and vectorize them all
"""
return np.array([self.vectorize_dialogue(d) for d in dialogues])
|
python
|
def vectorize_dialogues(self, dialogues):
"""
Take in a list of dialogues and vectorize them all
"""
return np.array([self.vectorize_dialogue(d) for d in dialogues])
|
[
"def",
"vectorize_dialogues",
"(",
"self",
",",
"dialogues",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"vectorize_dialogue",
"(",
"d",
")",
"for",
"d",
"in",
"dialogues",
"]",
")"
] |
Take in a list of dialogues and vectorize them all
|
[
"Take",
"in",
"a",
"list",
"of",
"dialogues",
"and",
"vectorize",
"them",
"all"
] |
bc664739f2f52839461d3e72773b71146fd56a9a
|
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L71-L75
|
239,045
|
sbarham/dsrt
|
build/lib/dsrt/data/transform/Vectorizer.py
|
Vectorizer.devectorize_utterance
|
def devectorize_utterance(self, utterance):
"""
Take in a sequence of indices and transform it back into a tokenized utterance
"""
utterance = self.swap_pad_and_zero(utterance)
return self.ie.inverse_transform(utterance).tolist()
|
python
|
def devectorize_utterance(self, utterance):
"""
Take in a sequence of indices and transform it back into a tokenized utterance
"""
utterance = self.swap_pad_and_zero(utterance)
return self.ie.inverse_transform(utterance).tolist()
|
[
"def",
"devectorize_utterance",
"(",
"self",
",",
"utterance",
")",
":",
"utterance",
"=",
"self",
".",
"swap_pad_and_zero",
"(",
"utterance",
")",
"return",
"self",
".",
"ie",
".",
"inverse_transform",
"(",
"utterance",
")",
".",
"tolist",
"(",
")"
] |
Take in a sequence of indices and transform it back into a tokenized utterance
|
[
"Take",
"in",
"a",
"sequence",
"of",
"indices",
"and",
"transform",
"it",
"back",
"into",
"a",
"tokenized",
"utterance"
] |
bc664739f2f52839461d3e72773b71146fd56a9a
|
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L106-L111
|
239,046
|
sbarham/dsrt
|
build/lib/dsrt/data/transform/Vectorizer.py
|
Vectorizer.vectorize_batch_ohe
|
def vectorize_batch_ohe(self, batch):
"""
One-hot vectorize a whole batch of dialogues
"""
return np.array([self.vectorize_dialogue_ohe(dia) for dia in batch])
|
python
|
def vectorize_batch_ohe(self, batch):
"""
One-hot vectorize a whole batch of dialogues
"""
return np.array([self.vectorize_dialogue_ohe(dia) for dia in batch])
|
[
"def",
"vectorize_batch_ohe",
"(",
"self",
",",
"batch",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"vectorize_dialogue_ohe",
"(",
"dia",
")",
"for",
"dia",
"in",
"batch",
"]",
")"
] |
One-hot vectorize a whole batch of dialogues
|
[
"One",
"-",
"hot",
"vectorize",
"a",
"whole",
"batch",
"of",
"dialogues"
] |
bc664739f2f52839461d3e72773b71146fd56a9a
|
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L124-L128
|
239,047
|
sbarham/dsrt
|
build/lib/dsrt/data/transform/Vectorizer.py
|
Vectorizer.vectorize_utterance_ohe
|
def vectorize_utterance_ohe(self, utterance):
"""
Take in a tokenized utterance and transform it into a sequence of one-hot vectors
"""
for i, word in enumerate(utterance):
if not word in self.vocab_list:
utterance[i] = '<unk>'
ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance))
ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1)))
return ohe_utterance
|
python
|
def vectorize_utterance_ohe(self, utterance):
"""
Take in a tokenized utterance and transform it into a sequence of one-hot vectors
"""
for i, word in enumerate(utterance):
if not word in self.vocab_list:
utterance[i] = '<unk>'
ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance))
ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1)))
return ohe_utterance
|
[
"def",
"vectorize_utterance_ohe",
"(",
"self",
",",
"utterance",
")",
":",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"utterance",
")",
":",
"if",
"not",
"word",
"in",
"self",
".",
"vocab_list",
":",
"utterance",
"[",
"i",
"]",
"=",
"'<unk>'",
"ie_utterance",
"=",
"self",
".",
"swap_pad_and_zero",
"(",
"self",
".",
"ie",
".",
"transform",
"(",
"utterance",
")",
")",
"ohe_utterance",
"=",
"np",
".",
"array",
"(",
"self",
".",
"ohe",
".",
"transform",
"(",
"ie_utterance",
".",
"reshape",
"(",
"len",
"(",
"ie_utterance",
")",
",",
"1",
")",
")",
")",
"return",
"ohe_utterance"
] |
Take in a tokenized utterance and transform it into a sequence of one-hot vectors
|
[
"Take",
"in",
"a",
"tokenized",
"utterance",
"and",
"transform",
"it",
"into",
"a",
"sequence",
"of",
"one",
"-",
"hot",
"vectors"
] |
bc664739f2f52839461d3e72773b71146fd56a9a
|
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L139-L150
|
239,048
|
sbarham/dsrt
|
build/lib/dsrt/data/transform/Vectorizer.py
|
Vectorizer.devectorize_utterance_ohe
|
def devectorize_utterance_ohe(self, ohe_utterance):
"""
Take in a sequence of one-hot vectors and transform it into a tokenized utterance
"""
ie_utterance = [argmax(w) for w in ohe_utterance]
utterance = self.ie.inverse_transform(self.swap_pad_and_zero(ie_utterance))
return utterance
|
python
|
def devectorize_utterance_ohe(self, ohe_utterance):
"""
Take in a sequence of one-hot vectors and transform it into a tokenized utterance
"""
ie_utterance = [argmax(w) for w in ohe_utterance]
utterance = self.ie.inverse_transform(self.swap_pad_and_zero(ie_utterance))
return utterance
|
[
"def",
"devectorize_utterance_ohe",
"(",
"self",
",",
"ohe_utterance",
")",
":",
"ie_utterance",
"=",
"[",
"argmax",
"(",
"w",
")",
"for",
"w",
"in",
"ohe_utterance",
"]",
"utterance",
"=",
"self",
".",
"ie",
".",
"inverse_transform",
"(",
"self",
".",
"swap_pad_and_zero",
"(",
"ie_utterance",
")",
")",
"return",
"utterance"
] |
Take in a sequence of one-hot vectors and transform it into a tokenized utterance
|
[
"Take",
"in",
"a",
"sequence",
"of",
"one",
"-",
"hot",
"vectors",
"and",
"transform",
"it",
"into",
"a",
"tokenized",
"utterance"
] |
bc664739f2f52839461d3e72773b71146fd56a9a
|
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L158-L165
|
239,049
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/log.py
|
setup_jukebox_logger
|
def setup_jukebox_logger():
"""Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
:returns: None
:rtype: None
:raises: None
"""
log = logging.getLogger("jb")
log.propagate = False
handler = logging.StreamHandler(sys.stdout)
fmt = "%(levelname)-8s:%(name)s: %(message)s"
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
log.addHandler(handler)
level = DEFAULT_LOGGING_LEVEL
log.setLevel(level)
|
python
|
def setup_jukebox_logger():
"""Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
:returns: None
:rtype: None
:raises: None
"""
log = logging.getLogger("jb")
log.propagate = False
handler = logging.StreamHandler(sys.stdout)
fmt = "%(levelname)-8s:%(name)s: %(message)s"
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
log.addHandler(handler)
level = DEFAULT_LOGGING_LEVEL
log.setLevel(level)
|
[
"def",
"setup_jukebox_logger",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"jb\"",
")",
"log",
".",
"propagate",
"=",
"False",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"fmt",
"=",
"\"%(levelname)-8s:%(name)s: %(message)s\"",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"log",
".",
"addHandler",
"(",
"handler",
")",
"level",
"=",
"DEFAULT_LOGGING_LEVEL",
"log",
".",
"setLevel",
"(",
"level",
")"
] |
Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
:returns: None
:rtype: None
:raises: None
|
[
"Setup",
"the",
"jukebox",
"top",
"-",
"level",
"logger",
"with",
"handlers"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/log.py#L8-L28
|
239,050
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/log.py
|
get_logger
|
def get_logger(name, level=None):
""" Return a setup logger for the given name
:param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \"jb.\".
:type name: str
:param level: the logging level, e.g. logging.DEBUG, logging.INFO etc
:type level: int
:returns: Logger
:rtype: logging.Logger
:raises: None
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
"""
log = logging.getLogger("jb.%s" % name)
if level is not None:
log.setLevel(level)
return log
|
python
|
def get_logger(name, level=None):
""" Return a setup logger for the given name
:param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \"jb.\".
:type name: str
:param level: the logging level, e.g. logging.DEBUG, logging.INFO etc
:type level: int
:returns: Logger
:rtype: logging.Logger
:raises: None
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
"""
log = logging.getLogger("jb.%s" % name)
if level is not None:
log.setLevel(level)
return log
|
[
"def",
"get_logger",
"(",
"name",
",",
"level",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"jb.%s\"",
"%",
"name",
")",
"if",
"level",
"is",
"not",
"None",
":",
"log",
".",
"setLevel",
"(",
"level",
")",
"return",
"log"
] |
Return a setup logger for the given name
:param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \"jb.\".
:type name: str
:param level: the logging level, e.g. logging.DEBUG, logging.INFO etc
:type level: int
:returns: Logger
:rtype: logging.Logger
:raises: None
The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\"
|
[
"Return",
"a",
"setup",
"logger",
"for",
"the",
"given",
"name"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/log.py#L31-L48
|
239,051
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
parse_cartouche_text
|
def parse_cartouche_text(lines):
'''Parse text in cartouche format and return a reStructuredText equivalent
Args:
lines: A sequence of strings representing the lines of a single
docstring as read from the source by Sphinx. This string should be
in a format that can be parsed by cartouche.
Returns:
A list of lines containing the transformed docstring as
reStructuredText as produced by cartouche.
Raises:
RuntimeError: If the docstring cannot be parsed.
'''
indent_lines = unindent(lines)
indent_lines = pad_blank_lines(indent_lines)
indent_lines = first_paragraph_indent(indent_lines)
indent_paragraphs = gather_lines(indent_lines)
parse_tree = group_paragraphs(indent_paragraphs)
syntax_tree = extract_structure(parse_tree)
result = syntax_tree.render_rst()
ensure_terminal_blank(result)
return result
|
python
|
def parse_cartouche_text(lines):
'''Parse text in cartouche format and return a reStructuredText equivalent
Args:
lines: A sequence of strings representing the lines of a single
docstring as read from the source by Sphinx. This string should be
in a format that can be parsed by cartouche.
Returns:
A list of lines containing the transformed docstring as
reStructuredText as produced by cartouche.
Raises:
RuntimeError: If the docstring cannot be parsed.
'''
indent_lines = unindent(lines)
indent_lines = pad_blank_lines(indent_lines)
indent_lines = first_paragraph_indent(indent_lines)
indent_paragraphs = gather_lines(indent_lines)
parse_tree = group_paragraphs(indent_paragraphs)
syntax_tree = extract_structure(parse_tree)
result = syntax_tree.render_rst()
ensure_terminal_blank(result)
return result
|
[
"def",
"parse_cartouche_text",
"(",
"lines",
")",
":",
"indent_lines",
"=",
"unindent",
"(",
"lines",
")",
"indent_lines",
"=",
"pad_blank_lines",
"(",
"indent_lines",
")",
"indent_lines",
"=",
"first_paragraph_indent",
"(",
"indent_lines",
")",
"indent_paragraphs",
"=",
"gather_lines",
"(",
"indent_lines",
")",
"parse_tree",
"=",
"group_paragraphs",
"(",
"indent_paragraphs",
")",
"syntax_tree",
"=",
"extract_structure",
"(",
"parse_tree",
")",
"result",
"=",
"syntax_tree",
".",
"render_rst",
"(",
")",
"ensure_terminal_blank",
"(",
"result",
")",
"return",
"result"
] |
Parse text in cartouche format and return a reStructuredText equivalent
Args:
lines: A sequence of strings representing the lines of a single
docstring as read from the source by Sphinx. This string should be
in a format that can be parsed by cartouche.
Returns:
A list of lines containing the transformed docstring as
reStructuredText as produced by cartouche.
Raises:
RuntimeError: If the docstring cannot be parsed.
|
[
"Parse",
"text",
"in",
"cartouche",
"format",
"and",
"return",
"a",
"reStructuredText",
"equivalent"
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L25-L48
|
239,052
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
unindent
|
def unindent(lines):
'''Convert an iterable of indented lines into a sequence of tuples.
The first element of each tuple is the indent in number of characters, and
the second element is the unindented string.
Args:
lines: A sequence of strings representing the lines of text in a docstring.
Returns:
A list of tuples where each tuple corresponds to one line of the input
list. Each tuple has two entries - the first is an integer giving the
size of the indent in characters, the second is the unindented text.
'''
unindented_lines = []
for line in lines:
unindented_line = line.lstrip()
indent = len(line) - len(unindented_line)
unindented_lines.append((indent, unindented_line))
return unindented_lines
|
python
|
def unindent(lines):
'''Convert an iterable of indented lines into a sequence of tuples.
The first element of each tuple is the indent in number of characters, and
the second element is the unindented string.
Args:
lines: A sequence of strings representing the lines of text in a docstring.
Returns:
A list of tuples where each tuple corresponds to one line of the input
list. Each tuple has two entries - the first is an integer giving the
size of the indent in characters, the second is the unindented text.
'''
unindented_lines = []
for line in lines:
unindented_line = line.lstrip()
indent = len(line) - len(unindented_line)
unindented_lines.append((indent, unindented_line))
return unindented_lines
|
[
"def",
"unindent",
"(",
"lines",
")",
":",
"unindented_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"unindented_line",
"=",
"line",
".",
"lstrip",
"(",
")",
"indent",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"unindented_line",
")",
"unindented_lines",
".",
"append",
"(",
"(",
"indent",
",",
"unindented_line",
")",
")",
"return",
"unindented_lines"
] |
Convert an iterable of indented lines into a sequence of tuples.
The first element of each tuple is the indent in number of characters, and
the second element is the unindented string.
Args:
lines: A sequence of strings representing the lines of text in a docstring.
Returns:
A list of tuples where each tuple corresponds to one line of the input
list. Each tuple has two entries - the first is an integer giving the
size of the indent in characters, the second is the unindented text.
|
[
"Convert",
"an",
"iterable",
"of",
"indented",
"lines",
"into",
"a",
"sequence",
"of",
"tuples",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L51-L70
|
239,053
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
parse_exception
|
def parse_exception(line):
'''Parse the first line of a Cartouche exception description.
Args:
line (str): A single line Cartouche exception description.
Returns:
A 2-tuple containing the exception type and the first line of the description.
'''
m = RAISES_REGEX.match(line)
if m is None:
raise CartoucheSyntaxError('Cartouche: Invalid argument syntax "{line}" for Raises block'.format(line=line))
return m.group(2), m.group(1)
|
python
|
def parse_exception(line):
'''Parse the first line of a Cartouche exception description.
Args:
line (str): A single line Cartouche exception description.
Returns:
A 2-tuple containing the exception type and the first line of the description.
'''
m = RAISES_REGEX.match(line)
if m is None:
raise CartoucheSyntaxError('Cartouche: Invalid argument syntax "{line}" for Raises block'.format(line=line))
return m.group(2), m.group(1)
|
[
"def",
"parse_exception",
"(",
"line",
")",
":",
"m",
"=",
"RAISES_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"CartoucheSyntaxError",
"(",
"'Cartouche: Invalid argument syntax \"{line}\" for Raises block'",
".",
"format",
"(",
"line",
"=",
"line",
")",
")",
"return",
"m",
".",
"group",
"(",
"2",
")",
",",
"m",
".",
"group",
"(",
"1",
")"
] |
Parse the first line of a Cartouche exception description.
Args:
line (str): A single line Cartouche exception description.
Returns:
A 2-tuple containing the exception type and the first line of the description.
|
[
"Parse",
"the",
"first",
"line",
"of",
"a",
"Cartouche",
"exception",
"description",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L250-L262
|
239,054
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
group_paragraphs
|
def group_paragraphs(indent_paragraphs):
'''
Group paragraphs so that more indented paragraphs become children of less
indented paragraphs.
'''
# The tree consists of tuples of the form (indent, [children]) where the
# children may be strings or other tuples
root = Node(0, [], None)
current_node = root
previous_indent = -1
for indent, lines in indent_paragraphs:
if indent > previous_indent:
current_node = create_child_node(current_node, indent, lines)
elif indent == previous_indent:
current_node = create_sibling_node(current_node, indent, lines)
elif indent < previous_indent:
current_node = create_uncle_node(current_node, indent, lines)
previous_indent = indent
return root
|
python
|
def group_paragraphs(indent_paragraphs):
'''
Group paragraphs so that more indented paragraphs become children of less
indented paragraphs.
'''
# The tree consists of tuples of the form (indent, [children]) where the
# children may be strings or other tuples
root = Node(0, [], None)
current_node = root
previous_indent = -1
for indent, lines in indent_paragraphs:
if indent > previous_indent:
current_node = create_child_node(current_node, indent, lines)
elif indent == previous_indent:
current_node = create_sibling_node(current_node, indent, lines)
elif indent < previous_indent:
current_node = create_uncle_node(current_node, indent, lines)
previous_indent = indent
return root
|
[
"def",
"group_paragraphs",
"(",
"indent_paragraphs",
")",
":",
"# The tree consists of tuples of the form (indent, [children]) where the",
"# children may be strings or other tuples",
"root",
"=",
"Node",
"(",
"0",
",",
"[",
"]",
",",
"None",
")",
"current_node",
"=",
"root",
"previous_indent",
"=",
"-",
"1",
"for",
"indent",
",",
"lines",
"in",
"indent_paragraphs",
":",
"if",
"indent",
">",
"previous_indent",
":",
"current_node",
"=",
"create_child_node",
"(",
"current_node",
",",
"indent",
",",
"lines",
")",
"elif",
"indent",
"==",
"previous_indent",
":",
"current_node",
"=",
"create_sibling_node",
"(",
"current_node",
",",
"indent",
",",
"lines",
")",
"elif",
"indent",
"<",
"previous_indent",
":",
"current_node",
"=",
"create_uncle_node",
"(",
"current_node",
",",
"indent",
",",
"lines",
")",
"previous_indent",
"=",
"indent",
"return",
"root"
] |
Group paragraphs so that more indented paragraphs become children of less
indented paragraphs.
|
[
"Group",
"paragraphs",
"so",
"that",
"more",
"indented",
"paragraphs",
"become",
"children",
"of",
"less",
"indented",
"paragraphs",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L283-L303
|
239,055
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
first_paragraph_indent
|
def first_paragraph_indent(indent_texts):
'''Fix the indentation on the first paragraph.
This occurs because the first line of a multi-line docstring following the
opening quote usually has no indent.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Return:
A list of 2-tuples, each containing an integer indent level as the
first element and the text as the second element.
'''
opening_indent = determine_opening_indent(indent_texts)
result = []
input = iter(indent_texts)
for indent, text in input:
if indent == 0:
result.append((opening_indent, text))
else:
result.append((indent, text))
break
for indent, text in input:
result.append((indent, text))
return result
|
python
|
def first_paragraph_indent(indent_texts):
'''Fix the indentation on the first paragraph.
This occurs because the first line of a multi-line docstring following the
opening quote usually has no indent.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Return:
A list of 2-tuples, each containing an integer indent level as the
first element and the text as the second element.
'''
opening_indent = determine_opening_indent(indent_texts)
result = []
input = iter(indent_texts)
for indent, text in input:
if indent == 0:
result.append((opening_indent, text))
else:
result.append((indent, text))
break
for indent, text in input:
result.append((indent, text))
return result
|
[
"def",
"first_paragraph_indent",
"(",
"indent_texts",
")",
":",
"opening_indent",
"=",
"determine_opening_indent",
"(",
"indent_texts",
")",
"result",
"=",
"[",
"]",
"input",
"=",
"iter",
"(",
"indent_texts",
")",
"for",
"indent",
",",
"text",
"in",
"input",
":",
"if",
"indent",
"==",
"0",
":",
"result",
".",
"append",
"(",
"(",
"opening_indent",
",",
"text",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"(",
"indent",
",",
"text",
")",
")",
"break",
"for",
"indent",
",",
"text",
"in",
"input",
":",
"result",
".",
"append",
"(",
"(",
"indent",
",",
"text",
")",
")",
"return",
"result"
] |
Fix the indentation on the first paragraph.
This occurs because the first line of a multi-line docstring following the
opening quote usually has no indent.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Return:
A list of 2-tuples, each containing an integer indent level as the
first element and the text as the second element.
|
[
"Fix",
"the",
"indentation",
"on",
"the",
"first",
"paragraph",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L373-L402
|
239,056
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
determine_opening_indent
|
def determine_opening_indent(indent_texts):
'''Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Returns:
The opening indent level as an integer.
'''
num_lines = len(indent_texts)
if num_lines < 1:
return 0
assert num_lines >= 1
first_line_indent = indent_texts[0][0]
if num_lines == 1:
return first_line_indent
assert num_lines >= 2
second_line_indent = indent_texts[1][0]
second_line_text = indent_texts[1][1]
if len(second_line_text) == 0:
return first_line_indent
return second_line_indent
|
python
|
def determine_opening_indent(indent_texts):
'''Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Returns:
The opening indent level as an integer.
'''
num_lines = len(indent_texts)
if num_lines < 1:
return 0
assert num_lines >= 1
first_line_indent = indent_texts[0][0]
if num_lines == 1:
return first_line_indent
assert num_lines >= 2
second_line_indent = indent_texts[1][0]
second_line_text = indent_texts[1][1]
if len(second_line_text) == 0:
return first_line_indent
return second_line_indent
|
[
"def",
"determine_opening_indent",
"(",
"indent_texts",
")",
":",
"num_lines",
"=",
"len",
"(",
"indent_texts",
")",
"if",
"num_lines",
"<",
"1",
":",
"return",
"0",
"assert",
"num_lines",
">=",
"1",
"first_line_indent",
"=",
"indent_texts",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"num_lines",
"==",
"1",
":",
"return",
"first_line_indent",
"assert",
"num_lines",
">=",
"2",
"second_line_indent",
"=",
"indent_texts",
"[",
"1",
"]",
"[",
"0",
"]",
"second_line_text",
"=",
"indent_texts",
"[",
"1",
"]",
"[",
"1",
"]",
"if",
"len",
"(",
"second_line_text",
")",
"==",
"0",
":",
"return",
"first_line_indent",
"return",
"second_line_indent"
] |
Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the text as the second element.
Returns:
The opening indent level as an integer.
|
[
"Determine",
"the",
"opening",
"indent",
"level",
"for",
"a",
"docstring",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L405-L439
|
239,057
|
rob-smallshire/cartouche
|
cartouche/parser.py
|
rewrite_autodoc
|
def rewrite_autodoc(app, what, name, obj, options, lines):
'''Convert lines from Cartouche to Sphinx format.
The function to be called by the Sphinx autodoc extension when autodoc
has read and processed a docstring. This function modified its
``lines`` argument *in place* replacing Cartouche syntax input into
Sphinx reStructuredText output.
Args:
apps: The Sphinx application object.
what: The type of object which the docstring belongs to. One of
'module', 'class', 'exception', 'function', 'method', 'attribute'
name: The fully qualified name of the object.
obj: The object itself.
options: The options given to the directive. An object with attributes
``inherited_members``, ``undoc_members``, ``show_inheritance`` and
``noindex`` that are ``True`` if the flag option of the same name
was given to the auto directive.
lines: The lines of the docstring. Will be modified *in place*.
Raises:
CartoucheSyntaxError: If the docstring is malformed.
'''
try:
lines[:] = parse_cartouche_text(lines)
except CartoucheSyntaxError as syntax_error:
args = syntax_error.args
arg0 = args[0] if args else ''
arg0 += " in docstring for {what} {name} :".format(what=what, name=name)
arg0 += "\n=== BEGIN DOCSTRING ===\n{lines}\n=== END DOCSTRING ===\n".format(lines='\n'.join(lines))
#noinspection PyPropertyAccess
syntax_error.args = (arg0,) + args[1:]
raise
|
python
|
def rewrite_autodoc(app, what, name, obj, options, lines):
'''Convert lines from Cartouche to Sphinx format.
The function to be called by the Sphinx autodoc extension when autodoc
has read and processed a docstring. This function modified its
``lines`` argument *in place* replacing Cartouche syntax input into
Sphinx reStructuredText output.
Args:
apps: The Sphinx application object.
what: The type of object which the docstring belongs to. One of
'module', 'class', 'exception', 'function', 'method', 'attribute'
name: The fully qualified name of the object.
obj: The object itself.
options: The options given to the directive. An object with attributes
``inherited_members``, ``undoc_members``, ``show_inheritance`` and
``noindex`` that are ``True`` if the flag option of the same name
was given to the auto directive.
lines: The lines of the docstring. Will be modified *in place*.
Raises:
CartoucheSyntaxError: If the docstring is malformed.
'''
try:
lines[:] = parse_cartouche_text(lines)
except CartoucheSyntaxError as syntax_error:
args = syntax_error.args
arg0 = args[0] if args else ''
arg0 += " in docstring for {what} {name} :".format(what=what, name=name)
arg0 += "\n=== BEGIN DOCSTRING ===\n{lines}\n=== END DOCSTRING ===\n".format(lines='\n'.join(lines))
#noinspection PyPropertyAccess
syntax_error.args = (arg0,) + args[1:]
raise
|
[
"def",
"rewrite_autodoc",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"try",
":",
"lines",
"[",
":",
"]",
"=",
"parse_cartouche_text",
"(",
"lines",
")",
"except",
"CartoucheSyntaxError",
"as",
"syntax_error",
":",
"args",
"=",
"syntax_error",
".",
"args",
"arg0",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"''",
"arg0",
"+=",
"\" in docstring for {what} {name} :\"",
".",
"format",
"(",
"what",
"=",
"what",
",",
"name",
"=",
"name",
")",
"arg0",
"+=",
"\"\\n=== BEGIN DOCSTRING ===\\n{lines}\\n=== END DOCSTRING ===\\n\"",
".",
"format",
"(",
"lines",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
")",
"#noinspection PyPropertyAccess",
"syntax_error",
".",
"args",
"=",
"(",
"arg0",
",",
")",
"+",
"args",
"[",
"1",
":",
"]",
"raise"
] |
Convert lines from Cartouche to Sphinx format.
The function to be called by the Sphinx autodoc extension when autodoc
has read and processed a docstring. This function modified its
``lines`` argument *in place* replacing Cartouche syntax input into
Sphinx reStructuredText output.
Args:
apps: The Sphinx application object.
what: The type of object which the docstring belongs to. One of
'module', 'class', 'exception', 'function', 'method', 'attribute'
name: The fully qualified name of the object.
obj: The object itself.
options: The options given to the directive. An object with attributes
``inherited_members``, ``undoc_members``, ``show_inheritance`` and
``noindex`` that are ``True`` if the flag option of the same name
was given to the auto directive.
lines: The lines of the docstring. Will be modified *in place*.
Raises:
CartoucheSyntaxError: If the docstring is malformed.
|
[
"Convert",
"lines",
"from",
"Cartouche",
"to",
"Sphinx",
"format",
"."
] |
d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a
|
https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L443-L480
|
239,058
|
takluyver/win_cli_launchers
|
win_cli_launchers/__init__.py
|
find_exe
|
def find_exe(arch='x86'):
"""Get the path to an exe launcher provided by this package.
The options for arch are currently 'x86' and 'x64'.
"""
if arch == 'x86':
return os.path.join(_pkg_dir, 'cli-32.exe')
elif arch == 'x64':
return os.path.join(_pkg_dir, 'cli-64.exe')
raise ValueError('Unrecognised arch: %r' % arch)
|
python
|
def find_exe(arch='x86'):
"""Get the path to an exe launcher provided by this package.
The options for arch are currently 'x86' and 'x64'.
"""
if arch == 'x86':
return os.path.join(_pkg_dir, 'cli-32.exe')
elif arch == 'x64':
return os.path.join(_pkg_dir, 'cli-64.exe')
raise ValueError('Unrecognised arch: %r' % arch)
|
[
"def",
"find_exe",
"(",
"arch",
"=",
"'x86'",
")",
":",
"if",
"arch",
"==",
"'x86'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"_pkg_dir",
",",
"'cli-32.exe'",
")",
"elif",
"arch",
"==",
"'x64'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"_pkg_dir",
",",
"'cli-64.exe'",
")",
"raise",
"ValueError",
"(",
"'Unrecognised arch: %r'",
"%",
"arch",
")"
] |
Get the path to an exe launcher provided by this package.
The options for arch are currently 'x86' and 'x64'.
|
[
"Get",
"the",
"path",
"to",
"an",
"exe",
"launcher",
"provided",
"by",
"this",
"package",
"."
] |
8f8dae7097f5a1c7d14b35eb3691d775afbfe9c4
|
https://github.com/takluyver/win_cli_launchers/blob/8f8dae7097f5a1c7d14b35eb3691d775afbfe9c4/win_cli_launchers/__init__.py#L9-L19
|
239,059
|
baguette-io/baguette-messaging
|
farine/settings.py
|
load
|
def load():
"""
| Load the configuration file.
| Add dynamically configuration to the module.
:rtype: None
"""
config = ConfigParser.RawConfigParser(DEFAULTS)
config.readfp(open(CONF_PATH))
for section in config.sections():
globals()[section] = {}
for key, val in config.items(section):
globals()[section][key] = val
|
python
|
def load():
"""
| Load the configuration file.
| Add dynamically configuration to the module.
:rtype: None
"""
config = ConfigParser.RawConfigParser(DEFAULTS)
config.readfp(open(CONF_PATH))
for section in config.sections():
globals()[section] = {}
for key, val in config.items(section):
globals()[section][key] = val
|
[
"def",
"load",
"(",
")",
":",
"config",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
"DEFAULTS",
")",
"config",
".",
"readfp",
"(",
"open",
"(",
"CONF_PATH",
")",
")",
"for",
"section",
"in",
"config",
".",
"sections",
"(",
")",
":",
"globals",
"(",
")",
"[",
"section",
"]",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"config",
".",
"items",
"(",
"section",
")",
":",
"globals",
"(",
")",
"[",
"section",
"]",
"[",
"key",
"]",
"=",
"val"
] |
| Load the configuration file.
| Add dynamically configuration to the module.
:rtype: None
|
[
"|",
"Load",
"the",
"configuration",
"file",
".",
"|",
"Add",
"dynamically",
"configuration",
"to",
"the",
"module",
"."
] |
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
|
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/settings.py#L36-L48
|
239,060
|
LionelAuroux/cnorm
|
cnorm/passes/visit.py
|
declfuncs
|
def declfuncs(self):
"""generator on all declaration of functions"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and not hasattr(f, 'body')):
yield f
|
python
|
def declfuncs(self):
"""generator on all declaration of functions"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and not hasattr(f, 'body')):
yield f
|
[
"def",
"declfuncs",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"body",
":",
"if",
"(",
"hasattr",
"(",
"f",
",",
"'_ctype'",
")",
"and",
"isinstance",
"(",
"f",
".",
"_ctype",
",",
"FuncType",
")",
"and",
"not",
"hasattr",
"(",
"f",
",",
"'body'",
")",
")",
":",
"yield",
"f"
] |
generator on all declaration of functions
|
[
"generator",
"on",
"all",
"declaration",
"of",
"functions"
] |
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
|
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/passes/visit.py#L5-L11
|
239,061
|
LionelAuroux/cnorm
|
cnorm/passes/visit.py
|
implfuncs
|
def implfuncs(self):
"""generator on all implemented functions"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and hasattr(f, 'body')):
yield f
|
python
|
def implfuncs(self):
"""generator on all implemented functions"""
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and hasattr(f, 'body')):
yield f
|
[
"def",
"implfuncs",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"body",
":",
"if",
"(",
"hasattr",
"(",
"f",
",",
"'_ctype'",
")",
"and",
"isinstance",
"(",
"f",
".",
"_ctype",
",",
"FuncType",
")",
"and",
"hasattr",
"(",
"f",
",",
"'body'",
")",
")",
":",
"yield",
"f"
] |
generator on all implemented functions
|
[
"generator",
"on",
"all",
"implemented",
"functions"
] |
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
|
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/passes/visit.py#L14-L20
|
239,062
|
LionelAuroux/cnorm
|
cnorm/passes/visit.py
|
defvars
|
def defvars(self):
"""generator on all definition of variable"""
for f in self.body:
if (hasattr(f, '_ctype')
and f._name != ''
and not isinstance(f._ctype, FuncType)
and f._ctype._storage != Storages.TYPEDEF):
yield f
|
python
|
def defvars(self):
"""generator on all definition of variable"""
for f in self.body:
if (hasattr(f, '_ctype')
and f._name != ''
and not isinstance(f._ctype, FuncType)
and f._ctype._storage != Storages.TYPEDEF):
yield f
|
[
"def",
"defvars",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"body",
":",
"if",
"(",
"hasattr",
"(",
"f",
",",
"'_ctype'",
")",
"and",
"f",
".",
"_name",
"!=",
"''",
"and",
"not",
"isinstance",
"(",
"f",
".",
"_ctype",
",",
"FuncType",
")",
"and",
"f",
".",
"_ctype",
".",
"_storage",
"!=",
"Storages",
".",
"TYPEDEF",
")",
":",
"yield",
"f"
] |
generator on all definition of variable
|
[
"generator",
"on",
"all",
"definition",
"of",
"variable"
] |
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
|
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/passes/visit.py#L23-L30
|
239,063
|
LionelAuroux/cnorm
|
cnorm/passes/visit.py
|
deftypes
|
def deftypes(self):
"""generator on all definition of type"""
for f in self.body:
if (hasattr(f, '_ctype')
and (f._ctype._storage == Storages.TYPEDEF
or (f._name == '' and isinstance(f._ctype, ComposedType)))):
yield f
|
python
|
def deftypes(self):
"""generator on all definition of type"""
for f in self.body:
if (hasattr(f, '_ctype')
and (f._ctype._storage == Storages.TYPEDEF
or (f._name == '' and isinstance(f._ctype, ComposedType)))):
yield f
|
[
"def",
"deftypes",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"body",
":",
"if",
"(",
"hasattr",
"(",
"f",
",",
"'_ctype'",
")",
"and",
"(",
"f",
".",
"_ctype",
".",
"_storage",
"==",
"Storages",
".",
"TYPEDEF",
"or",
"(",
"f",
".",
"_name",
"==",
"''",
"and",
"isinstance",
"(",
"f",
".",
"_ctype",
",",
"ComposedType",
")",
")",
")",
")",
":",
"yield",
"f"
] |
generator on all definition of type
|
[
"generator",
"on",
"all",
"definition",
"of",
"type"
] |
b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15
|
https://github.com/LionelAuroux/cnorm/blob/b7bb09a70c62fb02c1e41e6280a2a5c0cf2c0f15/cnorm/passes/visit.py#L33-L39
|
239,064
|
mlavin/argyle
|
argyle/supervisor.py
|
upload_supervisor_app_conf
|
def upload_supervisor_app_conf(app_name, template_name=None, context=None):
"""Upload Supervisor app configuration from a template."""
default = {'app_name': app_name}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % app_name, u'supervisor/base.conf']
destination = u'/etc/supervisor/conf.d/%s.conf' % app_name
upload_template(template_name, destination, context=default, use_sudo=True)
supervisor_command(u'update')
|
python
|
def upload_supervisor_app_conf(app_name, template_name=None, context=None):
"""Upload Supervisor app configuration from a template."""
default = {'app_name': app_name}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % app_name, u'supervisor/base.conf']
destination = u'/etc/supervisor/conf.d/%s.conf' % app_name
upload_template(template_name, destination, context=default, use_sudo=True)
supervisor_command(u'update')
|
[
"def",
"upload_supervisor_app_conf",
"(",
"app_name",
",",
"template_name",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"default",
"=",
"{",
"'app_name'",
":",
"app_name",
"}",
"context",
"=",
"context",
"or",
"{",
"}",
"default",
".",
"update",
"(",
"context",
")",
"template_name",
"=",
"template_name",
"or",
"[",
"u'supervisor/%s.conf'",
"%",
"app_name",
",",
"u'supervisor/base.conf'",
"]",
"destination",
"=",
"u'/etc/supervisor/conf.d/%s.conf'",
"%",
"app_name",
"upload_template",
"(",
"template_name",
",",
"destination",
",",
"context",
"=",
"default",
",",
"use_sudo",
"=",
"True",
")",
"supervisor_command",
"(",
"u'update'",
")"
] |
Upload Supervisor app configuration from a template.
|
[
"Upload",
"Supervisor",
"app",
"configuration",
"from",
"a",
"template",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/supervisor.py#L14-L23
|
239,065
|
mlavin/argyle
|
argyle/supervisor.py
|
remove_supervisor_app
|
def remove_supervisor_app(app_name):
"""Remove Supervisor app configuration."""
app = u'/etc/supervisor/conf.d/%s.conf' % app_name
if files.exists(app):
sudo(u'rm %s' % app)
supervisor_command(u'update')
|
python
|
def remove_supervisor_app(app_name):
"""Remove Supervisor app configuration."""
app = u'/etc/supervisor/conf.d/%s.conf' % app_name
if files.exists(app):
sudo(u'rm %s' % app)
supervisor_command(u'update')
|
[
"def",
"remove_supervisor_app",
"(",
"app_name",
")",
":",
"app",
"=",
"u'/etc/supervisor/conf.d/%s.conf'",
"%",
"app_name",
"if",
"files",
".",
"exists",
"(",
"app",
")",
":",
"sudo",
"(",
"u'rm %s'",
"%",
"app",
")",
"supervisor_command",
"(",
"u'update'",
")"
] |
Remove Supervisor app configuration.
|
[
"Remove",
"Supervisor",
"app",
"configuration",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/supervisor.py#L27-L33
|
239,066
|
mlavin/argyle
|
argyle/supervisor.py
|
upload_celery_conf
|
def upload_celery_conf(command='celeryd', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a celery command."""
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/celery.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=default)
|
python
|
def upload_celery_conf(command='celeryd', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a celery command."""
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/celery.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=default)
|
[
"def",
"upload_celery_conf",
"(",
"command",
"=",
"'celeryd'",
",",
"app_name",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"app_name",
"=",
"app_name",
"or",
"command",
"default",
"=",
"{",
"'app_name'",
":",
"app_name",
",",
"'command'",
":",
"command",
"}",
"context",
"=",
"context",
"or",
"{",
"}",
"default",
".",
"update",
"(",
"context",
")",
"template_name",
"=",
"template_name",
"or",
"[",
"u'supervisor/%s.conf'",
"%",
"command",
",",
"u'supervisor/celery.conf'",
"]",
"upload_supervisor_app_conf",
"(",
"app_name",
"=",
"app_name",
",",
"template_name",
"=",
"template_name",
",",
"context",
"=",
"default",
")"
] |
Upload Supervisor configuration for a celery command.
|
[
"Upload",
"Supervisor",
"configuration",
"for",
"a",
"celery",
"command",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/supervisor.py#L37-L45
|
239,067
|
mlavin/argyle
|
argyle/supervisor.py
|
upload_gunicorn_conf
|
def upload_gunicorn_conf(command='gunicorn', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a gunicorn server."""
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/gunicorn.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=default)
|
python
|
def upload_gunicorn_conf(command='gunicorn', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a gunicorn server."""
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/gunicorn.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=default)
|
[
"def",
"upload_gunicorn_conf",
"(",
"command",
"=",
"'gunicorn'",
",",
"app_name",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"app_name",
"=",
"app_name",
"or",
"command",
"default",
"=",
"{",
"'app_name'",
":",
"app_name",
",",
"'command'",
":",
"command",
"}",
"context",
"=",
"context",
"or",
"{",
"}",
"default",
".",
"update",
"(",
"context",
")",
"template_name",
"=",
"template_name",
"or",
"[",
"u'supervisor/%s.conf'",
"%",
"command",
",",
"u'supervisor/gunicorn.conf'",
"]",
"upload_supervisor_app_conf",
"(",
"app_name",
"=",
"app_name",
",",
"template_name",
"=",
"template_name",
",",
"context",
"=",
"default",
")"
] |
Upload Supervisor configuration for a gunicorn server.
|
[
"Upload",
"Supervisor",
"configuration",
"for",
"a",
"gunicorn",
"server",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/supervisor.py#L49-L57
|
239,068
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/run/Notifier.py
|
Notifier.notify
|
def notify(correlation_id, components, args = None):
"""
Notifies multiple components.
To be notified components must implement [[INotifiable]] interface.
If they don't the call to this method has no effect.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param components: a list of components that are to be notified.
:param args: notification arguments.
"""
if components == None:
return
args = args if args != None else Parameters()
for component in components:
Notifier.notify_one(correlation_id, component, args)
|
python
|
def notify(correlation_id, components, args = None):
"""
Notifies multiple components.
To be notified components must implement [[INotifiable]] interface.
If they don't the call to this method has no effect.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param components: a list of components that are to be notified.
:param args: notification arguments.
"""
if components == None:
return
args = args if args != None else Parameters()
for component in components:
Notifier.notify_one(correlation_id, component, args)
|
[
"def",
"notify",
"(",
"correlation_id",
",",
"components",
",",
"args",
"=",
"None",
")",
":",
"if",
"components",
"==",
"None",
":",
"return",
"args",
"=",
"args",
"if",
"args",
"!=",
"None",
"else",
"Parameters",
"(",
")",
"for",
"component",
"in",
"components",
":",
"Notifier",
".",
"notify_one",
"(",
"correlation_id",
",",
"component",
",",
"args",
")"
] |
Notifies multiple components.
To be notified components must implement [[INotifiable]] interface.
If they don't the call to this method has no effect.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param components: a list of components that are to be notified.
:param args: notification arguments.
|
[
"Notifies",
"multiple",
"components",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/run/Notifier.py#L39-L57
|
239,069
|
wooga/play-deliver
|
playdeliver/client.py
|
Client.list
|
def list(self, service_name, **params):
"""
convinent access method for list.
service_name describes the endpoint to call
the `list` function on.
images.list or apks.list.
"""
result = self._invoke_call(service_name, 'list', **params)
if result is not None:
return result.get(service_name, list())
return list()
|
python
|
def list(self, service_name, **params):
"""
convinent access method for list.
service_name describes the endpoint to call
the `list` function on.
images.list or apks.list.
"""
result = self._invoke_call(service_name, 'list', **params)
if result is not None:
return result.get(service_name, list())
return list()
|
[
"def",
"list",
"(",
"self",
",",
"service_name",
",",
"*",
"*",
"params",
")",
":",
"result",
"=",
"self",
".",
"_invoke_call",
"(",
"service_name",
",",
"'list'",
",",
"*",
"*",
"params",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
".",
"get",
"(",
"service_name",
",",
"list",
"(",
")",
")",
"return",
"list",
"(",
")"
] |
convinent access method for list.
service_name describes the endpoint to call
the `list` function on.
images.list or apks.list.
|
[
"convinent",
"access",
"method",
"for",
"list",
"."
] |
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
|
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L25-L37
|
239,070
|
wooga/play-deliver
|
playdeliver/client.py
|
Client.list_inappproducts
|
def list_inappproducts(self):
"""temp function to list inapp products."""
result = self.service.inappproducts().list(
packageName=self.package_name).execute()
if result is not None:
return result.get('inappproduct', list())
return list()
|
python
|
def list_inappproducts(self):
"""temp function to list inapp products."""
result = self.service.inappproducts().list(
packageName=self.package_name).execute()
if result is not None:
return result.get('inappproduct', list())
return list()
|
[
"def",
"list_inappproducts",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"service",
".",
"inappproducts",
"(",
")",
".",
"list",
"(",
"packageName",
"=",
"self",
".",
"package_name",
")",
".",
"execute",
"(",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
".",
"get",
"(",
"'inappproduct'",
",",
"list",
"(",
")",
")",
"return",
"list",
"(",
")"
] |
temp function to list inapp products.
|
[
"temp",
"function",
"to",
"list",
"inapp",
"products",
"."
] |
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
|
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L39-L46
|
239,071
|
wooga/play-deliver
|
playdeliver/client.py
|
Client.commit
|
def commit(self):
"""commit current edits."""
request = self.edits().commit(**self.build_params()).execute()
print 'Edit "%s" has been committed' % (request['id'])
self.edit_id = None
|
python
|
def commit(self):
"""commit current edits."""
request = self.edits().commit(**self.build_params()).execute()
print 'Edit "%s" has been committed' % (request['id'])
self.edit_id = None
|
[
"def",
"commit",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"edits",
"(",
")",
".",
"commit",
"(",
"*",
"*",
"self",
".",
"build_params",
"(",
")",
")",
".",
"execute",
"(",
")",
"print",
"'Edit \"%s\" has been committed'",
"%",
"(",
"request",
"[",
"'id'",
"]",
")",
"self",
".",
"edit_id",
"=",
"None"
] |
commit current edits.
|
[
"commit",
"current",
"edits",
"."
] |
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
|
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L89-L94
|
239,072
|
wooga/play-deliver
|
playdeliver/client.py
|
Client.build_params
|
def build_params(self, params={}):
"""
build a params dictionary with current editId and packageName.
use optional params parameter
to merge additional params into resulting dictionary.
"""
z = params.copy()
z.update({'editId': self.edit_id, 'packageName': self.package_name})
return z
|
python
|
def build_params(self, params={}):
"""
build a params dictionary with current editId and packageName.
use optional params parameter
to merge additional params into resulting dictionary.
"""
z = params.copy()
z.update({'editId': self.edit_id, 'packageName': self.package_name})
return z
|
[
"def",
"build_params",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"z",
"=",
"params",
".",
"copy",
"(",
")",
"z",
".",
"update",
"(",
"{",
"'editId'",
":",
"self",
".",
"edit_id",
",",
"'packageName'",
":",
"self",
".",
"package_name",
"}",
")",
"return",
"z"
] |
build a params dictionary with current editId and packageName.
use optional params parameter
to merge additional params into resulting dictionary.
|
[
"build",
"a",
"params",
"dictionary",
"with",
"current",
"editId",
"and",
"packageName",
"."
] |
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
|
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L107-L116
|
239,073
|
wooga/play-deliver
|
playdeliver/client.py
|
Client.ensure_edit_id
|
def ensure_edit_id(self):
"""create edit id if edit id is None."""
if self.edit_id is None:
edit_request = self.edits().insert(
body={}, packageName=self.package_name)
result = edit_request.execute()
self.edit_id = result['id']
|
python
|
def ensure_edit_id(self):
"""create edit id if edit id is None."""
if self.edit_id is None:
edit_request = self.edits().insert(
body={}, packageName=self.package_name)
result = edit_request.execute()
self.edit_id = result['id']
|
[
"def",
"ensure_edit_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"edit_id",
"is",
"None",
":",
"edit_request",
"=",
"self",
".",
"edits",
"(",
")",
".",
"insert",
"(",
"body",
"=",
"{",
"}",
",",
"packageName",
"=",
"self",
".",
"package_name",
")",
"result",
"=",
"edit_request",
".",
"execute",
"(",
")",
"self",
".",
"edit_id",
"=",
"result",
"[",
"'id'",
"]"
] |
create edit id if edit id is None.
|
[
"create",
"edit",
"id",
"if",
"edit",
"id",
"is",
"None",
"."
] |
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
|
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L122-L128
|
239,074
|
mlavin/argyle
|
argyle/rabbitmq.py
|
upload_rabbitmq_environment_conf
|
def upload_rabbitmq_environment_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ environment configuration from a template."""
template_name = template_name or u'rabbitmq/rabbitmq-env.conf'
destination = u'/etc/rabbitmq/rabbitmq-env.conf'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq')
|
python
|
def upload_rabbitmq_environment_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ environment configuration from a template."""
template_name = template_name or u'rabbitmq/rabbitmq-env.conf'
destination = u'/etc/rabbitmq/rabbitmq-env.conf'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq')
|
[
"def",
"upload_rabbitmq_environment_conf",
"(",
"template_name",
"=",
"None",
",",
"context",
"=",
"None",
",",
"restart",
"=",
"True",
")",
":",
"template_name",
"=",
"template_name",
"or",
"u'rabbitmq/rabbitmq-env.conf'",
"destination",
"=",
"u'/etc/rabbitmq/rabbitmq-env.conf'",
"upload_template",
"(",
"template_name",
",",
"destination",
",",
"context",
"=",
"context",
",",
"use_sudo",
"=",
"True",
")",
"if",
"restart",
":",
"restart_service",
"(",
"u'rabbitmq'",
")"
] |
Upload RabbitMQ environment configuration from a template.
|
[
"Upload",
"RabbitMQ",
"environment",
"configuration",
"from",
"a",
"template",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/rabbitmq.py#L35-L42
|
239,075
|
mlavin/argyle
|
argyle/rabbitmq.py
|
upload_rabbitmq_conf
|
def upload_rabbitmq_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ configuration from a template."""
template_name = template_name or u'rabbitmq/rabbitmq.config'
destination = u'/etc/rabbitmq/rabbitmq.config'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq')
|
python
|
def upload_rabbitmq_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ configuration from a template."""
template_name = template_name or u'rabbitmq/rabbitmq.config'
destination = u'/etc/rabbitmq/rabbitmq.config'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq')
|
[
"def",
"upload_rabbitmq_conf",
"(",
"template_name",
"=",
"None",
",",
"context",
"=",
"None",
",",
"restart",
"=",
"True",
")",
":",
"template_name",
"=",
"template_name",
"or",
"u'rabbitmq/rabbitmq.config'",
"destination",
"=",
"u'/etc/rabbitmq/rabbitmq.config'",
"upload_template",
"(",
"template_name",
",",
"destination",
",",
"context",
"=",
"context",
",",
"use_sudo",
"=",
"True",
")",
"if",
"restart",
":",
"restart_service",
"(",
"u'rabbitmq'",
")"
] |
Upload RabbitMQ configuration from a template.
|
[
"Upload",
"RabbitMQ",
"configuration",
"from",
"a",
"template",
"."
] |
92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72
|
https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/rabbitmq.py#L46-L53
|
239,076
|
host-anshu/simpleInterceptor
|
example/lint_pbook/lint.py
|
queue_exc
|
def queue_exc(*arg, **kw):
"""Queue undefined variable exception"""
_self = arg[0]
if not isinstance(_self, AnsibleUndefinedVariable):
# Run for AnsibleUndefinedVariable instance
return
_rslt_q = None
for stack_trace in inspect.stack():
# Check if method to be skipped
if stack_trace[3] in SKIP_METHODS:
continue
_frame = stack_trace[0]
_locals = inspect.getargvalues(_frame).locals
if 'self' not in _locals:
continue
# Check if current frame instance of worker
if isinstance(_locals['self'], WorkerProcess):
# Get queue to add exception
_rslt_q = getattr(_locals['self'], '_rslt_q')
if not _rslt_q:
raise ValueError("No Queue found.")
# Add interceptor exception
_rslt_q.put(arg[3].message, interceptor=True)
|
python
|
def queue_exc(*arg, **kw):
"""Queue undefined variable exception"""
_self = arg[0]
if not isinstance(_self, AnsibleUndefinedVariable):
# Run for AnsibleUndefinedVariable instance
return
_rslt_q = None
for stack_trace in inspect.stack():
# Check if method to be skipped
if stack_trace[3] in SKIP_METHODS:
continue
_frame = stack_trace[0]
_locals = inspect.getargvalues(_frame).locals
if 'self' not in _locals:
continue
# Check if current frame instance of worker
if isinstance(_locals['self'], WorkerProcess):
# Get queue to add exception
_rslt_q = getattr(_locals['self'], '_rslt_q')
if not _rslt_q:
raise ValueError("No Queue found.")
# Add interceptor exception
_rslt_q.put(arg[3].message, interceptor=True)
|
[
"def",
"queue_exc",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"_self",
"=",
"arg",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"_self",
",",
"AnsibleUndefinedVariable",
")",
":",
"# Run for AnsibleUndefinedVariable instance",
"return",
"_rslt_q",
"=",
"None",
"for",
"stack_trace",
"in",
"inspect",
".",
"stack",
"(",
")",
":",
"# Check if method to be skipped",
"if",
"stack_trace",
"[",
"3",
"]",
"in",
"SKIP_METHODS",
":",
"continue",
"_frame",
"=",
"stack_trace",
"[",
"0",
"]",
"_locals",
"=",
"inspect",
".",
"getargvalues",
"(",
"_frame",
")",
".",
"locals",
"if",
"'self'",
"not",
"in",
"_locals",
":",
"continue",
"# Check if current frame instance of worker",
"if",
"isinstance",
"(",
"_locals",
"[",
"'self'",
"]",
",",
"WorkerProcess",
")",
":",
"# Get queue to add exception",
"_rslt_q",
"=",
"getattr",
"(",
"_locals",
"[",
"'self'",
"]",
",",
"'_rslt_q'",
")",
"if",
"not",
"_rslt_q",
":",
"raise",
"ValueError",
"(",
"\"No Queue found.\"",
")",
"# Add interceptor exception",
"_rslt_q",
".",
"put",
"(",
"arg",
"[",
"3",
"]",
".",
"message",
",",
"interceptor",
"=",
"True",
")"
] |
Queue undefined variable exception
|
[
"Queue",
"undefined",
"variable",
"exception"
] |
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
|
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/example/lint_pbook/lint.py#L45-L67
|
239,077
|
host-anshu/simpleInterceptor
|
example/lint_pbook/lint.py
|
extract_worker_exc
|
def extract_worker_exc(*arg, **kw):
"""Get exception added by worker"""
_self = arg[0]
if not isinstance(_self, StrategyBase):
# Run for StrategyBase instance only
return
# Iterate over workers to get their task and queue
for _worker_prc, _main_q, _rslt_q in _self._workers:
_task = _worker_prc._task
if _task.action == 'setup':
# Ignore setup
continue
# Do till queue is empty for the worker
while True:
try:
_exc = _rslt_q.get(block=False, interceptor=True)
RESULT[_task.name].add(_exc)
except Empty:
break
|
python
|
def extract_worker_exc(*arg, **kw):
"""Get exception added by worker"""
_self = arg[0]
if not isinstance(_self, StrategyBase):
# Run for StrategyBase instance only
return
# Iterate over workers to get their task and queue
for _worker_prc, _main_q, _rslt_q in _self._workers:
_task = _worker_prc._task
if _task.action == 'setup':
# Ignore setup
continue
# Do till queue is empty for the worker
while True:
try:
_exc = _rslt_q.get(block=False, interceptor=True)
RESULT[_task.name].add(_exc)
except Empty:
break
|
[
"def",
"extract_worker_exc",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"_self",
"=",
"arg",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"_self",
",",
"StrategyBase",
")",
":",
"# Run for StrategyBase instance only",
"return",
"# Iterate over workers to get their task and queue",
"for",
"_worker_prc",
",",
"_main_q",
",",
"_rslt_q",
"in",
"_self",
".",
"_workers",
":",
"_task",
"=",
"_worker_prc",
".",
"_task",
"if",
"_task",
".",
"action",
"==",
"'setup'",
":",
"# Ignore setup",
"continue",
"# Do till queue is empty for the worker",
"while",
"True",
":",
"try",
":",
"_exc",
"=",
"_rslt_q",
".",
"get",
"(",
"block",
"=",
"False",
",",
"interceptor",
"=",
"True",
")",
"RESULT",
"[",
"_task",
".",
"name",
"]",
".",
"add",
"(",
"_exc",
")",
"except",
"Empty",
":",
"break"
] |
Get exception added by worker
|
[
"Get",
"exception",
"added",
"by",
"worker"
] |
71238fed57c62b5f77ce32d0c9b98acad73ab6a8
|
https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/example/lint_pbook/lint.py#L70-L88
|
239,078
|
Bystroushaak/pyDHTMLParser
|
src/dhtmlparser/htmlelement/html_query.py
|
HTMLQuery.containsParamSubset
|
def containsParamSubset(self, params):
"""
Test whether this element contains at least all `params`, or more.
Args:
params (dict/SpecialDict): Subset of parameters.
Returns:
bool: True if all `params` are contained in this element.
"""
for key in params.keys():
if key not in self.params:
return False
if params[key] != self.params[key]:
return False
return True
|
python
|
def containsParamSubset(self, params):
"""
Test whether this element contains at least all `params`, or more.
Args:
params (dict/SpecialDict): Subset of parameters.
Returns:
bool: True if all `params` are contained in this element.
"""
for key in params.keys():
if key not in self.params:
return False
if params[key] != self.params[key]:
return False
return True
|
[
"def",
"containsParamSubset",
"(",
"self",
",",
"params",
")",
":",
"for",
"key",
"in",
"params",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"params",
":",
"return",
"False",
"if",
"params",
"[",
"key",
"]",
"!=",
"self",
".",
"params",
"[",
"key",
"]",
":",
"return",
"False",
"return",
"True"
] |
Test whether this element contains at least all `params`, or more.
Args:
params (dict/SpecialDict): Subset of parameters.
Returns:
bool: True if all `params` are contained in this element.
|
[
"Test",
"whether",
"this",
"element",
"contains",
"at",
"least",
"all",
"params",
"or",
"more",
"."
] |
4756f93dd048500b038ece2323fe26e46b6bfdea
|
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_query.py#L17-L34
|
239,079
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/data/PagingParams.py
|
PagingParams.get_skip
|
def get_skip(self, min_skip):
"""
Gets the number of items to skip.
:param min_skip: the minimum number of items to skip.
:return: the number of items to skip.
"""
if self.skip == None:
return min_skip
if self.skip < min_skip:
return min_skip
return self.skip
|
python
|
def get_skip(self, min_skip):
"""
Gets the number of items to skip.
:param min_skip: the minimum number of items to skip.
:return: the number of items to skip.
"""
if self.skip == None:
return min_skip
if self.skip < min_skip:
return min_skip
return self.skip
|
[
"def",
"get_skip",
"(",
"self",
",",
"min_skip",
")",
":",
"if",
"self",
".",
"skip",
"==",
"None",
":",
"return",
"min_skip",
"if",
"self",
".",
"skip",
"<",
"min_skip",
":",
"return",
"min_skip",
"return",
"self",
".",
"skip"
] |
Gets the number of items to skip.
:param min_skip: the minimum number of items to skip.
:return: the number of items to skip.
|
[
"Gets",
"the",
"number",
"of",
"items",
"to",
"skip",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/PagingParams.py#L53-L65
|
239,080
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/data/PagingParams.py
|
PagingParams.get_take
|
def get_take(self, max_take):
"""
Gets the number of items to return in a page.
:param max_take: the maximum number of items to return.
:return: the number of items to return.
"""
if self.take == None:
return max_take
if self.take < 0:
return 0
if self.take > max_take:
return max_take
return self.take
|
python
|
def get_take(self, max_take):
"""
Gets the number of items to return in a page.
:param max_take: the maximum number of items to return.
:return: the number of items to return.
"""
if self.take == None:
return max_take
if self.take < 0:
return 0
if self.take > max_take:
return max_take
return self.take
|
[
"def",
"get_take",
"(",
"self",
",",
"max_take",
")",
":",
"if",
"self",
".",
"take",
"==",
"None",
":",
"return",
"max_take",
"if",
"self",
".",
"take",
"<",
"0",
":",
"return",
"0",
"if",
"self",
".",
"take",
">",
"max_take",
":",
"return",
"max_take",
"return",
"self",
".",
"take"
] |
Gets the number of items to return in a page.
:param max_take: the maximum number of items to return.
:return: the number of items to return.
|
[
"Gets",
"the",
"number",
"of",
"items",
"to",
"return",
"in",
"a",
"page",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/PagingParams.py#L67-L81
|
239,081
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/data/PagingParams.py
|
PagingParams.from_value
|
def from_value(value):
"""
Converts specified value into PagingParams.
:param value: value to be converted
:return: a newly created PagingParams.
"""
if isinstance(value, PagingParams):
return value
if isinstance(value, AnyValueMap):
return PagingParams.from_map(value)
map = AnyValueMap.from_value(value)
return PagingParams.from_map(map)
|
python
|
def from_value(value):
"""
Converts specified value into PagingParams.
:param value: value to be converted
:return: a newly created PagingParams.
"""
if isinstance(value, PagingParams):
return value
if isinstance(value, AnyValueMap):
return PagingParams.from_map(value)
map = AnyValueMap.from_value(value)
return PagingParams.from_map(map)
|
[
"def",
"from_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PagingParams",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"AnyValueMap",
")",
":",
"return",
"PagingParams",
".",
"from_map",
"(",
"value",
")",
"map",
"=",
"AnyValueMap",
".",
"from_value",
"(",
"value",
")",
"return",
"PagingParams",
".",
"from_map",
"(",
"map",
")"
] |
Converts specified value into PagingParams.
:param value: value to be converted
:return: a newly created PagingParams.
|
[
"Converts",
"specified",
"value",
"into",
"PagingParams",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/PagingParams.py#L104-L118
|
239,082
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/data/PagingParams.py
|
PagingParams.from_map
|
def from_map(map):
"""
Creates a new PagingParams and sets it parameters from the specified map
:param map: a AnyValueMap or StringValueMap to initialize this PagingParams
:return: a newly created PagingParams.
"""
skip = map.get_as_nullable_integer("skip")
take = map.get_as_nullable_integer("take")
total = map.get_as_nullable_boolean("total")
return PagingParams(skip, take, total)
|
python
|
def from_map(map):
"""
Creates a new PagingParams and sets it parameters from the specified map
:param map: a AnyValueMap or StringValueMap to initialize this PagingParams
:return: a newly created PagingParams.
"""
skip = map.get_as_nullable_integer("skip")
take = map.get_as_nullable_integer("take")
total = map.get_as_nullable_boolean("total")
return PagingParams(skip, take, total)
|
[
"def",
"from_map",
"(",
"map",
")",
":",
"skip",
"=",
"map",
".",
"get_as_nullable_integer",
"(",
"\"skip\"",
")",
"take",
"=",
"map",
".",
"get_as_nullable_integer",
"(",
"\"take\"",
")",
"total",
"=",
"map",
".",
"get_as_nullable_boolean",
"(",
"\"total\"",
")",
"return",
"PagingParams",
"(",
"skip",
",",
"take",
",",
"total",
")"
] |
Creates a new PagingParams and sets it parameters from the specified map
:param map: a AnyValueMap or StringValueMap to initialize this PagingParams
:return: a newly created PagingParams.
|
[
"Creates",
"a",
"new",
"PagingParams",
"and",
"sets",
"it",
"parameters",
"from",
"the",
"specified",
"map"
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/PagingParams.py#L133-L144
|
239,083
|
rvswift/EB
|
EB/builder/exhaustive/exhaustive_io.py
|
ParseArgs.get_int
|
def get_int(self, input_string):
"""
Return integer type user input
"""
if input_string in ('--ensemble_size', '--ncpu'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, so if it's required, exit
if input_string in self.required:
print("\n {flag} is required\n".format(flag=input_string))
print_short_help()
sys.exit(1)
# otherwise return the appropriate default
else:
return None
# the flag was set, so check if a value was set, otherwise exit
try:
if self.args[index] in self.flags:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
except IndexError:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
# a value was set, so check if its the correct type
try:
value = int(self.args[index])
except ValueError:
print("\n {flag} must be an integer".format(flag=input_string))
print_short_help()
sys.exit(1)
# verify the value provided is not negative
if value < 0:
print("\n {flag} must be an integer greater than 0".format(flag=input_string))
print_short_help()
sys.exit(1)
# everything checks out, so return the value
return value
|
python
|
def get_int(self, input_string):
"""
Return integer type user input
"""
if input_string in ('--ensemble_size', '--ncpu'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, so if it's required, exit
if input_string in self.required:
print("\n {flag} is required\n".format(flag=input_string))
print_short_help()
sys.exit(1)
# otherwise return the appropriate default
else:
return None
# the flag was set, so check if a value was set, otherwise exit
try:
if self.args[index] in self.flags:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
except IndexError:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
# a value was set, so check if its the correct type
try:
value = int(self.args[index])
except ValueError:
print("\n {flag} must be an integer".format(flag=input_string))
print_short_help()
sys.exit(1)
# verify the value provided is not negative
if value < 0:
print("\n {flag} must be an integer greater than 0".format(flag=input_string))
print_short_help()
sys.exit(1)
# everything checks out, so return the value
return value
|
[
"def",
"get_int",
"(",
"self",
",",
"input_string",
")",
":",
"if",
"input_string",
"in",
"(",
"'--ensemble_size'",
",",
"'--ncpu'",
")",
":",
"# was the flag set?",
"try",
":",
"index",
"=",
"self",
".",
"args",
".",
"index",
"(",
"input_string",
")",
"+",
"1",
"except",
"ValueError",
":",
"# it wasn't, so if it's required, exit",
"if",
"input_string",
"in",
"self",
".",
"required",
":",
"print",
"(",
"\"\\n {flag} is required\\n\"",
".",
"format",
"(",
"flag",
"=",
"input_string",
")",
")",
"print_short_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# otherwise return the appropriate default",
"else",
":",
"return",
"None",
"# the flag was set, so check if a value was set, otherwise exit",
"try",
":",
"if",
"self",
".",
"args",
"[",
"index",
"]",
"in",
"self",
".",
"flags",
":",
"print",
"(",
"\"\\n {flag} was set but a value was not specified\"",
".",
"format",
"(",
"flag",
"=",
"input_string",
")",
")",
"print_short_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"except",
"IndexError",
":",
"print",
"(",
"\"\\n {flag} was set but a value was not specified\"",
".",
"format",
"(",
"flag",
"=",
"input_string",
")",
")",
"print_short_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# a value was set, so check if its the correct type",
"try",
":",
"value",
"=",
"int",
"(",
"self",
".",
"args",
"[",
"index",
"]",
")",
"except",
"ValueError",
":",
"print",
"(",
"\"\\n {flag} must be an integer\"",
".",
"format",
"(",
"flag",
"=",
"input_string",
")",
")",
"print_short_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# verify the value provided is not negative",
"if",
"value",
"<",
"0",
":",
"print",
"(",
"\"\\n {flag} must be an integer greater than 0\"",
".",
"format",
"(",
"flag",
"=",
"input_string",
")",
")",
"print_short_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# everything checks out, so return the value",
"return",
"value"
] |
Return integer type user input
|
[
"Return",
"integer",
"type",
"user",
"input"
] |
341880b79faf8147dc9fa6e90438531cd09fabcc
|
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/exhaustive/exhaustive_io.py#L141-L187
|
239,084
|
sprockets/sprockets.handlers.status
|
sprockets/handlers/status/__init__.py
|
StatusHandler.get
|
def get(self, *args, **kwargs):
"""Tornado RequestHandler GET request endpoint for reporting status
:param list args: positional args
:param dict kwargs: keyword args
"""
self.set_status(self._status_response_code())
self.write(self._status_response())
|
python
|
def get(self, *args, **kwargs):
"""Tornado RequestHandler GET request endpoint for reporting status
:param list args: positional args
:param dict kwargs: keyword args
"""
self.set_status(self._status_response_code())
self.write(self._status_response())
|
[
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"set_status",
"(",
"self",
".",
"_status_response_code",
"(",
")",
")",
"self",
".",
"write",
"(",
"self",
".",
"_status_response",
"(",
")",
")"
] |
Tornado RequestHandler GET request endpoint for reporting status
:param list args: positional args
:param dict kwargs: keyword args
|
[
"Tornado",
"RequestHandler",
"GET",
"request",
"endpoint",
"for",
"reporting",
"status"
] |
99d0eababe8c5617cb04c3545df418306b3a03ef
|
https://github.com/sprockets/sprockets.handlers.status/blob/99d0eababe8c5617cb04c3545df418306b3a03ef/sprockets/handlers/status/__init__.py#L37-L45
|
239,085
|
botswana-harvard/edc-registration
|
edc_registration/signals.py
|
update_registered_subject_from_model_on_post_save
|
def update_registered_subject_from_model_on_post_save(sender, instance, raw, created, using, **kwargs):
"""Updates RegisteredSubject from models using UpdatesOrCreatesRegistrationModelMixin."""
if not raw and not kwargs.get('update_fields'):
try:
instance.registration_update_or_create()
except AttributeError as e:
if 'registration_update_or_create' not in str(e):
raise AttributeError(str(e))
|
python
|
def update_registered_subject_from_model_on_post_save(sender, instance, raw, created, using, **kwargs):
"""Updates RegisteredSubject from models using UpdatesOrCreatesRegistrationModelMixin."""
if not raw and not kwargs.get('update_fields'):
try:
instance.registration_update_or_create()
except AttributeError as e:
if 'registration_update_or_create' not in str(e):
raise AttributeError(str(e))
|
[
"def",
"update_registered_subject_from_model_on_post_save",
"(",
"sender",
",",
"instance",
",",
"raw",
",",
"created",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"raw",
"and",
"not",
"kwargs",
".",
"get",
"(",
"'update_fields'",
")",
":",
"try",
":",
"instance",
".",
"registration_update_or_create",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"if",
"'registration_update_or_create'",
"not",
"in",
"str",
"(",
"e",
")",
":",
"raise",
"AttributeError",
"(",
"str",
"(",
"e",
")",
")"
] |
Updates RegisteredSubject from models using UpdatesOrCreatesRegistrationModelMixin.
|
[
"Updates",
"RegisteredSubject",
"from",
"models",
"using",
"UpdatesOrCreatesRegistrationModelMixin",
"."
] |
3daca624a496945fd4536488f6f80790bbecc081
|
https://github.com/botswana-harvard/edc-registration/blob/3daca624a496945fd4536488f6f80790bbecc081/edc_registration/signals.py#L7-L14
|
239,086
|
sloria/read_env
|
tasks.py
|
publish
|
def publish(ctx, test=False):
"""Publish to the cheeseshop."""
clean(ctx)
if test:
run('python setup.py register -r test sdist bdist_wheel', echo=True)
run('twine upload dist/* -r test', echo=True)
else:
run('python setup.py register sdist bdist_wheel', echo=True)
run('twine upload dist/*', echo=True)
|
python
|
def publish(ctx, test=False):
"""Publish to the cheeseshop."""
clean(ctx)
if test:
run('python setup.py register -r test sdist bdist_wheel', echo=True)
run('twine upload dist/* -r test', echo=True)
else:
run('python setup.py register sdist bdist_wheel', echo=True)
run('twine upload dist/*', echo=True)
|
[
"def",
"publish",
"(",
"ctx",
",",
"test",
"=",
"False",
")",
":",
"clean",
"(",
"ctx",
")",
"if",
"test",
":",
"run",
"(",
"'python setup.py register -r test sdist bdist_wheel'",
",",
"echo",
"=",
"True",
")",
"run",
"(",
"'twine upload dist/* -r test'",
",",
"echo",
"=",
"True",
")",
"else",
":",
"run",
"(",
"'python setup.py register sdist bdist_wheel'",
",",
"echo",
"=",
"True",
")",
"run",
"(",
"'twine upload dist/*'",
",",
"echo",
"=",
"True",
")"
] |
Publish to the cheeseshop.
|
[
"Publish",
"to",
"the",
"cheeseshop",
"."
] |
90c5a7b38d70f06cd96b5d9a7e68e422bb5bd605
|
https://github.com/sloria/read_env/blob/90c5a7b38d70f06cd96b5d9a7e68e422bb5bd605/tasks.py#L37-L45
|
239,087
|
ptav/django-simplecrud
|
simplecrud/format.py
|
format_value
|
def format_value(value,number_format):
"Convert number to string using a style string"
style,sufix,scale = decode_format(number_format)
fmt = "{0:" + style + "}" + sufix
return fmt.format(scale * value)
|
python
|
def format_value(value,number_format):
"Convert number to string using a style string"
style,sufix,scale = decode_format(number_format)
fmt = "{0:" + style + "}" + sufix
return fmt.format(scale * value)
|
[
"def",
"format_value",
"(",
"value",
",",
"number_format",
")",
":",
"style",
",",
"sufix",
",",
"scale",
"=",
"decode_format",
"(",
"number_format",
")",
"fmt",
"=",
"\"{0:\"",
"+",
"style",
"+",
"\"}\"",
"+",
"sufix",
"return",
"fmt",
".",
"format",
"(",
"scale",
"*",
"value",
")"
] |
Convert number to string using a style string
|
[
"Convert",
"number",
"to",
"string",
"using",
"a",
"style",
"string"
] |
468f6322aab35c8001311ee7920114400a040f6c
|
https://github.com/ptav/django-simplecrud/blob/468f6322aab35c8001311ee7920114400a040f6c/simplecrud/format.py#L80-L86
|
239,088
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/reflect/PropertyReflector.py
|
PropertyReflector.has_property
|
def has_property(obj, name):
"""
Checks if object has a property with specified name.
:param obj: an object to introspect.
:param name: a name of the property to check.
:return: true if the object has the property and false if it doesn't.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return True
return False
|
python
|
def has_property(obj, name):
"""
Checks if object has a property with specified name.
:param obj: an object to introspect.
:param name: a name of the property to check.
:return: true if the object has the property and false if it doesn't.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return True
return False
|
[
"def",
"has_property",
"(",
"obj",
",",
"name",
")",
":",
"if",
"obj",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Object cannot be null\"",
")",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Property name cannot be null\"",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"if",
"property_name",
".",
"lower",
"(",
")",
"!=",
"name",
":",
"continue",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
"property",
",",
"property_name",
")",
":",
"return",
"True",
"return",
"False"
] |
Checks if object has a property with specified name.
:param obj: an object to introspect.
:param name: a name of the property to check.
:return: true if the object has the property and false if it doesn't.
|
[
"Checks",
"if",
"object",
"has",
"a",
"property",
"with",
"specified",
"name",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L43-L69
|
239,089
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/reflect/PropertyReflector.py
|
PropertyReflector.get_property
|
def get_property(obj, name):
"""
Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return property
except:
pass
return None
|
python
|
def get_property(obj, name):
"""
Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return property
except:
pass
return None
|
[
"def",
"get_property",
"(",
"obj",
",",
"name",
")",
":",
"if",
"obj",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Object cannot be null\"",
")",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Property name cannot be null\"",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"try",
":",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"if",
"property_name",
".",
"lower",
"(",
")",
"!=",
"name",
":",
"continue",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
"property",
",",
"property_name",
")",
":",
"return",
"property",
"except",
":",
"pass",
"return",
"None"
] |
Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed.
|
[
"Gets",
"value",
"of",
"object",
"property",
"specified",
"by",
"its",
"name",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L73-L102
|
239,090
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/reflect/PropertyReflector.py
|
PropertyReflector.get_property_names
|
def get_property_names(obj):
"""
Gets names of all properties implemented in specified object.
:param obj: an objec to introspect.
:return: a list with property names.
"""
property_names = []
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
property_names.append(property_name)
return property_names
|
python
|
def get_property_names(obj):
"""
Gets names of all properties implemented in specified object.
:param obj: an objec to introspect.
:return: a list with property names.
"""
property_names = []
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
property_names.append(property_name)
return property_names
|
[
"def",
"get_property_names",
"(",
"obj",
")",
":",
"property_names",
"=",
"[",
"]",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
"property",
",",
"property_name",
")",
":",
"property_names",
".",
"append",
"(",
"property_name",
")",
"return",
"property_names"
] |
Gets names of all properties implemented in specified object.
:param obj: an objec to introspect.
:return: a list with property names.
|
[
"Gets",
"names",
"of",
"all",
"properties",
"implemented",
"in",
"specified",
"object",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L106-L123
|
239,091
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/reflect/PropertyReflector.py
|
PropertyReflector.get_properties
|
def get_properties(obj):
"""
Get values of all properties in specified object and returns them as a map.
:param obj: an object to get properties from.
:return: a map, containing the names of the object's properties and their values.
"""
properties = {}
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
properties[property_name] = property
return properties
|
python
|
def get_properties(obj):
"""
Get values of all properties in specified object and returns them as a map.
:param obj: an object to get properties from.
:return: a map, containing the names of the object's properties and their values.
"""
properties = {}
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
properties[property_name] = property
return properties
|
[
"def",
"get_properties",
"(",
"obj",
")",
":",
"properties",
"=",
"{",
"}",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
"property",
",",
"property_name",
")",
":",
"properties",
"[",
"property_name",
"]",
"=",
"property",
"return",
"properties"
] |
Get values of all properties in specified object and returns them as a map.
:param obj: an object to get properties from.
:return: a map, containing the names of the object's properties and their values.
|
[
"Get",
"values",
"of",
"all",
"properties",
"in",
"specified",
"object",
"and",
"returns",
"them",
"as",
"a",
"map",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L127-L144
|
239,092
|
pip-services3-python/pip-services3-commons-python
|
pip_services3_commons/reflect/PropertyReflector.py
|
PropertyReflector.set_property
|
def set_property(obj, name, value):
"""
Sets value of object property specified by its name.
If the property does not exist or introspection fails
this method doesn't do anything and doesn't any throw errors.
:param obj: an object to write property to.
:param name: a name of the property to set.
:param value: a new value for the property to set.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
setattr(obj, property_name, value)
except:
pass
|
python
|
def set_property(obj, name, value):
"""
Sets value of object property specified by its name.
If the property does not exist or introspection fails
this method doesn't do anything and doesn't any throw errors.
:param obj: an object to write property to.
:param name: a name of the property to set.
:param value: a new value for the property to set.
"""
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
setattr(obj, property_name, value)
except:
pass
|
[
"def",
"set_property",
"(",
"obj",
",",
"name",
",",
"value",
")",
":",
"if",
"obj",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Object cannot be null\"",
")",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Property name cannot be null\"",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"try",
":",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"if",
"property_name",
".",
"lower",
"(",
")",
"!=",
"name",
":",
"continue",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
"property",
",",
"property_name",
")",
":",
"setattr",
"(",
"obj",
",",
"property_name",
",",
"value",
")",
"except",
":",
"pass"
] |
Sets value of object property specified by its name.
If the property does not exist or introspection fails
this method doesn't do anything and doesn't any throw errors.
:param obj: an object to write property to.
:param name: a name of the property to set.
:param value: a new value for the property to set.
|
[
"Sets",
"value",
"of",
"object",
"property",
"specified",
"by",
"its",
"name",
"."
] |
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L148-L178
|
239,093
|
thehq/python-crossbarhttp
|
crossbarhttp/crossbarhttp.py
|
Client._compute_signature
|
def _compute_signature(self, body):
"""
Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (signature, none, timestamp)
"""
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
nonce = randint(0, 2**53)
# Compute signature: HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature
hm = hmac.new(self.secret, None, hashlib.sha256)
hm.update(self.key)
hm.update(timestamp)
hm.update(str(self.sequence))
hm.update(str(nonce))
hm.update(body)
signature = base64.urlsafe_b64encode(hm.digest())
return signature, nonce, timestamp
|
python
|
def _compute_signature(self, body):
"""
Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (signature, none, timestamp)
"""
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
nonce = randint(0, 2**53)
# Compute signature: HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature
hm = hmac.new(self.secret, None, hashlib.sha256)
hm.update(self.key)
hm.update(timestamp)
hm.update(str(self.sequence))
hm.update(str(nonce))
hm.update(body)
signature = base64.urlsafe_b64encode(hm.digest())
return signature, nonce, timestamp
|
[
"def",
"_compute_signature",
"(",
"self",
",",
"body",
")",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S.%fZ\"",
")",
"nonce",
"=",
"randint",
"(",
"0",
",",
"2",
"**",
"53",
")",
"# Compute signature: HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature",
"hm",
"=",
"hmac",
".",
"new",
"(",
"self",
".",
"secret",
",",
"None",
",",
"hashlib",
".",
"sha256",
")",
"hm",
".",
"update",
"(",
"self",
".",
"key",
")",
"hm",
".",
"update",
"(",
"timestamp",
")",
"hm",
".",
"update",
"(",
"str",
"(",
"self",
".",
"sequence",
")",
")",
"hm",
".",
"update",
"(",
"str",
"(",
"nonce",
")",
")",
"hm",
".",
"update",
"(",
"body",
")",
"signature",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"hm",
".",
"digest",
"(",
")",
")",
"return",
"signature",
",",
"nonce",
",",
"timestamp"
] |
Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (signature, none, timestamp)
|
[
"Computes",
"the",
"signature",
"."
] |
15af59969ca1ace3b11f2d94ef966e0017cb1c77
|
https://github.com/thehq/python-crossbarhttp/blob/15af59969ca1ace3b11f2d94ef966e0017cb1c77/crossbarhttp/crossbarhttp.py#L126-L151
|
239,094
|
twneale/hercules
|
hercules/lazylist.py
|
LazyList.exhaust
|
def exhaust(self, index = None):
"""Exhaust the iterator generating this LazyList's values.
if index is None, this will exhaust the iterator completely.
Otherwise, it will iterate over the iterator until either the list
has a value for index or the iterator is exhausted.
"""
if self._exhausted:
return
if index is None:
ind_range = itertools.count(len(self))
else:
ind_range = range(len(self), index + 1)
for ind in ind_range:
try:
self._data.append(next(self._iterator))
except StopIteration: #iterator is fully exhausted
self._exhausted = True
break
|
python
|
def exhaust(self, index = None):
"""Exhaust the iterator generating this LazyList's values.
if index is None, this will exhaust the iterator completely.
Otherwise, it will iterate over the iterator until either the list
has a value for index or the iterator is exhausted.
"""
if self._exhausted:
return
if index is None:
ind_range = itertools.count(len(self))
else:
ind_range = range(len(self), index + 1)
for ind in ind_range:
try:
self._data.append(next(self._iterator))
except StopIteration: #iterator is fully exhausted
self._exhausted = True
break
|
[
"def",
"exhaust",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"self",
".",
"_exhausted",
":",
"return",
"if",
"index",
"is",
"None",
":",
"ind_range",
"=",
"itertools",
".",
"count",
"(",
"len",
"(",
"self",
")",
")",
"else",
":",
"ind_range",
"=",
"range",
"(",
"len",
"(",
"self",
")",
",",
"index",
"+",
"1",
")",
"for",
"ind",
"in",
"ind_range",
":",
"try",
":",
"self",
".",
"_data",
".",
"append",
"(",
"next",
"(",
"self",
".",
"_iterator",
")",
")",
"except",
"StopIteration",
":",
"#iterator is fully exhausted",
"self",
".",
"_exhausted",
"=",
"True",
"break"
] |
Exhaust the iterator generating this LazyList's values.
if index is None, this will exhaust the iterator completely.
Otherwise, it will iterate over the iterator until either the list
has a value for index or the iterator is exhausted.
|
[
"Exhaust",
"the",
"iterator",
"generating",
"this",
"LazyList",
"s",
"values",
".",
"if",
"index",
"is",
"None",
"this",
"will",
"exhaust",
"the",
"iterator",
"completely",
".",
"Otherwise",
"it",
"will",
"iterate",
"over",
"the",
"iterator",
"until",
"either",
"the",
"list",
"has",
"a",
"value",
"for",
"index",
"or",
"the",
"iterator",
"is",
"exhausted",
"."
] |
cd61582ef7e593093e9b28b56798df4203d1467a
|
https://github.com/twneale/hercules/blob/cd61582ef7e593093e9b28b56798df4203d1467a/hercules/lazylist.py#L77-L95
|
239,095
|
klmitch/policies
|
policies/parser.py
|
binary_construct
|
def binary_construct(tokens):
"""
Construct proper instructions for binary expressions from a
sequence of tokens at the same precedence level. For instance, if
the tokens represent "1 + 2 + 3", this will return the instruction
array "1 2 add_op 3 add_op".
:param tokens: The sequence of tokens.
:returns: An instance of ``Instructions`` containing the list of
instructions.
"""
# Initialize the list of instructions we will return with the
# left-most element
instructions = [tokens[0]]
# Now process all the remaining tokens, building up the array we
# will return
for i in range(1, len(tokens), 2):
op, rhs = tokens[i:i + 2]
# Add the right-hand side
instructions.append(rhs)
# Now apply constant folding
instructions[-2:] = op.fold(instructions[-2:])
return instructions
|
python
|
def binary_construct(tokens):
"""
Construct proper instructions for binary expressions from a
sequence of tokens at the same precedence level. For instance, if
the tokens represent "1 + 2 + 3", this will return the instruction
array "1 2 add_op 3 add_op".
:param tokens: The sequence of tokens.
:returns: An instance of ``Instructions`` containing the list of
instructions.
"""
# Initialize the list of instructions we will return with the
# left-most element
instructions = [tokens[0]]
# Now process all the remaining tokens, building up the array we
# will return
for i in range(1, len(tokens), 2):
op, rhs = tokens[i:i + 2]
# Add the right-hand side
instructions.append(rhs)
# Now apply constant folding
instructions[-2:] = op.fold(instructions[-2:])
return instructions
|
[
"def",
"binary_construct",
"(",
"tokens",
")",
":",
"# Initialize the list of instructions we will return with the",
"# left-most element",
"instructions",
"=",
"[",
"tokens",
"[",
"0",
"]",
"]",
"# Now process all the remaining tokens, building up the array we",
"# will return",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"tokens",
")",
",",
"2",
")",
":",
"op",
",",
"rhs",
"=",
"tokens",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"# Add the right-hand side",
"instructions",
".",
"append",
"(",
"rhs",
")",
"# Now apply constant folding",
"instructions",
"[",
"-",
"2",
":",
"]",
"=",
"op",
".",
"fold",
"(",
"instructions",
"[",
"-",
"2",
":",
"]",
")",
"return",
"instructions"
] |
Construct proper instructions for binary expressions from a
sequence of tokens at the same precedence level. For instance, if
the tokens represent "1 + 2 + 3", this will return the instruction
array "1 2 add_op 3 add_op".
:param tokens: The sequence of tokens.
:returns: An instance of ``Instructions`` containing the list of
instructions.
|
[
"Construct",
"proper",
"instructions",
"for",
"binary",
"expressions",
"from",
"a",
"sequence",
"of",
"tokens",
"at",
"the",
"same",
"precedence",
"level",
".",
"For",
"instance",
"if",
"the",
"tokens",
"represent",
"1",
"+",
"2",
"+",
"3",
"this",
"will",
"return",
"the",
"instruction",
"array",
"1",
"2",
"add_op",
"3",
"add_op",
"."
] |
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
|
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/parser.py#L45-L73
|
239,096
|
klmitch/policies
|
policies/parser.py
|
parse_rule
|
def parse_rule(name, rule_text, do_raise=False):
"""
Parses the given rule text.
:param name: The name of the rule. Used when emitting log
messages regarding a failure to parse the rule.
:param rule_text: The text of the rule to parse.
:param do_raise: If ``False`` and the rule fails to parse, a log
message is emitted to the "policies" logger at
level WARN, and a rule that always evaluates to
``False`` will be returned. If ``True``, a
``pyparsing.ParseException`` will be raised.
:returns: An instance of ``policies.instructions.Instructions``,
containing the instructions necessary to evaluate the
authorization rule.
"""
try:
return rule.parseString(rule_text, parseAll=True)[0]
except pyparsing.ParseException as exc:
# Allow for debugging
if do_raise:
raise
# Get the logger and emit our log messages
log = logging.getLogger('policies')
log.warn("Failed to parse rule %r: %s" % (name, exc))
log.warn("Rule line: %s" % exc.line)
log.warn("Location : %s^" % (" " * (exc.col - 1)))
# Construct and return a fail-closed instruction
return Instructions([Constant(False), set_authz])
|
python
|
def parse_rule(name, rule_text, do_raise=False):
"""
Parses the given rule text.
:param name: The name of the rule. Used when emitting log
messages regarding a failure to parse the rule.
:param rule_text: The text of the rule to parse.
:param do_raise: If ``False`` and the rule fails to parse, a log
message is emitted to the "policies" logger at
level WARN, and a rule that always evaluates to
``False`` will be returned. If ``True``, a
``pyparsing.ParseException`` will be raised.
:returns: An instance of ``policies.instructions.Instructions``,
containing the instructions necessary to evaluate the
authorization rule.
"""
try:
return rule.parseString(rule_text, parseAll=True)[0]
except pyparsing.ParseException as exc:
# Allow for debugging
if do_raise:
raise
# Get the logger and emit our log messages
log = logging.getLogger('policies')
log.warn("Failed to parse rule %r: %s" % (name, exc))
log.warn("Rule line: %s" % exc.line)
log.warn("Location : %s^" % (" " * (exc.col - 1)))
# Construct and return a fail-closed instruction
return Instructions([Constant(False), set_authz])
|
[
"def",
"parse_rule",
"(",
"name",
",",
"rule_text",
",",
"do_raise",
"=",
"False",
")",
":",
"try",
":",
"return",
"rule",
".",
"parseString",
"(",
"rule_text",
",",
"parseAll",
"=",
"True",
")",
"[",
"0",
"]",
"except",
"pyparsing",
".",
"ParseException",
"as",
"exc",
":",
"# Allow for debugging",
"if",
"do_raise",
":",
"raise",
"# Get the logger and emit our log messages",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'policies'",
")",
"log",
".",
"warn",
"(",
"\"Failed to parse rule %r: %s\"",
"%",
"(",
"name",
",",
"exc",
")",
")",
"log",
".",
"warn",
"(",
"\"Rule line: %s\"",
"%",
"exc",
".",
"line",
")",
"log",
".",
"warn",
"(",
"\"Location : %s^\"",
"%",
"(",
"\" \"",
"*",
"(",
"exc",
".",
"col",
"-",
"1",
")",
")",
")",
"# Construct and return a fail-closed instruction",
"return",
"Instructions",
"(",
"[",
"Constant",
"(",
"False",
")",
",",
"set_authz",
"]",
")"
] |
Parses the given rule text.
:param name: The name of the rule. Used when emitting log
messages regarding a failure to parse the rule.
:param rule_text: The text of the rule to parse.
:param do_raise: If ``False`` and the rule fails to parse, a log
message is emitted to the "policies" logger at
level WARN, and a rule that always evaluates to
``False`` will be returned. If ``True``, a
``pyparsing.ParseException`` will be raised.
:returns: An instance of ``policies.instructions.Instructions``,
containing the instructions necessary to evaluate the
authorization rule.
|
[
"Parses",
"the",
"given",
"rule",
"text",
"."
] |
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
|
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/parser.py#L369-L401
|
239,097
|
crypto101/arthur
|
arthur/util.py
|
MultiDeferred.callback
|
def callback(self, result):
"""
Callbacks the deferreds previously produced by this object.
@param result: The object which will be passed to the
C{callback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
"""
self._setResult(result)
self._isFailure = False
for d in self._deferreds:
d.callback(result)
|
python
|
def callback(self, result):
"""
Callbacks the deferreds previously produced by this object.
@param result: The object which will be passed to the
C{callback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
"""
self._setResult(result)
self._isFailure = False
for d in self._deferreds:
d.callback(result)
|
[
"def",
"callback",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_setResult",
"(",
"result",
")",
"self",
".",
"_isFailure",
"=",
"False",
"for",
"d",
"in",
"self",
".",
"_deferreds",
":",
"d",
".",
"callback",
"(",
"result",
")"
] |
Callbacks the deferreds previously produced by this object.
@param result: The object which will be passed to the
C{callback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
|
[
"Callbacks",
"the",
"deferreds",
"previously",
"produced",
"by",
"this",
"object",
"."
] |
c32e693fb5af17eac010e3b20f7653ed6e11eb6a
|
https://github.com/crypto101/arthur/blob/c32e693fb5af17eac010e3b20f7653ed6e11eb6a/arthur/util.py#L43-L57
|
239,098
|
crypto101/arthur
|
arthur/util.py
|
MultiDeferred.errback
|
def errback(self, failure):
"""
Errbacks the deferreds previously produced by this object.
@param failure: The object which will be passed to the
C{errback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
"""
self._setResult(failure)
self._isFailure = True
for d in self._deferreds:
d.errback(failure)
|
python
|
def errback(self, failure):
"""
Errbacks the deferreds previously produced by this object.
@param failure: The object which will be passed to the
C{errback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
"""
self._setResult(failure)
self._isFailure = True
for d in self._deferreds:
d.errback(failure)
|
[
"def",
"errback",
"(",
"self",
",",
"failure",
")",
":",
"self",
".",
"_setResult",
"(",
"failure",
")",
"self",
".",
"_isFailure",
"=",
"True",
"for",
"d",
"in",
"self",
".",
"_deferreds",
":",
"d",
".",
"errback",
"(",
"failure",
")"
] |
Errbacks the deferreds previously produced by this object.
@param failure: The object which will be passed to the
C{errback} method of all C{Deferred}s previously produced by
this object's C{tee} method.
@raise AlreadyCalledError: If L{callback} or L{errback} has
already been called on this object.
|
[
"Errbacks",
"the",
"deferreds",
"previously",
"produced",
"by",
"this",
"object",
"."
] |
c32e693fb5af17eac010e3b20f7653ed6e11eb6a
|
https://github.com/crypto101/arthur/blob/c32e693fb5af17eac010e3b20f7653ed6e11eb6a/arthur/util.py#L60-L74
|
239,099
|
ZeitOnline/sphinx_elasticsearch
|
src/sphinx_elasticsearch/parse_json.py
|
process_all_json_files
|
def process_all_json_files(build_dir):
"""Return a list of pages to index"""
html_files = []
for root, _, files in os.walk(build_dir):
for filename in fnmatch.filter(files, '*.fjson'):
if filename in ['search.fjson', 'genindex.fjson',
'py-modindex.fjson']:
continue
html_files.append(os.path.join(root, filename))
page_list = []
for filename in html_files:
try:
result = process_file(filename)
if result:
page_list.append(result)
# we're unsure which exceptions can be raised
except: # noqa
pass
return page_list
|
python
|
def process_all_json_files(build_dir):
"""Return a list of pages to index"""
html_files = []
for root, _, files in os.walk(build_dir):
for filename in fnmatch.filter(files, '*.fjson'):
if filename in ['search.fjson', 'genindex.fjson',
'py-modindex.fjson']:
continue
html_files.append(os.path.join(root, filename))
page_list = []
for filename in html_files:
try:
result = process_file(filename)
if result:
page_list.append(result)
# we're unsure which exceptions can be raised
except: # noqa
pass
return page_list
|
[
"def",
"process_all_json_files",
"(",
"build_dir",
")",
":",
"html_files",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"build_dir",
")",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"'*.fjson'",
")",
":",
"if",
"filename",
"in",
"[",
"'search.fjson'",
",",
"'genindex.fjson'",
",",
"'py-modindex.fjson'",
"]",
":",
"continue",
"html_files",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
")",
"page_list",
"=",
"[",
"]",
"for",
"filename",
"in",
"html_files",
":",
"try",
":",
"result",
"=",
"process_file",
"(",
"filename",
")",
"if",
"result",
":",
"page_list",
".",
"append",
"(",
"result",
")",
"# we're unsure which exceptions can be raised",
"except",
":",
"# noqa",
"pass",
"return",
"page_list"
] |
Return a list of pages to index
|
[
"Return",
"a",
"list",
"of",
"pages",
"to",
"index"
] |
cc5ebc18683439bd0949069045fcfd0290476edd
|
https://github.com/ZeitOnline/sphinx_elasticsearch/blob/cc5ebc18683439bd0949069045fcfd0290476edd/src/sphinx_elasticsearch/parse_json.py#L38-L56
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.