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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
src-d/modelforge
modelforge/backends.py
register_backend
def register_backend(cls: Type[StorageBackend]): """Decorator to register another StorageBackend using it's `NAME`.""" if not issubclass(cls, StorageBackend): raise TypeError("cls must be a subclass of StorageBackend") __registry__[cls.NAME] = cls return cls
python
def register_backend(cls: Type[StorageBackend]): """Decorator to register another StorageBackend using it's `NAME`.""" if not issubclass(cls, StorageBackend): raise TypeError("cls must be a subclass of StorageBackend") __registry__[cls.NAME] = cls return cls
[ "def", "register_backend", "(", "cls", ":", "Type", "[", "StorageBackend", "]", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "StorageBackend", ")", ":", "raise", "TypeError", "(", "\"cls must be a subclass of StorageBackend\"", ")", "__registry__", "[", ...
Decorator to register another StorageBackend using it's `NAME`.
[ "Decorator", "to", "register", "another", "StorageBackend", "using", "it", "s", "NAME", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L13-L18
train
26,400
src-d/modelforge
modelforge/backends.py
create_backend
def create_backend(name: str=None, git_index: GitIndex=None, args: str=None) -> StorageBackend: """Initialize a new StorageBackend by it's name and the specified model registry.""" if name is None: name = config.BACKEND if not args: args = config.BACKEND_ARGS if args: try: kwargs = dict(p.split("=") for p in args.split(",")) except: # flake8: noqa raise ValueError("Invalid args") from None else: kwargs = {} if git_index is None: git_index = GitIndex() kwargs["index"] = git_index return __registry__[name](**kwargs)
python
def create_backend(name: str=None, git_index: GitIndex=None, args: str=None) -> StorageBackend: """Initialize a new StorageBackend by it's name and the specified model registry.""" if name is None: name = config.BACKEND if not args: args = config.BACKEND_ARGS if args: try: kwargs = dict(p.split("=") for p in args.split(",")) except: # flake8: noqa raise ValueError("Invalid args") from None else: kwargs = {} if git_index is None: git_index = GitIndex() kwargs["index"] = git_index return __registry__[name](**kwargs)
[ "def", "create_backend", "(", "name", ":", "str", "=", "None", ",", "git_index", ":", "GitIndex", "=", "None", ",", "args", ":", "str", "=", "None", ")", "->", "StorageBackend", ":", "if", "name", "is", "None", ":", "name", "=", "config", ".", "BACKE...
Initialize a new StorageBackend by it's name and the specified model registry.
[ "Initialize", "a", "new", "StorageBackend", "by", "it", "s", "name", "and", "the", "specified", "model", "registry", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L21-L37
train
26,401
src-d/modelforge
modelforge/backends.py
create_backend_noexc
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: """Initialize a new Backend, return None if there was a known problem.""" try: return create_backend(name, git_index, args) except KeyError: log.critical("No such backend: %s (looked in %s)", name, list(__registry__.keys())) return None except ValueError: log.critical("Invalid backend arguments: %s", args) return None
python
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: """Initialize a new Backend, return None if there was a known problem.""" try: return create_backend(name, git_index, args) except KeyError: log.critical("No such backend: %s (looked in %s)", name, list(__registry__.keys())) return None except ValueError: log.critical("Invalid backend arguments: %s", args) return None
[ "def", "create_backend_noexc", "(", "log", ":", "logging", ".", "Logger", ",", "name", ":", "str", "=", "None", ",", "git_index", ":", "GitIndex", "=", "None", ",", "args", ":", "str", "=", "None", ")", "->", "Optional", "[", "StorageBackend", "]", ":"...
Initialize a new Backend, return None if there was a known problem.
[ "Initialize", "a", "new", "Backend", "return", "None", "if", "there", "was", "a", "known", "problem", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L40-L51
train
26,402
src-d/modelforge
modelforge/backends.py
supply_backend
def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True): """ Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicates whether we should \ construct the backend object if it does not exist in the wrapped function's \ `args`: `True` means we shouldn't. :param index_exists: Whether the Git model index exists on the remote side or not. """ real_optional = False if callable(optional) else optional def supply_backend_inner(func): @wraps(func) def wrapped_supply_backend(args): log = logging.getLogger(func.__name__) if real_optional and not getattr(args, "backend", False): backend = None else: try: git_index = GitIndex(remote=args.index_repo, username=args.username, password=args.password, cache=args.cache, exists=index_exists, signoff=args.signoff, log_level=args.log_level) except ValueError: return 1 backend = create_backend_noexc(log, args.backend, git_index, args.args) if backend is None: return 1 return func(args, backend, log) return wrapped_supply_backend if callable(optional): return supply_backend_inner(optional) return supply_backend_inner
python
def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True): """ Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicates whether we should \ construct the backend object if it does not exist in the wrapped function's \ `args`: `True` means we shouldn't. :param index_exists: Whether the Git model index exists on the remote side or not. """ real_optional = False if callable(optional) else optional def supply_backend_inner(func): @wraps(func) def wrapped_supply_backend(args): log = logging.getLogger(func.__name__) if real_optional and not getattr(args, "backend", False): backend = None else: try: git_index = GitIndex(remote=args.index_repo, username=args.username, password=args.password, cache=args.cache, exists=index_exists, signoff=args.signoff, log_level=args.log_level) except ValueError: return 1 backend = create_backend_noexc(log, args.backend, git_index, args.args) if backend is None: return 1 return func(args, backend, log) return wrapped_supply_backend if callable(optional): return supply_backend_inner(optional) return supply_backend_inner
[ "def", "supply_backend", "(", "optional", ":", "Union", "[", "callable", ",", "bool", "]", "=", "False", ",", "index_exists", ":", "bool", "=", "True", ")", ":", "real_optional", "=", "False", "if", "callable", "(", "optional", ")", "else", "optional", "...
Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicates whether we should \ construct the backend object if it does not exist in the wrapped function's \ `args`: `True` means we shouldn't. :param index_exists: Whether the Git model index exists on the remote side or not.
[ "Decorator", "to", "pass", "the", "initialized", "backend", "to", "the", "decorated", "callable", ".", "\\", "Used", "by", "command", "line", "entries", ".", "If", "the", "backend", "cannot", "be", "created", "return", "1", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L54-L87
train
26,403
src-d/modelforge
modelforge/meta.py
generate_new_meta
def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict: """ Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsible for support of the model. :param license: License identifier. :return: dict with the metadata. """ check_license(license) return { "code": None, "created_at": get_datetime_now(), "datasets": [], "dependencies": [], "description": description, "vendor": vendor, "environment": collect_environment_without_packages(), "extra": None, "license": license, "metrics": {}, "model": name, "parent": None, "references": [], "series": None, "tags": [], "uuid": str(uuid.uuid4()), "version": [1, 0, 0], }
python
def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict: """ Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsible for support of the model. :param license: License identifier. :return: dict with the metadata. """ check_license(license) return { "code": None, "created_at": get_datetime_now(), "datasets": [], "dependencies": [], "description": description, "vendor": vendor, "environment": collect_environment_without_packages(), "extra": None, "license": license, "metrics": {}, "model": name, "parent": None, "references": [], "series": None, "tags": [], "uuid": str(uuid.uuid4()), "version": [1, 0, 0], }
[ "def", "generate_new_meta", "(", "name", ":", "str", ",", "description", ":", "str", ",", "vendor", ":", "str", ",", "license", ":", "str", ")", "->", "dict", ":", "check_license", "(", "license", ")", "return", "{", "\"code\"", ":", "None", ",", "\"cr...
Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsible for support of the model. :param license: License identifier. :return: dict with the metadata.
[ "Create", "the", "metadata", "tree", "for", "the", "given", "model", "name", "and", "the", "list", "of", "dependencies", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L24-L53
train
26,404
src-d/modelforge
modelforge/meta.py
extract_model_meta
def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict: """ Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the user, similar to `template_meta.json`. :param model_url: public URL of the model. :return: converted dict. """ meta = {"default": {"default": base_meta["uuid"], "description": base_meta["description"], "code": extra_meta["code"]}} del base_meta["model"] del base_meta["uuid"] meta["model"] = base_meta meta["model"].update({k: extra_meta[k] for k in ("code", "datasets", "references", "tags", "extra")}) response = requests.get(model_url, stream=True) meta["model"]["size"] = humanize.naturalsize(int(response.headers["content-length"])) meta["model"]["url"] = model_url meta["model"]["created_at"] = format_datetime(meta["model"]["created_at"]) return meta
python
def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict: """ Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the user, similar to `template_meta.json`. :param model_url: public URL of the model. :return: converted dict. """ meta = {"default": {"default": base_meta["uuid"], "description": base_meta["description"], "code": extra_meta["code"]}} del base_meta["model"] del base_meta["uuid"] meta["model"] = base_meta meta["model"].update({k: extra_meta[k] for k in ("code", "datasets", "references", "tags", "extra")}) response = requests.get(model_url, stream=True) meta["model"]["size"] = humanize.naturalsize(int(response.headers["content-length"])) meta["model"]["url"] = model_url meta["model"]["created_at"] = format_datetime(meta["model"]["created_at"]) return meta
[ "def", "extract_model_meta", "(", "base_meta", ":", "dict", ",", "extra_meta", ":", "dict", ",", "model_url", ":", "str", ")", "->", "dict", ":", "meta", "=", "{", "\"default\"", ":", "{", "\"default\"", ":", "base_meta", "[", "\"uuid\"", "]", ",", "\"de...
Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the user, similar to `template_meta.json`. :param model_url: public URL of the model. :return: converted dict.
[ "Merge", "the", "metadata", "from", "the", "backend", "and", "the", "extra", "metadata", "into", "a", "dict", "which", "is", "suitable", "for", "\\", "index", ".", "json", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L73-L95
train
26,405
src-d/modelforge
modelforge/model.py
squeeze_bits
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray: """Return a copy of an integer numpy array with the minimum bitness.""" assert arr.dtype.kind in ("i", "u") if arr.dtype.kind == "i": assert arr.min() >= 0 mlbl = int(arr.max()).bit_length() if mlbl <= 8: dtype = numpy.uint8 elif mlbl <= 16: dtype = numpy.uint16 elif mlbl <= 32: dtype = numpy.uint32 else: dtype = numpy.uint64 return arr.astype(dtype)
python
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray: """Return a copy of an integer numpy array with the minimum bitness.""" assert arr.dtype.kind in ("i", "u") if arr.dtype.kind == "i": assert arr.min() >= 0 mlbl = int(arr.max()).bit_length() if mlbl <= 8: dtype = numpy.uint8 elif mlbl <= 16: dtype = numpy.uint16 elif mlbl <= 32: dtype = numpy.uint32 else: dtype = numpy.uint64 return arr.astype(dtype)
[ "def", "squeeze_bits", "(", "arr", ":", "numpy", ".", "ndarray", ")", "->", "numpy", ".", "ndarray", ":", "assert", "arr", ".", "dtype", ".", "kind", "in", "(", "\"i\"", ",", "\"u\"", ")", "if", "arr", ".", "dtype", ".", "kind", "==", "\"i\"", ":",...
Return a copy of an integer numpy array with the minimum bitness.
[ "Return", "a", "copy", "of", "an", "integer", "numpy", "array", "with", "the", "minimum", "bitness", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L572-L586
train
26,406
src-d/modelforge
modelforge/model.py
Model.metaprop
def metaprop(name: str, doc: str, readonly=False): """Temporary property builder.""" def get(self): return self.meta[name] get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "") if not readonly: def set(self, value): self.meta[name] = value set.__doc__ = "Set %s." % doc return property(get, set) return property(get)
python
def metaprop(name: str, doc: str, readonly=False): """Temporary property builder.""" def get(self): return self.meta[name] get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "") if not readonly: def set(self, value): self.meta[name] = value set.__doc__ = "Set %s." % doc return property(get, set) return property(get)
[ "def", "metaprop", "(", "name", ":", "str", ",", "doc", ":", "str", ",", "readonly", "=", "False", ")", ":", "def", "get", "(", "self", ")", ":", "return", "self", ".", "meta", "[", "name", "]", "get", ".", "__doc__", "=", "\"Get %s%s.\"", "%", "...
Temporary property builder.
[ "Temporary", "property", "builder", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L190-L202
train
26,407
src-d/modelforge
modelforge/model.py
Model.derive
def derive(self, new_version: Union[tuple, list]=None) -> "Model": """ Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self. """ meta = self.meta first_time = self._initial_version == self.version if new_version is None: new_version = meta["version"] new_version[-1] += 1 if not isinstance(new_version, (tuple, list)): raise ValueError("new_version must be either a list or a tuple, got %s" % type(new_version)) meta["version"] = list(new_version) if first_time: meta["parent"] = meta["uuid"] meta["uuid"] = str(uuid.uuid4()) return self
python
def derive(self, new_version: Union[tuple, list]=None) -> "Model": """ Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self. """ meta = self.meta first_time = self._initial_version == self.version if new_version is None: new_version = meta["version"] new_version[-1] += 1 if not isinstance(new_version, (tuple, list)): raise ValueError("new_version must be either a list or a tuple, got %s" % type(new_version)) meta["version"] = list(new_version) if first_time: meta["parent"] = meta["uuid"] meta["uuid"] = str(uuid.uuid4()) return self
[ "def", "derive", "(", "self", ",", "new_version", ":", "Union", "[", "tuple", ",", "list", "]", "=", "None", ")", "->", "\"Model\"", ":", "meta", "=", "self", ".", "meta", "first_time", "=", "self", ".", "_initial_version", "==", "self", ".", "version"...
Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self.
[ "Inherit", "the", "new", "model", "from", "the", "current", "one", "-", "used", "for", "versioning", ".", "\\", "This", "operation", "is", "in", "-", "place", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L237-L257
train
26,408
src-d/modelforge
modelforge/model.py
Model.cache_dir
def cache_dir() -> str: """Return the default cache directory where downloaded models are stored.""" if config.VENDOR is None: raise RuntimeError("modelforge is not configured; look at modelforge.configuration. " "Depending on your objective you may or may not want to create a " "modelforgecfg.py file which sets VENDOR and the rest.") return os.path.join("~", "." + config.VENDOR)
python
def cache_dir() -> str: """Return the default cache directory where downloaded models are stored.""" if config.VENDOR is None: raise RuntimeError("modelforge is not configured; look at modelforge.configuration. " "Depending on your objective you may or may not want to create a " "modelforgecfg.py file which sets VENDOR and the rest.") return os.path.join("~", "." + config.VENDOR)
[ "def", "cache_dir", "(", ")", "->", "str", ":", "if", "config", ".", "VENDOR", "is", "None", ":", "raise", "RuntimeError", "(", "\"modelforge is not configured; look at modelforge.configuration. \"", "\"Depending on your objective you may or may not want to create a \"", "\"mod...
Return the default cache directory where downloaded models are stored.
[ "Return", "the", "default", "cache", "directory", "where", "downloaded", "models", "are", "stored", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L335-L341
train
26,409
src-d/modelforge
modelforge/model.py
Model.get_dep
def get_dep(self, name: str) -> str: """ Return the uuid of the dependency identified with "name". :param name: :return: UUID """ deps = self.meta["dependencies"] for d in deps: if d["model"] == name: return d raise KeyError("%s not found in %s." % (name, deps))
python
def get_dep(self, name: str) -> str: """ Return the uuid of the dependency identified with "name". :param name: :return: UUID """ deps = self.meta["dependencies"] for d in deps: if d["model"] == name: return d raise KeyError("%s not found in %s." % (name, deps))
[ "def", "get_dep", "(", "self", ",", "name", ":", "str", ")", "->", "str", ":", "deps", "=", "self", ".", "meta", "[", "\"dependencies\"", "]", "for", "d", "in", "deps", ":", "if", "d", "[", "\"model\"", "]", "==", "name", ":", "return", "d", "rai...
Return the uuid of the dependency identified with "name". :param name: :return: UUID
[ "Return", "the", "uuid", "of", "the", "dependency", "identified", "with", "name", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L343-L354
train
26,410
src-d/modelforge
modelforge/model.py
Model.set_dep
def set_dep(self, *deps) -> "Model": """ Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self """ self.meta["dependencies"] = [ (d.meta if not isinstance(d, dict) else d) for d in deps] return self
python
def set_dep(self, *deps) -> "Model": """ Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self """ self.meta["dependencies"] = [ (d.meta if not isinstance(d, dict) else d) for d in deps] return self
[ "def", "set_dep", "(", "self", ",", "*", "deps", ")", "->", "\"Model\"", ":", "self", ".", "meta", "[", "\"dependencies\"", "]", "=", "[", "(", "d", ".", "meta", "if", "not", "isinstance", "(", "d", ",", "dict", ")", "else", "d", ")", "for", "d",...
Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self
[ "Register", "the", "dependencies", "for", "this", "model", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L356-L365
train
26,411
src-d/modelforge
modelforge/model.py
Model.save
def save(self, output: Union[str, BinaryIO], series: Optional[str] = None, deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model": """ Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it is None, it will be taken from \ the current value; if the current value is empty, an error is raised. :param deps: List of the dependencies. :param create_missing_dirs: create missing directories in output path if the output is a \ path. :return: self """ check_license(self.license) if series is None: if self.series is None: raise ValueError("series must be specified") else: self.series = series if isinstance(output, str) and create_missing_dirs: dirs = os.path.split(output)[0] if dirs: os.makedirs(dirs, exist_ok=True) self.set_dep(*deps) tree = self._generate_tree() self._write_tree(tree, output) self._initial_version = self.version return self
python
def save(self, output: Union[str, BinaryIO], series: Optional[str] = None, deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model": """ Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it is None, it will be taken from \ the current value; if the current value is empty, an error is raised. :param deps: List of the dependencies. :param create_missing_dirs: create missing directories in output path if the output is a \ path. :return: self """ check_license(self.license) if series is None: if self.series is None: raise ValueError("series must be specified") else: self.series = series if isinstance(output, str) and create_missing_dirs: dirs = os.path.split(output)[0] if dirs: os.makedirs(dirs, exist_ok=True) self.set_dep(*deps) tree = self._generate_tree() self._write_tree(tree, output) self._initial_version = self.version return self
[ "def", "save", "(", "self", ",", "output", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "series", ":", "Optional", "[", "str", "]", "=", "None", ",", "deps", ":", "Iterable", "=", "tuple", "(", ")", ",", "create_missing_dirs", ":", "bool", ...
Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it is None, it will be taken from \ the current value; if the current value is empty, an error is raised. :param deps: List of the dependencies. :param create_missing_dirs: create missing directories in output path if the output is a \ path. :return: self
[ "Serialize", "the", "model", "to", "a", "file", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L374-L401
train
26,412
src-d/modelforge
modelforge/model.py
Model._write_tree
def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None: """ Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. :return: None """ self.meta["created_at"] = get_datetime_now() meta = self.meta.copy() meta["environment"] = collect_environment() final_tree = {} final_tree.update(tree) final_tree["meta"] = meta isfileobj = not isinstance(output, str) if not isfileobj: self._source = output path = output output = open(output, "wb") os.chmod(path, file_mode) pos = 0 else: pos = output.tell() try: with asdf.AsdfFile(final_tree) as file: queue = [("", tree)] while queue: path, element = queue.pop() if isinstance(element, dict): for key, val in element.items(): queue.append((path + "/" + key, val)) elif isinstance(element, (list, tuple)): for child in element: queue.append((path, child)) elif isinstance(element, numpy.ndarray): path += "/" if path not in self._compression_prefixes: self._log.debug("%s -> %s compression", path, self.ARRAY_COMPRESSION) file.set_array_compression(element, self.ARRAY_COMPRESSION) else: self._log.debug("%s -> compression disabled", path) file.write_to(output) self._size = output.seek(0, os.SEEK_END) - pos finally: if not isfileobj: output.close()
python
def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None: """ Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. :return: None """ self.meta["created_at"] = get_datetime_now() meta = self.meta.copy() meta["environment"] = collect_environment() final_tree = {} final_tree.update(tree) final_tree["meta"] = meta isfileobj = not isinstance(output, str) if not isfileobj: self._source = output path = output output = open(output, "wb") os.chmod(path, file_mode) pos = 0 else: pos = output.tell() try: with asdf.AsdfFile(final_tree) as file: queue = [("", tree)] while queue: path, element = queue.pop() if isinstance(element, dict): for key, val in element.items(): queue.append((path + "/" + key, val)) elif isinstance(element, (list, tuple)): for child in element: queue.append((path, child)) elif isinstance(element, numpy.ndarray): path += "/" if path not in self._compression_prefixes: self._log.debug("%s -> %s compression", path, self.ARRAY_COMPRESSION) file.set_array_compression(element, self.ARRAY_COMPRESSION) else: self._log.debug("%s -> compression disabled", path) file.write_to(output) self._size = output.seek(0, os.SEEK_END) - pos finally: if not isfileobj: output.close()
[ "def", "_write_tree", "(", "self", ",", "tree", ":", "dict", ",", "output", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "file_mode", ":", "int", "=", "0o666", ")", "->", "None", ":", "self", ".", "meta", "[", "\"created_at\"", "]", "=", "g...
Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. :return: None
[ "Write", "the", "model", "to", "disk", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L403-L449
train
26,413
src-d/modelforge
modelforge/configuration.py
refresh
def refresh(): """Scan over all the involved directories and load configs from them.""" override_files = [] for stack in traceback.extract_stack(): f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE) if f not in override_files: override_files.insert(0, f) if OVERRIDE_FILE in override_files: del override_files[override_files.index(OVERRIDE_FILE)] override_files.append(OVERRIDE_FILE) def import_path(path): if sys.version_info < (3, 5, 0): from importlib.machinery import SourceFileLoader return SourceFileLoader(__name__, path).load_module() import importlib.util spec = importlib.util.spec_from_file_location(__name__, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module for override_file in override_files: if not os.path.isfile(override_file): continue mod = import_path(override_file) globals().update({n: getattr(mod, n) for n in dir(mod) if not n.startswith("__")})
python
def refresh(): """Scan over all the involved directories and load configs from them.""" override_files = [] for stack in traceback.extract_stack(): f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE) if f not in override_files: override_files.insert(0, f) if OVERRIDE_FILE in override_files: del override_files[override_files.index(OVERRIDE_FILE)] override_files.append(OVERRIDE_FILE) def import_path(path): if sys.version_info < (3, 5, 0): from importlib.machinery import SourceFileLoader return SourceFileLoader(__name__, path).load_module() import importlib.util spec = importlib.util.spec_from_file_location(__name__, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module for override_file in override_files: if not os.path.isfile(override_file): continue mod = import_path(override_file) globals().update({n: getattr(mod, n) for n in dir(mod) if not n.startswith("__")})
[ "def", "refresh", "(", ")", ":", "override_files", "=", "[", "]", "for", "stack", "in", "traceback", ".", "extract_stack", "(", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "stack", "[", "0", "]...
Scan over all the involved directories and load configs from them.
[ "Scan", "over", "all", "the", "involved", "directories", "and", "load", "configs", "from", "them", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/configuration.py#L17-L42
train
26,414
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.create_client
def create_client(self) -> "google.cloud.storage.Client": """ Construct GCS API client. """ # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google.cloud.storage import Client if self.credentials: client = Client.from_service_account_json(self.credentials) else: client = Client() return client
python
def create_client(self) -> "google.cloud.storage.Client": """ Construct GCS API client. """ # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google.cloud.storage import Client if self.credentials: client = Client.from_service_account_json(self.credentials) else: client = Client() return client
[ "def", "create_client", "(", "self", ")", "->", "\"google.cloud.storage.Client\"", ":", "# Client should be imported here because grpc starts threads during import", "# and if you call fork after that, a child process will be hang during exit", "from", "google", ".", "cloud", ".", "sto...
Construct GCS API client.
[ "Construct", "GCS", "API", "client", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L82-L93
train
26,415
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.connect
def connect(self) -> "google.cloud.storage.Bucket": """ Connect to the assigned bucket. """ log = self._log log.info("Connecting to the bucket...") client = self.create_client() return client.lookup_bucket(self.bucket_name)
python
def connect(self) -> "google.cloud.storage.Bucket": """ Connect to the assigned bucket. """ log = self._log log.info("Connecting to the bucket...") client = self.create_client() return client.lookup_bucket(self.bucket_name)
[ "def", "connect", "(", "self", ")", "->", "\"google.cloud.storage.Bucket\"", ":", "log", "=", "self", ".", "_log", "log", ".", "info", "(", "\"Connecting to the bucket...\"", ")", "client", "=", "self", ".", "create_client", "(", ")", "return", "client", ".", ...
Connect to the assigned bucket.
[ "Connect", "to", "the", "assigned", "bucket", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L95-L102
train
26,416
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.reset
def reset(self, force): """Connect to the assigned bucket or create if needed. Clear all the blobs inside.""" client = self.create_client() bucket = client.lookup_bucket(self.bucket_name) if bucket is not None: if not force: self._log.error("Bucket already exists, aborting.") raise ExistingBackendError self._log.info("Bucket already exists, deleting all content.") for blob in bucket.list_blobs(): self._log.info("Deleting %s ..." % blob.name) bucket.delete_blob(blob.name) else: client.create_bucket(self.bucket_name)
python
def reset(self, force): """Connect to the assigned bucket or create if needed. Clear all the blobs inside.""" client = self.create_client() bucket = client.lookup_bucket(self.bucket_name) if bucket is not None: if not force: self._log.error("Bucket already exists, aborting.") raise ExistingBackendError self._log.info("Bucket already exists, deleting all content.") for blob in bucket.list_blobs(): self._log.info("Deleting %s ..." % blob.name) bucket.delete_blob(blob.name) else: client.create_bucket(self.bucket_name)
[ "def", "reset", "(", "self", ",", "force", ")", ":", "client", "=", "self", ".", "create_client", "(", ")", "bucket", "=", "client", ".", "lookup_bucket", "(", "self", ".", "bucket_name", ")", "if", "bucket", "is", "not", "None", ":", "if", "not", "f...
Connect to the assigned bucket or create if needed. Clear all the blobs inside.
[ "Connect", "to", "the", "assigned", "bucket", "or", "create", "if", "needed", ".", "Clear", "all", "the", "blobs", "inside", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L104-L117
train
26,417
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.upload_model
def upload_model(self, path: str, meta: dict, force: bool): """Put the model to GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob = bucket.blob("models/%s/%s.asdf" % (meta["model"], meta["uuid"])) if blob.exists() and not force: self._log.error("Model %s already exists, aborted.", meta["uuid"]) raise ModelAlreadyExistsError self._log.info("Uploading %s from %s...", meta["model"], os.path.abspath(path)) def tracker(data): return self._Tracker(data, self._log) make_transport = blob._make_transport def make_transport_with_progress(client): transport = make_transport(client) request = transport.request def request_with_progress(method, url, data=None, headers=None, **kwargs): return request(method, url, data=tracker(data), headers=headers, **kwargs) transport.request = request_with_progress return transport blob._make_transport = make_transport_with_progress with open(path, "rb") as fin: blob.upload_from_file(fin, content_type="application/x-yaml") blob.make_public() return blob.public_url
python
def upload_model(self, path: str, meta: dict, force: bool): """Put the model to GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob = bucket.blob("models/%s/%s.asdf" % (meta["model"], meta["uuid"])) if blob.exists() and not force: self._log.error("Model %s already exists, aborted.", meta["uuid"]) raise ModelAlreadyExistsError self._log.info("Uploading %s from %s...", meta["model"], os.path.abspath(path)) def tracker(data): return self._Tracker(data, self._log) make_transport = blob._make_transport def make_transport_with_progress(client): transport = make_transport(client) request = transport.request def request_with_progress(method, url, data=None, headers=None, **kwargs): return request(method, url, data=tracker(data), headers=headers, **kwargs) transport.request = request_with_progress return transport blob._make_transport = make_transport_with_progress with open(path, "rb") as fin: blob.upload_from_file(fin, content_type="application/x-yaml") blob.make_public() return blob.public_url
[ "def", "upload_model", "(", "self", ",", "path", ":", "str", ",", "meta", ":", "dict", ",", "force", ":", "bool", ")", ":", "bucket", "=", "self", ".", "connect", "(", ")", "if", "bucket", "is", "None", ":", "raise", "BackendRequiredError", "blob", "...
Put the model to GCS.
[ "Put", "the", "model", "to", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L119-L150
train
26,418
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.fetch_model
def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(source, file, self._log, chunk_size)
python
def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(source, file, self._log, chunk_size)
[ "def", "fetch_model", "(", "self", ",", "source", ":", "str", ",", "file", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "chunk_size", ":", "int", "=", "DEFAULT_DOWNLOAD_CHUNK_SIZE", ")", "->", "None", ":", "download_http", "(", "source", ",", "fi...
Download the model from GCS.
[ "Download", "the", "model", "from", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L152-L155
train
26,419
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.delete_model
def delete_model(self, meta: dict): """Delete the model from GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"]) self._log.info(blob_name) try: self._log.info("Deleting model ...") bucket.delete_blob(blob_name) except NotFound: self._log.warning("Model %s already deleted.", meta["uuid"])
python
def delete_model(self, meta: dict): """Delete the model from GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"]) self._log.info(blob_name) try: self._log.info("Deleting model ...") bucket.delete_blob(blob_name) except NotFound: self._log.warning("Model %s already deleted.", meta["uuid"])
[ "def", "delete_model", "(", "self", ",", "meta", ":", "dict", ")", ":", "bucket", "=", "self", ".", "connect", "(", ")", "if", "bucket", "is", "None", ":", "raise", "BackendRequiredError", "blob_name", "=", "\"models/%s/%s.asdf\"", "%", "(", "meta", "[", ...
Delete the model from GCS.
[ "Delete", "the", "model", "from", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L157-L168
train
26,420
src-d/modelforge
modelforge/storage_backend.py
download_http
def download_http(source: str, file: Union[str, BinaryIO], log: logging.Logger, chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """ Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :param chunk_size: Size of download buffer. """ log.info("Fetching %s...", source) r = requests.get(source, stream=True) if r.status_code != 200: log.error( "An error occurred while fetching the model, with code %s" % r.status_code) raise ValueError if isinstance(file, str): os.makedirs(os.path.dirname(file), exist_ok=True) f = open(file, "wb") else: f = file try: total_length = int(r.headers.get("content-length")) num_chunks = math.ceil(total_length / chunk_size) if num_chunks == 1: f.write(r.content) else: for chunk in progress_bar( r.iter_content(chunk_size=chunk_size), log, expected_size=num_chunks): if chunk: f.write(chunk) finally: if isinstance(file, str): f.close()
python
def download_http(source: str, file: Union[str, BinaryIO], log: logging.Logger, chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """ Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :param chunk_size: Size of download buffer. """ log.info("Fetching %s...", source) r = requests.get(source, stream=True) if r.status_code != 200: log.error( "An error occurred while fetching the model, with code %s" % r.status_code) raise ValueError if isinstance(file, str): os.makedirs(os.path.dirname(file), exist_ok=True) f = open(file, "wb") else: f = file try: total_length = int(r.headers.get("content-length")) num_chunks = math.ceil(total_length / chunk_size) if num_chunks == 1: f.write(r.content) else: for chunk in progress_bar( r.iter_content(chunk_size=chunk_size), log, expected_size=num_chunks): if chunk: f.write(chunk) finally: if isinstance(file, str): f.close()
[ "def", "download_http", "(", "source", ":", "str", ",", "file", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "log", ":", "logging", ".", "Logger", ",", "chunk_size", ":", "int", "=", "DEFAULT_DOWNLOAD_CHUNK_SIZE", ")", "->", "None", ":", "log", ...
Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :param chunk_size: Size of download buffer.
[ "Download", "a", "file", "from", "an", "HTTP", "source", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/storage_backend.py#L111-L146
train
26,421
src-d/modelforge
modelforge/storage_backend.py
StorageBackend.upload_model
def upload_model(self, path: str, meta: dict, force: bool) -> str: """ Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. :raises BackendRequiredError: If supplied bucket is unusable. :raises ModelAlreadyExistsError: If model already exists and no forcing. """ raise NotImplementedError
python
def upload_model(self, path: str, meta: dict, force: bool) -> str: """ Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. :raises BackendRequiredError: If supplied bucket is unusable. :raises ModelAlreadyExistsError: If model already exists and no forcing. """ raise NotImplementedError
[ "def", "upload_model", "(", "self", ",", "path", ":", "str", ",", "meta", ":", "dict", ",", "force", ":", "bool", ")", "->", "str", ":", "raise", "NotImplementedError" ]
Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. :raises BackendRequiredError: If supplied bucket is unusable. :raises ModelAlreadyExistsError: If model already exists and no forcing.
[ "Put", "the", "given", "file", "to", "the", "remote", "storage", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/storage_backend.py#L48-L59
train
26,422
src-d/modelforge
modelforge/slogging.py
setup
def setup(level: Union[str, int], structured: bool, config_path: str = None): """ Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. :param structured: Output JSON logs to stdout. :param config_path: Path to a yaml file that configures the level of output of the loggers. \ Root logger level is set through the level argument and will override any \ root configuration found in the conf file. :return: None """ global logs_are_structured logs_are_structured = structured if not isinstance(level, int): level = logging._nameToLevel[level] def ensure_utf8_stream(stream): if not isinstance(stream, io.StringIO) and hasattr(stream, "buffer"): stream = codecs.getwriter("utf-8")(stream.buffer) stream.encoding = "utf-8" return stream sys.stdout, sys.stderr = (ensure_utf8_stream(s) for s in (sys.stdout, sys.stderr)) # basicConfig is only called to make sure there is at least one handler for the root logger. # All the output level setting is down right afterwards. logging.basicConfig() logging.setLogRecordFactory(NumpyLogRecord) if config_path is not None and os.path.isfile(config_path): with open(config_path) as fh: config = yaml.safe_load(fh) for key, val in config.items(): logging.getLogger(key).setLevel(logging._nameToLevel.get(val, level)) root = logging.getLogger() root.setLevel(level) if not structured: if not sys.stdin.closed and sys.stdout.isatty(): handler = root.handlers[0] handler.setFormatter(AwesomeFormatter()) else: root.handlers[0] = StructuredHandler(level)
python
def setup(level: Union[str, int], structured: bool, config_path: str = None): """ Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. :param structured: Output JSON logs to stdout. :param config_path: Path to a yaml file that configures the level of output of the loggers. \ Root logger level is set through the level argument and will override any \ root configuration found in the conf file. :return: None """ global logs_are_structured logs_are_structured = structured if not isinstance(level, int): level = logging._nameToLevel[level] def ensure_utf8_stream(stream): if not isinstance(stream, io.StringIO) and hasattr(stream, "buffer"): stream = codecs.getwriter("utf-8")(stream.buffer) stream.encoding = "utf-8" return stream sys.stdout, sys.stderr = (ensure_utf8_stream(s) for s in (sys.stdout, sys.stderr)) # basicConfig is only called to make sure there is at least one handler for the root logger. # All the output level setting is down right afterwards. logging.basicConfig() logging.setLogRecordFactory(NumpyLogRecord) if config_path is not None and os.path.isfile(config_path): with open(config_path) as fh: config = yaml.safe_load(fh) for key, val in config.items(): logging.getLogger(key).setLevel(logging._nameToLevel.get(val, level)) root = logging.getLogger() root.setLevel(level) if not structured: if not sys.stdin.closed and sys.stdout.isatty(): handler = root.handlers[0] handler.setFormatter(AwesomeFormatter()) else: root.handlers[0] = StructuredHandler(level)
[ "def", "setup", "(", "level", ":", "Union", "[", "str", ",", "int", "]", ",", "structured", ":", "bool", ",", "config_path", ":", "str", "=", "None", ")", ":", "global", "logs_are_structured", "logs_are_structured", "=", "structured", "if", "not", "isinsta...
Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. :param structured: Output JSON logs to stdout. :param config_path: Path to a yaml file that configures the level of output of the loggers. \ Root logger level is set through the level argument and will override any \ root configuration found in the conf file. :return: None
[ "Make", "stdout", "and", "stderr", "unicode", "friendly", "in", "case", "of", "misconfigured", "\\", "environments", "initializes", "the", "logging", "structured", "logging", "and", "\\", "enables", "colored", "logs", "if", "it", "is", "appropriate", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L164-L209
train
26,423
src-d/modelforge
modelforge/slogging.py
set_context
def set_context(context): """Assign the logging context - an abstract object - to the current thread.""" try: handler = logging.getLogger().handlers[0] except IndexError: # logging is not initialized return if not isinstance(handler, StructuredHandler): return handler.acquire() try: handler.local.context = context finally: handler.release()
python
def set_context(context): """Assign the logging context - an abstract object - to the current thread.""" try: handler = logging.getLogger().handlers[0] except IndexError: # logging is not initialized return if not isinstance(handler, StructuredHandler): return handler.acquire() try: handler.local.context = context finally: handler.release()
[ "def", "set_context", "(", "context", ")", ":", "try", ":", "handler", "=", "logging", ".", "getLogger", "(", ")", ".", "handlers", "[", "0", "]", "except", "IndexError", ":", "# logging is not initialized", "return", "if", "not", "isinstance", "(", "handler...
Assign the logging context - an abstract object - to the current thread.
[ "Assign", "the", "logging", "context", "-", "an", "abstract", "object", "-", "to", "the", "current", "thread", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L212-L225
train
26,424
src-d/modelforge
modelforge/slogging.py
add_logging_args
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: """ Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from parsed args. :param patch: Patch parse_args() to automatically setup logging. """ parser.add_argument("--log-level", default="INFO", choices=logging._nameToLevel, help="Logging verbosity.") parser.add_argument("--log-structured", action="store_true", help="Enable structured logging (JSON record per line).") parser.add_argument("--log-config", help="Path to the file which sets individual log levels of domains.") # monkey-patch parse_args() # custom actions do not work, unfortunately, because they are not invoked if # the corresponding --flags are not specified def _patched_parse_args(args=None, namespace=None) -> argparse.Namespace: args = parser._original_parse_args(args, namespace) setup(args.log_level, args.log_structured, args.log_config) if erase_args: for log_arg in ("log_level", "log_structured", "log_config"): delattr(args, log_arg) return args if patch and not hasattr(parser, "_original_parse_args"): parser._original_parse_args = parser.parse_args parser.parse_args = _patched_parse_args
python
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: """ Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from parsed args. :param patch: Patch parse_args() to automatically setup logging. """ parser.add_argument("--log-level", default="INFO", choices=logging._nameToLevel, help="Logging verbosity.") parser.add_argument("--log-structured", action="store_true", help="Enable structured logging (JSON record per line).") parser.add_argument("--log-config", help="Path to the file which sets individual log levels of domains.") # monkey-patch parse_args() # custom actions do not work, unfortunately, because they are not invoked if # the corresponding --flags are not specified def _patched_parse_args(args=None, namespace=None) -> argparse.Namespace: args = parser._original_parse_args(args, namespace) setup(args.log_level, args.log_structured, args.log_config) if erase_args: for log_arg in ("log_level", "log_structured", "log_config"): delattr(args, log_arg) return args if patch and not hasattr(parser, "_original_parse_args"): parser._original_parse_args = parser.parse_args parser.parse_args = _patched_parse_args
[ "def", "add_logging_args", "(", "parser", ":", "argparse", ".", "ArgumentParser", ",", "patch", ":", "bool", "=", "True", ",", "erase_args", ":", "bool", "=", "True", ")", "->", "None", ":", "parser", ".", "add_argument", "(", "\"--log-level\"", ",", "defa...
Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from parsed args. :param patch: Patch parse_args() to automatically setup logging.
[ "Add", "command", "line", "flags", "specific", "to", "logging", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L228-L257
train
26,425
src-d/modelforge
modelforge/slogging.py
NumpyLogRecord.array2string
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
python
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
[ "def", "array2string", "(", "arr", ":", "numpy", ".", "ndarray", ")", "->", "str", ":", "shape", "=", "str", "(", "arr", ".", "shape", ")", "[", "1", ":", "-", "1", "]", "if", "shape", ".", "endswith", "(", "\",\"", ")", ":", "shape", "=", "sha...
Format numpy array as a string.
[ "Format", "numpy", "array", "as", "a", "string", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L64-L69
train
26,426
src-d/modelforge
modelforge/slogging.py
NumpyLogRecord.getMessage
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message. """ if isinstance(self.msg, numpy.ndarray): msg = self.array2string(self.msg) else: msg = str(self.msg) if self.args: a2s = self.array2string if isinstance(self.args, Dict): args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v) for (k, v) in self.args.items()} elif isinstance(self.args, Sequence): args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a) for a in self.args) else: raise TypeError("Unexpected input '%s' with type '%s'" % (self.args, type(self.args))) msg = msg % args return msg
python
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message. """ if isinstance(self.msg, numpy.ndarray): msg = self.array2string(self.msg) else: msg = str(self.msg) if self.args: a2s = self.array2string if isinstance(self.args, Dict): args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v) for (k, v) in self.args.items()} elif isinstance(self.args, Sequence): args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a) for a in self.args) else: raise TypeError("Unexpected input '%s' with type '%s'" % (self.args, type(self.args))) msg = msg % args return msg
[ "def", "getMessage", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "msg", ",", "numpy", ".", "ndarray", ")", ":", "msg", "=", "self", ".", "array2string", "(", "self", ".", "msg", ")", "else", ":", "msg", "=", "str", "(", "self", "...
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message.
[ "Return", "the", "message", "for", "this", "LogRecord", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L71-L94
train
26,427
src-d/modelforge
modelforge/slogging.py
AwesomeFormatter.formatMessage
def formatMessage(self, record: logging.LogRecord) -> str: """Convert the already filled log record to a string.""" level_color = "0" text_color = "0" fmt = "" if record.levelno <= logging.DEBUG: fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m" elif record.levelno <= logging.INFO: level_color = "1;36" lmsg = record.message.lower() if self.GREEN_RE.search(lmsg): text_color = "1;32" elif record.levelno <= logging.WARNING: level_color = "1;33" elif record.levelno <= logging.CRITICAL: level_color = "1;31" if not fmt: fmt = "\033[" + level_color + \ "m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033[" + text_color + \ "m%(message)s\033[0m" fmt = _fest + fmt record.rthread = reduce_thread_id(record.thread) return fmt % record.__dict__
python
def formatMessage(self, record: logging.LogRecord) -> str: """Convert the already filled log record to a string.""" level_color = "0" text_color = "0" fmt = "" if record.levelno <= logging.DEBUG: fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m" elif record.levelno <= logging.INFO: level_color = "1;36" lmsg = record.message.lower() if self.GREEN_RE.search(lmsg): text_color = "1;32" elif record.levelno <= logging.WARNING: level_color = "1;33" elif record.levelno <= logging.CRITICAL: level_color = "1;31" if not fmt: fmt = "\033[" + level_color + \ "m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033[" + text_color + \ "m%(message)s\033[0m" fmt = _fest + fmt record.rthread = reduce_thread_id(record.thread) return fmt % record.__dict__
[ "def", "formatMessage", "(", "self", ",", "record", ":", "logging", ".", "LogRecord", ")", "->", "str", ":", "level_color", "=", "\"0\"", "text_color", "=", "\"0\"", "fmt", "=", "\"\"", "if", "record", ".", "levelno", "<=", "logging", ".", "DEBUG", ":", ...
Convert the already filled log record to a string.
[ "Convert", "the", "already", "filled", "log", "record", "to", "a", "string", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L106-L128
train
26,428
src-d/modelforge
modelforge/slogging.py
StructuredHandler.emit
def emit(self, record: logging.LogRecord): """Print the log record formatted as JSON to stdout.""" created = datetime.datetime.fromtimestamp(record.created, timezone) obj = { "level": record.levelname.lower(), "msg": record.msg % record.args, "source": "%s:%d" % (record.filename, record.lineno), "time": format_datetime(created), "thread": reduce_thread_id(record.thread), } if record.exc_info is not None: obj["error"] = traceback.format_exception(*record.exc_info)[1:] try: obj["context"] = self.local.context except AttributeError: pass json.dump(obj, sys.stdout, sort_keys=True) sys.stdout.write("\n") sys.stdout.flush()
python
def emit(self, record: logging.LogRecord): """Print the log record formatted as JSON to stdout.""" created = datetime.datetime.fromtimestamp(record.created, timezone) obj = { "level": record.levelname.lower(), "msg": record.msg % record.args, "source": "%s:%d" % (record.filename, record.lineno), "time": format_datetime(created), "thread": reduce_thread_id(record.thread), } if record.exc_info is not None: obj["error"] = traceback.format_exception(*record.exc_info)[1:] try: obj["context"] = self.local.context except AttributeError: pass json.dump(obj, sys.stdout, sort_keys=True) sys.stdout.write("\n") sys.stdout.flush()
[ "def", "emit", "(", "self", ",", "record", ":", "logging", ".", "LogRecord", ")", ":", "created", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ",", "timezone", ")", "obj", "=", "{", "\"level\"", ":", "record", ...
Print the log record formatted as JSON to stdout.
[ "Print", "the", "log", "record", "formatted", "as", "JSON", "to", "stdout", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L139-L157
train
26,429
src-d/modelforge
modelforge/models.py
register_model
def register_model(cls: Type[Model]): """ Include the given model class into the registry. :param cls: The class of the registered model. :return: None """ if not issubclass(cls, Model): raise TypeError("model bust be a subclass of Model") if issubclass(cls, GenericModel): raise TypeError("model must not be a subclass of GenericModel") __models__.add(cls) return cls
python
def register_model(cls: Type[Model]): """ Include the given model class into the registry. :param cls: The class of the registered model. :return: None """ if not issubclass(cls, Model): raise TypeError("model bust be a subclass of Model") if issubclass(cls, GenericModel): raise TypeError("model must not be a subclass of GenericModel") __models__.add(cls) return cls
[ "def", "register_model", "(", "cls", ":", "Type", "[", "Model", "]", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Model", ")", ":", "raise", "TypeError", "(", "\"model bust be a subclass of Model\"", ")", "if", "issubclass", "(", "cls", ",", "Gen...
Include the given model class into the registry. :param cls: The class of the registered model. :return: None
[ "Include", "the", "given", "model", "class", "into", "the", "registry", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/models.py#L10-L22
train
26,430
src-d/modelforge
modelforge/index.py
GitIndex.fetch
def fetch(self): """Load from the associated Git repository.""" os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True) if not os.path.exists(self.cached_repo): self._log.warning("Index not found, caching %s in %s", self.repo, self.cached_repo) git.clone(self.remote_url, self.cached_repo, checkout=True) else: self._log.debug("Index is cached") if self._are_local_and_remote_heads_different(): self._log.info("Cached index is not up to date, pulling %s", self. repo) git.pull(self.cached_repo, self.remote_url) with open(os.path.join(self.cached_repo, self.INDEX_FILE), encoding="utf-8") as _in: self.contents = json.load(_in)
python
def fetch(self): """Load from the associated Git repository.""" os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True) if not os.path.exists(self.cached_repo): self._log.warning("Index not found, caching %s in %s", self.repo, self.cached_repo) git.clone(self.remote_url, self.cached_repo, checkout=True) else: self._log.debug("Index is cached") if self._are_local_and_remote_heads_different(): self._log.info("Cached index is not up to date, pulling %s", self. repo) git.pull(self.cached_repo, self.remote_url) with open(os.path.join(self.cached_repo, self.INDEX_FILE), encoding="utf-8") as _in: self.contents = json.load(_in)
[ "def", "fetch", "(", "self", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "cached_repo", ")", ",", "exist_ok", "=", "True", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "cache...
Load from the associated Git repository.
[ "Load", "from", "the", "associated", "Git", "repository", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L102-L114
train
26,431
src-d/modelforge
modelforge/index.py
GitIndex.update_readme
def update_readme(self, template_readme: Template): """Generate the new README file locally.""" readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_type, model_uuids in self.models.items(): for model_uuid in model_uuids: links[model_type][model_uuid] = os.path.join("/", model_type, "%s.md" % model_uuid) with open(readme, "w") as fout: fout.write(template_readme.render(models=self.models, meta=self.meta, links=links)) git.add(self.cached_repo, [readme]) self._log.info("Updated %s", readme)
python
def update_readme(self, template_readme: Template): """Generate the new README file locally.""" readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_type, model_uuids in self.models.items(): for model_uuid in model_uuids: links[model_type][model_uuid] = os.path.join("/", model_type, "%s.md" % model_uuid) with open(readme, "w") as fout: fout.write(template_readme.render(models=self.models, meta=self.meta, links=links)) git.add(self.cached_repo, [readme]) self._log.info("Updated %s", readme)
[ "def", "update_readme", "(", "self", ",", "template_readme", ":", "Template", ")", ":", "readme", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cached_repo", ",", "\"README.md\"", ")", "if", "os", ".", "path", ".", "exists", "(", "readme", ")...
Generate the new README file locally.
[ "Generate", "the", "new", "README", "file", "locally", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L166-L178
train
26,432
src-d/modelforge
modelforge/index.py
GitIndex.reset
def reset(self): """Initialize the remote Git repository.""" paths = [] for filename in os.listdir(self.cached_repo): if filename.startswith(".git"): continue path = os.path.join(self.cached_repo, filename) if os.path.isfile(path): paths.append(path) elif os.path.isdir(path): for model in os.listdir(path): paths.append(os.path.join(path, model)) git.remove(self.cached_repo, paths) self.contents = {"models": {}, "meta": {}}
python
def reset(self): """Initialize the remote Git repository.""" paths = [] for filename in os.listdir(self.cached_repo): if filename.startswith(".git"): continue path = os.path.join(self.cached_repo, filename) if os.path.isfile(path): paths.append(path) elif os.path.isdir(path): for model in os.listdir(path): paths.append(os.path.join(path, model)) git.remove(self.cached_repo, paths) self.contents = {"models": {}, "meta": {}}
[ "def", "reset", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "cached_repo", ")", ":", "if", "filename", ".", "startswith", "(", "\".git\"", ")", ":", "continue", "path", "=", "os", ...
Initialize the remote Git repository.
[ "Initialize", "the", "remote", "Git", "repository", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L180-L193
train
26,433
src-d/modelforge
modelforge/index.py
GitIndex.upload
def upload(self, cmd: str, meta: dict): """Push the current state of the registry to Git.""" index = os.path.join(self.cached_repo, self.INDEX_FILE) if os.path.exists(index): os.remove(index) self._log.info("Writing the new index.json ...") with open(index, "w") as _out: json.dump(self.contents, _out) git.add(self.cached_repo, [index]) message = self.COMMIT_MESSAGES[cmd].format(**meta) if self.signoff: global_conf_path = os.path.expanduser("~/.gitconfig") if os.path.exists(global_conf_path): with open(global_conf_path, "br") as _in: conf = ConfigFile.from_file(_in) try: name = conf.get(b"user", b"name").decode() email = conf.get(b"user", b"email").decode() message += self.DCO_MESSAGE.format(name=name, email=email) except KeyError: self._log.warning( "Did not find name or email in %s, committing without DCO.", global_conf_path) else: self._log.warning("Global git configuration file %s does not exist, " "committing without DCO.", global_conf_path) else: self._log.info("Committing the index without DCO.") git.commit(self.cached_repo, message=message) self._log.info("Pushing the updated index ...") # TODO: change when https://github.com/dulwich/dulwich/issues/631 gets addressed git.push(self.cached_repo, self.remote_url, b"master") if self._are_local_and_remote_heads_different(): self._log.error("Push has failed") raise ValueError("Push has failed")
python
def upload(self, cmd: str, meta: dict): """Push the current state of the registry to Git.""" index = os.path.join(self.cached_repo, self.INDEX_FILE) if os.path.exists(index): os.remove(index) self._log.info("Writing the new index.json ...") with open(index, "w") as _out: json.dump(self.contents, _out) git.add(self.cached_repo, [index]) message = self.COMMIT_MESSAGES[cmd].format(**meta) if self.signoff: global_conf_path = os.path.expanduser("~/.gitconfig") if os.path.exists(global_conf_path): with open(global_conf_path, "br") as _in: conf = ConfigFile.from_file(_in) try: name = conf.get(b"user", b"name").decode() email = conf.get(b"user", b"email").decode() message += self.DCO_MESSAGE.format(name=name, email=email) except KeyError: self._log.warning( "Did not find name or email in %s, committing without DCO.", global_conf_path) else: self._log.warning("Global git configuration file %s does not exist, " "committing without DCO.", global_conf_path) else: self._log.info("Committing the index without DCO.") git.commit(self.cached_repo, message=message) self._log.info("Pushing the updated index ...") # TODO: change when https://github.com/dulwich/dulwich/issues/631 gets addressed git.push(self.cached_repo, self.remote_url, b"master") if self._are_local_and_remote_heads_different(): self._log.error("Push has failed") raise ValueError("Push has failed")
[ "def", "upload", "(", "self", ",", "cmd", ":", "str", ",", "meta", ":", "dict", ")", ":", "index", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cached_repo", ",", "self", ".", "INDEX_FILE", ")", "if", "os", ".", "path", ".", "exists", ...
Push the current state of the registry to Git.
[ "Push", "the", "current", "state", "of", "the", "registry", "to", "Git", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L195-L229
train
26,434
src-d/modelforge
modelforge/index.py
GitIndex.load_template
def load_template(self, template: str) -> Template: """Load a Jinja2 template from the source directory.""" env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False) jinja2_ext = ".jinja2" if not template.endswith(jinja2_ext): self._log.error("Template file name must end with %s" % jinja2_ext) raise ValueError if not template[:-len(jinja2_ext)].endswith(".md"): self._log.error("Template file should be a Markdown file.") raise ValueError if not os.path.isabs(template): template = os.path.join(os.path.dirname(__file__), template) with open(template, encoding="utf-8") as fin: template_obj = Template(fin.read(), **env) template_obj.filename = template self._log.info("Loaded %s", template) return template_obj
python
def load_template(self, template: str) -> Template: """Load a Jinja2 template from the source directory.""" env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False) jinja2_ext = ".jinja2" if not template.endswith(jinja2_ext): self._log.error("Template file name must end with %s" % jinja2_ext) raise ValueError if not template[:-len(jinja2_ext)].endswith(".md"): self._log.error("Template file should be a Markdown file.") raise ValueError if not os.path.isabs(template): template = os.path.join(os.path.dirname(__file__), template) with open(template, encoding="utf-8") as fin: template_obj = Template(fin.read(), **env) template_obj.filename = template self._log.info("Loaded %s", template) return template_obj
[ "def", "load_template", "(", "self", ",", "template", ":", "str", ")", "->", "Template", ":", "env", "=", "dict", "(", "trim_blocks", "=", "True", ",", "lstrip_blocks", "=", "True", ",", "keep_trailing_newline", "=", "False", ")", "jinja2_ext", "=", "\".ji...
Load a Jinja2 template from the source directory.
[ "Load", "a", "Jinja2", "template", "from", "the", "source", "directory", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L231-L247
train
26,435
src-d/modelforge
modelforge/progress_bar.py
progress_bar
def progress_bar(enumerable, logger, **kwargs): """ Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to clint.textui.progress.bar. :return: The wrapped iterator. """ if not logger.isEnabledFor(logging.INFO) or sys.stdin.closed or not sys.stdin.isatty(): return enumerable return progress.bar(enumerable, **kwargs)
python
def progress_bar(enumerable, logger, **kwargs): """ Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to clint.textui.progress.bar. :return: The wrapped iterator. """ if not logger.isEnabledFor(logging.INFO) or sys.stdin.closed or not sys.stdin.isatty(): return enumerable return progress.bar(enumerable, **kwargs)
[ "def", "progress_bar", "(", "enumerable", ",", "logger", ",", "*", "*", "kwargs", ")", ":", "if", "not", "logger", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", "or", "sys", ".", "stdin", ".", "closed", "or", "not", "sys", ".", "stdin", ".",...
Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to clint.textui.progress.bar. :return: The wrapped iterator.
[ "Show", "the", "progress", "bar", "in", "the", "terminal", "if", "the", "logging", "level", "matches", "and", "we", "are", "interactive", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/progress_bar.py#L7-L18
train
26,436
src-d/modelforge
modelforge/environment.py
collect_environment
def collect_environment(no_cache: bool = False) -> dict: """ Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True. """ global _env if _env is None or no_cache: _env = collect_environment_without_packages() _env["packages"] = collect_loaded_packages() return _env
python
def collect_environment(no_cache: bool = False) -> dict: """ Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True. """ global _env if _env is None or no_cache: _env = collect_environment_without_packages() _env["packages"] = collect_loaded_packages() return _env
[ "def", "collect_environment", "(", "no_cache", ":", "bool", "=", "False", ")", "->", "dict", ":", "global", "_env", "if", "_env", "is", "None", "or", "no_cache", ":", "_env", "=", "collect_environment_without_packages", "(", ")", "_env", "[", "\"packages\"", ...
Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True.
[ "Return", "the", "version", "of", "the", "Python", "executable", "the", "versions", "of", "the", "currently", "loaded", "packages", "\\", "and", "the", "running", "platform", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/environment.py#L28-L39
train
26,437
src-d/modelforge
modelforge/environment.py
collect_loaded_packages
def collect_loaded_packages() -> List[Tuple[str, str]]: """ Return the currently loaded package names and their versions. """ dists = get_installed_distributions() get_dist_files = DistFilesFinder() file_table = {} for dist in dists: for file in get_dist_files(dist): file_table[file] = dist used_dists = set() # we greedily load all values to a list to avoid weird # "dictionary changed size during iteration" errors for module in list(sys.modules.values()): try: dist = file_table[module.__file__] except (AttributeError, KeyError): continue used_dists.add(dist) return sorted((dist.project_name, dist.version) for dist in used_dists)
python
def collect_loaded_packages() -> List[Tuple[str, str]]: """ Return the currently loaded package names and their versions. """ dists = get_installed_distributions() get_dist_files = DistFilesFinder() file_table = {} for dist in dists: for file in get_dist_files(dist): file_table[file] = dist used_dists = set() # we greedily load all values to a list to avoid weird # "dictionary changed size during iteration" errors for module in list(sys.modules.values()): try: dist = file_table[module.__file__] except (AttributeError, KeyError): continue used_dists.add(dist) return sorted((dist.project_name, dist.version) for dist in used_dists)
[ "def", "collect_loaded_packages", "(", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "dists", "=", "get_installed_distributions", "(", ")", "get_dist_files", "=", "DistFilesFinder", "(", ")", "file_table", "=", "{", "}", "for", "d...
Return the currently loaded package names and their versions.
[ "Return", "the", "currently", "loaded", "package", "names", "and", "their", "versions", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/environment.py#L42-L61
train
26,438
criteo/gourde
gourde/gourde.py
Gourde.setup_blueprint
def setup_blueprint(self): """Initialize the blueprint.""" # Register endpoints. self.blueprint.add_url_rule("/", "status", self.status) self.blueprint.add_url_rule("/healthy", "health", self.healthy) self.blueprint.add_url_rule("/ready", "ready", self.ready) self.blueprint.add_url_rule("/threads", "threads", self.threads_bt)
python
def setup_blueprint(self): """Initialize the blueprint.""" # Register endpoints. self.blueprint.add_url_rule("/", "status", self.status) self.blueprint.add_url_rule("/healthy", "health", self.healthy) self.blueprint.add_url_rule("/ready", "ready", self.ready) self.blueprint.add_url_rule("/threads", "threads", self.threads_bt)
[ "def", "setup_blueprint", "(", "self", ")", ":", "# Register endpoints.", "self", ".", "blueprint", ".", "add_url_rule", "(", "\"/\"", ",", "\"status\"", ",", "self", ".", "status", ")", "self", ".", "blueprint", ".", "add_url_rule", "(", "\"/healthy\"", ",", ...
Initialize the blueprint.
[ "Initialize", "the", "blueprint", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L69-L76
train
26,439
criteo/gourde
gourde/gourde.py
Gourde._add_routes
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
python
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
[ "def", "_add_routes", "(", "self", ")", ":", "if", "self", ".", "app", ".", "has_static_folder", ":", "self", ".", "add_url_rule", "(", "\"/favicon.ico\"", ",", "\"favicon\"", ",", "self", ".", "favicon", ")", "self", ".", "add_url_rule", "(", "\"/\"", ","...
Add some nice default routes.
[ "Add", "some", "nice", "default", "routes", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L78-L82
train
26,440
criteo/gourde
gourde/gourde.py
Gourde.get_argparser
def get_argparser(parser=None): """Customize a parser to get the correct options.""" parser = parser or argparse.ArgumentParser() parser.add_argument("--host", default="0.0.0.0", help="Host listen address") parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int) parser.add_argument( "--debug", "-d", default=False, action="store_true", help="Enable debug mode", ) parser.add_argument( "--log-level", "-l", default="INFO", help="Log Level, empty string to disable.", ) parser.add_argument( "--twisted", default=False, action="store_true", help="Use twisted to server requests.", ) parser.add_argument( "--gunicorn", default=False, action="store_true", help="Use gunicorn to server requests.", ) parser.add_argument( "--threads", default=None, help="Number of threads to use.", type=int ) parser.add_argument("--disable-embedded-logging", default=False, action="store_true", help="Disable embedded logging configuration") return parser
python
def get_argparser(parser=None): """Customize a parser to get the correct options.""" parser = parser or argparse.ArgumentParser() parser.add_argument("--host", default="0.0.0.0", help="Host listen address") parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int) parser.add_argument( "--debug", "-d", default=False, action="store_true", help="Enable debug mode", ) parser.add_argument( "--log-level", "-l", default="INFO", help="Log Level, empty string to disable.", ) parser.add_argument( "--twisted", default=False, action="store_true", help="Use twisted to server requests.", ) parser.add_argument( "--gunicorn", default=False, action="store_true", help="Use gunicorn to server requests.", ) parser.add_argument( "--threads", default=None, help="Number of threads to use.", type=int ) parser.add_argument("--disable-embedded-logging", default=False, action="store_true", help="Disable embedded logging configuration") return parser
[ "def", "get_argparser", "(", "parser", "=", "None", ")", ":", "parser", "=", "parser", "or", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--host\"", ",", "default", "=", "\"0.0.0.0\"", ",", "help", "=", "\"Host listen a...
Customize a parser to get the correct options.
[ "Customize", "a", "parser", "to", "get", "the", "correct", "options", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L115-L152
train
26,441
criteo/gourde
gourde/gourde.py
Gourde.setup_prometheus
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg_resources.DistributionNotFound: version = "unknown" self.metrics.info( "app_info", "Application info", version=version, appname=self.app.name ) self.app.logger.info("Prometheus is enabled.")
python
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg_resources.DistributionNotFound: version = "unknown" self.metrics.info( "app_info", "Application info", version=version, appname=self.app.name ) self.app.logger.info("Prometheus is enabled.")
[ "def", "setup_prometheus", "(", "self", ",", "registry", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "registry", ":", "kwargs", "[", "\"registry\"", "]", "=", "registry", "self", ".", "metrics", "=", "PrometheusMetrics", "(", "self", ".", "app"...
Setup Prometheus.
[ "Setup", "Prometheus", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L169-L182
train
26,442
criteo/gourde
gourde/gourde.py
Gourde.add_url_rule
def add_url_rule(self, route, endpoint, handler): """Add a new url route. Args: See flask.Flask.add_url_route(). """ self.app.add_url_rule(route, endpoint, handler)
python
def add_url_rule(self, route, endpoint, handler): """Add a new url route. Args: See flask.Flask.add_url_route(). """ self.app.add_url_rule(route, endpoint, handler)
[ "def", "add_url_rule", "(", "self", ",", "route", ",", "endpoint", ",", "handler", ")", ":", "self", ".", "app", ".", "add_url_rule", "(", "route", ",", "endpoint", ",", "handler", ")" ]
Add a new url route. Args: See flask.Flask.add_url_route().
[ "Add", "a", "new", "url", "route", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L193-L199
train
26,443
criteo/gourde
gourde/gourde.py
Gourde.healthy
def healthy(self): """Return 200 is healthy, else 500. Override is_healthy() to change the health check. """ try: if self.is_healthy(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception(e) return str(e), 500
python
def healthy(self): """Return 200 is healthy, else 500. Override is_healthy() to change the health check. """ try: if self.is_healthy(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception(e) return str(e), 500
[ "def", "healthy", "(", "self", ")", ":", "try", ":", "if", "self", ".", "is_healthy", "(", ")", ":", "return", "\"OK\"", ",", "200", "else", ":", "return", "\"FAIL\"", ",", "500", "except", "Exception", "as", "e", ":", "self", ".", "app", ".", "log...
Return 200 is healthy, else 500. Override is_healthy() to change the health check.
[ "Return", "200", "is", "healthy", "else", "500", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L216-L230
train
26,444
criteo/gourde
gourde/gourde.py
Gourde.ready
def ready(self): """Return 200 is ready, else 500. Override is_ready() to change the readiness check. """ try: if self.is_ready(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception() return str(e), 500
python
def ready(self): """Return 200 is ready, else 500. Override is_ready() to change the readiness check. """ try: if self.is_ready(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception() return str(e), 500
[ "def", "ready", "(", "self", ")", ":", "try", ":", "if", "self", ".", "is_ready", "(", ")", ":", "return", "\"OK\"", ",", "200", "else", ":", "return", "\"FAIL\"", ",", "500", "except", "Exception", "as", "e", ":", "self", ".", "app", ".", "logger"...
Return 200 is ready, else 500. Override is_ready() to change the readiness check.
[ "Return", "200", "is", "ready", "else", "500", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L235-L249
train
26,445
criteo/gourde
gourde/gourde.py
Gourde.threads_bt
def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) else: stack = [] threads[thread] = "".join(stack) return flask.render_template("gourde/threads.html", threads=threads)
python
def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) else: stack = [] threads[thread] = "".join(stack) return flask.render_template("gourde/threads.html", threads=threads)
[ "def", "threads_bt", "(", "self", ")", ":", "import", "threading", "import", "traceback", "threads", "=", "{", "}", "for", "thread", "in", "threading", ".", "enumerate", "(", ")", ":", "frames", "=", "sys", ".", "_current_frames", "(", ")", ".", "get", ...
Display thread backtraces.
[ "Display", "thread", "backtraces", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L251-L264
train
26,446
criteo/gourde
gourde/gourde.py
Gourde.run_with_werkzeug
def run_with_werkzeug(self, **options): """Run with werkzeug simple wsgi container.""" threaded = self.threads is not None and (self.threads > 0) self.app.run( host=self.host, port=self.port, debug=self.debug, threaded=threaded, **options )
python
def run_with_werkzeug(self, **options): """Run with werkzeug simple wsgi container.""" threaded = self.threads is not None and (self.threads > 0) self.app.run( host=self.host, port=self.port, debug=self.debug, threaded=threaded, **options )
[ "def", "run_with_werkzeug", "(", "self", ",", "*", "*", "options", ")", ":", "threaded", "=", "self", ".", "threads", "is", "not", "None", "and", "(", "self", ".", "threads", ">", "0", ")", "self", ".", "app", ".", "run", "(", "host", "=", "self", ...
Run with werkzeug simple wsgi container.
[ "Run", "with", "werkzeug", "simple", "wsgi", "container", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L283-L292
train
26,447
criteo/gourde
gourde/gourde.py
Gourde.run_with_twisted
def run_with_twisted(self, **options): """Run with twisted.""" from twisted.internet import reactor from twisted.python import log import flask_twisted twisted = flask_twisted.Twisted(self.app) if self.threads: reactor.suggestThreadPoolSize(self.threads) if self.log_level: log.startLogging(sys.stderr) twisted.run(host=self.host, port=self.port, debug=self.debug, **options)
python
def run_with_twisted(self, **options): """Run with twisted.""" from twisted.internet import reactor from twisted.python import log import flask_twisted twisted = flask_twisted.Twisted(self.app) if self.threads: reactor.suggestThreadPoolSize(self.threads) if self.log_level: log.startLogging(sys.stderr) twisted.run(host=self.host, port=self.port, debug=self.debug, **options)
[ "def", "run_with_twisted", "(", "self", ",", "*", "*", "options", ")", ":", "from", "twisted", ".", "internet", "import", "reactor", "from", "twisted", ".", "python", "import", "log", "import", "flask_twisted", "twisted", "=", "flask_twisted", ".", "Twisted", ...
Run with twisted.
[ "Run", "with", "twisted", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L294-L305
train
26,448
criteo/gourde
gourde/gourde.py
Gourde.run_with_gunicorn
def run_with_gunicorn(self, **options): """Run with gunicorn.""" import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(GourdeApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '%s:%s' % (self.host, self.port), 'workers': self.threads or ((multiprocessing.cpu_count() * 2) + 1), 'debug': self.debug, **options, } GourdeApplication(self.app, options).run()
python
def run_with_gunicorn(self, **options): """Run with gunicorn.""" import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(GourdeApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '%s:%s' % (self.host, self.port), 'workers': self.threads or ((multiprocessing.cpu_count() * 2) + 1), 'debug': self.debug, **options, } GourdeApplication(self.app, options).run()
[ "def", "run_with_gunicorn", "(", "self", ",", "*", "*", "options", ")", ":", "import", "gunicorn", ".", "app", ".", "base", "from", "gunicorn", ".", "six", "import", "iteritems", "import", "multiprocessing", "class", "GourdeApplication", "(", "gunicorn", ".", ...
Run with gunicorn.
[ "Run", "with", "gunicorn", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L307-L335
train
26,449
criteo/gourde
example/app.py
initialize_api
def initialize_api(flask_app): """Initialize an API.""" if not flask_restplus: return api = flask_restplus.Api(version="1.0", title="My Example API") api.add_resource(HelloWorld, "/hello") blueprint = flask.Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) flask_app.register_blueprint(blueprint)
python
def initialize_api(flask_app): """Initialize an API.""" if not flask_restplus: return api = flask_restplus.Api(version="1.0", title="My Example API") api.add_resource(HelloWorld, "/hello") blueprint = flask.Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) flask_app.register_blueprint(blueprint)
[ "def", "initialize_api", "(", "flask_app", ")", ":", "if", "not", "flask_restplus", ":", "return", "api", "=", "flask_restplus", ".", "Api", "(", "version", "=", "\"1.0\"", ",", "title", "=", "\"My Example API\"", ")", "api", ".", "add_resource", "(", "Hello...
Initialize an API.
[ "Initialize", "an", "API", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/example/app.py#L69-L79
train
26,450
criteo/gourde
example/app.py
initialize_app
def initialize_app(flask_app, args): """Initialize the App.""" # Setup gourde with the args. gourde.setup(args) # Register a custom health check. gourde.is_healthy = is_healthy # Add an optional API initialize_api(flask_app)
python
def initialize_app(flask_app, args): """Initialize the App.""" # Setup gourde with the args. gourde.setup(args) # Register a custom health check. gourde.is_healthy = is_healthy # Add an optional API initialize_api(flask_app)
[ "def", "initialize_app", "(", "flask_app", ",", "args", ")", ":", "# Setup gourde with the args.", "gourde", ".", "setup", "(", "args", ")", "# Register a custom health check.", "gourde", ".", "is_healthy", "=", "is_healthy", "# Add an optional API", "initialize_api", "...
Initialize the App.
[ "Initialize", "the", "App", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/example/app.py#L82-L91
train
26,451
closeio/quotequail
quotequail/__init__.py
quote
def quote(text, limit=1000): """ Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some quoted text')] Unless the limit param is set to None, the text will automatically be quoted starting at the line where the limit is reached. """ lines = text.split('\n') found = _internal.find_quote_position(lines, _patterns.MAX_WRAP_LINES, limit) if found != None: return [(True, '\n'.join(lines[:found+1])), (False, '\n'.join(lines[found+1:]))] return [(True, text)]
python
def quote(text, limit=1000): """ Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some quoted text')] Unless the limit param is set to None, the text will automatically be quoted starting at the line where the limit is reached. """ lines = text.split('\n') found = _internal.find_quote_position(lines, _patterns.MAX_WRAP_LINES, limit) if found != None: return [(True, '\n'.join(lines[:found+1])), (False, '\n'.join(lines[found+1:]))] return [(True, text)]
[ "def", "quote", "(", "text", ",", "limit", "=", "1000", ")", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "found", "=", "_internal", ".", "find_quote_position", "(", "lines", ",", "_patterns", ".", "MAX_WRAP_LINES", ",", "limit", ")", "i...
Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some quoted text')] Unless the limit param is set to None, the text will automatically be quoted starting at the line where the limit is reached.
[ "Takes", "a", "plain", "text", "message", "as", "an", "argument", "returns", "a", "list", "of", "tuples", ".", "The", "first", "argument", "of", "the", "tuple", "denotes", "whether", "the", "text", "should", "be", "expanded", "by", "default", ".", "The", ...
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/__init__.py#L12-L31
train
26,452
closeio/quotequail
quotequail/_internal.py
extract_headers
def extract_headers(lines, max_wrap_lines): """ Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed. """ hdrs = {} header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 lines_processed = 0 for n, line in enumerate(lines): if not line.strip(): header_name = None continue match = HEADER_RE.match(line) if match: header_name, header_value = match.groups() header_name = header_name.strip().lower() extend_lines = 0 if header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = header_value.strip() lines_processed = n+1 else: extend_lines += 1 if extend_lines < max_wrap_lines and header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = join_wrapped_lines( [hdrs[HEADER_MAP[header_name]], line.strip()]) lines_processed = n+1 else: # no more headers found break return hdrs, lines_processed
python
def extract_headers(lines, max_wrap_lines): """ Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed. """ hdrs = {} header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 lines_processed = 0 for n, line in enumerate(lines): if not line.strip(): header_name = None continue match = HEADER_RE.match(line) if match: header_name, header_value = match.groups() header_name = header_name.strip().lower() extend_lines = 0 if header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = header_value.strip() lines_processed = n+1 else: extend_lines += 1 if extend_lines < max_wrap_lines and header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = join_wrapped_lines( [hdrs[HEADER_MAP[header_name]], line.strip()]) lines_processed = n+1 else: # no more headers found break return hdrs, lines_processed
[ "def", "extract_headers", "(", "lines", ",", "max_wrap_lines", ")", ":", "hdrs", "=", "{", "}", "header_name", "=", "None", "# Track overlong headers that extend over multiple lines", "extend_lines", "=", "0", "lines_processed", "=", "0", "for", "n", ",", "line", ...
Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed.
[ "Extracts", "email", "headers", "from", "the", "given", "lines", ".", "Returns", "a", "dict", "with", "the", "detected", "headers", "and", "the", "amount", "of", "lines", "that", "were", "processed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_internal.py#L63-L100
train
26,453
closeio/quotequail
quotequail/_html.py
trim_tree_after
def trim_tree_after(element, include_element=True): """ Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): el.tail = None if el != element or include_element: el = el.getnext() while el is not None: remove_el = el el = el.getnext() parent_el.remove(remove_el) el = parent_el
python
def trim_tree_after(element, include_element=True): """ Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): el.tail = None if el != element or include_element: el = el.getnext() while el is not None: remove_el = el el = el.getnext() parent_el.remove(remove_el) el = parent_el
[ "def", "trim_tree_after", "(", "element", ",", "include_element", "=", "True", ")", ":", "el", "=", "element", "for", "parent_el", "in", "element", ".", "iterancestors", "(", ")", ":", "el", ".", "tail", "=", "None", "if", "el", "!=", "element", "or", ...
Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed.
[ "Removes", "the", "document", "tree", "following", "the", "given", "element", ".", "If", "include_element", "is", "True", "the", "given", "element", "is", "kept", "in", "the", "tree", "otherwise", "it", "is", "removed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_html.py#L19-L33
train
26,454
closeio/quotequail
quotequail/_html.py
trim_tree_before
def trim_tree_before(element, include_element=True, keep_head=True): """ Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): parent_el.text = None if el != element or include_element: el = el.getprevious() else: parent_el.text = el.tail while el is not None: remove_el = el el = el.getprevious() tag = remove_el.tag is_head = isinstance(tag, string_class) and tag.lower() == 'head' if not keep_head or not is_head: parent_el.remove(remove_el) el = parent_el
python
def trim_tree_before(element, include_element=True, keep_head=True): """ Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): parent_el.text = None if el != element or include_element: el = el.getprevious() else: parent_el.text = el.tail while el is not None: remove_el = el el = el.getprevious() tag = remove_el.tag is_head = isinstance(tag, string_class) and tag.lower() == 'head' if not keep_head or not is_head: parent_el.remove(remove_el) el = parent_el
[ "def", "trim_tree_before", "(", "element", ",", "include_element", "=", "True", ",", "keep_head", "=", "True", ")", ":", "el", "=", "element", "for", "parent_el", "in", "element", ".", "iterancestors", "(", ")", ":", "parent_el", ".", "text", "=", "None", ...
Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed.
[ "Removes", "the", "document", "tree", "preceding", "the", "given", "element", ".", "If", "include_element", "is", "True", "the", "given", "element", "is", "kept", "in", "the", "tree", "otherwise", "it", "is", "removed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_html.py#L35-L54
train
26,455
cmollet/sridentify
sridentify/__init__.py
Sridentify.get_epsg
def get_epsg(self): """ Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, https://developers.arcgis.com/javascript/jshelp/pcs.html If it cannot be found there, it next tries the prj2epsg.org API. If an exact match is found, that EPSG code is returned and saved to the database to avoid future external API calls. TODO: If that API cannot find an exact match but several partial matches, those partials will be displayed to the user with the option to select one to save to the database. """ cur = self.conn.cursor() cur.execute("SELECT epsg_code FROM prj_epsg WHERE prjtext = ?", (self.prj,)) # prjtext has a unique constraint on it, we should only ever fetchone() result = cur.fetchone() if not result and self.call_remote_api: return self.call_api() elif result is not None: self.epsg_code = result[0] return self.epsg_code
python
def get_epsg(self): """ Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, https://developers.arcgis.com/javascript/jshelp/pcs.html If it cannot be found there, it next tries the prj2epsg.org API. If an exact match is found, that EPSG code is returned and saved to the database to avoid future external API calls. TODO: If that API cannot find an exact match but several partial matches, those partials will be displayed to the user with the option to select one to save to the database. """ cur = self.conn.cursor() cur.execute("SELECT epsg_code FROM prj_epsg WHERE prjtext = ?", (self.prj,)) # prjtext has a unique constraint on it, we should only ever fetchone() result = cur.fetchone() if not result and self.call_remote_api: return self.call_api() elif result is not None: self.epsg_code = result[0] return self.epsg_code
[ "def", "get_epsg", "(", "self", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"SELECT epsg_code FROM prj_epsg WHERE prjtext = ?\"", ",", "(", "self", ".", "prj", ",", ")", ")", "# prjtext has a unique constra...
Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, https://developers.arcgis.com/javascript/jshelp/pcs.html If it cannot be found there, it next tries the prj2epsg.org API. If an exact match is found, that EPSG code is returned and saved to the database to avoid future external API calls. TODO: If that API cannot find an exact match but several partial matches, those partials will be displayed to the user with the option to select one to save to the database.
[ "Attempts", "to", "determine", "the", "EPSG", "code", "for", "a", "given", "PRJ", "file", "or", "other", "similar", "text", "-", "based", "spatial", "reference", "file", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L92-L118
train
26,456
cmollet/sridentify
sridentify/__init__.py
Sridentify.from_epsg
def from_epsg(self, epsg_code): """ Loads self.prj by epsg_code. If prjtext not found returns False. """ self.epsg_code = epsg_code assert isinstance(self.epsg_code, int) cur = self.conn.cursor() cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ?", (self.epsg_code,)) result = cur.fetchone() if result is not None: self.prj = result[0] return True return False
python
def from_epsg(self, epsg_code): """ Loads self.prj by epsg_code. If prjtext not found returns False. """ self.epsg_code = epsg_code assert isinstance(self.epsg_code, int) cur = self.conn.cursor() cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ?", (self.epsg_code,)) result = cur.fetchone() if result is not None: self.prj = result[0] return True return False
[ "def", "from_epsg", "(", "self", ",", "epsg_code", ")", ":", "self", ".", "epsg_code", "=", "epsg_code", "assert", "isinstance", "(", "self", ".", "epsg_code", ",", "int", ")", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "ex...
Loads self.prj by epsg_code. If prjtext not found returns False.
[ "Loads", "self", ".", "prj", "by", "epsg_code", ".", "If", "prjtext", "not", "found", "returns", "False", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L172-L186
train
26,457
cmollet/sridentify
sridentify/__init__.py
Sridentify.to_prj
def to_prj(self, filename): """ Saves prj WKT to given file. """ with open(filename, "w") as fp: fp.write(self.prj)
python
def to_prj(self, filename): """ Saves prj WKT to given file. """ with open(filename, "w") as fp: fp.write(self.prj)
[ "def", "to_prj", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "self", ".", "prj", ")" ]
Saves prj WKT to given file.
[ "Saves", "prj", "WKT", "to", "given", "file", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L189-L194
train
26,458
globality-corp/microcosm-postgres
microcosm_postgres/health.py
get_current_head_version
def get_current_head_version(graph): """ Returns the current head version. """ script_dir = ScriptDirectory("/", version_locations=[graph.metadata.get_path("migrations")]) return script_dir.get_current_head()
python
def get_current_head_version(graph): """ Returns the current head version. """ script_dir = ScriptDirectory("/", version_locations=[graph.metadata.get_path("migrations")]) return script_dir.get_current_head()
[ "def", "get_current_head_version", "(", "graph", ")", ":", "script_dir", "=", "ScriptDirectory", "(", "\"/\"", ",", "version_locations", "=", "[", "graph", ".", "metadata", ".", "get_path", "(", "\"migrations\"", ")", "]", ")", "return", "script_dir", ".", "ge...
Returns the current head version.
[ "Returns", "the", "current", "head", "version", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/health.py#L30-L36
train
26,459
globality-corp/microcosm-postgres
microcosm_postgres/temporary/factories.py
create_temporary_table
def create_temporary_table(from_table, name=None, on_commit=None): """ Create a new temporary table from another table. """ from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the metadata with the new name. temporary_table = copy_table(from_table, name) # change create clause to: CREATE TEMPORARY TABLE temporary_table._prefixes = list(from_table._prefixes) temporary_table._prefixes.append("TEMPORARY") # change post create clause to: ON COMMIT DROP if on_commit: temporary_table.dialect_options["postgresql"].update( on_commit=on_commit, ) temporary_table.insert_many = MethodType(insert_many, temporary_table) temporary_table.select_from = MethodType(select_from, temporary_table) temporary_table.upsert_into = MethodType(upsert_into, temporary_table) return temporary_table
python
def create_temporary_table(from_table, name=None, on_commit=None): """ Create a new temporary table from another table. """ from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the metadata with the new name. temporary_table = copy_table(from_table, name) # change create clause to: CREATE TEMPORARY TABLE temporary_table._prefixes = list(from_table._prefixes) temporary_table._prefixes.append("TEMPORARY") # change post create clause to: ON COMMIT DROP if on_commit: temporary_table.dialect_options["postgresql"].update( on_commit=on_commit, ) temporary_table.insert_many = MethodType(insert_many, temporary_table) temporary_table.select_from = MethodType(select_from, temporary_table) temporary_table.upsert_into = MethodType(upsert_into, temporary_table) return temporary_table
[ "def", "create_temporary_table", "(", "from_table", ",", "name", "=", "None", ",", "on_commit", "=", "None", ")", ":", "from_table", "=", "from_table", ".", "__table__", "if", "hasattr", "(", "from_table", ",", "\"__table__\"", ")", "else", "from_table", "name...
Create a new temporary table from another table.
[ "Create", "a", "new", "temporary", "table", "from", "another", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/factories.py#L11-L37
train
26,460
globality-corp/microcosm-postgres
microcosm_postgres/operations.py
get_current_head
def get_current_head(graph): """ Get the current database head revision, if any. """ session = new_session(graph) try: result = session.execute("SELECT version_num FROM alembic_version") except ProgrammingError: return None else: return result.scalar() finally: session.close()
python
def get_current_head(graph): """ Get the current database head revision, if any. """ session = new_session(graph) try: result = session.execute("SELECT version_num FROM alembic_version") except ProgrammingError: return None else: return result.scalar() finally: session.close()
[ "def", "get_current_head", "(", "graph", ")", ":", "session", "=", "new_session", "(", "graph", ")", "try", ":", "result", "=", "session", ".", "execute", "(", "\"SELECT version_num FROM alembic_version\"", ")", "except", "ProgrammingError", ":", "return", "None",...
Get the current database head revision, if any.
[ "Get", "the", "current", "database", "head", "revision", "if", "any", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/operations.py#L19-L32
train
26,461
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.flushing
def flushing(self): """ Flush the current session, handling common errors. """ try: yield self.session.flush() except (FlushError, IntegrityError) as error: error_message = str(error) # There ought to be a cleaner way to capture this condition if "duplicate" in error_message: raise DuplicateModelError(error) if "already exists" in error_message: raise DuplicateModelError(error) if "conflicts with" in error_message and "identity key" in error_message: raise DuplicateModelError(error) elif "still referenced" in error_message: raise ReferencedModelError(error) elif "is not present" in error_message: raise MissingDependencyError(error) else: raise ModelIntegrityError(error)
python
def flushing(self): """ Flush the current session, handling common errors. """ try: yield self.session.flush() except (FlushError, IntegrityError) as error: error_message = str(error) # There ought to be a cleaner way to capture this condition if "duplicate" in error_message: raise DuplicateModelError(error) if "already exists" in error_message: raise DuplicateModelError(error) if "conflicts with" in error_message and "identity key" in error_message: raise DuplicateModelError(error) elif "still referenced" in error_message: raise ReferencedModelError(error) elif "is not present" in error_message: raise MissingDependencyError(error) else: raise ModelIntegrityError(error)
[ "def", "flushing", "(", "self", ")", ":", "try", ":", "yield", "self", ".", "session", ".", "flush", "(", ")", "except", "(", "FlushError", ",", "IntegrityError", ")", "as", "error", ":", "error_message", "=", "str", "(", "error", ")", "# There ought to ...
Flush the current session, handling common errors.
[ "Flush", "the", "current", "session", "handling", "common", "errors", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L64-L86
train
26,462
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.create
def create(self, instance): """ Create a new model instance. """ with self.flushing(): if instance.id is None: instance.id = self.new_object_id() self.session.add(instance) return instance
python
def create(self, instance): """ Create a new model instance. """ with self.flushing(): if instance.id is None: instance.id = self.new_object_id() self.session.add(instance) return instance
[ "def", "create", "(", "self", ",", "instance", ")", ":", "with", "self", ".", "flushing", "(", ")", ":", "if", "instance", ".", "id", "is", "None", ":", "instance", ".", "id", "=", "self", ".", "new_object_id", "(", ")", "self", ".", "session", "."...
Create a new model instance.
[ "Create", "a", "new", "model", "instance", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L88-L97
train
26,463
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.retrieve
def retrieve(self, identifier, *criterion): """ Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model """ return self._retrieve( self.model_class.id == identifier, *criterion )
python
def retrieve(self, identifier, *criterion): """ Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model """ return self._retrieve( self.model_class.id == identifier, *criterion )
[ "def", "retrieve", "(", "self", ",", "identifier", ",", "*", "criterion", ")", ":", "return", "self", ".", "_retrieve", "(", "self", ".", "model_class", ".", "id", "==", "identifier", ",", "*", "criterion", ")" ]
Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model
[ "Retrieve", "a", "model", "by", "primary", "key", "and", "zero", "or", "more", "other", "criteria", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L99-L109
train
26,464
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.count
def count(self, *criterion, **kwargs): """ Count the number of models matching some criterion. """ query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
python
def count(self, *criterion, **kwargs): """ Count the number of models matching some criterion. """ query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
[ "def", "count", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_filter", "(", "query", ",", "*", "*", "kwargs", ")", "return", "q...
Count the number of models matching some criterion.
[ "Count", "the", "number", "of", "models", "matching", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L160-L167
train
26,465
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.search
def search(self, *criterion, **kwargs): """ Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.all()
python
def search(self, *criterion, **kwargs): """ Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.all()
[ "def", "search", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_order_by", "(", "query", ",", "*", "*", "kwargs", ")", "query", ...
Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any
[ "Return", "the", "list", "of", "models", "matching", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L169-L182
train
26,466
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.search_first
def search_first(self, *criterion, **kwargs): """ Returns the first match based on criteria or None. """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.first()
python
def search_first(self, *criterion, **kwargs): """ Returns the first match based on criteria or None. """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.first()
[ "def", "search_first", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_order_by", "(", "query", ",", "*", "*", "kwargs", ")", "quer...
Returns the first match based on criteria or None.
[ "Returns", "the", "first", "match", "based", "on", "criteria", "or", "None", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L184-L194
train
26,467
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._filter
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
python
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
[ "def", "_filter", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_auto_filter", "(", "query", ",", "*", "*", "kwargs", ")", "return", "query" ]
Filter a query with user-supplied arguments.
[ "Filter", "a", "query", "with", "user", "-", "supplied", "arguments", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L211-L217
train
26,468
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._retrieve
def _retrieve(self, *criterion): """ Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted. """ try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( "{} not found".format( self.model_class.__name__, ), error, )
python
def _retrieve(self, *criterion): """ Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted. """ try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( "{} not found".format( self.model_class.__name__, ), error, )
[ "def", "_retrieve", "(", "self", ",", "*", "criterion", ")", ":", "try", ":", "return", "self", ".", "_query", "(", "*", "criterion", ")", ".", "one", "(", ")", "except", "NoResultFound", "as", "error", ":", "raise", "ModelNotFoundError", "(", "\"{} not ...
Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted.
[ "Retrieve", "a", "model", "by", "some", "criteria", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L239-L254
train
26,469
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._delete
def _delete(self, *criterion): """ Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted. """ with self.flushing(): count = self._query(*criterion).delete() if count == 0: raise ModelNotFoundError return True
python
def _delete(self, *criterion): """ Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted. """ with self.flushing(): count = self._query(*criterion).delete() if count == 0: raise ModelNotFoundError return True
[ "def", "_delete", "(", "self", ",", "*", "criterion", ")", ":", "with", "self", ".", "flushing", "(", ")", ":", "count", "=", "self", ".", "_query", "(", "*", "criterion", ")", ".", "delete", "(", ")", "if", "count", "==", "0", ":", "raise", "Mod...
Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted.
[ "Delete", "a", "model", "by", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L256-L269
train
26,470
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._query
def _query(self, *criterion): """ Construct a query for the model. """ return self.session.query( self.model_class ).filter( *criterion )
python
def _query(self, *criterion): """ Construct a query for the model. """ return self.session.query( self.model_class ).filter( *criterion )
[ "def", "_query", "(", "self", ",", "*", "criterion", ")", ":", "return", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter", "(", "*", "criterion", ")" ]
Construct a query for the model.
[ "Construct", "a", "query", "for", "the", "model", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L271-L280
train
26,471
globality-corp/microcosm-postgres
microcosm_postgres/context.py
maybe_transactional
def maybe_transactional(func): """ Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations. """ @wraps(func) def wrapper(*args, **kwargs): commit = kwargs.get("commit", True) with transaction(commit=commit): return func(*args, **kwargs) return wrapper
python
def maybe_transactional(func): """ Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations. """ @wraps(func) def wrapper(*args, **kwargs): commit = kwargs.get("commit", True) with transaction(commit=commit): return func(*args, **kwargs) return wrapper
[ "def", "maybe_transactional", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "commit", "=", "kwargs", ".", "get", "(", "\"commit\"", ",", "True", ")", "with", "transaction...
Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations.
[ "Variant", "of", "transactional", "that", "will", "not", "commit", "if", "there", "s", "an", "argument", "commit", "with", "a", "falsey", "value", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/context.py#L83-L95
train
26,472
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
make_alembic_config
def make_alembic_config(temporary_dir, migrations_dir): """ Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration directory), hard-coding the decision that there will be such a directory makes Alembic setup overly verbose. Instead, generate a `Config` object with the values we care about. :returns: a usable instance of `Alembic.config.Config` """ config = Config() config.set_main_option("temporary_dir", temporary_dir) config.set_main_option("migrations_dir", migrations_dir) return config
python
def make_alembic_config(temporary_dir, migrations_dir): """ Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration directory), hard-coding the decision that there will be such a directory makes Alembic setup overly verbose. Instead, generate a `Config` object with the values we care about. :returns: a usable instance of `Alembic.config.Config` """ config = Config() config.set_main_option("temporary_dir", temporary_dir) config.set_main_option("migrations_dir", migrations_dir) return config
[ "def", "make_alembic_config", "(", "temporary_dir", ",", "migrations_dir", ")", ":", "config", "=", "Config", "(", ")", "config", ".", "set_main_option", "(", "\"temporary_dir\"", ",", "temporary_dir", ")", "config", ".", "set_main_option", "(", "\"migrations_dir\""...
Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration directory), hard-coding the decision that there will be such a directory makes Alembic setup overly verbose. Instead, generate a `Config` object with the values we care about. :returns: a usable instance of `Alembic.config.Config`
[ "Alembic", "uses", "the", "alembic", ".", "ini", "file", "to", "configure", "where", "it", "looks", "for", "everything", "else", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L51-L67
train
26,473
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
make_script_directory
def make_script_directory(cls, config): """ Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree, and revision templates shouldn't vary between projects. Instead, generate a `ScriptDirectory` object, injecting values from the config. """ temporary_dir = config.get_main_option("temporary_dir") migrations_dir = config.get_main_option("migrations_dir") return cls( dir=temporary_dir, version_locations=[migrations_dir], )
python
def make_script_directory(cls, config): """ Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree, and revision templates shouldn't vary between projects. Instead, generate a `ScriptDirectory` object, injecting values from the config. """ temporary_dir = config.get_main_option("temporary_dir") migrations_dir = config.get_main_option("migrations_dir") return cls( dir=temporary_dir, version_locations=[migrations_dir], )
[ "def", "make_script_directory", "(", "cls", ",", "config", ")", ":", "temporary_dir", "=", "config", ".", "get_main_option", "(", "\"temporary_dir\"", ")", "migrations_dir", "=", "config", ".", "get_main_option", "(", "\"migrations_dir\"", ")", "return", "cls", "(...
Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree, and revision templates shouldn't vary between projects. Instead, generate a `ScriptDirectory` object, injecting values from the config.
[ "Alembic", "uses", "a", "script", "directory", "to", "encapsulate", "its", "env", ".", "py", "file", "its", "migrations", "directory", "and", "its", "script", ".", "py", ".", "mako", "revision", "template", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L70-L88
train
26,474
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
run_online_migration
def run_online_migration(self): """ Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration. """ connectable = self.graph.postgres with connectable.connect() as connection: context.configure( connection=connection, # assumes that all models extend our base target_metadata=Model.metadata, **get_alembic_environment_options(self.graph), ) with context.begin_transaction(): context.run_migrations()
python
def run_online_migration(self): """ Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration. """ connectable = self.graph.postgres with connectable.connect() as connection: context.configure( connection=connection, # assumes that all models extend our base target_metadata=Model.metadata, **get_alembic_environment_options(self.graph), ) with context.begin_transaction(): context.run_migrations()
[ "def", "run_online_migration", "(", "self", ")", ":", "connectable", "=", "self", ".", "graph", ".", "postgres", "with", "connectable", ".", "connect", "(", ")", "as", "connection", ":", "context", ".", "configure", "(", "connection", "=", "connection", ",",...
Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration.
[ "Run", "an", "online", "migration", "using", "microcosm", "configuration", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L98-L116
train
26,475
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
patch_script_directory
def patch_script_directory(graph): """ Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`. - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`. - Injecting the current object graph. """ temporary_dir = mkdtemp() from_config_original = getattr(ScriptDirectory, "from_config") run_env_original = getattr(ScriptDirectory, "run_env") # use a temporary directory for the revision template with open(join(temporary_dir, "script.py.mako"), "w") as file_: file_.write(make_script_py_mako()) file_.flush() # monkey patch our script directory and migration logic setattr(ScriptDirectory, "from_config", classmethod(make_script_directory)) setattr(ScriptDirectory, "run_env", run_online_migration) setattr(ScriptDirectory, "graph", graph) try: yield temporary_dir finally: # cleanup delattr(ScriptDirectory, "graph") setattr(ScriptDirectory, "run_env", run_env_original) setattr(ScriptDirectory, "from_config", from_config_original) rmtree(temporary_dir)
python
def patch_script_directory(graph): """ Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`. - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`. - Injecting the current object graph. """ temporary_dir = mkdtemp() from_config_original = getattr(ScriptDirectory, "from_config") run_env_original = getattr(ScriptDirectory, "run_env") # use a temporary directory for the revision template with open(join(temporary_dir, "script.py.mako"), "w") as file_: file_.write(make_script_py_mako()) file_.flush() # monkey patch our script directory and migration logic setattr(ScriptDirectory, "from_config", classmethod(make_script_directory)) setattr(ScriptDirectory, "run_env", run_online_migration) setattr(ScriptDirectory, "graph", graph) try: yield temporary_dir finally: # cleanup delattr(ScriptDirectory, "graph") setattr(ScriptDirectory, "run_env", run_env_original) setattr(ScriptDirectory, "from_config", from_config_original) rmtree(temporary_dir)
[ "def", "patch_script_directory", "(", "graph", ")", ":", "temporary_dir", "=", "mkdtemp", "(", ")", "from_config_original", "=", "getattr", "(", "ScriptDirectory", ",", "\"from_config\"", ")", "run_env_original", "=", "getattr", "(", "ScriptDirectory", ",", "\"run_e...
Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`. - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`. - Injecting the current object graph.
[ "Monkey", "patch", "the", "ScriptDirectory", "class", "working", "around", "configuration", "assumptions", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L156-L187
train
26,476
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
get_migrations_dir
def get_migrations_dir(graph): """ Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities. """ try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): migrations_dir = graph.metadata.get_path("migrations") if not isdir(migrations_dir): raise Exception("Migrations dir must exist: {}".format(migrations_dir)) return migrations_dir
python
def get_migrations_dir(graph): """ Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities. """ try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): migrations_dir = graph.metadata.get_path("migrations") if not isdir(migrations_dir): raise Exception("Migrations dir must exist: {}".format(migrations_dir)) return migrations_dir
[ "def", "get_migrations_dir", "(", "graph", ")", ":", "try", ":", "migrations_dir", "=", "graph", ".", "migrations_dir", "except", "(", "LockedGraphError", ",", "NotBoundError", ")", ":", "migrations_dir", "=", "graph", ".", "metadata", ".", "get_path", "(", "\...
Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities.
[ "Resolve", "the", "migrations", "directory", "path", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L190-L205
train
26,477
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
main
def main(graph, *args): """ Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with our patching. :param graph: an initialized object graph :param migration_dir: the path to the migrations directory """ migrations_dir = get_migrations_dir(graph) cli = CommandLine() options = cli.parser.parse_args(args if args else argv[1:]) if not hasattr(options, "cmd"): cli.parser.error("too few arguments") if options.cmd[0].__name__ == "init": cli.parser.error("Alembic 'init' command should not be used in the microcosm!") with patch_script_directory(graph) as temporary_dir: config = make_alembic_config(temporary_dir, migrations_dir) cli.run_cmd(config, options)
python
def main(graph, *args): """ Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with our patching. :param graph: an initialized object graph :param migration_dir: the path to the migrations directory """ migrations_dir = get_migrations_dir(graph) cli = CommandLine() options = cli.parser.parse_args(args if args else argv[1:]) if not hasattr(options, "cmd"): cli.parser.error("too few arguments") if options.cmd[0].__name__ == "init": cli.parser.error("Alembic 'init' command should not be used in the microcosm!") with patch_script_directory(graph) as temporary_dir: config = make_alembic_config(temporary_dir, migrations_dir) cli.run_cmd(config, options)
[ "def", "main", "(", "graph", ",", "*", "args", ")", ":", "migrations_dir", "=", "get_migrations_dir", "(", "graph", ")", "cli", "=", "CommandLine", "(", ")", "options", "=", "cli", ".", "parser", ".", "parse_args", "(", "args", "if", "args", "else", "a...
Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with our patching. :param graph: an initialized object graph :param migration_dir: the path to the migrations directory
[ "Entry", "point", "for", "invoking", "Alembic", "s", "CommandLine", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L208-L231
train
26,478
globality-corp/microcosm-postgres
microcosm_postgres/factories/sessionmaker.py
configure_sessionmaker
def configure_sessionmaker(graph): """ Create the SQLAlchemy session class. """ engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(Session): """ Route session bind to an appropriate engine. See: http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#partitioning-strategies """ def get_bind(self, mapper=None, clause=None): return engine_routing_strategy.get_bind(mapper, clause) return sessionmaker(class_=RoutingSession)
python
def configure_sessionmaker(graph): """ Create the SQLAlchemy session class. """ engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(Session): """ Route session bind to an appropriate engine. See: http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#partitioning-strategies """ def get_bind(self, mapper=None, clause=None): return engine_routing_strategy.get_bind(mapper, clause) return sessionmaker(class_=RoutingSession)
[ "def", "configure_sessionmaker", "(", "graph", ")", ":", "engine_routing_strategy", "=", "getattr", "(", "graph", ",", "graph", ".", "config", ".", "sessionmaker", ".", "engine_routing_strategy", ")", "if", "engine_routing_strategy", ".", "supports_multiple_binds", ":...
Create the SQLAlchemy session class.
[ "Create", "the", "SQLAlchemy", "session", "class", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/sessionmaker.py#L9-L29
train
26,479
globality-corp/microcosm-postgres
microcosm_postgres/cloning.py
clone
def clone(instance, substitutions, ignore=()): """ Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore """ substitutions[instance.id] = new_object_id() def substitute(value): try: hash(value) except Exception: return value else: return substitutions.get(value, value) return instance.__class__(**{ key: substitute(value) for key, value in iter_items(instance, ignore) }).create()
python
def clone(instance, substitutions, ignore=()): """ Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore """ substitutions[instance.id] = new_object_id() def substitute(value): try: hash(value) except Exception: return value else: return substitutions.get(value, value) return instance.__class__(**{ key: substitute(value) for key, value in iter_items(instance, ignore) }).create()
[ "def", "clone", "(", "instance", ",", "substitutions", ",", "ignore", "=", "(", ")", ")", ":", "substitutions", "[", "instance", ".", "id", "]", "=", "new_object_id", "(", ")", "def", "substitute", "(", "value", ")", ":", "try", ":", "hash", "(", "va...
Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore
[ "Clone", "an", "instance", "of", "Model", "that", "uses", "IdentityMixin", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/cloning.py#L10-L32
train
26,480
globality-corp/microcosm-postgres
microcosm_postgres/encryption/factories.py
configure_encryptor
def configure_encryptor(graph): """ Create a MultiTenantEncryptor from configured keys. """ encryptor = graph.multi_tenant_key_registry.make_encryptor(graph) # register the encryptor will each encryptable type for encryptable in EncryptableMixin.__subclasses__(): encryptable.register(encryptor) return encryptor
python
def configure_encryptor(graph): """ Create a MultiTenantEncryptor from configured keys. """ encryptor = graph.multi_tenant_key_registry.make_encryptor(graph) # register the encryptor will each encryptable type for encryptable in EncryptableMixin.__subclasses__(): encryptable.register(encryptor) return encryptor
[ "def", "configure_encryptor", "(", "graph", ")", ":", "encryptor", "=", "graph", ".", "multi_tenant_key_registry", ".", "make_encryptor", "(", "graph", ")", "# register the encryptor will each encryptable type", "for", "encryptable", "in", "EncryptableMixin", ".", "__subc...
Create a MultiTenantEncryptor from configured keys.
[ "Create", "a", "MultiTenantEncryptor", "from", "configured", "keys", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/factories.py#L4-L15
train
26,481
globality-corp/microcosm-postgres
microcosm_postgres/toposort.py
toposorted
def toposorted(nodes, edges): """ Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ incoming = defaultdict(set) outgoing = defaultdict(set) for edge in edges: incoming[edge.to_id].add(edge.from_id) outgoing[edge.from_id].add(edge.to_id) working_set = list(nodes.values()) results = [] while working_set: remaining = [] for node in working_set: if incoming[node.id]: # node still has incoming edges remaining.append(node) continue results.append(node) for child in outgoing[node.id]: incoming[child].remove(node.id) if len(working_set) == len(remaining): raise Exception("Cycle detected") working_set = remaining return results
python
def toposorted(nodes, edges): """ Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ incoming = defaultdict(set) outgoing = defaultdict(set) for edge in edges: incoming[edge.to_id].add(edge.from_id) outgoing[edge.from_id].add(edge.to_id) working_set = list(nodes.values()) results = [] while working_set: remaining = [] for node in working_set: if incoming[node.id]: # node still has incoming edges remaining.append(node) continue results.append(node) for child in outgoing[node.id]: incoming[child].remove(node.id) if len(working_set) == len(remaining): raise Exception("Cycle detected") working_set = remaining return results
[ "def", "toposorted", "(", "nodes", ",", "edges", ")", ":", "incoming", "=", "defaultdict", "(", "set", ")", "outgoing", "=", "defaultdict", "(", "set", ")", "for", "edge", "in", "edges", ":", "incoming", "[", "edge", ".", "to_id", "]", ".", "add", "(...
Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching.
[ "Perform", "a", "topological", "sort", "on", "the", "input", "resources", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/toposort.py#L8-L40
train
26,482
globality-corp/microcosm-postgres
microcosm_postgres/temporary/copy.py
should_copy
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted on upsert/insert return False
python
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted on upsert/insert return False
[ "def", "should_copy", "(", "column", ")", ":", "if", "not", "isinstance", "(", "column", ".", "type", ",", "Serial", ")", ":", "return", "True", "if", "column", ".", "nullable", ":", "return", "True", "if", "not", "column", ".", "server_default", ":", ...
Determine if a column should be copied.
[ "Determine", "if", "a", "column", "should", "be", "copied", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/copy.py#L18-L33
train
26,483
globality-corp/microcosm-postgres
microcosm_postgres/encryption/encryptor.py
SingleTenantEncryptor.encrypt
def encrypt(self, encryption_context_key: str, plaintext: str) -> Tuple[bytes, Sequence[str]]: """ Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the likely case that the encryptor was initialized with master key aliases, these master key ids returned will represent the unaliased key. """ encryption_context = dict( microcosm=encryption_context_key, ) cyphertext, header = encrypt( source=plaintext, materials_manager=self.materials_manager, encryption_context=encryption_context, ) key_ids = [ self.unpack_key_id(encrypted_data_key.key_provider) for encrypted_data_key in header.encrypted_data_keys ] return cyphertext, key_ids
python
def encrypt(self, encryption_context_key: str, plaintext: str) -> Tuple[bytes, Sequence[str]]: """ Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the likely case that the encryptor was initialized with master key aliases, these master key ids returned will represent the unaliased key. """ encryption_context = dict( microcosm=encryption_context_key, ) cyphertext, header = encrypt( source=plaintext, materials_manager=self.materials_manager, encryption_context=encryption_context, ) key_ids = [ self.unpack_key_id(encrypted_data_key.key_provider) for encrypted_data_key in header.encrypted_data_keys ] return cyphertext, key_ids
[ "def", "encrypt", "(", "self", ",", "encryption_context_key", ":", "str", ",", "plaintext", ":", "str", ")", "->", "Tuple", "[", "bytes", ",", "Sequence", "[", "str", "]", "]", ":", "encryption_context", "=", "dict", "(", "microcosm", "=", "encryption_cont...
Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the likely case that the encryptor was initialized with master key aliases, these master key ids returned will represent the unaliased key.
[ "Encrypt", "a", "plaintext", "string", "value", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/encryptor.py#L27-L52
train
26,484
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
on_init
def on_init(target: "EncryptableMixin", args, kwargs): """ Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` dictionary is mutable (which is why it is not passed as `**kwargs`). We leverage this callback to conditionally remove the `__plaintext__` value and set the `ciphertext` property. """ encryptor = target.__encryptor__ # encryption context may be nullable try: encryption_context_key = str(kwargs[target.__encryption_context_key__]) except KeyError: return # do not encrypt targets that are not configured for it if encryption_context_key not in encryptor: return plaintext = target.plaintext_to_str(kwargs.pop(target.__plaintext__)) # do not try to encrypt when plaintext is None if plaintext is None: return ciphertext, key_ids = encryptor.encrypt(encryption_context_key, plaintext) target.ciphertext = (ciphertext, key_ids)
python
def on_init(target: "EncryptableMixin", args, kwargs): """ Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` dictionary is mutable (which is why it is not passed as `**kwargs`). We leverage this callback to conditionally remove the `__plaintext__` value and set the `ciphertext` property. """ encryptor = target.__encryptor__ # encryption context may be nullable try: encryption_context_key = str(kwargs[target.__encryption_context_key__]) except KeyError: return # do not encrypt targets that are not configured for it if encryption_context_key not in encryptor: return plaintext = target.plaintext_to_str(kwargs.pop(target.__plaintext__)) # do not try to encrypt when plaintext is None if plaintext is None: return ciphertext, key_ids = encryptor.encrypt(encryption_context_key, plaintext) target.ciphertext = (ciphertext, key_ids)
[ "def", "on_init", "(", "target", ":", "\"EncryptableMixin\"", ",", "args", ",", "kwargs", ")", ":", "encryptor", "=", "target", ".", "__encryptor__", "# encryption context may be nullable", "try", ":", "encryption_context_key", "=", "str", "(", "kwargs", "[", "tar...
Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` dictionary is mutable (which is why it is not passed as `**kwargs`). We leverage this callback to conditionally remove the `__plaintext__` value and set the `ciphertext` property.
[ "Intercept", "SQLAlchemy", "s", "instance", "init", "event", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L14-L44
train
26,485
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
on_load
def on_load(target: "EncryptableMixin", context): """ Intercept SQLAlchemy's instance load event. """ decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
python
def on_load(target: "EncryptableMixin", context): """ Intercept SQLAlchemy's instance load event. """ decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
[ "def", "on_load", "(", "target", ":", "\"EncryptableMixin\"", ",", "context", ")", ":", "decrypt", ",", "plaintext", "=", "decrypt_instance", "(", "target", ")", "if", "decrypt", ":", "target", ".", "plaintext", "=", "plaintext" ]
Intercept SQLAlchemy's instance load event.
[ "Intercept", "SQLAlchemy", "s", "instance", "load", "event", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L47-L54
train
26,486
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
EncryptableMixin.register
def register(cls, encryptor: Encryptor): """ Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load. """ # save the current encryptor statically cls.__encryptor__ = encryptor # NB: we cannot use the before_insert listener in conjunction with a foreign key relationship # for encrypted data; SQLAlchemy will warn about using 'related attribute set' operation so # late in its insert/flush process. listeners = dict( init=on_init, load=on_load, ) for name, func in listeners.items(): # If we initialize the graph multiple times (as in many unit testing scenarios), # we will accumulate listener functions -- with unpredictable results. As protection, # we need to remove existing listeners before adding new ones; this solution only # works if the id (e.g. memory address) of the listener does not change, which means # they cannot be closures around the `encryptor` reference. # # Hence the `__encryptor__` hack above... if contains(cls, name, func): remove(cls, name, func) listen(cls, name, func)
python
def register(cls, encryptor: Encryptor): """ Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load. """ # save the current encryptor statically cls.__encryptor__ = encryptor # NB: we cannot use the before_insert listener in conjunction with a foreign key relationship # for encrypted data; SQLAlchemy will warn about using 'related attribute set' operation so # late in its insert/flush process. listeners = dict( init=on_init, load=on_load, ) for name, func in listeners.items(): # If we initialize the graph multiple times (as in many unit testing scenarios), # we will accumulate listener functions -- with unpredictable results. As protection, # we need to remove existing listeners before adding new ones; this solution only # works if the id (e.g. memory address) of the listener does not change, which means # they cannot be closures around the `encryptor` reference. # # Hence the `__encryptor__` hack above... if contains(cls, name, func): remove(cls, name, func) listen(cls, name, func)
[ "def", "register", "(", "cls", ",", "encryptor", ":", "Encryptor", ")", ":", "# save the current encryptor statically", "cls", ".", "__encryptor__", "=", "encryptor", "# NB: we cannot use the before_insert listener in conjunction with a foreign key relationship", "# for encrypted d...
Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load.
[ "Register", "this", "encryptable", "with", "an", "encryptor", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L138-L166
train
26,487
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.nodes_map
def nodes_map(self): """ Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers. """ dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablename__" in base.__dict__) key = getattr(cls, "__alias__", underscore(cls.__name__)) dct.setdefault(key, []).append(node) return dct
python
def nodes_map(self): """ Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers. """ dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablename__" in base.__dict__) key = getattr(cls, "__alias__", underscore(cls.__name__)) dct.setdefault(key, []).append(node) return dct
[ "def", "nodes_map", "(", "self", ")", ":", "dct", "=", "dict", "(", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "cls", "=", "next", "(", "base", "for", "base", "in", "getmro", "(", "node", ".", "__class__", ")", ...
Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers.
[ "Build", "a", "mapping", "from", "node", "type", "to", "a", "list", "of", "nodes", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L46-L58
train
26,488
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.build_edges
def build_edges(self): """ Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG. """ self.edges = [ edge if isinstance(edge, Edge) else Edge(*edge) for node in self.nodes.values() for edge in getattr(node, "edges", []) if edge[0] in self.nodes and edge[1] in self.nodes ] return self
python
def build_edges(self): """ Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG. """ self.edges = [ edge if isinstance(edge, Edge) else Edge(*edge) for node in self.nodes.values() for edge in getattr(node, "edges", []) if edge[0] in self.nodes and edge[1] in self.nodes ] return self
[ "def", "build_edges", "(", "self", ")", ":", "self", ".", "edges", "=", "[", "edge", "if", "isinstance", "(", "edge", ",", "Edge", ")", "else", "Edge", "(", "*", "edge", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", "fo...
Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG.
[ "Build", "edges", "based", "on", "node", "edges", "property", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L60-L73
train
26,489
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.clone
def clone(self, ignore=()): """ Clone this dag using a set of substitutions. Traverse the dag in topological order. """ nodes = [ clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges) ] return DAG(nodes=nodes, substitutions=self.substitutions).build_edges()
python
def clone(self, ignore=()): """ Clone this dag using a set of substitutions. Traverse the dag in topological order. """ nodes = [ clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges) ] return DAG(nodes=nodes, substitutions=self.substitutions).build_edges()
[ "def", "clone", "(", "self", ",", "ignore", "=", "(", ")", ")", ":", "nodes", "=", "[", "clone", "(", "node", ",", "self", ".", "substitutions", ",", "ignore", ")", "for", "node", "in", "toposorted", "(", "self", ".", "nodes", ",", "self", ".", "...
Clone this dag using a set of substitutions. Traverse the dag in topological order.
[ "Clone", "this", "dag", "using", "a", "set", "of", "substitutions", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L75-L86
train
26,490
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAGCloner.explain
def explain(self, **kwargs): """ Generate a "dry run" DAG of that state that WILL be cloned. """ root = self.retrieve_root(**kwargs) children = self.iter_children(root, **kwargs) dag = DAG.from_nodes(root, *children) return self.add_edges(dag)
python
def explain(self, **kwargs): """ Generate a "dry run" DAG of that state that WILL be cloned. """ root = self.retrieve_root(**kwargs) children = self.iter_children(root, **kwargs) dag = DAG.from_nodes(root, *children) return self.add_edges(dag)
[ "def", "explain", "(", "self", ",", "*", "*", "kwargs", ")", ":", "root", "=", "self", ".", "retrieve_root", "(", "*", "*", "kwargs", ")", "children", "=", "self", ".", "iter_children", "(", "root", ",", "*", "*", "kwargs", ")", "dag", "=", "DAG", ...
Generate a "dry run" DAG of that state that WILL be cloned.
[ "Generate", "a", "dry", "run", "DAG", "of", "that", "state", "that", "WILL", "be", "cloned", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L104-L112
train
26,491
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAGCloner.clone
def clone(self, substitutions, **kwargs): """ Clone a DAG. """ dag = self.explain(**kwargs) dag.substitutions.update(substitutions) cloned_dag = dag.clone(ignore=self.ignore) return self.update_nodes(self.add_edges(cloned_dag))
python
def clone(self, substitutions, **kwargs): """ Clone a DAG. """ dag = self.explain(**kwargs) dag.substitutions.update(substitutions) cloned_dag = dag.clone(ignore=self.ignore) return self.update_nodes(self.add_edges(cloned_dag))
[ "def", "clone", "(", "self", ",", "substitutions", ",", "*", "*", "kwargs", ")", ":", "dag", "=", "self", ".", "explain", "(", "*", "*", "kwargs", ")", "dag", ".", "substitutions", ".", "update", "(", "substitutions", ")", "cloned_dag", "=", "dag", "...
Clone a DAG.
[ "Clone", "a", "DAG", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L114-L122
train
26,492
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_database_name
def choose_database_name(metadata, config): """ Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident. """ if config.database_name is not None: # we allow -- but do not encourage -- database name configuration return config.database_name if metadata.testing: # by convention, we provision different databases for unit testing and runtime return f"{metadata.name}_test_db" return f"{metadata.name}_db"
python
def choose_database_name(metadata, config): """ Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident. """ if config.database_name is not None: # we allow -- but do not encourage -- database name configuration return config.database_name if metadata.testing: # by convention, we provision different databases for unit testing and runtime return f"{metadata.name}_test_db" return f"{metadata.name}_db"
[ "def", "choose_database_name", "(", "metadata", ",", "config", ")", ":", "if", "config", ".", "database_name", "is", "not", "None", ":", "# we allow -- but do not encourage -- database name configuration", "return", "config", ".", "database_name", "if", "metadata", ".",...
Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident.
[ "Choose", "the", "database", "name", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L11-L28
train
26,493
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_username
def choose_username(metadata, config): """ Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them. """ if config.username is not None: # we allow -- but do not encourage -- database username configuration return config.username if config.read_only: # by convention, we provision read-only username for every service return f"{metadata.name}_ro" return metadata.name
python
def choose_username(metadata, config): """ Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them. """ if config.username is not None: # we allow -- but do not encourage -- database username configuration return config.username if config.read_only: # by convention, we provision read-only username for every service return f"{metadata.name}_ro" return metadata.name
[ "def", "choose_username", "(", "metadata", ",", "config", ")", ":", "if", "config", ".", "username", "is", "not", "None", ":", "# we allow -- but do not encourage -- database username configuration", "return", "config", ".", "username", "if", "config", ".", "read_only...
Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them.
[ "Choose", "the", "database", "username", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L31-L47
train
26,494
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_uri
def choose_uri(metadata, config): """ Choose the database URI to use. """ database_name = choose_database_name(metadata, config) driver = config.driver host, port = config.host, config.port username, password = choose_username(metadata, config), config.password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}"
python
def choose_uri(metadata, config): """ Choose the database URI to use. """ database_name = choose_database_name(metadata, config) driver = config.driver host, port = config.host, config.port username, password = choose_username(metadata, config), config.password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}"
[ "def", "choose_uri", "(", "metadata", ",", "config", ")", ":", "database_name", "=", "choose_database_name", "(", "metadata", ",", "config", ")", "driver", "=", "config", ".", "driver", "host", ",", "port", "=", "config", ".", "host", ",", "config", ".", ...
Choose the database URI to use.
[ "Choose", "the", "database", "URI", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L50-L60
train
26,495
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_connect_args
def choose_connect_args(metadata, config): """ Choose the SSL mode and optional root cert for the connection. """ if not config.require_ssl and not config.verify_ssl: return dict( sslmode="prefer", ) if config.require_ssl and not config.verify_ssl: return dict( sslmode="require", ) if not config.ssl_cert_path: raise Exception("SSL certificate path (`ssl_cert_path`) must be configured for verification") return dict( sslmode="verify-full", sslrootcert=config.ssl_cert_path, )
python
def choose_connect_args(metadata, config): """ Choose the SSL mode and optional root cert for the connection. """ if not config.require_ssl and not config.verify_ssl: return dict( sslmode="prefer", ) if config.require_ssl and not config.verify_ssl: return dict( sslmode="require", ) if not config.ssl_cert_path: raise Exception("SSL certificate path (`ssl_cert_path`) must be configured for verification") return dict( sslmode="verify-full", sslrootcert=config.ssl_cert_path, )
[ "def", "choose_connect_args", "(", "metadata", ",", "config", ")", ":", "if", "not", "config", ".", "require_ssl", "and", "not", "config", ".", "verify_ssl", ":", "return", "dict", "(", "sslmode", "=", "\"prefer\"", ",", ")", "if", "config", ".", "require_...
Choose the SSL mode and optional root cert for the connection.
[ "Choose", "the", "SSL", "mode", "and", "optional", "root", "cert", "for", "the", "connection", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L63-L84
train
26,496
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_args
def choose_args(metadata, config): """ Choose database connection arguments. """ return dict( connect_args=choose_connect_args(metadata, config), echo=config.echo, max_overflow=config.max_overflow, pool_size=config.pool_size, pool_timeout=config.pool_timeout, )
python
def choose_args(metadata, config): """ Choose database connection arguments. """ return dict( connect_args=choose_connect_args(metadata, config), echo=config.echo, max_overflow=config.max_overflow, pool_size=config.pool_size, pool_timeout=config.pool_timeout, )
[ "def", "choose_args", "(", "metadata", ",", "config", ")", ":", "return", "dict", "(", "connect_args", "=", "choose_connect_args", "(", "metadata", ",", "config", ")", ",", "echo", "=", "config", ".", "echo", ",", "max_overflow", "=", "config", ".", "max_o...
Choose database connection arguments.
[ "Choose", "database", "connection", "arguments", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L87-L98
train
26,497
globality-corp/microcosm-postgres
microcosm_postgres/models.py
IdentityMixin._members
def _members(self): """ Return a dict of non-private members. """ return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(value, Model) }
python
def _members(self): """ Return a dict of non-private members. """ return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(value, Model) }
[ "def", "_members", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", "# NB: ignore internal SQLAlchemy state and nested relationships", "if", "not", "key", ".", "starts...
Return a dict of non-private members.
[ "Return", "a", "dict", "of", "non", "-", "private", "members", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/models.py#L113-L123
train
26,498
globality-corp/microcosm-postgres
microcosm_postgres/temporary/methods.py
insert_many
def insert_many(self, items): """ Insert many items at once into a temporary table. """ return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
python
def insert_many(self, items): """ Insert many items at once into a temporary table. """ return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
[ "def", "insert_many", "(", "self", ",", "items", ")", ":", "return", "SessionContext", ".", "session", ".", "execute", "(", "self", ".", "insert", "(", "values", "=", "[", "to_dict", "(", "item", ",", "self", ".", "c", ")", "for", "item", "in", "item...
Insert many items at once into a temporary table.
[ "Insert", "many", "items", "at", "once", "into", "a", "temporary", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/methods.py#L23-L33
train
26,499