INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Run the work () method from the class instance in the file job - instance. pickle. | def main(args=sys.argv):
"""Run the work() method from the class instance in the file "job-instance.pickle".
"""
try:
tarball = "--no-tarball" not in args
# Set up logging.
logging.basicConfig(level=logging.WARN)
work_dir = args[1]
assert os.path.exists(work_dir), "Fi... |
Arbitrarily picks an object in input and reads the Avro schema from it. | def _get_input_schema(self):
"""Arbitrarily picks an object in input and reads the Avro schema from it."""
assert avro, 'avro module required'
input_target = flatten(self.input())[0]
input_fs = input_target.fs if hasattr(input_target, 'fs') else GCSClient()
input_uri = self.sour... |
Return a string representation of the tasks their statuses/ parameters in a dependency tree format | def print_tree(task, indent='', last=True):
'''
Return a string representation of the tasks, their statuses/parameters in a dependency tree format
'''
# dont bother printing out warnings about tasks with no output
with warnings.catch_warnings():
warnings.filterwarnings(action='ignore', messa... |
Join relative URLs to base URLs like urllib. parse. urljoin but support arbitrary URIs ( esp. http + unix:// ). | def _urljoin(base, url):
"""
Join relative URLs to base URLs like urllib.parse.urljoin but support
arbitrary URIs (esp. 'http+unix://').
"""
parsed = urlparse(base)
scheme = parsed.scheme
return urlparse(
urljoin(parsed._replace(scheme='http').geturl(), url)
)._replace(scheme=sch... |
Returns whether the given dataset exists. If regional location is specified for the dataset that is also checked to be compatible with the remote dataset otherwise an exception is thrown. | def dataset_exists(self, dataset):
"""Returns whether the given dataset exists.
If regional location is specified for the dataset, that is also checked
to be compatible with the remote dataset, otherwise an exception is thrown.
:param dataset:
:type dataset: BQDataset
... |
Returns whether the given table exists. | def table_exists(self, table):
"""Returns whether the given table exists.
:param table:
:type table: BQTable
"""
if not self.dataset_exists(table.dataset):
return False
try:
self.client.tables().get(projectId=table.project_id,
... |
Creates a new dataset with the default permissions. | def make_dataset(self, dataset, raise_if_exists=False, body=None):
"""Creates a new dataset with the default permissions.
:param dataset:
:type dataset: BQDataset
:param raise_if_exists: whether to raise an exception if the dataset already exists.
:raises luigi.targe... |
Deletes a dataset ( and optionally any tables in it ) if it exists. | def delete_dataset(self, dataset, delete_nonempty=True):
"""Deletes a dataset (and optionally any tables in it), if it exists.
:param dataset:
:type dataset: BQDataset
:param delete_nonempty: if true, will delete any tables before deleting the dataset
"""
if no... |
Deletes a table if it exists. | def delete_table(self, table):
"""Deletes a table, if it exists.
:param table:
:type table: BQTable
"""
if not self.table_exists(table):
return
self.client.tables().delete(projectId=table.project_id,
datasetId=table... |
Returns the list of datasets in a given project. | def list_datasets(self, project_id):
"""Returns the list of datasets in a given project.
:param project_id:
:type project_id: str
"""
request = self.client.datasets().list(projectId=project_id,
maxResults=1000)
respons... |
Returns the list of tables in a given dataset. | def list_tables(self, dataset):
"""Returns the list of tables in a given dataset.
:param dataset:
:type dataset: BQDataset
"""
request = self.client.tables().list(projectId=dataset.project_id,
datasetId=dataset.dataset_id,
... |
Returns the SQL query for a view or None if it doesn t exist or is not a view. | def get_view(self, table):
"""Returns the SQL query for a view, or None if it doesn't exist or is not a view.
:param table: The table containing the view.
:type table: BQTable
"""
request = self.client.tables().get(projectId=table.project_id,
... |
Updates the SQL query for a view. | def update_view(self, table, view):
"""Updates the SQL query for a view.
If the output table exists, it is replaced with the supplied view query. Otherwise a new
table is created with this view.
:param table: The table to contain the view.
:type table: BQTable
:param vi... |
Runs a BigQuery job. See the documentation for the format of body. | def run_job(self, project_id, body, dataset=None):
"""Runs a BigQuery "job". See the documentation for the format of body.
.. note::
You probably don't need to use this directly. Use the tasks defined below.
:param dataset:
:type dataset: BQDataset
"""
... |
Copies ( or appends ) a table to another table. | def copy(self,
source_table,
dest_table,
create_disposition=CreateDisposition.CREATE_IF_NEEDED,
write_disposition=WriteDisposition.WRITE_TRUNCATE):
"""Copies (or appends) a table to another table.
:param source_table:
:type source_tabl... |
A constructor that takes a: py: class: BQTable. | def from_bqtable(cls, table, client=None):
"""A constructor that takes a :py:class:`BQTable`.
:param table:
:type table: BQTable
"""
return cls(table.project_id, table.dataset_id, table.table_id, client=client) |
The fully - qualified URIs that point to your data in Google Cloud Storage. | def source_uris(self):
"""The fully-qualified URIs that point to your data in Google Cloud Storage.
Each URI can contain one '*' wildcard character and it must come after the 'bucket' name."""
return [x.path for x in luigi.task.flatten(self.input())] |
The fully - qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one * wildcard character and it must come after the bucket name. | def destination_uris(self):
"""
The fully-qualified URIs that point to your data in Google Cloud
Storage. Each URI can contain one '*' wildcard character and it must
come after the 'bucket' name.
Wildcarded destinationUris in GCSQueryTarget might not be resolved
correctl... |
Remote Popen. | def Popen(self, cmd, **kwargs):
"""
Remote Popen.
"""
prefixed_cmd = self._prepare_cmd(cmd)
return subprocess.Popen(prefixed_cmd, **kwargs) |
Execute a shell command remotely and return the output. | def check_output(self, cmd):
"""
Execute a shell command remotely and return the output.
Simplified version of Popen when you only want the output as a string and detect any errors.
"""
p = self.Popen(cmd, stdout=subprocess.PIPE)
output, _ = p.communicate()
if p.... |
Open a tunnel between localhost: local_port and remote_host: remote_port via the host specified by this context. | def tunnel(self, local_port, remote_port=None, remote_host="localhost"):
"""
Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context.
Remember to close() the returned "tunnel" object in order to clean up
after yourself when you are d... |
Return True if directory at path exist False otherwise. | def isdir(self, path):
"""
Return `True` if directory at `path` exist, False otherwise.
"""
try:
self.remote_context.check_output(["test", "-d", path])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
return False
... |
Remove file or directory at location path. | def remove(self, path, recursive=True):
"""
Remove file or directory at location `path`.
"""
if recursive:
cmd = ["rm", "-r", path]
else:
cmd = ["rm", path]
self.remote_context.check_output(cmd) |
Returns command of process. | def getpcmd(pid):
"""
Returns command of process.
:param pid:
"""
if os.name == "nt":
# Use wmic command instead of ps on Windows.
cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, )
with os.popen(cmd, 'r') as p:
lines = [line for ... |
Makes sure the process is only run once at the same time with the same name. | def acquire_for(pid_dir, num_available=1, kill_signal=None):
"""
Makes sure the process is only run once at the same time with the same name.
Notice that we since we check the process name, different parameters to the same
command can spawn multiple processes at the same time, i.e. running
"/usr/bi... |
Add a failure event with the current timestamp. | def add_failure(self):
"""
Add a failure event with the current timestamp.
"""
failure_time = time.time()
if not self.first_failure_time:
self.first_failure_time = failure_time
self.failures.append(failure_time) |
Return the number of failures in the window. | def num_failures(self):
"""
Return the number of failures in the window.
"""
min_time = time.time() - self.window
while self.failures and self.failures[0] < min_time:
self.failures.popleft()
return len(self.failures) |
If it s not an assistant having only tasks that are without requirements. | def is_trivial_worker(self, state):
"""
If it's not an assistant having only tasks that are without
requirements.
We have to pass the state parameter for optimization reasons.
"""
if self.assistant:
return False
return all(not task.resources for task ... |
Return how many tasks are PENDING + RUNNING. O ( 1 ). | def num_pending_tasks(self):
"""
Return how many tasks are PENDING + RUNNING. O(1).
"""
return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING]) |
Update priority of the given task. | def _update_priority(self, task, prio, worker):
"""
Update priority of the given task.
Priority can only be increased.
If the task doesn't exist, a placeholder task is created to preserve priority when the task is later scheduled.
"""
task.priority = prio = max(prio, tas... |
* add task identified by task_id if it doesn t exist * if deps is not None update dependency list * update status of task * add additional workers/ stakeholders * update priority when needed | def add_task(self, task_id=None, status=PENDING, runnable=True,
deps=None, new_deps=None, expl=None, resources=None,
priority=0, family='', module=None, params=None, param_visibilities=None, accepts_messages=False,
assistant=False, tracking_url=None, worker=None, batch... |
Returns the dependency graph rooted at task_id | def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True):
""" Returns the dependency graph rooted at task_id
This does a breadth-first traversal to find the nodes closest to the
root before hitting the scheduler.max_graph_nodes limit.
:param root_task_id: th... |
Query for a subset of tasks by status. | def task_list(self, status='', upstream_status='', limit=True, search=None, max_shown_tasks=None,
**kwargs):
"""
Query for a subset of tasks by status.
"""
if not search:
count_limit = max_shown_tasks or self._config.max_shown_tasks
pre_count = s... |
Resources usage info and their consumers ( tasks ). | def resource_list(self):
"""
Resources usage info and their consumers (tasks).
"""
self.prune()
resources = [
dict(
name=resource,
num_total=r_dict['total'],
num_used=r_dict['used']
) for resource, r_dict in ... |
get total resources and available ones | def resources(self):
''' get total resources and available ones '''
used_resources = self._used_resources()
ret = collections.defaultdict(dict)
for resource, total in six.iteritems(self._resources):
ret[resource]['total'] = total
if resource in used_resources:
... |
Query for a subset of tasks by task_id. | def task_search(self, task_str, **kwargs):
"""
Query for a subset of tasks by task_id.
:param task_str:
:return:
"""
self.prune()
result = collections.defaultdict(dict)
for task in self._state.get_active_tasks():
if task.id.find(task_str) != -... |
Returns True if the path for this FileSystemTarget exists ; False otherwise. | def exists(self):
"""
Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise.
This method is implemented by using :py:attr:`fs`.
"""
path = self.path
if '*' in path or '?' in path or '[' in path or '{' in path:
logger.warning("Usin... |
A context manager that enables a reasonably short general and magic - less way to solve the: ref: AtomicWrites. | def temporary_path(self):
"""
A context manager that enables a reasonably short, general and
magic-less way to solve the :ref:`AtomicWrites`.
* On *entering*, it will create the parent directories so the
temporary_path is writeable right away.
This step uses :py:m... |
Generate an id for the indicator document. | def marker_index_document_id(self):
"""
Generate an id for the indicator document.
"""
params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id)
return hashlib.sha1(params.encode('utf-8')).hexdigest() |
Mark this update as complete. | def touch(self):
"""
Mark this update as complete.
The document id would be sufficent but,
for documentation,
we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well.
"""
self.create_marker_index()
self.es.index(index=sel... |
Test if this task has been run. | def exists(self):
"""
Test, if this task has been run.
"""
try:
self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id())
return True
except elasticsearch.NotFoundError:
logger.debug('Marker documen... |
Create the index that will keep track of the tasks if necessary. | def create_marker_index(self):
"""
Create the index that will keep track of the tasks if necessary.
"""
if not self.es.indices.exists(index=self.marker_index):
self.es.indices.create(index=self.marker_index) |
Shrink the history of updates for a index/ doc_type combination down to self. marker_index_hist_size. | def ensure_hist_size(self):
"""
Shrink the history of updates for
a `index/doc_type` combination down to `self.marker_index_hist_size`.
"""
if self.marker_index_hist_size == 0:
return
result = self.es.search(index=self.marker_index,
... |
Since self. docs may yield documents that do not explicitly contain _index or _type add those attributes here if necessary. | def _docs(self):
"""
Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`,
add those attributes here, if necessary.
"""
iterdocs = iter(self.docs())
first = next(iterdocs)
needs_parsing = False
if isinstance(first, six.s... |
Override to provide code for creating the target index. | def create_index(self):
"""
Override to provide code for creating the target index.
By default it will be created without any special settings or mappings.
"""
es = self._init_connection()
if not es.indices.exists(index=self.index):
es.indices.create(index=se... |
Delete the index if it exists. | def delete_index(self):
"""
Delete the index, if it exists.
"""
es = self._init_connection()
if es.indices.exists(index=self.index):
es.indices.delete(index=self.index) |
Returns a ElasticsearchTarget representing the inserted dataset. | def output(self):
"""
Returns a ElasticsearchTarget representing the inserted dataset.
Normally you don't override this.
"""
return ElasticsearchTarget(
host=self.host,
port=self.port,
http_auth=self.http_auth,
index=self.index,
... |
Run task namely: | def run(self):
"""
Run task, namely:
* purge existing index, if requested (`purge_existing_index`),
* create the index, if missing,
* apply mappings, if given,
* set refresh interval to -1 (disable) for performance reasons,
* bulk index in batches of size `chunk_... |
Gets the value of the section/ option using method. | def _get_with_default(self, method, section, option, default, expected_type=None, **kwargs):
"""
Gets the value of the section/option using method.
Returns default if value is not found.
Raises an exception if the default value is not None and doesn't match the expected_type.
"... |
Poll job status while active | def __track_job(self):
"""Poll job status while active"""
while not self.__verify_job_has_started():
time.sleep(self.__POLL_TIME)
self.__logger.debug("Waiting for Kubernetes job " + self.uu_name + " to start")
self.__print_kubectl_hints()
status = self.__get_job_... |
Asserts that the job has successfully started | def __verify_job_has_started(self):
"""Asserts that the job has successfully started"""
# Verify that the job started
self.__get_job()
# Verify that the pod started
pods = self.__get_pods()
assert len(pods) > 0, "No pod scheduled by " + self.uu_name
for pod in p... |
Return the Kubernetes job status | def __get_job_status(self):
"""Return the Kubernetes job status"""
# Figure out status and return it
job = self.__get_job()
if "succeeded" in job.obj["status"] and job.obj["status"]["succeeded"] > 0:
job.scale(replicas=0)
if self.print_pod_logs_on_exit:
... |
Return an engine instance creating it if it doesn t exist. | def engine(self):
"""
Return an engine instance, creating it if it doesn't exist.
Recreate the engine connection if it wasn't originally created
by the current process.
"""
pid = os.getpid()
conn = SQLAlchemyTarget._engine_dict.get(self.connection_string)
... |
Mark this update as complete. | def touch(self):
"""
Mark this update as complete.
"""
if self.marker_table_bound is None:
self.create_marker_table()
table = self.marker_table_bound
id_exists = self.exists()
with self.engine.begin() as conn:
if not id_exists:
... |
Create marker table if it doesn t exist. | def create_marker_table(self):
"""
Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset.
"""
if self.marker_table is None:
self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-tabl... |
Override to provide code for creating the target table. | def create_table(self, engine):
"""
Override to provide code for creating the target table.
By default it will be created using types specified in columns.
If the table exists, then it binds to the existing table.
If overridden, use the provided connection object for setting up... |
This method does the actual insertion of the rows of data given by ins_rows into the database. A task that needs row updates instead of insertions should overload this method.: param conn: The sqlalchemy connection object: param ins_rows: The dictionary of rows with the keys in the format _<column_name >. For example i... | def copy(self, conn, ins_rows, table_bound):
"""
This method does the actual insertion of the rows of data given by ins_rows into the
database. A task that needs row updates instead of insertions should overload this method.
:param conn: The sqlalchemy connection object
:param in... |
Run the work () method from the class instance in the file job - instance. pickle. | def main(args=sys.argv):
"""Run the work() method from the class instance in the file "job-instance.pickle".
"""
try:
# Set up logging.
logging.basicConfig(level=logging.WARN)
work_dir = args[1]
assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a direc... |
Does not change self. path. | def rename(self, path, raise_if_exists=False):
"""
Does not change self.path.
Unlike ``move_dir()``, ``rename()`` might cause nested directories.
See spotify/luigi#522
"""
if isinstance(path, HdfsTarget):
path = path.path
if raise_if_exists and self.f... |
Alias for rename () | def move(self, path, raise_if_exists=False):
"""
Alias for ``rename()``
"""
self.rename(path, raise_if_exists=raise_if_exists) |
Currently only works with hadoopcli | def is_writable(self):
"""
Currently only works with hadoopcli
"""
if "/" in self.path:
# example path: /log/ap/2013-01-17/00
parts = self.path.split("/")
# start with the full path and then up the tree until we can check
length = len(parts... |
Takes a worker and sorts out tasks based on their status. Still_pending_not_ext is only used to get upstream_failure upstream_missing_dependency and run_by_other_worker | def _partition_tasks(worker):
"""
Takes a worker and sorts out tasks based on their status.
Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker
"""
task_history = worker._add_task_history
pending_tasks = {task for(task, status, ext) in ... |
Add the upstream_ * and not_run statuses my mutating set_tasks. | def _populate_unknown_statuses(set_tasks):
"""
Add the "upstream_*" and "not_run" statuses my mutating set_tasks.
"""
visited = set()
for task in set_tasks["still_pending_not_ext"]:
_depth_first_search(set_tasks, task, visited) |
This dfs checks why tasks are still pending. | def _depth_first_search(set_tasks, current_task, visited):
"""
This dfs checks why tasks are still pending.
"""
visited.add(current_task)
if current_task in set_tasks["still_pending_not_ext"]:
upstream_failure = False
upstream_missing_dependency = False
upstream_run_by_other_... |
This returns a string for each status | def _get_str(task_dict, extra_indent):
"""
This returns a string for each status
"""
summary_length = execution_summary().summary_length
lines = []
task_names = sorted(task_dict.keys())
for task_family in task_names:
tasks = task_dict[task_family]
tasks = sorted(tasks, key=l... |
Checks if there is a continuous range | def _ranging_attributes(attributes, param_class):
"""
Checks if there is a continuous range
"""
next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes}
in_first = attributes.difference(next_attributes)
in_second = next_attributes.difference(attributes)
if l... |
Get the human readable comments and quantities for the task types. | def _get_comments(group_tasks):
"""
Get the human readable comments and quantities for the task types.
"""
comments = {}
for status, human in _COMMENTS:
num_tasks = _get_number_of_tasks_for(status, group_tasks)
if num_tasks:
space = " " if status in _PENDING_SUB_STATUS... |
This returns a set of the tasks that are being run by other worker | def _get_run_by_other_worker(worker):
"""
This returns a set of the tasks that are being run by other worker
"""
task_sets = _get_external_workers(worker).values()
return functools.reduce(lambda a, b: a | b, task_sets, set()) |
This returns a dict with a set of tasks for all of the other workers | def _get_external_workers(worker):
"""
This returns a dict with a set of tasks for all of the other workers
"""
worker_that_blocked_task = collections.defaultdict(set)
get_work_response_history = worker._get_work_response_history
for get_work_response in get_work_response_history:
if get... |
Takes a dictionary with sets of tasks grouped by their status and returns a dictionary with dictionaries with an array of tasks grouped by their status and task name | def _group_tasks_by_name_and_status(task_dict):
"""
Takes a dictionary with sets of tasks grouped by their status and
returns a dictionary with dictionaries with an array of tasks grouped by
their status and task name
"""
group_status = {}
for task in task_dict:
if task.task_family n... |
Given a grouped set of tasks returns a LuigiStatusCode | def _tasks_status(set_tasks):
"""
Given a grouped set of tasks, returns a LuigiStatusCode
"""
if set_tasks["ever_failed"]:
if not set_tasks["failed"]:
return LuigiStatusCode.SUCCESS_WITH_RETRY
else:
if set_tasks["scheduling_error"]:
return LuigiSta... |
Returns a canonical string used to identify a particular task | def task_id_str(task_family, params):
"""
Returns a canonical string used to identify a particular task
:param task_family: The task family (class name) of the task
:param params: a dict mapping parameter names to their serialized values
:return: A unique, shortened identifier corresponding to the ... |
Returns an externalized version of a Task. You may both pass an instantiated task object or a task class. Some examples: | def externalize(taskclass_or_taskobject):
"""
Returns an externalized version of a Task. You may both pass an
instantiated task object or a task class. Some examples:
.. code-block:: python
class RequiringTask(luigi.Task):
def requires(self):
task_object = self.clon... |
Maps all Tasks in a structured data object to their. output (). | def getpaths(struct):
"""
Maps all Tasks in a structured data object to their .output().
"""
if isinstance(struct, Task):
return struct.output()
elif isinstance(struct, dict):
return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct))
elif isinstance(struct, (lis... |
Creates a flat list of all all items in structured output ( dicts lists items ): | def flatten(struct):
"""
Creates a flat list of all all items in structured output (dicts, lists, items):
.. code-block:: python
>>> sorted(flatten({'a': 'foo', 'b': 'bar'}))
['bar', 'foo']
>>> sorted(flatten(['foo', ['bar', 'troll']]))
['bar', 'foo', 'troll']
>>> f... |
Lists all output targets by recursively walking output - less ( wrapper ) tasks. | def flatten_output(task):
"""
Lists all output targets by recursively walking output-less (wrapper) tasks.
FIXME order consistently.
"""
r = flatten(task.output())
if not r:
for dep in flatten(task.requires()):
r += flatten_output(dep)
return r |
If Luigi has forked we have a different PID and need to reconnect. | def get_bite(self):
"""
If Luigi has forked, we have a different PID, and need to reconnect.
"""
config = hdfs_config.hdfs()
if self.pid != os.getpid() or not self._bite:
client_kwargs = dict(filter(
lambda k_v: k_v[1] is not None and k_v[1] != '', six... |
Use snakebite. rename if available. | def move(self, path, dest):
"""
Use snakebite.rename, if available.
:param path: source file(s)
:type path: either a string or sequence of strings
:param dest: destination file (single input) or directory (multiple)
:type dest: string
:return: list of renamed ite... |
Use snakebite. rename_dont_move if available. | def rename_dont_move(self, path, dest):
"""
Use snakebite.rename_dont_move, if available.
:param path: source path (single input)
:type path: string
:param dest: destination path
:type dest: string
:return: True if succeeded
:raises: snakebite.errors.File... |
Use snakebite. delete if available. | def remove(self, path, recursive=True, skip_trash=False):
"""
Use snakebite.delete, if available.
:param path: delete-able file(s) or directory(ies)
:type path: either a string or a sequence of strings
:param recursive: delete directories trees like \\*nix: rm -r
:type r... |
Use snakebite. chmod if available. | def chmod(self, path, permissions, recursive=False):
"""
Use snakebite.chmod, if available.
:param path: update-able file(s)
:type path: either a string or sequence of strings
:param permissions: \\*nix style permission number
:type permissions: octal
:param recu... |
Use snakebite. chown/ chgrp if available. | def chown(self, path, owner, group, recursive=False):
"""
Use snakebite.chown/chgrp, if available.
One of owner or group must be set. Just setting group calls chgrp.
:param path: update-able file(s)
:type path: either a string or sequence of strings
:param owner: new ow... |
Use snakebite. count if available. | def count(self, path):
"""
Use snakebite.count, if available.
:param path: directory to count the contents of
:type path: string
:return: dictionary with content_size, dir_count and file_count keys
"""
try:
res = self.get_bite().count(self.list_path(p... |
Use snakebite. copyToLocal if available. | def get(self, path, local_destination):
"""
Use snakebite.copyToLocal, if available.
:param path: HDFS file
:type path: string
:param local_destination: path on the system running Luigi
:type local_destination: string
"""
return list(self.get_bite().copyT... |
Using snakebite getmerge to implement this.: param path: HDFS directory: param local_destination: path on the system running Luigi: return: merge of the directory | def get_merge(self, path, local_destination):
"""
Using snakebite getmerge to implement this.
:param path: HDFS directory
:param local_destination: path on the system running Luigi
:return: merge of the directory
"""
return list(self.get_bite().getmerge(path=path,... |
Use snakebite. mkdir if available. | def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False):
"""
Use snakebite.mkdir, if available.
Snakebite's mkdir method allows control over full path creation, so by
default, tell it to build a full path to work like ``hadoop fs -mkdir``.
:param path: HDFS path ... |
Use snakebite. ls to get the list of items in a directory. | def listdir(self, path, ignore_directories=False, ignore_files=False,
include_size=False, include_type=False, include_time=False,
recursive=False):
"""
Use snakebite.ls to get the list of items in a directory.
:param path: the directory to list
:type path... |
Singleton getter | def instance(cls, *args, **kwargs):
""" Singleton getter """
if cls._instance is None:
cls._instance = cls(*args, **kwargs)
loaded = cls._instance.reload()
logging.getLogger('luigi-interface').info('Loaded %r', loaded)
return cls._instance |
Imports task dynamically given a module and a task name. | def load_task(module, task_name, params_str):
"""
Imports task dynamically given a module and a task name.
"""
if module is not None:
__import__(module)
task_cls = Register.get_task_cls(task_name)
return task_cls.from_str_params(params_str) |
Internal note: This function will be deleted soon. | def task_family(cls):
"""
Internal note: This function will be deleted soon.
"""
if not cls.get_task_namespace():
return cls.__name__
else:
return "{}.{}".format(cls.get_task_namespace(), cls.__name__) |
Return all of the registered classes. | def _get_reg(cls):
"""Return all of the registered classes.
:return: an ``dict`` of task_family -> class
"""
# We have to do this on-demand in case task names have changed later
reg = dict()
for task_cls in cls._reg:
if not task_cls._visible_in_registry:
... |
The writing complement of _get_reg | def _set_reg(cls, reg):
"""The writing complement of _get_reg
"""
cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] |
Returns an unambiguous class or raises an exception. | def get_task_cls(cls, name):
"""
Returns an unambiguous class or raises an exception.
"""
task_cls = cls._get_reg().get(name)
if not task_cls:
raise TaskClassNotFoundException(cls._missing_task_msg(name))
if task_cls == cls.AMBIGUOUS_CLASS:
raise ... |
Compiles and returns all parameters for all: py: class: Task. | def get_all_params(cls):
"""
Compiles and returns all parameters for all :py:class:`Task`.
:return: a generator of tuples (TODO: we should make this more elegant)
"""
for task_name, task_cls in six.iteritems(cls._get_reg()):
if task_cls == cls.AMBIGUOUS_CLASS:
... |
Simple unweighted Levenshtein distance | def _editdistance(a, b):
""" Simple unweighted Levenshtein distance """
r0 = range(0, len(b) + 1)
r1 = [0] * (len(b) + 1)
for i in range(0, len(a)):
r1[0] = i + 1
for j in range(0, len(b)):
c = 0 if a[i] is b[j] else 1
r1[j + 1] =... |
>>> list ( Register. _module_parents ( a. b )) [ a. b a ] | def _module_parents(module_name):
'''
>>> list(Register._module_parents('a.b'))
['a.b', 'a', '']
'''
spl = module_name.split('.')
for i in range(len(spl), 0, -1):
yield '.'.join(spl[0:i])
if module_name:
yield '' |
Retrieve task statuses from ECS API | def _get_task_statuses(task_ids, cluster):
"""
Retrieve task statuses from ECS API
Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids
"""
response = client.describe_tasks(tasks=task_ids, cluster=cluster)
# Error checking
if response['failures'] != []:
raise Exception... |
Poll task status until STOPPED | def _track_tasks(task_ids, cluster):
"""Poll task status until STOPPED"""
while True:
statuses = _get_task_statuses(task_ids, cluster)
if all([status == 'STOPPED' for status in statuses]):
logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids)))
break
time.... |
Override to provide code for creating the target table. | def create_table(self, connection):
"""
Override to provide code for creating the target table.
By default it will be created using types (optionally) specified in columns.
If overridden, use the provided connection object for setting up the table in order to
create the table a... |
Override to perform custom queries. | def init_copy(self, connection):
"""
Override to perform custom queries.
Any code here will be formed in the same transaction as the main copy, just prior to copying data.
Example use cases include truncating the table or removing all data older than X in the database
to keep a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.