code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
parts = [self.include_dir(root=self.url_root)]
parts.append("index")
return "/".join(parts) | def include_path(self) | Return 'absolute' path without regarding OS path separator
This is used in ``toctree`` directives, as Sphinx always expects Unix
path separators | 10.075072 | 11.227485 | 0.897358 |
for path in self.find_files(patterns=patterns, dirs=dirs, ignore=ignore):
data = self.read_file(path=path)
if data:
self.paths[path] = data | def load(self, patterns, dirs, ignore=None) | Load objects from the filesystem into the ``paths`` dictionary. | 3.349716 | 2.73848 | 1.223203 |
self.objects[obj.id] = obj
self.all_objects[obj.id] = obj
child_stack = list(obj.children)
while child_stack:
child = child_stack.pop()
self.all_objects[child.id] = child
child_stack.extend(getattr(child, "children", ())) | def add_object(self, obj) | Add object to local and app environment storage
:param obj: Instance of a AutoAPI object | 2.543299 | 2.640722 | 0.963108 |
for path, data in self.paths.items():
for obj in self.create_class(data, options=options):
self.add_object(obj) | def map(self, options=None) | Trigger find of serialized sources and build objects | 6.43279 | 5.329451 | 1.207027 |
# TODO support JSON here
# TODO sphinx way of reporting errors in logs?
subcmd = "jsdoc"
if os.name == "nt":
subcmd = ".".join([subcmd, "cmd"])
try:
parsed_data = json.loads(subprocess.check_output([subcmd, "-X", path]))
return parsed... | def read_file(self, path, **kwargs) | Read file input into memory, returning deserialized objects
:param path: Path of file to read | 5.514472 | 5.82123 | 0.947304 |
for path, data in self.paths.items():
for item in data:
for obj in self.create_class(item, options):
obj.jinja_env = self.jinja_env
self.add_object(obj) | def map(self, options=None) | Trigger find of serialized sources and build objects | 5.620549 | 5.192876 | 1.082358 |
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["kind"]]
except (KeyError, TypeError):
LOGGER.warning("Unknown Type: %s" % data)
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
... | def create_class(self, data, options=None, **kwargs) | Return instance of class based on Javascript data
Data keys handled here:
type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data fr... | 3.356317 | 3.601073 | 0.932033 |
value = re.sub(r"[^\w\s-]", "", value).strip()
return re.sub(r"[-\s]+", "-", value) | def slugify(value) | Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace. | 2.282 | 2.424179 | 0.941349 |
raise_error = kwargs.get("raise_error", True)
all_files = set()
if not self.app.config.autoapi_file_patterns:
all_files = set()
for _file in self.find_files(
patterns=["docfx.json"], dirs=dirs, ignore=ignore
):
all_file... | def load(self, patterns, dirs, ignore=None, **kwargs) | Load objects from the filesystem into the ``paths`` dictionary.
If the setting ``autoapi_patterns`` was not specified, look for a
``docfx.json`` file by default. A ``docfx.json`` should be treated as
the canonical source before the default patterns. Fallback to default
pattern matches... | 3.155793 | 2.865482 | 1.101313 |
try:
with open(path, "r") as handle:
parsed_data = yaml.safe_load(handle)
return parsed_data
except IOError:
LOGGER.warning("Error reading file: {0}".format(path))
except TypeError:
LOGGER.warning("Error reading file: {... | def read_file(self, path, **kwargs) | Read file input into memory, returning deserialized objects
:param path: Path of file to read | 2.595097 | 2.885066 | 0.899493 |
for path, data in self.paths.items():
references = data.get("references", [])
for item in data["items"]:
for obj in self.create_class(item, options, references=references):
self.add_object(obj)
self.organize_objects() | def map(self, options=None) | Trigger find of serialized sources and build objects | 6.022876 | 5.38139 | 1.119205 |
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["type"].lower()]
except KeyError:
LOGGER.warning("Unknown type: %s" % data)
else:
obj = cls(
data,
jinja_env=self.jinja_env,
... | def create_class(self, data, options=None, path=None, **kwargs) | Return instance of class based on Roslyn type property
Data keys handled here:
type
Set the object class
items
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from Roslyn output... | 6.078378 | 6.302024 | 0.964512 |
if obj.top_level_object:
if isinstance(obj, DotNetNamespace):
self.namespaces[obj.name] = obj
self.objects[obj.id] = obj | def add_object(self, obj) | Add object to local and app environment storage
:param obj: Instance of a .NET object | 5.262076 | 5.946779 | 0.884862 |
def _render_children(obj):
for child in obj.children_strings:
child_object = self.objects.get(child)
if child_object:
obj.item_map[child_object.plural].append(child_object)
obj.children.append(child_object)
... | def organize_objects(self) | Organize objects and namespaces | 3.139873 | 2.998674 | 1.047087 |
try:
while True:
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
reftype = "any"
replacement = ""
... | def transform_doc_comments(text) | Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://m... | 2.83285 | 2.767043 | 1.023783 |
ref = self.references.get(obj_name)
if ref is None:
return obj_name
resolved = ref.get("fullName", obj_name)
spec = ref.get("spec.csharp", [])
parts = []
for part in spec:
if part.get("name") == "<":
parts.append("{")
... | def resolve_spec_identifier(self, obj_name) | Find reference name based on spec identifier
Spec identifiers are used in parameter and return type definitions, but
should be a user-friendly version instead. Use docfx ``references``
lookup mapping for resolution.
If the spec identifier reference has a ``spec.csharp`` key, this impli... | 3.125596 | 2.673234 | 1.169219 |
if self.is_undoc_member and "undoc-members" not in self.options:
return False
if self.is_private_member and "private-members" not in self.options:
return False
if self.is_special_member and "special-members" not in self.options:
return False
r... | def display(self) | Whether this object should be displayed in documentation.
This attribute depends on the configuration options given in
:confval:`autoapi_options`.
:type: bool | 2.883193 | 2.590816 | 1.112851 |
for line in self.docstring.splitlines():
line = line.strip()
if line:
return line
return "" | def summary(self) | The summary line of the docstring.
The summary line is the first non-empty line, as-per :pep:`257`.
This will be the empty string if the object does not have a docstring.
:type: str | 6.50268 | 3.602818 | 1.804887 |
resolved_name = name
for import_name, imported_as in import_names:
if import_name == name:
break
if imported_as == name:
resolved_name = import_name
break
return resolved_name | def resolve_import_alias(name, import_names) | Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple(str, str or None))
:returns: The original name.... | 2.924375 | 3.686858 | 0.793189 |
partial_basename = resolve_import_alias(name, import_from.names)
module_name = import_from.modname
if import_from.level:
module = import_from.root()
assert isinstance(module, astroid.nodes.Module)
module_name = module.relative_to_absolute_name(
import_from.modname, ... | def get_full_import_name(import_from, name) | Get the full path of a name from a ``from x import y`` statement.
:param import_from: The astroid node to resolve the name of.
:type import_from: astroid.nodes.ImportFrom
:param name:
:type name: str
:returns: The full import path of the name.
:rtype: str | 3.892268 | 3.907196 | 0.996179 |
full_basename = basename
top_level_name = re.sub(r"\(.*\)", "", basename).split(".", 1)[0]
lookup_node = node
while not hasattr(lookup_node, "lookup"):
lookup_node = lookup_node.parent
assigns = lookup_node.lookup(top_level_name)[1]
for assignment in assigns:
if isinstance(... | def get_full_basename(node, basename) | Resolve a partial base name to the full path.
:param node: The node representing the base name.
:type node: astroid.NodeNG
:param basename: The partial base name to resolve.
:type basename: str
:returns: The fully resolved base name.
:rtype: str | 2.269566 | 2.359414 | 0.961919 |
for base, basename in zip(bases, basenames):
yield get_full_basename(base, basename) | def get_full_basenames(bases, basenames) | Resolve the base nodes and partial names of a class to full names.
:param bases: The astroid node representing something that a class
inherits from.
:type bases: iterable(astroid.NodeNG)
:param basenames: The partial name of something that a class inherits from.
:type basenames: iterable(str)
... | 3.261969 | 4.354617 | 0.749083 |
try:
targets = node.targets
except AttributeError:
targets = [node.target]
if len(targets) == 1:
target = targets[0]
if isinstance(target, astroid.nodes.AssignName):
name = target.name
elif isinstance(target, astroid.nodes.AssignAttr):
na... | def get_assign_value(node) | Get the name and value of the assignment of the given node.
Assignments to multiple names are ignored, as per PEP 257.
:param node: The node to get the assignment value from.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The name that is assigned to,
and the value assi... | 2.520458 | 2.427307 | 1.038377 |
annotation = None
annotation_node = None
try:
annotation_node = node.annotation
except AttributeError:
# Python 2 has no support for type annotations, so use getattr
annotation_node = getattr(node, "type_annotation", None)
if annotation_node:
if isinstance(anno... | def get_assign_annotation(node) | Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None | 3.076786 | 3.154987 | 0.975213 |
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
... | def is_decorated_with_property(node) | Check if the function is decorated as a property.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property, False otherwise.
:rtype: bool | 2.697694 | 2.865281 | 0.941511 |
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if (
isinstance(decorator, astroid.nodes.Attribute)
and decorator.attrname == "setter"
):
return True
return False | def is_decorated_with_property_setter(node) | Check if the function is decorated as a property setter.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property setter, False otherwise.
:rtype: bool | 2.683373 | 2.511001 | 1.068647 |
return (
node.parent
and isinstance(node.parent.scope(), astroid.nodes.ClassDef)
and node.name == "__init__"
) | def is_constructor(node) | Check if the function is a constructor.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a contructor, False otherwise.
:rtype: bool | 5.241706 | 4.869615 | 1.076411 |
if (
node.name in ("Exception", "BaseException")
and node.root().name == _EXCEPTIONS_MODULE
):
return True
if not hasattr(node, "ancestors"):
return False
return any(is_exception(parent) for parent in node.ancestors(recurs=True)) | def is_exception(node) | Check if a class is an exception.
:param node: The node to check.
:type node: astroid.nodes.ClassDef
:returns: True if the class is an exception, False otherwise.
:rtype: bool | 4.146723 | 4.217701 | 0.983171 |
if not isinstance(node, astroid.ImportFrom):
return False
return (
node.level
or node.modname == package_name
or node.modname.startswith(package_name + ".")
) | def is_local_import_from(node, package_name) | Check if a node is an import from the local package.
:param node: The node to check.
:type node: astroid.node.NodeNG
:param package_name: The name of the local package.
:type package_name: str
:returns: True if the node is an import from the local package,
False otherwise.
:rtype: boo... | 2.844322 | 3.258886 | 0.87279 |
all_ = None
if "__all__" in node.locals:
assigned = next(node.igetattr("__all__"))
if assigned is not astroid.Uninferable:
all_ = []
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
excep... | def get_module_all(node) | Get the contents of the ``__all__`` variable from a module.
:param node: The module to get ``__all__`` from.
:type node: astroid.nodes.Module
:returns: The contents of ``__all__`` if defined. Otherwise None.
:rtype: list(str) or None | 3.071473 | 2.709789 | 1.133473 |
if not app.config.autoapi_dirs:
raise ExtensionError("You must configure an autoapi_dirs setting")
# Make sure the paths are full
normalized_dirs = []
autoapi_dirs = app.config.autoapi_dirs
if isinstance(autoapi_dirs, str):
autoapi_dirs = [autoapi_dirs]
for path in autoapi... | def run_autoapi(app) | Load AutoAPI data from the filesystem. | 2.257509 | 2.225307 | 1.014471 |
if app.env.docname == "index":
all_docs = set()
insert = True
nodes = doctree.traverse(toctree)
toc_entry = "%s/index" % app.config.autoapi_root
add_entry = (
nodes
and app.config.autoapi_generate_api_docs
and app.config.autoapi_add_to... | def doctree_read(app, doctree) | Inject AutoAPI into the TOC Tree dynamically. | 3.838489 | 3.637739 | 1.055185 |
originals = originals_map.values()
if original_module["all"] is not None:
originals = []
for name in original_module["all"]:
if name == "__all__":
continue
if name not in originals_map:
msg = "Invalid __all__ entry {0} in {1}".format(... | def _expand_wildcard_placeholder(original_module, originals_map, placeholder) | Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the names of children under the module
to their data dictionaries.
... | 2.41518 | 2.37418 | 1.017269 |
if module_name in resolved:
return
visit_path[module_name] = True
module, children = modules[module_name]
for child in list(children.values()):
if child["type"] != "placeholder":
continue
if child["original_path"] in modules:
module["children"].rem... | def _resolve_module_placeholders(modules, module_name, visit_path, resolved) | Resolve all placeholder children under a module.
:param modules: A mapping of module names to their data dictionary.
Placeholders are resolved in place.
:type modules: dict(str, dict)
:param module_name: The name of the module to resolve.
:type module_name: str
:param visit_path: An ordered... | 2.20981 | 2.16764 | 1.019454 |
new = copy.deepcopy(original)
# The name remains the same.
new["name"] = placeholder["name"]
new["full_name"] = placeholder["full_name"]
# Record where the placeholder originally came from.
new["original_path"] = original["full_name"]
# The source lines for this placeholder do not exist... | def _resolve_placeholder(placeholder, original) | Resolve a placeholder to the given original object.
:param placeholder: The placeholder to resolve, in place.
:type placeholder: dict
:param original: The object that the placeholder represents.
:type original: dict | 2.945906 | 3.044626 | 0.967576 |
for dir_ in dirs:
dir_root = dir_
if os.path.exists(os.path.join(dir_, "__init__.py")):
dir_root = os.path.abspath(os.path.join(dir_, os.pardir))
for path in self.find_files(patterns=patterns, dirs=[dir_], ignore=ignore):
data = self.... | def load(self, patterns, dirs, ignore=None) | Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module | 2.503104 | 2.447724 | 1.022625 |
try:
parsed_data = Parser().parse_file(path)
return parsed_data
except (IOError, TypeError, ImportError):
LOGGER.warning("Error reading file: {0}".format(path))
return None | def read_file(self, path, **kwargs) | Read file input into memory, returning deserialized objects
:param path: Path of file to read | 5.203558 | 5.880997 | 0.884809 |
modules = {}
for module in self.paths.values():
children = {child["name"]: child for child in module["children"]}
modules[module["name"]] = (module, children)
resolved = set()
for module_name in modules:
visit_path = collections.OrderedDict()... | def _resolve_placeholders(self) | Resolve objects that have been imported from elsewhere. | 4.911874 | 4.614796 | 1.064375 |
obj_map = dict(
(cls.type, cls)
for cls in [
PythonClass,
PythonFunction,
PythonModule,
PythonMethod,
PythonPackage,
PythonAttribute,
PythonData,
Pytho... | def create_class(self, data, options=None, **kwargs) | Create a class from the passed in data
:param data: dictionary data of parser output | 2.939186 | 3.092891 | 0.950304 |
reference = nodes.reference(
"",
"",
internal=True,
refuri=docname,
anchorname="#" + anchor,
*[nodes.Text(text, text)]
)
para = addnodes.compact_paragraph("", "", reference)
ret_list = nodes.list_item("", para)
return nodes.bullet_list("", ret_lis... | def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False) | Create the node structure that Sphinx expects for TOC Tree entries.
The ``bullet`` argument wraps it in a ``nodes.bullet_list``,
which is how you nest TOC Tree entries. | 3.377829 | 3.550569 | 0.951349 |
curr_node = node.parent
while curr_node is not None:
if isinstance(curr_node, objtypes):
return curr_node
curr_node = curr_node.parent
return None | def _traverse_parent(node, objtypes) | Traverse up the node's parents until you hit the ``objtypes`` referenced.
Can either be a single type,
or a tuple of types. | 2.066214 | 2.47787 | 0.833867 |
for check_node in toc.traverse(nodes.reference):
if objtype == nodes.section and (
check_node.attributes["refuri"] == ref_id
or check_node.attributes["anchorname"] == "#" + ref_id
):
return check_node
if (
objtype == addnodes.desc
... | def _find_toc_node(toc, ref_id, objtype) | Find the actual TOC node for a ref_id.
Depends on the object type:
* Section - First section (refuri) or 2nd+ level section (anchorname)
* Desc - Just use the anchor name | 3.589181 | 3.338615 | 1.075051 |
if isinstance(node, nodes.section) and isinstance(node.parent, nodes.document):
# Top Level Section header
ref_id = docname
toc_reference = _find_toc_node(toc, ref_id, nodes.section)
elif isinstance(node, nodes.section):
# Nested Section header
ref_id = node.attribut... | def _get_toc_reference(app, node, toc, docname) | Logic that understands maps a specific node to it's part of the toctree.
It takes a specific incoming ``node``,
and returns the actual TOC Tree node that is said reference. | 2.694498 | 2.767676 | 0.97356 |
toc = app.env.tocs[docname]
for desc_node in doctree.traverse(addnodes.desc):
try:
ref_id = desc_node.children[0].attributes["ids"][0]
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
continue
try:
# Pyth... | def add_domain_to_toctree(app, doctree, docname) | Add domain objects to the toctree dynamically.
This should be attached to the ``doctree-resolved`` event.
This works by:
* Finding each domain node (addnodes.desc)
* Figuring out it's parent that will be in the toctree
(nodes.section, or a previously added addnodes.desc)
* Finding that pa... | 4.764838 | 4.353726 | 1.094428 |
self.warnings.append(
self.state.document.reporter.warning(msg, line=self.lineno)
) | def warn(self, msg) | Add a warning message.
:param msg: The warning message to add.
:type msg: str | 5.190199 | 5.751363 | 0.902429 |
for line in self.content:
line = line.strip()
if line and re.search("^[a-zA-Z0-9]", line):
yield line | def _get_names(self) | Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str) | 4.583024 | 4.833373 | 0.948204 |
days = duration.days
hours = int(duration.seconds / 3600)
minutes = int(duration.seconds % 3600 / 60)
seconds = int(duration.seconds % 3600 % 60)
parts = []
if days > 0:
parts.append(u'%s %s' % (days, pluralize(days, _('day,days'))))
if hours > 0:
parts.append(u'%s %s'... | def humanize_duration(duration) | Returns a humanized string representing time difference
For example: 2 days 1 hour 25 minutes 10 seconds | 1.547685 | 1.61556 | 0.957987 |
with CronJobManager(cron_class, silent) as manager:
manager.run(force) | def run_cron_with_cache_check(cron_class, force=False, silent=False) | Checks the cache and runs the cron or not.
@cron_class - cron class to run.
@force - run job even if not scheduled
@silent - suppress notifications | 6.257452 | 7.376805 | 0.848261 |
if hasattr(settings, 'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'):
delta = timedelta(days=settings.DJANGO_CRON_DELETE_LOGS_OLDER_THAN)
CronJobLog.objects.filter(end_time__lt=get_current_time() - delta).delete() | def clear_old_log_entries() | Removes older log entries, if the appropriate setting has been set | 3.017002 | 2.972563 | 1.01495 |
cron_classes = options['cron_classes']
if cron_classes:
cron_class_names = cron_classes
else:
cron_class_names = getattr(settings, 'CRON_CLASSES', [])
try:
crons_to_run = [get_class(x) for x in cron_class_names]
except Exception:
... | def handle(self, *args, **options) | Iterates over all the CRON_CLASSES (or if passed in as a commandline argument)
and runs them. | 3.254655 | 2.882827 | 1.12898 |
from django_cron.models import CronJobLog
cron_job = self.cron_job
self.user_time = None
self.previously_ran_successful_cron = None
# If we pass --force options, we force cron run
if force:
return True
if cron_job.schedule.run_every_mins is ... | def should_run_now(self, force=False) | Returns a boolean determining whether this cron should run now or not! | 2.366506 | 2.337201 | 1.012538 |
cron_job_class = self.cron_job_class
if not issubclass(cron_job_class, CronJobBase):
raise Exception('The cron_job to be run must be a subclass of %s' % CronJobBase.__name__)
with self.lock_class(cron_job_class, self.silent):
self.cron_job = cron_job_class()
... | def run(self, force=False) | apply the logic of the schedule and call do() on the CronJobBase class | 4.18108 | 3.782948 | 1.105244 |
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | def lock(self) | This method sets a cache variable to mark current job as "already running". | 3.67432 | 3.181597 | 1.154867 |
path = app_settings.INVITATION_MODEL
try:
return django_apps.get_model(path)
except ValueError:
raise ImproperlyConfigured(
"path must be of the form 'app_label.model_name'"
)
except LookupError:
raise ImproperlyConfigured(
"path refers to mod... | def get_invitation_model() | Returns the Invitation model that is active in this project. | 3.258726 | 3.065333 | 1.06309 |
subject = render_to_string('{0}_subject.txt'.format(template_prefix),
context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
subject = self.format_email_subject(subject)
bodies = {}
for ext i... | def render_mail(self, template_prefix, email, context) | Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation" | 2.095665 | 2.155287 | 0.972337 |
response = await self.docker._query_json("images/json", "GET", params=params)
return response | async def list(self, **params) -> Mapping | List of images | 10.463301 | 8.130452 | 1.286927 |
response = await self.docker._query_json("images/{name}/json".format(name=name))
return response | async def inspect(self, name: str) -> Mapping | Return low-level information about an image
Args:
name: name of the image | 8.784246 | 8.167962 | 1.075451 |
image = from_image # TODO: clean up
params = {"fromImage": image}
headers = {}
if repo:
params["repo"] = repo
if tag:
params["tag"] = tag
if auth is not None:
registry, has_registry_host, _ = image.partition("/")
i... | async def pull(
self,
from_image: str,
*,
auth: Optional[Union[MutableMapping, str, bytes]] = None,
tag: str = None,
repo: str = None,
stream: bool = False
) -> Mapping | Similar to `docker pull`, pull an image locally
Args:
fromImage: name of the image to pull
repo: repository name given to an image when it is imported
tag: if empty when pulling an image all tags
for the given image to be pulled
auth: special {'a... | 4.356394 | 4.771873 | 0.912932 |
params = {"repo": repo}
if tag:
params["tag"] = tag
await self.docker._query(
"images/{name}/tag".format(name=name),
"POST",
params=params,
headers={"content-type": "application/json"},
)
return True | async def tag(self, name: str, repo: str, *, tag: str = None) -> bool | Tag the given image so that it becomes part of a repository.
Args:
repo: the repository to tag in
tag: the name for the new tag | 3.51722 | 3.771245 | 0.932642 |
params = {"force": force, "noprune": noprune}
response = await self.docker._query_json(
"images/{name}".format(name=name), "DELETE", params=params
)
return response | async def delete(
self, name: str, *, force: bool = False, noprune: bool = False
) -> List | Remove an image along with any untagged parent
images that were referenced by that image
Args:
name: name/id of the image to delete
force: remove the image even if it is being used
by stopped containers or has other tags
noprune: don't delete untag... | 3.49721 | 3.795949 | 0.921301 |
local_context = None
headers = {}
params = {
"t": tag,
"rm": rm,
"q": quiet,
"pull": pull,
"remote": remote,
"nocache": nocache,
"forcerm": forcerm,
"dockerfile": path_dockerfile,
... | async def build(
self,
*,
remote: str = None,
fileobj: BinaryIO = None,
path_dockerfile: str = None,
tag: str = None,
quiet: bool = False,
nocache: bool = False,
buildargs: Mapping = None,
pull: bool = False,
rm: bool = True,
... | Build an image given a remote Dockerfile
or a file object with a Dockerfile inside
Args:
path_dockerfile: path within the build context to the Dockerfile
remote: a Git repository URI or HTTP/HTTPS context URI
quiet: suppress verbose build output
nocache: ... | 2.54018 | 2.624955 | 0.967704 |
response = await self.docker._query(
"images/{name}/get".format(name=name), "GET"
)
return response.content | async def export_image(self, name: str) | Get a tarball of an image by name or id.
Args:
name: name/id of the image to be exported
Returns:
Streamreader of tarball image | 8.242966 | 6.597765 | 1.249357 |
headers = {"Content-Type": "application/x-tar"}
response = await self.docker._query_chunked_post(
"images/load", "POST", data=data, headers=headers
)
return await json_stream_result(response, stream=stream) | async def import_image(self, data, stream: bool = False) | Import tarball of image to docker.
Args:
data: tarball data of image to be imported
Returns:
Tarball of the image | 6.734717 | 6.951302 | 0.968843 |
if response_type is None:
ct = response.headers.get("content-type")
if ct is None:
cl = response.headers.get("content-length")
if cl is None or cl == "0":
return ""
raise TypeError(
"Cannot auto-detect response type "
... | async def parse_result(response, response_type=None, *, encoding="utf-8") | Convert the response to native objects by the given response type
or the auto-detected HTTP content-type.
It also ensures release of the response object. | 2.241379 | 2.211528 | 1.013498 |
pieces = ct.split(";")
try:
main_type, sub_type = pieces[0].split("/")
except ValueError:
msg = 'Invalid mime-type component: "{0}"'.format(pieces[0])
raise ValueError(msg)
if len(pieces) > 1:
options = {}
for opt in pieces[1:]:
opt = opt.strip()
... | def parse_content_type(ct: str) -> Tuple[str, str, Mapping[str, str]] | Decompose the value of HTTP "Content-Type" header into
the main/sub MIME types and other extra options as a dictionary.
All parsed values are lower-cased automatically. | 1.95521 | 1.811835 | 1.079132 |
return {k: v for k, v in obj.items() if v is not None} | def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any] | Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object. | 2.78728 | 2.917657 | 0.955315 |
if value is None:
return key
if isinstance(value, bytes):
value = value.decode("utf-8")
return "{key}={value}".format(key=key, value=value) | def format_env(key, value: Union[None, bytes, str]) -> str | Formats envs from {key:value} to ['key=value'] | 2.572897 | 2.062628 | 1.247387 |
if not networks:
return networks
if not isinstance(networks, list):
raise TypeError("networks parameter must be a list.")
result = []
for n in networks:
if isinstance(n, str):
n = {"Target": n}
result.append(n)
return result | def clean_networks(networks: Iterable[str] = None) -> Optional[Iterable[str]] | Cleans the values inside `networks`
Returns a new list | 3.436419 | 3.492877 | 0.983836 |
if filters and isinstance(filters, dict):
for k, v in filters.items():
if not isinstance(v, list):
v = [v]
filters[k] = v
return json.dumps(filters) | def clean_filters(filters: Mapping = None) -> str | Checks the values inside `filters`
https://docs.docker.com/engine/api/v1.29/#operation/ServiceList
Returns a new dictionary in the format `map[string][]string` jsonized | 2.767907 | 2.694746 | 1.027149 |
f = tempfile.NamedTemporaryFile()
t = tarfile.open(mode="w:gz", fileobj=f)
if isinstance(fileobject, BytesIO):
dfinfo = tarfile.TarInfo("Dockerfile")
dfinfo.size = len(fileobject.getvalue())
fileobject.seek(0)
else:
dfinfo = t.gettarinfo(fileobj=fileobject, arcname... | def mktar_from_dockerfile(fileobject: BinaryIO) -> IO | Create a zipped tar archive from a Dockerfile
**Remember to close the file object**
Args:
fileobj: a Dockerfile
Returns:
a NamedTemporaryFile() object | 2.257226 | 2.15433 | 1.047763 |
if isinstance(auth, Mapping):
# Validate the JSON format only.
if "identitytoken" in auth:
pass
elif "auth" in auth:
return compose_auth_header(auth["auth"], registry_addr)
else:
if registry_addr:
auth["serveraddress"] = regist... | def compose_auth_header(
auth: Union[MutableMapping, str, bytes], registry_addr: str = None
) -> str | Validate and compose base64-encoded authentication header
with an optional support for parsing legacy-style "user:password"
strings.
Args:
auth: Authentication information
registry_addr: An address of the registry server
Returns:
A base64-encoded X-Registry-Auth header value | 2.943621 | 2.931031 | 1.004295 |
response = await self.docker._query_json(
"tasks/{task_id}".format(task_id=task_id), method="GET"
)
return response | async def inspect(self, task_id: str) -> Mapping[str, Any] | Return info about a task
Args:
task_id: is ID of the task | 5.11141 | 4.922707 | 1.038333 |
try:
container = await self.create(config, name=name)
except DockerError as err:
# image not find, try pull it
if err.status == 404 and "Image" in config:
await self.docker.pull(config["Image"])
container = await self.create(co... | async def run(self, config, *, name=None) | Create and start a container.
If container.start() will raise an error the exception will contain
a `container_id` attribute with the id of the container. | 3.294479 | 2.905661 | 1.133814 |
if create_task and not self.task:
self.task = asyncio.ensure_future(self.run(**params))
return self.channel.subscribe() | def subscribe(self, *, create_task=True, **params) | Subscribes to the Docker events channel. Use the keyword argument
create_task=False to prevent automatically spawning the background
tasks that listen to the events.
This function returns a ChannelSubscriber object. | 4.449753 | 4.680683 | 0.950663 |
if self.json_stream:
warnings.warn("already running", RuntimeWarning, stackelevel=2)
return
forced_params = {"stream": True}
params = ChainMap(forced_params, params)
try:
# timeout has to be set to 0, None is not passed
# Otherwise... | async def run(self, **params) | Query the events endpoint of the Docker daemon.
Publish messages inside the asyncio queue. | 5.318062 | 4.867548 | 1.092555 |
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="GET"
)
return response | async def inspect(self, *, node_id: str) -> Mapping[str, Any] | Inspect a node
Args:
node_id: The ID or name of the node | 5.248291 | 5.967693 | 0.879451 |
params = {"version": version}
if "Role" in spec:
assert spec["Role"] in {"worker", "manager"}
if "Availability" in spec:
assert spec["Availability"] in {"active", "pause", "drain"}
response = await self.docker._query_json(
"nodes/{node_id}... | async def update(
self, *, node_id: str, version: int, spec: Mapping[str, Any]
) -> Mapping[str, Any] | Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be updated | 3.75692 | 4.069678 | 0.923149 |
params = {"force": force}
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="DELETE", params=params
)
return response | async def remove(self, *, node_id: str, force: bool = False) -> Mapping[str, Any] | Remove a node from a swarm.
Args:
node_id: The ID or name of the node | 3.996316 | 5.491254 | 0.72776 |
url = self._canonicalize_url(path)
if headers and "content-type" not in headers:
headers["content-type"] = "application/json"
try:
response = await self.session.request(
method,
url,
params=httpize(params),
... | async def _query(
self,
path,
method="GET",
*,
params=None,
data=None,
headers=None,
timeout=None,
chunked=None
) | Get the response object by performing the HTTP request.
The caller is responsible to finalize the response object. | 2.411023 | 2.34801 | 1.026837 |
if headers is None:
headers = {}
headers["content-type"] = "application/json"
if not isinstance(data, (str, bytes)):
data = json.dumps(data)
response = await self._query(
path, method, params=params, data=data, headers=headers, timeout=timeout... | async def _query_json(
self, path, method="GET", *, params=None, data=None, headers=None, timeout=None
) | A shorthand of _query() that treats the input as JSON. | 2.341875 | 2.074439 | 1.12892 |
if headers is None:
headers = {}
if headers and "content-type" not in headers:
headers["content-type"] = "application/octet-stream"
response = await self._query(
path,
method,
params=params,
data=data,
h... | async def _query_chunked_post(
self, path, method="POST", *, params=None, data=None, headers=None, timeout=None
) | A shorthand for uploading data by chunks | 2.067976 | 1.858662 | 1.112615 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.set_ciphers(ssl._RESTRICTED_SERVER_CIPHERS)
certs_path = os.environ.get("DOCKER_CERT_PATH", None)
if certs_path is None:
raise ValueError(
"Cannot create ssl context, " "DOCKER_CERT_PATH is not set!"
... | def _docker_machine_ssl_context() | Create a SSLContext object using DOCKER_* env vars. | 2.22279 | 2.105047 | 1.055934 |
data = {
"AdvertiseAddr": advertise_addr,
"ListenAddr": listen_addr,
"ForceNewCluster": force_new_cluster,
"Spec": swarm_spec,
}
response = await self.docker._query_json("swarm/init", method="POST", data=data)
return response | async def init(
self,
*,
advertise_addr: str = None,
listen_addr: str = "0.0.0.0:2377",
force_new_cluster: bool = False,
swarm_spec: Mapping = None
) -> str | Initialize a new swarm.
Args:
ListenAddr: listen address used for inter-manager communication
AdvertiseAddr: address advertised to other nodes.
ForceNewCluster: Force creation of a new swarm.
SwarmSpec: User modifiable swarm configuration.
Returns:
... | 2.865484 | 3.293539 | 0.870032 |
data = {
"RemoteAddrs": list(remote_addrs),
"JoinToken": join_token,
"ListenAddr": listen_addr,
"AdvertiseAddr": advertise_addr,
"DataPathAddr": data_path_addr,
}
await self.docker._query("swarm/join", method="POST", data=cle... | async def join(
self,
*,
remote_addrs: Iterable[str],
listen_addr: str = "0.0.0.0:2377",
join_token: str,
advertise_addr: str = None,
data_path_addr: str = None
) -> bool | Join a swarm.
Args:
listen_addr
Used for inter-manager communication
advertise_addr
Externally reachable address advertised to other nodes.
data_path_addr
Address or interface to use for data path traffic.
remote... | 3.345597 | 3.578297 | 0.934969 |
params = {"force": force}
await self.docker._query("swarm/leave", method="POST", params=params)
return True | async def leave(self, *, force: bool = False) -> bool | Leave a swarm.
Args:
force: force to leave the swarm even if the node is a master | 9.468158 | 10.022107 | 0.944727 |
params = {"filters": clean_filters(filters)}
response = await self.docker._query_json(
"services", method="GET", params=params
)
return response | async def list(self, *, filters: Mapping = None) -> List[Mapping] | Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name=<service name> | 6.510499 | 7.905237 | 0.823568 |
if "Image" not in task_template["ContainerSpec"]:
raise KeyError("Missing mandatory Image key in ContainerSpec")
if auth and registry is None:
raise KeyError(
"When auth is specified you need to specifiy also the registry"
)
# from ... | async def create(
self,
task_template: Mapping[str, Any],
*,
name: str = None,
labels: List = None,
mode: Mapping = None,
update_config: Mapping = None,
rollback_config: Mapping = None,
networks: List = None,
endpoint_spec: Mapping = None,
... | Create a service
Args:
task_template: user modifiable task configuration
name: name of the service
labels: user-defined key/value metadata
mode: scheduling mode for the service
update_config: update strategy of the service
rollback_config:... | 2.838605 | 2.848143 | 0.996651 |
if image is None and rollback is False:
raise ValueError("You need to specify an image.")
inspect_service = await self.inspect(service_id)
spec = inspect_service["Spec"]
if image is not None:
spec["TaskTemplate"]["ContainerSpec"]["Image"] = image
... | async def update(
self,
service_id: str,
version: str,
*,
image: str = None,
rollback: bool = False
) -> bool | Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.
Returns:
True if succe... | 3.291282 | 3.280961 | 1.003146 |
await self.docker._query(
"services/{service_id}".format(service_id=service_id), method="DELETE"
)
return True | async def delete(self, service_id: str) -> bool | Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful | 6.7925 | 6.209588 | 1.093873 |
response = await self.docker._query_json(
"services/{service_id}".format(service_id=service_id), method="GET"
)
return response | async def inspect(self, service_id: str) -> Mapping[str, Any] | Inspect a service
Args:
service_id: ID or name of the service
Returns:
a dict with info about a service | 5.433629 | 5.070393 | 1.071639 |
if stdout is False and stderr is False:
raise TypeError("Need one of stdout or stderr")
params = {
"details": details,
"follow": follow,
"stdout": stdout,
"stderr": stderr,
"since": since,
"timestamps": timesta... | async def logs(
self,
service_id: str,
*,
details: bool = False,
follow: bool = False,
stdout: bool = False,
stderr: bool = False,
since: int = 0,
timestamps: bool = False,
is_tty: bool = False,
tail: str = "all"
) -> Union[str,... | Retrieve logs of the given service
Args:
details: show service context and extra details provided to logs
follow: return the logs as a stream.
stdout: return logs from stdout
stderr: return logs from stderr
since: return logs since this time, as a UNI... | 2.730489 | 2.935296 | 0.930226 |
if not hash_name in self.buckets:
self.buckets[hash_name] = {}
if not bucket_key in self.buckets[hash_name]:
self.buckets[hash_name][bucket_key] = []
self.buckets[hash_name][bucket_key].append((v, data)) | def store_vector(self, hash_name, bucket_key, v, data) | Stores vector and JSON-serializable data in bucket with specified key. | 1.709873 | 1.743207 | 0.980878 |
if data is None:
data = itertools.repeat(data)
for v, k, d in zip(vs, bucket_keys, data):
self.store_vector(hash_name, k, v, d) | def store_many_vectors(self, hash_name, bucket_keys, vs, data) | Store a batch of vectors.
Stores vector and JSON-serializable data in bucket with specified key. | 3.032614 | 2.958634 | 1.025005 |
for key in bucket_keys:
bucket = self.get_bucket(hash_name, key)
bucket[:] = [(v, id_data) for v, id_data
in bucket if id_data != data] | def delete_vector(self, hash_name, bucket_keys, data) | Deletes vector and JSON-serializable data in buckets with specified keys. | 4.438119 | 4.39483 | 1.00985 |
if hash_name in self.buckets:
if bucket_key in self.buckets[hash_name]:
return self.buckets[hash_name][bucket_key]
return [] | def get_bucket(self, hash_name, bucket_key) | Returns bucket content as list of tuples (vector, data). | 2.101647 | 1.803888 | 1.165065 |
# First increase vector count of this subtree
self.vector_count = self.vector_count + 1
if tree_depth < len(bucket_key):
hash_char = bucket_key[tree_depth]
# This is not the leaf so continue down into the tree towards the leafes
#print 'hash_char=... | def insert_entry_for_bucket(self, bucket_key, tree_depth) | Increases counter for specified bucket_key (leaf of tree) and
also increases counters along the way from the root to the leaf. | 4.129347 | 4.15795 | 0.993121 |
if len(self.childs) == 0:
# This is a leaf so just return the bucket key (we reached the bucket leaf)
#print 'Returning (collect) leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
return [self.bucket_key]
# Not leaf, return results o... | def collect_all_bucket_keys(self) | Just collects all buckets keys from subtree | 4.867591 | 4.640388 | 1.048962 |
if tree_depth == len(bucket_key):
#print 'Returning leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
# This is a leaf so just return the bucket key (we reached the bucket leaf)
return [self.bucket_key]
# If not leaf, this is a subt... | def bucket_keys_to_guarantee_result_set_size(self, bucket_key, N, tree_depth) | Returns list of bucket keys based on the specified bucket key
and minimum result size N. | 3.263419 | 3.224225 | 1.012156 |
if self.dim != dim:
self.dim = dim
self.normals = self.rand.randn(self.projection_count, dim)
self.tree_root = RandomBinaryProjectionTreeNode() | def reset(self, dim) | Resets / Initializes the hash for the specified dimension. | 10.464848 | 9.906463 | 1.056366 |
if scipy.sparse.issparse(v):
# If vector is sparse, make sure we have the CSR representation
# of the projection matrix
if self.normals_csr == None:
self.normals_csr = scipy.sparse.csr_matrix(self.normals)
# Make sure that we are using CSR... | def hash_vector(self, v, querying=False) | Hashes the vector and returns the binary bucket key as string. | 4.997781 | 4.704409 | 1.062361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.