repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
sdispater/poetry
poetry/version/version_selector.py
VersionSelector.find_best_candidate
def find_best_candidate( self, package_name, # type: str target_package_version=None, # type: Union[str, None] allow_prereleases=False, # type: bool ): # type: (...) -> Union[Package, bool] """ Given a package name and optional version, returns the latest Package that matches """ if target_package_version: constraint = parse_constraint(target_package_version) else: constraint = parse_constraint("*") candidates = self._pool.find_packages( package_name, constraint, allow_prereleases=allow_prereleases ) if not candidates: return False dependency = Dependency(package_name, constraint) # Select highest version if we have many package = candidates[0] for candidate in candidates: if candidate.is_prerelease() and not dependency.allows_prereleases(): continue # Select highest version of the two if package.version < candidate.version: package = candidate return package
python
def find_best_candidate( self, package_name, # type: str target_package_version=None, # type: Union[str, None] allow_prereleases=False, # type: bool ): # type: (...) -> Union[Package, bool] """ Given a package name and optional version, returns the latest Package that matches """ if target_package_version: constraint = parse_constraint(target_package_version) else: constraint = parse_constraint("*") candidates = self._pool.find_packages( package_name, constraint, allow_prereleases=allow_prereleases ) if not candidates: return False dependency = Dependency(package_name, constraint) # Select highest version if we have many package = candidates[0] for candidate in candidates: if candidate.is_prerelease() and not dependency.allows_prereleases(): continue # Select highest version of the two if package.version < candidate.version: package = candidate return package
[ "def", "find_best_candidate", "(", "self", ",", "package_name", ",", "# type: str", "target_package_version", "=", "None", ",", "# type: Union[str, None]", "allow_prereleases", "=", "False", ",", "# type: bool", ")", ":", "# type: (...) -> Union[Package, bool]", "if", "target_package_version", ":", "constraint", "=", "parse_constraint", "(", "target_package_version", ")", "else", ":", "constraint", "=", "parse_constraint", "(", "\"*\"", ")", "candidates", "=", "self", ".", "_pool", ".", "find_packages", "(", "package_name", ",", "constraint", ",", "allow_prereleases", "=", "allow_prereleases", ")", "if", "not", "candidates", ":", "return", "False", "dependency", "=", "Dependency", "(", "package_name", ",", "constraint", ")", "# Select highest version if we have many", "package", "=", "candidates", "[", "0", "]", "for", "candidate", "in", "candidates", ":", "if", "candidate", ".", "is_prerelease", "(", ")", "and", "not", "dependency", ".", "allows_prereleases", "(", ")", ":", "continue", "# Select highest version of the two", "if", "package", ".", "version", "<", "candidate", ".", "version", ":", "package", "=", "candidate", "return", "package" ]
Given a package name and optional version, returns the latest Package that matches
[ "Given", "a", "package", "name", "and", "optional", "version", "returns", "the", "latest", "Package", "that", "matches" ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/version/version_selector.py#L13-L47
train
sdispater/poetry
poetry/repositories/legacy_repository.py
Page.clean_link
def clean_link(self, url): """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).""" return self._clean_re.sub(lambda match: "%%%2x" % ord(match.group(0)), url)
python
def clean_link(self, url): """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).""" return self._clean_re.sub(lambda match: "%%%2x" % ord(match.group(0)), url)
[ "def", "clean_link", "(", "self", ",", "url", ")", ":", "return", "self", ".", "_clean_re", ".", "sub", "(", "lambda", "match", ":", "\"%%%2x\"", "%", "ord", "(", "match", ".", "group", "(", "0", ")", ")", ",", "url", ")" ]
Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).
[ "Makes", "sure", "a", "link", "is", "fully", "encoded", ".", "That", "is", "if", "a", "shows", "up", "in", "the", "link", "it", "will", "be", "rewritten", "to", "%20", "(", "while", "not", "over", "-", "quoting", "%", "or", "other", "characters", ")", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/legacy_repository.py#L143-L147
train
sdispater/poetry
poetry/repositories/legacy_repository.py
LegacyRepository.package
def package( self, name, version, extras=None ): # type: (...) -> poetry.packages.Package """ Retrieve the release information. This is a heavy task which takes time. We have to download a package to get the dependencies. We also need to download every file matching this release to get the various hashes. Note that, this will be cached so the subsequent operations should be much faster. """ try: index = self._packages.index( poetry.packages.Package(name, version, version) ) return self._packages[index] except ValueError: if extras is None: extras = [] release_info = self.get_release_info(name, version) package = poetry.packages.Package(name, version, version) if release_info["requires_python"]: package.python_versions = release_info["requires_python"] package.source_type = "legacy" package.source_url = self._url package.source_reference = self.name requires_dist = release_info["requires_dist"] or [] for req in requires_dist: try: dependency = dependency_from_pep_508(req) except InvalidMarker: # Invalid marker # We strip the markers hoping for the best req = req.split(";")[0] dependency = dependency_from_pep_508(req) except ValueError: # Likely unable to parse constraint so we skip it self._log( "Invalid constraint ({}) found in {}-{} dependencies, " "skipping".format(req, package.name, package.version), level="debug", ) continue if dependency.in_extras: for extra in dependency.in_extras: if extra not in package.extras: package.extras[extra] = [] package.extras[extra].append(dependency) if not dependency.is_optional(): package.requires.append(dependency) # Adding description package.description = release_info.get("summary", "") # Adding hashes information package.hashes = release_info["digests"] # Activate extra dependencies for extra in extras: if extra in package.extras: for dep in package.extras[extra]: dep.activate() package.requires += package.extras[extra] self._packages.append(package) return package
python
def package( self, name, version, extras=None ): # type: (...) -> poetry.packages.Package """ Retrieve the release information. This is a heavy task which takes time. We have to download a package to get the dependencies. We also need to download every file matching this release to get the various hashes. Note that, this will be cached so the subsequent operations should be much faster. """ try: index = self._packages.index( poetry.packages.Package(name, version, version) ) return self._packages[index] except ValueError: if extras is None: extras = [] release_info = self.get_release_info(name, version) package = poetry.packages.Package(name, version, version) if release_info["requires_python"]: package.python_versions = release_info["requires_python"] package.source_type = "legacy" package.source_url = self._url package.source_reference = self.name requires_dist = release_info["requires_dist"] or [] for req in requires_dist: try: dependency = dependency_from_pep_508(req) except InvalidMarker: # Invalid marker # We strip the markers hoping for the best req = req.split(";")[0] dependency = dependency_from_pep_508(req) except ValueError: # Likely unable to parse constraint so we skip it self._log( "Invalid constraint ({}) found in {}-{} dependencies, " "skipping".format(req, package.name, package.version), level="debug", ) continue if dependency.in_extras: for extra in dependency.in_extras: if extra not in package.extras: package.extras[extra] = [] package.extras[extra].append(dependency) if not dependency.is_optional(): package.requires.append(dependency) # Adding description package.description = release_info.get("summary", "") # Adding hashes information package.hashes = release_info["digests"] # Activate extra dependencies for extra in extras: if extra in package.extras: for dep in package.extras[extra]: dep.activate() package.requires += package.extras[extra] self._packages.append(package) return package
[ "def", "package", "(", "self", ",", "name", ",", "version", ",", "extras", "=", "None", ")", ":", "# type: (...) -> poetry.packages.Package", "try", ":", "index", "=", "self", ".", "_packages", ".", "index", "(", "poetry", ".", "packages", ".", "Package", "(", "name", ",", "version", ",", "version", ")", ")", "return", "self", ".", "_packages", "[", "index", "]", "except", "ValueError", ":", "if", "extras", "is", "None", ":", "extras", "=", "[", "]", "release_info", "=", "self", ".", "get_release_info", "(", "name", ",", "version", ")", "package", "=", "poetry", ".", "packages", ".", "Package", "(", "name", ",", "version", ",", "version", ")", "if", "release_info", "[", "\"requires_python\"", "]", ":", "package", ".", "python_versions", "=", "release_info", "[", "\"requires_python\"", "]", "package", ".", "source_type", "=", "\"legacy\"", "package", ".", "source_url", "=", "self", ".", "_url", "package", ".", "source_reference", "=", "self", ".", "name", "requires_dist", "=", "release_info", "[", "\"requires_dist\"", "]", "or", "[", "]", "for", "req", "in", "requires_dist", ":", "try", ":", "dependency", "=", "dependency_from_pep_508", "(", "req", ")", "except", "InvalidMarker", ":", "# Invalid marker", "# We strip the markers hoping for the best", "req", "=", "req", ".", "split", "(", "\";\"", ")", "[", "0", "]", "dependency", "=", "dependency_from_pep_508", "(", "req", ")", "except", "ValueError", ":", "# Likely unable to parse constraint so we skip it", "self", ".", "_log", "(", "\"Invalid constraint ({}) found in {}-{} dependencies, \"", "\"skipping\"", ".", "format", "(", "req", ",", "package", ".", "name", ",", "package", ".", "version", ")", ",", "level", "=", "\"debug\"", ",", ")", "continue", "if", "dependency", ".", "in_extras", ":", "for", "extra", "in", "dependency", ".", "in_extras", ":", "if", "extra", "not", "in", "package", ".", "extras", ":", "package", ".", "extras", "[", "extra", "]", "=", "[", "]", "package", ".", "extras", "[", "extra", "]", ".", "append", "(", "dependency", ")", "if", "not", "dependency", ".", "is_optional", "(", ")", ":", "package", ".", "requires", ".", "append", "(", "dependency", ")", "# Adding description", "package", ".", "description", "=", "release_info", ".", "get", "(", "\"summary\"", ",", "\"\"", ")", "# Adding hashes information", "package", ".", "hashes", "=", "release_info", "[", "\"digests\"", "]", "# Activate extra dependencies", "for", "extra", "in", "extras", ":", "if", "extra", "in", "package", ".", "extras", ":", "for", "dep", "in", "package", ".", "extras", "[", "extra", "]", ":", "dep", ".", "activate", "(", ")", "package", ".", "requires", "+=", "package", ".", "extras", "[", "extra", "]", "self", ".", "_packages", ".", "append", "(", "package", ")", "return", "package" ]
Retrieve the release information. This is a heavy task which takes time. We have to download a package to get the dependencies. We also need to download every file matching this release to get the various hashes. Note that, this will be cached so the subsequent operations should be much faster.
[ "Retrieve", "the", "release", "information", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/legacy_repository.py#L246-L325
train
sdispater/poetry
poetry/console/commands/command.py
Command.run
def run(self, i, o): # type: () -> int """ Initialize command. """ self.input = i self.output = PoetryStyle(i, o) for logger in self._loggers: self.register_logger(logging.getLogger(logger)) return super(BaseCommand, self).run(i, o)
python
def run(self, i, o): # type: () -> int """ Initialize command. """ self.input = i self.output = PoetryStyle(i, o) for logger in self._loggers: self.register_logger(logging.getLogger(logger)) return super(BaseCommand, self).run(i, o)
[ "def", "run", "(", "self", ",", "i", ",", "o", ")", ":", "# type: () -> int", "self", ".", "input", "=", "i", "self", ".", "output", "=", "PoetryStyle", "(", "i", ",", "o", ")", "for", "logger", "in", "self", ".", "_loggers", ":", "self", ".", "register_logger", "(", "logging", ".", "getLogger", "(", "logger", ")", ")", "return", "super", "(", "BaseCommand", ",", "self", ")", ".", "run", "(", "i", ",", "o", ")" ]
Initialize command.
[ "Initialize", "command", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/console/commands/command.py#L67-L77
train
sdispater/poetry
poetry/console/commands/command.py
Command.register_logger
def register_logger(self, logger): """ Register a new logger. """ handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = logging.WARNING if output.is_debug(): level = logging.DEBUG elif output.is_very_verbose() or output.is_verbose(): level = logging.INFO logger.setLevel(level)
python
def register_logger(self, logger): """ Register a new logger. """ handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = logging.WARNING if output.is_debug(): level = logging.DEBUG elif output.is_very_verbose() or output.is_verbose(): level = logging.INFO logger.setLevel(level)
[ "def", "register_logger", "(", "self", ",", "logger", ")", ":", "handler", "=", "CommandHandler", "(", "self", ")", "handler", ".", "setFormatter", "(", "CommandFormatter", "(", ")", ")", "logger", ".", "handlers", "=", "[", "handler", "]", "logger", ".", "propagate", "=", "False", "output", "=", "self", ".", "output", "level", "=", "logging", ".", "WARNING", "if", "output", ".", "is_debug", "(", ")", ":", "level", "=", "logging", ".", "DEBUG", "elif", "output", ".", "is_very_verbose", "(", ")", "or", "output", ".", "is_verbose", "(", ")", ":", "level", "=", "logging", ".", "INFO", "logger", ".", "setLevel", "(", "level", ")" ]
Register a new logger.
[ "Register", "a", "new", "logger", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/console/commands/command.py#L79-L95
train
sdispater/poetry
poetry/masonry/publishing/uploader.py
Uploader._register
def _register(self, session, url): """ Register a package to a repository. """ dist = self._poetry.file.parent / "dist" file = dist / "{}-{}.tar.gz".format( self._package.name, normalize_version(self._package.version.text) ) if not file.exists(): raise RuntimeError('"{0}" does not exist.'.format(file.name)) data = self.post_data(file) data.update({":action": "submit", "protocol_version": "1"}) data_to_send = self._prepare_data(data) encoder = MultipartEncoder(data_to_send) resp = session.post( url, data=encoder, allow_redirects=False, headers={"Content-Type": encoder.content_type}, ) resp.raise_for_status() return resp
python
def _register(self, session, url): """ Register a package to a repository. """ dist = self._poetry.file.parent / "dist" file = dist / "{}-{}.tar.gz".format( self._package.name, normalize_version(self._package.version.text) ) if not file.exists(): raise RuntimeError('"{0}" does not exist.'.format(file.name)) data = self.post_data(file) data.update({":action": "submit", "protocol_version": "1"}) data_to_send = self._prepare_data(data) encoder = MultipartEncoder(data_to_send) resp = session.post( url, data=encoder, allow_redirects=False, headers={"Content-Type": encoder.content_type}, ) resp.raise_for_status() return resp
[ "def", "_register", "(", "self", ",", "session", ",", "url", ")", ":", "dist", "=", "self", ".", "_poetry", ".", "file", ".", "parent", "/", "\"dist\"", "file", "=", "dist", "/", "\"{}-{}.tar.gz\"", ".", "format", "(", "self", ".", "_package", ".", "name", ",", "normalize_version", "(", "self", ".", "_package", ".", "version", ".", "text", ")", ")", "if", "not", "file", ".", "exists", "(", ")", ":", "raise", "RuntimeError", "(", "'\"{0}\" does not exist.'", ".", "format", "(", "file", ".", "name", ")", ")", "data", "=", "self", ".", "post_data", "(", "file", ")", "data", ".", "update", "(", "{", "\":action\"", ":", "\"submit\"", ",", "\"protocol_version\"", ":", "\"1\"", "}", ")", "data_to_send", "=", "self", ".", "_prepare_data", "(", "data", ")", "encoder", "=", "MultipartEncoder", "(", "data_to_send", ")", "resp", "=", "session", ".", "post", "(", "url", ",", "data", "=", "encoder", ",", "allow_redirects", "=", "False", ",", "headers", "=", "{", "\"Content-Type\"", ":", "encoder", ".", "content_type", "}", ",", ")", "resp", ".", "raise_for_status", "(", ")", "return", "resp" ]
Register a package to a repository.
[ "Register", "a", "package", "to", "a", "repository", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/publishing/uploader.py#L256-L282
train
sdispater/poetry
poetry/repositories/pypi_repository.py
PyPiRepository.find_packages
def find_packages( self, name, # type: str constraint=None, # type: Union[VersionConstraint, str, None] extras=None, # type: Union[list, None] allow_prereleases=False, # type: bool ): # type: (...) -> List[Package] """ Find packages on the remote server. """ if constraint is None: constraint = "*" if not isinstance(constraint, VersionConstraint): constraint = parse_constraint(constraint) if isinstance(constraint, VersionRange): if ( constraint.max is not None and constraint.max.is_prerelease() or constraint.min is not None and constraint.min.is_prerelease() ): allow_prereleases = True info = self.get_package_info(name) packages = [] for version, release in info["releases"].items(): if not release: # Bad release self._log( "No release information found for {}-{}, skipping".format( name, version ), level="debug", ) continue try: package = Package(name, version) except ParseVersionError: self._log( 'Unable to parse version "{}" for the {} package, skipping'.format( version, name ), level="debug", ) continue if package.is_prerelease() and not allow_prereleases: continue if not constraint or (constraint and constraint.allows(package.version)): if extras is not None: package.requires_extras = extras packages.append(package) self._log( "{} packages found for {} {}".format(len(packages), name, str(constraint)), level="debug", ) return packages
python
def find_packages( self, name, # type: str constraint=None, # type: Union[VersionConstraint, str, None] extras=None, # type: Union[list, None] allow_prereleases=False, # type: bool ): # type: (...) -> List[Package] """ Find packages on the remote server. """ if constraint is None: constraint = "*" if not isinstance(constraint, VersionConstraint): constraint = parse_constraint(constraint) if isinstance(constraint, VersionRange): if ( constraint.max is not None and constraint.max.is_prerelease() or constraint.min is not None and constraint.min.is_prerelease() ): allow_prereleases = True info = self.get_package_info(name) packages = [] for version, release in info["releases"].items(): if not release: # Bad release self._log( "No release information found for {}-{}, skipping".format( name, version ), level="debug", ) continue try: package = Package(name, version) except ParseVersionError: self._log( 'Unable to parse version "{}" for the {} package, skipping'.format( version, name ), level="debug", ) continue if package.is_prerelease() and not allow_prereleases: continue if not constraint or (constraint and constraint.allows(package.version)): if extras is not None: package.requires_extras = extras packages.append(package) self._log( "{} packages found for {} {}".format(len(packages), name, str(constraint)), level="debug", ) return packages
[ "def", "find_packages", "(", "self", ",", "name", ",", "# type: str", "constraint", "=", "None", ",", "# type: Union[VersionConstraint, str, None]", "extras", "=", "None", ",", "# type: Union[list, None]", "allow_prereleases", "=", "False", ",", "# type: bool", ")", ":", "# type: (...) -> List[Package]", "if", "constraint", "is", "None", ":", "constraint", "=", "\"*\"", "if", "not", "isinstance", "(", "constraint", ",", "VersionConstraint", ")", ":", "constraint", "=", "parse_constraint", "(", "constraint", ")", "if", "isinstance", "(", "constraint", ",", "VersionRange", ")", ":", "if", "(", "constraint", ".", "max", "is", "not", "None", "and", "constraint", ".", "max", ".", "is_prerelease", "(", ")", "or", "constraint", ".", "min", "is", "not", "None", "and", "constraint", ".", "min", ".", "is_prerelease", "(", ")", ")", ":", "allow_prereleases", "=", "True", "info", "=", "self", ".", "get_package_info", "(", "name", ")", "packages", "=", "[", "]", "for", "version", ",", "release", "in", "info", "[", "\"releases\"", "]", ".", "items", "(", ")", ":", "if", "not", "release", ":", "# Bad release", "self", ".", "_log", "(", "\"No release information found for {}-{}, skipping\"", ".", "format", "(", "name", ",", "version", ")", ",", "level", "=", "\"debug\"", ",", ")", "continue", "try", ":", "package", "=", "Package", "(", "name", ",", "version", ")", "except", "ParseVersionError", ":", "self", ".", "_log", "(", "'Unable to parse version \"{}\" for the {} package, skipping'", ".", "format", "(", "version", ",", "name", ")", ",", "level", "=", "\"debug\"", ",", ")", "continue", "if", "package", ".", "is_prerelease", "(", ")", "and", "not", "allow_prereleases", ":", "continue", "if", "not", "constraint", "or", "(", "constraint", "and", "constraint", ".", "allows", "(", "package", ".", "version", ")", ")", ":", "if", "extras", "is", "not", "None", ":", "package", ".", "requires_extras", "=", "extras", "packages", ".", "append", "(", "package", ")", "self", ".", "_log", "(", "\"{} packages found for {} {}\"", ".", "format", "(", "len", "(", "packages", ")", ",", "name", ",", "str", "(", "constraint", ")", ")", ",", "level", "=", "\"debug\"", ",", ")", "return", "packages" ]
Find packages on the remote server.
[ "Find", "packages", "on", "the", "remote", "server", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L83-L148
train
sdispater/poetry
poetry/repositories/pypi_repository.py
PyPiRepository.get_package_info
def get_package_info(self, name): # type: (str) -> dict """ Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server. """ if self._disable_cache: return self._get_package_info(name) return self._cache.store("packages").remember_forever( name, lambda: self._get_package_info(name) )
python
def get_package_info(self, name): # type: (str) -> dict """ Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server. """ if self._disable_cache: return self._get_package_info(name) return self._cache.store("packages").remember_forever( name, lambda: self._get_package_info(name) )
[ "def", "get_package_info", "(", "self", ",", "name", ")", ":", "# type: (str) -> dict", "if", "self", ".", "_disable_cache", ":", "return", "self", ".", "_get_package_info", "(", "name", ")", "return", "self", ".", "_cache", ".", "store", "(", "\"packages\"", ")", ".", "remember_forever", "(", "name", ",", "lambda", ":", "self", ".", "_get_package_info", "(", "name", ")", ")" ]
Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server.
[ "Return", "the", "package", "information", "given", "its", "name", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L230-L242
train
sdispater/poetry
poetry/repositories/pypi_repository.py
PyPiRepository.get_release_info
def get_release_info(self, name, version): # type: (str, str) -> dict """ Return the release information given a package name and a version. The information is returned from the cache if it exists or retrieved from the remote server. """ if self._disable_cache: return self._get_release_info(name, version) cached = self._cache.remember_forever( "{}:{}".format(name, version), lambda: self._get_release_info(name, version) ) cache_version = cached.get("_cache_version", "0.0.0") if parse_constraint(cache_version) != self.CACHE_VERSION: # The cache must be updated self._log( "The cache for {} {} is outdated. Refreshing.".format(name, version), level="debug", ) cached = self._get_release_info(name, version) self._cache.forever("{}:{}".format(name, version), cached) return cached
python
def get_release_info(self, name, version): # type: (str, str) -> dict """ Return the release information given a package name and a version. The information is returned from the cache if it exists or retrieved from the remote server. """ if self._disable_cache: return self._get_release_info(name, version) cached = self._cache.remember_forever( "{}:{}".format(name, version), lambda: self._get_release_info(name, version) ) cache_version = cached.get("_cache_version", "0.0.0") if parse_constraint(cache_version) != self.CACHE_VERSION: # The cache must be updated self._log( "The cache for {} {} is outdated. Refreshing.".format(name, version), level="debug", ) cached = self._get_release_info(name, version) self._cache.forever("{}:{}".format(name, version), cached) return cached
[ "def", "get_release_info", "(", "self", ",", "name", ",", "version", ")", ":", "# type: (str, str) -> dict", "if", "self", ".", "_disable_cache", ":", "return", "self", ".", "_get_release_info", "(", "name", ",", "version", ")", "cached", "=", "self", ".", "_cache", ".", "remember_forever", "(", "\"{}:{}\"", ".", "format", "(", "name", ",", "version", ")", ",", "lambda", ":", "self", ".", "_get_release_info", "(", "name", ",", "version", ")", ")", "cache_version", "=", "cached", ".", "get", "(", "\"_cache_version\"", ",", "\"0.0.0\"", ")", "if", "parse_constraint", "(", "cache_version", ")", "!=", "self", ".", "CACHE_VERSION", ":", "# The cache must be updated", "self", ".", "_log", "(", "\"The cache for {} {} is outdated. Refreshing.\"", ".", "format", "(", "name", ",", "version", ")", ",", "level", "=", "\"debug\"", ",", ")", "cached", "=", "self", ".", "_get_release_info", "(", "name", ",", "version", ")", "self", ".", "_cache", ".", "forever", "(", "\"{}:{}\"", ".", "format", "(", "name", ",", "version", ")", ",", "cached", ")", "return", "cached" ]
Return the release information given a package name and a version. The information is returned from the cache if it exists or retrieved from the remote server.
[ "Return", "the", "release", "information", "given", "a", "package", "name", "and", "a", "version", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L251-L276
train
sdispater/poetry
poetry/masonry/builders/wheel.py
WheelBuilder.make
def make(cls, poetry, env, io): """Build a wheel in the dist/ directory, and optionally upload it.""" cls.make_in(poetry, env, io)
python
def make(cls, poetry, env, io): """Build a wheel in the dist/ directory, and optionally upload it.""" cls.make_in(poetry, env, io)
[ "def", "make", "(", "cls", ",", "poetry", ",", "env", ",", "io", ")", ":", "cls", ".", "make_in", "(", "poetry", ",", "env", ",", "io", ")" ]
Build a wheel in the dist/ directory, and optionally upload it.
[ "Build", "a", "wheel", "in", "the", "dist", "/", "directory", "and", "optionally", "upload", "it", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/wheel.py#L55-L57
train
sdispater/poetry
poetry/masonry/builders/wheel.py
WheelBuilder._write_entry_points
def _write_entry_points(self, fp): """ Write entry_points.txt. """ entry_points = self.convert_entry_points() for group_name in sorted(entry_points): fp.write("[{}]\n".format(group_name)) for ep in sorted(entry_points[group_name]): fp.write(ep.replace(" ", "") + "\n") fp.write("\n")
python
def _write_entry_points(self, fp): """ Write entry_points.txt. """ entry_points = self.convert_entry_points() for group_name in sorted(entry_points): fp.write("[{}]\n".format(group_name)) for ep in sorted(entry_points[group_name]): fp.write(ep.replace(" ", "") + "\n") fp.write("\n")
[ "def", "_write_entry_points", "(", "self", ",", "fp", ")", ":", "entry_points", "=", "self", ".", "convert_entry_points", "(", ")", "for", "group_name", "in", "sorted", "(", "entry_points", ")", ":", "fp", ".", "write", "(", "\"[{}]\\n\"", ".", "format", "(", "group_name", ")", ")", "for", "ep", "in", "sorted", "(", "entry_points", "[", "group_name", "]", ")", ":", "fp", ".", "write", "(", "ep", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "+", "\"\\n\"", ")", "fp", ".", "write", "(", "\"\\n\"", ")" ]
Write entry_points.txt.
[ "Write", "entry_points", ".", "txt", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/wheel.py#L288-L299
train
sdispater/poetry
poetry/utils/appdirs.py
_get_win_folder_from_registry
def _get_win_folder_from_registry(csidl_name): """ This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", ) directory, _type = _winreg.QueryValueEx(key, shell_folder_name) return directory
python
def _get_win_folder_from_registry(csidl_name): """ This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", ) directory, _type = _winreg.QueryValueEx(key, shell_folder_name) return directory
[ "def", "_get_win_folder_from_registry", "(", "csidl_name", ")", ":", "import", "_winreg", "shell_folder_name", "=", "{", "\"CSIDL_APPDATA\"", ":", "\"AppData\"", ",", "\"CSIDL_COMMON_APPDATA\"", ":", "\"Common AppData\"", ",", "\"CSIDL_LOCAL_APPDATA\"", ":", "\"Local AppData\"", ",", "}", "[", "csidl_name", "]", "key", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_CURRENT_USER", ",", "r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"", ",", ")", "directory", ",", "_type", "=", "_winreg", ".", "QueryValueEx", "(", "key", ",", "shell_folder_name", ")", "return", "directory" ]
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
[ "This", "is", "a", "fallback", "technique", "at", "best", ".", "I", "m", "not", "sure", "if", "using", "the", "registry", "for", "this", "guarantees", "us", "the", "correct", "answer", "for", "all", "CSIDL_", "*", "names", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/utils/appdirs.py#L180-L199
train
sdispater/poetry
poetry/installation/installer.py
Installer.lock
def lock(self): # type: () -> Installer """ Prepare the installer for locking only. """ self.update() self.execute_operations(False) self._lock = True return self
python
def lock(self): # type: () -> Installer """ Prepare the installer for locking only. """ self.update() self.execute_operations(False) self._lock = True return self
[ "def", "lock", "(", "self", ")", ":", "# type: () -> Installer", "self", ".", "update", "(", ")", "self", ".", "execute_operations", "(", "False", ")", "self", ".", "_lock", "=", "True", "return", "self" ]
Prepare the installer for locking only.
[ "Prepare", "the", "installer", "for", "locking", "only", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L111-L119
train
sdispater/poetry
poetry/installation/installer.py
Installer._execute
def _execute(self, operation): # type: (Operation) -> None """ Execute a given operation. """ method = operation.job_type getattr(self, "_execute_{}".format(method))(operation)
python
def _execute(self, operation): # type: (Operation) -> None """ Execute a given operation. """ method = operation.job_type getattr(self, "_execute_{}".format(method))(operation)
[ "def", "_execute", "(", "self", ",", "operation", ")", ":", "# type: (Operation) -> None", "method", "=", "operation", ".", "job_type", "getattr", "(", "self", ",", "\"_execute_{}\"", ".", "format", "(", "method", ")", ")", "(", "operation", ")" ]
Execute a given operation.
[ "Execute", "a", "given", "operation", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L300-L306
train
sdispater/poetry
poetry/installation/installer.py
Installer._get_extra_packages
def _get_extra_packages(self, repo): """ Returns all packages required by extras. Maybe we just let the solver handle it? """ if self._update: extras = {k: [d.name for d in v] for k, v in self._package.extras.items()} else: extras = self._locker.lock_data.get("extras", {}) extra_packages = [] for extra_name, packages in extras.items(): if extra_name not in self._extras: continue extra_packages += [Dependency(p, "*") for p in packages] def _extra_packages(packages): pkgs = [] for package in packages: for pkg in repo.packages: if pkg.name == package.name: pkgs.append(package) pkgs += _extra_packages(pkg.requires) break return pkgs return _extra_packages(extra_packages)
python
def _get_extra_packages(self, repo): """ Returns all packages required by extras. Maybe we just let the solver handle it? """ if self._update: extras = {k: [d.name for d in v] for k, v in self._package.extras.items()} else: extras = self._locker.lock_data.get("extras", {}) extra_packages = [] for extra_name, packages in extras.items(): if extra_name not in self._extras: continue extra_packages += [Dependency(p, "*") for p in packages] def _extra_packages(packages): pkgs = [] for package in packages: for pkg in repo.packages: if pkg.name == package.name: pkgs.append(package) pkgs += _extra_packages(pkg.requires) break return pkgs return _extra_packages(extra_packages)
[ "def", "_get_extra_packages", "(", "self", ",", "repo", ")", ":", "if", "self", ".", "_update", ":", "extras", "=", "{", "k", ":", "[", "d", ".", "name", "for", "d", "in", "v", "]", "for", "k", ",", "v", "in", "self", ".", "_package", ".", "extras", ".", "items", "(", ")", "}", "else", ":", "extras", "=", "self", ".", "_locker", ".", "lock_data", ".", "get", "(", "\"extras\"", ",", "{", "}", ")", "extra_packages", "=", "[", "]", "for", "extra_name", ",", "packages", "in", "extras", ".", "items", "(", ")", ":", "if", "extra_name", "not", "in", "self", ".", "_extras", ":", "continue", "extra_packages", "+=", "[", "Dependency", "(", "p", ",", "\"*\"", ")", "for", "p", "in", "packages", "]", "def", "_extra_packages", "(", "packages", ")", ":", "pkgs", "=", "[", "]", "for", "package", "in", "packages", ":", "for", "pkg", "in", "repo", ".", "packages", ":", "if", "pkg", ".", "name", "==", "package", ".", "name", ":", "pkgs", ".", "append", "(", "package", ")", "pkgs", "+=", "_extra_packages", "(", "pkg", ".", "requires", ")", "break", "return", "pkgs", "return", "_extra_packages", "(", "extra_packages", ")" ]
Returns all packages required by extras. Maybe we just let the solver handle it?
[ "Returns", "all", "packages", "required", "by", "extras", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L480-L510
train
spotify/luigi
luigi/tools/luigi_grep.py
LuigiGrep._fetch_json
def _fetch_json(self): """Returns the json representation of the dep graph""" print("Fetching from url: " + self.graph_url) resp = urlopen(self.graph_url).read() return json.loads(resp.decode('utf-8'))
python
def _fetch_json(self): """Returns the json representation of the dep graph""" print("Fetching from url: " + self.graph_url) resp = urlopen(self.graph_url).read() return json.loads(resp.decode('utf-8'))
[ "def", "_fetch_json", "(", "self", ")", ":", "print", "(", "\"Fetching from url: \"", "+", "self", ".", "graph_url", ")", "resp", "=", "urlopen", "(", "self", ".", "graph_url", ")", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "resp", ".", "decode", "(", "'utf-8'", ")", ")" ]
Returns the json representation of the dep graph
[ "Returns", "the", "json", "representation", "of", "the", "dep", "graph" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L21-L25
train
spotify/luigi
luigi/tools/luigi_grep.py
LuigiGrep.prefix_search
def prefix_search(self, job_name_prefix): """Searches for jobs matching the given ``job_name_prefix``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: if job.startswith(job_name_prefix): yield self._build_results(jobs, job)
python
def prefix_search(self, job_name_prefix): """Searches for jobs matching the given ``job_name_prefix``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: if job.startswith(job_name_prefix): yield self._build_results(jobs, job)
[ "def", "prefix_search", "(", "self", ",", "job_name_prefix", ")", ":", "json", "=", "self", ".", "_fetch_json", "(", ")", "jobs", "=", "json", "[", "'response'", "]", "for", "job", "in", "jobs", ":", "if", "job", ".", "startswith", "(", "job_name_prefix", ")", ":", "yield", "self", ".", "_build_results", "(", "jobs", ",", "job", ")" ]
Searches for jobs matching the given ``job_name_prefix``.
[ "Searches", "for", "jobs", "matching", "the", "given", "job_name_prefix", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L38-L44
train
spotify/luigi
luigi/tools/luigi_grep.py
LuigiGrep.status_search
def status_search(self, status): """Searches for jobs matching the given ``status``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: job_info = jobs[job] if job_info['status'].lower() == status.lower(): yield self._build_results(jobs, job)
python
def status_search(self, status): """Searches for jobs matching the given ``status``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: job_info = jobs[job] if job_info['status'].lower() == status.lower(): yield self._build_results(jobs, job)
[ "def", "status_search", "(", "self", ",", "status", ")", ":", "json", "=", "self", ".", "_fetch_json", "(", ")", "jobs", "=", "json", "[", "'response'", "]", "for", "job", "in", "jobs", ":", "job_info", "=", "jobs", "[", "job", "]", "if", "job_info", "[", "'status'", "]", ".", "lower", "(", ")", "==", "status", ".", "lower", "(", ")", ":", "yield", "self", ".", "_build_results", "(", "jobs", ",", "job", ")" ]
Searches for jobs matching the given ``status``.
[ "Searches", "for", "jobs", "matching", "the", "given", "status", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L46-L53
train
spotify/luigi
luigi/local_target.py
LocalFileSystem.move
def move(self, old_path, new_path, raise_if_exists=False): """ Move file atomically. If source and destination are located on different filesystems, atomicity is approximated but cannot be guaranteed. """ if raise_if_exists and os.path.exists(new_path): raise FileAlreadyExists('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.mkdir(d) try: os.rename(old_path, new_path) except OSError as err: if err.errno == errno.EXDEV: new_path_tmp = '%s-%09d' % (new_path, random.randint(0, 999999999)) shutil.copy(old_path, new_path_tmp) os.rename(new_path_tmp, new_path) os.remove(old_path) else: raise err
python
def move(self, old_path, new_path, raise_if_exists=False): """ Move file atomically. If source and destination are located on different filesystems, atomicity is approximated but cannot be guaranteed. """ if raise_if_exists and os.path.exists(new_path): raise FileAlreadyExists('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.mkdir(d) try: os.rename(old_path, new_path) except OSError as err: if err.errno == errno.EXDEV: new_path_tmp = '%s-%09d' % (new_path, random.randint(0, 999999999)) shutil.copy(old_path, new_path_tmp) os.rename(new_path_tmp, new_path) os.remove(old_path) else: raise err
[ "def", "move", "(", "self", ",", "old_path", ",", "new_path", ",", "raise_if_exists", "=", "False", ")", ":", "if", "raise_if_exists", "and", "os", ".", "path", ".", "exists", "(", "new_path", ")", ":", "raise", "FileAlreadyExists", "(", "'Destination exists: %s'", "%", "new_path", ")", "d", "=", "os", ".", "path", ".", "dirname", "(", "new_path", ")", "if", "d", "and", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "self", ".", "mkdir", "(", "d", ")", "try", ":", "os", ".", "rename", "(", "old_path", ",", "new_path", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "EXDEV", ":", "new_path_tmp", "=", "'%s-%09d'", "%", "(", "new_path", ",", "random", ".", "randint", "(", "0", ",", "999999999", ")", ")", "shutil", ".", "copy", "(", "old_path", ",", "new_path_tmp", ")", "os", ".", "rename", "(", "new_path_tmp", ",", "new_path", ")", "os", ".", "remove", "(", "old_path", ")", "else", ":", "raise", "err" ]
Move file atomically. If source and destination are located on different filesystems, atomicity is approximated but cannot be guaranteed.
[ "Move", "file", "atomically", ".", "If", "source", "and", "destination", "are", "located", "on", "different", "filesystems", "atomicity", "is", "approximated", "but", "cannot", "be", "guaranteed", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/local_target.py#L100-L120
train
spotify/luigi
luigi/local_target.py
LocalFileSystem.rename_dont_move
def rename_dont_move(self, path, dest): """ Rename ``path`` to ``dest``, but don't move it into the ``dest`` folder (if it is a folder). This method is just a wrapper around the ``move`` method of LocalTarget. """ self.move(path, dest, raise_if_exists=True)
python
def rename_dont_move(self, path, dest): """ Rename ``path`` to ``dest``, but don't move it into the ``dest`` folder (if it is a folder). This method is just a wrapper around the ``move`` method of LocalTarget. """ self.move(path, dest, raise_if_exists=True)
[ "def", "rename_dont_move", "(", "self", ",", "path", ",", "dest", ")", ":", "self", ".", "move", "(", "path", ",", "dest", ",", "raise_if_exists", "=", "True", ")" ]
Rename ``path`` to ``dest``, but don't move it into the ``dest`` folder (if it is a folder). This method is just a wrapper around the ``move`` method of LocalTarget.
[ "Rename", "path", "to", "dest", "but", "don", "t", "move", "it", "into", "the", "dest", "folder", "(", "if", "it", "is", "a", "folder", ")", ".", "This", "method", "is", "just", "a", "wrapper", "around", "the", "move", "method", "of", "LocalTarget", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/local_target.py#L122-L128
train
spotify/luigi
luigi/local_target.py
LocalTarget.makedirs
def makedirs(self): """ Create all parent folders if they do not exist. """ normpath = os.path.normpath(self.path) parentfolder = os.path.dirname(normpath) if parentfolder: try: os.makedirs(parentfolder) except OSError: pass
python
def makedirs(self): """ Create all parent folders if they do not exist. """ normpath = os.path.normpath(self.path) parentfolder = os.path.dirname(normpath) if parentfolder: try: os.makedirs(parentfolder) except OSError: pass
[ "def", "makedirs", "(", "self", ")", ":", "normpath", "=", "os", ".", "path", ".", "normpath", "(", "self", ".", "path", ")", "parentfolder", "=", "os", ".", "path", ".", "dirname", "(", "normpath", ")", "if", "parentfolder", ":", "try", ":", "os", ".", "makedirs", "(", "parentfolder", ")", "except", "OSError", ":", "pass" ]
Create all parent folders if they do not exist.
[ "Create", "all", "parent", "folders", "if", "they", "do", "not", "exist", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/local_target.py#L146-L156
train
spotify/luigi
luigi/contrib/lsf.py
track_job
def track_job(job_id): """ Tracking is done by requesting each job and then searching for whether the job has one of the following states: - "RUN", - "PEND", - "SSUSP", - "EXIT" based on the LSF documentation """ cmd = "bjobs -noheader -o stat {}".format(job_id) track_job_proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, shell=True) status = track_job_proc.communicate()[0].strip('\n') return status
python
def track_job(job_id): """ Tracking is done by requesting each job and then searching for whether the job has one of the following states: - "RUN", - "PEND", - "SSUSP", - "EXIT" based on the LSF documentation """ cmd = "bjobs -noheader -o stat {}".format(job_id) track_job_proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, shell=True) status = track_job_proc.communicate()[0].strip('\n') return status
[ "def", "track_job", "(", "job_id", ")", ":", "cmd", "=", "\"bjobs -noheader -o stat {}\"", ".", "format", "(", "job_id", ")", "track_job_proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "status", "=", "track_job_proc", ".", "communicate", "(", ")", "[", "0", "]", ".", "strip", "(", "'\\n'", ")", "return", "status" ]
Tracking is done by requesting each job and then searching for whether the job has one of the following states: - "RUN", - "PEND", - "SSUSP", - "EXIT" based on the LSF documentation
[ "Tracking", "is", "done", "by", "requesting", "each", "job", "and", "then", "searching", "for", "whether", "the", "job", "has", "one", "of", "the", "following", "states", ":", "-", "RUN", "-", "PEND", "-", "SSUSP", "-", "EXIT", "based", "on", "the", "LSF", "documentation" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L74-L88
train
spotify/luigi
luigi/contrib/lsf.py
LSFJobTask.fetch_task_failures
def fetch_task_failures(self): """ Read in the error file from bsub """ error_file = os.path.join(self.tmp_dir, "job.err") if os.path.isfile(error_file): with open(error_file, "r") as f_err: errors = f_err.readlines() else: errors = '' return errors
python
def fetch_task_failures(self): """ Read in the error file from bsub """ error_file = os.path.join(self.tmp_dir, "job.err") if os.path.isfile(error_file): with open(error_file, "r") as f_err: errors = f_err.readlines() else: errors = '' return errors
[ "def", "fetch_task_failures", "(", "self", ")", ":", "error_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_dir", ",", "\"job.err\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "error_file", ")", ":", "with", "open", "(", "error_file", ",", "\"r\"", ")", "as", "f_err", ":", "errors", "=", "f_err", ".", "readlines", "(", ")", "else", ":", "errors", "=", "''", "return", "errors" ]
Read in the error file from bsub
[ "Read", "in", "the", "error", "file", "from", "bsub" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L119-L129
train
spotify/luigi
luigi/contrib/lsf.py
LSFJobTask.fetch_task_output
def fetch_task_output(self): """ Read in the output file """ # Read in the output file if os.path.isfile(os.path.join(self.tmp_dir, "job.out")): with open(os.path.join(self.tmp_dir, "job.out"), "r") as f_out: outputs = f_out.readlines() else: outputs = '' return outputs
python
def fetch_task_output(self): """ Read in the output file """ # Read in the output file if os.path.isfile(os.path.join(self.tmp_dir, "job.out")): with open(os.path.join(self.tmp_dir, "job.out"), "r") as f_out: outputs = f_out.readlines() else: outputs = '' return outputs
[ "def", "fetch_task_output", "(", "self", ")", ":", "# Read in the output file", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_dir", ",", "\"job.out\"", ")", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_dir", ",", "\"job.out\"", ")", ",", "\"r\"", ")", "as", "f_out", ":", "outputs", "=", "f_out", ".", "readlines", "(", ")", "else", ":", "outputs", "=", "''", "return", "outputs" ]
Read in the output file
[ "Read", "in", "the", "output", "file" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L131-L141
train
spotify/luigi
luigi/contrib/lsf.py
LSFJobTask._run_job
def _run_job(self): """ Build a bsub argument that will run lsf_runner.py on the directory we've specified. """ args = [] if isinstance(self.output(), list): log_output = os.path.split(self.output()[0].path) else: log_output = os.path.split(self.output().path) args += ["bsub", "-q", self.queue_flag] args += ["-n", str(self.n_cpu_flag)] args += ["-M", str(self.memory_flag)] args += ["-R", "rusage[%s]" % self.resource_flag] args += ["-W", str(self.runtime_flag)] if self.job_name_flag: args += ["-J", str(self.job_name_flag)] args += ["-o", os.path.join(log_output[0], "job.out")] args += ["-e", os.path.join(log_output[0], "job.err")] if self.extra_bsub_args: args += self.extra_bsub_args.split() # Find where the runner file is runner_path = os.path.abspath(lsf_runner.__file__) args += [runner_path] args += [self.tmp_dir] # That should do it. Let the world know what we're doing. LOGGER.info("### LSF SUBMISSION ARGS: %s", " ".join([str(a) for a in args])) # Submit the job run_job_proc = subprocess.Popen( [str(a) for a in args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmp_dir) output = run_job_proc.communicate()[0] # ASSUMPTION # The result will be of the format # Job <123> is submitted ot queue <myqueue> # So get the number in those first brackets. # I cannot think of a better workaround that leaves logic on the Task side of things. LOGGER.info("### JOB SUBMISSION OUTPUT: %s", str(output)) self.job_id = int(output.split("<")[1].split(">")[0]) LOGGER.info( "Job %ssubmitted as job %s", self.job_name_flag + ' ', str(self.job_id) ) self._track_job() # If we want to save the job temporaries, then do so # We'll move them to be next to the job output if self.save_job_info: LOGGER.info("Saving up temporary bits") # dest_dir = self.output().path shutil.move(self.tmp_dir, "/".join(log_output[0:-1])) # Now delete the temporaries, if they're there. self._finish()
python
def _run_job(self): """ Build a bsub argument that will run lsf_runner.py on the directory we've specified. """ args = [] if isinstance(self.output(), list): log_output = os.path.split(self.output()[0].path) else: log_output = os.path.split(self.output().path) args += ["bsub", "-q", self.queue_flag] args += ["-n", str(self.n_cpu_flag)] args += ["-M", str(self.memory_flag)] args += ["-R", "rusage[%s]" % self.resource_flag] args += ["-W", str(self.runtime_flag)] if self.job_name_flag: args += ["-J", str(self.job_name_flag)] args += ["-o", os.path.join(log_output[0], "job.out")] args += ["-e", os.path.join(log_output[0], "job.err")] if self.extra_bsub_args: args += self.extra_bsub_args.split() # Find where the runner file is runner_path = os.path.abspath(lsf_runner.__file__) args += [runner_path] args += [self.tmp_dir] # That should do it. Let the world know what we're doing. LOGGER.info("### LSF SUBMISSION ARGS: %s", " ".join([str(a) for a in args])) # Submit the job run_job_proc = subprocess.Popen( [str(a) for a in args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmp_dir) output = run_job_proc.communicate()[0] # ASSUMPTION # The result will be of the format # Job <123> is submitted ot queue <myqueue> # So get the number in those first brackets. # I cannot think of a better workaround that leaves logic on the Task side of things. LOGGER.info("### JOB SUBMISSION OUTPUT: %s", str(output)) self.job_id = int(output.split("<")[1].split(">")[0]) LOGGER.info( "Job %ssubmitted as job %s", self.job_name_flag + ' ', str(self.job_id) ) self._track_job() # If we want to save the job temporaries, then do so # We'll move them to be next to the job output if self.save_job_info: LOGGER.info("Saving up temporary bits") # dest_dir = self.output().path shutil.move(self.tmp_dir, "/".join(log_output[0:-1])) # Now delete the temporaries, if they're there. self._finish()
[ "def", "_run_job", "(", "self", ")", ":", "args", "=", "[", "]", "if", "isinstance", "(", "self", ".", "output", "(", ")", ",", "list", ")", ":", "log_output", "=", "os", ".", "path", ".", "split", "(", "self", ".", "output", "(", ")", "[", "0", "]", ".", "path", ")", "else", ":", "log_output", "=", "os", ".", "path", ".", "split", "(", "self", ".", "output", "(", ")", ".", "path", ")", "args", "+=", "[", "\"bsub\"", ",", "\"-q\"", ",", "self", ".", "queue_flag", "]", "args", "+=", "[", "\"-n\"", ",", "str", "(", "self", ".", "n_cpu_flag", ")", "]", "args", "+=", "[", "\"-M\"", ",", "str", "(", "self", ".", "memory_flag", ")", "]", "args", "+=", "[", "\"-R\"", ",", "\"rusage[%s]\"", "%", "self", ".", "resource_flag", "]", "args", "+=", "[", "\"-W\"", ",", "str", "(", "self", ".", "runtime_flag", ")", "]", "if", "self", ".", "job_name_flag", ":", "args", "+=", "[", "\"-J\"", ",", "str", "(", "self", ".", "job_name_flag", ")", "]", "args", "+=", "[", "\"-o\"", ",", "os", ".", "path", ".", "join", "(", "log_output", "[", "0", "]", ",", "\"job.out\"", ")", "]", "args", "+=", "[", "\"-e\"", ",", "os", ".", "path", ".", "join", "(", "log_output", "[", "0", "]", ",", "\"job.err\"", ")", "]", "if", "self", ".", "extra_bsub_args", ":", "args", "+=", "self", ".", "extra_bsub_args", ".", "split", "(", ")", "# Find where the runner file is", "runner_path", "=", "os", ".", "path", ".", "abspath", "(", "lsf_runner", ".", "__file__", ")", "args", "+=", "[", "runner_path", "]", "args", "+=", "[", "self", ".", "tmp_dir", "]", "# That should do it. Let the world know what we're doing.", "LOGGER", ".", "info", "(", "\"### LSF SUBMISSION ARGS: %s\"", ",", "\" \"", ".", "join", "(", "[", "str", "(", "a", ")", "for", "a", "in", "args", "]", ")", ")", "# Submit the job", "run_job_proc", "=", "subprocess", ".", "Popen", "(", "[", "str", "(", "a", ")", "for", "a", "in", "args", "]", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "self", ".", "tmp_dir", ")", "output", "=", "run_job_proc", ".", "communicate", "(", ")", "[", "0", "]", "# ASSUMPTION", "# The result will be of the format", "# Job <123> is submitted ot queue <myqueue>", "# So get the number in those first brackets.", "# I cannot think of a better workaround that leaves logic on the Task side of things.", "LOGGER", ".", "info", "(", "\"### JOB SUBMISSION OUTPUT: %s\"", ",", "str", "(", "output", ")", ")", "self", ".", "job_id", "=", "int", "(", "output", ".", "split", "(", "\"<\"", ")", "[", "1", "]", ".", "split", "(", "\">\"", ")", "[", "0", "]", ")", "LOGGER", ".", "info", "(", "\"Job %ssubmitted as job %s\"", ",", "self", ".", "job_name_flag", "+", "' '", ",", "str", "(", "self", ".", "job_id", ")", ")", "self", ".", "_track_job", "(", ")", "# If we want to save the job temporaries, then do so", "# We'll move them to be next to the job output", "if", "self", ".", "save_job_info", ":", "LOGGER", ".", "info", "(", "\"Saving up temporary bits\"", ")", "# dest_dir = self.output().path", "shutil", ".", "move", "(", "self", ".", "tmp_dir", ",", "\"/\"", ".", "join", "(", "log_output", "[", "0", ":", "-", "1", "]", ")", ")", "# Now delete the temporaries, if they're there.", "self", ".", "_finish", "(", ")" ]
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
[ "Build", "a", "bsub", "argument", "that", "will", "run", "lsf_runner", ".", "py", "on", "the", "directory", "we", "ve", "specified", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L219-L283
train
spotify/luigi
examples/spark_als.py
UserItemMatrix.run
def run(self): """ Generates :py:attr:`~.UserItemMatrix.data_size` elements. Writes this data in \\ separated value format into the target :py:func:`~/.UserItemMatrix.output`. The data has the following elements: * `user` is the default Elasticsearch id field, * `track`: the text, * `rating`: the day when the data was created. """ w = self.output().open('w') for user in range(self.data_size): track = int(random.random() * self.data_size) w.write('%d\\%d\\%f' % (user, track, 1.0)) w.close()
python
def run(self): """ Generates :py:attr:`~.UserItemMatrix.data_size` elements. Writes this data in \\ separated value format into the target :py:func:`~/.UserItemMatrix.output`. The data has the following elements: * `user` is the default Elasticsearch id field, * `track`: the text, * `rating`: the day when the data was created. """ w = self.output().open('w') for user in range(self.data_size): track = int(random.random() * self.data_size) w.write('%d\\%d\\%f' % (user, track, 1.0)) w.close()
[ "def", "run", "(", "self", ")", ":", "w", "=", "self", ".", "output", "(", ")", ".", "open", "(", "'w'", ")", "for", "user", "in", "range", "(", "self", ".", "data_size", ")", ":", "track", "=", "int", "(", "random", ".", "random", "(", ")", "*", "self", ".", "data_size", ")", "w", ".", "write", "(", "'%d\\\\%d\\\\%f'", "%", "(", "user", ",", "track", ",", "1.0", ")", ")", "w", ".", "close", "(", ")" ]
Generates :py:attr:`~.UserItemMatrix.data_size` elements. Writes this data in \\ separated value format into the target :py:func:`~/.UserItemMatrix.output`. The data has the following elements: * `user` is the default Elasticsearch id field, * `track`: the text, * `rating`: the day when the data was created.
[ "Generates", ":", "py", ":", "attr", ":", "~", ".", "UserItemMatrix", ".", "data_size", "elements", ".", "Writes", "this", "data", "in", "\\\\", "separated", "value", "format", "into", "the", "target", ":", "py", ":", "func", ":", "~", "/", ".", "UserItemMatrix", ".", "output", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/spark_als.py#L31-L47
train
spotify/luigi
examples/spark_als.py
UserItemMatrix.output
def output(self): """ Returns the target output for this task. In this case, a successful execution of this task will create a file in HDFS. :return: the target output for this task. :rtype: object (:py:class:`~luigi.target.Target`) """ return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip)
python
def output(self): """ Returns the target output for this task. In this case, a successful execution of this task will create a file in HDFS. :return: the target output for this task. :rtype: object (:py:class:`~luigi.target.Target`) """ return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip)
[ "def", "output", "(", "self", ")", ":", "return", "luigi", ".", "contrib", ".", "hdfs", ".", "HdfsTarget", "(", "'data-matrix'", ",", "format", "=", "luigi", ".", "format", ".", "Gzip", ")" ]
Returns the target output for this task. In this case, a successful execution of this task will create a file in HDFS. :return: the target output for this task. :rtype: object (:py:class:`~luigi.target.Target`)
[ "Returns", "the", "target", "output", "for", "this", "task", ".", "In", "this", "case", "a", "successful", "execution", "of", "this", "task", "will", "create", "a", "file", "in", "HDFS", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/spark_als.py#L49-L57
train
spotify/luigi
luigi/server.py
from_utc
def from_utc(utcTime, fmt=None): """convert UTC time string to time.struct_time: change datetime.datetime to time, return time.struct_time type""" if fmt is None: try_formats = ["%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"] else: try_formats = [fmt] for fmt in try_formats: try: time_struct = datetime.datetime.strptime(utcTime, fmt) except ValueError: pass else: date = int(time.mktime(time_struct.timetuple())) return date else: raise ValueError("No UTC format matches {}".format(utcTime))
python
def from_utc(utcTime, fmt=None): """convert UTC time string to time.struct_time: change datetime.datetime to time, return time.struct_time type""" if fmt is None: try_formats = ["%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"] else: try_formats = [fmt] for fmt in try_formats: try: time_struct = datetime.datetime.strptime(utcTime, fmt) except ValueError: pass else: date = int(time.mktime(time_struct.timetuple())) return date else: raise ValueError("No UTC format matches {}".format(utcTime))
[ "def", "from_utc", "(", "utcTime", ",", "fmt", "=", "None", ")", ":", "if", "fmt", "is", "None", ":", "try_formats", "=", "[", "\"%Y-%m-%d %H:%M:%S.%f\"", ",", "\"%Y-%m-%d %H:%M:%S\"", "]", "else", ":", "try_formats", "=", "[", "fmt", "]", "for", "fmt", "in", "try_formats", ":", "try", ":", "time_struct", "=", "datetime", ".", "datetime", ".", "strptime", "(", "utcTime", ",", "fmt", ")", "except", "ValueError", ":", "pass", "else", ":", "date", "=", "int", "(", "time", ".", "mktime", "(", "time_struct", ".", "timetuple", "(", ")", ")", ")", "return", "date", "else", ":", "raise", "ValueError", "(", "\"No UTC format matches {}\"", ".", "format", "(", "utcTime", ")", ")" ]
convert UTC time string to time.struct_time: change datetime.datetime to time, return time.struct_time type
[ "convert", "UTC", "time", "string", "to", "time", ".", "struct_time", ":", "change", "datetime", ".", "datetime", "to", "time", "return", "time", ".", "struct_time", "type" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/server.py#L228-L244
train
spotify/luigi
luigi/server.py
run
def run(api_port=8082, address=None, unix_socket=None, scheduler=None): """ Runs one instance of the API server. """ if scheduler is None: scheduler = Scheduler() # load scheduler state scheduler.load() _init_api( scheduler=scheduler, api_port=api_port, address=address, unix_socket=unix_socket, ) # prune work DAG every 60 seconds pruner = tornado.ioloop.PeriodicCallback(scheduler.prune, 60000) pruner.start() def shutdown_handler(signum, frame): exit_handler() sys.exit(0) @atexit.register def exit_handler(): logger.info("Scheduler instance shutting down") scheduler.dump() stop() signal.signal(signal.SIGINT, shutdown_handler) signal.signal(signal.SIGTERM, shutdown_handler) if os.name == 'nt': signal.signal(signal.SIGBREAK, shutdown_handler) else: signal.signal(signal.SIGQUIT, shutdown_handler) logger.info("Scheduler starting up") tornado.ioloop.IOLoop.instance().start()
python
def run(api_port=8082, address=None, unix_socket=None, scheduler=None): """ Runs one instance of the API server. """ if scheduler is None: scheduler = Scheduler() # load scheduler state scheduler.load() _init_api( scheduler=scheduler, api_port=api_port, address=address, unix_socket=unix_socket, ) # prune work DAG every 60 seconds pruner = tornado.ioloop.PeriodicCallback(scheduler.prune, 60000) pruner.start() def shutdown_handler(signum, frame): exit_handler() sys.exit(0) @atexit.register def exit_handler(): logger.info("Scheduler instance shutting down") scheduler.dump() stop() signal.signal(signal.SIGINT, shutdown_handler) signal.signal(signal.SIGTERM, shutdown_handler) if os.name == 'nt': signal.signal(signal.SIGBREAK, shutdown_handler) else: signal.signal(signal.SIGQUIT, shutdown_handler) logger.info("Scheduler starting up") tornado.ioloop.IOLoop.instance().start()
[ "def", "run", "(", "api_port", "=", "8082", ",", "address", "=", "None", ",", "unix_socket", "=", "None", ",", "scheduler", "=", "None", ")", ":", "if", "scheduler", "is", "None", ":", "scheduler", "=", "Scheduler", "(", ")", "# load scheduler state", "scheduler", ".", "load", "(", ")", "_init_api", "(", "scheduler", "=", "scheduler", ",", "api_port", "=", "api_port", ",", "address", "=", "address", ",", "unix_socket", "=", "unix_socket", ",", ")", "# prune work DAG every 60 seconds", "pruner", "=", "tornado", ".", "ioloop", ".", "PeriodicCallback", "(", "scheduler", ".", "prune", ",", "60000", ")", "pruner", ".", "start", "(", ")", "def", "shutdown_handler", "(", "signum", ",", "frame", ")", ":", "exit_handler", "(", ")", "sys", ".", "exit", "(", "0", ")", "@", "atexit", ".", "register", "def", "exit_handler", "(", ")", ":", "logger", ".", "info", "(", "\"Scheduler instance shutting down\"", ")", "scheduler", ".", "dump", "(", ")", "stop", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "shutdown_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "shutdown_handler", ")", "if", "os", ".", "name", "==", "'nt'", ":", "signal", ".", "signal", "(", "signal", ".", "SIGBREAK", ",", "shutdown_handler", ")", "else", ":", "signal", ".", "signal", "(", "signal", ".", "SIGQUIT", ",", "shutdown_handler", ")", "logger", ".", "info", "(", "\"Scheduler starting up\"", ")", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "start", "(", ")" ]
Runs one instance of the API server.
[ "Runs", "one", "instance", "of", "the", "API", "server", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/server.py#L322-L362
train
spotify/luigi
luigi/contrib/salesforce.py
get_soql_fields
def get_soql_fields(soql): """ Gets queried columns names. """ soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE) # get fields soql_fields = re.sub(' ', '', soql_fields.group()) # remove extra spaces soql_fields = re.sub('\t', '', soql_fields) # remove tabs fields = re.split(',|\n|\r|', soql_fields) # split on commas and newlines fields = [field for field in fields if field != ''] # remove empty strings return fields
python
def get_soql_fields(soql): """ Gets queried columns names. """ soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE) # get fields soql_fields = re.sub(' ', '', soql_fields.group()) # remove extra spaces soql_fields = re.sub('\t', '', soql_fields) # remove tabs fields = re.split(',|\n|\r|', soql_fields) # split on commas and newlines fields = [field for field in fields if field != ''] # remove empty strings return fields
[ "def", "get_soql_fields", "(", "soql", ")", ":", "soql_fields", "=", "re", ".", "search", "(", "'(?<=select)(?s)(.*)(?=from)'", ",", "soql", ",", "re", ".", "IGNORECASE", ")", "# get fields", "soql_fields", "=", "re", ".", "sub", "(", "' '", ",", "''", ",", "soql_fields", ".", "group", "(", ")", ")", "# remove extra spaces", "soql_fields", "=", "re", ".", "sub", "(", "'\\t'", ",", "''", ",", "soql_fields", ")", "# remove tabs", "fields", "=", "re", ".", "split", "(", "',|\\n|\\r|'", ",", "soql_fields", ")", "# split on commas and newlines", "fields", "=", "[", "field", "for", "field", "in", "fields", "if", "field", "!=", "''", "]", "# remove empty strings", "return", "fields" ]
Gets queried columns names.
[ "Gets", "queried", "columns", "names", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L43-L52
train
spotify/luigi
luigi/contrib/salesforce.py
parse_results
def parse_results(fields, data): """ Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data """ master = [] for record in data['records']: # for each 'record' in response row = [None] * len(fields) # create null list the length of number of columns for obj, value in record.iteritems(): # for each obj in record if not isinstance(value, (dict, list, tuple)): # if not data structure if obj in fields: row[fields.index(obj)] = ensure_utf(value) elif isinstance(value, dict) and obj != 'attributes': # traverse down into object path = obj _traverse_results(value, fields, row, path) master.append(row) return master
python
def parse_results(fields, data): """ Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data """ master = [] for record in data['records']: # for each 'record' in response row = [None] * len(fields) # create null list the length of number of columns for obj, value in record.iteritems(): # for each obj in record if not isinstance(value, (dict, list, tuple)): # if not data structure if obj in fields: row[fields.index(obj)] = ensure_utf(value) elif isinstance(value, dict) and obj != 'attributes': # traverse down into object path = obj _traverse_results(value, fields, row, path) master.append(row) return master
[ "def", "parse_results", "(", "fields", ",", "data", ")", ":", "master", "=", "[", "]", "for", "record", "in", "data", "[", "'records'", "]", ":", "# for each 'record' in response", "row", "=", "[", "None", "]", "*", "len", "(", "fields", ")", "# create null list the length of number of columns", "for", "obj", ",", "value", "in", "record", ".", "iteritems", "(", ")", ":", "# for each obj in record", "if", "not", "isinstance", "(", "value", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", ":", "# if not data structure", "if", "obj", "in", "fields", ":", "row", "[", "fields", ".", "index", "(", "obj", ")", "]", "=", "ensure_utf", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", "and", "obj", "!=", "'attributes'", ":", "# traverse down into object", "path", "=", "obj", "_traverse_results", "(", "value", ",", "fields", ",", "row", ",", "path", ")", "master", ".", "append", "(", "row", ")", "return", "master" ]
Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data
[ "Traverses", "ordered", "dictionary", "calls", "_traverse_results", "()", "to", "recursively", "read", "into", "the", "dictionary", "depth", "of", "data" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L59-L77
train
spotify/luigi
luigi/contrib/salesforce.py
_traverse_results
def _traverse_results(value, fields, row, path): """ Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary """ for f, v in value.iteritems(): # for each item in obj field_name = '{path}.{name}'.format(path=path, name=f) if path else f if not isinstance(v, (dict, list, tuple)): # if not data structure if field_name in fields: row[fields.index(field_name)] = ensure_utf(v) elif isinstance(v, dict) and f != 'attributes': # it is a dict _traverse_results(v, fields, row, field_name)
python
def _traverse_results(value, fields, row, path): """ Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary """ for f, v in value.iteritems(): # for each item in obj field_name = '{path}.{name}'.format(path=path, name=f) if path else f if not isinstance(v, (dict, list, tuple)): # if not data structure if field_name in fields: row[fields.index(field_name)] = ensure_utf(v) elif isinstance(v, dict) and f != 'attributes': # it is a dict _traverse_results(v, fields, row, field_name)
[ "def", "_traverse_results", "(", "value", ",", "fields", ",", "row", ",", "path", ")", ":", "for", "f", ",", "v", "in", "value", ".", "iteritems", "(", ")", ":", "# for each item in obj", "field_name", "=", "'{path}.{name}'", ".", "format", "(", "path", "=", "path", ",", "name", "=", "f", ")", "if", "path", "else", "f", "if", "not", "isinstance", "(", "v", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", ":", "# if not data structure", "if", "field_name", "in", "fields", ":", "row", "[", "fields", ".", "index", "(", "field_name", ")", "]", "=", "ensure_utf", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "dict", ")", "and", "f", "!=", "'attributes'", ":", "# it is a dict", "_traverse_results", "(", "v", ",", "fields", ",", "row", ",", "field_name", ")" ]
Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary
[ "Helper", "method", "for", "parse_results", "()", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L80-L94
train
spotify/luigi
luigi/contrib/salesforce.py
QuerySalesforce.merge_batch_results
def merge_batch_results(self, result_ids): """ Merges the resulting files of a multi-result batch bulk query. """ outfile = open(self.output().path, 'w') if self.content_type.lower() == 'csv': for i, result_id in enumerate(result_ids): with open("%s.%d" % (self.output().path, i), 'r') as f: header = f.readline() if i == 0: outfile.write(header) for line in f: outfile.write(line) else: raise Exception("Batch result merging not implemented for %s" % self.content_type) outfile.close()
python
def merge_batch_results(self, result_ids): """ Merges the resulting files of a multi-result batch bulk query. """ outfile = open(self.output().path, 'w') if self.content_type.lower() == 'csv': for i, result_id in enumerate(result_ids): with open("%s.%d" % (self.output().path, i), 'r') as f: header = f.readline() if i == 0: outfile.write(header) for line in f: outfile.write(line) else: raise Exception("Batch result merging not implemented for %s" % self.content_type) outfile.close()
[ "def", "merge_batch_results", "(", "self", ",", "result_ids", ")", ":", "outfile", "=", "open", "(", "self", ".", "output", "(", ")", ".", "path", ",", "'w'", ")", "if", "self", ".", "content_type", ".", "lower", "(", ")", "==", "'csv'", ":", "for", "i", ",", "result_id", "in", "enumerate", "(", "result_ids", ")", ":", "with", "open", "(", "\"%s.%d\"", "%", "(", "self", ".", "output", "(", ")", ".", "path", ",", "i", ")", ",", "'r'", ")", "as", "f", ":", "header", "=", "f", ".", "readline", "(", ")", "if", "i", "==", "0", ":", "outfile", ".", "write", "(", "header", ")", "for", "line", "in", "f", ":", "outfile", ".", "write", "(", "line", ")", "else", ":", "raise", "Exception", "(", "\"Batch result merging not implemented for %s\"", "%", "self", ".", "content_type", ")", "outfile", ".", "close", "(", ")" ]
Merges the resulting files of a multi-result batch bulk query.
[ "Merges", "the", "resulting", "files", "of", "a", "multi", "-", "result", "batch", "bulk", "query", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L212-L229
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.start_session
def start_session(self): """ Starts a Salesforce session and determines which SF instance to use for future requests. """ if self.has_active_session(): raise Exception("Session already in progress.") response = requests.post(self._get_login_url(), headers=self._get_login_headers(), data=self._get_login_xml()) response.raise_for_status() root = ET.fromstring(response.text) for e in root.iter("%ssessionId" % self.SOAP_NS): if self.session_id: raise Exception("Invalid login attempt. Multiple session ids found.") self.session_id = e.text for e in root.iter("%sserverUrl" % self.SOAP_NS): if self.server_url: raise Exception("Invalid login attempt. Multiple server urls found.") self.server_url = e.text if not self.has_active_session(): raise Exception("Invalid login attempt resulted in null sessionId [%s] and/or serverUrl [%s]." % (self.session_id, self.server_url)) self.hostname = urlsplit(self.server_url).hostname
python
def start_session(self): """ Starts a Salesforce session and determines which SF instance to use for future requests. """ if self.has_active_session(): raise Exception("Session already in progress.") response = requests.post(self._get_login_url(), headers=self._get_login_headers(), data=self._get_login_xml()) response.raise_for_status() root = ET.fromstring(response.text) for e in root.iter("%ssessionId" % self.SOAP_NS): if self.session_id: raise Exception("Invalid login attempt. Multiple session ids found.") self.session_id = e.text for e in root.iter("%sserverUrl" % self.SOAP_NS): if self.server_url: raise Exception("Invalid login attempt. Multiple server urls found.") self.server_url = e.text if not self.has_active_session(): raise Exception("Invalid login attempt resulted in null sessionId [%s] and/or serverUrl [%s]." % (self.session_id, self.server_url)) self.hostname = urlsplit(self.server_url).hostname
[ "def", "start_session", "(", "self", ")", ":", "if", "self", ".", "has_active_session", "(", ")", ":", "raise", "Exception", "(", "\"Session already in progress.\"", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "_get_login_url", "(", ")", ",", "headers", "=", "self", ".", "_get_login_headers", "(", ")", ",", "data", "=", "self", ".", "_get_login_xml", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "for", "e", "in", "root", ".", "iter", "(", "\"%ssessionId\"", "%", "self", ".", "SOAP_NS", ")", ":", "if", "self", ".", "session_id", ":", "raise", "Exception", "(", "\"Invalid login attempt. Multiple session ids found.\"", ")", "self", ".", "session_id", "=", "e", ".", "text", "for", "e", "in", "root", ".", "iter", "(", "\"%sserverUrl\"", "%", "self", ".", "SOAP_NS", ")", ":", "if", "self", ".", "server_url", ":", "raise", "Exception", "(", "\"Invalid login attempt. Multiple server urls found.\"", ")", "self", ".", "server_url", "=", "e", ".", "text", "if", "not", "self", ".", "has_active_session", "(", ")", ":", "raise", "Exception", "(", "\"Invalid login attempt resulted in null sessionId [%s] and/or serverUrl [%s].\"", "%", "(", "self", ".", "session_id", ",", "self", ".", "server_url", ")", ")", "self", ".", "hostname", "=", "urlsplit", "(", "self", ".", "server_url", ")", ".", "hostname" ]
Starts a Salesforce session and determines which SF instance to use for future requests.
[ "Starts", "a", "Salesforce", "session", "and", "determines", "which", "SF", "instance", "to", "use", "for", "future", "requests", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L255-L281
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.query
def query(self, query, **kwargs): """ Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload. :param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'" """ params = {'q': query} response = requests.get(self._get_norm_query_url(), headers=self._get_rest_headers(), params=params, **kwargs) if response.status_code != requests.codes.ok: raise Exception(response.content) return response.json()
python
def query(self, query, **kwargs): """ Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload. :param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'" """ params = {'q': query} response = requests.get(self._get_norm_query_url(), headers=self._get_rest_headers(), params=params, **kwargs) if response.status_code != requests.codes.ok: raise Exception(response.content) return response.json()
[ "def", "query", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'q'", ":", "query", "}", "response", "=", "requests", ".", "get", "(", "self", ".", "_get_norm_query_url", "(", ")", ",", "headers", "=", "self", ".", "_get_rest_headers", "(", ")", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")", "if", "response", ".", "status_code", "!=", "requests", ".", "codes", ".", "ok", ":", "raise", "Exception", "(", "response", ".", "content", ")", "return", "response", ".", "json", "(", ")" ]
Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload. :param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'"
[ "Return", "the", "result", "of", "a", "Salesforce", "SOQL", "query", "as", "a", "dict", "decoded", "from", "the", "Salesforce", "response", "JSON", "payload", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L286-L300
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.query_more
def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs): """ Retrieves more results from a query that returned more results than the batch maximum. Returns a dict decoded from the Salesforce response JSON payload. :param next_records_identifier: either the Id of the next Salesforce object in the result, or a URL to the next record in the result. :param identifier_is_url: True if `next_records_identifier` should be treated as a URL, False if `next_records_identifer` should be treated as an Id. """ if identifier_is_url: # Don't use `self.base_url` here because the full URI is provided url = (u'https://{instance}{next_record_url}' .format(instance=self.hostname, next_record_url=next_records_identifier)) else: url = self._get_norm_query_url() + '{next_record_id}' url = url.format(next_record_id=next_records_identifier) response = requests.get(url, headers=self._get_rest_headers(), **kwargs) response.raise_for_status() return response.json()
python
def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs): """ Retrieves more results from a query that returned more results than the batch maximum. Returns a dict decoded from the Salesforce response JSON payload. :param next_records_identifier: either the Id of the next Salesforce object in the result, or a URL to the next record in the result. :param identifier_is_url: True if `next_records_identifier` should be treated as a URL, False if `next_records_identifer` should be treated as an Id. """ if identifier_is_url: # Don't use `self.base_url` here because the full URI is provided url = (u'https://{instance}{next_record_url}' .format(instance=self.hostname, next_record_url=next_records_identifier)) else: url = self._get_norm_query_url() + '{next_record_id}' url = url.format(next_record_id=next_records_identifier) response = requests.get(url, headers=self._get_rest_headers(), **kwargs) response.raise_for_status() return response.json()
[ "def", "query_more", "(", "self", ",", "next_records_identifier", ",", "identifier_is_url", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "identifier_is_url", ":", "# Don't use `self.base_url` here because the full URI is provided", "url", "=", "(", "u'https://{instance}{next_record_url}'", ".", "format", "(", "instance", "=", "self", ".", "hostname", ",", "next_record_url", "=", "next_records_identifier", ")", ")", "else", ":", "url", "=", "self", ".", "_get_norm_query_url", "(", ")", "+", "'{next_record_id}'", "url", "=", "url", ".", "format", "(", "next_record_id", "=", "next_records_identifier", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_get_rest_headers", "(", ")", ",", "*", "*", "kwargs", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Retrieves more results from a query that returned more results than the batch maximum. Returns a dict decoded from the Salesforce response JSON payload. :param next_records_identifier: either the Id of the next Salesforce object in the result, or a URL to the next record in the result. :param identifier_is_url: True if `next_records_identifier` should be treated as a URL, False if `next_records_identifer` should be treated as an Id.
[ "Retrieves", "more", "results", "from", "a", "query", "that", "returned", "more", "results", "than", "the", "batch", "maximum", ".", "Returns", "a", "dict", "decoded", "from", "the", "Salesforce", "response", "JSON", "payload", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L302-L328
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.query_all
def query_all(self, query, **kwargs): """ Returns the full set of results for the `query`. This is a convenience wrapper around `query(...)` and `query_more(...)`. The returned dict is the decoded JSON payload from the final call to Salesforce, but with the `totalSize` field representing the full number of results retrieved and the `records` list representing the full list of records retrieved. :param query: the SOQL query to send to Salesforce, e.g. `SELECT Id FROM Lead WHERE Email = "waldo@somewhere.com"` """ # Make the initial query to Salesforce response = self.query(query, **kwargs) # get fields fields = get_soql_fields(query) # put fields and first page of results into a temp list to be written to TempFile tmp_list = [fields] tmp_list.extend(parse_results(fields, response)) tmp_dir = luigi.configuration.get_config().get('salesforce', 'local-tmp-dir', None) tmp_file = tempfile.TemporaryFile(mode='a+b', dir=tmp_dir) writer = csv.writer(tmp_file) writer.writerows(tmp_list) # The number of results might have exceeded the Salesforce batch limit # so check whether there are more results and retrieve them if so. length = len(response['records']) while not response['done']: response = self.query_more(response['nextRecordsUrl'], identifier_is_url=True, **kwargs) writer.writerows(parse_results(fields, response)) length += len(response['records']) if not length % 10000: logger.info('Requested {0} lines...'.format(length)) logger.info('Requested a total of {0} lines.'.format(length)) tmp_file.seek(0) return tmp_file
python
def query_all(self, query, **kwargs): """ Returns the full set of results for the `query`. This is a convenience wrapper around `query(...)` and `query_more(...)`. The returned dict is the decoded JSON payload from the final call to Salesforce, but with the `totalSize` field representing the full number of results retrieved and the `records` list representing the full list of records retrieved. :param query: the SOQL query to send to Salesforce, e.g. `SELECT Id FROM Lead WHERE Email = "waldo@somewhere.com"` """ # Make the initial query to Salesforce response = self.query(query, **kwargs) # get fields fields = get_soql_fields(query) # put fields and first page of results into a temp list to be written to TempFile tmp_list = [fields] tmp_list.extend(parse_results(fields, response)) tmp_dir = luigi.configuration.get_config().get('salesforce', 'local-tmp-dir', None) tmp_file = tempfile.TemporaryFile(mode='a+b', dir=tmp_dir) writer = csv.writer(tmp_file) writer.writerows(tmp_list) # The number of results might have exceeded the Salesforce batch limit # so check whether there are more results and retrieve them if so. length = len(response['records']) while not response['done']: response = self.query_more(response['nextRecordsUrl'], identifier_is_url=True, **kwargs) writer.writerows(parse_results(fields, response)) length += len(response['records']) if not length % 10000: logger.info('Requested {0} lines...'.format(length)) logger.info('Requested a total of {0} lines.'.format(length)) tmp_file.seek(0) return tmp_file
[ "def", "query_all", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "# Make the initial query to Salesforce", "response", "=", "self", ".", "query", "(", "query", ",", "*", "*", "kwargs", ")", "# get fields", "fields", "=", "get_soql_fields", "(", "query", ")", "# put fields and first page of results into a temp list to be written to TempFile", "tmp_list", "=", "[", "fields", "]", "tmp_list", ".", "extend", "(", "parse_results", "(", "fields", ",", "response", ")", ")", "tmp_dir", "=", "luigi", ".", "configuration", ".", "get_config", "(", ")", ".", "get", "(", "'salesforce'", ",", "'local-tmp-dir'", ",", "None", ")", "tmp_file", "=", "tempfile", ".", "TemporaryFile", "(", "mode", "=", "'a+b'", ",", "dir", "=", "tmp_dir", ")", "writer", "=", "csv", ".", "writer", "(", "tmp_file", ")", "writer", ".", "writerows", "(", "tmp_list", ")", "# The number of results might have exceeded the Salesforce batch limit", "# so check whether there are more results and retrieve them if so.", "length", "=", "len", "(", "response", "[", "'records'", "]", ")", "while", "not", "response", "[", "'done'", "]", ":", "response", "=", "self", ".", "query_more", "(", "response", "[", "'nextRecordsUrl'", "]", ",", "identifier_is_url", "=", "True", ",", "*", "*", "kwargs", ")", "writer", ".", "writerows", "(", "parse_results", "(", "fields", ",", "response", ")", ")", "length", "+=", "len", "(", "response", "[", "'records'", "]", ")", "if", "not", "length", "%", "10000", ":", "logger", ".", "info", "(", "'Requested {0} lines...'", ".", "format", "(", "length", ")", ")", "logger", ".", "info", "(", "'Requested a total of {0} lines.'", ".", "format", "(", "length", ")", ")", "tmp_file", ".", "seek", "(", "0", ")", "return", "tmp_file" ]
Returns the full set of results for the `query`. This is a convenience wrapper around `query(...)` and `query_more(...)`. The returned dict is the decoded JSON payload from the final call to Salesforce, but with the `totalSize` field representing the full number of results retrieved and the `records` list representing the full list of records retrieved. :param query: the SOQL query to send to Salesforce, e.g. `SELECT Id FROM Lead WHERE Email = "waldo@somewhere.com"`
[ "Returns", "the", "full", "set", "of", "results", "for", "the", "query", ".", "This", "is", "a", "convenience", "wrapper", "around", "query", "(", "...", ")", "and", "query_more", "(", "...", ")", ".", "The", "returned", "dict", "is", "the", "decoded", "JSON", "payload", "from", "the", "final", "call", "to", "Salesforce", "but", "with", "the", "totalSize", "field", "representing", "the", "full", "number", "of", "results", "retrieved", "and", "the", "records", "list", "representing", "the", "full", "list", "of", "records", "retrieved", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L330-L373
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.restful
def restful(self, path, params): """ Allows you to make a direct REST call if you know the path Arguments: :param path: The path of the request. Example: sobjects/User/ABC123/password' :param params: dict of parameters to pass to the path """ url = self._get_norm_base_url() + path response = requests.get(url, headers=self._get_rest_headers(), params=params) if response.status_code != 200: raise Exception(response) json_result = response.json(object_pairs_hook=OrderedDict) if len(json_result) == 0: return None else: return json_result
python
def restful(self, path, params): """ Allows you to make a direct REST call if you know the path Arguments: :param path: The path of the request. Example: sobjects/User/ABC123/password' :param params: dict of parameters to pass to the path """ url = self._get_norm_base_url() + path response = requests.get(url, headers=self._get_rest_headers(), params=params) if response.status_code != 200: raise Exception(response) json_result = response.json(object_pairs_hook=OrderedDict) if len(json_result) == 0: return None else: return json_result
[ "def", "restful", "(", "self", ",", "path", ",", "params", ")", ":", "url", "=", "self", ".", "_get_norm_base_url", "(", ")", "+", "path", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_get_rest_headers", "(", ")", ",", "params", "=", "params", ")", "if", "response", ".", "status_code", "!=", "200", ":", "raise", "Exception", "(", "response", ")", "json_result", "=", "response", ".", "json", "(", "object_pairs_hook", "=", "OrderedDict", ")", "if", "len", "(", "json_result", ")", "==", "0", ":", "return", "None", "else", ":", "return", "json_result" ]
Allows you to make a direct REST call if you know the path Arguments: :param path: The path of the request. Example: sobjects/User/ABC123/password' :param params: dict of parameters to pass to the path
[ "Allows", "you", "to", "make", "a", "direct", "REST", "call", "if", "you", "know", "the", "path", "Arguments", ":", ":", "param", "path", ":", "The", "path", "of", "the", "request", ".", "Example", ":", "sobjects", "/", "User", "/", "ABC123", "/", "password", ":", "param", "params", ":", "dict", "of", "parameters", "to", "pass", "to", "the", "path" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L376-L393
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.create_operation_job
def create_operation_job(self, operation, obj, external_id_field_name=None, content_type=None): """ Creates a new SF job that for doing any operation (insert, upsert, update, delete, query) :param operation: delete, insert, query, upsert, update, hardDelete. Must be lowercase. :param obj: Parent SF object :param external_id_field_name: Optional. """ if not self.has_active_session(): self.start_session() response = requests.post(self._get_create_job_url(), headers=self._get_create_job_headers(), data=self._get_create_job_xml(operation, obj, external_id_field_name, content_type)) response.raise_for_status() root = ET.fromstring(response.text) job_id = root.find('%sid' % self.API_NS).text return job_id
python
def create_operation_job(self, operation, obj, external_id_field_name=None, content_type=None): """ Creates a new SF job that for doing any operation (insert, upsert, update, delete, query) :param operation: delete, insert, query, upsert, update, hardDelete. Must be lowercase. :param obj: Parent SF object :param external_id_field_name: Optional. """ if not self.has_active_session(): self.start_session() response = requests.post(self._get_create_job_url(), headers=self._get_create_job_headers(), data=self._get_create_job_xml(operation, obj, external_id_field_name, content_type)) response.raise_for_status() root = ET.fromstring(response.text) job_id = root.find('%sid' % self.API_NS).text return job_id
[ "def", "create_operation_job", "(", "self", ",", "operation", ",", "obj", ",", "external_id_field_name", "=", "None", ",", "content_type", "=", "None", ")", ":", "if", "not", "self", ".", "has_active_session", "(", ")", ":", "self", ".", "start_session", "(", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "_get_create_job_url", "(", ")", ",", "headers", "=", "self", ".", "_get_create_job_headers", "(", ")", ",", "data", "=", "self", ".", "_get_create_job_xml", "(", "operation", ",", "obj", ",", "external_id_field_name", ",", "content_type", ")", ")", "response", ".", "raise_for_status", "(", ")", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "job_id", "=", "root", ".", "find", "(", "'%sid'", "%", "self", ".", "API_NS", ")", ".", "text", "return", "job_id" ]
Creates a new SF job that for doing any operation (insert, upsert, update, delete, query) :param operation: delete, insert, query, upsert, update, hardDelete. Must be lowercase. :param obj: Parent SF object :param external_id_field_name: Optional.
[ "Creates", "a", "new", "SF", "job", "that", "for", "doing", "any", "operation", "(", "insert", "upsert", "update", "delete", "query", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L395-L413
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.get_job_details
def get_job_details(self, job_id): """ Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml """ response = requests.get(self._get_job_details_url(job_id)) response.raise_for_status() return response
python
def get_job_details(self, job_id): """ Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml """ response = requests.get(self._get_job_details_url(job_id)) response.raise_for_status() return response
[ "def", "get_job_details", "(", "self", ",", "job_id", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "_get_job_details_url", "(", "job_id", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response" ]
Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml
[ "Gets", "all", "details", "for", "existing", "job" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L415-L426
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.abort_job
def abort_job(self, job_id): """ Abort an existing job. When a job is aborted, no more records are processed. Changes to data may already have been committed and aren't rolled back. :param job_id: job_id as returned by 'create_operation_job(...)' :return: abort response as xml """ response = requests.post(self._get_abort_job_url(job_id), headers=self._get_abort_job_headers(), data=self._get_abort_job_xml()) response.raise_for_status() return response
python
def abort_job(self, job_id): """ Abort an existing job. When a job is aborted, no more records are processed. Changes to data may already have been committed and aren't rolled back. :param job_id: job_id as returned by 'create_operation_job(...)' :return: abort response as xml """ response = requests.post(self._get_abort_job_url(job_id), headers=self._get_abort_job_headers(), data=self._get_abort_job_xml()) response.raise_for_status() return response
[ "def", "abort_job", "(", "self", ",", "job_id", ")", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "_get_abort_job_url", "(", "job_id", ")", ",", "headers", "=", "self", ".", "_get_abort_job_headers", "(", ")", ",", "data", "=", "self", ".", "_get_abort_job_xml", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response" ]
Abort an existing job. When a job is aborted, no more records are processed. Changes to data may already have been committed and aren't rolled back. :param job_id: job_id as returned by 'create_operation_job(...)' :return: abort response as xml
[ "Abort", "an", "existing", "job", ".", "When", "a", "job", "is", "aborted", "no", "more", "records", "are", "processed", ".", "Changes", "to", "data", "may", "already", "have", "been", "committed", "and", "aren", "t", "rolled", "back", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L428-L441
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.close_job
def close_job(self, job_id): """ Closes job :param job_id: job_id as returned by 'create_operation_job(...)' :return: close response as xml """ if not job_id or not self.has_active_session(): raise Exception("Can not close job without valid job_id and an active session.") response = requests.post(self._get_close_job_url(job_id), headers=self._get_close_job_headers(), data=self._get_close_job_xml()) response.raise_for_status() return response
python
def close_job(self, job_id): """ Closes job :param job_id: job_id as returned by 'create_operation_job(...)' :return: close response as xml """ if not job_id or not self.has_active_session(): raise Exception("Can not close job without valid job_id and an active session.") response = requests.post(self._get_close_job_url(job_id), headers=self._get_close_job_headers(), data=self._get_close_job_xml()) response.raise_for_status() return response
[ "def", "close_job", "(", "self", ",", "job_id", ")", ":", "if", "not", "job_id", "or", "not", "self", ".", "has_active_session", "(", ")", ":", "raise", "Exception", "(", "\"Can not close job without valid job_id and an active session.\"", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "_get_close_job_url", "(", "job_id", ")", ",", "headers", "=", "self", ".", "_get_close_job_headers", "(", ")", ",", "data", "=", "self", ".", "_get_close_job_xml", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response" ]
Closes job :param job_id: job_id as returned by 'create_operation_job(...)' :return: close response as xml
[ "Closes", "job" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L443-L458
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.create_batch
def create_batch(self, job_id, data, file_type): """ Creates a batch with either a string of data or a file containing data. If a file is provided, this will pull the contents of the file_target into memory when running. That shouldn't be a problem for any files that meet the Salesforce single batch upload size limit (10MB) and is done to ensure compressed files can be uploaded properly. :param job_id: job_id as returned by 'create_operation_job(...)' :param data: :return: Returns batch_id """ if not job_id or not self.has_active_session(): raise Exception("Can not create a batch without a valid job_id and an active session.") headers = self._get_create_batch_content_headers(file_type) headers['Content-Length'] = str(len(data)) response = requests.post(self._get_create_batch_url(job_id), headers=headers, data=data) response.raise_for_status() root = ET.fromstring(response.text) batch_id = root.find('%sid' % self.API_NS).text return batch_id
python
def create_batch(self, job_id, data, file_type): """ Creates a batch with either a string of data or a file containing data. If a file is provided, this will pull the contents of the file_target into memory when running. That shouldn't be a problem for any files that meet the Salesforce single batch upload size limit (10MB) and is done to ensure compressed files can be uploaded properly. :param job_id: job_id as returned by 'create_operation_job(...)' :param data: :return: Returns batch_id """ if not job_id or not self.has_active_session(): raise Exception("Can not create a batch without a valid job_id and an active session.") headers = self._get_create_batch_content_headers(file_type) headers['Content-Length'] = str(len(data)) response = requests.post(self._get_create_batch_url(job_id), headers=headers, data=data) response.raise_for_status() root = ET.fromstring(response.text) batch_id = root.find('%sid' % self.API_NS).text return batch_id
[ "def", "create_batch", "(", "self", ",", "job_id", ",", "data", ",", "file_type", ")", ":", "if", "not", "job_id", "or", "not", "self", ".", "has_active_session", "(", ")", ":", "raise", "Exception", "(", "\"Can not create a batch without a valid job_id and an active session.\"", ")", "headers", "=", "self", ".", "_get_create_batch_content_headers", "(", "file_type", ")", "headers", "[", "'Content-Length'", "]", "=", "str", "(", "len", "(", "data", ")", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "_get_create_batch_url", "(", "job_id", ")", ",", "headers", "=", "headers", ",", "data", "=", "data", ")", "response", ".", "raise_for_status", "(", ")", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "batch_id", "=", "root", ".", "find", "(", "'%sid'", "%", "self", ".", "API_NS", ")", ".", "text", "return", "batch_id" ]
Creates a batch with either a string of data or a file containing data. If a file is provided, this will pull the contents of the file_target into memory when running. That shouldn't be a problem for any files that meet the Salesforce single batch upload size limit (10MB) and is done to ensure compressed files can be uploaded properly. :param job_id: job_id as returned by 'create_operation_job(...)' :param data: :return: Returns batch_id
[ "Creates", "a", "batch", "with", "either", "a", "string", "of", "data", "or", "a", "file", "containing", "data", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L460-L486
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.block_on_batch
def block_on_batch(self, job_id, batch_id, sleep_time_seconds=5, max_wait_time_seconds=-1): """ Blocks until @batch_id is completed or failed. :param job_id: :param batch_id: :param sleep_time_seconds: :param max_wait_time_seconds: """ if not job_id or not batch_id or not self.has_active_session(): raise Exception("Can not block on a batch without a valid batch_id, job_id and an active session.") start_time = time.time() status = {} while max_wait_time_seconds < 0 or time.time() - start_time < max_wait_time_seconds: status = self._get_batch_info(job_id, batch_id) logger.info("Batch %s Job %s in state %s. %s records processed. %s records failed." % (batch_id, job_id, status['state'], status['num_processed'], status['num_failed'])) if status['state'].lower() in ["completed", "failed"]: return status time.sleep(sleep_time_seconds) raise Exception("Batch did not complete in %s seconds. Final status was: %s" % (sleep_time_seconds, status))
python
def block_on_batch(self, job_id, batch_id, sleep_time_seconds=5, max_wait_time_seconds=-1): """ Blocks until @batch_id is completed or failed. :param job_id: :param batch_id: :param sleep_time_seconds: :param max_wait_time_seconds: """ if not job_id or not batch_id or not self.has_active_session(): raise Exception("Can not block on a batch without a valid batch_id, job_id and an active session.") start_time = time.time() status = {} while max_wait_time_seconds < 0 or time.time() - start_time < max_wait_time_seconds: status = self._get_batch_info(job_id, batch_id) logger.info("Batch %s Job %s in state %s. %s records processed. %s records failed." % (batch_id, job_id, status['state'], status['num_processed'], status['num_failed'])) if status['state'].lower() in ["completed", "failed"]: return status time.sleep(sleep_time_seconds) raise Exception("Batch did not complete in %s seconds. Final status was: %s" % (sleep_time_seconds, status))
[ "def", "block_on_batch", "(", "self", ",", "job_id", ",", "batch_id", ",", "sleep_time_seconds", "=", "5", ",", "max_wait_time_seconds", "=", "-", "1", ")", ":", "if", "not", "job_id", "or", "not", "batch_id", "or", "not", "self", ".", "has_active_session", "(", ")", ":", "raise", "Exception", "(", "\"Can not block on a batch without a valid batch_id, job_id and an active session.\"", ")", "start_time", "=", "time", ".", "time", "(", ")", "status", "=", "{", "}", "while", "max_wait_time_seconds", "<", "0", "or", "time", ".", "time", "(", ")", "-", "start_time", "<", "max_wait_time_seconds", ":", "status", "=", "self", ".", "_get_batch_info", "(", "job_id", ",", "batch_id", ")", "logger", ".", "info", "(", "\"Batch %s Job %s in state %s. %s records processed. %s records failed.\"", "%", "(", "batch_id", ",", "job_id", ",", "status", "[", "'state'", "]", ",", "status", "[", "'num_processed'", "]", ",", "status", "[", "'num_failed'", "]", ")", ")", "if", "status", "[", "'state'", "]", ".", "lower", "(", ")", "in", "[", "\"completed\"", ",", "\"failed\"", "]", ":", "return", "status", "time", ".", "sleep", "(", "sleep_time_seconds", ")", "raise", "Exception", "(", "\"Batch did not complete in %s seconds. Final status was: %s\"", "%", "(", "sleep_time_seconds", ",", "status", ")", ")" ]
Blocks until @batch_id is completed or failed. :param job_id: :param batch_id: :param sleep_time_seconds: :param max_wait_time_seconds:
[ "Blocks", "until" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L488-L509
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.get_batch_results
def get_batch_results(self, job_id, batch_id): """ DEPRECATED: Use `get_batch_result_ids` """ warnings.warn("get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids") return self.get_batch_result_ids(job_id, batch_id)[0]
python
def get_batch_results(self, job_id, batch_id): """ DEPRECATED: Use `get_batch_result_ids` """ warnings.warn("get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids") return self.get_batch_result_ids(job_id, batch_id)[0]
[ "def", "get_batch_results", "(", "self", ",", "job_id", ",", "batch_id", ")", ":", "warnings", ".", "warn", "(", "\"get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids\"", ")", "return", "self", ".", "get_batch_result_ids", "(", "job_id", ",", "batch_id", ")", "[", "0", "]" ]
DEPRECATED: Use `get_batch_result_ids`
[ "DEPRECATED", ":", "Use", "get_batch_result_ids" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L511-L516
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.get_batch_result_ids
def get_batch_result_ids(self, job_id, batch_id): """ Get result IDs of a batch that has completed processing. :param job_id: job_id as returned by 'create_operation_job(...)' :param batch_id: batch_id as returned by 'create_batch(...)' :return: list of batch result IDs to be used in 'get_batch_result(...)' """ response = requests.get(self._get_batch_results_url(job_id, batch_id), headers=self._get_batch_info_headers()) response.raise_for_status() root = ET.fromstring(response.text) result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)] return result_ids
python
def get_batch_result_ids(self, job_id, batch_id): """ Get result IDs of a batch that has completed processing. :param job_id: job_id as returned by 'create_operation_job(...)' :param batch_id: batch_id as returned by 'create_batch(...)' :return: list of batch result IDs to be used in 'get_batch_result(...)' """ response = requests.get(self._get_batch_results_url(job_id, batch_id), headers=self._get_batch_info_headers()) response.raise_for_status() root = ET.fromstring(response.text) result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)] return result_ids
[ "def", "get_batch_result_ids", "(", "self", ",", "job_id", ",", "batch_id", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "_get_batch_results_url", "(", "job_id", ",", "batch_id", ")", ",", "headers", "=", "self", ".", "_get_batch_info_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "result_ids", "=", "[", "r", ".", "text", "for", "r", "in", "root", ".", "findall", "(", "'%sresult'", "%", "self", ".", "API_NS", ")", "]", "return", "result_ids" ]
Get result IDs of a batch that has completed processing. :param job_id: job_id as returned by 'create_operation_job(...)' :param batch_id: batch_id as returned by 'create_batch(...)' :return: list of batch result IDs to be used in 'get_batch_result(...)'
[ "Get", "result", "IDs", "of", "a", "batch", "that", "has", "completed", "processing", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L518-L533
train
spotify/luigi
luigi/contrib/salesforce.py
SalesforceAPI.get_batch_result
def get_batch_result(self, job_id, batch_id, result_id): """ Gets result back from Salesforce as whatever type was originally sent in create_batch (xml, or csv). :param job_id: :param batch_id: :param result_id: """ response = requests.get(self._get_batch_result_url(job_id, batch_id, result_id), headers=self._get_session_headers()) response.raise_for_status() return response.content
python
def get_batch_result(self, job_id, batch_id, result_id): """ Gets result back from Salesforce as whatever type was originally sent in create_batch (xml, or csv). :param job_id: :param batch_id: :param result_id: """ response = requests.get(self._get_batch_result_url(job_id, batch_id, result_id), headers=self._get_session_headers()) response.raise_for_status() return response.content
[ "def", "get_batch_result", "(", "self", ",", "job_id", ",", "batch_id", ",", "result_id", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "_get_batch_result_url", "(", "job_id", ",", "batch_id", ",", "result_id", ")", ",", "headers", "=", "self", ".", "_get_session_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "content" ]
Gets result back from Salesforce as whatever type was originally sent in create_batch (xml, or csv). :param job_id: :param batch_id: :param result_id:
[ "Gets", "result", "back", "from", "Salesforce", "as", "whatever", "type", "was", "originally", "sent", "in", "create_batch", "(", "xml", "or", "csv", ")", ".", ":", "param", "job_id", ":", ":", "param", "batch_id", ":", ":", "param", "result_id", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L535-L547
train
spotify/luigi
luigi/contrib/sge.py
_parse_qstat_state
def _parse_qstat_state(qstat_out, job_id): """Parse "state" column from `qstat` output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `qstat` output is empty or job_id is not found. """ if qstat_out.strip() == '': return 'u' lines = qstat_out.split('\n') # skip past header while not lines.pop(0).startswith('---'): pass for line in lines: if line: job, prior, name, user, state = line.strip().split()[0:5] if int(job) == int(job_id): return state return 'u'
python
def _parse_qstat_state(qstat_out, job_id): """Parse "state" column from `qstat` output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `qstat` output is empty or job_id is not found. """ if qstat_out.strip() == '': return 'u' lines = qstat_out.split('\n') # skip past header while not lines.pop(0).startswith('---'): pass for line in lines: if line: job, prior, name, user, state = line.strip().split()[0:5] if int(job) == int(job_id): return state return 'u'
[ "def", "_parse_qstat_state", "(", "qstat_out", ",", "job_id", ")", ":", "if", "qstat_out", ".", "strip", "(", ")", "==", "''", ":", "return", "'u'", "lines", "=", "qstat_out", ".", "split", "(", "'\\n'", ")", "# skip past header", "while", "not", "lines", ".", "pop", "(", "0", ")", ".", "startswith", "(", "'---'", ")", ":", "pass", "for", "line", "in", "lines", ":", "if", "line", ":", "job", ",", "prior", ",", "name", ",", "user", ",", "state", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "[", "0", ":", "5", "]", "if", "int", "(", "job", ")", "==", "int", "(", "job_id", ")", ":", "return", "state", "return", "'u'" ]
Parse "state" column from `qstat` output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `qstat` output is empty or job_id is not found.
[ "Parse", "state", "column", "from", "qstat", "output", "for", "given", "job_id" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sge.py#L113-L131
train
spotify/luigi
luigi/contrib/sge.py
_build_qsub_command
def _build_qsub_command(cmd, job_name, outfile, errfile, pe, n_cpu): """Submit shell command to SGE queue via `qsub`""" qsub_template = """echo {cmd} | qsub -o ":{outfile}" -e ":{errfile}" -V -r y -pe {pe} {n_cpu} -N {job_name}""" return qsub_template.format( cmd=cmd, job_name=job_name, outfile=outfile, errfile=errfile, pe=pe, n_cpu=n_cpu)
python
def _build_qsub_command(cmd, job_name, outfile, errfile, pe, n_cpu): """Submit shell command to SGE queue via `qsub`""" qsub_template = """echo {cmd} | qsub -o ":{outfile}" -e ":{errfile}" -V -r y -pe {pe} {n_cpu} -N {job_name}""" return qsub_template.format( cmd=cmd, job_name=job_name, outfile=outfile, errfile=errfile, pe=pe, n_cpu=n_cpu)
[ "def", "_build_qsub_command", "(", "cmd", ",", "job_name", ",", "outfile", ",", "errfile", ",", "pe", ",", "n_cpu", ")", ":", "qsub_template", "=", "\"\"\"echo {cmd} | qsub -o \":{outfile}\" -e \":{errfile}\" -V -r y -pe {pe} {n_cpu} -N {job_name}\"\"\"", "return", "qsub_template", ".", "format", "(", "cmd", "=", "cmd", ",", "job_name", "=", "job_name", ",", "outfile", "=", "outfile", ",", "errfile", "=", "errfile", ",", "pe", "=", "pe", ",", "n_cpu", "=", "n_cpu", ")" ]
Submit shell command to SGE queue via `qsub`
[ "Submit", "shell", "command", "to", "SGE", "queue", "via", "qsub" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sge.py#L145-L150
train
spotify/luigi
luigi/contrib/sge.py
SGEJobTask._dump
def _dump(self, out_dir=''): """Dump instance to file.""" with self.no_unpicklable_properties(): self.job_file = os.path.join(out_dir, 'job-instance.pickle') if self.__module__ == '__main__': d = pickle.dumps(self) module_name = os.path.basename(sys.argv[0]).rsplit('.', 1)[0] d = d.replace('(c__main__', "(c" + module_name) open(self.job_file, "w").write(d) else: pickle.dump(self, open(self.job_file, "w"))
python
def _dump(self, out_dir=''): """Dump instance to file.""" with self.no_unpicklable_properties(): self.job_file = os.path.join(out_dir, 'job-instance.pickle') if self.__module__ == '__main__': d = pickle.dumps(self) module_name = os.path.basename(sys.argv[0]).rsplit('.', 1)[0] d = d.replace('(c__main__', "(c" + module_name) open(self.job_file, "w").write(d) else: pickle.dump(self, open(self.job_file, "w"))
[ "def", "_dump", "(", "self", ",", "out_dir", "=", "''", ")", ":", "with", "self", ".", "no_unpicklable_properties", "(", ")", ":", "self", ".", "job_file", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'job-instance.pickle'", ")", "if", "self", ".", "__module__", "==", "'__main__'", ":", "d", "=", "pickle", ".", "dumps", "(", "self", ")", "module_name", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "d", "=", "d", ".", "replace", "(", "'(c__main__'", ",", "\"(c\"", "+", "module_name", ")", "open", "(", "self", ".", "job_file", ",", "\"w\"", ")", ".", "write", "(", "d", ")", "else", ":", "pickle", ".", "dump", "(", "self", ",", "open", "(", "self", ".", "job_file", ",", "\"w\"", ")", ")" ]
Dump instance to file.
[ "Dump", "instance", "to", "file", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sge.py#L273-L283
train
spotify/luigi
examples/elasticsearch_index.py
FakeDocuments.run
def run(self): """ Writes data in JSON format into the task's output target. The data objects have the following attributes: * `_id` is the default Elasticsearch id field, * `text`: the text, * `date`: the day when the data was created. """ today = datetime.date.today() with self.output().open('w') as output: for i in range(5): output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i, 'date': str(today)})) output.write('\n')
python
def run(self): """ Writes data in JSON format into the task's output target. The data objects have the following attributes: * `_id` is the default Elasticsearch id field, * `text`: the text, * `date`: the day when the data was created. """ today = datetime.date.today() with self.output().open('w') as output: for i in range(5): output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i, 'date': str(today)})) output.write('\n')
[ "def", "run", "(", "self", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "with", "self", ".", "output", "(", ")", ".", "open", "(", "'w'", ")", "as", "output", ":", "for", "i", "in", "range", "(", "5", ")", ":", "output", ".", "write", "(", "json", ".", "dumps", "(", "{", "'_id'", ":", "i", ",", "'text'", ":", "'Hi %s'", "%", "i", ",", "'date'", ":", "str", "(", "today", ")", "}", ")", ")", "output", ".", "write", "(", "'\\n'", ")" ]
Writes data in JSON format into the task's output target. The data objects have the following attributes: * `_id` is the default Elasticsearch id field, * `text`: the text, * `date`: the day when the data was created.
[ "Writes", "data", "in", "JSON", "format", "into", "the", "task", "s", "output", "target", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/elasticsearch_index.py#L32-L48
train
spotify/luigi
luigi/contrib/hdfs/clients.py
get_autoconfig_client
def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT): """ Creates the client as specified in the `luigi.cfg` configuration. """ try: return client_cache.client except AttributeError: configured_client = hdfs_config.get_configured_hdfs_client() if configured_client == "webhdfs": client_cache.client = hdfs_webhdfs_client.WebHdfsClient() elif configured_client == "snakebite": client_cache.client = hdfs_snakebite_client.SnakebiteHdfsClient() elif configured_client == "snakebite_with_hadoopcli_fallback": client_cache.client = luigi.contrib.target.CascadingClient([ hdfs_snakebite_client.SnakebiteHdfsClient(), hdfs_hadoopcli_clients.create_hadoopcli_client(), ]) elif configured_client == "hadoopcli": client_cache.client = hdfs_hadoopcli_clients.create_hadoopcli_client() else: raise Exception("Unknown hdfs client " + configured_client) return client_cache.client
python
def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT): """ Creates the client as specified in the `luigi.cfg` configuration. """ try: return client_cache.client except AttributeError: configured_client = hdfs_config.get_configured_hdfs_client() if configured_client == "webhdfs": client_cache.client = hdfs_webhdfs_client.WebHdfsClient() elif configured_client == "snakebite": client_cache.client = hdfs_snakebite_client.SnakebiteHdfsClient() elif configured_client == "snakebite_with_hadoopcli_fallback": client_cache.client = luigi.contrib.target.CascadingClient([ hdfs_snakebite_client.SnakebiteHdfsClient(), hdfs_hadoopcli_clients.create_hadoopcli_client(), ]) elif configured_client == "hadoopcli": client_cache.client = hdfs_hadoopcli_clients.create_hadoopcli_client() else: raise Exception("Unknown hdfs client " + configured_client) return client_cache.client
[ "def", "get_autoconfig_client", "(", "client_cache", "=", "_AUTOCONFIG_CLIENT", ")", ":", "try", ":", "return", "client_cache", ".", "client", "except", "AttributeError", ":", "configured_client", "=", "hdfs_config", ".", "get_configured_hdfs_client", "(", ")", "if", "configured_client", "==", "\"webhdfs\"", ":", "client_cache", ".", "client", "=", "hdfs_webhdfs_client", ".", "WebHdfsClient", "(", ")", "elif", "configured_client", "==", "\"snakebite\"", ":", "client_cache", ".", "client", "=", "hdfs_snakebite_client", ".", "SnakebiteHdfsClient", "(", ")", "elif", "configured_client", "==", "\"snakebite_with_hadoopcli_fallback\"", ":", "client_cache", ".", "client", "=", "luigi", ".", "contrib", ".", "target", ".", "CascadingClient", "(", "[", "hdfs_snakebite_client", ".", "SnakebiteHdfsClient", "(", ")", ",", "hdfs_hadoopcli_clients", ".", "create_hadoopcli_client", "(", ")", ",", "]", ")", "elif", "configured_client", "==", "\"hadoopcli\"", ":", "client_cache", ".", "client", "=", "hdfs_hadoopcli_clients", ".", "create_hadoopcli_client", "(", ")", "else", ":", "raise", "Exception", "(", "\"Unknown hdfs client \"", "+", "configured_client", ")", "return", "client_cache", ".", "client" ]
Creates the client as specified in the `luigi.cfg` configuration.
[ "Creates", "the", "client", "as", "specified", "in", "the", "luigi", ".", "cfg", "configuration", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/clients.py#L36-L57
train
spotify/luigi
luigi/notifications.py
wrap_traceback
def wrap_traceback(traceback): """ For internal use only (until further notice) """ if email().format == 'html': try: from pygments import highlight from pygments.lexers import PythonTracebackLexer from pygments.formatters import HtmlFormatter with_pygments = True except ImportError: with_pygments = False if with_pygments: formatter = HtmlFormatter(noclasses=True) wrapped = highlight(traceback, PythonTracebackLexer(), formatter) else: wrapped = '<pre>%s</pre>' % traceback else: wrapped = traceback return wrapped
python
def wrap_traceback(traceback): """ For internal use only (until further notice) """ if email().format == 'html': try: from pygments import highlight from pygments.lexers import PythonTracebackLexer from pygments.formatters import HtmlFormatter with_pygments = True except ImportError: with_pygments = False if with_pygments: formatter = HtmlFormatter(noclasses=True) wrapped = highlight(traceback, PythonTracebackLexer(), formatter) else: wrapped = '<pre>%s</pre>' % traceback else: wrapped = traceback return wrapped
[ "def", "wrap_traceback", "(", "traceback", ")", ":", "if", "email", "(", ")", ".", "format", "==", "'html'", ":", "try", ":", "from", "pygments", "import", "highlight", "from", "pygments", ".", "lexers", "import", "PythonTracebackLexer", "from", "pygments", ".", "formatters", "import", "HtmlFormatter", "with_pygments", "=", "True", "except", "ImportError", ":", "with_pygments", "=", "False", "if", "with_pygments", ":", "formatter", "=", "HtmlFormatter", "(", "noclasses", "=", "True", ")", "wrapped", "=", "highlight", "(", "traceback", ",", "PythonTracebackLexer", "(", ")", ",", "formatter", ")", "else", ":", "wrapped", "=", "'<pre>%s</pre>'", "%", "traceback", "else", ":", "wrapped", "=", "traceback", "return", "wrapped" ]
For internal use only (until further notice)
[ "For", "internal", "use", "only", "(", "until", "further", "notice", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L159-L180
train
spotify/luigi
luigi/notifications.py
send_email_ses
def send_email_ses(sender, subject, message, recipients, image_png): """ Sends notification through AWS SES. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. """ from boto3 import client as boto3_client client = boto3_client('ses') msg_root = generate_email(sender, subject, message, recipients, image_png) response = client.send_raw_email(Source=sender, Destinations=recipients, RawMessage={'Data': msg_root.as_string()}) logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n" "HTTPSStatusCode: {}").format(response['MessageId'], response['ResponseMetadata']['RequestId'], response['ResponseMetadata']['HTTPStatusCode']))
python
def send_email_ses(sender, subject, message, recipients, image_png): """ Sends notification through AWS SES. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. """ from boto3 import client as boto3_client client = boto3_client('ses') msg_root = generate_email(sender, subject, message, recipients, image_png) response = client.send_raw_email(Source=sender, Destinations=recipients, RawMessage={'Data': msg_root.as_string()}) logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n" "HTTPSStatusCode: {}").format(response['MessageId'], response['ResponseMetadata']['RequestId'], response['ResponseMetadata']['HTTPStatusCode']))
[ "def", "send_email_ses", "(", "sender", ",", "subject", ",", "message", ",", "recipients", ",", "image_png", ")", ":", "from", "boto3", "import", "client", "as", "boto3_client", "client", "=", "boto3_client", "(", "'ses'", ")", "msg_root", "=", "generate_email", "(", "sender", ",", "subject", ",", "message", ",", "recipients", ",", "image_png", ")", "response", "=", "client", ".", "send_raw_email", "(", "Source", "=", "sender", ",", "Destinations", "=", "recipients", ",", "RawMessage", "=", "{", "'Data'", ":", "msg_root", ".", "as_string", "(", ")", "}", ")", "logger", ".", "debug", "(", "(", "\"Message sent to SES.\\nMessageId: {},\\nRequestId: {},\\n\"", "\"HTTPSStatusCode: {}\"", ")", ".", "format", "(", "response", "[", "'MessageId'", "]", ",", "response", "[", "'ResponseMetadata'", "]", "[", "'RequestId'", "]", ",", "response", "[", "'ResponseMetadata'", "]", "[", "'HTTPStatusCode'", "]", ")", ")" ]
Sends notification through AWS SES. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
[ "Sends", "notification", "through", "AWS", "SES", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L210-L232
train
spotify/luigi
luigi/notifications.py
send_email_sns
def send_email_sns(sender, subject, message, topic_ARN, image_png): """ Sends notification through AWS SNS. Takes Topic ARN from recipients. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. """ from boto3 import resource as boto3_resource sns = boto3_resource('sns') topic = sns.Topic(topic_ARN[0]) # Subject is max 100 chars if len(subject) > 100: subject = subject[0:48] + '...' + subject[-49:] response = topic.publish(Subject=subject, Message=message) logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n" "HTTPSStatusCode: {}").format(response['MessageId'], response['ResponseMetadata']['RequestId'], response['ResponseMetadata']['HTTPStatusCode']))
python
def send_email_sns(sender, subject, message, topic_ARN, image_png): """ Sends notification through AWS SNS. Takes Topic ARN from recipients. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. """ from boto3 import resource as boto3_resource sns = boto3_resource('sns') topic = sns.Topic(topic_ARN[0]) # Subject is max 100 chars if len(subject) > 100: subject = subject[0:48] + '...' + subject[-49:] response = topic.publish(Subject=subject, Message=message) logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n" "HTTPSStatusCode: {}").format(response['MessageId'], response['ResponseMetadata']['RequestId'], response['ResponseMetadata']['HTTPStatusCode']))
[ "def", "send_email_sns", "(", "sender", ",", "subject", ",", "message", ",", "topic_ARN", ",", "image_png", ")", ":", "from", "boto3", "import", "resource", "as", "boto3_resource", "sns", "=", "boto3_resource", "(", "'sns'", ")", "topic", "=", "sns", ".", "Topic", "(", "topic_ARN", "[", "0", "]", ")", "# Subject is max 100 chars", "if", "len", "(", "subject", ")", ">", "100", ":", "subject", "=", "subject", "[", "0", ":", "48", "]", "+", "'...'", "+", "subject", "[", "-", "49", ":", "]", "response", "=", "topic", ".", "publish", "(", "Subject", "=", "subject", ",", "Message", "=", "message", ")", "logger", ".", "debug", "(", "(", "\"Message sent to SNS.\\nMessageId: {},\\nRequestId: {},\\n\"", "\"HTTPSStatusCode: {}\"", ")", ".", "format", "(", "response", "[", "'MessageId'", "]", ",", "response", "[", "'ResponseMetadata'", "]", "[", "'RequestId'", "]", ",", "response", "[", "'ResponseMetadata'", "]", "[", "'HTTPStatusCode'", "]", ")", ")" ]
Sends notification through AWS SNS. Takes Topic ARN from recipients. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
[ "Sends", "notification", "through", "AWS", "SNS", ".", "Takes", "Topic", "ARN", "from", "recipients", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L264-L288
train
spotify/luigi
luigi/notifications.py
send_email
def send_email(subject, message, sender, recipients, image_png=None): """ Decides whether to send notification. Notification is cancelled if there are no recipients or if stdout is onto tty or if in debug mode. Dispatches on config value email.method. Default is 'smtp'. """ notifiers = { 'ses': send_email_ses, 'sendgrid': send_email_sendgrid, 'smtp': send_email_smtp, 'sns': send_email_sns, } subject = _prefix(subject) if not recipients or recipients == (None,): return if _email_disabled_reason(): logger.info("Not sending email to %r because %s", recipients, _email_disabled_reason()) return # Clean the recipients lists to allow multiple email addresses, comma # separated in luigi.cfg recipients_tmp = [] for r in recipients: recipients_tmp.extend([a.strip() for a in r.split(',') if a.strip()]) # Replace original recipients with the clean list recipients = recipients_tmp logger.info("Sending email to %r", recipients) # Get appropriate sender and call it to send the notification email_sender = notifiers[email().method] email_sender(sender, subject, message, recipients, image_png)
python
def send_email(subject, message, sender, recipients, image_png=None): """ Decides whether to send notification. Notification is cancelled if there are no recipients or if stdout is onto tty or if in debug mode. Dispatches on config value email.method. Default is 'smtp'. """ notifiers = { 'ses': send_email_ses, 'sendgrid': send_email_sendgrid, 'smtp': send_email_smtp, 'sns': send_email_sns, } subject = _prefix(subject) if not recipients or recipients == (None,): return if _email_disabled_reason(): logger.info("Not sending email to %r because %s", recipients, _email_disabled_reason()) return # Clean the recipients lists to allow multiple email addresses, comma # separated in luigi.cfg recipients_tmp = [] for r in recipients: recipients_tmp.extend([a.strip() for a in r.split(',') if a.strip()]) # Replace original recipients with the clean list recipients = recipients_tmp logger.info("Sending email to %r", recipients) # Get appropriate sender and call it to send the notification email_sender = notifiers[email().method] email_sender(sender, subject, message, recipients, image_png)
[ "def", "send_email", "(", "subject", ",", "message", ",", "sender", ",", "recipients", ",", "image_png", "=", "None", ")", ":", "notifiers", "=", "{", "'ses'", ":", "send_email_ses", ",", "'sendgrid'", ":", "send_email_sendgrid", ",", "'smtp'", ":", "send_email_smtp", ",", "'sns'", ":", "send_email_sns", ",", "}", "subject", "=", "_prefix", "(", "subject", ")", "if", "not", "recipients", "or", "recipients", "==", "(", "None", ",", ")", ":", "return", "if", "_email_disabled_reason", "(", ")", ":", "logger", ".", "info", "(", "\"Not sending email to %r because %s\"", ",", "recipients", ",", "_email_disabled_reason", "(", ")", ")", "return", "# Clean the recipients lists to allow multiple email addresses, comma", "# separated in luigi.cfg", "recipients_tmp", "=", "[", "]", "for", "r", "in", "recipients", ":", "recipients_tmp", ".", "extend", "(", "[", "a", ".", "strip", "(", ")", "for", "a", "in", "r", ".", "split", "(", "','", ")", "if", "a", ".", "strip", "(", ")", "]", ")", "# Replace original recipients with the clean list", "recipients", "=", "recipients_tmp", "logger", ".", "info", "(", "\"Sending email to %r\"", ",", "recipients", ")", "# Get appropriate sender and call it to send the notification", "email_sender", "=", "notifiers", "[", "email", "(", ")", ".", "method", "]", "email_sender", "(", "sender", ",", "subject", ",", "message", ",", "recipients", ",", "image_png", ")" ]
Decides whether to send notification. Notification is cancelled if there are no recipients or if stdout is onto tty or if in debug mode. Dispatches on config value email.method. Default is 'smtp'.
[ "Decides", "whether", "to", "send", "notification", ".", "Notification", "is", "cancelled", "if", "there", "are", "no", "recipients", "or", "if", "stdout", "is", "onto", "tty", "or", "if", "in", "debug", "mode", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L291-L327
train
spotify/luigi
luigi/notifications.py
send_error_email
def send_error_email(subject, message, additional_recipients=None): """ Sends an email to the configured error email, if it's configured. """ recipients = _email_recipients(additional_recipients) sender = email().sender send_email( subject=subject, message=message, sender=sender, recipients=recipients )
python
def send_error_email(subject, message, additional_recipients=None): """ Sends an email to the configured error email, if it's configured. """ recipients = _email_recipients(additional_recipients) sender = email().sender send_email( subject=subject, message=message, sender=sender, recipients=recipients )
[ "def", "send_error_email", "(", "subject", ",", "message", ",", "additional_recipients", "=", "None", ")", ":", "recipients", "=", "_email_recipients", "(", "additional_recipients", ")", "sender", "=", "email", "(", ")", ".", "sender", "send_email", "(", "subject", "=", "subject", ",", "message", "=", "message", ",", "sender", "=", "sender", ",", "recipients", "=", "recipients", ")" ]
Sends an email to the configured error email, if it's configured.
[ "Sends", "an", "email", "to", "the", "configured", "error", "email", "if", "it", "s", "configured", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L341-L352
train
spotify/luigi
luigi/notifications.py
format_task_error
def format_task_error(headline, task, command, formatted_exception=None): """ Format a message body for an error email related to a luigi.task.Task :param headline: Summary line for the message :param task: `luigi.task.Task` instance where this error occurred :param formatted_exception: optional string showing traceback :return: message body """ if formatted_exception: formatted_exception = wrap_traceback(formatted_exception) else: formatted_exception = "" if email().format == 'html': msg_template = textwrap.dedent(''' <html> <body> <h2>{headline}</h2> <table style="border-top: 1px solid black; border-bottom: 1px solid black"> <thead> <tr><th>name</th><td>{name}</td></tr> </thead> <tbody> {param_rows} </tbody> </table> </pre> <h2>Command line</h2> <pre> {command} </pre> <h2>Traceback</h2> {traceback} </body> </html> ''') str_params = task.to_str_params() params = '\n'.join('<tr><th>{}</th><td>{}</td></tr>'.format(*items) for items in str_params.items()) body = msg_template.format(headline=headline, name=task.task_family, param_rows=params, command=command, traceback=formatted_exception) else: msg_template = textwrap.dedent('''\ {headline} Name: {name} Parameters: {params} Command line: {command} {traceback} ''') str_params = task.to_str_params() max_width = max([0] + [len(x) for x in str_params.keys()]) params = '\n'.join(' {:{width}}: {}'.format(*items, width=max_width) for items in str_params.items()) body = msg_template.format(headline=headline, name=task.task_family, params=params, command=command, traceback=formatted_exception) return body
python
def format_task_error(headline, task, command, formatted_exception=None): """ Format a message body for an error email related to a luigi.task.Task :param headline: Summary line for the message :param task: `luigi.task.Task` instance where this error occurred :param formatted_exception: optional string showing traceback :return: message body """ if formatted_exception: formatted_exception = wrap_traceback(formatted_exception) else: formatted_exception = "" if email().format == 'html': msg_template = textwrap.dedent(''' <html> <body> <h2>{headline}</h2> <table style="border-top: 1px solid black; border-bottom: 1px solid black"> <thead> <tr><th>name</th><td>{name}</td></tr> </thead> <tbody> {param_rows} </tbody> </table> </pre> <h2>Command line</h2> <pre> {command} </pre> <h2>Traceback</h2> {traceback} </body> </html> ''') str_params = task.to_str_params() params = '\n'.join('<tr><th>{}</th><td>{}</td></tr>'.format(*items) for items in str_params.items()) body = msg_template.format(headline=headline, name=task.task_family, param_rows=params, command=command, traceback=formatted_exception) else: msg_template = textwrap.dedent('''\ {headline} Name: {name} Parameters: {params} Command line: {command} {traceback} ''') str_params = task.to_str_params() max_width = max([0] + [len(x) for x in str_params.keys()]) params = '\n'.join(' {:{width}}: {}'.format(*items, width=max_width) for items in str_params.items()) body = msg_template.format(headline=headline, name=task.task_family, params=params, command=command, traceback=formatted_exception) return body
[ "def", "format_task_error", "(", "headline", ",", "task", ",", "command", ",", "formatted_exception", "=", "None", ")", ":", "if", "formatted_exception", ":", "formatted_exception", "=", "wrap_traceback", "(", "formatted_exception", ")", "else", ":", "formatted_exception", "=", "\"\"", "if", "email", "(", ")", ".", "format", "==", "'html'", ":", "msg_template", "=", "textwrap", ".", "dedent", "(", "'''\n <html>\n <body>\n <h2>{headline}</h2>\n\n <table style=\"border-top: 1px solid black; border-bottom: 1px solid black\">\n <thead>\n <tr><th>name</th><td>{name}</td></tr>\n </thead>\n <tbody>\n {param_rows}\n </tbody>\n </table>\n </pre>\n\n <h2>Command line</h2>\n <pre>\n {command}\n </pre>\n\n <h2>Traceback</h2>\n {traceback}\n </body>\n </html>\n '''", ")", "str_params", "=", "task", ".", "to_str_params", "(", ")", "params", "=", "'\\n'", ".", "join", "(", "'<tr><th>{}</th><td>{}</td></tr>'", ".", "format", "(", "*", "items", ")", "for", "items", "in", "str_params", ".", "items", "(", ")", ")", "body", "=", "msg_template", ".", "format", "(", "headline", "=", "headline", ",", "name", "=", "task", ".", "task_family", ",", "param_rows", "=", "params", ",", "command", "=", "command", ",", "traceback", "=", "formatted_exception", ")", "else", ":", "msg_template", "=", "textwrap", ".", "dedent", "(", "'''\\\n {headline}\n\n Name: {name}\n\n Parameters:\n {params}\n\n Command line:\n {command}\n\n {traceback}\n '''", ")", "str_params", "=", "task", ".", "to_str_params", "(", ")", "max_width", "=", "max", "(", "[", "0", "]", "+", "[", "len", "(", "x", ")", "for", "x", "in", "str_params", ".", "keys", "(", ")", "]", ")", "params", "=", "'\\n'", ".", "join", "(", "' {:{width}}: {}'", ".", "format", "(", "*", "items", ",", "width", "=", "max_width", ")", "for", "items", "in", "str_params", ".", "items", "(", ")", ")", "body", "=", "msg_template", ".", "format", "(", "headline", "=", "headline", ",", "name", "=", "task", ".", "task_family", ",", "params", "=", "params", ",", "command", "=", "command", ",", "traceback", "=", "formatted_exception", ")", "return", "body" ]
Format a message body for an error email related to a luigi.task.Task :param headline: Summary line for the message :param task: `luigi.task.Task` instance where this error occurred :param formatted_exception: optional string showing traceback :return: message body
[ "Format", "a", "message", "body", "for", "an", "error", "email", "related", "to", "a", "luigi", ".", "task", ".", "Task" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L366-L434
train
spotify/luigi
luigi/contrib/hdfs/webhdfs_client.py
WebHdfsClient.exists
def exists(self, path): """ Returns true if the path exists and false otherwise. """ import hdfs try: self.client.status(path) return True except hdfs.util.HdfsError as e: if str(e).startswith('File does not exist: '): return False else: raise e
python
def exists(self, path): """ Returns true if the path exists and false otherwise. """ import hdfs try: self.client.status(path) return True except hdfs.util.HdfsError as e: if str(e).startswith('File does not exist: '): return False else: raise e
[ "def", "exists", "(", "self", ",", "path", ")", ":", "import", "hdfs", "try", ":", "self", ".", "client", ".", "status", "(", "path", ")", "return", "True", "except", "hdfs", ".", "util", ".", "HdfsError", "as", "e", ":", "if", "str", "(", "e", ")", ".", "startswith", "(", "'File does not exist: '", ")", ":", "return", "False", "else", ":", "raise", "e" ]
Returns true if the path exists and false otherwise.
[ "Returns", "true", "if", "the", "path", "exists", "and", "false", "otherwise", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/webhdfs_client.py#L89-L101
train
spotify/luigi
luigi/contrib/hdfs/webhdfs_client.py
WebHdfsClient.mkdir
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): """ Has no returnvalue (just like WebHDFS) """ if not parents or raise_if_exists: warnings.warn('webhdfs mkdir: parents/raise_if_exists not implemented') permission = int(oct(mode)[2:]) # Convert from int(decimal) to int(octal) self.client.makedirs(path, permission=permission)
python
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): """ Has no returnvalue (just like WebHDFS) """ if not parents or raise_if_exists: warnings.warn('webhdfs mkdir: parents/raise_if_exists not implemented') permission = int(oct(mode)[2:]) # Convert from int(decimal) to int(octal) self.client.makedirs(path, permission=permission)
[ "def", "mkdir", "(", "self", ",", "path", ",", "parents", "=", "True", ",", "mode", "=", "0o755", ",", "raise_if_exists", "=", "False", ")", ":", "if", "not", "parents", "or", "raise_if_exists", ":", "warnings", ".", "warn", "(", "'webhdfs mkdir: parents/raise_if_exists not implemented'", ")", "permission", "=", "int", "(", "oct", "(", "mode", ")", "[", "2", ":", "]", ")", "# Convert from int(decimal) to int(octal)", "self", ".", "client", ".", "makedirs", "(", "path", ",", "permission", "=", "permission", ")" ]
Has no returnvalue (just like WebHDFS)
[ "Has", "no", "returnvalue", "(", "just", "like", "WebHDFS", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/webhdfs_client.py#L128-L135
train
spotify/luigi
luigi/contrib/hdfs/webhdfs_client.py
WebHdfsClient.touchz
def touchz(self, path): """ To touchz using the web hdfs "write" cmd. """ self.client.write(path, data='', overwrite=False)
python
def touchz(self, path): """ To touchz using the web hdfs "write" cmd. """ self.client.write(path, data='', overwrite=False)
[ "def", "touchz", "(", "self", ",", "path", ")", ":", "self", ".", "client", ".", "write", "(", "path", ",", "data", "=", "''", ",", "overwrite", "=", "False", ")" ]
To touchz using the web hdfs "write" cmd.
[ "To", "touchz", "using", "the", "web", "hdfs", "write", "cmd", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/webhdfs_client.py#L179-L183
train
spotify/luigi
luigi/contrib/azureblob.py
AzureBlobTarget.open
def open(self, mode): """ Open the target for reading or writing :param char mode: 'r' for reading and 'w' for writing. 'b' is not supported and will be stripped if used. For binary mode, use `format` :return: * :class:`.ReadableAzureBlobFile` if 'r' * :class:`.AtomicAzureBlobFile` if 'w' """ if mode not in ('r', 'w'): raise ValueError("Unsupported open mode '%s'" % mode) if mode == 'r': return self.format.pipe_reader(ReadableAzureBlobFile(self.container, self.blob, self.client, self.download_when_reading, **self.azure_blob_options)) else: return self.format.pipe_writer(AtomicAzureBlobFile(self.container, self.blob, self.client, **self.azure_blob_options))
python
def open(self, mode): """ Open the target for reading or writing :param char mode: 'r' for reading and 'w' for writing. 'b' is not supported and will be stripped if used. For binary mode, use `format` :return: * :class:`.ReadableAzureBlobFile` if 'r' * :class:`.AtomicAzureBlobFile` if 'w' """ if mode not in ('r', 'w'): raise ValueError("Unsupported open mode '%s'" % mode) if mode == 'r': return self.format.pipe_reader(ReadableAzureBlobFile(self.container, self.blob, self.client, self.download_when_reading, **self.azure_blob_options)) else: return self.format.pipe_writer(AtomicAzureBlobFile(self.container, self.blob, self.client, **self.azure_blob_options))
[ "def", "open", "(", "self", ",", "mode", ")", ":", "if", "mode", "not", "in", "(", "'r'", ",", "'w'", ")", ":", "raise", "ValueError", "(", "\"Unsupported open mode '%s'\"", "%", "mode", ")", "if", "mode", "==", "'r'", ":", "return", "self", ".", "format", ".", "pipe_reader", "(", "ReadableAzureBlobFile", "(", "self", ".", "container", ",", "self", ".", "blob", ",", "self", ".", "client", ",", "self", ".", "download_when_reading", ",", "*", "*", "self", ".", "azure_blob_options", ")", ")", "else", ":", "return", "self", ".", "format", ".", "pipe_writer", "(", "AtomicAzureBlobFile", "(", "self", ".", "container", ",", "self", ".", "blob", ",", "self", ".", "client", ",", "*", "*", "self", ".", "azure_blob_options", ")", ")" ]
Open the target for reading or writing :param char mode: 'r' for reading and 'w' for writing. 'b' is not supported and will be stripped if used. For binary mode, use `format` :return: * :class:`.ReadableAzureBlobFile` if 'r' * :class:`.AtomicAzureBlobFile` if 'w'
[ "Open", "the", "target", "for", "reading", "or", "writing" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/azureblob.py#L275-L292
train
spotify/luigi
examples/top_artists.py
Streams.run
def run(self): """ Generates bogus data and writes it into the :py:meth:`~.Streams.output` target. """ with self.output().open('w') as output: for _ in range(1000): output.write('{} {} {}\n'.format( random.randint(0, 999), random.randint(0, 999), random.randint(0, 999)))
python
def run(self): """ Generates bogus data and writes it into the :py:meth:`~.Streams.output` target. """ with self.output().open('w') as output: for _ in range(1000): output.write('{} {} {}\n'.format( random.randint(0, 999), random.randint(0, 999), random.randint(0, 999)))
[ "def", "run", "(", "self", ")", ":", "with", "self", ".", "output", "(", ")", ".", "open", "(", "'w'", ")", "as", "output", ":", "for", "_", "in", "range", "(", "1000", ")", ":", "output", ".", "write", "(", "'{} {} {}\\n'", ".", "format", "(", "random", ".", "randint", "(", "0", ",", "999", ")", ",", "random", ".", "randint", "(", "0", ",", "999", ")", ",", "random", ".", "randint", "(", "0", ",", "999", ")", ")", ")" ]
Generates bogus data and writes it into the :py:meth:`~.Streams.output` target.
[ "Generates", "bogus", "data", "and", "writes", "it", "into", "the", ":", "py", ":", "meth", ":", "~", ".", "Streams", ".", "output", "target", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/top_artists.py#L56-L65
train
spotify/luigi
examples/top_artists.py
Top10Artists.requires
def requires(self): """ This task's dependencies: * :py:class:`~.AggregateArtists` or * :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set. :return: object (:py:class:`luigi.task.Task`) """ if self.use_spark: return AggregateArtistsSpark(self.date_interval) else: return AggregateArtists(self.date_interval)
python
def requires(self): """ This task's dependencies: * :py:class:`~.AggregateArtists` or * :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set. :return: object (:py:class:`luigi.task.Task`) """ if self.use_spark: return AggregateArtistsSpark(self.date_interval) else: return AggregateArtists(self.date_interval)
[ "def", "requires", "(", "self", ")", ":", "if", "self", ".", "use_spark", ":", "return", "AggregateArtistsSpark", "(", "self", ".", "date_interval", ")", "else", ":", "return", "AggregateArtists", "(", "self", ".", "date_interval", ")" ]
This task's dependencies: * :py:class:`~.AggregateArtists` or * :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set. :return: object (:py:class:`luigi.task.Task`)
[ "This", "task", "s", "dependencies", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/top_artists.py#L198-L210
train
spotify/luigi
luigi/contrib/simulate.py
RunAnywayTarget.get_path
def get_path(self): """ Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments """ md5_hash = hashlib.md5(self.task_id.encode()).hexdigest() logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id) return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
python
def get_path(self): """ Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments """ md5_hash = hashlib.md5(self.task_id.encode()).hexdigest() logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id) return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
[ "def", "get_path", "(", "self", ")", ":", "md5_hash", "=", "hashlib", ".", "md5", "(", "self", ".", "task_id", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "logger", ".", "debug", "(", "'Hash %s corresponds to task %s'", ",", "md5_hash", ",", "self", ".", "task_id", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "temp_dir", ",", "str", "(", "self", ".", "unique", ".", "value", ")", ",", "md5_hash", ")" ]
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
[ "Returns", "a", "temporary", "file", "path", "based", "on", "a", "MD5", "hash", "generated", "with", "the", "task", "s", "name", "and", "its", "arguments" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/simulate.py#L82-L89
train
spotify/luigi
luigi/contrib/simulate.py
RunAnywayTarget.done
def done(self): """ Creates temporary file to mark the task as `done` """ logger.info('Marking %s as done', self) fn = self.get_path() try: os.makedirs(os.path.dirname(fn)) except OSError: pass open(fn, 'w').close()
python
def done(self): """ Creates temporary file to mark the task as `done` """ logger.info('Marking %s as done', self) fn = self.get_path() try: os.makedirs(os.path.dirname(fn)) except OSError: pass open(fn, 'w').close()
[ "def", "done", "(", "self", ")", ":", "logger", ".", "info", "(", "'Marking %s as done'", ",", "self", ")", "fn", "=", "self", ".", "get_path", "(", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "fn", ")", ")", "except", "OSError", ":", "pass", "open", "(", "fn", ",", "'w'", ")", ".", "close", "(", ")" ]
Creates temporary file to mark the task as `done`
[ "Creates", "temporary", "file", "to", "mark", "the", "task", "as", "done" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/simulate.py#L97-L108
train
spotify/luigi
luigi/contrib/s3.py
S3Client.exists
def exists(self, path): """ Does provided path exist on S3? """ (bucket, key) = self._path_to_bucket_and_key(path) # root always exists if self._is_root(key): return True # file if self._exists(bucket, key): return True if self.isdir(path): return True logger.debug('Path %s does not exist', path) return False
python
def exists(self, path): """ Does provided path exist on S3? """ (bucket, key) = self._path_to_bucket_and_key(path) # root always exists if self._is_root(key): return True # file if self._exists(bucket, key): return True if self.isdir(path): return True logger.debug('Path %s does not exist', path) return False
[ "def", "exists", "(", "self", ",", "path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "# root always exists", "if", "self", ".", "_is_root", "(", "key", ")", ":", "return", "True", "# file", "if", "self", ".", "_exists", "(", "bucket", ",", "key", ")", ":", "return", "True", "if", "self", ".", "isdir", "(", "path", ")", ":", "return", "True", "logger", ".", "debug", "(", "'Path %s does not exist'", ",", "path", ")", "return", "False" ]
Does provided path exist on S3?
[ "Does", "provided", "path", "exist", "on", "S3?" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L177-L195
train
spotify/luigi
luigi/contrib/s3.py
S3Client.remove
def remove(self, path, recursive=True): """ Remove a file or directory from S3. :param path: File or directory to remove :param recursive: Boolean indicator to remove object and children :return: Boolean indicator denoting success of the removal of 1 or more files """ if not self.exists(path): logger.debug('Could not delete %s; path does not exist', path) return False (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root if self._is_root(key): raise InvalidDeleteException('Cannot delete root of bucket at path %s' % path) # file if self._exists(bucket, key): self.s3.meta.client.delete_object(Bucket=bucket, Key=key) logger.debug('Deleting %s from bucket %s', key, bucket) return True if self.isdir(path) and not recursive: raise InvalidDeleteException('Path %s is a directory. Must use recursive delete' % path) delete_key_list = [{'Key': obj.key} for obj in s3_bucket.objects.filter(Prefix=self._add_path_delimiter(key))] # delete the directory marker file if it exists if self._exists(bucket, '{}{}'.format(key, S3_DIRECTORY_MARKER_SUFFIX_0)): delete_key_list.append({'Key': '{}{}'.format(key, S3_DIRECTORY_MARKER_SUFFIX_0)}) if len(delete_key_list) > 0: n = 1000 for i in range(0, len(delete_key_list), n): self.s3.meta.client.delete_objects(Bucket=bucket, Delete={'Objects': delete_key_list[i: i + n]}) return True return False
python
def remove(self, path, recursive=True): """ Remove a file or directory from S3. :param path: File or directory to remove :param recursive: Boolean indicator to remove object and children :return: Boolean indicator denoting success of the removal of 1 or more files """ if not self.exists(path): logger.debug('Could not delete %s; path does not exist', path) return False (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root if self._is_root(key): raise InvalidDeleteException('Cannot delete root of bucket at path %s' % path) # file if self._exists(bucket, key): self.s3.meta.client.delete_object(Bucket=bucket, Key=key) logger.debug('Deleting %s from bucket %s', key, bucket) return True if self.isdir(path) and not recursive: raise InvalidDeleteException('Path %s is a directory. Must use recursive delete' % path) delete_key_list = [{'Key': obj.key} for obj in s3_bucket.objects.filter(Prefix=self._add_path_delimiter(key))] # delete the directory marker file if it exists if self._exists(bucket, '{}{}'.format(key, S3_DIRECTORY_MARKER_SUFFIX_0)): delete_key_list.append({'Key': '{}{}'.format(key, S3_DIRECTORY_MARKER_SUFFIX_0)}) if len(delete_key_list) > 0: n = 1000 for i in range(0, len(delete_key_list), n): self.s3.meta.client.delete_objects(Bucket=bucket, Delete={'Objects': delete_key_list[i: i + n]}) return True return False
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "True", ")", ":", "if", "not", "self", ".", "exists", "(", "path", ")", ":", "logger", ".", "debug", "(", "'Could not delete %s; path does not exist'", ",", "path", ")", "return", "False", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "s3_bucket", "=", "self", ".", "s3", ".", "Bucket", "(", "bucket", ")", "# root", "if", "self", ".", "_is_root", "(", "key", ")", ":", "raise", "InvalidDeleteException", "(", "'Cannot delete root of bucket at path %s'", "%", "path", ")", "# file", "if", "self", ".", "_exists", "(", "bucket", ",", "key", ")", ":", "self", ".", "s3", ".", "meta", ".", "client", ".", "delete_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "logger", ".", "debug", "(", "'Deleting %s from bucket %s'", ",", "key", ",", "bucket", ")", "return", "True", "if", "self", ".", "isdir", "(", "path", ")", "and", "not", "recursive", ":", "raise", "InvalidDeleteException", "(", "'Path %s is a directory. Must use recursive delete'", "%", "path", ")", "delete_key_list", "=", "[", "{", "'Key'", ":", "obj", ".", "key", "}", "for", "obj", "in", "s3_bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "self", ".", "_add_path_delimiter", "(", "key", ")", ")", "]", "# delete the directory marker file if it exists", "if", "self", ".", "_exists", "(", "bucket", ",", "'{}{}'", ".", "format", "(", "key", ",", "S3_DIRECTORY_MARKER_SUFFIX_0", ")", ")", ":", "delete_key_list", ".", "append", "(", "{", "'Key'", ":", "'{}{}'", ".", "format", "(", "key", ",", "S3_DIRECTORY_MARKER_SUFFIX_0", ")", "}", ")", "if", "len", "(", "delete_key_list", ")", ">", "0", ":", "n", "=", "1000", "for", "i", "in", "range", "(", "0", ",", "len", "(", "delete_key_list", ")", ",", "n", ")", ":", "self", ".", "s3", ".", "meta", ".", "client", ".", "delete_objects", "(", "Bucket", "=", "bucket", ",", "Delete", "=", "{", "'Objects'", ":", "delete_key_list", "[", "i", ":", "i", "+", "n", "]", "}", ")", "return", "True", "return", "False" ]
Remove a file or directory from S3. :param path: File or directory to remove :param recursive: Boolean indicator to remove object and children :return: Boolean indicator denoting success of the removal of 1 or more files
[ "Remove", "a", "file", "or", "directory", "from", "S3", ".", ":", "param", "path", ":", "File", "or", "directory", "to", "remove", ":", "param", "recursive", ":", "Boolean", "indicator", "to", "remove", "object", "and", "children", ":", "return", ":", "Boolean", "indicator", "denoting", "success", "of", "the", "removal", "of", "1", "or", "more", "files" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L197-L235
train
spotify/luigi
luigi/contrib/s3.py
S3Client.get_key
def get_key(self, path): """ Returns the object summary at the path """ (bucket, key) = self._path_to_bucket_and_key(path) if self._exists(bucket, key): return self.s3.ObjectSummary(bucket, key)
python
def get_key(self, path): """ Returns the object summary at the path """ (bucket, key) = self._path_to_bucket_and_key(path) if self._exists(bucket, key): return self.s3.ObjectSummary(bucket, key)
[ "def", "get_key", "(", "self", ",", "path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "if", "self", ".", "_exists", "(", "bucket", ",", "key", ")", ":", "return", "self", ".", "s3", ".", "ObjectSummary", "(", "bucket", ",", "key", ")" ]
Returns the object summary at the path
[ "Returns", "the", "object", "summary", "at", "the", "path" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L247-L254
train
spotify/luigi
luigi/contrib/s3.py
S3Client.put
def put(self, local_path, destination_s3_path, **kwargs): """ Put an object stored locally to an S3 path. :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto function `put_object` """ self._check_deprecated_argument(**kwargs) # put the file self.put_multipart(local_path, destination_s3_path, **kwargs)
python
def put(self, local_path, destination_s3_path, **kwargs): """ Put an object stored locally to an S3 path. :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto function `put_object` """ self._check_deprecated_argument(**kwargs) # put the file self.put_multipart(local_path, destination_s3_path, **kwargs)
[ "def", "put", "(", "self", ",", "local_path", ",", "destination_s3_path", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_deprecated_argument", "(", "*", "*", "kwargs", ")", "# put the file", "self", ".", "put_multipart", "(", "local_path", ",", "destination_s3_path", ",", "*", "*", "kwargs", ")" ]
Put an object stored locally to an S3 path. :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto function `put_object`
[ "Put", "an", "object", "stored", "locally", "to", "an", "S3", "path", ".", ":", "param", "local_path", ":", "Path", "to", "source", "local", "file", ":", "param", "destination_s3_path", ":", "URL", "for", "target", "S3", "location", ":", "param", "kwargs", ":", "Keyword", "arguments", "are", "passed", "to", "the", "boto", "function", "put_object" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L256-L266
train
spotify/luigi
luigi/contrib/s3.py
S3Client.put_string
def put_string(self, content, destination_s3_path, **kwargs): """ Put a string to an S3 path. :param content: Data str :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto3 function `put_object` """ self._check_deprecated_argument(**kwargs) (bucket, key) = self._path_to_bucket_and_key(destination_s3_path) # put the file self.s3.meta.client.put_object( Key=key, Bucket=bucket, Body=content, **kwargs)
python
def put_string(self, content, destination_s3_path, **kwargs): """ Put a string to an S3 path. :param content: Data str :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto3 function `put_object` """ self._check_deprecated_argument(**kwargs) (bucket, key) = self._path_to_bucket_and_key(destination_s3_path) # put the file self.s3.meta.client.put_object( Key=key, Bucket=bucket, Body=content, **kwargs)
[ "def", "put_string", "(", "self", ",", "content", ",", "destination_s3_path", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_deprecated_argument", "(", "*", "*", "kwargs", ")", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "destination_s3_path", ")", "# put the file", "self", ".", "s3", ".", "meta", ".", "client", ".", "put_object", "(", "Key", "=", "key", ",", "Bucket", "=", "bucket", ",", "Body", "=", "content", ",", "*", "*", "kwargs", ")" ]
Put a string to an S3 path. :param content: Data str :param destination_s3_path: URL for target S3 location :param kwargs: Keyword arguments are passed to the boto3 function `put_object`
[ "Put", "a", "string", "to", "an", "S3", "path", ".", ":", "param", "content", ":", "Data", "str", ":", "param", "destination_s3_path", ":", "URL", "for", "target", "S3", "location", ":", "param", "kwargs", ":", "Keyword", "arguments", "are", "passed", "to", "the", "boto3", "function", "put_object" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L268-L280
train
spotify/luigi
luigi/contrib/s3.py
S3Client.put_multipart
def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs): """ Put an object stored locally to an S3 path using S3 multi-part upload (for files > 8Mb). :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param part_size: Part size in bytes. Default: 8388608 (8MB) :param kwargs: Keyword arguments are passed to the boto function `upload_fileobj` as ExtraArgs """ self._check_deprecated_argument(**kwargs) from boto3.s3.transfer import TransferConfig # default part size for boto3 is 8Mb, changing it to fit part_size # provided as a parameter transfer_config = TransferConfig(multipart_chunksize=part_size) (bucket, key) = self._path_to_bucket_and_key(destination_s3_path) self.s3.meta.client.upload_fileobj( Fileobj=open(local_path, 'rb'), Bucket=bucket, Key=key, Config=transfer_config, ExtraArgs=kwargs)
python
def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs): """ Put an object stored locally to an S3 path using S3 multi-part upload (for files > 8Mb). :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param part_size: Part size in bytes. Default: 8388608 (8MB) :param kwargs: Keyword arguments are passed to the boto function `upload_fileobj` as ExtraArgs """ self._check_deprecated_argument(**kwargs) from boto3.s3.transfer import TransferConfig # default part size for boto3 is 8Mb, changing it to fit part_size # provided as a parameter transfer_config = TransferConfig(multipart_chunksize=part_size) (bucket, key) = self._path_to_bucket_and_key(destination_s3_path) self.s3.meta.client.upload_fileobj( Fileobj=open(local_path, 'rb'), Bucket=bucket, Key=key, Config=transfer_config, ExtraArgs=kwargs)
[ "def", "put_multipart", "(", "self", ",", "local_path", ",", "destination_s3_path", ",", "part_size", "=", "DEFAULT_PART_SIZE", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_deprecated_argument", "(", "*", "*", "kwargs", ")", "from", "boto3", ".", "s3", ".", "transfer", "import", "TransferConfig", "# default part size for boto3 is 8Mb, changing it to fit part_size", "# provided as a parameter", "transfer_config", "=", "TransferConfig", "(", "multipart_chunksize", "=", "part_size", ")", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "destination_s3_path", ")", "self", ".", "s3", ".", "meta", ".", "client", ".", "upload_fileobj", "(", "Fileobj", "=", "open", "(", "local_path", ",", "'rb'", ")", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "Config", "=", "transfer_config", ",", "ExtraArgs", "=", "kwargs", ")" ]
Put an object stored locally to an S3 path using S3 multi-part upload (for files > 8Mb). :param local_path: Path to source local file :param destination_s3_path: URL for target S3 location :param part_size: Part size in bytes. Default: 8388608 (8MB) :param kwargs: Keyword arguments are passed to the boto function `upload_fileobj` as ExtraArgs
[ "Put", "an", "object", "stored", "locally", "to", "an", "S3", "path", "using", "S3", "multi", "-", "part", "upload", "(", "for", "files", ">", "8Mb", ")", ".", ":", "param", "local_path", ":", "Path", "to", "source", "local", "file", ":", "param", "destination_s3_path", ":", "URL", "for", "target", "S3", "location", ":", "param", "part_size", ":", "Part", "size", "in", "bytes", ".", "Default", ":", "8388608", "(", "8MB", ")", ":", "param", "kwargs", ":", "Keyword", "arguments", "are", "passed", "to", "the", "boto", "function", "upload_fileobj", "as", "ExtraArgs" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L282-L301
train
spotify/luigi
luigi/contrib/s3.py
S3Client.copy
def copy(self, source_path, destination_path, threads=DEFAULT_THREADS, start_time=None, end_time=None, part_size=DEFAULT_PART_SIZE, **kwargs): """ Copy object(s) from one S3 location to another. Works for individual keys or entire directories. When files are larger than `part_size`, multipart uploading will be used. :param source_path: The `s3://` path of the directory or key to copy from :param destination_path: The `s3://` path of the directory or key to copy to :param threads: Optional argument to define the number of threads to use when copying (min: 3 threads) :param start_time: Optional argument to copy files with modified dates after start_time :param end_time: Optional argument to copy files with modified dates before end_time :param part_size: Part size in bytes :param kwargs: Keyword arguments are passed to the boto function `copy` as ExtraArgs :returns tuple (number_of_files_copied, total_size_copied_in_bytes) """ # don't allow threads to be less than 3 threads = 3 if threads < 3 else threads if self.isdir(source_path): return self._copy_dir(source_path, destination_path, threads=threads, start_time=start_time, end_time=end_time, part_size=part_size, **kwargs) # If the file isn't a directory just perform a simple copy else: return self._copy_file(source_path, destination_path, threads=threads, part_size=part_size, **kwargs)
python
def copy(self, source_path, destination_path, threads=DEFAULT_THREADS, start_time=None, end_time=None, part_size=DEFAULT_PART_SIZE, **kwargs): """ Copy object(s) from one S3 location to another. Works for individual keys or entire directories. When files are larger than `part_size`, multipart uploading will be used. :param source_path: The `s3://` path of the directory or key to copy from :param destination_path: The `s3://` path of the directory or key to copy to :param threads: Optional argument to define the number of threads to use when copying (min: 3 threads) :param start_time: Optional argument to copy files with modified dates after start_time :param end_time: Optional argument to copy files with modified dates before end_time :param part_size: Part size in bytes :param kwargs: Keyword arguments are passed to the boto function `copy` as ExtraArgs :returns tuple (number_of_files_copied, total_size_copied_in_bytes) """ # don't allow threads to be less than 3 threads = 3 if threads < 3 else threads if self.isdir(source_path): return self._copy_dir(source_path, destination_path, threads=threads, start_time=start_time, end_time=end_time, part_size=part_size, **kwargs) # If the file isn't a directory just perform a simple copy else: return self._copy_file(source_path, destination_path, threads=threads, part_size=part_size, **kwargs)
[ "def", "copy", "(", "self", ",", "source_path", ",", "destination_path", ",", "threads", "=", "DEFAULT_THREADS", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "part_size", "=", "DEFAULT_PART_SIZE", ",", "*", "*", "kwargs", ")", ":", "# don't allow threads to be less than 3", "threads", "=", "3", "if", "threads", "<", "3", "else", "threads", "if", "self", ".", "isdir", "(", "source_path", ")", ":", "return", "self", ".", "_copy_dir", "(", "source_path", ",", "destination_path", ",", "threads", "=", "threads", ",", "start_time", "=", "start_time", ",", "end_time", "=", "end_time", ",", "part_size", "=", "part_size", ",", "*", "*", "kwargs", ")", "# If the file isn't a directory just perform a simple copy", "else", ":", "return", "self", ".", "_copy_file", "(", "source_path", ",", "destination_path", ",", "threads", "=", "threads", ",", "part_size", "=", "part_size", ",", "*", "*", "kwargs", ")" ]
Copy object(s) from one S3 location to another. Works for individual keys or entire directories. When files are larger than `part_size`, multipart uploading will be used. :param source_path: The `s3://` path of the directory or key to copy from :param destination_path: The `s3://` path of the directory or key to copy to :param threads: Optional argument to define the number of threads to use when copying (min: 3 threads) :param start_time: Optional argument to copy files with modified dates after start_time :param end_time: Optional argument to copy files with modified dates before end_time :param part_size: Part size in bytes :param kwargs: Keyword arguments are passed to the boto function `copy` as ExtraArgs :returns tuple (number_of_files_copied, total_size_copied_in_bytes)
[ "Copy", "object", "(", "s", ")", "from", "one", "S3", "location", "to", "another", ".", "Works", "for", "individual", "keys", "or", "entire", "directories", ".", "When", "files", "are", "larger", "than", "part_size", "multipart", "uploading", "will", "be", "used", ".", ":", "param", "source_path", ":", "The", "s3", ":", "//", "path", "of", "the", "directory", "or", "key", "to", "copy", "from", ":", "param", "destination_path", ":", "The", "s3", ":", "//", "path", "of", "the", "directory", "or", "key", "to", "copy", "to", ":", "param", "threads", ":", "Optional", "argument", "to", "define", "the", "number", "of", "threads", "to", "use", "when", "copying", "(", "min", ":", "3", "threads", ")", ":", "param", "start_time", ":", "Optional", "argument", "to", "copy", "files", "with", "modified", "dates", "after", "start_time", ":", "param", "end_time", ":", "Optional", "argument", "to", "copy", "files", "with", "modified", "dates", "before", "end_time", ":", "param", "part_size", ":", "Part", "size", "in", "bytes", ":", "param", "kwargs", ":", "Keyword", "arguments", "are", "passed", "to", "the", "boto", "function", "copy", "as", "ExtraArgs", ":", "returns", "tuple", "(", "number_of_files_copied", "total_size_copied_in_bytes", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L303-L327
train
spotify/luigi
luigi/contrib/s3.py
S3Client.get
def get(self, s3_path, destination_local_path): """ Get an object stored in S3 and write it to a local path. """ (bucket, key) = self._path_to_bucket_and_key(s3_path) # download the file self.s3.meta.client.download_file(bucket, key, destination_local_path)
python
def get(self, s3_path, destination_local_path): """ Get an object stored in S3 and write it to a local path. """ (bucket, key) = self._path_to_bucket_and_key(s3_path) # download the file self.s3.meta.client.download_file(bucket, key, destination_local_path)
[ "def", "get", "(", "self", ",", "s3_path", ",", "destination_local_path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "s3_path", ")", "# download the file", "self", ".", "s3", ".", "meta", ".", "client", ".", "download_file", "(", "bucket", ",", "key", ",", "destination_local_path", ")" ]
Get an object stored in S3 and write it to a local path.
[ "Get", "an", "object", "stored", "in", "S3", "and", "write", "it", "to", "a", "local", "path", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L383-L389
train
spotify/luigi
luigi/contrib/s3.py
S3Client.get_as_bytes
def get_as_bytes(self, s3_path): """ Get the contents of an object stored in S3 as bytes :param s3_path: URL for target S3 location :return: File contents as pure bytes """ (bucket, key) = self._path_to_bucket_and_key(s3_path) obj = self.s3.Object(bucket, key) contents = obj.get()['Body'].read() return contents
python
def get_as_bytes(self, s3_path): """ Get the contents of an object stored in S3 as bytes :param s3_path: URL for target S3 location :return: File contents as pure bytes """ (bucket, key) = self._path_to_bucket_and_key(s3_path) obj = self.s3.Object(bucket, key) contents = obj.get()['Body'].read() return contents
[ "def", "get_as_bytes", "(", "self", ",", "s3_path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "s3_path", ")", "obj", "=", "self", ".", "s3", ".", "Object", "(", "bucket", ",", "key", ")", "contents", "=", "obj", ".", "get", "(", ")", "[", "'Body'", "]", ".", "read", "(", ")", "return", "contents" ]
Get the contents of an object stored in S3 as bytes :param s3_path: URL for target S3 location :return: File contents as pure bytes
[ "Get", "the", "contents", "of", "an", "object", "stored", "in", "S3", "as", "bytes" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L391-L401
train
spotify/luigi
luigi/contrib/s3.py
S3Client.get_as_string
def get_as_string(self, s3_path, encoding='utf-8'): """ Get the contents of an object stored in S3 as string. :param s3_path: URL for target S3 location :param encoding: Encoding to decode bytes to string :return: File contents as a string """ content = self.get_as_bytes(s3_path) return content.decode(encoding)
python
def get_as_string(self, s3_path, encoding='utf-8'): """ Get the contents of an object stored in S3 as string. :param s3_path: URL for target S3 location :param encoding: Encoding to decode bytes to string :return: File contents as a string """ content = self.get_as_bytes(s3_path) return content.decode(encoding)
[ "def", "get_as_string", "(", "self", ",", "s3_path", ",", "encoding", "=", "'utf-8'", ")", ":", "content", "=", "self", ".", "get_as_bytes", "(", "s3_path", ")", "return", "content", ".", "decode", "(", "encoding", ")" ]
Get the contents of an object stored in S3 as string. :param s3_path: URL for target S3 location :param encoding: Encoding to decode bytes to string :return: File contents as a string
[ "Get", "the", "contents", "of", "an", "object", "stored", "in", "S3", "as", "string", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L403-L412
train
spotify/luigi
luigi/contrib/s3.py
S3Client.isdir
def isdir(self, path): """ Is the parameter S3 path a directory? """ (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root is a directory if self._is_root(key): return True for suffix in (S3_DIRECTORY_MARKER_SUFFIX_0, S3_DIRECTORY_MARKER_SUFFIX_1): try: self.s3.meta.client.get_object( Bucket=bucket, Key=key + suffix) except botocore.exceptions.ClientError as e: if not e.response['Error']['Code'] in ['NoSuchKey', '404']: raise else: return True # files with this prefix key_path = self._add_path_delimiter(key) s3_bucket_list_result = list(itertools.islice( s3_bucket.objects.filter(Prefix=key_path), 1)) if s3_bucket_list_result: return True return False
python
def isdir(self, path): """ Is the parameter S3 path a directory? """ (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root is a directory if self._is_root(key): return True for suffix in (S3_DIRECTORY_MARKER_SUFFIX_0, S3_DIRECTORY_MARKER_SUFFIX_1): try: self.s3.meta.client.get_object( Bucket=bucket, Key=key + suffix) except botocore.exceptions.ClientError as e: if not e.response['Error']['Code'] in ['NoSuchKey', '404']: raise else: return True # files with this prefix key_path = self._add_path_delimiter(key) s3_bucket_list_result = list(itertools.islice( s3_bucket.objects.filter(Prefix=key_path), 1)) if s3_bucket_list_result: return True return False
[ "def", "isdir", "(", "self", ",", "path", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "s3_bucket", "=", "self", ".", "s3", ".", "Bucket", "(", "bucket", ")", "# root is a directory", "if", "self", ".", "_is_root", "(", "key", ")", ":", "return", "True", "for", "suffix", "in", "(", "S3_DIRECTORY_MARKER_SUFFIX_0", ",", "S3_DIRECTORY_MARKER_SUFFIX_1", ")", ":", "try", ":", "self", ".", "s3", ".", "meta", ".", "client", ".", "get_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", "+", "suffix", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "e", ":", "if", "not", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "in", "[", "'NoSuchKey'", ",", "'404'", "]", ":", "raise", "else", ":", "return", "True", "# files with this prefix", "key_path", "=", "self", ".", "_add_path_delimiter", "(", "key", ")", "s3_bucket_list_result", "=", "list", "(", "itertools", ".", "islice", "(", "s3_bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "key_path", ")", ",", "1", ")", ")", "if", "s3_bucket_list_result", ":", "return", "True", "return", "False" ]
Is the parameter S3 path a directory?
[ "Is", "the", "parameter", "S3", "path", "a", "directory?" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L414-L444
train
spotify/luigi
luigi/contrib/s3.py
S3Client.listdir
def listdir(self, path, start_time=None, end_time=None, return_key=False): """ Get an iterable with S3 folder contents. Iterable contains paths relative to queried path. :param path: URL for target S3 location :param start_time: Optional argument to list files with modified (offset aware) datetime after start_time :param end_time: Optional argument to list files with modified (offset aware) datetime before end_time :param return_key: Optional argument, when set to True will return boto3's ObjectSummary (instead of the filename) """ (bucket, key) = self._path_to_bucket_and_key(path) # grab and validate the bucket s3_bucket = self.s3.Bucket(bucket) key_path = self._add_path_delimiter(key) key_path_len = len(key_path) for item in s3_bucket.objects.filter(Prefix=key_path): last_modified_date = item.last_modified if ( # neither are defined, list all (not start_time and not end_time) or # start defined, after start (start_time and not end_time and start_time < last_modified_date) or # end defined, prior to end (not start_time and end_time and last_modified_date < end_time) or (start_time and end_time and start_time < last_modified_date < end_time) # both defined, between ): if return_key: yield item else: yield self._add_path_delimiter(path) + item.key[key_path_len:]
python
def listdir(self, path, start_time=None, end_time=None, return_key=False): """ Get an iterable with S3 folder contents. Iterable contains paths relative to queried path. :param path: URL for target S3 location :param start_time: Optional argument to list files with modified (offset aware) datetime after start_time :param end_time: Optional argument to list files with modified (offset aware) datetime before end_time :param return_key: Optional argument, when set to True will return boto3's ObjectSummary (instead of the filename) """ (bucket, key) = self._path_to_bucket_and_key(path) # grab and validate the bucket s3_bucket = self.s3.Bucket(bucket) key_path = self._add_path_delimiter(key) key_path_len = len(key_path) for item in s3_bucket.objects.filter(Prefix=key_path): last_modified_date = item.last_modified if ( # neither are defined, list all (not start_time and not end_time) or # start defined, after start (start_time and not end_time and start_time < last_modified_date) or # end defined, prior to end (not start_time and end_time and last_modified_date < end_time) or (start_time and end_time and start_time < last_modified_date < end_time) # both defined, between ): if return_key: yield item else: yield self._add_path_delimiter(path) + item.key[key_path_len:]
[ "def", "listdir", "(", "self", ",", "path", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "return_key", "=", "False", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "# grab and validate the bucket", "s3_bucket", "=", "self", ".", "s3", ".", "Bucket", "(", "bucket", ")", "key_path", "=", "self", ".", "_add_path_delimiter", "(", "key", ")", "key_path_len", "=", "len", "(", "key_path", ")", "for", "item", "in", "s3_bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "key_path", ")", ":", "last_modified_date", "=", "item", ".", "last_modified", "if", "(", "# neither are defined, list all", "(", "not", "start_time", "and", "not", "end_time", ")", "or", "# start defined, after start", "(", "start_time", "and", "not", "end_time", "and", "start_time", "<", "last_modified_date", ")", "or", "# end defined, prior to end", "(", "not", "start_time", "and", "end_time", "and", "last_modified_date", "<", "end_time", ")", "or", "(", "start_time", "and", "end_time", "and", "start_time", "<", "last_modified_date", "<", "end_time", ")", "# both defined, between", ")", ":", "if", "return_key", ":", "yield", "item", "else", ":", "yield", "self", ".", "_add_path_delimiter", "(", "path", ")", "+", "item", ".", "key", "[", "key_path_len", ":", "]" ]
Get an iterable with S3 folder contents. Iterable contains paths relative to queried path. :param path: URL for target S3 location :param start_time: Optional argument to list files with modified (offset aware) datetime after start_time :param end_time: Optional argument to list files with modified (offset aware) datetime before end_time :param return_key: Optional argument, when set to True will return boto3's ObjectSummary (instead of the filename)
[ "Get", "an", "iterable", "with", "S3", "folder", "contents", ".", "Iterable", "contains", "paths", "relative", "to", "queried", "path", ".", ":", "param", "path", ":", "URL", "for", "target", "S3", "location", ":", "param", "start_time", ":", "Optional", "argument", "to", "list", "files", "with", "modified", "(", "offset", "aware", ")", "datetime", "after", "start_time", ":", "param", "end_time", ":", "Optional", "argument", "to", "list", "files", "with", "modified", "(", "offset", "aware", ")", "datetime", "before", "end_time", ":", "param", "return_key", ":", "Optional", "argument", "when", "set", "to", "True", "will", "return", "boto3", "s", "ObjectSummary", "(", "instead", "of", "the", "filename", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L464-L495
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem.exists
def exists(self, path, mtime=None): """ Return `True` if file or directory at `path` exist, False otherwise. Additional check on modified time when mtime is passed in. Return False if the file's modified time is older mtime. """ self._connect() if self.sftp: exists = self._sftp_exists(path, mtime) else: exists = self._ftp_exists(path, mtime) self._close() return exists
python
def exists(self, path, mtime=None): """ Return `True` if file or directory at `path` exist, False otherwise. Additional check on modified time when mtime is passed in. Return False if the file's modified time is older mtime. """ self._connect() if self.sftp: exists = self._sftp_exists(path, mtime) else: exists = self._ftp_exists(path, mtime) self._close() return exists
[ "def", "exists", "(", "self", ",", "path", ",", "mtime", "=", "None", ")", ":", "self", ".", "_connect", "(", ")", "if", "self", ".", "sftp", ":", "exists", "=", "self", ".", "_sftp_exists", "(", "path", ",", "mtime", ")", "else", ":", "exists", "=", "self", ".", "_ftp_exists", "(", "path", ",", "mtime", ")", "self", ".", "_close", "(", ")", "return", "exists" ]
Return `True` if file or directory at `path` exist, False otherwise. Additional check on modified time when mtime is passed in. Return False if the file's modified time is older mtime.
[ "Return", "True", "if", "file", "or", "directory", "at", "path", "exist", "False", "otherwise", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L109-L126
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem.remove
def remove(self, path, recursive=True): """ Remove file or directory at location ``path``. :param path: a path within the FileSystem to remove. :type path: str :param recursive: if the path is a directory, recursively remove the directory and all of its descendants. Defaults to ``True``. :type recursive: bool """ self._connect() if self.sftp: self._sftp_remove(path, recursive) else: self._ftp_remove(path, recursive) self._close()
python
def remove(self, path, recursive=True): """ Remove file or directory at location ``path``. :param path: a path within the FileSystem to remove. :type path: str :param recursive: if the path is a directory, recursively remove the directory and all of its descendants. Defaults to ``True``. :type recursive: bool """ self._connect() if self.sftp: self._sftp_remove(path, recursive) else: self._ftp_remove(path, recursive) self._close()
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "True", ")", ":", "self", ".", "_connect", "(", ")", "if", "self", ".", "sftp", ":", "self", ".", "_sftp_remove", "(", "path", ",", "recursive", ")", "else", ":", "self", ".", "_ftp_remove", "(", "path", ",", "recursive", ")", "self", ".", "_close", "(", ")" ]
Remove file or directory at location ``path``. :param path: a path within the FileSystem to remove. :type path: str :param recursive: if the path is a directory, recursively remove the directory and all of its descendants. Defaults to ``True``. :type recursive: bool
[ "Remove", "file", "or", "directory", "at", "location", "path", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L151-L168
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem._rm_recursive
def _rm_recursive(self, ftp, path): """ Recursively delete a directory tree on a remote server. Source: https://gist.github.com/artlogic/2632647 """ wd = ftp.pwd() # check if it is a file first, because some FTP servers don't return # correctly on ftp.nlst(file) try: ftp.cwd(path) except ftplib.all_errors: # this is a file, we will just delete the file ftp.delete(path) return try: names = ftp.nlst() except ftplib.all_errors: # some FTP servers complain when you try and list non-existent paths return for name in names: if os.path.split(name)[1] in ('.', '..'): continue try: ftp.cwd(name) # if we can cwd to it, it's a folder ftp.cwd(wd) # don't try a nuke a folder we're in ftp.cwd(path) # then go back to where we were self._rm_recursive(ftp, name) except ftplib.all_errors: ftp.delete(name) try: ftp.cwd(wd) # do not delete the folder that we are in ftp.rmd(path) except ftplib.all_errors as e: print('_rm_recursive: Could not remove {0}: {1}'.format(path, e))
python
def _rm_recursive(self, ftp, path): """ Recursively delete a directory tree on a remote server. Source: https://gist.github.com/artlogic/2632647 """ wd = ftp.pwd() # check if it is a file first, because some FTP servers don't return # correctly on ftp.nlst(file) try: ftp.cwd(path) except ftplib.all_errors: # this is a file, we will just delete the file ftp.delete(path) return try: names = ftp.nlst() except ftplib.all_errors: # some FTP servers complain when you try and list non-existent paths return for name in names: if os.path.split(name)[1] in ('.', '..'): continue try: ftp.cwd(name) # if we can cwd to it, it's a folder ftp.cwd(wd) # don't try a nuke a folder we're in ftp.cwd(path) # then go back to where we were self._rm_recursive(ftp, name) except ftplib.all_errors: ftp.delete(name) try: ftp.cwd(wd) # do not delete the folder that we are in ftp.rmd(path) except ftplib.all_errors as e: print('_rm_recursive: Could not remove {0}: {1}'.format(path, e))
[ "def", "_rm_recursive", "(", "self", ",", "ftp", ",", "path", ")", ":", "wd", "=", "ftp", ".", "pwd", "(", ")", "# check if it is a file first, because some FTP servers don't return", "# correctly on ftp.nlst(file)", "try", ":", "ftp", ".", "cwd", "(", "path", ")", "except", "ftplib", ".", "all_errors", ":", "# this is a file, we will just delete the file", "ftp", ".", "delete", "(", "path", ")", "return", "try", ":", "names", "=", "ftp", ".", "nlst", "(", ")", "except", "ftplib", ".", "all_errors", ":", "# some FTP servers complain when you try and list non-existent paths", "return", "for", "name", "in", "names", ":", "if", "os", ".", "path", ".", "split", "(", "name", ")", "[", "1", "]", "in", "(", "'.'", ",", "'..'", ")", ":", "continue", "try", ":", "ftp", ".", "cwd", "(", "name", ")", "# if we can cwd to it, it's a folder", "ftp", ".", "cwd", "(", "wd", ")", "# don't try a nuke a folder we're in", "ftp", ".", "cwd", "(", "path", ")", "# then go back to where we were", "self", ".", "_rm_recursive", "(", "ftp", ",", "name", ")", "except", "ftplib", ".", "all_errors", ":", "ftp", ".", "delete", "(", "name", ")", "try", ":", "ftp", ".", "cwd", "(", "wd", ")", "# do not delete the folder that we are in", "ftp", ".", "rmd", "(", "path", ")", "except", "ftplib", ".", "all_errors", "as", "e", ":", "print", "(", "'_rm_recursive: Could not remove {0}: {1}'", ".", "format", "(", "path", ",", "e", ")", ")" ]
Recursively delete a directory tree on a remote server. Source: https://gist.github.com/artlogic/2632647
[ "Recursively", "delete", "a", "directory", "tree", "on", "a", "remote", "server", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L197-L236
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem.put
def put(self, local_path, path, atomic=True): """ Put file from local filesystem to (s)FTP. """ self._connect() if self.sftp: self._sftp_put(local_path, path, atomic) else: self._ftp_put(local_path, path, atomic) self._close()
python
def put(self, local_path, path, atomic=True): """ Put file from local filesystem to (s)FTP. """ self._connect() if self.sftp: self._sftp_put(local_path, path, atomic) else: self._ftp_put(local_path, path, atomic) self._close()
[ "def", "put", "(", "self", ",", "local_path", ",", "path", ",", "atomic", "=", "True", ")", ":", "self", ".", "_connect", "(", ")", "if", "self", ".", "sftp", ":", "self", ".", "_sftp_put", "(", "local_path", ",", "path", ",", "atomic", ")", "else", ":", "self", ".", "_ftp_put", "(", "local_path", ",", "path", ",", "atomic", ")", "self", ".", "_close", "(", ")" ]
Put file from local filesystem to (s)FTP.
[ "Put", "file", "from", "local", "filesystem", "to", "(", "s", ")", "FTP", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L238-L249
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem.get
def get(self, path, local_path): """ Download file from (s)FTP to local filesystem. """ normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder and not os.path.exists(folder): os.makedirs(folder) tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # download file self._connect() if self.sftp: self._sftp_get(path, tmp_local_path) else: self._ftp_get(path, tmp_local_path) self._close() os.rename(tmp_local_path, local_path)
python
def get(self, path, local_path): """ Download file from (s)FTP to local filesystem. """ normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder and not os.path.exists(folder): os.makedirs(folder) tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # download file self._connect() if self.sftp: self._sftp_get(path, tmp_local_path) else: self._ftp_get(path, tmp_local_path) self._close() os.rename(tmp_local_path, local_path)
[ "def", "get", "(", "self", ",", "path", ",", "local_path", ")", ":", "normpath", "=", "os", ".", "path", ".", "normpath", "(", "local_path", ")", "folder", "=", "os", ".", "path", ".", "dirname", "(", "normpath", ")", "if", "folder", "and", "not", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "os", ".", "makedirs", "(", "folder", ")", "tmp_local_path", "=", "local_path", "+", "'-luigi-tmp-%09d'", "%", "random", ".", "randrange", "(", "0", ",", "1e10", ")", "# download file", "self", ".", "_connect", "(", ")", "if", "self", ".", "sftp", ":", "self", ".", "_sftp_get", "(", "path", ",", "tmp_local_path", ")", "else", ":", "self", ".", "_ftp_get", "(", "path", ",", "tmp_local_path", ")", "self", ".", "_close", "(", ")", "os", ".", "rename", "(", "tmp_local_path", ",", "local_path", ")" ]
Download file from (s)FTP to local filesystem.
[ "Download", "file", "from", "(", "s", ")", "FTP", "to", "local", "filesystem", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L291-L312
train
spotify/luigi
luigi/contrib/ftp.py
RemoteFileSystem.listdir
def listdir(self, path='.'): """ Gets an list of the contents of path in (s)FTP """ self._connect() if self.sftp: contents = self._sftp_listdir(path) else: contents = self._ftp_listdir(path) self._close() return contents
python
def listdir(self, path='.'): """ Gets an list of the contents of path in (s)FTP """ self._connect() if self.sftp: contents = self._sftp_listdir(path) else: contents = self._ftp_listdir(path) self._close() return contents
[ "def", "listdir", "(", "self", ",", "path", "=", "'.'", ")", ":", "self", ".", "_connect", "(", ")", "if", "self", ".", "sftp", ":", "contents", "=", "self", ".", "_sftp_listdir", "(", "path", ")", "else", ":", "contents", "=", "self", ".", "_ftp_listdir", "(", "path", ")", "self", ".", "_close", "(", ")", "return", "contents" ]
Gets an list of the contents of path in (s)FTP
[ "Gets", "an", "list", "of", "the", "contents", "of", "path", "in", "(", "s", ")", "FTP" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L320-L333
train
spotify/luigi
luigi/contrib/ftp.py
RemoteTarget.open
def open(self, mode): """ Open the FileSystem target. This method returns a file-like object which can either be read from or written to depending on the specified mode. :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will open the FileSystemTarget in write mode. Subclasses can implement additional options. :type mode: str """ if mode == 'w': return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path)) elif mode == 'r': temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp') self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # download file to local self._fs.get(self.path, self.__tmp_path) return self.format.pipe_reader( FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r'))) ) else: raise Exception("mode must be 'r' or 'w' (got: %s)" % mode)
python
def open(self, mode): """ Open the FileSystem target. This method returns a file-like object which can either be read from or written to depending on the specified mode. :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will open the FileSystemTarget in write mode. Subclasses can implement additional options. :type mode: str """ if mode == 'w': return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path)) elif mode == 'r': temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp') self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # download file to local self._fs.get(self.path, self.__tmp_path) return self.format.pipe_reader( FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r'))) ) else: raise Exception("mode must be 'r' or 'w' (got: %s)" % mode)
[ "def", "open", "(", "self", ",", "mode", ")", ":", "if", "mode", "==", "'w'", ":", "return", "self", ".", "format", ".", "pipe_writer", "(", "AtomicFtpFile", "(", "self", ".", "_fs", ",", "self", ".", "path", ")", ")", "elif", "mode", "==", "'r'", ":", "temp_dir", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "'luigi-contrib-ftp'", ")", "self", ".", "__tmp_path", "=", "temp_dir", "+", "'/'", "+", "self", ".", "path", ".", "lstrip", "(", "'/'", ")", "+", "'-luigi-tmp-%09d'", "%", "random", ".", "randrange", "(", "0", ",", "1e10", ")", "# download file to local", "self", ".", "_fs", ".", "get", "(", "self", ".", "path", ",", "self", ".", "__tmp_path", ")", "return", "self", ".", "format", ".", "pipe_reader", "(", "FileWrapper", "(", "io", ".", "BufferedReader", "(", "io", ".", "FileIO", "(", "self", ".", "__tmp_path", ",", "'r'", ")", ")", ")", ")", "else", ":", "raise", "Exception", "(", "\"mode must be 'r' or 'w' (got: %s)\"", "%", "mode", ")" ]
Open the FileSystem target. This method returns a file-like object which can either be read from or written to depending on the specified mode. :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will open the FileSystemTarget in write mode. Subclasses can implement additional options. :type mode: str
[ "Open", "the", "FileSystem", "target", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L394-L419
train
spotify/luigi
luigi/contrib/mongodb.py
MongoTarget.get_collection
def get_collection(self): """ Return targeted mongo collection to query on """ db_mongo = self._mongo_client[self._index] return db_mongo[self._collection]
python
def get_collection(self): """ Return targeted mongo collection to query on """ db_mongo = self._mongo_client[self._index] return db_mongo[self._collection]
[ "def", "get_collection", "(", "self", ")", ":", "db_mongo", "=", "self", ".", "_mongo_client", "[", "self", ".", "_index", "]", "return", "db_mongo", "[", "self", ".", "_collection", "]" ]
Return targeted mongo collection to query on
[ "Return", "targeted", "mongo", "collection", "to", "query", "on" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L38-L43
train
spotify/luigi
luigi/contrib/mongodb.py
MongoCellTarget.read
def read(self): """ Read the target value Use $project aggregate operator in order to support nested objects """ result = self.get_collection().aggregate([ {'$match': {'_id': self._document_id}}, {'$project': {'_value': '$' + self._path, '_id': False}} ]) for doc in result: if '_value' not in doc: break return doc['_value']
python
def read(self): """ Read the target value Use $project aggregate operator in order to support nested objects """ result = self.get_collection().aggregate([ {'$match': {'_id': self._document_id}}, {'$project': {'_value': '$' + self._path, '_id': False}} ]) for doc in result: if '_value' not in doc: break return doc['_value']
[ "def", "read", "(", "self", ")", ":", "result", "=", "self", ".", "get_collection", "(", ")", ".", "aggregate", "(", "[", "{", "'$match'", ":", "{", "'_id'", ":", "self", ".", "_document_id", "}", "}", ",", "{", "'$project'", ":", "{", "'_value'", ":", "'$'", "+", "self", ".", "_path", ",", "'_id'", ":", "False", "}", "}", "]", ")", "for", "doc", "in", "result", ":", "if", "'_value'", "not", "in", "doc", ":", "break", "return", "doc", "[", "'_value'", "]" ]
Read the target value Use $project aggregate operator in order to support nested objects
[ "Read", "the", "target", "value", "Use", "$project", "aggregate", "operator", "in", "order", "to", "support", "nested", "objects" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L75-L89
train
spotify/luigi
luigi/contrib/mongodb.py
MongoCellTarget.write
def write(self, value): """ Write value to the target """ self.get_collection().update_one( {'_id': self._document_id}, {'$set': {self._path: value}}, upsert=True )
python
def write(self, value): """ Write value to the target """ self.get_collection().update_one( {'_id': self._document_id}, {'$set': {self._path: value}}, upsert=True )
[ "def", "write", "(", "self", ",", "value", ")", ":", "self", ".", "get_collection", "(", ")", ".", "update_one", "(", "{", "'_id'", ":", "self", ".", "_document_id", "}", ",", "{", "'$set'", ":", "{", "self", ".", "_path", ":", "value", "}", "}", ",", "upsert", "=", "True", ")" ]
Write value to the target
[ "Write", "value", "to", "the", "target" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L91-L99
train
spotify/luigi
luigi/contrib/mongodb.py
MongoRangeTarget.read
def read(self): """ Read the targets value """ cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {self._field: True} ) return {doc['_id']: doc[self._field] for doc in cursor}
python
def read(self): """ Read the targets value """ cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {self._field: True} ) return {doc['_id']: doc[self._field] for doc in cursor}
[ "def", "read", "(", "self", ")", ":", "cursor", "=", "self", ".", "get_collection", "(", ")", ".", "find", "(", "{", "'_id'", ":", "{", "'$in'", ":", "self", ".", "_document_ids", "}", ",", "self", ".", "_field", ":", "{", "'$exists'", ":", "True", "}", "}", ",", "{", "self", ".", "_field", ":", "True", "}", ")", "return", "{", "doc", "[", "'_id'", "]", ":", "doc", "[", "self", ".", "_field", "]", "for", "doc", "in", "cursor", "}" ]
Read the targets value
[ "Read", "the", "targets", "value" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L125-L137
train
spotify/luigi
luigi/contrib/mongodb.py
MongoRangeTarget.write
def write(self, values): """ Write values to the targeted documents Values need to be a dict as : {document_id: value} """ # Insert only for docs targeted by the target filtered = {_id: value for _id, value in values.items() if _id in self._document_ids} if not filtered: return bulk = self.get_collection().initialize_ordered_bulk_op() for _id, value in filtered.items(): bulk.find({'_id': _id}).upsert() \ .update_one({'$set': {self._field: value}}) bulk.execute()
python
def write(self, values): """ Write values to the targeted documents Values need to be a dict as : {document_id: value} """ # Insert only for docs targeted by the target filtered = {_id: value for _id, value in values.items() if _id in self._document_ids} if not filtered: return bulk = self.get_collection().initialize_ordered_bulk_op() for _id, value in filtered.items(): bulk.find({'_id': _id}).upsert() \ .update_one({'$set': {self._field: value}}) bulk.execute()
[ "def", "write", "(", "self", ",", "values", ")", ":", "# Insert only for docs targeted by the target", "filtered", "=", "{", "_id", ":", "value", "for", "_id", ",", "value", "in", "values", ".", "items", "(", ")", "if", "_id", "in", "self", ".", "_document_ids", "}", "if", "not", "filtered", ":", "return", "bulk", "=", "self", ".", "get_collection", "(", ")", ".", "initialize_ordered_bulk_op", "(", ")", "for", "_id", ",", "value", "in", "filtered", ".", "items", "(", ")", ":", "bulk", ".", "find", "(", "{", "'_id'", ":", "_id", "}", ")", ".", "upsert", "(", ")", ".", "update_one", "(", "{", "'$set'", ":", "{", "self", ".", "_field", ":", "value", "}", "}", ")", "bulk", ".", "execute", "(", ")" ]
Write values to the targeted documents Values need to be a dict as : {document_id: value}
[ "Write", "values", "to", "the", "targeted", "documents", "Values", "need", "to", "be", "a", "dict", "as", ":", "{", "document_id", ":", "value", "}" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L139-L155
train
spotify/luigi
luigi/contrib/mongodb.py
MongoRangeTarget.get_empty_ids
def get_empty_ids(self): """ Get documents id with missing targeted field """ cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {'_id': True} ) return set(self._document_ids) - {doc['_id'] for doc in cursor}
python
def get_empty_ids(self): """ Get documents id with missing targeted field """ cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {'_id': True} ) return set(self._document_ids) - {doc['_id'] for doc in cursor}
[ "def", "get_empty_ids", "(", "self", ")", ":", "cursor", "=", "self", ".", "get_collection", "(", ")", ".", "find", "(", "{", "'_id'", ":", "{", "'$in'", ":", "self", ".", "_document_ids", "}", ",", "self", ".", "_field", ":", "{", "'$exists'", ":", "True", "}", "}", ",", "{", "'_id'", ":", "True", "}", ")", "return", "set", "(", "self", ".", "_document_ids", ")", "-", "{", "doc", "[", "'_id'", "]", "for", "doc", "in", "cursor", "}" ]
Get documents id with missing targeted field
[ "Get", "documents", "id", "with", "missing", "targeted", "field" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L157-L169
train
spotify/luigi
luigi/setup_logging.py
BaseLogging._section
def _section(cls, opts): """Get logging settings from config file section "logging".""" if isinstance(cls.config, LuigiConfigParser): return False try: logging_config = cls.config['logging'] except (TypeError, KeyError, NoSectionError): return False logging.config.dictConfig(logging_config) return True
python
def _section(cls, opts): """Get logging settings from config file section "logging".""" if isinstance(cls.config, LuigiConfigParser): return False try: logging_config = cls.config['logging'] except (TypeError, KeyError, NoSectionError): return False logging.config.dictConfig(logging_config) return True
[ "def", "_section", "(", "cls", ",", "opts", ")", ":", "if", "isinstance", "(", "cls", ".", "config", ",", "LuigiConfigParser", ")", ":", "return", "False", "try", ":", "logging_config", "=", "cls", ".", "config", "[", "'logging'", "]", "except", "(", "TypeError", ",", "KeyError", ",", "NoSectionError", ")", ":", "return", "False", "logging", ".", "config", ".", "dictConfig", "(", "logging_config", ")", "return", "True" ]
Get logging settings from config file section "logging".
[ "Get", "logging", "settings", "from", "config", "file", "section", "logging", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L40-L49
train
spotify/luigi
luigi/setup_logging.py
BaseLogging.setup
def setup(cls, opts=type('opts', (), { 'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG' })): """Setup logging via CLI params and config.""" logger = logging.getLogger('luigi') if cls._configured: logger.info('logging already configured') return False cls._configured = True if cls.config.getboolean('core', 'no_configure_logging', False): logger.info('logging disabled in settings') return False configured = cls._cli(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via special settings') return True configured = cls._conf(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via *.conf file') return True configured = cls._section(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via config section') return True configured = cls._default(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured by default settings') return configured
python
def setup(cls, opts=type('opts', (), { 'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG' })): """Setup logging via CLI params and config.""" logger = logging.getLogger('luigi') if cls._configured: logger.info('logging already configured') return False cls._configured = True if cls.config.getboolean('core', 'no_configure_logging', False): logger.info('logging disabled in settings') return False configured = cls._cli(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via special settings') return True configured = cls._conf(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via *.conf file') return True configured = cls._section(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured via config section') return True configured = cls._default(opts) if configured: logger = logging.getLogger('luigi') logger.info('logging configured by default settings') return configured
[ "def", "setup", "(", "cls", ",", "opts", "=", "type", "(", "'opts'", ",", "(", ")", ",", "{", "'background'", ":", "None", ",", "'logdir'", ":", "None", ",", "'logging_conf_file'", ":", "None", ",", "'log_level'", ":", "'DEBUG'", "}", ")", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'luigi'", ")", "if", "cls", ".", "_configured", ":", "logger", ".", "info", "(", "'logging already configured'", ")", "return", "False", "cls", ".", "_configured", "=", "True", "if", "cls", ".", "config", ".", "getboolean", "(", "'core'", ",", "'no_configure_logging'", ",", "False", ")", ":", "logger", ".", "info", "(", "'logging disabled in settings'", ")", "return", "False", "configured", "=", "cls", ".", "_cli", "(", "opts", ")", "if", "configured", ":", "logger", "=", "logging", ".", "getLogger", "(", "'luigi'", ")", "logger", ".", "info", "(", "'logging configured via special settings'", ")", "return", "True", "configured", "=", "cls", ".", "_conf", "(", "opts", ")", "if", "configured", ":", "logger", "=", "logging", ".", "getLogger", "(", "'luigi'", ")", "logger", ".", "info", "(", "'logging configured via *.conf file'", ")", "return", "True", "configured", "=", "cls", ".", "_section", "(", "opts", ")", "if", "configured", ":", "logger", "=", "logging", ".", "getLogger", "(", "'luigi'", ")", "logger", ".", "info", "(", "'logging configured via config section'", ")", "return", "True", "configured", "=", "cls", ".", "_default", "(", "opts", ")", "if", "configured", ":", "logger", "=", "logging", ".", "getLogger", "(", "'luigi'", ")", "logger", ".", "info", "(", "'logging configured by default settings'", ")", "return", "configured" ]
Setup logging via CLI params and config.
[ "Setup", "logging", "via", "CLI", "params", "and", "config", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L52-L93
train
spotify/luigi
luigi/setup_logging.py
DaemonLogging._cli
def _cli(cls, opts): """Setup logging via CLI options If `--background` -- set INFO level for root logger. If `--logdir` -- set logging with next params: default Luigi's formatter, INFO level, output in logdir in `luigi-server.log` file """ if opts.background: logging.getLogger().setLevel(logging.INFO) return True if opts.logdir: logging.basicConfig( level=logging.INFO, format=cls._log_format, filename=os.path.join(opts.logdir, "luigi-server.log")) return True return False
python
def _cli(cls, opts): """Setup logging via CLI options If `--background` -- set INFO level for root logger. If `--logdir` -- set logging with next params: default Luigi's formatter, INFO level, output in logdir in `luigi-server.log` file """ if opts.background: logging.getLogger().setLevel(logging.INFO) return True if opts.logdir: logging.basicConfig( level=logging.INFO, format=cls._log_format, filename=os.path.join(opts.logdir, "luigi-server.log")) return True return False
[ "def", "_cli", "(", "cls", ",", "opts", ")", ":", "if", "opts", ".", "background", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "INFO", ")", "return", "True", "if", "opts", ".", "logdir", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "cls", ".", "_log_format", ",", "filename", "=", "os", ".", "path", ".", "join", "(", "opts", ".", "logdir", ",", "\"luigi-server.log\"", ")", ")", "return", "True", "return", "False" ]
Setup logging via CLI options If `--background` -- set INFO level for root logger. If `--logdir` -- set logging with next params: default Luigi's formatter, INFO level, output in logdir in `luigi-server.log` file
[ "Setup", "logging", "via", "CLI", "options" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L103-L123
train
spotify/luigi
luigi/setup_logging.py
DaemonLogging._conf
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" logging_conf = cls.config.get('core', 'logging_conf_file', None) if logging_conf is None: return False if not os.path.exists(logging_conf): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy raise OSError("Error: Unable to locate specified logging configuration file!") logging.config.fileConfig(logging_conf) return True
python
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" logging_conf = cls.config.get('core', 'logging_conf_file', None) if logging_conf is None: return False if not os.path.exists(logging_conf): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy raise OSError("Error: Unable to locate specified logging configuration file!") logging.config.fileConfig(logging_conf) return True
[ "def", "_conf", "(", "cls", ",", "opts", ")", ":", "logging_conf", "=", "cls", ".", "config", ".", "get", "(", "'core'", ",", "'logging_conf_file'", ",", "None", ")", "if", "logging_conf", "is", "None", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "logging_conf", ")", ":", "# FileNotFoundError added only in Python 3.3", "# https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy", "raise", "OSError", "(", "\"Error: Unable to locate specified logging configuration file!\"", ")", "logging", ".", "config", ".", "fileConfig", "(", "logging_conf", ")", "return", "True" ]
Setup logging via ini-file from logging_conf_file option.
[ "Setup", "logging", "via", "ini", "-", "file", "from", "logging_conf_file", "option", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L126-L138
train
spotify/luigi
luigi/setup_logging.py
DaemonLogging._default
def _default(cls, opts): """Setup default logger""" logging.basicConfig(level=logging.INFO, format=cls._log_format) return True
python
def _default(cls, opts): """Setup default logger""" logging.basicConfig(level=logging.INFO, format=cls._log_format) return True
[ "def", "_default", "(", "cls", ",", "opts", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "cls", ".", "_log_format", ")", "return", "True" ]
Setup default logger
[ "Setup", "default", "logger" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L141-L144
train
spotify/luigi
luigi/setup_logging.py
InterfaceLogging._conf
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" if not opts.logging_conf_file: return False if not os.path.exists(opts.logging_conf_file): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy raise OSError("Error: Unable to locate specified logging configuration file!") logging.config.fileConfig(opts.logging_conf_file, disable_existing_loggers=False) return True
python
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" if not opts.logging_conf_file: return False if not os.path.exists(opts.logging_conf_file): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy raise OSError("Error: Unable to locate specified logging configuration file!") logging.config.fileConfig(opts.logging_conf_file, disable_existing_loggers=False) return True
[ "def", "_conf", "(", "cls", ",", "opts", ")", ":", "if", "not", "opts", ".", "logging_conf_file", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "opts", ".", "logging_conf_file", ")", ":", "# FileNotFoundError added only in Python 3.3", "# https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy", "raise", "OSError", "(", "\"Error: Unable to locate specified logging configuration file!\"", ")", "logging", ".", "config", ".", "fileConfig", "(", "opts", ".", "logging_conf_file", ",", "disable_existing_loggers", "=", "False", ")", "return", "True" ]
Setup logging via ini-file from logging_conf_file option.
[ "Setup", "logging", "via", "ini", "-", "file", "from", "logging_conf_file", "option", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L157-L168
train
spotify/luigi
luigi/setup_logging.py
InterfaceLogging._default
def _default(cls, opts): """Setup default logger""" level = getattr(logging, opts.log_level, logging.DEBUG) logger = logging.getLogger('luigi-interface') logger.setLevel(level) stream_handler = logging.StreamHandler() stream_handler.setLevel(level) formatter = logging.Formatter('%(levelname)s: %(message)s') stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) return True
python
def _default(cls, opts): """Setup default logger""" level = getattr(logging, opts.log_level, logging.DEBUG) logger = logging.getLogger('luigi-interface') logger.setLevel(level) stream_handler = logging.StreamHandler() stream_handler.setLevel(level) formatter = logging.Formatter('%(levelname)s: %(message)s') stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) return True
[ "def", "_default", "(", "cls", ",", "opts", ")", ":", "level", "=", "getattr", "(", "logging", ",", "opts", ".", "log_level", ",", "logging", ".", "DEBUG", ")", "logger", "=", "logging", ".", "getLogger", "(", "'luigi-interface'", ")", "logger", ".", "setLevel", "(", "level", ")", "stream_handler", "=", "logging", ".", "StreamHandler", "(", ")", "stream_handler", ".", "setLevel", "(", "level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(levelname)s: %(message)s'", ")", "stream_handler", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "stream_handler", ")", "return", "True" ]
Setup default logger
[ "Setup", "default", "logger" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L171-L185
train
spotify/luigi
luigi/contrib/hdfs/config.py
get_configured_hdfs_client
def get_configured_hdfs_client(): """ This is a helper that fetches the configuration value for 'client' in the [hdfs] section. It will return the client that retains backwards compatibility when 'client' isn't configured. """ config = hdfs() custom = config.client conf_usinf_snakebite = [ "snakebite_with_hadoopcli_fallback", "snakebite", ] if six.PY3 and (custom in conf_usinf_snakebite): warnings.warn( "snakebite client not compatible with python3 at the moment" "falling back on hadoopcli", stacklevel=2 ) return "hadoopcli" return custom
python
def get_configured_hdfs_client(): """ This is a helper that fetches the configuration value for 'client' in the [hdfs] section. It will return the client that retains backwards compatibility when 'client' isn't configured. """ config = hdfs() custom = config.client conf_usinf_snakebite = [ "snakebite_with_hadoopcli_fallback", "snakebite", ] if six.PY3 and (custom in conf_usinf_snakebite): warnings.warn( "snakebite client not compatible with python3 at the moment" "falling back on hadoopcli", stacklevel=2 ) return "hadoopcli" return custom
[ "def", "get_configured_hdfs_client", "(", ")", ":", "config", "=", "hdfs", "(", ")", "custom", "=", "config", ".", "client", "conf_usinf_snakebite", "=", "[", "\"snakebite_with_hadoopcli_fallback\"", ",", "\"snakebite\"", ",", "]", "if", "six", ".", "PY3", "and", "(", "custom", "in", "conf_usinf_snakebite", ")", ":", "warnings", ".", "warn", "(", "\"snakebite client not compatible with python3 at the moment\"", "\"falling back on hadoopcli\"", ",", "stacklevel", "=", "2", ")", "return", "\"hadoopcli\"", "return", "custom" ]
This is a helper that fetches the configuration value for 'client' in the [hdfs] section. It will return the client that retains backwards compatibility when 'client' isn't configured.
[ "This", "is", "a", "helper", "that", "fetches", "the", "configuration", "value", "for", "client", "in", "the", "[", "hdfs", "]", "section", ".", "It", "will", "return", "the", "client", "that", "retains", "backwards", "compatibility", "when", "client", "isn", "t", "configured", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/config.py#L80-L99
train
spotify/luigi
luigi/contrib/hdfs/config.py
tmppath
def tmppath(path=None, include_unix_username=True): """ @param path: target path for which it is needed to generate temporary location @type path: str @type include_unix_username: bool @rtype: str Note that include_unix_username might work on windows too. """ addon = "luigitemp-%08d" % random.randrange(1e9) temp_dir = '/tmp' # default tmp dir if none is specified in config # 1. Figure out to which temporary directory to place configured_hdfs_tmp_dir = hdfs().tmp_dir if configured_hdfs_tmp_dir is not None: # config is superior base_dir = configured_hdfs_tmp_dir elif path is not None: # need to copy correct schema and network location parsed = urlparse(path) base_dir = urlunparse((parsed.scheme, parsed.netloc, temp_dir, '', '', '')) else: # just system temporary directory base_dir = temp_dir # 2. Figure out what to place if path is not None: if path.startswith(temp_dir + '/'): # Not 100%, but some protection from directories like /tmp/tmp/file subdir = path[len(temp_dir):] else: # Protection from /tmp/hdfs:/dir/file parsed = urlparse(path) subdir = parsed.path subdir = subdir.lstrip('/') + '-' else: # just return any random temporary location subdir = '' if include_unix_username: subdir = os.path.join(getpass.getuser(), subdir) return os.path.join(base_dir, subdir + addon)
python
def tmppath(path=None, include_unix_username=True): """ @param path: target path for which it is needed to generate temporary location @type path: str @type include_unix_username: bool @rtype: str Note that include_unix_username might work on windows too. """ addon = "luigitemp-%08d" % random.randrange(1e9) temp_dir = '/tmp' # default tmp dir if none is specified in config # 1. Figure out to which temporary directory to place configured_hdfs_tmp_dir = hdfs().tmp_dir if configured_hdfs_tmp_dir is not None: # config is superior base_dir = configured_hdfs_tmp_dir elif path is not None: # need to copy correct schema and network location parsed = urlparse(path) base_dir = urlunparse((parsed.scheme, parsed.netloc, temp_dir, '', '', '')) else: # just system temporary directory base_dir = temp_dir # 2. Figure out what to place if path is not None: if path.startswith(temp_dir + '/'): # Not 100%, but some protection from directories like /tmp/tmp/file subdir = path[len(temp_dir):] else: # Protection from /tmp/hdfs:/dir/file parsed = urlparse(path) subdir = parsed.path subdir = subdir.lstrip('/') + '-' else: # just return any random temporary location subdir = '' if include_unix_username: subdir = os.path.join(getpass.getuser(), subdir) return os.path.join(base_dir, subdir + addon)
[ "def", "tmppath", "(", "path", "=", "None", ",", "include_unix_username", "=", "True", ")", ":", "addon", "=", "\"luigitemp-%08d\"", "%", "random", ".", "randrange", "(", "1e9", ")", "temp_dir", "=", "'/tmp'", "# default tmp dir if none is specified in config", "# 1. Figure out to which temporary directory to place", "configured_hdfs_tmp_dir", "=", "hdfs", "(", ")", ".", "tmp_dir", "if", "configured_hdfs_tmp_dir", "is", "not", "None", ":", "# config is superior", "base_dir", "=", "configured_hdfs_tmp_dir", "elif", "path", "is", "not", "None", ":", "# need to copy correct schema and network location", "parsed", "=", "urlparse", "(", "path", ")", "base_dir", "=", "urlunparse", "(", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "temp_dir", ",", "''", ",", "''", ",", "''", ")", ")", "else", ":", "# just system temporary directory", "base_dir", "=", "temp_dir", "# 2. Figure out what to place", "if", "path", "is", "not", "None", ":", "if", "path", ".", "startswith", "(", "temp_dir", "+", "'/'", ")", ":", "# Not 100%, but some protection from directories like /tmp/tmp/file", "subdir", "=", "path", "[", "len", "(", "temp_dir", ")", ":", "]", "else", ":", "# Protection from /tmp/hdfs:/dir/file", "parsed", "=", "urlparse", "(", "path", ")", "subdir", "=", "parsed", ".", "path", "subdir", "=", "subdir", ".", "lstrip", "(", "'/'", ")", "+", "'-'", "else", ":", "# just return any random temporary location", "subdir", "=", "''", "if", "include_unix_username", ":", "subdir", "=", "os", ".", "path", ".", "join", "(", "getpass", ".", "getuser", "(", ")", ",", "subdir", ")", "return", "os", ".", "path", ".", "join", "(", "base_dir", ",", "subdir", "+", "addon", ")" ]
@param path: target path for which it is needed to generate temporary location @type path: str @type include_unix_username: bool @rtype: str Note that include_unix_username might work on windows too.
[ "@param", "path", ":", "target", "path", "for", "which", "it", "is", "needed", "to", "generate", "temporary", "location", "@type", "path", ":", "str", "@type", "include_unix_username", ":", "bool", "@rtype", ":", "str" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/config.py#L102-L144
train