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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
248,100 | azogue/dataweb | dataweb/classdataweb.py | DataWeb.info_data | def info_data(self, data_info=None, completo=True, key=None, verbose=True):
"""Show some info."""
def _info_dataframe(data_frame):
if completo:
print('\n', data_frame.info(), '\n', data_frame.describe(), '\n')
print(data_frame.head())
print(data_frame.tail())
if verbose:
if data_info is None:
_info_dataframe(self.data[key or self.masterkey])
elif type(data_info) is dict:
[_info_dataframe(df) for df in data_info.values()]
else:
_info_dataframe(data_info) | python | def info_data(self, data_info=None, completo=True, key=None, verbose=True):
"""Show some info."""
def _info_dataframe(data_frame):
if completo:
print('\n', data_frame.info(), '\n', data_frame.describe(), '\n')
print(data_frame.head())
print(data_frame.tail())
if verbose:
if data_info is None:
_info_dataframe(self.data[key or self.masterkey])
elif type(data_info) is dict:
[_info_dataframe(df) for df in data_info.values()]
else:
_info_dataframe(data_info) | [
"def",
"info_data",
"(",
"self",
",",
"data_info",
"=",
"None",
",",
"completo",
"=",
"True",
",",
"key",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"def",
"_info_dataframe",
"(",
"data_frame",
")",
":",
"if",
"completo",
":",
"print",
"(",
"'\\n'",
",",
"data_frame",
".",
"info",
"(",
")",
",",
"'\\n'",
",",
"data_frame",
".",
"describe",
"(",
")",
",",
"'\\n'",
")",
"print",
"(",
"data_frame",
".",
"head",
"(",
")",
")",
"print",
"(",
"data_frame",
".",
"tail",
"(",
")",
")",
"if",
"verbose",
":",
"if",
"data_info",
"is",
"None",
":",
"_info_dataframe",
"(",
"self",
".",
"data",
"[",
"key",
"or",
"self",
".",
"masterkey",
"]",
")",
"elif",
"type",
"(",
"data_info",
")",
"is",
"dict",
":",
"[",
"_info_dataframe",
"(",
"df",
")",
"for",
"df",
"in",
"data_info",
".",
"values",
"(",
")",
"]",
"else",
":",
"_info_dataframe",
"(",
"data_info",
")"
] | Show some info. | [
"Show",
"some",
"info",
"."
] | 085035855df7cef0fe7725bbe9a706832344d946 | https://github.com/azogue/dataweb/blob/085035855df7cef0fe7725bbe9a706832344d946/dataweb/classdataweb.py#L236-L251 |
248,101 | jabbas/pynapi | pynapi/__init__.py | list_services | def list_services():
""" returns list of available services """
for importer, modname, ispkg in pkgutil.iter_modules(services.__path__):
if ispkg is False:
importer.find_module(modname).load_module(modname)
services_list = list()
for s in services.serviceBase.__subclasses__():
services_list.append(s.__name__.lower())
return services_list | python | def list_services():
""" returns list of available services """
for importer, modname, ispkg in pkgutil.iter_modules(services.__path__):
if ispkg is False:
importer.find_module(modname).load_module(modname)
services_list = list()
for s in services.serviceBase.__subclasses__():
services_list.append(s.__name__.lower())
return services_list | [
"def",
"list_services",
"(",
")",
":",
"for",
"importer",
",",
"modname",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"services",
".",
"__path__",
")",
":",
"if",
"ispkg",
"is",
"False",
":",
"importer",
".",
"find_module",
"(",
"modname",
")",
".",
"load_module",
"(",
"modname",
")",
"services_list",
"=",
"list",
"(",
")",
"for",
"s",
"in",
"services",
".",
"serviceBase",
".",
"__subclasses__",
"(",
")",
":",
"services_list",
".",
"append",
"(",
"s",
".",
"__name__",
".",
"lower",
"(",
")",
")",
"return",
"services_list"
] | returns list of available services | [
"returns",
"list",
"of",
"available",
"services"
] | d9b3b4d9cd05501c14fe5cc5903b1c21e1905753 | https://github.com/jabbas/pynapi/blob/d9b3b4d9cd05501c14fe5cc5903b1c21e1905753/pynapi/__init__.py#L9-L19 |
248,102 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.create_model_class | def create_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None,
other_bases=None):
"""Creates a new class derived from ModelBase."""
members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
if otherattrs:
members.update(otherattrs)
return type(name, other_bases or (), members) | python | def create_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None,
other_bases=None):
"""Creates a new class derived from ModelBase."""
members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
if otherattrs:
members.update(otherattrs)
return type(name, other_bases or (), members) | [
"def",
"create_model_class",
"(",
"cls",
",",
"name",
",",
"table_name",
",",
"attrs",
",",
"validations",
"=",
"None",
",",
"*",
",",
"otherattrs",
"=",
"None",
",",
"other_bases",
"=",
"None",
")",
":",
"members",
"=",
"dict",
"(",
"table_name",
"=",
"table_name",
",",
"attrs",
"=",
"attrs",
",",
"validations",
"=",
"validations",
"or",
"[",
"]",
")",
"if",
"otherattrs",
":",
"members",
".",
"update",
"(",
"otherattrs",
")",
"return",
"type",
"(",
"name",
",",
"other_bases",
"or",
"(",
")",
",",
"members",
")"
] | Creates a new class derived from ModelBase. | [
"Creates",
"a",
"new",
"class",
"derived",
"from",
"ModelBase",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L33-L39 |
248,103 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.has_attr | def has_attr(cls, attr_name):
"""Check to see if an attribute is defined for the model."""
if attr_name in cls.attrs:
return True
if isinstance(cls.primary_key_name, str) and cls.primary_key_name == attr_name:
return True
if isinstance(cls.primary_key_name, tuple) and attr_name in cls.primary_key_name:
return True
if cls.timestamps is not None and attr_name in cls.timestamps:
return True
return False | python | def has_attr(cls, attr_name):
"""Check to see if an attribute is defined for the model."""
if attr_name in cls.attrs:
return True
if isinstance(cls.primary_key_name, str) and cls.primary_key_name == attr_name:
return True
if isinstance(cls.primary_key_name, tuple) and attr_name in cls.primary_key_name:
return True
if cls.timestamps is not None and attr_name in cls.timestamps:
return True
return False | [
"def",
"has_attr",
"(",
"cls",
",",
"attr_name",
")",
":",
"if",
"attr_name",
"in",
"cls",
".",
"attrs",
":",
"return",
"True",
"if",
"isinstance",
"(",
"cls",
".",
"primary_key_name",
",",
"str",
")",
"and",
"cls",
".",
"primary_key_name",
"==",
"attr_name",
":",
"return",
"True",
"if",
"isinstance",
"(",
"cls",
".",
"primary_key_name",
",",
"tuple",
")",
"and",
"attr_name",
"in",
"cls",
".",
"primary_key_name",
":",
"return",
"True",
"if",
"cls",
".",
"timestamps",
"is",
"not",
"None",
"and",
"attr_name",
"in",
"cls",
".",
"timestamps",
":",
"return",
"True",
"return",
"False"
] | Check to see if an attribute is defined for the model. | [
"Check",
"to",
"see",
"if",
"an",
"attribute",
"is",
"defined",
"for",
"the",
"model",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L42-L56 |
248,104 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.primary_key | def primary_key(self):
"""Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key.
"""
pkname = self.primary_key_name
if pkname is None:
return None
elif isinstance(pkname, str):
return getattr(self, pkname)
else:
return tuple((getattr(self, pkn) for pkn in pkname)) | python | def primary_key(self):
"""Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key.
"""
pkname = self.primary_key_name
if pkname is None:
return None
elif isinstance(pkname, str):
return getattr(self, pkname)
else:
return tuple((getattr(self, pkn) for pkn in pkname)) | [
"def",
"primary_key",
"(",
"self",
")",
":",
"pkname",
"=",
"self",
".",
"primary_key_name",
"if",
"pkname",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"pkname",
",",
"str",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"pkname",
")",
"else",
":",
"return",
"tuple",
"(",
"(",
"getattr",
"(",
"self",
",",
"pkn",
")",
"for",
"pkn",
"in",
"pkname",
")",
")"
] | Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key. | [
"Returns",
"either",
"the",
"primary",
"key",
"value",
"or",
"a",
"tuple",
"containing",
"the",
"primary",
"key",
"values",
"in",
"the",
"case",
"of",
"a",
"composite",
"primary",
"key",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L59-L69 |
248,105 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.validate | def validate(self, data_access=None):
"""Run the class validations against the instance. If the validations require database access,
pass in a DataAccess derived instance.
"""
self.clear_errors()
self.before_validation()
self.validator.validate(self, data_access)
return not self.has_errors | python | def validate(self, data_access=None):
"""Run the class validations against the instance. If the validations require database access,
pass in a DataAccess derived instance.
"""
self.clear_errors()
self.before_validation()
self.validator.validate(self, data_access)
return not self.has_errors | [
"def",
"validate",
"(",
"self",
",",
"data_access",
"=",
"None",
")",
":",
"self",
".",
"clear_errors",
"(",
")",
"self",
".",
"before_validation",
"(",
")",
"self",
".",
"validator",
".",
"validate",
"(",
"self",
",",
"data_access",
")",
"return",
"not",
"self",
".",
"has_errors"
] | Run the class validations against the instance. If the validations require database access,
pass in a DataAccess derived instance. | [
"Run",
"the",
"class",
"validations",
"against",
"the",
"instance",
".",
"If",
"the",
"validations",
"require",
"database",
"access",
"pass",
"in",
"a",
"DataAccess",
"derived",
"instance",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L84-L91 |
248,106 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.add_error | def add_error(self, property_name, message):
"""Add an error for the given property."""
if property_name not in self.errors:
self.errors[property_name] = []
self.errors[property_name].append(message) | python | def add_error(self, property_name, message):
"""Add an error for the given property."""
if property_name not in self.errors:
self.errors[property_name] = []
self.errors[property_name].append(message) | [
"def",
"add_error",
"(",
"self",
",",
"property_name",
",",
"message",
")",
":",
"if",
"property_name",
"not",
"in",
"self",
".",
"errors",
":",
"self",
".",
"errors",
"[",
"property_name",
"]",
"=",
"[",
"]",
"self",
".",
"errors",
"[",
"property_name",
"]",
".",
"append",
"(",
"message",
")"
] | Add an error for the given property. | [
"Add",
"an",
"error",
"for",
"the",
"given",
"property",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L98-L102 |
248,107 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.all_errors | def all_errors(self, joiner="; "):
"""Returns a string representation of all errors recorded for the instance."""
parts = []
for pname, errs in self.errors.items():
for err in errs:
parts.append("{0}: {1}".format(pname, err))
return joiner.join(parts) | python | def all_errors(self, joiner="; "):
"""Returns a string representation of all errors recorded for the instance."""
parts = []
for pname, errs in self.errors.items():
for err in errs:
parts.append("{0}: {1}".format(pname, err))
return joiner.join(parts) | [
"def",
"all_errors",
"(",
"self",
",",
"joiner",
"=",
"\"; \"",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"pname",
",",
"errs",
"in",
"self",
".",
"errors",
".",
"items",
"(",
")",
":",
"for",
"err",
"in",
"errs",
":",
"parts",
".",
"append",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"pname",
",",
"err",
")",
")",
"return",
"joiner",
".",
"join",
"(",
"parts",
")"
] | Returns a string representation of all errors recorded for the instance. | [
"Returns",
"a",
"string",
"representation",
"of",
"all",
"errors",
"recorded",
"for",
"the",
"instance",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L108-L114 |
248,108 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.to_dict | def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True):
"""Converts the class to a dictionary.
:include_keys: if not None, only the attrs given will be included.
:exclude_keys: if not None, all attrs except those listed will be included, with respect to
use_default_excludes.
:use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined
with exclude_keys if given, or used in place of exlcude_keys if not given.
"""
data = self.__dict__
if include_keys:
return pick(data, include_keys, transform=self._other_to_dict)
else:
skeys = self.exclude_keys_serialize if use_default_excludes else None
ekeys = exclude_keys
return exclude(
data,
lambda k: (skeys is not None and k in skeys) or (ekeys is not None and k in ekeys),
transform=self._other_to_dict) | python | def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True):
"""Converts the class to a dictionary.
:include_keys: if not None, only the attrs given will be included.
:exclude_keys: if not None, all attrs except those listed will be included, with respect to
use_default_excludes.
:use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined
with exclude_keys if given, or used in place of exlcude_keys if not given.
"""
data = self.__dict__
if include_keys:
return pick(data, include_keys, transform=self._other_to_dict)
else:
skeys = self.exclude_keys_serialize if use_default_excludes else None
ekeys = exclude_keys
return exclude(
data,
lambda k: (skeys is not None and k in skeys) or (ekeys is not None and k in ekeys),
transform=self._other_to_dict) | [
"def",
"to_dict",
"(",
"self",
",",
"*",
",",
"include_keys",
"=",
"None",
",",
"exclude_keys",
"=",
"None",
",",
"use_default_excludes",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"__dict__",
"if",
"include_keys",
":",
"return",
"pick",
"(",
"data",
",",
"include_keys",
",",
"transform",
"=",
"self",
".",
"_other_to_dict",
")",
"else",
":",
"skeys",
"=",
"self",
".",
"exclude_keys_serialize",
"if",
"use_default_excludes",
"else",
"None",
"ekeys",
"=",
"exclude_keys",
"return",
"exclude",
"(",
"data",
",",
"lambda",
"k",
":",
"(",
"skeys",
"is",
"not",
"None",
"and",
"k",
"in",
"skeys",
")",
"or",
"(",
"ekeys",
"is",
"not",
"None",
"and",
"k",
"in",
"ekeys",
")",
",",
"transform",
"=",
"self",
".",
"_other_to_dict",
")"
] | Converts the class to a dictionary.
:include_keys: if not None, only the attrs given will be included.
:exclude_keys: if not None, all attrs except those listed will be included, with respect to
use_default_excludes.
:use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined
with exclude_keys if given, or used in place of exlcude_keys if not given. | [
"Converts",
"the",
"class",
"to",
"a",
"dictionary",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L116-L136 |
248,109 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.to_json | def to_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True,
pretty=False):
"""Converts the response from to_dict to a JSON string. If pretty is True then newlines,
indentation and key sorting are used.
"""
return to_json(
self.to_dict(
include_keys=include_keys,
exclude_keys=exclude_keys,
use_default_excludes=use_default_excludes),
pretty=pretty) | python | def to_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True,
pretty=False):
"""Converts the response from to_dict to a JSON string. If pretty is True then newlines,
indentation and key sorting are used.
"""
return to_json(
self.to_dict(
include_keys=include_keys,
exclude_keys=exclude_keys,
use_default_excludes=use_default_excludes),
pretty=pretty) | [
"def",
"to_json",
"(",
"self",
",",
"*",
",",
"include_keys",
"=",
"None",
",",
"exclude_keys",
"=",
"None",
",",
"use_default_excludes",
"=",
"True",
",",
"pretty",
"=",
"False",
")",
":",
"return",
"to_json",
"(",
"self",
".",
"to_dict",
"(",
"include_keys",
"=",
"include_keys",
",",
"exclude_keys",
"=",
"exclude_keys",
",",
"use_default_excludes",
"=",
"use_default_excludes",
")",
",",
"pretty",
"=",
"pretty",
")"
] | Converts the response from to_dict to a JSON string. If pretty is True then newlines,
indentation and key sorting are used. | [
"Converts",
"the",
"response",
"from",
"to_dict",
"to",
"a",
"JSON",
"string",
".",
"If",
"pretty",
"is",
"True",
"then",
"newlines",
"indentation",
"and",
"key",
"sorting",
"are",
"used",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L138-L148 |
248,110 | treycucco/bidon | bidon/db/model/model_base.py | ModelBase.update | def update(self, data_=None, **kwargs):
"""Update the object with the given data object, and with any other key-value args. Returns a
set containing all the property names that were changed.
"""
if data_ is None:
data_ = dict()
else:
data_ = dict(data_)
data_.update(**kwargs)
changes = set()
for attr_name in data_:
if hasattr(self, attr_name):
if getattr(self, attr_name) != data_[attr_name]:
changes.add(attr_name)
setattr(self, attr_name, data_[attr_name])
else:
if self.strict_attrs:
raise Exception("Unknown attribute for {}: {}".format(self.__class__.__name__, attr_name))
return changes | python | def update(self, data_=None, **kwargs):
"""Update the object with the given data object, and with any other key-value args. Returns a
set containing all the property names that were changed.
"""
if data_ is None:
data_ = dict()
else:
data_ = dict(data_)
data_.update(**kwargs)
changes = set()
for attr_name in data_:
if hasattr(self, attr_name):
if getattr(self, attr_name) != data_[attr_name]:
changes.add(attr_name)
setattr(self, attr_name, data_[attr_name])
else:
if self.strict_attrs:
raise Exception("Unknown attribute for {}: {}".format(self.__class__.__name__, attr_name))
return changes | [
"def",
"update",
"(",
"self",
",",
"data_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data_",
"is",
"None",
":",
"data_",
"=",
"dict",
"(",
")",
"else",
":",
"data_",
"=",
"dict",
"(",
"data_",
")",
"data_",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"changes",
"=",
"set",
"(",
")",
"for",
"attr_name",
"in",
"data_",
":",
"if",
"hasattr",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"attr_name",
")",
"!=",
"data_",
"[",
"attr_name",
"]",
":",
"changes",
".",
"add",
"(",
"attr_name",
")",
"setattr",
"(",
"self",
",",
"attr_name",
",",
"data_",
"[",
"attr_name",
"]",
")",
"else",
":",
"if",
"self",
".",
"strict_attrs",
":",
"raise",
"Exception",
"(",
"\"Unknown attribute for {}: {}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"attr_name",
")",
")",
"return",
"changes"
] | Update the object with the given data object, and with any other key-value args. Returns a
set containing all the property names that were changed. | [
"Update",
"the",
"object",
"with",
"the",
"given",
"data",
"object",
"and",
"with",
"any",
"other",
"key",
"-",
"value",
"args",
".",
"Returns",
"a",
"set",
"containing",
"all",
"the",
"property",
"names",
"that",
"were",
"changed",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/model_base.py#L150-L168 |
248,111 | drastus/unicover | unicover/unicover.py | UniCover.dispatch | def dispatch(self, args):
"""
Calls proper method depending on command-line arguments.
"""
if not args.list and not args.group:
if not args.font and not args.char and not args.block:
self.info()
return
else:
args.list = args.group = True
self._display = {k: args.__dict__[k] for k in ('list', 'group', 'omit_summary')}
if args.char:
char = self._getChar(args.char)
if args.font:
self.fontChar(args.font, char)
else:
self.char(char)
else:
block = self._getBlock(args.block)
self.chars(args.font, block) | python | def dispatch(self, args):
"""
Calls proper method depending on command-line arguments.
"""
if not args.list and not args.group:
if not args.font and not args.char and not args.block:
self.info()
return
else:
args.list = args.group = True
self._display = {k: args.__dict__[k] for k in ('list', 'group', 'omit_summary')}
if args.char:
char = self._getChar(args.char)
if args.font:
self.fontChar(args.font, char)
else:
self.char(char)
else:
block = self._getBlock(args.block)
self.chars(args.font, block) | [
"def",
"dispatch",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"args",
".",
"list",
"and",
"not",
"args",
".",
"group",
":",
"if",
"not",
"args",
".",
"font",
"and",
"not",
"args",
".",
"char",
"and",
"not",
"args",
".",
"block",
":",
"self",
".",
"info",
"(",
")",
"return",
"else",
":",
"args",
".",
"list",
"=",
"args",
".",
"group",
"=",
"True",
"self",
".",
"_display",
"=",
"{",
"k",
":",
"args",
".",
"__dict__",
"[",
"k",
"]",
"for",
"k",
"in",
"(",
"'list'",
",",
"'group'",
",",
"'omit_summary'",
")",
"}",
"if",
"args",
".",
"char",
":",
"char",
"=",
"self",
".",
"_getChar",
"(",
"args",
".",
"char",
")",
"if",
"args",
".",
"font",
":",
"self",
".",
"fontChar",
"(",
"args",
".",
"font",
",",
"char",
")",
"else",
":",
"self",
".",
"char",
"(",
"char",
")",
"else",
":",
"block",
"=",
"self",
".",
"_getBlock",
"(",
"args",
".",
"block",
")",
"self",
".",
"chars",
"(",
"args",
".",
"font",
",",
"block",
")"
] | Calls proper method depending on command-line arguments. | [
"Calls",
"proper",
"method",
"depending",
"on",
"command",
"-",
"line",
"arguments",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L55-L74 |
248,112 | drastus/unicover | unicover/unicover.py | UniCover.chars | def chars(self, font, block):
"""
Analyses characters in single font or all fonts.
"""
if font:
font_files = self._getFont(font)
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
blocks = all_blocks
ranges_column = map(itemgetter(3), blocks)
overlapped = Ranges(code_points).getOverlappedList(ranges_column)
else:
blocks = [block]
overlapped = [Ranges(code_points).getOverlapped(block[3])]
if self._display['group']:
char_count = block_count = 0
for i, block in enumerate(blocks):
o_count = len(overlapped[i])
if o_count:
block_count += 1
char_count += o_count
total = sum(len(r) for r in block[3])
percent = 0 if total == 0 else o_count / total
print("{0:>6} {1:47} {2:>4.0%} ({3}/{4})".format(block[0], block[2], percent, o_count, total))
if self._display['list']:
for point in overlapped[i]:
self._charInfo(point, padding=9)
self._charSummary(char_count, block_count)
else:
for point in code_points:
self._charInfo(point, padding=7)
self._charSummary(len(code_points)) | python | def chars(self, font, block):
"""
Analyses characters in single font or all fonts.
"""
if font:
font_files = self._getFont(font)
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
blocks = all_blocks
ranges_column = map(itemgetter(3), blocks)
overlapped = Ranges(code_points).getOverlappedList(ranges_column)
else:
blocks = [block]
overlapped = [Ranges(code_points).getOverlapped(block[3])]
if self._display['group']:
char_count = block_count = 0
for i, block in enumerate(blocks):
o_count = len(overlapped[i])
if o_count:
block_count += 1
char_count += o_count
total = sum(len(r) for r in block[3])
percent = 0 if total == 0 else o_count / total
print("{0:>6} {1:47} {2:>4.0%} ({3}/{4})".format(block[0], block[2], percent, o_count, total))
if self._display['list']:
for point in overlapped[i]:
self._charInfo(point, padding=9)
self._charSummary(char_count, block_count)
else:
for point in code_points:
self._charInfo(point, padding=7)
self._charSummary(len(code_points)) | [
"def",
"chars",
"(",
"self",
",",
"font",
",",
"block",
")",
":",
"if",
"font",
":",
"font_files",
"=",
"self",
".",
"_getFont",
"(",
"font",
")",
"else",
":",
"font_files",
"=",
"fc",
".",
"query",
"(",
")",
"code_points",
"=",
"self",
".",
"_getFontChars",
"(",
"font_files",
")",
"if",
"not",
"block",
":",
"blocks",
"=",
"all_blocks",
"ranges_column",
"=",
"map",
"(",
"itemgetter",
"(",
"3",
")",
",",
"blocks",
")",
"overlapped",
"=",
"Ranges",
"(",
"code_points",
")",
".",
"getOverlappedList",
"(",
"ranges_column",
")",
"else",
":",
"blocks",
"=",
"[",
"block",
"]",
"overlapped",
"=",
"[",
"Ranges",
"(",
"code_points",
")",
".",
"getOverlapped",
"(",
"block",
"[",
"3",
"]",
")",
"]",
"if",
"self",
".",
"_display",
"[",
"'group'",
"]",
":",
"char_count",
"=",
"block_count",
"=",
"0",
"for",
"i",
",",
"block",
"in",
"enumerate",
"(",
"blocks",
")",
":",
"o_count",
"=",
"len",
"(",
"overlapped",
"[",
"i",
"]",
")",
"if",
"o_count",
":",
"block_count",
"+=",
"1",
"char_count",
"+=",
"o_count",
"total",
"=",
"sum",
"(",
"len",
"(",
"r",
")",
"for",
"r",
"in",
"block",
"[",
"3",
"]",
")",
"percent",
"=",
"0",
"if",
"total",
"==",
"0",
"else",
"o_count",
"/",
"total",
"print",
"(",
"\"{0:>6} {1:47} {2:>4.0%} ({3}/{4})\"",
".",
"format",
"(",
"block",
"[",
"0",
"]",
",",
"block",
"[",
"2",
"]",
",",
"percent",
",",
"o_count",
",",
"total",
")",
")",
"if",
"self",
".",
"_display",
"[",
"'list'",
"]",
":",
"for",
"point",
"in",
"overlapped",
"[",
"i",
"]",
":",
"self",
".",
"_charInfo",
"(",
"point",
",",
"padding",
"=",
"9",
")",
"self",
".",
"_charSummary",
"(",
"char_count",
",",
"block_count",
")",
"else",
":",
"for",
"point",
"in",
"code_points",
":",
"self",
".",
"_charInfo",
"(",
"point",
",",
"padding",
"=",
"7",
")",
"self",
".",
"_charSummary",
"(",
"len",
"(",
"code_points",
")",
")"
] | Analyses characters in single font or all fonts. | [
"Analyses",
"characters",
"in",
"single",
"font",
"or",
"all",
"fonts",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L83-L118 |
248,113 | drastus/unicover | unicover/unicover.py | UniCover.char | def char(self, char):
"""
Shows all system fonts that contain given character.
"""
font_files = fc.query()
if self._display['group']:
font_files = self._getCharFont(font_files, char)
font_families = self._groupFontByFamily(font_files)
for font_family in sorted(font_families):
print(font_family)
if self._display['list']:
for font_file in font_families[font_family]:
print(' '+font_file)
self._fontSummary(len(font_files), len(font_families))
else:
font_files = self._getCharFont(font_files, char)
for font_file in sorted(font_files):
print(font_file)
self._fontSummary(len(font_files)) | python | def char(self, char):
"""
Shows all system fonts that contain given character.
"""
font_files = fc.query()
if self._display['group']:
font_files = self._getCharFont(font_files, char)
font_families = self._groupFontByFamily(font_files)
for font_family in sorted(font_families):
print(font_family)
if self._display['list']:
for font_file in font_families[font_family]:
print(' '+font_file)
self._fontSummary(len(font_files), len(font_families))
else:
font_files = self._getCharFont(font_files, char)
for font_file in sorted(font_files):
print(font_file)
self._fontSummary(len(font_files)) | [
"def",
"char",
"(",
"self",
",",
"char",
")",
":",
"font_files",
"=",
"fc",
".",
"query",
"(",
")",
"if",
"self",
".",
"_display",
"[",
"'group'",
"]",
":",
"font_files",
"=",
"self",
".",
"_getCharFont",
"(",
"font_files",
",",
"char",
")",
"font_families",
"=",
"self",
".",
"_groupFontByFamily",
"(",
"font_files",
")",
"for",
"font_family",
"in",
"sorted",
"(",
"font_families",
")",
":",
"print",
"(",
"font_family",
")",
"if",
"self",
".",
"_display",
"[",
"'list'",
"]",
":",
"for",
"font_file",
"in",
"font_families",
"[",
"font_family",
"]",
":",
"print",
"(",
"' '",
"+",
"font_file",
")",
"self",
".",
"_fontSummary",
"(",
"len",
"(",
"font_files",
")",
",",
"len",
"(",
"font_families",
")",
")",
"else",
":",
"font_files",
"=",
"self",
".",
"_getCharFont",
"(",
"font_files",
",",
"char",
")",
"for",
"font_file",
"in",
"sorted",
"(",
"font_files",
")",
":",
"print",
"(",
"font_file",
")",
"self",
".",
"_fontSummary",
"(",
"len",
"(",
"font_files",
")",
")"
] | Shows all system fonts that contain given character. | [
"Shows",
"all",
"system",
"fonts",
"that",
"contain",
"given",
"character",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L120-L138 |
248,114 | drastus/unicover | unicover/unicover.py | UniCover.fontChar | def fontChar(self, font, char):
"""
Checks if characters occurs in the given font.
"""
font_files = self._getCharFont(self._getFont(font), char)
print('The character is {0}present in this font.'.format('' if font_files else 'not ')) | python | def fontChar(self, font, char):
"""
Checks if characters occurs in the given font.
"""
font_files = self._getCharFont(self._getFont(font), char)
print('The character is {0}present in this font.'.format('' if font_files else 'not ')) | [
"def",
"fontChar",
"(",
"self",
",",
"font",
",",
"char",
")",
":",
"font_files",
"=",
"self",
".",
"_getCharFont",
"(",
"self",
".",
"_getFont",
"(",
"font",
")",
",",
"char",
")",
"print",
"(",
"'The character is {0}present in this font.'",
".",
"format",
"(",
"''",
"if",
"font_files",
"else",
"'not '",
")",
")"
] | Checks if characters occurs in the given font. | [
"Checks",
"if",
"characters",
"occurs",
"in",
"the",
"given",
"font",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L140-L145 |
248,115 | drastus/unicover | unicover/unicover.py | UniCover._charInfo | def _charInfo(self, point, padding):
"""
Displays character info.
"""
print('{0:0>4X} '.format(point).rjust(padding), ud.name(chr(point), '<code point {0:0>4X}>'.format(point))) | python | def _charInfo(self, point, padding):
"""
Displays character info.
"""
print('{0:0>4X} '.format(point).rjust(padding), ud.name(chr(point), '<code point {0:0>4X}>'.format(point))) | [
"def",
"_charInfo",
"(",
"self",
",",
"point",
",",
"padding",
")",
":",
"print",
"(",
"'{0:0>4X} '",
".",
"format",
"(",
"point",
")",
".",
"rjust",
"(",
"padding",
")",
",",
"ud",
".",
"name",
"(",
"chr",
"(",
"point",
")",
",",
"'<code point {0:0>4X}>'",
".",
"format",
"(",
"point",
")",
")",
")"
] | Displays character info. | [
"Displays",
"character",
"info",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L147-L151 |
248,116 | drastus/unicover | unicover/unicover.py | UniCover._charSummary | def _charSummary(self, char_count, block_count=None):
"""
Displays characters summary.
"""
if not self._display['omit_summary']:
if block_count is None:
print('Total code points:', char_count)
else:
print('Total {0} code point{1} in {2} block{3}'.format(
char_count,
's' if char_count != 1 else '',
block_count,
's' if block_count != 1 else ''
)) | python | def _charSummary(self, char_count, block_count=None):
"""
Displays characters summary.
"""
if not self._display['omit_summary']:
if block_count is None:
print('Total code points:', char_count)
else:
print('Total {0} code point{1} in {2} block{3}'.format(
char_count,
's' if char_count != 1 else '',
block_count,
's' if block_count != 1 else ''
)) | [
"def",
"_charSummary",
"(",
"self",
",",
"char_count",
",",
"block_count",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_display",
"[",
"'omit_summary'",
"]",
":",
"if",
"block_count",
"is",
"None",
":",
"print",
"(",
"'Total code points:'",
",",
"char_count",
")",
"else",
":",
"print",
"(",
"'Total {0} code point{1} in {2} block{3}'",
".",
"format",
"(",
"char_count",
",",
"'s'",
"if",
"char_count",
"!=",
"1",
"else",
"''",
",",
"block_count",
",",
"'s'",
"if",
"block_count",
"!=",
"1",
"else",
"''",
")",
")"
] | Displays characters summary. | [
"Displays",
"characters",
"summary",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L153-L166 |
248,117 | drastus/unicover | unicover/unicover.py | UniCover._fontSummary | def _fontSummary(self, font_file_count, font_family_count=None):
"""
Displays fonts summary.
"""
if not self._display['omit_summary']:
if font_family_count is None:
print('Total font files:', font_file_count)
else:
print('The character is present in {0} font file{1} and {2} font famil{3}'.format(
font_file_count,
's' if font_file_count != 1 else '',
font_family_count,
'ies' if font_family_count != 1 else 'y'
)) | python | def _fontSummary(self, font_file_count, font_family_count=None):
"""
Displays fonts summary.
"""
if not self._display['omit_summary']:
if font_family_count is None:
print('Total font files:', font_file_count)
else:
print('The character is present in {0} font file{1} and {2} font famil{3}'.format(
font_file_count,
's' if font_file_count != 1 else '',
font_family_count,
'ies' if font_family_count != 1 else 'y'
)) | [
"def",
"_fontSummary",
"(",
"self",
",",
"font_file_count",
",",
"font_family_count",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_display",
"[",
"'omit_summary'",
"]",
":",
"if",
"font_family_count",
"is",
"None",
":",
"print",
"(",
"'Total font files:'",
",",
"font_file_count",
")",
"else",
":",
"print",
"(",
"'The character is present in {0} font file{1} and {2} font famil{3}'",
".",
"format",
"(",
"font_file_count",
",",
"'s'",
"if",
"font_file_count",
"!=",
"1",
"else",
"''",
",",
"font_family_count",
",",
"'ies'",
"if",
"font_family_count",
"!=",
"1",
"else",
"'y'",
")",
")"
] | Displays fonts summary. | [
"Displays",
"fonts",
"summary",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L168-L181 |
248,118 | drastus/unicover | unicover/unicover.py | UniCover._getChar | def _getChar(self, char_spec):
"""
Returns character from given code point or character.
"""
if len(char_spec) >= 4 and all(c in string.hexdigits for c in char_spec):
char_number = int(char_spec, 16)
if char_number not in range(0x110000):
raise ValueError('No such character')
return chr(char_number)
elif len(char_spec) == 1:
return char_spec
else:
raise ValueError('No such character') | python | def _getChar(self, char_spec):
"""
Returns character from given code point or character.
"""
if len(char_spec) >= 4 and all(c in string.hexdigits for c in char_spec):
char_number = int(char_spec, 16)
if char_number not in range(0x110000):
raise ValueError('No such character')
return chr(char_number)
elif len(char_spec) == 1:
return char_spec
else:
raise ValueError('No such character') | [
"def",
"_getChar",
"(",
"self",
",",
"char_spec",
")",
":",
"if",
"len",
"(",
"char_spec",
")",
">=",
"4",
"and",
"all",
"(",
"c",
"in",
"string",
".",
"hexdigits",
"for",
"c",
"in",
"char_spec",
")",
":",
"char_number",
"=",
"int",
"(",
"char_spec",
",",
"16",
")",
"if",
"char_number",
"not",
"in",
"range",
"(",
"0x110000",
")",
":",
"raise",
"ValueError",
"(",
"'No such character'",
")",
"return",
"chr",
"(",
"char_number",
")",
"elif",
"len",
"(",
"char_spec",
")",
"==",
"1",
":",
"return",
"char_spec",
"else",
":",
"raise",
"ValueError",
"(",
"'No such character'",
")"
] | Returns character from given code point or character. | [
"Returns",
"character",
"from",
"given",
"code",
"point",
"or",
"character",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L183-L195 |
248,119 | drastus/unicover | unicover/unicover.py | UniCover._getBlock | def _getBlock(self, block_spec):
"""
Returns block info from given block start code point or block name.
"""
if block_spec is None:
return
if all(c in string.hexdigits for c in block_spec):
block_spec = block_spec.upper()
ix = 0
else:
ix = 2
for block in all_blocks:
if block[ix] == block_spec:
return block
raise ValueError('No such block') | python | def _getBlock(self, block_spec):
"""
Returns block info from given block start code point or block name.
"""
if block_spec is None:
return
if all(c in string.hexdigits for c in block_spec):
block_spec = block_spec.upper()
ix = 0
else:
ix = 2
for block in all_blocks:
if block[ix] == block_spec:
return block
raise ValueError('No such block') | [
"def",
"_getBlock",
"(",
"self",
",",
"block_spec",
")",
":",
"if",
"block_spec",
"is",
"None",
":",
"return",
"if",
"all",
"(",
"c",
"in",
"string",
".",
"hexdigits",
"for",
"c",
"in",
"block_spec",
")",
":",
"block_spec",
"=",
"block_spec",
".",
"upper",
"(",
")",
"ix",
"=",
"0",
"else",
":",
"ix",
"=",
"2",
"for",
"block",
"in",
"all_blocks",
":",
"if",
"block",
"[",
"ix",
"]",
"==",
"block_spec",
":",
"return",
"block",
"raise",
"ValueError",
"(",
"'No such block'",
")"
] | Returns block info from given block start code point or block name. | [
"Returns",
"block",
"info",
"from",
"given",
"block",
"start",
"code",
"point",
"or",
"block",
"name",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L197-L211 |
248,120 | drastus/unicover | unicover/unicover.py | UniCover._getFont | def _getFont(self, font):
"""
Returns font paths from font name or path
"""
if os.path.isfile(font):
font_files = [font]
else:
font_files = fc.query(family=font)
if not font_files:
raise ValueError('No such font')
return font_files | python | def _getFont(self, font):
"""
Returns font paths from font name or path
"""
if os.path.isfile(font):
font_files = [font]
else:
font_files = fc.query(family=font)
if not font_files:
raise ValueError('No such font')
return font_files | [
"def",
"_getFont",
"(",
"self",
",",
"font",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"font",
")",
":",
"font_files",
"=",
"[",
"font",
"]",
"else",
":",
"font_files",
"=",
"fc",
".",
"query",
"(",
"family",
"=",
"font",
")",
"if",
"not",
"font_files",
":",
"raise",
"ValueError",
"(",
"'No such font'",
")",
"return",
"font_files"
] | Returns font paths from font name or path | [
"Returns",
"font",
"paths",
"from",
"font",
"name",
"or",
"path"
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L213-L223 |
248,121 | drastus/unicover | unicover/unicover.py | UniCover._getFontChars | def _getFontChars(self, font_files):
"""
Returns code points of characters included in given font files.
"""
code_points = set()
for font_file in font_files:
face = ft.Face(font_file)
charcode, agindex = face.get_first_char()
while agindex != 0:
code_points.add(charcode)
charcode, agindex = face.get_next_char(charcode, agindex)
return sorted(code_points) | python | def _getFontChars(self, font_files):
"""
Returns code points of characters included in given font files.
"""
code_points = set()
for font_file in font_files:
face = ft.Face(font_file)
charcode, agindex = face.get_first_char()
while agindex != 0:
code_points.add(charcode)
charcode, agindex = face.get_next_char(charcode, agindex)
return sorted(code_points) | [
"def",
"_getFontChars",
"(",
"self",
",",
"font_files",
")",
":",
"code_points",
"=",
"set",
"(",
")",
"for",
"font_file",
"in",
"font_files",
":",
"face",
"=",
"ft",
".",
"Face",
"(",
"font_file",
")",
"charcode",
",",
"agindex",
"=",
"face",
".",
"get_first_char",
"(",
")",
"while",
"agindex",
"!=",
"0",
":",
"code_points",
".",
"add",
"(",
"charcode",
")",
"charcode",
",",
"agindex",
"=",
"face",
".",
"get_next_char",
"(",
"charcode",
",",
"agindex",
")",
"return",
"sorted",
"(",
"code_points",
")"
] | Returns code points of characters included in given font files. | [
"Returns",
"code",
"points",
"of",
"characters",
"included",
"in",
"given",
"font",
"files",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L225-L236 |
248,122 | drastus/unicover | unicover/unicover.py | UniCover._getCharFont | def _getCharFont(self, font_files, code_point):
"""
Returns font files containing given code point.
"""
return_font_files = []
for font_file in font_files:
face = ft.Face(font_file)
if face.get_char_index(code_point):
return_font_files.append(font_file)
return return_font_files | python | def _getCharFont(self, font_files, code_point):
"""
Returns font files containing given code point.
"""
return_font_files = []
for font_file in font_files:
face = ft.Face(font_file)
if face.get_char_index(code_point):
return_font_files.append(font_file)
return return_font_files | [
"def",
"_getCharFont",
"(",
"self",
",",
"font_files",
",",
"code_point",
")",
":",
"return_font_files",
"=",
"[",
"]",
"for",
"font_file",
"in",
"font_files",
":",
"face",
"=",
"ft",
".",
"Face",
"(",
"font_file",
")",
"if",
"face",
".",
"get_char_index",
"(",
"code_point",
")",
":",
"return_font_files",
".",
"append",
"(",
"font_file",
")",
"return",
"return_font_files"
] | Returns font files containing given code point. | [
"Returns",
"font",
"files",
"containing",
"given",
"code",
"point",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L238-L247 |
248,123 | drastus/unicover | unicover/unicover.py | UniCover._groupFontByFamily | def _groupFontByFamily(self, font_files):
"""
Returns font files grouped in dict by font family.
"""
font_families = defaultdict(list)
for font_file in font_files:
font = fc.FcFont(font_file)
font_families[font.family[0][1]].append(font_file)
return font_families | python | def _groupFontByFamily(self, font_files):
"""
Returns font files grouped in dict by font family.
"""
font_families = defaultdict(list)
for font_file in font_files:
font = fc.FcFont(font_file)
font_families[font.family[0][1]].append(font_file)
return font_families | [
"def",
"_groupFontByFamily",
"(",
"self",
",",
"font_files",
")",
":",
"font_families",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"font_file",
"in",
"font_files",
":",
"font",
"=",
"fc",
".",
"FcFont",
"(",
"font_file",
")",
"font_families",
"[",
"font",
".",
"family",
"[",
"0",
"]",
"[",
"1",
"]",
"]",
".",
"append",
"(",
"font_file",
")",
"return",
"font_families"
] | Returns font files grouped in dict by font family. | [
"Returns",
"font",
"files",
"grouped",
"in",
"dict",
"by",
"font",
"family",
"."
] | 4702d0151c63d525c25718a838396afe62302255 | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L249-L257 |
248,124 | PSU-OIT-ARC/elasticmodels | elasticmodels/fields.py | ListField | def ListField(field):
"""
This wraps a field so that when get_from_instance is called, the field's
values are iterated over
"""
# alter the original field's get_from_instance so it iterates over the
# values that the field's get_from_instance() method returns
original_get_from_instance = field.get_from_instance
def get_from_instance(self, instance):
for value in original_get_from_instance(instance):
yield value
field.get_from_instance = MethodType(get_from_instance, field)
return field | python | def ListField(field):
"""
This wraps a field so that when get_from_instance is called, the field's
values are iterated over
"""
# alter the original field's get_from_instance so it iterates over the
# values that the field's get_from_instance() method returns
original_get_from_instance = field.get_from_instance
def get_from_instance(self, instance):
for value in original_get_from_instance(instance):
yield value
field.get_from_instance = MethodType(get_from_instance, field)
return field | [
"def",
"ListField",
"(",
"field",
")",
":",
"# alter the original field's get_from_instance so it iterates over the",
"# values that the field's get_from_instance() method returns",
"original_get_from_instance",
"=",
"field",
".",
"get_from_instance",
"def",
"get_from_instance",
"(",
"self",
",",
"instance",
")",
":",
"for",
"value",
"in",
"original_get_from_instance",
"(",
"instance",
")",
":",
"yield",
"value",
"field",
".",
"get_from_instance",
"=",
"MethodType",
"(",
"get_from_instance",
",",
"field",
")",
"return",
"field"
] | This wraps a field so that when get_from_instance is called, the field's
values are iterated over | [
"This",
"wraps",
"a",
"field",
"so",
"that",
"when",
"get_from_instance",
"is",
"called",
"the",
"field",
"s",
"values",
"are",
"iterated",
"over"
] | 67870508096f66123ef10b89789bbac06571cc80 | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/fields.py#L88-L103 |
248,125 | PSU-OIT-ARC/elasticmodels | elasticmodels/fields.py | EMField.get_from_instance | def get_from_instance(self, instance):
"""
Given an object to index with ES, return the value that should be put
into ES for this field
"""
# walk the attribute path to get the value. Similarly to Django, first
# try getting the value from a dict, then as a attribute lookup, and
# then as a list index
for attr in self._path:
try: # dict lookup
instance = instance[attr]
except (TypeError, AttributeError, KeyError, ValueError, IndexError):
try: # attr lookup
instance = getattr(instance, attr)
except (TypeError, AttributeError):
try: # list-index lookup
instance = instance[int(attr)]
except (IndexError, # list index out of range
ValueError, # invalid literal for int()
KeyError, # current is a dict without `int(bit)` key
TypeError): # unsubscriptable object
raise VariableLookupError("Failed lookup for key [%s] in %r" % (attr, instance))
if callable(instance):
instance = instance()
elif instance is None: # no sense walking down the path any further
return None
return instance | python | def get_from_instance(self, instance):
"""
Given an object to index with ES, return the value that should be put
into ES for this field
"""
# walk the attribute path to get the value. Similarly to Django, first
# try getting the value from a dict, then as a attribute lookup, and
# then as a list index
for attr in self._path:
try: # dict lookup
instance = instance[attr]
except (TypeError, AttributeError, KeyError, ValueError, IndexError):
try: # attr lookup
instance = getattr(instance, attr)
except (TypeError, AttributeError):
try: # list-index lookup
instance = instance[int(attr)]
except (IndexError, # list index out of range
ValueError, # invalid literal for int()
KeyError, # current is a dict without `int(bit)` key
TypeError): # unsubscriptable object
raise VariableLookupError("Failed lookup for key [%s] in %r" % (attr, instance))
if callable(instance):
instance = instance()
elif instance is None: # no sense walking down the path any further
return None
return instance | [
"def",
"get_from_instance",
"(",
"self",
",",
"instance",
")",
":",
"# walk the attribute path to get the value. Similarly to Django, first",
"# try getting the value from a dict, then as a attribute lookup, and",
"# then as a list index",
"for",
"attr",
"in",
"self",
".",
"_path",
":",
"try",
":",
"# dict lookup",
"instance",
"=",
"instance",
"[",
"attr",
"]",
"except",
"(",
"TypeError",
",",
"AttributeError",
",",
"KeyError",
",",
"ValueError",
",",
"IndexError",
")",
":",
"try",
":",
"# attr lookup",
"instance",
"=",
"getattr",
"(",
"instance",
",",
"attr",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"try",
":",
"# list-index lookup",
"instance",
"=",
"instance",
"[",
"int",
"(",
"attr",
")",
"]",
"except",
"(",
"IndexError",
",",
"# list index out of range",
"ValueError",
",",
"# invalid literal for int()",
"KeyError",
",",
"# current is a dict without `int(bit)` key",
"TypeError",
")",
":",
"# unsubscriptable object",
"raise",
"VariableLookupError",
"(",
"\"Failed lookup for key [%s] in %r\"",
"%",
"(",
"attr",
",",
"instance",
")",
")",
"if",
"callable",
"(",
"instance",
")",
":",
"instance",
"=",
"instance",
"(",
")",
"elif",
"instance",
"is",
"None",
":",
"# no sense walking down the path any further",
"return",
"None",
"return",
"instance"
] | Given an object to index with ES, return the value that should be put
into ES for this field | [
"Given",
"an",
"object",
"to",
"index",
"with",
"ES",
"return",
"the",
"value",
"that",
"should",
"be",
"put",
"into",
"ES",
"for",
"this",
"field"
] | 67870508096f66123ef10b89789bbac06571cc80 | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/fields.py#L26-L54 |
248,126 | KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | run_query_series | def run_query_series(queries, conn):
"""
Iterates through a list of queries and runs them through the connection
Args:
-----
queries: list of strings or tuples containing (query_string, kwargs)
conn: the triplestore connection to use
"""
results = []
for item in queries:
qry = item
kwargs = {}
if isinstance(item, tuple):
qry = item[0]
kwargs = item[1]
result = conn.update_query(qry, **kwargs)
# pdb.set_trace()
results.append(result)
return results | python | def run_query_series(queries, conn):
"""
Iterates through a list of queries and runs them through the connection
Args:
-----
queries: list of strings or tuples containing (query_string, kwargs)
conn: the triplestore connection to use
"""
results = []
for item in queries:
qry = item
kwargs = {}
if isinstance(item, tuple):
qry = item[0]
kwargs = item[1]
result = conn.update_query(qry, **kwargs)
# pdb.set_trace()
results.append(result)
return results | [
"def",
"run_query_series",
"(",
"queries",
",",
"conn",
")",
":",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"queries",
":",
"qry",
"=",
"item",
"kwargs",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"item",
",",
"tuple",
")",
":",
"qry",
"=",
"item",
"[",
"0",
"]",
"kwargs",
"=",
"item",
"[",
"1",
"]",
"result",
"=",
"conn",
".",
"update_query",
"(",
"qry",
",",
"*",
"*",
"kwargs",
")",
"# pdb.set_trace()",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results"
] | Iterates through a list of queries and runs them through the connection
Args:
-----
queries: list of strings or tuples containing (query_string, kwargs)
conn: the triplestore connection to use | [
"Iterates",
"through",
"a",
"list",
"of",
"queries",
"and",
"runs",
"them",
"through",
"the",
"connection"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L14-L33 |
248,127 | KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | get_all_item_data | def get_all_item_data(items, conn, graph=None, output='json', **kwargs):
""" queries a triplestore with the provided template or uses a generic
template that returns triples 3 edges out in either direction from the
provided item_uri
args:
items: the starting uri or list of uris to the query
conn: the rdfframework triplestore connection to query against
output: 'json' or 'rdf'
kwargs:
template: template to use in place of the generic template
rdfclass: rdfclass the items are based on.
filters: list of filters to apply
"""
# set the jinja2 template to use
if kwargs.get('template'):
template = kwargs.pop('template')
else:
template = "sparqlAllItemDataTemplate.rq"
# build the keyword arguments for the templace
template_kwargs = {"prefix": NSM.prefix(), "output": output}
if isinstance(items, list):
template_kwargs['uri_list'] = items
else:
template_kwargs['item_uri'] = Uri(items).sparql
if kwargs.get("special_union"):
template_kwargs['special_union'] = kwargs.get("special_union")
if kwargs.get('rdfclass'):
# pdb.set_trace()
template_kwargs.update(kwargs['rdfclass'].query_kwargs)
if kwargs.get("filters"):
template_kwargs['filters'] = make_sparql_filter(kwargs.get('filters'))
sparql = render_without_request(template, **template_kwargs)
return conn.query(sparql, **kwargs) | python | def get_all_item_data(items, conn, graph=None, output='json', **kwargs):
""" queries a triplestore with the provided template or uses a generic
template that returns triples 3 edges out in either direction from the
provided item_uri
args:
items: the starting uri or list of uris to the query
conn: the rdfframework triplestore connection to query against
output: 'json' or 'rdf'
kwargs:
template: template to use in place of the generic template
rdfclass: rdfclass the items are based on.
filters: list of filters to apply
"""
# set the jinja2 template to use
if kwargs.get('template'):
template = kwargs.pop('template')
else:
template = "sparqlAllItemDataTemplate.rq"
# build the keyword arguments for the templace
template_kwargs = {"prefix": NSM.prefix(), "output": output}
if isinstance(items, list):
template_kwargs['uri_list'] = items
else:
template_kwargs['item_uri'] = Uri(items).sparql
if kwargs.get("special_union"):
template_kwargs['special_union'] = kwargs.get("special_union")
if kwargs.get('rdfclass'):
# pdb.set_trace()
template_kwargs.update(kwargs['rdfclass'].query_kwargs)
if kwargs.get("filters"):
template_kwargs['filters'] = make_sparql_filter(kwargs.get('filters'))
sparql = render_without_request(template, **template_kwargs)
return conn.query(sparql, **kwargs) | [
"def",
"get_all_item_data",
"(",
"items",
",",
"conn",
",",
"graph",
"=",
"None",
",",
"output",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"# set the jinja2 template to use",
"if",
"kwargs",
".",
"get",
"(",
"'template'",
")",
":",
"template",
"=",
"kwargs",
".",
"pop",
"(",
"'template'",
")",
"else",
":",
"template",
"=",
"\"sparqlAllItemDataTemplate.rq\"",
"# build the keyword arguments for the templace",
"template_kwargs",
"=",
"{",
"\"prefix\"",
":",
"NSM",
".",
"prefix",
"(",
")",
",",
"\"output\"",
":",
"output",
"}",
"if",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"template_kwargs",
"[",
"'uri_list'",
"]",
"=",
"items",
"else",
":",
"template_kwargs",
"[",
"'item_uri'",
"]",
"=",
"Uri",
"(",
"items",
")",
".",
"sparql",
"if",
"kwargs",
".",
"get",
"(",
"\"special_union\"",
")",
":",
"template_kwargs",
"[",
"'special_union'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"special_union\"",
")",
"if",
"kwargs",
".",
"get",
"(",
"'rdfclass'",
")",
":",
"# pdb.set_trace()",
"template_kwargs",
".",
"update",
"(",
"kwargs",
"[",
"'rdfclass'",
"]",
".",
"query_kwargs",
")",
"if",
"kwargs",
".",
"get",
"(",
"\"filters\"",
")",
":",
"template_kwargs",
"[",
"'filters'",
"]",
"=",
"make_sparql_filter",
"(",
"kwargs",
".",
"get",
"(",
"'filters'",
")",
")",
"sparql",
"=",
"render_without_request",
"(",
"template",
",",
"*",
"*",
"template_kwargs",
")",
"return",
"conn",
".",
"query",
"(",
"sparql",
",",
"*",
"*",
"kwargs",
")"
] | queries a triplestore with the provided template or uses a generic
template that returns triples 3 edges out in either direction from the
provided item_uri
args:
items: the starting uri or list of uris to the query
conn: the rdfframework triplestore connection to query against
output: 'json' or 'rdf'
kwargs:
template: template to use in place of the generic template
rdfclass: rdfclass the items are based on.
filters: list of filters to apply | [
"queries",
"a",
"triplestore",
"with",
"the",
"provided",
"template",
"or",
"uses",
"a",
"generic",
"template",
"that",
"returns",
"triples",
"3",
"edges",
"out",
"in",
"either",
"direction",
"from",
"the",
"provided",
"item_uri"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L35-L69 |
248,128 | KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | get_graph | def get_graph(graph, conn, **kwargs):
""" Returns all the triples for a specific are graph
args:
graph: the URI of the graph to retreive
conn: the rdfframework triplestore connection
"""
sparql = render_without_request("sparqlGraphDataTemplate.rq",
prefix=NSM.prefix(),
graph=graph)
return conn.query(sparql, **kwargs) | python | def get_graph(graph, conn, **kwargs):
""" Returns all the triples for a specific are graph
args:
graph: the URI of the graph to retreive
conn: the rdfframework triplestore connection
"""
sparql = render_without_request("sparqlGraphDataTemplate.rq",
prefix=NSM.prefix(),
graph=graph)
return conn.query(sparql, **kwargs) | [
"def",
"get_graph",
"(",
"graph",
",",
"conn",
",",
"*",
"*",
"kwargs",
")",
":",
"sparql",
"=",
"render_without_request",
"(",
"\"sparqlGraphDataTemplate.rq\"",
",",
"prefix",
"=",
"NSM",
".",
"prefix",
"(",
")",
",",
"graph",
"=",
"graph",
")",
"return",
"conn",
".",
"query",
"(",
"sparql",
",",
"*",
"*",
"kwargs",
")"
] | Returns all the triples for a specific are graph
args:
graph: the URI of the graph to retreive
conn: the rdfframework triplestore connection | [
"Returns",
"all",
"the",
"triples",
"for",
"a",
"specific",
"are",
"graph"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L71-L81 |
248,129 | KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | make_sparql_filter | def make_sparql_filter(filters):
""" Make the filter section for a query template
args:
filters: list of dictionaries to generate the filter
example:
filters = [{'variable': 'p',
'operator': '=',
'union_type': '||',
'values': ['rdf:type', 'rdfs:label']}]
"""
def make_filter_str(variable, operator, union_type, values):
""" generates a filter string for a sparql query
args:
variable: the variable to reference
operator: '=' or '!='
union_type" '&&' or '||'
values: list of values to apply the filter
"""
formated_vals = UniqueList()
for val in values:
try:
formated_vals.append(val.sparql)
except AttributeError:
formated_vals.append(val)
pre_str = "?%s%s" % (variable.replace("?", ""), operator)
union = "%s\n\t\t" % union_type
return "\tFilter( %s) .\n" % union.join([pre_str + val
for val in formated_vals])
if not filters:
return ""
rtn_str = ""
for param in filters:
rtn_str += make_filter_str(**param)
return rtn_str | python | def make_sparql_filter(filters):
""" Make the filter section for a query template
args:
filters: list of dictionaries to generate the filter
example:
filters = [{'variable': 'p',
'operator': '=',
'union_type': '||',
'values': ['rdf:type', 'rdfs:label']}]
"""
def make_filter_str(variable, operator, union_type, values):
""" generates a filter string for a sparql query
args:
variable: the variable to reference
operator: '=' or '!='
union_type" '&&' or '||'
values: list of values to apply the filter
"""
formated_vals = UniqueList()
for val in values:
try:
formated_vals.append(val.sparql)
except AttributeError:
formated_vals.append(val)
pre_str = "?%s%s" % (variable.replace("?", ""), operator)
union = "%s\n\t\t" % union_type
return "\tFilter( %s) .\n" % union.join([pre_str + val
for val in formated_vals])
if not filters:
return ""
rtn_str = ""
for param in filters:
rtn_str += make_filter_str(**param)
return rtn_str | [
"def",
"make_sparql_filter",
"(",
"filters",
")",
":",
"def",
"make_filter_str",
"(",
"variable",
",",
"operator",
",",
"union_type",
",",
"values",
")",
":",
"\"\"\" generates a filter string for a sparql query\n\n args:\n variable: the variable to reference\n operator: '=' or '!='\n union_type\" '&&' or '||'\n values: list of values to apply the filter\n \"\"\"",
"formated_vals",
"=",
"UniqueList",
"(",
")",
"for",
"val",
"in",
"values",
":",
"try",
":",
"formated_vals",
".",
"append",
"(",
"val",
".",
"sparql",
")",
"except",
"AttributeError",
":",
"formated_vals",
".",
"append",
"(",
"val",
")",
"pre_str",
"=",
"\"?%s%s\"",
"%",
"(",
"variable",
".",
"replace",
"(",
"\"?\"",
",",
"\"\"",
")",
",",
"operator",
")",
"union",
"=",
"\"%s\\n\\t\\t\"",
"%",
"union_type",
"return",
"\"\\tFilter( %s) .\\n\"",
"%",
"union",
".",
"join",
"(",
"[",
"pre_str",
"+",
"val",
"for",
"val",
"in",
"formated_vals",
"]",
")",
"if",
"not",
"filters",
":",
"return",
"\"\"",
"rtn_str",
"=",
"\"\"",
"for",
"param",
"in",
"filters",
":",
"rtn_str",
"+=",
"make_filter_str",
"(",
"*",
"*",
"param",
")",
"return",
"rtn_str"
] | Make the filter section for a query template
args:
filters: list of dictionaries to generate the filter
example:
filters = [{'variable': 'p',
'operator': '=',
'union_type': '||',
'values': ['rdf:type', 'rdfs:label']}] | [
"Make",
"the",
"filter",
"section",
"for",
"a",
"query",
"template"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L83-L120 |
248,130 | KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | add_sparql_line_nums | def add_sparql_line_nums(sparql):
"""
Returns a sparql query with line numbers prepended
"""
lines = sparql.split("\n")
return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)]) | python | def add_sparql_line_nums(sparql):
"""
Returns a sparql query with line numbers prepended
"""
lines = sparql.split("\n")
return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)]) | [
"def",
"add_sparql_line_nums",
"(",
"sparql",
")",
":",
"lines",
"=",
"sparql",
".",
"split",
"(",
"\"\\n\"",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"%s %s\"",
"%",
"(",
"i",
"+",
"1",
",",
"line",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
"]",
")"
] | Returns a sparql query with line numbers prepended | [
"Returns",
"a",
"sparql",
"query",
"with",
"line",
"numbers",
"prepended"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L122-L127 |
248,131 | gabrielfalcao/dominic | dominic/xpath/expr.py | string_value | def string_value(node):
"""Compute the string-value of a node."""
if (node.nodeType == node.DOCUMENT_NODE or
node.nodeType == node.ELEMENT_NODE):
s = u''
for n in axes['descendant'](node):
if n.nodeType == n.TEXT_NODE:
s += n.data
return s
elif node.nodeType == node.ATTRIBUTE_NODE:
return node.value
elif (node.nodeType == node.PROCESSING_INSTRUCTION_NODE or
node.nodeType == node.COMMENT_NODE or
node.nodeType == node.TEXT_NODE):
return node.data | python | def string_value(node):
"""Compute the string-value of a node."""
if (node.nodeType == node.DOCUMENT_NODE or
node.nodeType == node.ELEMENT_NODE):
s = u''
for n in axes['descendant'](node):
if n.nodeType == n.TEXT_NODE:
s += n.data
return s
elif node.nodeType == node.ATTRIBUTE_NODE:
return node.value
elif (node.nodeType == node.PROCESSING_INSTRUCTION_NODE or
node.nodeType == node.COMMENT_NODE or
node.nodeType == node.TEXT_NODE):
return node.data | [
"def",
"string_value",
"(",
"node",
")",
":",
"if",
"(",
"node",
".",
"nodeType",
"==",
"node",
".",
"DOCUMENT_NODE",
"or",
"node",
".",
"nodeType",
"==",
"node",
".",
"ELEMENT_NODE",
")",
":",
"s",
"=",
"u''",
"for",
"n",
"in",
"axes",
"[",
"'descendant'",
"]",
"(",
"node",
")",
":",
"if",
"n",
".",
"nodeType",
"==",
"n",
".",
"TEXT_NODE",
":",
"s",
"+=",
"n",
".",
"data",
"return",
"s",
"elif",
"node",
".",
"nodeType",
"==",
"node",
".",
"ATTRIBUTE_NODE",
":",
"return",
"node",
".",
"value",
"elif",
"(",
"node",
".",
"nodeType",
"==",
"node",
".",
"PROCESSING_INSTRUCTION_NODE",
"or",
"node",
".",
"nodeType",
"==",
"node",
".",
"COMMENT_NODE",
"or",
"node",
".",
"nodeType",
"==",
"node",
".",
"TEXT_NODE",
")",
":",
"return",
"node",
".",
"data"
] | Compute the string-value of a node. | [
"Compute",
"the",
"string",
"-",
"value",
"of",
"a",
"node",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L17-L33 |
248,132 | gabrielfalcao/dominic | dominic/xpath/expr.py | document_order | def document_order(node):
"""Compute a document order value for the node.
cmp(document_order(a), document_order(b)) will return -1, 0, or 1 if
a is before, identical to, or after b in the document respectively.
We represent document order as a list of sibling indexes. That is,
the third child of the document node has an order of [2]. The first
child of that node has an order of [2,0].
Attributes have a sibling index of -1 (coming before all children of
their node) and are further ordered by name--e.g., [2,0,-1,'href'].
"""
# Attributes: parent-order + [-1, attribute-name]
if node.nodeType == node.ATTRIBUTE_NODE:
order = document_order(node.ownerElement)
order.extend((-1, node.name))
return order
# The document root (hopefully): []
if node.parentNode is None:
return []
# Determine which child this is of its parent.
sibpos = 0
sib = node
while sib.previousSibling is not None:
sibpos += 1
sib = sib.previousSibling
# Order: parent-order + [sibling-position]
order = document_order(node.parentNode)
order.append(sibpos)
return order | python | def document_order(node):
"""Compute a document order value for the node.
cmp(document_order(a), document_order(b)) will return -1, 0, or 1 if
a is before, identical to, or after b in the document respectively.
We represent document order as a list of sibling indexes. That is,
the third child of the document node has an order of [2]. The first
child of that node has an order of [2,0].
Attributes have a sibling index of -1 (coming before all children of
their node) and are further ordered by name--e.g., [2,0,-1,'href'].
"""
# Attributes: parent-order + [-1, attribute-name]
if node.nodeType == node.ATTRIBUTE_NODE:
order = document_order(node.ownerElement)
order.extend((-1, node.name))
return order
# The document root (hopefully): []
if node.parentNode is None:
return []
# Determine which child this is of its parent.
sibpos = 0
sib = node
while sib.previousSibling is not None:
sibpos += 1
sib = sib.previousSibling
# Order: parent-order + [sibling-position]
order = document_order(node.parentNode)
order.append(sibpos)
return order | [
"def",
"document_order",
"(",
"node",
")",
":",
"# Attributes: parent-order + [-1, attribute-name]",
"if",
"node",
".",
"nodeType",
"==",
"node",
".",
"ATTRIBUTE_NODE",
":",
"order",
"=",
"document_order",
"(",
"node",
".",
"ownerElement",
")",
"order",
".",
"extend",
"(",
"(",
"-",
"1",
",",
"node",
".",
"name",
")",
")",
"return",
"order",
"# The document root (hopefully): []",
"if",
"node",
".",
"parentNode",
"is",
"None",
":",
"return",
"[",
"]",
"# Determine which child this is of its parent.",
"sibpos",
"=",
"0",
"sib",
"=",
"node",
"while",
"sib",
".",
"previousSibling",
"is",
"not",
"None",
":",
"sibpos",
"+=",
"1",
"sib",
"=",
"sib",
".",
"previousSibling",
"# Order: parent-order + [sibling-position]",
"order",
"=",
"document_order",
"(",
"node",
".",
"parentNode",
")",
"order",
".",
"append",
"(",
"sibpos",
")",
"return",
"order"
] | Compute a document order value for the node.
cmp(document_order(a), document_order(b)) will return -1, 0, or 1 if
a is before, identical to, or after b in the document respectively.
We represent document order as a list of sibling indexes. That is,
the third child of the document node has an order of [2]. The first
child of that node has an order of [2,0].
Attributes have a sibling index of -1 (coming before all children of
their node) and are further ordered by name--e.g., [2,0,-1,'href']. | [
"Compute",
"a",
"document",
"order",
"value",
"for",
"the",
"node",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L35-L70 |
248,133 | gabrielfalcao/dominic | dominic/xpath/expr.py | string | def string(v):
"""Convert a value to a string."""
if nodesetp(v):
if not v:
return u''
return string_value(v[0])
elif numberp(v):
if v == float('inf'):
return u'Infinity'
elif v == float('-inf'):
return u'-Infinity'
elif str(v) == 'nan':
return u'NaN'
elif int(v) == v and v <= 0xffffffff:
v = int(v)
return unicode(v)
elif booleanp(v):
return u'true' if v else u'false'
return v | python | def string(v):
"""Convert a value to a string."""
if nodesetp(v):
if not v:
return u''
return string_value(v[0])
elif numberp(v):
if v == float('inf'):
return u'Infinity'
elif v == float('-inf'):
return u'-Infinity'
elif str(v) == 'nan':
return u'NaN'
elif int(v) == v and v <= 0xffffffff:
v = int(v)
return unicode(v)
elif booleanp(v):
return u'true' if v else u'false'
return v | [
"def",
"string",
"(",
"v",
")",
":",
"if",
"nodesetp",
"(",
"v",
")",
":",
"if",
"not",
"v",
":",
"return",
"u''",
"return",
"string_value",
"(",
"v",
"[",
"0",
"]",
")",
"elif",
"numberp",
"(",
"v",
")",
":",
"if",
"v",
"==",
"float",
"(",
"'inf'",
")",
":",
"return",
"u'Infinity'",
"elif",
"v",
"==",
"float",
"(",
"'-inf'",
")",
":",
"return",
"u'-Infinity'",
"elif",
"str",
"(",
"v",
")",
"==",
"'nan'",
":",
"return",
"u'NaN'",
"elif",
"int",
"(",
"v",
")",
"==",
"v",
"and",
"v",
"<=",
"0xffffffff",
":",
"v",
"=",
"int",
"(",
"v",
")",
"return",
"unicode",
"(",
"v",
")",
"elif",
"booleanp",
"(",
"v",
")",
":",
"return",
"u'true'",
"if",
"v",
"else",
"u'false'",
"return",
"v"
] | Convert a value to a string. | [
"Convert",
"a",
"value",
"to",
"a",
"string",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L93-L111 |
248,134 | gabrielfalcao/dominic | dominic/xpath/expr.py | boolean | def boolean(v):
"""Convert a value to a boolean."""
if nodesetp(v):
return len(v) > 0
elif numberp(v):
if v == 0 or v != v:
return False
return True
elif stringp(v):
return v != ''
return v | python | def boolean(v):
"""Convert a value to a boolean."""
if nodesetp(v):
return len(v) > 0
elif numberp(v):
if v == 0 or v != v:
return False
return True
elif stringp(v):
return v != ''
return v | [
"def",
"boolean",
"(",
"v",
")",
":",
"if",
"nodesetp",
"(",
"v",
")",
":",
"return",
"len",
"(",
"v",
")",
">",
"0",
"elif",
"numberp",
"(",
"v",
")",
":",
"if",
"v",
"==",
"0",
"or",
"v",
"!=",
"v",
":",
"return",
"False",
"return",
"True",
"elif",
"stringp",
"(",
"v",
")",
":",
"return",
"v",
"!=",
"''",
"return",
"v"
] | Convert a value to a boolean. | [
"Convert",
"a",
"value",
"to",
"a",
"boolean",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L117-L127 |
248,135 | gabrielfalcao/dominic | dominic/xpath/expr.py | number | def number(v):
"""Convert a value to a number."""
if nodesetp(v):
v = string(v)
try:
return float(v)
except ValueError:
return float('NaN') | python | def number(v):
"""Convert a value to a number."""
if nodesetp(v):
v = string(v)
try:
return float(v)
except ValueError:
return float('NaN') | [
"def",
"number",
"(",
"v",
")",
":",
"if",
"nodesetp",
"(",
"v",
")",
":",
"v",
"=",
"string",
"(",
"v",
")",
"try",
":",
"return",
"float",
"(",
"v",
")",
"except",
"ValueError",
":",
"return",
"float",
"(",
"'NaN'",
")"
] | Convert a value to a number. | [
"Convert",
"a",
"value",
"to",
"a",
"number",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L133-L140 |
248,136 | gabrielfalcao/dominic | dominic/xpath/expr.py | numberp | def numberp(v):
"""Return true iff 'v' is a number."""
return (not(isinstance(v, bool)) and
(isinstance(v, int) or isinstance(v, float))) | python | def numberp(v):
"""Return true iff 'v' is a number."""
return (not(isinstance(v, bool)) and
(isinstance(v, int) or isinstance(v, float))) | [
"def",
"numberp",
"(",
"v",
")",
":",
"return",
"(",
"not",
"(",
"isinstance",
"(",
"v",
",",
"bool",
")",
")",
"and",
"(",
"isinstance",
"(",
"v",
",",
"int",
")",
"or",
"isinstance",
"(",
"v",
",",
"float",
")",
")",
")"
] | Return true iff 'v' is a number. | [
"Return",
"true",
"iff",
"v",
"is",
"a",
"number",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L142-L145 |
248,137 | gabrielfalcao/dominic | dominic/xpath/expr.py | axisfn | def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE):
"""Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node type.
"""
def decorate(f):
f.__name__ = f.__name__.replace('_', '-')
f.reverse = reverse
f.principal_node_type = principal_node_type
return f
return decorate | python | def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE):
"""Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node type.
"""
def decorate(f):
f.__name__ = f.__name__.replace('_', '-')
f.reverse = reverse
f.principal_node_type = principal_node_type
return f
return decorate | [
"def",
"axisfn",
"(",
"reverse",
"=",
"False",
",",
"principal_node_type",
"=",
"xml",
".",
"dom",
".",
"Node",
".",
"ELEMENT_NODE",
")",
":",
"def",
"decorate",
"(",
"f",
")",
":",
"f",
".",
"__name__",
"=",
"f",
".",
"__name__",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"f",
".",
"reverse",
"=",
"reverse",
"f",
".",
"principal_node_type",
"=",
"principal_node_type",
"return",
"f",
"return",
"decorate"
] | Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node type. | [
"Axis",
"function",
"decorator",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L580-L592 |
248,138 | gabrielfalcao/dominic | dominic/xpath/expr.py | make_axes | def make_axes():
"""Define functions to walk each of the possible XPath axes."""
@axisfn()
def child(node):
return node.childNodes
@axisfn()
def descendant(node):
for child in node.childNodes:
for node in descendant_or_self(child):
yield node
@axisfn()
def parent(node):
if node.parentNode is not None:
yield node.parentNode
@axisfn(reverse=True)
def ancestor(node):
while node.parentNode is not None:
node = node.parentNode
yield node
@axisfn()
def following_sibling(node):
while node.nextSibling is not None:
node = node.nextSibling
yield node
@axisfn(reverse=True)
def preceding_sibling(node):
while node.previousSibling is not None:
node = node.previousSibling
yield node
@axisfn()
def following(node):
while node is not None:
while node.nextSibling is not None:
node = node.nextSibling
for n in descendant_or_self(node):
yield n
node = node.parentNode
@axisfn(reverse=True)
def preceding(node):
while node is not None:
while node.previousSibling is not None:
node = node.previousSibling
# Could be more efficient here.
for n in reversed(list(descendant_or_self(node))):
yield n
node = node.parentNode
@axisfn(principal_node_type=xml.dom.Node.ATTRIBUTE_NODE)
def attribute(node):
if node.attributes is not None:
return (node.attributes.item(i)
for i in xrange(node.attributes.length))
return ()
@axisfn()
def namespace(node):
raise XPathNotImplementedError("namespace axis is not implemented")
@axisfn()
def self(node):
yield node
@axisfn()
def descendant_or_self(node):
yield node
for child in node.childNodes:
for node in descendant_or_self(child):
yield node
@axisfn(reverse=True)
def ancestor_or_self(node):
return chain([node], ancestor(node))
# Place each axis function defined here into the 'axes' dict.
for axis in locals().values():
axes[axis.__name__] = axis | python | def make_axes():
"""Define functions to walk each of the possible XPath axes."""
@axisfn()
def child(node):
return node.childNodes
@axisfn()
def descendant(node):
for child in node.childNodes:
for node in descendant_or_self(child):
yield node
@axisfn()
def parent(node):
if node.parentNode is not None:
yield node.parentNode
@axisfn(reverse=True)
def ancestor(node):
while node.parentNode is not None:
node = node.parentNode
yield node
@axisfn()
def following_sibling(node):
while node.nextSibling is not None:
node = node.nextSibling
yield node
@axisfn(reverse=True)
def preceding_sibling(node):
while node.previousSibling is not None:
node = node.previousSibling
yield node
@axisfn()
def following(node):
while node is not None:
while node.nextSibling is not None:
node = node.nextSibling
for n in descendant_or_self(node):
yield n
node = node.parentNode
@axisfn(reverse=True)
def preceding(node):
while node is not None:
while node.previousSibling is not None:
node = node.previousSibling
# Could be more efficient here.
for n in reversed(list(descendant_or_self(node))):
yield n
node = node.parentNode
@axisfn(principal_node_type=xml.dom.Node.ATTRIBUTE_NODE)
def attribute(node):
if node.attributes is not None:
return (node.attributes.item(i)
for i in xrange(node.attributes.length))
return ()
@axisfn()
def namespace(node):
raise XPathNotImplementedError("namespace axis is not implemented")
@axisfn()
def self(node):
yield node
@axisfn()
def descendant_or_self(node):
yield node
for child in node.childNodes:
for node in descendant_or_self(child):
yield node
@axisfn(reverse=True)
def ancestor_or_self(node):
return chain([node], ancestor(node))
# Place each axis function defined here into the 'axes' dict.
for axis in locals().values():
axes[axis.__name__] = axis | [
"def",
"make_axes",
"(",
")",
":",
"@",
"axisfn",
"(",
")",
"def",
"child",
"(",
"node",
")",
":",
"return",
"node",
".",
"childNodes",
"@",
"axisfn",
"(",
")",
"def",
"descendant",
"(",
"node",
")",
":",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"for",
"node",
"in",
"descendant_or_self",
"(",
"child",
")",
":",
"yield",
"node",
"@",
"axisfn",
"(",
")",
"def",
"parent",
"(",
"node",
")",
":",
"if",
"node",
".",
"parentNode",
"is",
"not",
"None",
":",
"yield",
"node",
".",
"parentNode",
"@",
"axisfn",
"(",
"reverse",
"=",
"True",
")",
"def",
"ancestor",
"(",
"node",
")",
":",
"while",
"node",
".",
"parentNode",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"parentNode",
"yield",
"node",
"@",
"axisfn",
"(",
")",
"def",
"following_sibling",
"(",
"node",
")",
":",
"while",
"node",
".",
"nextSibling",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"nextSibling",
"yield",
"node",
"@",
"axisfn",
"(",
"reverse",
"=",
"True",
")",
"def",
"preceding_sibling",
"(",
"node",
")",
":",
"while",
"node",
".",
"previousSibling",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"previousSibling",
"yield",
"node",
"@",
"axisfn",
"(",
")",
"def",
"following",
"(",
"node",
")",
":",
"while",
"node",
"is",
"not",
"None",
":",
"while",
"node",
".",
"nextSibling",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"nextSibling",
"for",
"n",
"in",
"descendant_or_self",
"(",
"node",
")",
":",
"yield",
"n",
"node",
"=",
"node",
".",
"parentNode",
"@",
"axisfn",
"(",
"reverse",
"=",
"True",
")",
"def",
"preceding",
"(",
"node",
")",
":",
"while",
"node",
"is",
"not",
"None",
":",
"while",
"node",
".",
"previousSibling",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"previousSibling",
"# Could be more efficient here.",
"for",
"n",
"in",
"reversed",
"(",
"list",
"(",
"descendant_or_self",
"(",
"node",
")",
")",
")",
":",
"yield",
"n",
"node",
"=",
"node",
".",
"parentNode",
"@",
"axisfn",
"(",
"principal_node_type",
"=",
"xml",
".",
"dom",
".",
"Node",
".",
"ATTRIBUTE_NODE",
")",
"def",
"attribute",
"(",
"node",
")",
":",
"if",
"node",
".",
"attributes",
"is",
"not",
"None",
":",
"return",
"(",
"node",
".",
"attributes",
".",
"item",
"(",
"i",
")",
"for",
"i",
"in",
"xrange",
"(",
"node",
".",
"attributes",
".",
"length",
")",
")",
"return",
"(",
")",
"@",
"axisfn",
"(",
")",
"def",
"namespace",
"(",
"node",
")",
":",
"raise",
"XPathNotImplementedError",
"(",
"\"namespace axis is not implemented\"",
")",
"@",
"axisfn",
"(",
")",
"def",
"self",
"(",
"node",
")",
":",
"yield",
"node",
"@",
"axisfn",
"(",
")",
"def",
"descendant_or_self",
"(",
"node",
")",
":",
"yield",
"node",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"for",
"node",
"in",
"descendant_or_self",
"(",
"child",
")",
":",
"yield",
"node",
"@",
"axisfn",
"(",
"reverse",
"=",
"True",
")",
"def",
"ancestor_or_self",
"(",
"node",
")",
":",
"return",
"chain",
"(",
"[",
"node",
"]",
",",
"ancestor",
"(",
"node",
")",
")",
"# Place each axis function defined here into the 'axes' dict.",
"for",
"axis",
"in",
"locals",
"(",
")",
".",
"values",
"(",
")",
":",
"axes",
"[",
"axis",
".",
"__name__",
"]",
"=",
"axis"
] | Define functions to walk each of the possible XPath axes. | [
"Define",
"functions",
"to",
"walk",
"each",
"of",
"the",
"possible",
"XPath",
"axes",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L594-L677 |
248,139 | gabrielfalcao/dominic | dominic/xpath/expr.py | merge_into_nodeset | def merge_into_nodeset(target, source):
"""Place all the nodes from the source node-set into the target
node-set, preserving document order. Both node-sets must be in
document order to begin with.
"""
if len(target) == 0:
target.extend(source)
return
source = [n for n in source if n not in target]
if len(source) == 0:
return
# If the last node in the target set comes before the first node in the
# source set, then we can just concatenate the sets. Otherwise, we
# will need to sort. (We could also check to see if the last node in
# the source set comes before the first node in the target set, but this
# situation is very unlikely in practice.)
if document_order(target[-1]) < document_order(source[0]):
target.extend(source)
else:
target.extend(source)
target.sort(key=document_order) | python | def merge_into_nodeset(target, source):
"""Place all the nodes from the source node-set into the target
node-set, preserving document order. Both node-sets must be in
document order to begin with.
"""
if len(target) == 0:
target.extend(source)
return
source = [n for n in source if n not in target]
if len(source) == 0:
return
# If the last node in the target set comes before the first node in the
# source set, then we can just concatenate the sets. Otherwise, we
# will need to sort. (We could also check to see if the last node in
# the source set comes before the first node in the target set, but this
# situation is very unlikely in practice.)
if document_order(target[-1]) < document_order(source[0]):
target.extend(source)
else:
target.extend(source)
target.sort(key=document_order) | [
"def",
"merge_into_nodeset",
"(",
"target",
",",
"source",
")",
":",
"if",
"len",
"(",
"target",
")",
"==",
"0",
":",
"target",
".",
"extend",
"(",
"source",
")",
"return",
"source",
"=",
"[",
"n",
"for",
"n",
"in",
"source",
"if",
"n",
"not",
"in",
"target",
"]",
"if",
"len",
"(",
"source",
")",
"==",
"0",
":",
"return",
"# If the last node in the target set comes before the first node in the",
"# source set, then we can just concatenate the sets. Otherwise, we",
"# will need to sort. (We could also check to see if the last node in",
"# the source set comes before the first node in the target set, but this",
"# situation is very unlikely in practice.)",
"if",
"document_order",
"(",
"target",
"[",
"-",
"1",
"]",
")",
"<",
"document_order",
"(",
"source",
"[",
"0",
"]",
")",
":",
"target",
".",
"extend",
"(",
"source",
")",
"else",
":",
"target",
".",
"extend",
"(",
"source",
")",
"target",
".",
"sort",
"(",
"key",
"=",
"document_order",
")"
] | Place all the nodes from the source node-set into the target
node-set, preserving document order. Both node-sets must be in
document order to begin with. | [
"Place",
"all",
"the",
"nodes",
"from",
"the",
"source",
"node",
"-",
"set",
"into",
"the",
"target",
"node",
"-",
"set",
"preserving",
"document",
"order",
".",
"Both",
"node",
"-",
"sets",
"must",
"be",
"in",
"document",
"order",
"to",
"begin",
"with",
"."
] | a42f418fc288f3b70cb95847b405eaf7b83bb3a0 | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L681-L704 |
248,140 | echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/natsd/driver.py | Requester.on_response | def on_response(self, msg):
"""
setup response if correlation id is the good one
"""
LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg)) + " bytes received")
working_response = json.loads(msg.data.decode())
working_properties = DriverTools.json2properties(working_response['properties'])
working_body = b''+bytes(working_response['body'], 'utf8') if 'body' in working_response else None
if DriverTools.MSG_CORRELATION_ID in working_properties:
if self.corr_id == working_properties[DriverTools.MSG_CORRELATION_ID]:
if DriverTools.MSG_SPLIT_COUNT in working_properties and \
int(working_properties[DriverTools.MSG_SPLIT_COUNT]) > 1:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
if self.split_responses is None:
self.split_responses = []
self.split_responses_mid = working_properties[DriverTools.MSG_SPLIT_MID]
if working_properties[DriverTools.MSG_SPLIT_MID] == self.split_responses_mid:
response = {
'properties': working_properties,
'body': working_body_decoded
}
self.split_responses.insert(int(working_properties[DriverTools.MSG_SPLIT_OID]), response)
if self.split_responses.__len__() == int(working_properties[DriverTools.MSG_SPLIT_COUNT]):
properties = {}
body = b''
for num in range(0, self.split_responses.__len__()):
properties.update(self.split_responses[num]['properties'])
body += self.split_responses[num]['body']
self.response = {
'properties': properties,
'body': body
}
self.split_responses = None
self.split_responses_mid = None
else:
LOGGER.warn("natsd.Requester.on_response - discarded response : (" +
str(working_properties[DriverTools.MSG_CORRELATION_ID]) + "," +
str(working_properties[DriverTools.MSG_SPLIT_MID]) + ")")
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
}))
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else \
bytes(json.dumps({}), 'utf8')
self.response = {
'properties': working_properties,
'body': working_body_decoded
}
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
LOGGER.warn("natsd.Requester.on_response - discarded response : " +
str(working_properties[DriverTools.MSG_CORRELATION_ID]))
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
}))
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
LOGGER.warn("natsd.Requester.on_response - discarded response (no correlation ID)")
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
})) | python | def on_response(self, msg):
"""
setup response if correlation id is the good one
"""
LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg)) + " bytes received")
working_response = json.loads(msg.data.decode())
working_properties = DriverTools.json2properties(working_response['properties'])
working_body = b''+bytes(working_response['body'], 'utf8') if 'body' in working_response else None
if DriverTools.MSG_CORRELATION_ID in working_properties:
if self.corr_id == working_properties[DriverTools.MSG_CORRELATION_ID]:
if DriverTools.MSG_SPLIT_COUNT in working_properties and \
int(working_properties[DriverTools.MSG_SPLIT_COUNT]) > 1:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
if self.split_responses is None:
self.split_responses = []
self.split_responses_mid = working_properties[DriverTools.MSG_SPLIT_MID]
if working_properties[DriverTools.MSG_SPLIT_MID] == self.split_responses_mid:
response = {
'properties': working_properties,
'body': working_body_decoded
}
self.split_responses.insert(int(working_properties[DriverTools.MSG_SPLIT_OID]), response)
if self.split_responses.__len__() == int(working_properties[DriverTools.MSG_SPLIT_COUNT]):
properties = {}
body = b''
for num in range(0, self.split_responses.__len__()):
properties.update(self.split_responses[num]['properties'])
body += self.split_responses[num]['body']
self.response = {
'properties': properties,
'body': body
}
self.split_responses = None
self.split_responses_mid = None
else:
LOGGER.warn("natsd.Requester.on_response - discarded response : (" +
str(working_properties[DriverTools.MSG_CORRELATION_ID]) + "," +
str(working_properties[DriverTools.MSG_SPLIT_MID]) + ")")
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
}))
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else \
bytes(json.dumps({}), 'utf8')
self.response = {
'properties': working_properties,
'body': working_body_decoded
}
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
LOGGER.warn("natsd.Requester.on_response - discarded response : " +
str(working_properties[DriverTools.MSG_CORRELATION_ID]))
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
}))
else:
working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
LOGGER.warn("natsd.Requester.on_response - discarded response (no correlation ID)")
LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
'properties': working_properties,
'body': working_body_decoded
})) | [
"def",
"on_response",
"(",
"self",
",",
"msg",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response: \"",
"+",
"str",
"(",
"sys",
".",
"getsizeof",
"(",
"msg",
")",
")",
"+",
"\" bytes received\"",
")",
"working_response",
"=",
"json",
".",
"loads",
"(",
"msg",
".",
"data",
".",
"decode",
"(",
")",
")",
"working_properties",
"=",
"DriverTools",
".",
"json2properties",
"(",
"working_response",
"[",
"'properties'",
"]",
")",
"working_body",
"=",
"b''",
"+",
"bytes",
"(",
"working_response",
"[",
"'body'",
"]",
",",
"'utf8'",
")",
"if",
"'body'",
"in",
"working_response",
"else",
"None",
"if",
"DriverTools",
".",
"MSG_CORRELATION_ID",
"in",
"working_properties",
":",
"if",
"self",
".",
"corr_id",
"==",
"working_properties",
"[",
"DriverTools",
".",
"MSG_CORRELATION_ID",
"]",
":",
"if",
"DriverTools",
".",
"MSG_SPLIT_COUNT",
"in",
"working_properties",
"and",
"int",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_COUNT",
"]",
")",
">",
"1",
":",
"working_body_decoded",
"=",
"base64",
".",
"b64decode",
"(",
"working_body",
")",
"if",
"working_body",
"is",
"not",
"None",
"else",
"None",
"if",
"self",
".",
"split_responses",
"is",
"None",
":",
"self",
".",
"split_responses",
"=",
"[",
"]",
"self",
".",
"split_responses_mid",
"=",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_MID",
"]",
"if",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_MID",
"]",
"==",
"self",
".",
"split_responses_mid",
":",
"response",
"=",
"{",
"'properties'",
":",
"working_properties",
",",
"'body'",
":",
"working_body_decoded",
"}",
"self",
".",
"split_responses",
".",
"insert",
"(",
"int",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_OID",
"]",
")",
",",
"response",
")",
"if",
"self",
".",
"split_responses",
".",
"__len__",
"(",
")",
"==",
"int",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_COUNT",
"]",
")",
":",
"properties",
"=",
"{",
"}",
"body",
"=",
"b''",
"for",
"num",
"in",
"range",
"(",
"0",
",",
"self",
".",
"split_responses",
".",
"__len__",
"(",
")",
")",
":",
"properties",
".",
"update",
"(",
"self",
".",
"split_responses",
"[",
"num",
"]",
"[",
"'properties'",
"]",
")",
"body",
"+=",
"self",
".",
"split_responses",
"[",
"num",
"]",
"[",
"'body'",
"]",
"self",
".",
"response",
"=",
"{",
"'properties'",
":",
"properties",
",",
"'body'",
":",
"body",
"}",
"self",
".",
"split_responses",
"=",
"None",
"self",
".",
"split_responses_mid",
"=",
"None",
"else",
":",
"LOGGER",
".",
"warn",
"(",
"\"natsd.Requester.on_response - discarded response : (\"",
"+",
"str",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_CORRELATION_ID",
"]",
")",
"+",
"\",\"",
"+",
"str",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_SPLIT_MID",
"]",
")",
"+",
"\")\"",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"working_properties",
",",
"'body'",
":",
"working_body_decoded",
"}",
")",
")",
"else",
":",
"working_body_decoded",
"=",
"base64",
".",
"b64decode",
"(",
"working_body",
")",
"if",
"working_body",
"is",
"not",
"None",
"else",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"{",
"}",
")",
",",
"'utf8'",
")",
"self",
".",
"response",
"=",
"{",
"'properties'",
":",
"working_properties",
",",
"'body'",
":",
"working_body_decoded",
"}",
"else",
":",
"working_body_decoded",
"=",
"base64",
".",
"b64decode",
"(",
"working_body",
")",
"if",
"working_body",
"is",
"not",
"None",
"else",
"None",
"LOGGER",
".",
"warn",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"working_properties",
"[",
"DriverTools",
".",
"MSG_CORRELATION_ID",
"]",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"working_properties",
",",
"'body'",
":",
"working_body_decoded",
"}",
")",
")",
"else",
":",
"working_body_decoded",
"=",
"base64",
".",
"b64decode",
"(",
"working_body",
")",
"if",
"working_body",
"is",
"not",
"None",
"else",
"None",
"LOGGER",
".",
"warn",
"(",
"\"natsd.Requester.on_response - discarded response (no correlation ID)\"",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"working_properties",
",",
"'body'",
":",
"working_body_decoded",
"}",
")",
")"
] | setup response if correlation id is the good one | [
"setup",
"response",
"if",
"correlation",
"id",
"is",
"the",
"good",
"one"
] | 0a7feddebf66fee4bef38d64f456d93a7e9fcd68 | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/natsd/driver.py#L243-L308 |
248,141 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.ttl | def ttl(self):
"""Get actual ttl in seconds.
:return: actual ttl.
:rtype: float
"""
# result is self ts
result = getattr(self, Annotation.__TS, None)
# if result is not None
if result is not None:
# result is now - result
now = time()
result = result - now
return result | python | def ttl(self):
"""Get actual ttl in seconds.
:return: actual ttl.
:rtype: float
"""
# result is self ts
result = getattr(self, Annotation.__TS, None)
# if result is not None
if result is not None:
# result is now - result
now = time()
result = result - now
return result | [
"def",
"ttl",
"(",
"self",
")",
":",
"# result is self ts",
"result",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"None",
")",
"# if result is not None",
"if",
"result",
"is",
"not",
"None",
":",
"# result is now - result",
"now",
"=",
"time",
"(",
")",
"result",
"=",
"result",
"-",
"now",
"return",
"result"
] | Get actual ttl in seconds.
:return: actual ttl.
:rtype: float | [
"Get",
"actual",
"ttl",
"in",
"seconds",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L191-L206 |
248,142 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.ttl | def ttl(self, value):
"""Change self ttl with input value.
:param float value: new ttl in seconds.
"""
# get timer
timer = getattr(self, Annotation.__TIMER, None)
# if timer is running, stop the timer
if timer is not None:
timer.cancel()
# initialize timestamp
timestamp = None
# if value is None
if value is None:
# nonify timer
timer = None
else: # else, renew a timer
# get timestamp
timestamp = time() + value
# start a new timer
timer = Timer(value, self.__del__)
timer.start()
# set/update attributes
setattr(self, Annotation.__TIMER, timer)
setattr(self, Annotation.__TS, timestamp) | python | def ttl(self, value):
"""Change self ttl with input value.
:param float value: new ttl in seconds.
"""
# get timer
timer = getattr(self, Annotation.__TIMER, None)
# if timer is running, stop the timer
if timer is not None:
timer.cancel()
# initialize timestamp
timestamp = None
# if value is None
if value is None:
# nonify timer
timer = None
else: # else, renew a timer
# get timestamp
timestamp = time() + value
# start a new timer
timer = Timer(value, self.__del__)
timer.start()
# set/update attributes
setattr(self, Annotation.__TIMER, timer)
setattr(self, Annotation.__TS, timestamp) | [
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")",
"# initialize timestamp",
"timestamp",
"=",
"None",
"# if value is None",
"if",
"value",
"is",
"None",
":",
"# nonify timer",
"timer",
"=",
"None",
"else",
":",
"# else, renew a timer",
"# get timestamp",
"timestamp",
"=",
"time",
"(",
")",
"+",
"value",
"# start a new timer",
"timer",
"=",
"Timer",
"(",
"value",
",",
"self",
".",
"__del__",
")",
"timer",
".",
"start",
"(",
")",
"# set/update attributes",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"timer",
")",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"timestamp",
")"
] | Change self ttl with input value.
:param float value: new ttl in seconds. | [
"Change",
"self",
"ttl",
"with",
"input",
"value",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L209-L239 |
248,143 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.in_memory | def in_memory(self, value):
"""Add or remove self from global memory.
:param bool value: if True(False) ensure self is(is not) in memory.
"""
self_class = self.__class__
memory = Annotation.__ANNOTATIONS_IN_MEMORY__
if value:
annotations_memory = memory.setdefault(self_class, set())
annotations_memory.add(self)
else:
if self_class in memory:
annotations_memory = memory[self_class]
while self in annotations_memory:
annotations_memory.remove(self)
if not annotations_memory:
del memory[self_class] | python | def in_memory(self, value):
"""Add or remove self from global memory.
:param bool value: if True(False) ensure self is(is not) in memory.
"""
self_class = self.__class__
memory = Annotation.__ANNOTATIONS_IN_MEMORY__
if value:
annotations_memory = memory.setdefault(self_class, set())
annotations_memory.add(self)
else:
if self_class in memory:
annotations_memory = memory[self_class]
while self in annotations_memory:
annotations_memory.remove(self)
if not annotations_memory:
del memory[self_class] | [
"def",
"in_memory",
"(",
"self",
",",
"value",
")",
":",
"self_class",
"=",
"self",
".",
"__class__",
"memory",
"=",
"Annotation",
".",
"__ANNOTATIONS_IN_MEMORY__",
"if",
"value",
":",
"annotations_memory",
"=",
"memory",
".",
"setdefault",
"(",
"self_class",
",",
"set",
"(",
")",
")",
"annotations_memory",
".",
"add",
"(",
"self",
")",
"else",
":",
"if",
"self_class",
"in",
"memory",
":",
"annotations_memory",
"=",
"memory",
"[",
"self_class",
"]",
"while",
"self",
"in",
"annotations_memory",
":",
"annotations_memory",
".",
"remove",
"(",
"self",
")",
"if",
"not",
"annotations_memory",
":",
"del",
"memory",
"[",
"self_class",
"]"
] | Add or remove self from global memory.
:param bool value: if True(False) ensure self is(is not) in memory. | [
"Add",
"or",
"remove",
"self",
"from",
"global",
"memory",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L256-L275 |
248,144 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.bind_target | def bind_target(self, target, ctx=None):
"""Bind self annotation to target.
:param target: target to annotate.
:param ctx: target ctx.
:return: bound target.
"""
# process self _bind_target
result = self._bind_target(target=target, ctx=ctx)
# fire on bind target event
self.on_bind_target(target=target, ctx=ctx)
return result | python | def bind_target(self, target, ctx=None):
"""Bind self annotation to target.
:param target: target to annotate.
:param ctx: target ctx.
:return: bound target.
"""
# process self _bind_target
result = self._bind_target(target=target, ctx=ctx)
# fire on bind target event
self.on_bind_target(target=target, ctx=ctx)
return result | [
"def",
"bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"# process self _bind_target",
"result",
"=",
"self",
".",
"_bind_target",
"(",
"target",
"=",
"target",
",",
"ctx",
"=",
"ctx",
")",
"# fire on bind target event",
"self",
".",
"on_bind_target",
"(",
"target",
"=",
"target",
",",
"ctx",
"=",
"ctx",
")",
"return",
"result"
] | Bind self annotation to target.
:param target: target to annotate.
:param ctx: target ctx.
:return: bound target. | [
"Bind",
"self",
"annotation",
"to",
"target",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L277-L291 |
248,145 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation._bind_target | def _bind_target(self, target, ctx=None):
"""Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target.
"""
result = target
try:
# get annotations from target if exists.
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, [], ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable.'.format(target))
# if local_annotations do not exist, put them in target
if not local_annotations:
put_properties(
target,
properties={Annotation.__ANNOTATIONS_KEY__: local_annotations},
ctx=ctx
)
# insert self at first position
local_annotations.insert(0, self)
# add target to self targets
if target not in self.targets:
self.targets.append(target)
return result | python | def _bind_target(self, target, ctx=None):
"""Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target.
"""
result = target
try:
# get annotations from target if exists.
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, [], ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable.'.format(target))
# if local_annotations do not exist, put them in target
if not local_annotations:
put_properties(
target,
properties={Annotation.__ANNOTATIONS_KEY__: local_annotations},
ctx=ctx
)
# insert self at first position
local_annotations.insert(0, self)
# add target to self targets
if target not in self.targets:
self.targets.append(target)
return result | [
"def",
"_bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"target",
"try",
":",
"# get annotations from target if exists.",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"[",
"]",
",",
"ctx",
"=",
"ctx",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'target {0} must be hashable.'",
".",
"format",
"(",
"target",
")",
")",
"# if local_annotations do not exist, put them in target",
"if",
"not",
"local_annotations",
":",
"put_properties",
"(",
"target",
",",
"properties",
"=",
"{",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
":",
"local_annotations",
"}",
",",
"ctx",
"=",
"ctx",
")",
"# insert self at first position",
"local_annotations",
".",
"insert",
"(",
"0",
",",
"self",
")",
"# add target to self targets",
"if",
"target",
"not",
"in",
"self",
".",
"targets",
":",
"self",
".",
"targets",
".",
"append",
"(",
"target",
")",
"return",
"result"
] | Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target. | [
"Method",
"to",
"override",
"in",
"order",
"to",
"specialize",
"binding",
"of",
"target",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L293-L326 |
248,146 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.on_bind_target | def on_bind_target(self, target, ctx=None):
"""Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx.
"""
_on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None)
if _on_bind_target is not None:
_on_bind_target(self, target=target, ctx=ctx) | python | def on_bind_target(self, target, ctx=None):
"""Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx.
"""
_on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None)
if _on_bind_target is not None:
_on_bind_target(self, target=target, ctx=ctx) | [
"def",
"on_bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"_on_bind_target",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"_ON_BIND_TARGET",
",",
"None",
")",
"if",
"_on_bind_target",
"is",
"not",
"None",
":",
"_on_bind_target",
"(",
"self",
",",
"target",
"=",
"target",
",",
"ctx",
"=",
"ctx",
")"
] | Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx. | [
"Fired",
"after",
"target",
"is",
"bound",
"to",
"self",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L328-L338 |
248,147 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.remove_from | def remove_from(self, target, ctx=None):
"""Remove self annotation from target annotations.
:param target: target from where remove self annotation.
:param ctx: target ctx.
"""
annotations_key = Annotation.__ANNOTATIONS_KEY__
try:
# get local annotations
local_annotations = get_local_property(
target, annotations_key, ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
# if local annotations exist
if local_annotations is not None:
# if target in self.targets
if target in self.targets:
# remove target from self.targets
self.targets.remove(target)
# and remove all self annotations from local_annotations
while self in local_annotations:
local_annotations.remove(self)
# if target is not annotated anymore, remove the empty list
if not local_annotations:
del_properties(target, annotations_key) | python | def remove_from(self, target, ctx=None):
"""Remove self annotation from target annotations.
:param target: target from where remove self annotation.
:param ctx: target ctx.
"""
annotations_key = Annotation.__ANNOTATIONS_KEY__
try:
# get local annotations
local_annotations = get_local_property(
target, annotations_key, ctx=ctx
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
# if local annotations exist
if local_annotations is not None:
# if target in self.targets
if target in self.targets:
# remove target from self.targets
self.targets.remove(target)
# and remove all self annotations from local_annotations
while self in local_annotations:
local_annotations.remove(self)
# if target is not annotated anymore, remove the empty list
if not local_annotations:
del_properties(target, annotations_key) | [
"def",
"remove_from",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"annotations_key",
"=",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
"try",
":",
"# get local annotations",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"annotations_key",
",",
"ctx",
"=",
"ctx",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'target {0} must be hashable'",
".",
"format",
"(",
"target",
")",
")",
"# if local annotations exist",
"if",
"local_annotations",
"is",
"not",
"None",
":",
"# if target in self.targets",
"if",
"target",
"in",
"self",
".",
"targets",
":",
"# remove target from self.targets",
"self",
".",
"targets",
".",
"remove",
"(",
"target",
")",
"# and remove all self annotations from local_annotations",
"while",
"self",
"in",
"local_annotations",
":",
"local_annotations",
".",
"remove",
"(",
"self",
")",
"# if target is not annotated anymore, remove the empty list",
"if",
"not",
"local_annotations",
":",
"del_properties",
"(",
"target",
",",
"annotations_key",
")"
] | Remove self annotation from target annotations.
:param target: target from where remove self annotation.
:param ctx: target ctx. | [
"Remove",
"self",
"annotation",
"from",
"target",
"annotations",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L340-L368 |
248,148 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.free_memory | def free_memory(cls, exclude=None):
"""Free global annotation memory."""
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
for annotation_cls in list(annotations_in_memory.keys()):
if issubclass(annotation_cls, exclude):
continue
if issubclass(annotation_cls, cls):
del annotations_in_memory[annotation_cls] | python | def free_memory(cls, exclude=None):
"""Free global annotation memory."""
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
for annotation_cls in list(annotations_in_memory.keys()):
if issubclass(annotation_cls, exclude):
continue
if issubclass(annotation_cls, cls):
del annotations_in_memory[annotation_cls] | [
"def",
"free_memory",
"(",
"cls",
",",
"exclude",
"=",
"None",
")",
":",
"annotations_in_memory",
"=",
"Annotation",
".",
"__ANNOTATIONS_IN_MEMORY__",
"exclude",
"=",
"(",
")",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"for",
"annotation_cls",
"in",
"list",
"(",
"annotations_in_memory",
".",
"keys",
"(",
")",
")",
":",
"if",
"issubclass",
"(",
"annotation_cls",
",",
"exclude",
")",
":",
"continue",
"if",
"issubclass",
"(",
"annotation_cls",
",",
"cls",
")",
":",
"del",
"annotations_in_memory",
"[",
"annotation_cls",
"]"
] | Free global annotation memory. | [
"Free",
"global",
"annotation",
"memory",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L371-L384 |
248,149 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.get_memory_annotations | def get_memory_annotations(cls, exclude=None):
"""Get annotations in memory which inherits from cls.
:param tuple/type exclude: annotation type(s) to exclude from search.
:return: found annotations which inherits from cls.
:rtype: set
"""
result = set()
# get global dictionary
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
# iterate on annotation classes
for annotation_cls in annotations_in_memory:
# if annotation class is excluded, continue
if issubclass(annotation_cls, exclude):
continue
# if annotation class inherits from self, add it in the result
if issubclass(annotation_cls, cls):
result |= annotations_in_memory[annotation_cls]
return result | python | def get_memory_annotations(cls, exclude=None):
"""Get annotations in memory which inherits from cls.
:param tuple/type exclude: annotation type(s) to exclude from search.
:return: found annotations which inherits from cls.
:rtype: set
"""
result = set()
# get global dictionary
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
# iterate on annotation classes
for annotation_cls in annotations_in_memory:
# if annotation class is excluded, continue
if issubclass(annotation_cls, exclude):
continue
# if annotation class inherits from self, add it in the result
if issubclass(annotation_cls, cls):
result |= annotations_in_memory[annotation_cls]
return result | [
"def",
"get_memory_annotations",
"(",
"cls",
",",
"exclude",
"=",
"None",
")",
":",
"result",
"=",
"set",
"(",
")",
"# get global dictionary",
"annotations_in_memory",
"=",
"Annotation",
".",
"__ANNOTATIONS_IN_MEMORY__",
"exclude",
"=",
"(",
")",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"# iterate on annotation classes",
"for",
"annotation_cls",
"in",
"annotations_in_memory",
":",
"# if annotation class is excluded, continue",
"if",
"issubclass",
"(",
"annotation_cls",
",",
"exclude",
")",
":",
"continue",
"# if annotation class inherits from self, add it in the result",
"if",
"issubclass",
"(",
"annotation_cls",
",",
"cls",
")",
":",
"result",
"|=",
"annotations_in_memory",
"[",
"annotation_cls",
"]",
"return",
"result"
] | Get annotations in memory which inherits from cls.
:param tuple/type exclude: annotation type(s) to exclude from search.
:return: found annotations which inherits from cls.
:rtype: set | [
"Get",
"annotations",
"in",
"memory",
"which",
"inherits",
"from",
"cls",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L387-L413 |
248,150 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.get_local_annotations | def get_local_annotations(
cls, target, exclude=None, ctx=None, select=lambda *p: True
):
"""Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: selection function which takes in parameters a target,
a ctx and an annotation and returns True if the annotation has to
be selected. True by default.
:return: target local annotations.
:rtype: list
"""
result = []
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx
)
if not local_annotations:
if ismethod(target):
func = get_method_function(target)
local_annotations = get_local_property(
func, Annotation.__ANNOTATIONS_KEY__,
result, ctx=ctx
)
if not local_annotations:
local_annotations = get_local_property(
func, Annotation.__ANNOTATIONS_KEY__,
result
)
elif isfunction(target):
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__,
result
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
for local_annotation in local_annotations:
# check if local annotation inherits from cls
inherited = isinstance(local_annotation, cls)
# and if not excluded
not_excluded = not isinstance(local_annotation, exclude)
# and if selected
selected = select(target, ctx, local_annotation)
# if three conditions, add local annotation to the result
if inherited and not_excluded and selected:
result.append(local_annotation)
return result | python | def get_local_annotations(
cls, target, exclude=None, ctx=None, select=lambda *p: True
):
"""Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: selection function which takes in parameters a target,
a ctx and an annotation and returns True if the annotation has to
be selected. True by default.
:return: target local annotations.
:rtype: list
"""
result = []
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx
)
if not local_annotations:
if ismethod(target):
func = get_method_function(target)
local_annotations = get_local_property(
func, Annotation.__ANNOTATIONS_KEY__,
result, ctx=ctx
)
if not local_annotations:
local_annotations = get_local_property(
func, Annotation.__ANNOTATIONS_KEY__,
result
)
elif isfunction(target):
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__,
result
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
for local_annotation in local_annotations:
# check if local annotation inherits from cls
inherited = isinstance(local_annotation, cls)
# and if not excluded
not_excluded = not isinstance(local_annotation, exclude)
# and if selected
selected = select(target, ctx, local_annotation)
# if three conditions, add local annotation to the result
if inherited and not_excluded and selected:
result.append(local_annotation)
return result | [
"def",
"get_local_annotations",
"(",
"cls",
",",
"target",
",",
"exclude",
"=",
"None",
",",
"ctx",
"=",
"None",
",",
"select",
"=",
"lambda",
"*",
"p",
":",
"True",
")",
":",
"result",
"=",
"[",
"]",
"# initialize exclude",
"exclude",
"=",
"(",
")",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"try",
":",
"# get local annotations",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"result",
",",
"ctx",
"=",
"ctx",
")",
"if",
"not",
"local_annotations",
":",
"if",
"ismethod",
"(",
"target",
")",
":",
"func",
"=",
"get_method_function",
"(",
"target",
")",
"local_annotations",
"=",
"get_local_property",
"(",
"func",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"result",
",",
"ctx",
"=",
"ctx",
")",
"if",
"not",
"local_annotations",
":",
"local_annotations",
"=",
"get_local_property",
"(",
"func",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"result",
")",
"elif",
"isfunction",
"(",
"target",
")",
":",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"result",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'target {0} must be hashable'",
".",
"format",
"(",
"target",
")",
")",
"for",
"local_annotation",
"in",
"local_annotations",
":",
"# check if local annotation inherits from cls",
"inherited",
"=",
"isinstance",
"(",
"local_annotation",
",",
"cls",
")",
"# and if not excluded",
"not_excluded",
"=",
"not",
"isinstance",
"(",
"local_annotation",
",",
"exclude",
")",
"# and if selected",
"selected",
"=",
"select",
"(",
"target",
",",
"ctx",
",",
"local_annotation",
")",
"# if three conditions, add local annotation to the result",
"if",
"inherited",
"and",
"not_excluded",
"and",
"selected",
":",
"result",
".",
"append",
"(",
"local_annotation",
")",
"return",
"result"
] | Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: selection function which takes in parameters a target,
a ctx and an annotation and returns True if the annotation has to
be selected. True by default.
:return: target local annotations.
:rtype: list | [
"Get",
"a",
"list",
"of",
"local",
"target",
"annotations",
"in",
"the",
"order",
"of",
"their",
"definition",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L416-L476 |
248,151 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.remove | def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):
"""Remove from target annotations which inherit from cls.
:param target: target from where remove annotations which inherits from
cls.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: annotation selection function which takes in parameters
a target, a ctx and an annotation and return True if the annotation
has to be removed.
"""
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
# if there are local annotations
if local_annotations is not None:
# get annotations to remove which inherits from cls
annotations_to_remove = [
annotation for annotation in local_annotations
if (
isinstance(annotation, cls)
and not isinstance(annotation, exclude)
and select(target, ctx, annotation)
)
]
# and remove annotations from target
for annotation_to_remove in annotations_to_remove:
annotation_to_remove.remove_from(target) | python | def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):
"""Remove from target annotations which inherit from cls.
:param target: target from where remove annotations which inherits from
cls.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: annotation selection function which takes in parameters
a target, a ctx and an annotation and return True if the annotation
has to be removed.
"""
# initialize exclude
exclude = () if exclude is None else exclude
try:
# get local annotations
local_annotations = get_local_property(
target, Annotation.__ANNOTATIONS_KEY__
)
except TypeError:
raise TypeError('target {0} must be hashable'.format(target))
# if there are local annotations
if local_annotations is not None:
# get annotations to remove which inherits from cls
annotations_to_remove = [
annotation for annotation in local_annotations
if (
isinstance(annotation, cls)
and not isinstance(annotation, exclude)
and select(target, ctx, annotation)
)
]
# and remove annotations from target
for annotation_to_remove in annotations_to_remove:
annotation_to_remove.remove_from(target) | [
"def",
"remove",
"(",
"cls",
",",
"target",
",",
"exclude",
"=",
"None",
",",
"ctx",
"=",
"None",
",",
"select",
"=",
"lambda",
"*",
"p",
":",
"True",
")",
":",
"# initialize exclude",
"exclude",
"=",
"(",
")",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"try",
":",
"# get local annotations",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'target {0} must be hashable'",
".",
"format",
"(",
"target",
")",
")",
"# if there are local annotations",
"if",
"local_annotations",
"is",
"not",
"None",
":",
"# get annotations to remove which inherits from cls",
"annotations_to_remove",
"=",
"[",
"annotation",
"for",
"annotation",
"in",
"local_annotations",
"if",
"(",
"isinstance",
"(",
"annotation",
",",
"cls",
")",
"and",
"not",
"isinstance",
"(",
"annotation",
",",
"exclude",
")",
"and",
"select",
"(",
"target",
",",
"ctx",
",",
"annotation",
")",
")",
"]",
"# and remove annotations from target",
"for",
"annotation_to_remove",
"in",
"annotations_to_remove",
":",
"annotation_to_remove",
".",
"remove_from",
"(",
"target",
")"
] | Remove from target annotations which inherit from cls.
:param target: target from where remove annotations which inherits from
cls.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: annotation selection function which takes in parameters
a target, a ctx and an annotation and return True if the annotation
has to be removed. | [
"Remove",
"from",
"target",
"annotations",
"which",
"inherit",
"from",
"cls",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L479-L518 |
248,152 | b3j0f/annotation | b3j0f/annotation/core.py | Annotation.get_annotations | def get_annotations(
cls, target,
exclude=None, ctx=None, select=lambda *p: True,
mindepth=0, maxdepth=0, followannotated=True, public=True,
_history=None
):
"""Returns all input target annotations of cls type sorted
by definition order.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to remove from selection.
:param ctx: target ctx.
:param select: bool function which select annotations after applying
previous type filters. Takes a target, a ctx and an annotation in
parameters. True by default.
:param int mindepth: minimal depth for searching annotations (default 0)
:param int maxdepth: maximal depth for searching annotations (default 0)
:param bool followannotated: if True (default) follow deeply only
annotated members.
:param bool public: if True (default) follow public members.
:param list _history: private parameter which save parsed elements.
:rtype: Annotation
"""
result = []
if mindepth <= 0:
try:
annotations_by_ctx = get_property(
elt=target, key=Annotation.__ANNOTATIONS_KEY__, ctx=ctx
)
except TypeError:
annotations_by_ctx = {}
if not annotations_by_ctx:
if ismethod(target):
func = get_method_function(target)
annotations_by_ctx = get_property(
elt=func,
key=Annotation.__ANNOTATIONS_KEY__,
ctx=ctx
)
if not annotations_by_ctx:
annotations_by_ctx = get_property(
elt=func, key=Annotation.__ANNOTATIONS_KEY__
)
elif isfunction(target):
annotations_by_ctx = get_property(
elt=target,
key=Annotation.__ANNOTATIONS_KEY__
)
exclude = () if exclude is None else exclude
for elt, annotations in annotations_by_ctx:
for annotation in annotations:
# check if annotation is a StopPropagation rule
if isinstance(annotation, StopPropagation):
exclude += annotation.annotation_types
# ensure propagation
if elt is not target and not annotation.propagate:
continue
# ensure overriding
if annotation.override:
exclude += (annotation.__class__, )
# check for annotation
if (isinstance(annotation, cls)
and not isinstance(annotation, exclude)
and select(target, ctx, annotation)):
result.append(annotation)
if mindepth >= 0 or (maxdepth > 0 and (result or not followannotated)):
if _history is None:
_history = [target]
else:
_history.append(target)
for name, member in getmembers(target):
if (name[0] != '_' or not public) and member not in _history:
if ismethod(target) and name.startswith('im_'):
continue
result += cls.get_annotations(
target=member, exclude=exclude, ctx=ctx, select=select,
mindepth=mindepth - 1, maxdepth=maxdepth - 1,
followannotated=followannotated, _history=_history
)
return result | python | def get_annotations(
cls, target,
exclude=None, ctx=None, select=lambda *p: True,
mindepth=0, maxdepth=0, followannotated=True, public=True,
_history=None
):
"""Returns all input target annotations of cls type sorted
by definition order.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to remove from selection.
:param ctx: target ctx.
:param select: bool function which select annotations after applying
previous type filters. Takes a target, a ctx and an annotation in
parameters. True by default.
:param int mindepth: minimal depth for searching annotations (default 0)
:param int maxdepth: maximal depth for searching annotations (default 0)
:param bool followannotated: if True (default) follow deeply only
annotated members.
:param bool public: if True (default) follow public members.
:param list _history: private parameter which save parsed elements.
:rtype: Annotation
"""
result = []
if mindepth <= 0:
try:
annotations_by_ctx = get_property(
elt=target, key=Annotation.__ANNOTATIONS_KEY__, ctx=ctx
)
except TypeError:
annotations_by_ctx = {}
if not annotations_by_ctx:
if ismethod(target):
func = get_method_function(target)
annotations_by_ctx = get_property(
elt=func,
key=Annotation.__ANNOTATIONS_KEY__,
ctx=ctx
)
if not annotations_by_ctx:
annotations_by_ctx = get_property(
elt=func, key=Annotation.__ANNOTATIONS_KEY__
)
elif isfunction(target):
annotations_by_ctx = get_property(
elt=target,
key=Annotation.__ANNOTATIONS_KEY__
)
exclude = () if exclude is None else exclude
for elt, annotations in annotations_by_ctx:
for annotation in annotations:
# check if annotation is a StopPropagation rule
if isinstance(annotation, StopPropagation):
exclude += annotation.annotation_types
# ensure propagation
if elt is not target and not annotation.propagate:
continue
# ensure overriding
if annotation.override:
exclude += (annotation.__class__, )
# check for annotation
if (isinstance(annotation, cls)
and not isinstance(annotation, exclude)
and select(target, ctx, annotation)):
result.append(annotation)
if mindepth >= 0 or (maxdepth > 0 and (result or not followannotated)):
if _history is None:
_history = [target]
else:
_history.append(target)
for name, member in getmembers(target):
if (name[0] != '_' or not public) and member not in _history:
if ismethod(target) and name.startswith('im_'):
continue
result += cls.get_annotations(
target=member, exclude=exclude, ctx=ctx, select=select,
mindepth=mindepth - 1, maxdepth=maxdepth - 1,
followannotated=followannotated, _history=_history
)
return result | [
"def",
"get_annotations",
"(",
"cls",
",",
"target",
",",
"exclude",
"=",
"None",
",",
"ctx",
"=",
"None",
",",
"select",
"=",
"lambda",
"*",
"p",
":",
"True",
",",
"mindepth",
"=",
"0",
",",
"maxdepth",
"=",
"0",
",",
"followannotated",
"=",
"True",
",",
"public",
"=",
"True",
",",
"_history",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"if",
"mindepth",
"<=",
"0",
":",
"try",
":",
"annotations_by_ctx",
"=",
"get_property",
"(",
"elt",
"=",
"target",
",",
"key",
"=",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"ctx",
"=",
"ctx",
")",
"except",
"TypeError",
":",
"annotations_by_ctx",
"=",
"{",
"}",
"if",
"not",
"annotations_by_ctx",
":",
"if",
"ismethod",
"(",
"target",
")",
":",
"func",
"=",
"get_method_function",
"(",
"target",
")",
"annotations_by_ctx",
"=",
"get_property",
"(",
"elt",
"=",
"func",
",",
"key",
"=",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
",",
"ctx",
"=",
"ctx",
")",
"if",
"not",
"annotations_by_ctx",
":",
"annotations_by_ctx",
"=",
"get_property",
"(",
"elt",
"=",
"func",
",",
"key",
"=",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
")",
"elif",
"isfunction",
"(",
"target",
")",
":",
"annotations_by_ctx",
"=",
"get_property",
"(",
"elt",
"=",
"target",
",",
"key",
"=",
"Annotation",
".",
"__ANNOTATIONS_KEY__",
")",
"exclude",
"=",
"(",
")",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"for",
"elt",
",",
"annotations",
"in",
"annotations_by_ctx",
":",
"for",
"annotation",
"in",
"annotations",
":",
"# check if annotation is a StopPropagation rule",
"if",
"isinstance",
"(",
"annotation",
",",
"StopPropagation",
")",
":",
"exclude",
"+=",
"annotation",
".",
"annotation_types",
"# ensure propagation",
"if",
"elt",
"is",
"not",
"target",
"and",
"not",
"annotation",
".",
"propagate",
":",
"continue",
"# ensure overriding",
"if",
"annotation",
".",
"override",
":",
"exclude",
"+=",
"(",
"annotation",
".",
"__class__",
",",
")",
"# check for annotation",
"if",
"(",
"isinstance",
"(",
"annotation",
",",
"cls",
")",
"and",
"not",
"isinstance",
"(",
"annotation",
",",
"exclude",
")",
"and",
"select",
"(",
"target",
",",
"ctx",
",",
"annotation",
")",
")",
":",
"result",
".",
"append",
"(",
"annotation",
")",
"if",
"mindepth",
">=",
"0",
"or",
"(",
"maxdepth",
">",
"0",
"and",
"(",
"result",
"or",
"not",
"followannotated",
")",
")",
":",
"if",
"_history",
"is",
"None",
":",
"_history",
"=",
"[",
"target",
"]",
"else",
":",
"_history",
".",
"append",
"(",
"target",
")",
"for",
"name",
",",
"member",
"in",
"getmembers",
"(",
"target",
")",
":",
"if",
"(",
"name",
"[",
"0",
"]",
"!=",
"'_'",
"or",
"not",
"public",
")",
"and",
"member",
"not",
"in",
"_history",
":",
"if",
"ismethod",
"(",
"target",
")",
"and",
"name",
".",
"startswith",
"(",
"'im_'",
")",
":",
"continue",
"result",
"+=",
"cls",
".",
"get_annotations",
"(",
"target",
"=",
"member",
",",
"exclude",
"=",
"exclude",
",",
"ctx",
"=",
"ctx",
",",
"select",
"=",
"select",
",",
"mindepth",
"=",
"mindepth",
"-",
"1",
",",
"maxdepth",
"=",
"maxdepth",
"-",
"1",
",",
"followannotated",
"=",
"followannotated",
",",
"_history",
"=",
"_history",
")",
"return",
"result"
] | Returns all input target annotations of cls type sorted
by definition order.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to remove from selection.
:param ctx: target ctx.
:param select: bool function which select annotations after applying
previous type filters. Takes a target, a ctx and an annotation in
parameters. True by default.
:param int mindepth: minimal depth for searching annotations (default 0)
:param int maxdepth: maximal depth for searching annotations (default 0)
:param bool followannotated: if True (default) follow deeply only
annotated members.
:param bool public: if True (default) follow public members.
:param list _history: private parameter which save parsed elements.
:rtype: Annotation | [
"Returns",
"all",
"input",
"target",
"annotations",
"of",
"cls",
"type",
"sorted",
"by",
"definition",
"order",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L521-L621 |
248,153 | ulf1/oxyba | oxyba/rand_chol.py | rand_chol | def rand_chol(X, rho):
"""Transform C uncorrelated random variables into correlated data
X : ndarray
C univariate correlated random variables
with N observations as <N x C> matrix
rho : ndarray
Correlation Matrix (Pearson method) with
coefficients between [-1, +1]
"""
import numpy as np
return np.dot(X, np.linalg.cholesky(rho).T) | python | def rand_chol(X, rho):
"""Transform C uncorrelated random variables into correlated data
X : ndarray
C univariate correlated random variables
with N observations as <N x C> matrix
rho : ndarray
Correlation Matrix (Pearson method) with
coefficients between [-1, +1]
"""
import numpy as np
return np.dot(X, np.linalg.cholesky(rho).T) | [
"def",
"rand_chol",
"(",
"X",
",",
"rho",
")",
":",
"import",
"numpy",
"as",
"np",
"return",
"np",
".",
"dot",
"(",
"X",
",",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"rho",
")",
".",
"T",
")"
] | Transform C uncorrelated random variables into correlated data
X : ndarray
C univariate correlated random variables
with N observations as <N x C> matrix
rho : ndarray
Correlation Matrix (Pearson method) with
coefficients between [-1, +1] | [
"Transform",
"C",
"uncorrelated",
"random",
"variables",
"into",
"correlated",
"data"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/rand_chol.py#L2-L14 |
248,154 | opinkerfi/nago | nago/protocols/httpserver/__init__.py | login_required | def login_required(func, permission=None):
""" decorate with this function in order to require a valid token for any view
If no token is present you will be sent to a login page
"""
@wraps(func)
def decorated_function(*args, **kwargs):
if not check_token():
return login()
elif not nago.core.has_access(session.get('token')):
return http403()
return func(*args, **kwargs)
return decorated_function | python | def login_required(func, permission=None):
""" decorate with this function in order to require a valid token for any view
If no token is present you will be sent to a login page
"""
@wraps(func)
def decorated_function(*args, **kwargs):
if not check_token():
return login()
elif not nago.core.has_access(session.get('token')):
return http403()
return func(*args, **kwargs)
return decorated_function | [
"def",
"login_required",
"(",
"func",
",",
"permission",
"=",
"None",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"check_token",
"(",
")",
":",
"return",
"login",
"(",
")",
"elif",
"not",
"nago",
".",
"core",
".",
"has_access",
"(",
"session",
".",
"get",
"(",
"'token'",
")",
")",
":",
"return",
"http403",
"(",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorated_function"
] | decorate with this function in order to require a valid token for any view
If no token is present you will be sent to a login page | [
"decorate",
"with",
"this",
"function",
"in",
"order",
"to",
"require",
"a",
"valid",
"token",
"for",
"any",
"view"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L25-L37 |
248,155 | opinkerfi/nago | nago/protocols/httpserver/__init__.py | list_nodes | def list_nodes():
""" Return a list of all nodes """
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
nodes = nago.core.get_nodes().values()
return render_template('nodes.html', **locals()) | python | def list_nodes():
""" Return a list of all nodes """
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
nodes = nago.core.get_nodes().values()
return render_template('nodes.html', **locals()) | [
"def",
"list_nodes",
"(",
")",
":",
"token",
"=",
"session",
".",
"get",
"(",
"'token'",
")",
"node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"token",
")",
"if",
"not",
"node",
".",
"get",
"(",
"'access'",
")",
"==",
"'master'",
":",
"return",
"jsonify",
"(",
"status",
"=",
"'error'",
",",
"error",
"=",
"\"You need master access to view this page\"",
")",
"nodes",
"=",
"nago",
".",
"core",
".",
"get_nodes",
"(",
")",
".",
"values",
"(",
")",
"return",
"render_template",
"(",
"'nodes.html'",
",",
"*",
"*",
"locals",
"(",
")",
")"
] | Return a list of all nodes | [
"Return",
"a",
"list",
"of",
"all",
"nodes"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L96-L104 |
248,156 | opinkerfi/nago | nago/protocols/httpserver/__init__.py | node_detail | def node_detail(node_name):
""" View one specific node """
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
node = nago.core.get_node(node_name)
return render_template('node_detail.html', node=node) | python | def node_detail(node_name):
""" View one specific node """
token = session.get('token')
node = nago.core.get_node(token)
if not node.get('access') == 'master':
return jsonify(status='error', error="You need master access to view this page")
node = nago.core.get_node(node_name)
return render_template('node_detail.html', node=node) | [
"def",
"node_detail",
"(",
"node_name",
")",
":",
"token",
"=",
"session",
".",
"get",
"(",
"'token'",
")",
"node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"token",
")",
"if",
"not",
"node",
".",
"get",
"(",
"'access'",
")",
"==",
"'master'",
":",
"return",
"jsonify",
"(",
"status",
"=",
"'error'",
",",
"error",
"=",
"\"You need master access to view this page\"",
")",
"node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"node_name",
")",
"return",
"render_template",
"(",
"'node_detail.html'",
",",
"node",
"=",
"node",
")"
] | View one specific node | [
"View",
"one",
"specific",
"node"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L108-L116 |
248,157 | eddiejessup/agaro | agaro/output_utils.py | get_filenames | def get_filenames(dirname):
"""Return all model output filenames inside a model output directory,
sorted by iteration number.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
filenames: list[str]
Paths to all output files inside `dirname`, sorted in order of
increasing iteration number.
"""
filenames = glob.glob('{}/*.pkl'.format(dirname))
return sorted(filenames, key=_f_to_i) | python | def get_filenames(dirname):
"""Return all model output filenames inside a model output directory,
sorted by iteration number.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
filenames: list[str]
Paths to all output files inside `dirname`, sorted in order of
increasing iteration number.
"""
filenames = glob.glob('{}/*.pkl'.format(dirname))
return sorted(filenames, key=_f_to_i) | [
"def",
"get_filenames",
"(",
"dirname",
")",
":",
"filenames",
"=",
"glob",
".",
"glob",
"(",
"'{}/*.pkl'",
".",
"format",
"(",
"dirname",
")",
")",
"return",
"sorted",
"(",
"filenames",
",",
"key",
"=",
"_f_to_i",
")"
] | Return all model output filenames inside a model output directory,
sorted by iteration number.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
filenames: list[str]
Paths to all output files inside `dirname`, sorted in order of
increasing iteration number. | [
"Return",
"all",
"model",
"output",
"filenames",
"inside",
"a",
"model",
"output",
"directory",
"sorted",
"by",
"iteration",
"number",
"."
] | b2feb45d6129d749088c70b3e9290af7ca7c7d33 | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L24-L40 |
248,158 | eddiejessup/agaro | agaro/output_utils.py | get_output_every | def get_output_every(dirname):
"""Get how many iterations between outputs have been done in a directory
run.
If there are multiple values used in a run, raise an exception.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
output_every: int
The inferred number of iterations between outputs.
Raises
------
TypeError
If there are multiple different values for `output_every` found. This
usually means a run has been resumed with a different value.
"""
fnames = get_filenames(dirname)
i_s = np.array([_f_to_i(fname) for fname in fnames])
everys = list(set(np.diff(i_s)))
if len(everys) > 1:
raise TypeError('Multiple values for `output_every` '
'found, {}.'.format(everys))
return everys[0] | python | def get_output_every(dirname):
"""Get how many iterations between outputs have been done in a directory
run.
If there are multiple values used in a run, raise an exception.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
output_every: int
The inferred number of iterations between outputs.
Raises
------
TypeError
If there are multiple different values for `output_every` found. This
usually means a run has been resumed with a different value.
"""
fnames = get_filenames(dirname)
i_s = np.array([_f_to_i(fname) for fname in fnames])
everys = list(set(np.diff(i_s)))
if len(everys) > 1:
raise TypeError('Multiple values for `output_every` '
'found, {}.'.format(everys))
return everys[0] | [
"def",
"get_output_every",
"(",
"dirname",
")",
":",
"fnames",
"=",
"get_filenames",
"(",
"dirname",
")",
"i_s",
"=",
"np",
".",
"array",
"(",
"[",
"_f_to_i",
"(",
"fname",
")",
"for",
"fname",
"in",
"fnames",
"]",
")",
"everys",
"=",
"list",
"(",
"set",
"(",
"np",
".",
"diff",
"(",
"i_s",
")",
")",
")",
"if",
"len",
"(",
"everys",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"'Multiple values for `output_every` '",
"'found, {}.'",
".",
"format",
"(",
"everys",
")",
")",
"return",
"everys",
"[",
"0",
"]"
] | Get how many iterations between outputs have been done in a directory
run.
If there are multiple values used in a run, raise an exception.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
output_every: int
The inferred number of iterations between outputs.
Raises
------
TypeError
If there are multiple different values for `output_every` found. This
usually means a run has been resumed with a different value. | [
"Get",
"how",
"many",
"iterations",
"between",
"outputs",
"have",
"been",
"done",
"in",
"a",
"directory",
"run",
"."
] | b2feb45d6129d749088c70b3e9290af7ca7c7d33 | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L59-L87 |
248,159 | eddiejessup/agaro | agaro/output_utils.py | model_to_file | def model_to_file(model, filename):
"""Dump a model to a file as a pickle file.
Parameters
----------
model: Model
Model instance.
filename: str
A path to the file in which to store the pickle output.
"""
with open(filename, 'wb') as f:
pickle.dump(model, f) | python | def model_to_file(model, filename):
"""Dump a model to a file as a pickle file.
Parameters
----------
model: Model
Model instance.
filename: str
A path to the file in which to store the pickle output.
"""
with open(filename, 'wb') as f:
pickle.dump(model, f) | [
"def",
"model_to_file",
"(",
"model",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"model",
",",
"f",
")"
] | Dump a model to a file as a pickle file.
Parameters
----------
model: Model
Model instance.
filename: str
A path to the file in which to store the pickle output. | [
"Dump",
"a",
"model",
"to",
"a",
"file",
"as",
"a",
"pickle",
"file",
"."
] | b2feb45d6129d749088c70b3e9290af7ca7c7d33 | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L107-L118 |
248,160 | eddiejessup/agaro | agaro/output_utils.py | sparsify | def sparsify(dirname, output_every):
"""Remove files from an output directory at regular interval, so as to
make it as if there had been more iterations between outputs. Can be used
to reduce the storage size of a directory.
If the new number of iterations between outputs is not an integer multiple
of the old number, then raise an exception.
Parameters
----------
dirname: str
A path to a directory.
output_every: int
Desired new number of iterations between outputs.
Raises
------
ValueError
The directory cannot be coerced into representing `output_every`.
"""
fnames = get_filenames(dirname)
output_every_old = get_output_every(dirname)
if output_every % output_every_old != 0:
raise ValueError('Directory with output_every={} cannot be coerced to'
'desired new value.'.format(output_every_old))
keep_every = output_every // output_every_old
fnames_to_keep = fnames[::keep_every]
fnames_to_delete = set(fnames) - set(fnames_to_keep)
for fname in fnames_to_delete:
os.remove(fname) | python | def sparsify(dirname, output_every):
"""Remove files from an output directory at regular interval, so as to
make it as if there had been more iterations between outputs. Can be used
to reduce the storage size of a directory.
If the new number of iterations between outputs is not an integer multiple
of the old number, then raise an exception.
Parameters
----------
dirname: str
A path to a directory.
output_every: int
Desired new number of iterations between outputs.
Raises
------
ValueError
The directory cannot be coerced into representing `output_every`.
"""
fnames = get_filenames(dirname)
output_every_old = get_output_every(dirname)
if output_every % output_every_old != 0:
raise ValueError('Directory with output_every={} cannot be coerced to'
'desired new value.'.format(output_every_old))
keep_every = output_every // output_every_old
fnames_to_keep = fnames[::keep_every]
fnames_to_delete = set(fnames) - set(fnames_to_keep)
for fname in fnames_to_delete:
os.remove(fname) | [
"def",
"sparsify",
"(",
"dirname",
",",
"output_every",
")",
":",
"fnames",
"=",
"get_filenames",
"(",
"dirname",
")",
"output_every_old",
"=",
"get_output_every",
"(",
"dirname",
")",
"if",
"output_every",
"%",
"output_every_old",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'Directory with output_every={} cannot be coerced to'",
"'desired new value.'",
".",
"format",
"(",
"output_every_old",
")",
")",
"keep_every",
"=",
"output_every",
"//",
"output_every_old",
"fnames_to_keep",
"=",
"fnames",
"[",
":",
":",
"keep_every",
"]",
"fnames_to_delete",
"=",
"set",
"(",
"fnames",
")",
"-",
"set",
"(",
"fnames_to_keep",
")",
"for",
"fname",
"in",
"fnames_to_delete",
":",
"os",
".",
"remove",
"(",
"fname",
")"
] | Remove files from an output directory at regular interval, so as to
make it as if there had been more iterations between outputs. Can be used
to reduce the storage size of a directory.
If the new number of iterations between outputs is not an integer multiple
of the old number, then raise an exception.
Parameters
----------
dirname: str
A path to a directory.
output_every: int
Desired new number of iterations between outputs.
Raises
------
ValueError
The directory cannot be coerced into representing `output_every`. | [
"Remove",
"files",
"from",
"an",
"output",
"directory",
"at",
"regular",
"interval",
"so",
"as",
"to",
"make",
"it",
"as",
"if",
"there",
"had",
"been",
"more",
"iterations",
"between",
"outputs",
".",
"Can",
"be",
"used",
"to",
"reduce",
"the",
"storage",
"size",
"of",
"a",
"directory",
"."
] | b2feb45d6129d749088c70b3e9290af7ca7c7d33 | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L121-L150 |
248,161 | tempodb/tempodb-python | tempodb/endpoint.py | HTTPEndpoint.post | def post(self, url, body):
"""Perform a POST request to the given resource with the given
body. The "url" argument will be joined to the base URL this
object was initialized with.
:param string url: the URL resource to hit
:param string body: the POST body for the request
:rtype: requests.Response object"""
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.post(to_hit, data=body, auth=self.auth)
return resp | python | def post(self, url, body):
"""Perform a POST request to the given resource with the given
body. The "url" argument will be joined to the base URL this
object was initialized with.
:param string url: the URL resource to hit
:param string body: the POST body for the request
:rtype: requests.Response object"""
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.post(to_hit, data=body, auth=self.auth)
return resp | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"body",
")",
":",
"to_hit",
"=",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"resp",
"=",
"self",
".",
"pool",
".",
"post",
"(",
"to_hit",
",",
"data",
"=",
"body",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"resp"
] | Perform a POST request to the given resource with the given
body. The "url" argument will be joined to the base URL this
object was initialized with.
:param string url: the URL resource to hit
:param string body: the POST body for the request
:rtype: requests.Response object | [
"Perform",
"a",
"POST",
"request",
"to",
"the",
"given",
"resource",
"with",
"the",
"given",
"body",
".",
"The",
"url",
"argument",
"will",
"be",
"joined",
"to",
"the",
"base",
"URL",
"this",
"object",
"was",
"initialized",
"with",
"."
] | 8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3 | https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/endpoint.py#L63-L74 |
248,162 | tempodb/tempodb-python | tempodb/endpoint.py | HTTPEndpoint.get | def get(self, url):
"""Perform a GET request to the given resource with the given URL. The
"url" argument will be joined to the base URL this object was
initialized with.
:param string url: the URL resource to hit
:rtype: requests.Response object"""
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.get(to_hit, auth=self.auth)
return resp | python | def get(self, url):
"""Perform a GET request to the given resource with the given URL. The
"url" argument will be joined to the base URL this object was
initialized with.
:param string url: the URL resource to hit
:rtype: requests.Response object"""
to_hit = urlparse.urljoin(self.base_url, url)
resp = self.pool.get(to_hit, auth=self.auth)
return resp | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"to_hit",
"=",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"resp",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"to_hit",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"resp"
] | Perform a GET request to the given resource with the given URL. The
"url" argument will be joined to the base URL this object was
initialized with.
:param string url: the URL resource to hit
:rtype: requests.Response object | [
"Perform",
"a",
"GET",
"request",
"to",
"the",
"given",
"resource",
"with",
"the",
"given",
"URL",
".",
"The",
"url",
"argument",
"will",
"be",
"joined",
"to",
"the",
"base",
"URL",
"this",
"object",
"was",
"initialized",
"with",
"."
] | 8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3 | https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/endpoint.py#L76-L86 |
248,163 | ryanjdillon/pyotelem | pyotelem/seawater.py | SWdensityFromCTD | def SWdensityFromCTD(SA, t, p, potential=False):
'''Calculate seawater density at CTD depth
Args
----
SA: ndarray
Absolute salinity, g/kg
t: ndarray
In-situ temperature (ITS-90), degrees C
p: ndarray
Sea pressure (absolute pressure minus 10.1325 dbar), dbar
Returns
-------
rho: ndarray
Seawater density, in-situ or potential, kg/m^3
'''
import numpy
import gsw
CT = gsw.CT_from_t(SA, t, p)
# Calculate potential density (0 bar) instead of in-situ
if potential:
p = numpy.zeros(len(SA))
return gsw.rho(SA, CT, p) | python | def SWdensityFromCTD(SA, t, p, potential=False):
'''Calculate seawater density at CTD depth
Args
----
SA: ndarray
Absolute salinity, g/kg
t: ndarray
In-situ temperature (ITS-90), degrees C
p: ndarray
Sea pressure (absolute pressure minus 10.1325 dbar), dbar
Returns
-------
rho: ndarray
Seawater density, in-situ or potential, kg/m^3
'''
import numpy
import gsw
CT = gsw.CT_from_t(SA, t, p)
# Calculate potential density (0 bar) instead of in-situ
if potential:
p = numpy.zeros(len(SA))
return gsw.rho(SA, CT, p) | [
"def",
"SWdensityFromCTD",
"(",
"SA",
",",
"t",
",",
"p",
",",
"potential",
"=",
"False",
")",
":",
"import",
"numpy",
"import",
"gsw",
"CT",
"=",
"gsw",
".",
"CT_from_t",
"(",
"SA",
",",
"t",
",",
"p",
")",
"# Calculate potential density (0 bar) instead of in-situ",
"if",
"potential",
":",
"p",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"SA",
")",
")",
"return",
"gsw",
".",
"rho",
"(",
"SA",
",",
"CT",
",",
"p",
")"
] | Calculate seawater density at CTD depth
Args
----
SA: ndarray
Absolute salinity, g/kg
t: ndarray
In-situ temperature (ITS-90), degrees C
p: ndarray
Sea pressure (absolute pressure minus 10.1325 dbar), dbar
Returns
-------
rho: ndarray
Seawater density, in-situ or potential, kg/m^3 | [
"Calculate",
"seawater",
"density",
"at",
"CTD",
"depth"
] | 816563a9c3feb3fa416f1c2921c6b75db34111ad | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/seawater.py#L2-L28 |
248,164 | minhhoit/yacms | yacms/utils/views.py | is_editable | def is_editable(obj, request):
"""
Returns ``True`` if the object is editable for the request. First
check for a custom ``editable`` handler on the object, otherwise
use the logged in user and check change permissions for the
object's model.
"""
if hasattr(obj, "is_editable"):
return obj.is_editable(request)
else:
codename = get_permission_codename("change", obj._meta)
perm = "%s.%s" % (obj._meta.app_label, codename)
return (request.user.is_authenticated() and
has_site_permission(request.user) and
request.user.has_perm(perm)) | python | def is_editable(obj, request):
"""
Returns ``True`` if the object is editable for the request. First
check for a custom ``editable`` handler on the object, otherwise
use the logged in user and check change permissions for the
object's model.
"""
if hasattr(obj, "is_editable"):
return obj.is_editable(request)
else:
codename = get_permission_codename("change", obj._meta)
perm = "%s.%s" % (obj._meta.app_label, codename)
return (request.user.is_authenticated() and
has_site_permission(request.user) and
request.user.has_perm(perm)) | [
"def",
"is_editable",
"(",
"obj",
",",
"request",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"is_editable\"",
")",
":",
"return",
"obj",
".",
"is_editable",
"(",
"request",
")",
"else",
":",
"codename",
"=",
"get_permission_codename",
"(",
"\"change\"",
",",
"obj",
".",
"_meta",
")",
"perm",
"=",
"\"%s.%s\"",
"%",
"(",
"obj",
".",
"_meta",
".",
"app_label",
",",
"codename",
")",
"return",
"(",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"has_site_permission",
"(",
"request",
".",
"user",
")",
"and",
"request",
".",
"user",
".",
"has_perm",
"(",
"perm",
")",
")"
] | Returns ``True`` if the object is editable for the request. First
check for a custom ``editable`` handler on the object, otherwise
use the logged in user and check change permissions for the
object's model. | [
"Returns",
"True",
"if",
"the",
"object",
"is",
"editable",
"for",
"the",
"request",
".",
"First",
"check",
"for",
"a",
"custom",
"editable",
"handler",
"on",
"the",
"object",
"otherwise",
"use",
"the",
"logged",
"in",
"user",
"and",
"check",
"change",
"permissions",
"for",
"the",
"object",
"s",
"model",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L32-L46 |
248,165 | minhhoit/yacms | yacms/utils/views.py | is_spam | def is_spam(request, form, url):
"""
Main entry point for spam handling - called from the comment view and
page processor for ``yacms.forms``, to check if posted content is
spam. Spam filters are configured via the ``SPAM_FILTERS`` setting.
"""
for spam_filter_path in settings.SPAM_FILTERS:
spam_filter = import_dotted_path(spam_filter_path)
if spam_filter(request, form, url):
return True | python | def is_spam(request, form, url):
"""
Main entry point for spam handling - called from the comment view and
page processor for ``yacms.forms``, to check if posted content is
spam. Spam filters are configured via the ``SPAM_FILTERS`` setting.
"""
for spam_filter_path in settings.SPAM_FILTERS:
spam_filter = import_dotted_path(spam_filter_path)
if spam_filter(request, form, url):
return True | [
"def",
"is_spam",
"(",
"request",
",",
"form",
",",
"url",
")",
":",
"for",
"spam_filter_path",
"in",
"settings",
".",
"SPAM_FILTERS",
":",
"spam_filter",
"=",
"import_dotted_path",
"(",
"spam_filter_path",
")",
"if",
"spam_filter",
"(",
"request",
",",
"form",
",",
"url",
")",
":",
"return",
"True"
] | Main entry point for spam handling - called from the comment view and
page processor for ``yacms.forms``, to check if posted content is
spam. Spam filters are configured via the ``SPAM_FILTERS`` setting. | [
"Main",
"entry",
"point",
"for",
"spam",
"handling",
"-",
"called",
"from",
"the",
"comment",
"view",
"and",
"page",
"processor",
"for",
"yacms",
".",
"forms",
"to",
"check",
"if",
"posted",
"content",
"is",
"spam",
".",
"Spam",
"filters",
"are",
"configured",
"via",
"the",
"SPAM_FILTERS",
"setting",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L124-L133 |
248,166 | minhhoit/yacms | yacms/utils/views.py | paginate | def paginate(objects, page_num, per_page, max_paging_links):
"""
Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``.
"""
if not per_page:
return Paginator(objects, 0)
paginator = Paginator(objects, per_page)
try:
page_num = int(page_num)
except ValueError:
page_num = 1
try:
objects = paginator.page(page_num)
except (EmptyPage, InvalidPage):
objects = paginator.page(paginator.num_pages)
page_range = objects.paginator.page_range
if len(page_range) > max_paging_links:
start = min(objects.paginator.num_pages - max_paging_links,
max(0, objects.number - (max_paging_links // 2) - 1))
page_range = list(page_range)[start:start + max_paging_links]
objects.visible_page_range = page_range
return objects | python | def paginate(objects, page_num, per_page, max_paging_links):
"""
Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``.
"""
if not per_page:
return Paginator(objects, 0)
paginator = Paginator(objects, per_page)
try:
page_num = int(page_num)
except ValueError:
page_num = 1
try:
objects = paginator.page(page_num)
except (EmptyPage, InvalidPage):
objects = paginator.page(paginator.num_pages)
page_range = objects.paginator.page_range
if len(page_range) > max_paging_links:
start = min(objects.paginator.num_pages - max_paging_links,
max(0, objects.number - (max_paging_links // 2) - 1))
page_range = list(page_range)[start:start + max_paging_links]
objects.visible_page_range = page_range
return objects | [
"def",
"paginate",
"(",
"objects",
",",
"page_num",
",",
"per_page",
",",
"max_paging_links",
")",
":",
"if",
"not",
"per_page",
":",
"return",
"Paginator",
"(",
"objects",
",",
"0",
")",
"paginator",
"=",
"Paginator",
"(",
"objects",
",",
"per_page",
")",
"try",
":",
"page_num",
"=",
"int",
"(",
"page_num",
")",
"except",
"ValueError",
":",
"page_num",
"=",
"1",
"try",
":",
"objects",
"=",
"paginator",
".",
"page",
"(",
"page_num",
")",
"except",
"(",
"EmptyPage",
",",
"InvalidPage",
")",
":",
"objects",
"=",
"paginator",
".",
"page",
"(",
"paginator",
".",
"num_pages",
")",
"page_range",
"=",
"objects",
".",
"paginator",
".",
"page_range",
"if",
"len",
"(",
"page_range",
")",
">",
"max_paging_links",
":",
"start",
"=",
"min",
"(",
"objects",
".",
"paginator",
".",
"num_pages",
"-",
"max_paging_links",
",",
"max",
"(",
"0",
",",
"objects",
".",
"number",
"-",
"(",
"max_paging_links",
"//",
"2",
")",
"-",
"1",
")",
")",
"page_range",
"=",
"list",
"(",
"page_range",
")",
"[",
"start",
":",
"start",
"+",
"max_paging_links",
"]",
"objects",
".",
"visible_page_range",
"=",
"page_range",
"return",
"objects"
] | Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``. | [
"Return",
"a",
"paginated",
"page",
"for",
"the",
"given",
"objects",
"giving",
"it",
"a",
"custom",
"visible_page_range",
"attribute",
"calculated",
"from",
"max_paging_links",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L136-L158 |
248,167 | minhhoit/yacms | yacms/utils/views.py | render | def render(request, templates, dictionary=None, context_instance=None,
**kwargs):
"""
Mimics ``django.shortcuts.render`` but uses a TemplateResponse for
``yacms.core.middleware.TemplateForDeviceMiddleware``
"""
warnings.warn(
"yacms.utils.views.render is deprecated and will be removed "
"in a future version. Please update your project to use Django's "
"TemplateResponse, which now provides equivalent functionality.",
DeprecationWarning
)
dictionary = dictionary or {}
if context_instance:
context_instance.update(dictionary)
else:
context_instance = RequestContext(request, dictionary)
return TemplateResponse(request, templates, context_instance, **kwargs) | python | def render(request, templates, dictionary=None, context_instance=None,
**kwargs):
"""
Mimics ``django.shortcuts.render`` but uses a TemplateResponse for
``yacms.core.middleware.TemplateForDeviceMiddleware``
"""
warnings.warn(
"yacms.utils.views.render is deprecated and will be removed "
"in a future version. Please update your project to use Django's "
"TemplateResponse, which now provides equivalent functionality.",
DeprecationWarning
)
dictionary = dictionary or {}
if context_instance:
context_instance.update(dictionary)
else:
context_instance = RequestContext(request, dictionary)
return TemplateResponse(request, templates, context_instance, **kwargs) | [
"def",
"render",
"(",
"request",
",",
"templates",
",",
"dictionary",
"=",
"None",
",",
"context_instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"yacms.utils.views.render is deprecated and will be removed \"",
"\"in a future version. Please update your project to use Django's \"",
"\"TemplateResponse, which now provides equivalent functionality.\"",
",",
"DeprecationWarning",
")",
"dictionary",
"=",
"dictionary",
"or",
"{",
"}",
"if",
"context_instance",
":",
"context_instance",
".",
"update",
"(",
"dictionary",
")",
"else",
":",
"context_instance",
"=",
"RequestContext",
"(",
"request",
",",
"dictionary",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"templates",
",",
"context_instance",
",",
"*",
"*",
"kwargs",
")"
] | Mimics ``django.shortcuts.render`` but uses a TemplateResponse for
``yacms.core.middleware.TemplateForDeviceMiddleware`` | [
"Mimics",
"django",
".",
"shortcuts",
".",
"render",
"but",
"uses",
"a",
"TemplateResponse",
"for",
"yacms",
".",
"core",
".",
"middleware",
".",
"TemplateForDeviceMiddleware"
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L161-L180 |
248,168 | minhhoit/yacms | yacms/utils/views.py | set_cookie | def set_cookie(response, name, value, expiry_seconds=None, secure=False):
"""
Set cookie wrapper that allows number of seconds to be given as the
expiry time, and ensures values are correctly encoded.
"""
if expiry_seconds is None:
expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days.
expires = datetime.strftime(datetime.utcnow() +
timedelta(seconds=expiry_seconds),
"%a, %d-%b-%Y %H:%M:%S GMT")
# Django doesn't seem to support unicode cookie keys correctly on
# Python 2. Work around by encoding it. See
# https://code.djangoproject.com/ticket/19802
try:
response.set_cookie(name, value, expires=expires, secure=secure)
except (KeyError, TypeError):
response.set_cookie(name.encode('utf-8'), value, expires=expires,
secure=secure) | python | def set_cookie(response, name, value, expiry_seconds=None, secure=False):
"""
Set cookie wrapper that allows number of seconds to be given as the
expiry time, and ensures values are correctly encoded.
"""
if expiry_seconds is None:
expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days.
expires = datetime.strftime(datetime.utcnow() +
timedelta(seconds=expiry_seconds),
"%a, %d-%b-%Y %H:%M:%S GMT")
# Django doesn't seem to support unicode cookie keys correctly on
# Python 2. Work around by encoding it. See
# https://code.djangoproject.com/ticket/19802
try:
response.set_cookie(name, value, expires=expires, secure=secure)
except (KeyError, TypeError):
response.set_cookie(name.encode('utf-8'), value, expires=expires,
secure=secure) | [
"def",
"set_cookie",
"(",
"response",
",",
"name",
",",
"value",
",",
"expiry_seconds",
"=",
"None",
",",
"secure",
"=",
"False",
")",
":",
"if",
"expiry_seconds",
"is",
"None",
":",
"expiry_seconds",
"=",
"90",
"*",
"24",
"*",
"60",
"*",
"60",
"# Default to 90 days.",
"expires",
"=",
"datetime",
".",
"strftime",
"(",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"expiry_seconds",
")",
",",
"\"%a, %d-%b-%Y %H:%M:%S GMT\"",
")",
"# Django doesn't seem to support unicode cookie keys correctly on",
"# Python 2. Work around by encoding it. See",
"# https://code.djangoproject.com/ticket/19802",
"try",
":",
"response",
".",
"set_cookie",
"(",
"name",
",",
"value",
",",
"expires",
"=",
"expires",
",",
"secure",
"=",
"secure",
")",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"response",
".",
"set_cookie",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"value",
",",
"expires",
"=",
"expires",
",",
"secure",
"=",
"secure",
")"
] | Set cookie wrapper that allows number of seconds to be given as the
expiry time, and ensures values are correctly encoded. | [
"Set",
"cookie",
"wrapper",
"that",
"allows",
"number",
"of",
"seconds",
"to",
"be",
"given",
"as",
"the",
"expiry",
"time",
"and",
"ensures",
"values",
"are",
"correctly",
"encoded",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L183-L200 |
248,169 | MitalAshok/objecttools | objecttools/cached_property.py | CachedProperty.getter | def getter(self, fget):
"""
Change the getter for this descriptor to use to get the value
:param fget: Function to call with an object as its only argument
:type fget: Callable[[Any], Any]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if getattr(self, '__doc__', None) is None:
self.__doc__ = getattr(fget, _FUNC_DOC, None)
if self.name is None:
self.name = getattr(fget, _FUNC_NAME, None)
self._getter = fget
return self | python | def getter(self, fget):
"""
Change the getter for this descriptor to use to get the value
:param fget: Function to call with an object as its only argument
:type fget: Callable[[Any], Any]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if getattr(self, '__doc__', None) is None:
self.__doc__ = getattr(fget, _FUNC_DOC, None)
if self.name is None:
self.name = getattr(fget, _FUNC_NAME, None)
self._getter = fget
return self | [
"def",
"getter",
"(",
"self",
",",
"fget",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'__doc__'",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"__doc__",
"=",
"getattr",
"(",
"fget",
",",
"_FUNC_DOC",
",",
"None",
")",
"if",
"self",
".",
"name",
"is",
"None",
":",
"self",
".",
"name",
"=",
"getattr",
"(",
"fget",
",",
"_FUNC_NAME",
",",
"None",
")",
"self",
".",
"_getter",
"=",
"fget",
"return",
"self"
] | Change the getter for this descriptor to use to get the value
:param fget: Function to call with an object as its only argument
:type fget: Callable[[Any], Any]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty | [
"Change",
"the",
"getter",
"for",
"this",
"descriptor",
"to",
"use",
"to",
"get",
"the",
"value"
] | bddd14d1f702c8b559d3fcc2099bc22370e16de7 | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L94-L108 |
248,170 | MitalAshok/objecttools | objecttools/cached_property.py | CachedProperty.setter | def setter(self, can_set=None):
"""
Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set`
:param can_set: boolean to change to it, and None to toggle
:type can_set: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if can_set is None:
self._setter = not self._setter
else:
self._setter = bool(can_set)
# For use as decorator
return self | python | def setter(self, can_set=None):
"""
Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set`
:param can_set: boolean to change to it, and None to toggle
:type can_set: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if can_set is None:
self._setter = not self._setter
else:
self._setter = bool(can_set)
# For use as decorator
return self | [
"def",
"setter",
"(",
"self",
",",
"can_set",
"=",
"None",
")",
":",
"if",
"can_set",
"is",
"None",
":",
"self",
".",
"_setter",
"=",
"not",
"self",
".",
"_setter",
"else",
":",
"self",
".",
"_setter",
"=",
"bool",
"(",
"can_set",
")",
"# For use as decorator",
"return",
"self"
] | Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set`
:param can_set: boolean to change to it, and None to toggle
:type can_set: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty | [
"Like",
"CachedProp",
".",
"deleter",
"is",
"for",
"CachedProp",
".",
"can_delete",
"but",
"for",
"can_set"
] | bddd14d1f702c8b559d3fcc2099bc22370e16de7 | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L110-L124 |
248,171 | MitalAshok/objecttools | objecttools/cached_property.py | CachedProperty.deleter | def deleter(self, can_delete=None):
"""
Change if this descriptor's can be invalidated through `del obj.attr`.
`cached_prop.deleter(True)` and::
@cached_prop.deleter
def cached_prop(self):
pass
are equivalent to `cached_prop.can_delete = True`.
:param can_delete: boolean to change to it, and None to toggle
:type can_delete: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if can_delete is None:
self._deleter = not self._deleter
else:
self._deleter = bool(can_delete)
# For use as decorator
return self | python | def deleter(self, can_delete=None):
"""
Change if this descriptor's can be invalidated through `del obj.attr`.
`cached_prop.deleter(True)` and::
@cached_prop.deleter
def cached_prop(self):
pass
are equivalent to `cached_prop.can_delete = True`.
:param can_delete: boolean to change to it, and None to toggle
:type can_delete: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty
"""
if can_delete is None:
self._deleter = not self._deleter
else:
self._deleter = bool(can_delete)
# For use as decorator
return self | [
"def",
"deleter",
"(",
"self",
",",
"can_delete",
"=",
"None",
")",
":",
"if",
"can_delete",
"is",
"None",
":",
"self",
".",
"_deleter",
"=",
"not",
"self",
".",
"_deleter",
"else",
":",
"self",
".",
"_deleter",
"=",
"bool",
"(",
"can_delete",
")",
"# For use as decorator",
"return",
"self"
] | Change if this descriptor's can be invalidated through `del obj.attr`.
`cached_prop.deleter(True)` and::
@cached_prop.deleter
def cached_prop(self):
pass
are equivalent to `cached_prop.can_delete = True`.
:param can_delete: boolean to change to it, and None to toggle
:type can_delete: Optional[bool]
:return: self, so this can be used as a decorator like a `property`
:rtype: CachedProperty | [
"Change",
"if",
"this",
"descriptor",
"s",
"can",
"be",
"invalidated",
"through",
"del",
"obj",
".",
"attr",
"."
] | bddd14d1f702c8b559d3fcc2099bc22370e16de7 | https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L139-L161 |
248,172 | exekias/droplet | droplet/files.py | ConfFile.write | def write(self):
"""
Write the file, forcing the proper permissions
"""
with root():
self._write_log()
with open(self.path, 'w') as f:
# file owner
os.chown(self.path, self.uid(), self.gid())
# mode
if self.mode:
oldmask = os.umask(0)
os.chmod(self.path, self.mode)
os.umask(oldmask)
f.write(self.contents()) | python | def write(self):
"""
Write the file, forcing the proper permissions
"""
with root():
self._write_log()
with open(self.path, 'w') as f:
# file owner
os.chown(self.path, self.uid(), self.gid())
# mode
if self.mode:
oldmask = os.umask(0)
os.chmod(self.path, self.mode)
os.umask(oldmask)
f.write(self.contents()) | [
"def",
"write",
"(",
"self",
")",
":",
"with",
"root",
"(",
")",
":",
"self",
".",
"_write_log",
"(",
")",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"# file owner",
"os",
".",
"chown",
"(",
"self",
".",
"path",
",",
"self",
".",
"uid",
"(",
")",
",",
"self",
".",
"gid",
"(",
")",
")",
"# mode",
"if",
"self",
".",
"mode",
":",
"oldmask",
"=",
"os",
".",
"umask",
"(",
"0",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"path",
",",
"self",
".",
"mode",
")",
"os",
".",
"umask",
"(",
"oldmask",
")",
"f",
".",
"write",
"(",
"self",
".",
"contents",
"(",
")",
")"
] | Write the file, forcing the proper permissions | [
"Write",
"the",
"file",
"forcing",
"the",
"proper",
"permissions"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/files.py#L53-L69 |
248,173 | exekias/droplet | droplet/files.py | ConfFile._write_log | def _write_log(self):
"""
Write log info
"""
logger.info("Writing config file %s" % self.path)
if settings.DEBUG:
try:
old_content = open(self.path, 'r').readlines()
except IOError:
old_content = ''
new_content = self.contents().splitlines(True)
diff = difflib.unified_diff(old_content, new_content,
fromfile=self.path, tofile=self.path)
if diff:
logger.debug('Diff:\n' + ''.join(diff))
else:
logger.debug('File not changed') | python | def _write_log(self):
"""
Write log info
"""
logger.info("Writing config file %s" % self.path)
if settings.DEBUG:
try:
old_content = open(self.path, 'r').readlines()
except IOError:
old_content = ''
new_content = self.contents().splitlines(True)
diff = difflib.unified_diff(old_content, new_content,
fromfile=self.path, tofile=self.path)
if diff:
logger.debug('Diff:\n' + ''.join(diff))
else:
logger.debug('File not changed') | [
"def",
"_write_log",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Writing config file %s\"",
"%",
"self",
".",
"path",
")",
"if",
"settings",
".",
"DEBUG",
":",
"try",
":",
"old_content",
"=",
"open",
"(",
"self",
".",
"path",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"old_content",
"=",
"''",
"new_content",
"=",
"self",
".",
"contents",
"(",
")",
".",
"splitlines",
"(",
"True",
")",
"diff",
"=",
"difflib",
".",
"unified_diff",
"(",
"old_content",
",",
"new_content",
",",
"fromfile",
"=",
"self",
".",
"path",
",",
"tofile",
"=",
"self",
".",
"path",
")",
"if",
"diff",
":",
"logger",
".",
"debug",
"(",
"'Diff:\\n'",
"+",
"''",
".",
"join",
"(",
"diff",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'File not changed'",
")"
] | Write log info | [
"Write",
"log",
"info"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/files.py#L77-L95 |
248,174 | cirruscluster/cirruscluster | cirruscluster/ami/builder.py | GetAmi | def GetAmi(ec2, ami_spec):
""" Get the boto ami object given a AmiSpecification object. """
images = ec2.get_all_images(owners=[ami_spec.owner_id] )
requested_image = None
for image in images:
if image.name == ami_spec.ami_name:
requested_image = image
break
return requested_image | python | def GetAmi(ec2, ami_spec):
""" Get the boto ami object given a AmiSpecification object. """
images = ec2.get_all_images(owners=[ami_spec.owner_id] )
requested_image = None
for image in images:
if image.name == ami_spec.ami_name:
requested_image = image
break
return requested_image | [
"def",
"GetAmi",
"(",
"ec2",
",",
"ami_spec",
")",
":",
"images",
"=",
"ec2",
".",
"get_all_images",
"(",
"owners",
"=",
"[",
"ami_spec",
".",
"owner_id",
"]",
")",
"requested_image",
"=",
"None",
"for",
"image",
"in",
"images",
":",
"if",
"image",
".",
"name",
"==",
"ami_spec",
".",
"ami_name",
":",
"requested_image",
"=",
"image",
"break",
"return",
"requested_image"
] | Get the boto ami object given a AmiSpecification object. | [
"Get",
"the",
"boto",
"ami",
"object",
"given",
"a",
"AmiSpecification",
"object",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ami/builder.py#L53-L61 |
248,175 | cirruscluster/cirruscluster | cirruscluster/ami/builder.py | AmiBuilder.Run | def Run(self):
""" Build the Amazon Machine Image. """
template_instance = None
res = self.ec2.get_all_instances( \
filters={'tag-key': 'spec',
'tag-value' : self.ami_spec.ami_name,
'instance-state-name' : 'running'})
if res:
running_template_instances = res[0].instances
if running_template_instances:
assert(len(running_template_instances) == 1)
template_instance = running_template_instances[0]
# if there is not a currently running template instance, start one
if not template_instance:
template_instance = self.__CreateTemplateInstance()
template_instance.add_tag('spec', self.ami_spec.ami_name)
assert(template_instance)
if self.ami_spec.role == 'workstation':
self.__ConfigureAsWorkstation(template_instance)
elif self.ami_spec.role == 'master':
self.__ConfigureAsClusterMaster(template_instance)
elif self.ami_spec.role == 'worker':
self.__ConfigureAsClusterWorker(template_instance)
else:
raise RuntimeError('unknown role: %s' % (self.ami_spec.role))
print 'Please login and perform any custom manipulations before '\
'snapshot is made!'
raw_input('Press any key to shutdown and begin creating AMI. '\
'(or ctrl-c to quit and re-run config process).')
self.__SecurityScrub(template_instance)
ami_id = None
if self.ami_spec.root_store_type == 'ebs':
ami_id = self.__CreateEbsAmi(template_instance)
else:
logging.info('Support for creating instance-store backed images has been'
' disabled in this version because it required much greater'
' complexity.')
ami_id = self.__CreateEbsAmi(template_instance)
logging.info('ami id: %s' % (ami_id))
# TODO(heathkh): implement these features...
#self.__SetImagePermissions(ami_id)
#self.__DistributeImageToAllRegions(ami_id)
print 'terminating template instance'
self.ec2.terminate_instances(instance_ids=[template_instance.id])
core.WaitForInstanceTerminated(template_instance)
return | python | def Run(self):
""" Build the Amazon Machine Image. """
template_instance = None
res = self.ec2.get_all_instances( \
filters={'tag-key': 'spec',
'tag-value' : self.ami_spec.ami_name,
'instance-state-name' : 'running'})
if res:
running_template_instances = res[0].instances
if running_template_instances:
assert(len(running_template_instances) == 1)
template_instance = running_template_instances[0]
# if there is not a currently running template instance, start one
if not template_instance:
template_instance = self.__CreateTemplateInstance()
template_instance.add_tag('spec', self.ami_spec.ami_name)
assert(template_instance)
if self.ami_spec.role == 'workstation':
self.__ConfigureAsWorkstation(template_instance)
elif self.ami_spec.role == 'master':
self.__ConfigureAsClusterMaster(template_instance)
elif self.ami_spec.role == 'worker':
self.__ConfigureAsClusterWorker(template_instance)
else:
raise RuntimeError('unknown role: %s' % (self.ami_spec.role))
print 'Please login and perform any custom manipulations before '\
'snapshot is made!'
raw_input('Press any key to shutdown and begin creating AMI. '\
'(or ctrl-c to quit and re-run config process).')
self.__SecurityScrub(template_instance)
ami_id = None
if self.ami_spec.root_store_type == 'ebs':
ami_id = self.__CreateEbsAmi(template_instance)
else:
logging.info('Support for creating instance-store backed images has been'
' disabled in this version because it required much greater'
' complexity.')
ami_id = self.__CreateEbsAmi(template_instance)
logging.info('ami id: %s' % (ami_id))
# TODO(heathkh): implement these features...
#self.__SetImagePermissions(ami_id)
#self.__DistributeImageToAllRegions(ami_id)
print 'terminating template instance'
self.ec2.terminate_instances(instance_ids=[template_instance.id])
core.WaitForInstanceTerminated(template_instance)
return | [
"def",
"Run",
"(",
"self",
")",
":",
"template_instance",
"=",
"None",
"res",
"=",
"self",
".",
"ec2",
".",
"get_all_instances",
"(",
"filters",
"=",
"{",
"'tag-key'",
":",
"'spec'",
",",
"'tag-value'",
":",
"self",
".",
"ami_spec",
".",
"ami_name",
",",
"'instance-state-name'",
":",
"'running'",
"}",
")",
"if",
"res",
":",
"running_template_instances",
"=",
"res",
"[",
"0",
"]",
".",
"instances",
"if",
"running_template_instances",
":",
"assert",
"(",
"len",
"(",
"running_template_instances",
")",
"==",
"1",
")",
"template_instance",
"=",
"running_template_instances",
"[",
"0",
"]",
"# if there is not a currently running template instance, start one",
"if",
"not",
"template_instance",
":",
"template_instance",
"=",
"self",
".",
"__CreateTemplateInstance",
"(",
")",
"template_instance",
".",
"add_tag",
"(",
"'spec'",
",",
"self",
".",
"ami_spec",
".",
"ami_name",
")",
"assert",
"(",
"template_instance",
")",
"if",
"self",
".",
"ami_spec",
".",
"role",
"==",
"'workstation'",
":",
"self",
".",
"__ConfigureAsWorkstation",
"(",
"template_instance",
")",
"elif",
"self",
".",
"ami_spec",
".",
"role",
"==",
"'master'",
":",
"self",
".",
"__ConfigureAsClusterMaster",
"(",
"template_instance",
")",
"elif",
"self",
".",
"ami_spec",
".",
"role",
"==",
"'worker'",
":",
"self",
".",
"__ConfigureAsClusterWorker",
"(",
"template_instance",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'unknown role: %s'",
"%",
"(",
"self",
".",
"ami_spec",
".",
"role",
")",
")",
"print",
"'Please login and perform any custom manipulations before '",
"'snapshot is made!'",
"raw_input",
"(",
"'Press any key to shutdown and begin creating AMI. '",
"'(or ctrl-c to quit and re-run config process).'",
")",
"self",
".",
"__SecurityScrub",
"(",
"template_instance",
")",
"ami_id",
"=",
"None",
"if",
"self",
".",
"ami_spec",
".",
"root_store_type",
"==",
"'ebs'",
":",
"ami_id",
"=",
"self",
".",
"__CreateEbsAmi",
"(",
"template_instance",
")",
"else",
":",
"logging",
".",
"info",
"(",
"'Support for creating instance-store backed images has been'",
"' disabled in this version because it required much greater'",
"' complexity.'",
")",
"ami_id",
"=",
"self",
".",
"__CreateEbsAmi",
"(",
"template_instance",
")",
"logging",
".",
"info",
"(",
"'ami id: %s'",
"%",
"(",
"ami_id",
")",
")",
"# TODO(heathkh): implement these features...",
"#self.__SetImagePermissions(ami_id)",
"#self.__DistributeImageToAllRegions(ami_id)",
"print",
"'terminating template instance'",
"self",
".",
"ec2",
".",
"terminate_instances",
"(",
"instance_ids",
"=",
"[",
"template_instance",
".",
"id",
"]",
")",
"core",
".",
"WaitForInstanceTerminated",
"(",
"template_instance",
")",
"return"
] | Build the Amazon Machine Image. | [
"Build",
"the",
"Amazon",
"Machine",
"Image",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ami/builder.py#L79-L133 |
248,176 | ramrod-project/database-brain | schema/brain/environment.py | log_env_gte | def log_env_gte(desired):
"""
Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool>
"""
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST]) | python | def log_env_gte(desired):
"""
Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool>
"""
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST]) | [
"def",
"log_env_gte",
"(",
"desired",
")",
":",
"return",
"LOGLEVELS",
".",
"get",
"(",
"check_log_env",
"(",
")",
")",
">=",
"LOGLEVELS",
".",
"get",
"(",
"desired",
",",
"LOGLEVELS",
"[",
"TEST",
"]",
")"
] | Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool> | [
"Boolean",
"check",
"if",
"the",
"current",
"environment",
"LOGLEVEL",
"is",
"at",
"least",
"as",
"verbose",
"as",
"a",
"desired",
"LOGLEVEL"
] | b024cb44f34cabb9d80af38271ddb65c25767083 | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/environment.py#L50-L58 |
248,177 | wlwang41/cb | cb/tools.py | copytree | def copytree(src, dst, symlinks=False, ignore=None):
"""Copy from source directory to destination"""
# TODO(crow): OSError: [Errno 17] File exists
if not osp.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = osp.join(src, item)
d = osp.join(dst, item)
if osp.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d) | python | def copytree(src, dst, symlinks=False, ignore=None):
"""Copy from source directory to destination"""
# TODO(crow): OSError: [Errno 17] File exists
if not osp.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = osp.join(src, item)
d = osp.join(dst, item)
if osp.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d) | [
"def",
"copytree",
"(",
"src",
",",
"dst",
",",
"symlinks",
"=",
"False",
",",
"ignore",
"=",
"None",
")",
":",
"# TODO(crow): OSError: [Errno 17] File exists",
"if",
"not",
"osp",
".",
"exists",
"(",
"dst",
")",
":",
"os",
".",
"makedirs",
"(",
"dst",
")",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"src",
")",
":",
"s",
"=",
"osp",
".",
"join",
"(",
"src",
",",
"item",
")",
"d",
"=",
"osp",
".",
"join",
"(",
"dst",
",",
"item",
")",
"if",
"osp",
".",
"isdir",
"(",
"s",
")",
":",
"shutil",
".",
"copytree",
"(",
"s",
",",
"d",
",",
"symlinks",
",",
"ignore",
")",
"else",
":",
"shutil",
".",
"copy2",
"(",
"s",
",",
"d",
")"
] | Copy from source directory to destination | [
"Copy",
"from",
"source",
"directory",
"to",
"destination"
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L58-L70 |
248,178 | wlwang41/cb | cb/tools.py | emptytree | def emptytree(directory):
"""Delete all the files and dirs under specified directory"""
for p in os.listdir(directory):
fp = osp.join(directory, p)
if osp.isdir(fp):
try:
shutil.rmtree(fp)
logger.info("Delete directory %s" % fp)
except Exception, e:
logger.error("Unable to delete directory %s: %s" % (fp, str(e)))
elif osp.isfile(fp):
try:
logging.info("Delete file %s" % fp)
os.remove(fp)
except Exception, e:
logger.error("Unable to delete file %s: %s" % (fp, str(e)))
else:
logger.error("Unable to delete %s, unknown filetype" % fp) | python | def emptytree(directory):
"""Delete all the files and dirs under specified directory"""
for p in os.listdir(directory):
fp = osp.join(directory, p)
if osp.isdir(fp):
try:
shutil.rmtree(fp)
logger.info("Delete directory %s" % fp)
except Exception, e:
logger.error("Unable to delete directory %s: %s" % (fp, str(e)))
elif osp.isfile(fp):
try:
logging.info("Delete file %s" % fp)
os.remove(fp)
except Exception, e:
logger.error("Unable to delete file %s: %s" % (fp, str(e)))
else:
logger.error("Unable to delete %s, unknown filetype" % fp) | [
"def",
"emptytree",
"(",
"directory",
")",
":",
"for",
"p",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"fp",
"=",
"osp",
".",
"join",
"(",
"directory",
",",
"p",
")",
"if",
"osp",
".",
"isdir",
"(",
"fp",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"fp",
")",
"logger",
".",
"info",
"(",
"\"Delete directory %s\"",
"%",
"fp",
")",
"except",
"Exception",
",",
"e",
":",
"logger",
".",
"error",
"(",
"\"Unable to delete directory %s: %s\"",
"%",
"(",
"fp",
",",
"str",
"(",
"e",
")",
")",
")",
"elif",
"osp",
".",
"isfile",
"(",
"fp",
")",
":",
"try",
":",
"logging",
".",
"info",
"(",
"\"Delete file %s\"",
"%",
"fp",
")",
"os",
".",
"remove",
"(",
"fp",
")",
"except",
"Exception",
",",
"e",
":",
"logger",
".",
"error",
"(",
"\"Unable to delete file %s: %s\"",
"%",
"(",
"fp",
",",
"str",
"(",
"e",
")",
")",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Unable to delete %s, unknown filetype\"",
"%",
"fp",
")"
] | Delete all the files and dirs under specified directory | [
"Delete",
"all",
"the",
"files",
"and",
"dirs",
"under",
"specified",
"directory"
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L73-L91 |
248,179 | wlwang41/cb | cb/tools.py | listdir_nohidden | def listdir_nohidden(path):
"""List not hidden files or directories under path"""
for f in os.listdir(path):
if isinstance(f, str):
f = unicode(f, "utf-8")
if not f.startswith('.'):
yield f | python | def listdir_nohidden(path):
"""List not hidden files or directories under path"""
for f in os.listdir(path):
if isinstance(f, str):
f = unicode(f, "utf-8")
if not f.startswith('.'):
yield f | [
"def",
"listdir_nohidden",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"f",
"=",
"unicode",
"(",
"f",
",",
"\"utf-8\"",
")",
"if",
"not",
"f",
".",
"startswith",
"(",
"'.'",
")",
":",
"yield",
"f"
] | List not hidden files or directories under path | [
"List",
"not",
"hidden",
"files",
"or",
"directories",
"under",
"path"
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L105-L111 |
248,180 | wlwang41/cb | cb/tools.py | check_config | def check_config(data):
"""Check if metadata is right
TODO(crow): check more
"""
is_right = True
if "title" not in data:
logging.error("No 'title' in _config.yml")
is_right = False
return is_right | python | def check_config(data):
"""Check if metadata is right
TODO(crow): check more
"""
is_right = True
if "title" not in data:
logging.error("No 'title' in _config.yml")
is_right = False
return is_right | [
"def",
"check_config",
"(",
"data",
")",
":",
"is_right",
"=",
"True",
"if",
"\"title\"",
"not",
"in",
"data",
":",
"logging",
".",
"error",
"(",
"\"No 'title' in _config.yml\"",
")",
"is_right",
"=",
"False",
"return",
"is_right"
] | Check if metadata is right
TODO(crow): check more | [
"Check",
"if",
"metadata",
"is",
"right"
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L131-L143 |
248,181 | wlwang41/cb | cb/tools.py | get_ymal_data | def get_ymal_data(data):
"""Get metadata and validate them
:param data: metadata in yaml format
"""
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sys.exit(1)
if not check_config(format_data):
sys.exit(1)
return format_data | python | def get_ymal_data(data):
"""Get metadata and validate them
:param data: metadata in yaml format
"""
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sys.exit(1)
if not check_config(format_data):
sys.exit(1)
return format_data | [
"def",
"get_ymal_data",
"(",
"data",
")",
":",
"try",
":",
"format_data",
"=",
"yaml",
".",
"load",
"(",
"data",
")",
"except",
"yaml",
".",
"YAMLError",
",",
"e",
":",
"msg",
"=",
"\"Yaml format error: {}\"",
".",
"format",
"(",
"unicode",
"(",
"str",
"(",
"e",
")",
",",
"\"utf-8\"",
")",
")",
"logging",
".",
"error",
"(",
"msg",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"check_config",
"(",
"format_data",
")",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"format_data"
] | Get metadata and validate them
:param data: metadata in yaml format | [
"Get",
"metadata",
"and",
"validate",
"them"
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L146-L163 |
248,182 | wlwang41/cb | cb/tools.py | parse_markdown | def parse_markdown(markdown_content, site_settings):
"""Parse markdown text to html.
:param markdown_content: Markdown text lists #TODO#
"""
markdown_extensions = set_markdown_extensions(site_settings)
html_content = markdown.markdown(
markdown_content,
extensions=markdown_extensions,
)
return html_content | python | def parse_markdown(markdown_content, site_settings):
"""Parse markdown text to html.
:param markdown_content: Markdown text lists #TODO#
"""
markdown_extensions = set_markdown_extensions(site_settings)
html_content = markdown.markdown(
markdown_content,
extensions=markdown_extensions,
)
return html_content | [
"def",
"parse_markdown",
"(",
"markdown_content",
",",
"site_settings",
")",
":",
"markdown_extensions",
"=",
"set_markdown_extensions",
"(",
"site_settings",
")",
"html_content",
"=",
"markdown",
".",
"markdown",
"(",
"markdown_content",
",",
"extensions",
"=",
"markdown_extensions",
",",
")",
"return",
"html_content"
] | Parse markdown text to html.
:param markdown_content: Markdown text lists #TODO# | [
"Parse",
"markdown",
"text",
"to",
"html",
"."
] | 0a7faa427e3e6593980687dfe1a882ac99d743f6 | https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L180-L192 |
248,183 | fopina/tgbotplug | tgbot/botapi.py | TelegramBotRPCRequest.wait | def wait(self):
"""
Wait for the request to finish and return the result or error when finished
:returns: result or error
:type: result tyoe or Error
"""
self.thread.join()
if self.error is not None:
return self.error
return self.result | python | def wait(self):
"""
Wait for the request to finish and return the result or error when finished
:returns: result or error
:type: result tyoe or Error
"""
self.thread.join()
if self.error is not None:
return self.error
return self.result | [
"def",
"wait",
"(",
"self",
")",
":",
"self",
".",
"thread",
".",
"join",
"(",
")",
"if",
"self",
".",
"error",
"is",
"not",
"None",
":",
"return",
"self",
".",
"error",
"return",
"self",
".",
"result"
] | Wait for the request to finish and return the result or error when finished
:returns: result or error
:type: result tyoe or Error | [
"Wait",
"for",
"the",
"request",
"to",
"finish",
"and",
"return",
"the",
"result",
"or",
"error",
"when",
"finished"
] | c115733b03f2e23ddcdecfce588d1a6a1e5bde91 | https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1149-L1159 |
248,184 | armstrong/armstrong.core.arm_sections | armstrong/core/arm_sections/backends.py | ItemFilter.filter_objects_by_section | def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_manager(get_item_model_class()).filter(q).distinct() | python | def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_manager(get_item_model_class()).filter(q).distinct() | [
"def",
"filter_objects_by_section",
"(",
"self",
",",
"rels",
",",
"section",
")",
":",
"subtree",
"=",
"section",
".",
"get_descendants",
"(",
"include_self",
"=",
"True",
")",
"kwargs_list",
"=",
"[",
"{",
"'%s__in'",
"%",
"rel",
".",
"field",
".",
"name",
":",
"subtree",
"}",
"for",
"rel",
"in",
"rels",
"]",
"q",
"=",
"Q",
"(",
"*",
"*",
"kwargs_list",
"[",
"0",
"]",
")",
"for",
"kwargs",
"in",
"kwargs_list",
"[",
"1",
":",
"]",
":",
"q",
"|=",
"Q",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"get_manager",
"(",
"get_item_model_class",
"(",
")",
")",
".",
"filter",
"(",
"q",
")",
".",
"distinct",
"(",
")"
] | Build a queryset containing all objects in the section subtree. | [
"Build",
"a",
"queryset",
"containing",
"all",
"objects",
"in",
"the",
"section",
"subtree",
"."
] | 39c999c93771da909359e53b35afefe4846f77cb | https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/backends.py#L16-L24 |
248,185 | etgalloway/fullqualname | fullqualname.py | fullqualname_py3 | def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
elif type(obj).__name__ == 'function':
return _fullqualname_function_py3(obj)
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_descriptor']:
return obj.__objclass__.__module__ + '.' + obj.__qualname__
elif type(obj).__name__ == 'method':
return _fullqualname_method_py3(obj)
elif type(obj).__name__ == 'method-wrapper':
return fullqualname_py3(obj.__self__) + '.' + obj.__name__
elif type(obj).__name__ == 'module':
return obj.__name__
elif type(obj).__name__ == 'property':
return obj.fget.__module__ + '.' + obj.fget.__qualname__
elif inspect.isclass(obj):
return obj.__module__ + '.' + obj.__qualname__
return obj.__class__.__module__ + '.' + obj.__class__.__qualname__ | python | def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
elif type(obj).__name__ == 'function':
return _fullqualname_function_py3(obj)
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_descriptor']:
return obj.__objclass__.__module__ + '.' + obj.__qualname__
elif type(obj).__name__ == 'method':
return _fullqualname_method_py3(obj)
elif type(obj).__name__ == 'method-wrapper':
return fullqualname_py3(obj.__self__) + '.' + obj.__name__
elif type(obj).__name__ == 'module':
return obj.__name__
elif type(obj).__name__ == 'property':
return obj.fget.__module__ + '.' + obj.fget.__qualname__
elif inspect.isclass(obj):
return obj.__module__ + '.' + obj.__qualname__
return obj.__class__.__module__ + '.' + obj.__class__.__qualname__ | [
"def",
"fullqualname_py3",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'builtin_function_or_method'",
":",
"return",
"_fullqualname_builtin_py3",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'function'",
":",
"return",
"_fullqualname_function_py3",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"in",
"[",
"'member_descriptor'",
",",
"'method_descriptor'",
",",
"'wrapper_descriptor'",
"]",
":",
"return",
"obj",
".",
"__objclass__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__qualname__",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'method'",
":",
"return",
"_fullqualname_method_py3",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'method-wrapper'",
":",
"return",
"fullqualname_py3",
"(",
"obj",
".",
"__self__",
")",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'module'",
":",
"return",
"obj",
".",
"__name__",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'property'",
":",
"return",
"obj",
".",
"fget",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"fget",
".",
"__qualname__",
"elif",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__qualname__",
"return",
"obj",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__class__",
".",
"__qualname__"
] | Fully qualified name for objects in Python 3. | [
"Fully",
"qualified",
"name",
"for",
"objects",
"in",
"Python",
"3",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L9-L45 |
248,186 | etgalloway/fullqualname | fullqualname.py | _fullqualname_builtin_py3 | def _fullqualname_builtin_py3(obj):
"""Fully qualified name for 'builtin_function_or_method' objects in
Python 3.
"""
if obj.__module__ is not None:
# built-in functions
module = obj.__module__
else:
# built-in methods
if inspect.isclass(obj.__self__):
module = obj.__self__.__module__
else:
module = obj.__self__.__class__.__module__
return module + '.' + obj.__qualname__ | python | def _fullqualname_builtin_py3(obj):
"""Fully qualified name for 'builtin_function_or_method' objects in
Python 3.
"""
if obj.__module__ is not None:
# built-in functions
module = obj.__module__
else:
# built-in methods
if inspect.isclass(obj.__self__):
module = obj.__self__.__module__
else:
module = obj.__self__.__class__.__module__
return module + '.' + obj.__qualname__ | [
"def",
"_fullqualname_builtin_py3",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"__module__",
"is",
"not",
"None",
":",
"# built-in functions",
"module",
"=",
"obj",
".",
"__module__",
"else",
":",
"# built-in methods",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
".",
"__self__",
")",
":",
"module",
"=",
"obj",
".",
"__self__",
".",
"__module__",
"else",
":",
"module",
"=",
"obj",
".",
"__self__",
".",
"__class__",
".",
"__module__",
"return",
"module",
"+",
"'.'",
"+",
"obj",
".",
"__qualname__"
] | Fully qualified name for 'builtin_function_or_method' objects in
Python 3. | [
"Fully",
"qualified",
"name",
"for",
"builtin_function_or_method",
"objects",
"in",
"Python",
"3",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L48-L63 |
248,187 | etgalloway/fullqualname | fullqualname.py | _fullqualname_function_py3 | def _fullqualname_function_py3(obj):
"""Fully qualified name for 'function' objects in Python 3.
"""
if hasattr(obj, "__wrapped__"):
# Required for decorator.__version__ <= 4.0.0.
qualname = obj.__wrapped__.__qualname__
else:
qualname = obj.__qualname__
return obj.__module__ + '.' + qualname | python | def _fullqualname_function_py3(obj):
"""Fully qualified name for 'function' objects in Python 3.
"""
if hasattr(obj, "__wrapped__"):
# Required for decorator.__version__ <= 4.0.0.
qualname = obj.__wrapped__.__qualname__
else:
qualname = obj.__qualname__
return obj.__module__ + '.' + qualname | [
"def",
"_fullqualname_function_py3",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"__wrapped__\"",
")",
":",
"# Required for decorator.__version__ <= 4.0.0.",
"qualname",
"=",
"obj",
".",
"__wrapped__",
".",
"__qualname__",
"else",
":",
"qualname",
"=",
"obj",
".",
"__qualname__",
"return",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"qualname"
] | Fully qualified name for 'function' objects in Python 3. | [
"Fully",
"qualified",
"name",
"for",
"function",
"objects",
"in",
"Python",
"3",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L66-L76 |
248,188 | etgalloway/fullqualname | fullqualname.py | _fullqualname_method_py3 | def _fullqualname_method_py3(obj):
"""Fully qualified name for 'method' objects in Python 3.
"""
if inspect.isclass(obj.__self__):
cls = obj.__self__.__qualname__
else:
cls = obj.__self__.__class__.__qualname__
return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__ | python | def _fullqualname_method_py3(obj):
"""Fully qualified name for 'method' objects in Python 3.
"""
if inspect.isclass(obj.__self__):
cls = obj.__self__.__qualname__
else:
cls = obj.__self__.__class__.__qualname__
return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__ | [
"def",
"_fullqualname_method_py3",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
".",
"__self__",
")",
":",
"cls",
"=",
"obj",
".",
"__self__",
".",
"__qualname__",
"else",
":",
"cls",
"=",
"obj",
".",
"__self__",
".",
"__class__",
".",
"__qualname__",
"return",
"obj",
".",
"__self__",
".",
"__module__",
"+",
"'.'",
"+",
"cls",
"+",
"'.'",
"+",
"obj",
".",
"__name__"
] | Fully qualified name for 'method' objects in Python 3. | [
"Fully",
"qualified",
"name",
"for",
"method",
"objects",
"in",
"Python",
"3",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L79-L88 |
248,189 | etgalloway/fullqualname | fullqualname.py | fullqualname_py2 | def fullqualname_py2(obj):
"""Fully qualified name for objects in Python 2."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py2(obj)
elif type(obj).__name__ == 'function':
return obj.__module__ + '.' + obj.__name__
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_descriptor']:
return (obj.__objclass__.__module__ + '.' +
obj.__objclass__.__name__ + '.' +
obj.__name__)
elif type(obj).__name__ == 'instancemethod':
return _fullqualname_method_py2(obj)
elif type(obj).__name__ == 'method-wrapper':
return fullqualname_py2(obj.__self__) + '.' + obj.__name__
elif type(obj).__name__ == 'module':
return obj.__name__
elif inspect.isclass(obj):
return obj.__module__ + '.' + obj.__name__
return obj.__class__.__module__ + '.' + obj.__class__.__name__ | python | def fullqualname_py2(obj):
"""Fully qualified name for objects in Python 2."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py2(obj)
elif type(obj).__name__ == 'function':
return obj.__module__ + '.' + obj.__name__
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_descriptor']:
return (obj.__objclass__.__module__ + '.' +
obj.__objclass__.__name__ + '.' +
obj.__name__)
elif type(obj).__name__ == 'instancemethod':
return _fullqualname_method_py2(obj)
elif type(obj).__name__ == 'method-wrapper':
return fullqualname_py2(obj.__self__) + '.' + obj.__name__
elif type(obj).__name__ == 'module':
return obj.__name__
elif inspect.isclass(obj):
return obj.__module__ + '.' + obj.__name__
return obj.__class__.__module__ + '.' + obj.__class__.__name__ | [
"def",
"fullqualname_py2",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'builtin_function_or_method'",
":",
"return",
"_fullqualname_builtin_py2",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'function'",
":",
"return",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"in",
"[",
"'member_descriptor'",
",",
"'method_descriptor'",
",",
"'wrapper_descriptor'",
"]",
":",
"return",
"(",
"obj",
".",
"__objclass__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__objclass__",
".",
"__name__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'instancemethod'",
":",
"return",
"_fullqualname_method_py2",
"(",
"obj",
")",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'method-wrapper'",
":",
"return",
"fullqualname_py2",
"(",
"obj",
".",
"__self__",
")",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
"elif",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'module'",
":",
"return",
"obj",
".",
"__name__",
"elif",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
"return",
"obj",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__class__",
".",
"__name__"
] | Fully qualified name for objects in Python 2. | [
"Fully",
"qualified",
"name",
"for",
"objects",
"in",
"Python",
"2",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L91-L125 |
248,190 | etgalloway/fullqualname | fullqualname.py | _fullqualname_builtin_py2 | def _fullqualname_builtin_py2(obj):
"""Fully qualified name for 'builtin_function_or_method' objects
in Python 2.
"""
if obj.__self__ is None:
# built-in functions
module = obj.__module__
qualname = obj.__name__
else:
# built-in methods
if inspect.isclass(obj.__self__):
cls = obj.__self__
else:
cls = obj.__self__.__class__
module = cls.__module__
qualname = cls.__name__ + '.' + obj.__name__
return module + '.' + qualname | python | def _fullqualname_builtin_py2(obj):
"""Fully qualified name for 'builtin_function_or_method' objects
in Python 2.
"""
if obj.__self__ is None:
# built-in functions
module = obj.__module__
qualname = obj.__name__
else:
# built-in methods
if inspect.isclass(obj.__self__):
cls = obj.__self__
else:
cls = obj.__self__.__class__
module = cls.__module__
qualname = cls.__name__ + '.' + obj.__name__
return module + '.' + qualname | [
"def",
"_fullqualname_builtin_py2",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"__self__",
"is",
"None",
":",
"# built-in functions",
"module",
"=",
"obj",
".",
"__module__",
"qualname",
"=",
"obj",
".",
"__name__",
"else",
":",
"# built-in methods",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
".",
"__self__",
")",
":",
"cls",
"=",
"obj",
".",
"__self__",
"else",
":",
"cls",
"=",
"obj",
".",
"__self__",
".",
"__class__",
"module",
"=",
"cls",
".",
"__module__",
"qualname",
"=",
"cls",
".",
"__name__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
"return",
"module",
"+",
"'.'",
"+",
"qualname"
] | Fully qualified name for 'builtin_function_or_method' objects
in Python 2. | [
"Fully",
"qualified",
"name",
"for",
"builtin_function_or_method",
"objects",
"in",
"Python",
"2",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L128-L146 |
248,191 | etgalloway/fullqualname | fullqualname.py | _fullqualname_method_py2 | def _fullqualname_method_py2(obj):
"""Fully qualified name for 'instancemethod' objects in Python 2.
"""
if obj.__self__ is None:
# unbound methods
module = obj.im_class.__module__
cls = obj.im_class.__name__
else:
# bound methods
if inspect.isclass(obj.__self__):
# methods decorated with @classmethod
module = obj.__self__.__module__
cls = obj.__self__.__name__
else:
module = obj.__self__.__class__.__module__
cls = obj.__self__.__class__.__name__
return module + '.' + cls + '.' + obj.__func__.__name__ | python | def _fullqualname_method_py2(obj):
"""Fully qualified name for 'instancemethod' objects in Python 2.
"""
if obj.__self__ is None:
# unbound methods
module = obj.im_class.__module__
cls = obj.im_class.__name__
else:
# bound methods
if inspect.isclass(obj.__self__):
# methods decorated with @classmethod
module = obj.__self__.__module__
cls = obj.__self__.__name__
else:
module = obj.__self__.__class__.__module__
cls = obj.__self__.__class__.__name__
return module + '.' + cls + '.' + obj.__func__.__name__ | [
"def",
"_fullqualname_method_py2",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"__self__",
"is",
"None",
":",
"# unbound methods",
"module",
"=",
"obj",
".",
"im_class",
".",
"__module__",
"cls",
"=",
"obj",
".",
"im_class",
".",
"__name__",
"else",
":",
"# bound methods",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
".",
"__self__",
")",
":",
"# methods decorated with @classmethod",
"module",
"=",
"obj",
".",
"__self__",
".",
"__module__",
"cls",
"=",
"obj",
".",
"__self__",
".",
"__name__",
"else",
":",
"module",
"=",
"obj",
".",
"__self__",
".",
"__class__",
".",
"__module__",
"cls",
"=",
"obj",
".",
"__self__",
".",
"__class__",
".",
"__name__",
"return",
"module",
"+",
"'.'",
"+",
"cls",
"+",
"'.'",
"+",
"obj",
".",
"__func__",
".",
"__name__"
] | Fully qualified name for 'instancemethod' objects in Python 2. | [
"Fully",
"qualified",
"name",
"for",
"instancemethod",
"objects",
"in",
"Python",
"2",
"."
] | c16fa82880219cf91cdcd5466db9bf2099592c59 | https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L149-L167 |
248,192 | monkeython/scriba | scriba/content_types/scriba_x_tar.py | parse | def parse(binary, **params):
"""Turns a TAR file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with tarfile.TarFile(fileobj=binary, mode='r') as tar:
for tar_info in tar.getmembers():
content_type, encoding = mimetypes.guess_type(tar_info.name)
content = tar.extractfile(tar_info)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content, **params)
collection.apppend((tar_info.name, content))
return collection | python | def parse(binary, **params):
"""Turns a TAR file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with tarfile.TarFile(fileobj=binary, mode='r') as tar:
for tar_info in tar.getmembers():
content_type, encoding = mimetypes.guess_type(tar_info.name)
content = tar.extractfile(tar_info)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content, **params)
collection.apppend((tar_info.name, content))
return collection | [
"def",
"parse",
"(",
"binary",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
"binary",
")",
"collection",
"=",
"list",
"(",
")",
"with",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"binary",
",",
"mode",
"=",
"'r'",
")",
"as",
"tar",
":",
"for",
"tar_info",
"in",
"tar",
".",
"getmembers",
"(",
")",
":",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"tar_info",
".",
"name",
")",
"content",
"=",
"tar",
".",
"extractfile",
"(",
"tar_info",
")",
"content",
"=",
"content_encodings",
".",
"get",
"(",
"encoding",
")",
".",
"decode",
"(",
"content",
")",
"content",
"=",
"content_types",
".",
"get",
"(",
"content_type",
")",
".",
"parse",
"(",
"content",
",",
"*",
"*",
"params",
")",
"collection",
".",
"apppend",
"(",
"(",
"tar_info",
".",
"name",
",",
"content",
")",
")",
"return",
"collection"
] | Turns a TAR file into a frozen sample. | [
"Turns",
"a",
"TAR",
"file",
"into",
"a",
"frozen",
"sample",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L16-L27 |
248,193 | monkeython/scriba | scriba/content_types/scriba_x_tar.py | format | def format(collection, **params):
"""Truns a frozen sample into a TAR file."""
binary = io.BytesIO()
with tarfile.TarFile(fileobj=binary, mode='w') as tar:
mode = params.get('mode', 0o640)
now = calendar.timegm(datetime.datetime.utcnow().timetuple())
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename)
content = content_types.get(content_type).format(content, **params)
content = content_encodings.get(encoding).encode(content)
member_content = io.BytesIO(content)
member_info = tarfile.TarInfo(filename)
member_info.size = len(content)
member_info.mode = mode
member_info.mtime = now
tar.addfile(member_info, member_content)
binary.seek(0)
return binary.read() | python | def format(collection, **params):
"""Truns a frozen sample into a TAR file."""
binary = io.BytesIO()
with tarfile.TarFile(fileobj=binary, mode='w') as tar:
mode = params.get('mode', 0o640)
now = calendar.timegm(datetime.datetime.utcnow().timetuple())
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename)
content = content_types.get(content_type).format(content, **params)
content = content_encodings.get(encoding).encode(content)
member_content = io.BytesIO(content)
member_info = tarfile.TarInfo(filename)
member_info.size = len(content)
member_info.mode = mode
member_info.mtime = now
tar.addfile(member_info, member_content)
binary.seek(0)
return binary.read() | [
"def",
"format",
"(",
"collection",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
")",
"with",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"binary",
",",
"mode",
"=",
"'w'",
")",
"as",
"tar",
":",
"mode",
"=",
"params",
".",
"get",
"(",
"'mode'",
",",
"0o640",
")",
"now",
"=",
"calendar",
".",
"timegm",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timetuple",
"(",
")",
")",
"for",
"filename",
",",
"content",
"in",
"collection",
":",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"content",
"=",
"content_types",
".",
"get",
"(",
"content_type",
")",
".",
"format",
"(",
"content",
",",
"*",
"*",
"params",
")",
"content",
"=",
"content_encodings",
".",
"get",
"(",
"encoding",
")",
".",
"encode",
"(",
"content",
")",
"member_content",
"=",
"io",
".",
"BytesIO",
"(",
"content",
")",
"member_info",
"=",
"tarfile",
".",
"TarInfo",
"(",
"filename",
")",
"member_info",
".",
"size",
"=",
"len",
"(",
"content",
")",
"member_info",
".",
"mode",
"=",
"mode",
"member_info",
".",
"mtime",
"=",
"now",
"tar",
".",
"addfile",
"(",
"member_info",
",",
"member_content",
")",
"binary",
".",
"seek",
"(",
"0",
")",
"return",
"binary",
".",
"read",
"(",
")"
] | Truns a frozen sample into a TAR file. | [
"Truns",
"a",
"frozen",
"sample",
"into",
"a",
"TAR",
"file",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L30-L47 |
248,194 | abalkin/tz | tzdata-pkg/tzdata/__init__.py | get | def get(tzid):
"""Return timezone data"""
ns = {}
path = os.path.join(DATA_DIR, tzid)
with open(path) as f:
raw_data = f.read()
exec(raw_data, ns, ns)
z = ZoneData()
z.types = [(delta(offset), delta(save), abbr)
for offset, save, abbr in ns['types']]
z.times = [(datetime(*time), i)
for time, i in ns['times']]
z.rules = ns['posix']
return z | python | def get(tzid):
"""Return timezone data"""
ns = {}
path = os.path.join(DATA_DIR, tzid)
with open(path) as f:
raw_data = f.read()
exec(raw_data, ns, ns)
z = ZoneData()
z.types = [(delta(offset), delta(save), abbr)
for offset, save, abbr in ns['types']]
z.times = [(datetime(*time), i)
for time, i in ns['times']]
z.rules = ns['posix']
return z | [
"def",
"get",
"(",
"tzid",
")",
":",
"ns",
"=",
"{",
"}",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DATA_DIR",
",",
"tzid",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"raw_data",
"=",
"f",
".",
"read",
"(",
")",
"exec",
"(",
"raw_data",
",",
"ns",
",",
"ns",
")",
"z",
"=",
"ZoneData",
"(",
")",
"z",
".",
"types",
"=",
"[",
"(",
"delta",
"(",
"offset",
")",
",",
"delta",
"(",
"save",
")",
",",
"abbr",
")",
"for",
"offset",
",",
"save",
",",
"abbr",
"in",
"ns",
"[",
"'types'",
"]",
"]",
"z",
".",
"times",
"=",
"[",
"(",
"datetime",
"(",
"*",
"time",
")",
",",
"i",
")",
"for",
"time",
",",
"i",
"in",
"ns",
"[",
"'times'",
"]",
"]",
"z",
".",
"rules",
"=",
"ns",
"[",
"'posix'",
"]",
"return",
"z"
] | Return timezone data | [
"Return",
"timezone",
"data"
] | f25fca6afbf1abd46fd7aeb978282823c7dab5ab | https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/tzdata-pkg/tzdata/__init__.py#L40-L53 |
248,195 | carlitux/turboengine | src/turboengine/decorators.py | login_required | def login_required(method):
"""A decorator that control if a user is logged."""
def wrapper(self, *arg, **karg):
if not self.user:
if self.request.method == "GET":
self.redirect(settings.LOGIN_PATH)
else:
self.error(403)
else:
method(self, *arg, **karg)
return wrapper | python | def login_required(method):
"""A decorator that control if a user is logged."""
def wrapper(self, *arg, **karg):
if not self.user:
if self.request.method == "GET":
self.redirect(settings.LOGIN_PATH)
else:
self.error(403)
else:
method(self, *arg, **karg)
return wrapper | [
"def",
"login_required",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"arg",
",",
"*",
"*",
"karg",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"if",
"self",
".",
"request",
".",
"method",
"==",
"\"GET\"",
":",
"self",
".",
"redirect",
"(",
"settings",
".",
"LOGIN_PATH",
")",
"else",
":",
"self",
".",
"error",
"(",
"403",
")",
"else",
":",
"method",
"(",
"self",
",",
"*",
"arg",
",",
"*",
"*",
"karg",
")",
"return",
"wrapper"
] | A decorator that control if a user is logged. | [
"A",
"decorator",
"that",
"control",
"if",
"a",
"user",
"is",
"logged",
"."
] | 627b6dbc400d8c16e2ff7e17afd01915371ea287 | https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/decorators.py#L29-L39 |
248,196 | b3j0f/annotation | b3j0f/annotation/interception.py | Interceptor.pointcut | def pointcut(self, value):
"""Change of pointcut.
"""
pointcut = getattr(self, Interceptor.POINTCUT)
# for all targets
for target in self.targets:
# unweave old advices
unweave(target, pointcut=pointcut, advices=self.intercepts)
# weave new advices with new pointcut
weave(target, pointcut=value, advices=self.intercepts)
# and save new pointcut
setattr(self, Interceptor._POINTCUT, value) | python | def pointcut(self, value):
"""Change of pointcut.
"""
pointcut = getattr(self, Interceptor.POINTCUT)
# for all targets
for target in self.targets:
# unweave old advices
unweave(target, pointcut=pointcut, advices=self.intercepts)
# weave new advices with new pointcut
weave(target, pointcut=value, advices=self.intercepts)
# and save new pointcut
setattr(self, Interceptor._POINTCUT, value) | [
"def",
"pointcut",
"(",
"self",
",",
"value",
")",
":",
"pointcut",
"=",
"getattr",
"(",
"self",
",",
"Interceptor",
".",
"POINTCUT",
")",
"# for all targets",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"# unweave old advices",
"unweave",
"(",
"target",
",",
"pointcut",
"=",
"pointcut",
",",
"advices",
"=",
"self",
".",
"intercepts",
")",
"# weave new advices with new pointcut",
"weave",
"(",
"target",
",",
"pointcut",
"=",
"value",
",",
"advices",
"=",
"self",
".",
"intercepts",
")",
"# and save new pointcut",
"setattr",
"(",
"self",
",",
"Interceptor",
".",
"_POINTCUT",
",",
"value",
")"
] | Change of pointcut. | [
"Change",
"of",
"pointcut",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L95-L109 |
248,197 | b3j0f/annotation | b3j0f/annotation/interception.py | Interceptor._bind_target | def _bind_target(self, target, ctx=None, *args, **kwargs):
"""Weave self.intercepts among target advices with pointcut."""
result = super(Interceptor, self)._bind_target(
target=target, ctx=ctx, *args, **kwargs
)
pointcut = getattr(self, Interceptor.POINTCUT)
weave(result, pointcut=pointcut, advices=self.intercepts, ctx=ctx)
return result | python | def _bind_target(self, target, ctx=None, *args, **kwargs):
"""Weave self.intercepts among target advices with pointcut."""
result = super(Interceptor, self)._bind_target(
target=target, ctx=ctx, *args, **kwargs
)
pointcut = getattr(self, Interceptor.POINTCUT)
weave(result, pointcut=pointcut, advices=self.intercepts, ctx=ctx)
return result | [
"def",
"_bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"super",
"(",
"Interceptor",
",",
"self",
")",
".",
"_bind_target",
"(",
"target",
"=",
"target",
",",
"ctx",
"=",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"pointcut",
"=",
"getattr",
"(",
"self",
",",
"Interceptor",
".",
"POINTCUT",
")",
"weave",
"(",
"result",
",",
"pointcut",
"=",
"pointcut",
",",
"advices",
"=",
"self",
".",
"intercepts",
",",
"ctx",
"=",
"ctx",
")",
"return",
"result"
] | Weave self.intercepts among target advices with pointcut. | [
"Weave",
"self",
".",
"intercepts",
"among",
"target",
"advices",
"with",
"pointcut",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L111-L122 |
248,198 | b3j0f/annotation | b3j0f/annotation/interception.py | Interceptor.intercepts | def intercepts(self, joinpoint):
"""Self target interception if self is enabled
:param joinpoint: advices executor
"""
result = None
if self.enable:
interception = getattr(self, Interceptor.INTERCEPTION)
joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self
result = interception(joinpoint)
else:
result = joinpoint.proceed()
return result | python | def intercepts(self, joinpoint):
"""Self target interception if self is enabled
:param joinpoint: advices executor
"""
result = None
if self.enable:
interception = getattr(self, Interceptor.INTERCEPTION)
joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self
result = interception(joinpoint)
else:
result = joinpoint.proceed()
return result | [
"def",
"intercepts",
"(",
"self",
",",
"joinpoint",
")",
":",
"result",
"=",
"None",
"if",
"self",
".",
"enable",
":",
"interception",
"=",
"getattr",
"(",
"self",
",",
"Interceptor",
".",
"INTERCEPTION",
")",
"joinpoint",
".",
"exec_ctx",
"[",
"Interceptor",
".",
"INTERCEPTION",
"]",
"=",
"self",
"result",
"=",
"interception",
"(",
"joinpoint",
")",
"else",
":",
"result",
"=",
"joinpoint",
".",
"proceed",
"(",
")",
"return",
"result"
] | Self target interception if self is enabled
:param joinpoint: advices executor | [
"Self",
"target",
"interception",
"if",
"self",
"is",
"enabled"
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L132-L151 |
248,199 | devricks/soft_drf | soft_drf/auth/utilities.py | create_token | def create_token(user):
"""
Create token.
"""
payload = jwt_payload_handler(user)
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.utcnow().utctimetuple()
)
# Return values
token = jwt_encode_handler(payload)
return token | python | def create_token(user):
"""
Create token.
"""
payload = jwt_payload_handler(user)
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.utcnow().utctimetuple()
)
# Return values
token = jwt_encode_handler(payload)
return token | [
"def",
"create_token",
"(",
"user",
")",
":",
"payload",
"=",
"jwt_payload_handler",
"(",
"user",
")",
"if",
"api_settings",
".",
"JWT_ALLOW_REFRESH",
":",
"payload",
"[",
"'orig_iat'",
"]",
"=",
"timegm",
"(",
"datetime",
".",
"utcnow",
"(",
")",
".",
"utctimetuple",
"(",
")",
")",
"# Return values",
"token",
"=",
"jwt_encode_handler",
"(",
"payload",
")",
"return",
"token"
] | Create token. | [
"Create",
"token",
"."
] | 1869b13f9341bfcebd931059e93de2bc38570da3 | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/utilities.py#L107-L119 |
Subsets and Splits