Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def setting(self, setting_name, default=None): # type: (str) -> Any
keys = setting_name.split(".")
config = self._content
for key in keys:
if key not in config:
return default
config = config[key]
... | [
"\n Retrieve a setting value.\n "
] |
Please provide a description of the function:def get_requires_for_build_wheel(config_settings=None):
poetry = Poetry.create(".")
main, _ = SdistBuilder.convert_dependencies(poetry.package, poetry.package.requires)
return main | [
"\n Returns a list of requirements for building, as strings\n "
] |
Please provide a description of the function:def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
poetry = Poetry.create(".")
return unicode(
WheelBuilder.make_in(
poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path(wheel_directory)
)
) | [
"Builds a wheel, places it in wheel_directory"
] |
Please provide a description of the function:def build_sdist(sdist_directory, config_settings=None):
poetry = Poetry.create(".")
path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build(
Path(sdist_directory)
)
return unicode(path.name) | [
"Builds an sdist, places it in sdist_directory"
] |
Please provide a description of the function:def external_incompatibilities(self): # type: () -> Generator[Incompatibility]
if isinstance(self._cause, ConflictCause):
cause = self._cause # type: ConflictCause
for incompatibility in cause.conflict.external_incompatibilities:
... | [
"\n Returns all external incompatibilities in this incompatibility's\n derivation graph.\n "
] |
Please provide a description of the function:def decide(self, package): # type: (Package) -> None
# When we make a new decision after backtracking, count an additional
# attempted solution. If we backtrack multiple times in a row, though, we
# only want to count one, since we haven't a... | [
"\n Adds an assignment of package as a decision\n and increments the decision level.\n "
] |
Please provide a description of the function:def derive(
self, dependency, is_positive, cause
): # type: (Dependency, bool, Incompatibility) -> None
self._assign(
Assignment.derivation(
dependency,
is_positive,
cause,
... | [
"\n Adds an assignment of package as a derivation.\n "
] |
Please provide a description of the function:def _assign(self, assignment): # type: (Assignment) -> None
self._assignments.append(assignment)
self._register(assignment) | [
"\n Adds an Assignment to _assignments and _positive or _negative.\n "
] |
Please provide a description of the function:def backtrack(self, decision_level): # type: (int) -> None
self._backtracking = True
packages = set()
while self._assignments[-1].decision_level > decision_level:
removed = self._assignments.pop(-1)
packages.add(remo... | [
"\n Resets the current decision level to decision_level, and removes all\n assignments made after that level.\n "
] |
Please provide a description of the function:def _register(self, assignment): # type: (Assignment) -> None
name = assignment.dependency.name
old_positive = self._positive.get(name)
if old_positive is not None:
self._positive[name] = old_positive.intersect(assignment)
... | [
"\n Registers an Assignment in _positive or _negative.\n "
] |
Please provide a description of the function:def satisfier(self, term): # type: (Term) -> Assignment
assigned_term = None # type: Term
for assignment in self._assignments:
if assignment.dependency.name != term.dependency.name:
continue
if (
... | [
"\n Returns the first Assignment in this solution such that the sublist of\n assignments up to and including that entry collectively satisfies term.\n "
] |
Please provide a description of the function:def check(cls, config, strict=False): # type: (dict, bool) -> Dict[str, List[str]]
result = {"errors": [], "warnings": []}
# Schema validation errors
validation_errors = validate_object(config, "poetry-schema")
result["errors"] += v... | [
"\n Checks the validity of a configuration\n "
] |
Please provide a description of the function:def find_packages(self, include):
pkgdir = None
if include.source is not None:
pkgdir = str(include.base)
base = str(include.elements[0].parent)
pkg_name = include.package
pkg_data = defaultdict(list)
# U... | [
"\n Discover subpackages and data.\n\n It also retrieves necessary files.\n "
] |
Please provide a description of the function:def clean_tarinfo(cls, tar_info):
ti = copy(tar_info)
ti.uid = 0
ti.gid = 0
ti.uname = ""
ti.gname = ""
ti.mode = normalize_file_permissions(ti.mode)
return ti | [
"\n Clean metadata from a TarInfo object to make it more reproducible.\n\n - Set uid & gid to 0\n - Set uname and gname to \"\"\n - Normalise permissions to 644 or 755\n - Set mtime if not None\n "
] |
Please provide a description of the function:def get(cls): # type: () -> Shell
if cls._shell is not None:
return cls._shell
try:
name, path = detect_shell(os.getpid())
except (RuntimeError, ShellDetectionFailure):
raise RuntimeError("Unable to detec... | [
"\n Retrieve the current shell.\n "
] |
Please provide a description of the function:def search_for(self, dependency): # type: (Dependency) -> List[Package]
if dependency.is_root:
return PackageCollection(dependency, [self._package])
for constraint in self._search_for.keys():
if (
constraint.... | [
"\n Search for the specifications that match the given dependency.\n\n The specifications in the returned list will be considered in reverse\n order, so the latest version ought to be last.\n "
] |
Please provide a description of the function:def search_for_vcs(self, dependency): # type: (VCSDependency) -> List[Package]
if dependency.vcs != "git":
raise ValueError("Unsupported VCS dependency {}".format(dependency.vcs))
tmp_dir = Path(mkdtemp(prefix="pypoetry-git-{}".format(d... | [
"\n Search for the specifications that match the given VCS dependency.\n\n Basically, we clone the repository in a temporary directory\n and get the information we need by checking out the specified reference.\n "
] |
Please provide a description of the function:def incompatibilities_for(
self, package
): # type: (DependencyPackage) -> List[Incompatibility]
if package.is_root():
dependencies = package.all_requires
else:
dependencies = package.requires
if not ... | [
"\n Returns incompatibilities that encapsulate a given package's dependencies,\n or that it can't be safely selected.\n\n If multiple subsequent versions of this package have the same\n dependencies, this will return incompatibilities that reflect that. It\n won't return incompati... |
Please provide a description of the function:def solve(self): # type: () -> SolverResult
start = time.time()
root_dependency = Dependency(self._root.name, self._root.version)
root_dependency.is_root = True
self._add_incompatibility(
Incompatibility([Term(root_depen... | [
"\n Finds a set of dependencies that match the root package's constraints,\n or raises an error if no such set is available.\n "
] |
Please provide a description of the function:def _propagate(self, package): # type: (str) -> None
changed = set()
changed.add(package)
while changed:
package = changed.pop()
# Iterate in reverse because conflict resolution tends to produce more
# g... | [
"\n Performs unit propagation on incompatibilities transitively\n related to package to derive new assignments for _solution.\n "
] |
Please provide a description of the function:def _propagate_incompatibility(
self, incompatibility
): # type: (Incompatibility) -> Union[str, _conflict, None]
# The first entry in incompatibility.terms that's not yet satisfied by
# _solution, if one exists. If we find more than one... | [
"\n If incompatibility is almost satisfied by _solution, adds the\n negation of the unsatisfied term to _solution.\n\n If incompatibility is satisfied by _solution, returns _conflict. If\n incompatibility is almost satisfied by _solution, returns the\n unsatisfied term's package n... |
Please provide a description of the function:def _resolve_conflict(
self, incompatibility
): # type: (Incompatibility) -> Incompatibility
self._log("conflict: {}".format(incompatibility))
new_incompatibility = False
while not incompatibility.is_failure():
# The... | [
"\n Given an incompatibility that's satisfied by _solution,\n The `conflict resolution`_ constructs a new incompatibility that encapsulates the root\n cause of the conflict and backtracks _solution until the new\n incompatibility will allow _propagate() to deduce new assignments.\n\n ... |
Please provide a description of the function:def _choose_package_version(self): # type: () -> Union[str, None]
unsatisfied = self._solution.unsatisfied
if not unsatisfied:
return
# Prefer packages with as few remaining versions as possible,
# so that if a conflict ... | [
"\n Tries to select a version of a required package.\n\n Returns the name of the package whose incompatibilities should be\n propagated by _propagate(), or None indicating that version solving is\n complete and a solution has been found.\n "
] |
Please provide a description of the function:def _result(self): # type: () -> SolverResult
decisions = self._solution.decisions
return SolverResult(
self._root,
[p for p in decisions if not p.is_root()],
self._solution.attempted_solutions,
) | [
"\n Creates a #SolverResult from the decisions in _solution\n "
] |
Please provide a description of the function:def run(self, bin, *args, **kwargs):
bin = self._bin(bin)
cmd = [bin] + list(args)
shell = kwargs.get("shell", False)
call = kwargs.pop("call", False)
input_ = kwargs.pop("input_", None)
if shell:
cmd = l... | [
"\n Run a command inside the Python environment.\n "
] |
Please provide a description of the function:def _bin(self, bin): # type: (str) -> str
bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "")
if not bin_path.exists():
return bin
return str(bin_path) | [
"\n Return path to the given executable.\n "
] |
Please provide a description of the function:def format_python_constraint(constraint):
if isinstance(constraint, Version):
if constraint.precision >= 3:
return "=={}".format(str(constraint))
# Transform 3.6 or 3
if constraint.precision == 2:
# 3.6
co... | [
"\n This helper will help in transforming\n disjunctive constraint into proper constraint.\n "
] |
Please provide a description of the function:def get_abbr_impl(env):
impl = env.python_implementation
if impl == "PyPy":
return "pp"
elif impl == "Jython":
return "jy"
elif impl == "IronPython":
return "ip"
elif impl == "CPython":
return "cp"
raise LookupEr... | [
"Return abbreviated implementation name."
] |
Please provide a description of the function:def get_impl_ver(env):
impl_ver = env.config_var("py_version_nodot")
if not impl_ver or get_abbr_impl(env) == "pp":
impl_ver = "".join(map(str, get_impl_version_info(env)))
return impl_ver | [
"Return implementation version."
] |
Please provide a description of the function:def get_flag(env, var, fallback, expected=True, warn=True):
val = env.config_var(var)
if val is None:
if warn:
warnings.warn(
"Config variable '{0}' is unset, Python ABI tag may "
"be incorrect".format(var),
... | [
"Use a fallback method for determining SOABI flags if the needed config\n var is unset or unavailable."
] |
Please provide a description of the function:def accepts(self, package): # type: (poetry.packages.Package) -> bool
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or self.allows_prereleases())
... | [
"\n Determines if the given package matches this dependency.\n "
] |
Please provide a description of the function:def deactivate(self):
if not self._optional:
self._optional = True
self._activated = False | [
"\n Set the dependency as optional.\n "
] |
Please provide a description of the function:def install(self, version, upgrade=False):
print("Installing version: " + colorize("info", version))
self.make_lib(version)
self.make_bin()
self.make_env()
self.update_path()
return 0 | [
"\n Installs Poetry in $POETRY_HOME.\n "
] |
Please provide a description of the function:def make_lib(self, version):
if os.path.exists(POETRY_LIB_BACKUP):
shutil.rmtree(POETRY_LIB_BACKUP)
# Backup the current installation
if os.path.exists(POETRY_LIB):
shutil.copytree(POETRY_LIB, POETRY_LIB_BACKUP)
... | [
"\n Packs everything into a single lib/ directory.\n "
] |
Please provide a description of the function:def update_path(self):
if WINDOWS:
return self.add_to_windows_path()
# Updating any profile we can on UNIX systems
export_string = self.get_export_string()
addition = "\n{}\n".format(export_string)
updated = []
... | [
"\n Tries to update the $PATH automatically.\n "
] |
Please provide a description of the function:def satisfies(self, other): # type: (Term) -> bool
return (
self.dependency.name == other.dependency.name
and self.relation(other) == SetRelation.SUBSET
) | [
"\n Returns whether this term satisfies another.\n "
] |
Please provide a description of the function:def relation(self, other): # type: (Term) -> int
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
other_constraint = other.cons... | [
"\n Returns the relationship between the package versions\n allowed by this term and another.\n "
] |
Please provide a description of the function:def intersect(self, other): # type: (Term) -> Union[Term, None]
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
if self._compa... | [
"\n Returns a Term that represents the packages\n allowed by both this term and another\n "
] |
Please provide a description of the function:def find_files_to_add(self, exclude_build=True): # type: (bool) -> list
to_add = []
for include in self._module.includes:
for file in include.elements:
if "__pycache__" in str(file):
continue
... | [
"\n Finds all files to add to the tarball\n "
] |
Please provide a description of the function:def parse(
version, strict=False # type: str # type: bool
): # type:(...) -> Union[Version, LegacyVersion]
try:
return Version(version)
except InvalidVersion:
if strict:
raise
return LegacyVersion(version) | [
"\n Parse the given version string and return either a :class:`Version` object\n or a LegacyVersion object depending on if the given version is\n a valid PEP 440 version or a legacy version.\n\n If strict=True only PEP 440 versions will be accepted.\n "
] |
Please provide a description of the function:def is_fresh(self): # type: () -> bool
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["content-hash"]
return False | [
"\n Checks whether the lock file is still up to date with the current hash.\n "
] |
Please provide a description of the function:def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data
packages = poetry.repos... | [
"\n Searches and returns a repository of locked packages.\n "
] |
Please provide a description of the function:def _get_content_hash(self): # type: () -> str
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
content_hash = sha256(
json.dumps(re... | [
"\n Returns the sha256 hash of the sorted content of the pyproject file.\n "
] |
Please provide a description of the function:def load(cls, env): # type: (Env) -> InstalledRepository
repo = cls()
freeze_output = env.run("pip", "freeze")
for line in freeze_output.split("\n"):
if "==" in line:
name, version = re.split("={2,3}", line)
... | [
"\n Load installed packages.\n\n For now, it uses the pip \"freeze\" command.\n "
] |
Please provide a description of the function: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:
... | [
"\n Given a package name and optional version,\n returns the latest Package that matches\n "
] |
Please provide a description of the function: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\n the link, it will be rewritten to %20 (while not over-quoting\n % or other characters)."
] |
Please provide a description of the function:def package(
self, name, version, extras=None
): # type: (...) -> poetry.packages.Package
try:
index = self._packages.index(
poetry.packages.Package(name, version, version)
)
return self._pack... | [
"\n Retrieve the release information.\n\n This is a heavy task which takes time.\n We have to download a package to get the dependencies.\n We also need to download every file matching this release\n to get the various hashes.\n\n Note that, this will be cached so the subse... |
Please provide a description of the function: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) | [
"\n Initialize command.\n "
] |
Please provide a description of the function:def register_logger(self, logger):
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if o... | [
"\n Register a new logger.\n "
] |
Please provide a description of the function: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 ... | [
"\n Register a package to a repository.\n "
] |
Please provide a description of the function: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]
... | [
"\n Find packages on the remote server.\n "
] |
Please provide a description of the function: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)
) | [
"\n Return the package information given its name.\n\n The information is returned from the cache if it exists\n or retrieved from the remote server.\n "
] |
Please provide a description of the function: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._g... | [
"\n Return the release information given a package name and a version.\n\n The information is returned from the cache if it exists\n or retrieved from the remote server.\n "
] |
Please provide a description of the function:def make(cls, poetry, env, io):
cls.make_in(poetry, env, io) | [
"Build a wheel in the dist/ directory, and optionally upload it."
] |
Please provide a description of the function: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(... | [
"\n Write entry_points.txt.\n "
] |
Please provide a description of the function: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.OpenKe... | [
"\n This is a fallback technique at best. I'm not sure if using the\n registry for this guarantees us the correct answer for all CSIDL_*\n names.\n "
] |
Please provide a description of the function:def lock(self): # type: () -> Installer
self.update()
self.execute_operations(False)
self._lock = True
return self | [
"\n Prepare the installer for locking only.\n "
] |
Please provide a description of the function:def _execute(self, operation): # type: (Operation) -> None
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation) | [
"\n Execute a given operation.\n "
] |
Please provide a description of the function: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 ... | [
"\n Returns all packages required by extras.\n\n Maybe we just let the solver handle it?\n "
] |
Please provide a description of the function: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"
] |
Please provide a description of the function: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``."
] |
Please provide a description of the function: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, ... | [
"Searches for jobs matching the given ``status``."
] |
Please provide a description of the function: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):... | [
"\n Move file atomically. If source and destination are located\n on different filesystems, atomicity is approximated\n but cannot be guaranteed.\n "
] |
Please provide a description of the function:def rename_dont_move(self, path, dest):
self.move(path, dest, raise_if_exists=True) | [
"\n Rename ``path`` to ``dest``, but don't move it into the ``dest``\n folder (if it is a folder). This method is just a wrapper around the\n ``move`` method of LocalTarget.\n "
] |
Please provide a description of the function:def makedirs(self):
normpath = os.path.normpath(self.path)
parentfolder = os.path.dirname(normpath)
if parentfolder:
try:
os.makedirs(parentfolder)
except OSError:
pass | [
"\n Create all parent folders if they do not exist.\n "
] |
Please provide a description of the function: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 | [
"\n Tracking is done by requesting each job and then searching for whether the job\n has one of the following states:\n - \"RUN\",\n - \"PEND\",\n - \"SSUSP\",\n - \"EXIT\"\n based on the LSF documentation\n "
] |
Please provide a description of the function: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 = ''
... | [
"\n Read in the error file from bsub\n "
] |
Please provide a description of the function: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:
... | [
"\n Read in the output file\n "
] |
Please provide a description of the function: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... | [
"\n Build a bsub argument that will run lsf_runner.py on the directory we've specified.\n "
] |
Please provide a description of the function: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() | [
"\n Generates :py:attr:`~.UserItemMatrix.data_size` elements.\n Writes this data in \\\\ separated value format into the target :py:func:`~/.UserItemMatrix.output`.\n\n The data has the following elements:\n\n * `user` is the default Elasticsearch id field,\n * `track`: the text,\... |
Please provide a description of the function:def output(self):
return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip) | [
"\n Returns the target output for this task.\n In this case, a successful execution of this task will create a file in HDFS.\n\n :return: the target output for this task.\n :rtype: object (:py:class:`~luigi.target.Target`)\n "
] |
Please provide a description of the function: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)
... | [
"convert UTC time string to time.struct_time: change datetime.datetime to time, return time.struct_time type"
] |
Please provide a description of the function: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=add... | [
"\n Runs one instance of the API server.\n "
] |
Please provide a description of the function: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_... | [
"\n Gets queried columns names.\n "
] |
Please provide a description of the function: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 ... | [
"\n Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data\n "
] |
Please provide a description of the function: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
... | [
"\n Helper method for parse_results().\n\n Traverses through ordered dict and recursively calls itself when encountering a dictionary\n "
] |
Please provide a description of the function: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:
... | [
"\n Merges the resulting files of a multi-result batch bulk query.\n "
] |
Please provide a description of the function: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(),
... | [
"\n Starts a Salesforce session and determines which SF instance to use for future requests.\n "
] |
Please provide a description of the function:def query(self, query, **kwargs):
params = {'q': query}
response = requests.get(self._get_norm_query_url(),
headers=self._get_rest_headers(),
params=params,
... | [
"\n Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload.\n\n :param query: the SOQL query to send to Salesforce, e.g. \"SELECT id from Lead WHERE email = 'a@b.com'\"\n "
] |
Please provide a description of the function: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}'
... | [
"\n Retrieves more results from a query that returned more results\n than the batch maximum. Returns a dict decoded from the Salesforce\n response JSON payload.\n\n :param next_records_identifier: either the Id of the next Salesforce\n object in the re... |
Please provide a description of the function: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 w... | [
"\n Returns the full set of results for the `query`. This is a\n convenience wrapper around `query(...)` and `query_more(...)`.\n The returned dict is the decoded JSON payload from the final call to\n Salesforce, but with the `totalSize` field representing the full\n number of res... |
Please provide a description of the function: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 ... | [
"\n Allows you to make a direct REST call if you know the path\n Arguments:\n :param path: The path of the request. Example: sobjects/User/ABC123/password'\n :param params: dict of parameters to pass to the path\n "
] |
Please provide a description of the function: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(),
... | [
"\n Creates a new SF job that for doing any operation (insert, upsert, update, delete, query)\n\n :param operation: delete, insert, query, upsert, update, hardDelete. Must be lowercase.\n :param obj: Parent SF object\n :param external_id_field_name: Optional.\n "
] |
Please provide a description of the function:def get_job_details(self, job_id):
response = requests.get(self._get_job_details_url(job_id))
response.raise_for_status()
return response | [
"\n Gets all details for existing job\n\n :param job_id: job_id as returned by 'create_operation_job(...)'\n :return: job info as xml\n "
] |
Please provide a description of the function: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(... | [
"\n Abort an existing job. When a job is aborted, no more records are processed.\n Changes to data may already have been committed and aren't rolled back.\n\n :param job_id: job_id as returned by 'create_operation_job(...)'\n :return: abort response as xml\n "
] |
Please provide a description of the function: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),
... | [
"\n Closes job\n\n :param job_id: job_id as returned by 'create_operation_job(...)'\n :return: close response as xml\n "
] |
Please provide a description of the function: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(fil... | [
"\n Creates a batch with either a string of data or a file containing data.\n\n If a file is provided, this will pull the contents of the file_target into memory when running.\n That shouldn't be a problem for any files that meet the Salesforce single batch upload\n size limit (10MB) and... |
Please provide a description of the function: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 s... | [
"\n Blocks until @batch_id is completed or failed.\n :param job_id:\n :param batch_id:\n :param sleep_time_seconds:\n :param max_wait_time_seconds:\n "
] |
Please provide a description of the function: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] | [
"\n DEPRECATED: Use `get_batch_result_ids`\n "
] |
Please provide a description of the function: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... | [
"\n Get result IDs of a batch that has completed processing.\n\n :param job_id: job_id as returned by 'create_operation_job(...)'\n :param batch_id: batch_id as returned by 'create_batch(...)'\n :return: list of batch result IDs to be used in 'get_batch_result(...)'\n "
] |
Please provide a description of the function: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... | [
"\n Gets result back from Salesforce as whatever type was originally sent in create_batch (xml, or csv).\n :param job_id:\n :param batch_id:\n :param result_id:\n\n "
] |
Please provide a description of the function: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, pri... | [
"Parse \"state\" column from `qstat` output for given job_id\n\n Returns state for the *first* job matching job_id. Returns 'u' if\n `qstat` output is empty or job_id is not found.\n\n "
] |
Please provide a description of the function:def _build_qsub_command(cmd, job_name, outfile, errfile, pe, n_cpu):
qsub_template =
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`",
"echo {cmd} | qsub -o \":{outfile}\" -e \":{errfile}\" -V -r y -pe {pe} {n_cpu} -N {job_name}"
] |
Please provide a description of the function: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... | [
"Dump instance to file."
] |
Please provide a description of the function: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)}))... | [
"\n Writes data in JSON format into the task's output target.\n\n The data objects have the following attributes:\n\n * `_id` is the default Elasticsearch id field,\n * `text`: the text,\n * `date`: the day when the data was created.\n\n "
] |
Please provide a description of the function: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.cl... | [
"\n Creates the client as specified in the `luigi.cfg` configuration.\n "
] |
Please provide a description of the function: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 = Tru... | [
"\n For internal use only (until further notice)\n "
] |
Please provide a description of the function: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(Sourc... | [
"\n Sends notification through AWS SES.\n\n Does not handle access keys. Use either\n 1/ configuration file\n 2/ EC2 instance profile\n\n See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.\n "
] |
Please provide a description of the function: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... | [
"\n Sends notification through AWS SNS. Takes Topic ARN from recipients.\n\n Does not handle access keys. Use either\n 1/ configuration file\n 2/ EC2 instance profile\n\n See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.\n "
] |
Please provide a description of the function: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 n... | [
"\n Decides whether to send notification. Notification is cancelled if there are\n no recipients or if stdout is onto tty or if in debug mode.\n\n Dispatches on config value email.method. Default is 'smtp'.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.