INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 di... | 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`,... |
Get an object stored in S3 and write it to a local path. | 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) |
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 | 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)
... |
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 | 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_... |
Is the parameter S3 path a directory? | 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_M... |
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 wi... | 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 (offs... |
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. | 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:
... |
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:... | 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... |
Recursively delete a directory tree on a remote server.
Source: https://gist.github.com/artlogic/2632647 | 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)... |
Put file from local filesystem to (s)FTP. | 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() |
Download file from (s)FTP to local filesystem. | 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_pat... |
Gets an list of the contents of path in (s)FTP | 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 |
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.... | 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
... |
Return targeted mongo collection to query on | def get_collection(self):
"""
Return targeted mongo collection to query on
"""
db_mongo = self._mongo_client[self._index]
return db_mongo[self._collection] |
Read the target value
Use $project aggregate operator in order to support nested objects | 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}}
... |
Write value to the target | def write(self, value):
"""
Write value to the target
"""
self.get_collection().update_one(
{'_id': self._document_id},
{'$set': {self._path: value}},
upsert=True
) |
Read the targets value | 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[s... |
Write values to the targeted documents
Values need to be a dict as : {document_id: value} | 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 f... |
Get documents id with missing targeted field | 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}
)
... |
Get logging settings from config file section "logging". | 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
... |
Setup logging via CLI params and config. | 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('l... |
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 | 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... |
Setup logging via ini-file from logging_conf_file option. | 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 Pyt... |
Setup default logger | def _default(cls, opts):
"""Setup default logger"""
logging.basicConfig(level=logging.INFO, format=cls._log_format)
return True |
Setup logging via ini-file from logging_conf_file option. | 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/... |
Setup default logger | 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 = ... |
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. | 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 =... |
@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. | 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" % ... |
Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit. | def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
... |
Rename/move an object from one GCS location to another. | def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) |
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path. | def listdir(self, path):
"""
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path.
"""
bucket, obj = self._path_to_bucket_and_key(path)
obj_prefix = self._add_path_delimiter(obj)
if self._is_root(obj_prefix):
obj_... |
Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iter... | def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleC... |
Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True. | def download(self, path, chunksize=None, chunk_callback=lambda _: False):
"""Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True.
"""
chunksize = chunksize or self.chunksize
bucket, obj = self._path_to_... |
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html | def create_subprocess(self, command):
"""
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html
"""
def subprocess_setup():
# Python installs a SIGPIPE handler by default. This is usually not what
# non-Python subprocesses expect... |
Closes and waits for subprocess to exit. | def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True |
Checks if task is complete, puts the result to out_queue. | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((t... |
Call ``self._scheduler.add_task``, but store the values too so we can
implement :py:func:`luigi.execution_summary.summary`. | def _add_task(self, *args, **kwargs):
"""
Call ``self._scheduler.add_task``, but store the values too so we can
implement :py:func:`luigi.execution_summary.summary`.
"""
task_id = kwargs['task_id']
status = kwargs['status']
runnable = kwargs['runnable']
ta... |
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before. | def add(self, task, multiprocess=False, processes=0):
"""
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before.
"""
if self._first_task is None and hasattr(task, 'task_id'):
... |
Find dead children and put a response on the result queue.
:return: | def _purge_children(self):
"""
Find dead children and put a response on the result queue.
:return:
"""
for task_id, p in six.iteritems(self._running_tasks):
if not p.is_alive() and p.exitcode:
error_msg = 'Task {} died unexpectedly with exit code {}'.... |
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catc... | def _handle_next_task(self):
"""
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies adde... |
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will... | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pe... |
Returns True if all scheduled tasks were executed successfully. | def run(self):
"""
Returns True if all scheduled tasks were executed successfully.
"""
logger.info('Running Worker with %d processes', self.worker_processes)
sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker()
while True:
... |
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database. | def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index t... |
Find tasks with the given task_name and the same parameters as the kwargs. | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == tas... |
Return all tasks that have been updated. | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() |
Return all running/failed/done events. | def find_all_events(self, session=None):
"""
Return all running/failed/done events.
"""
with self._session(session) as session:
return session.query(TaskEvent).all() |
Find task with the given record ID. | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) |
Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient... | def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If ... |
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError. | def _credentials(self):
"""
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError.
"""
if self.aws_account_id and self.aws_arn_role_name:
return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
... |
Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in. | def do_prune(self):
"""
Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in.
... |
Will create the schema in the database | def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) |
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 and
insert data using the same transactio... | 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... |
If the target table doesn't exist, self.create_table
will be called to attempt to create the table. | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
output = self.output()
con... |
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used. | def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
... |
Determine whether the schema already exists. | def does_schema_exist(self, connection):
"""
Determine whether the schema already exists.
"""
if '.' in self.table:
query = ("select 1 as schema_exists "
"from pg_namespace "
"where nspname = lower(%s) limit 1")
else:
... |
Determine whether the table already exists. | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name =... |
Perform pre-copy sql - such as creating table, truncating, or removing data older than x. | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
... |
Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc. | def post_copy(self, cursor):
"""
Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc.
"""
logger.info('Executing post copy queries')
for query in self.queries:
cursor.execute(query) |
Performs post-copy to fill metadata columns. | def post_copy_metacolums(self, cursor):
"""
Performs post-copy to fill metadata columns.
"""
logger.info('Executing post copy metadata queries')
for query in self.metadata_queries:
cursor.execute(query) |
Defines copying JSON from s3 into redshift. | def copy(self, cursor, f):
"""
Defines copying JSON from s3 into redshift.
"""
logger.info("Inserting file: %s", f)
cursor.execute("""
COPY %s from '%s'
CREDENTIALS '%s'
JSON AS '%s' %s
%s
;""" % (self.table, f, self._credentials(),
... |
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this. | def output(self):
"""
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this.
"""
# uses class name as a meta-table
return RedshiftTarget(
host=self.host,
database=self.database,
user=self.user,
... |
Kill any open Redshift sessions for the given database. | def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from... |
Returns a list of dates in this date interval. | def dates(self):
''' Returns a list of dates in this date interval.'''
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates |
Same as dates() but returns 24 times more info: one for each hour. | def hours(self):
''' Same as dates() but returns 24 times more info: one for each hour.'''
for date in self.dates():
for hour in xrange(24):
yield datetime.datetime.combine(date, datetime.time(hour)) |
The execution of this task will write 4 lines of data on this task's target output. | def run(self):
"""
The execution of this task will write 4 lines of data on this task's target output.
"""
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 1... |
Copies the contents of a single file path to dest | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_a... |
Removes the given mockfile. skip_trash doesn't have any meaning. | def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete... |
Moves a single file from path to dest | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data(... |
listdir does a prefix match of self.get_all_data(), but doesn't yet support globs. | def listdir(self, path):
"""
listdir does a prefix match of self.get_all_data(), but doesn't yet support globs.
"""
return [s for s in self.get_all_data().keys()
if s.startswith(path)] |
Call MockFileSystem's move command | def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) |
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. | def _recursively_freeze(value):
"""
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(val... |
Loads the default from the config. Returns _no_value if it doesn't exist | def _get_value_from_config(self, section, name):
"""Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError, KeyError):
return _no_va... |
Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first. | def _value_iterator(self, task_name, param_name):
"""
Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first.
"""
cp_parser = CmdlineParser.get_instance()
if cp_parser:... |
Parse a list of values from the scheduler.
Only possible if this is_batchable() is True. This will combine the list into a single
parameter value using batch method. This should never need to be overridden.
:param xs: list of values to parse and combine
:return: the combined parsed val... | def _parse_list(self, xs):
"""
Parse a list of values from the scheduler.
Only possible if this is_batchable() is True. This will combine the list into a single
parameter value using batch method. This should never need to be overridden.
:param xs: list of values to parse and c... |
Parses a date string formatted like ``YYYY-MM-DD``. | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() |
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. | def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format) |
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month. | def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
... |
Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`. | def normalize(self, dt):
"""
Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`.
"""
if dt is None:
return None
dt = self._convert_to_dt(dt)
dt = dt.replace(microsecond=0) # remove ... |
Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case. | def parse(self, val):
"""
Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case.
"""
s = str(val).lower()
if s == "true":
return True
elif s == "false":
return False
else:
raise ValueError("cannot interpret... |
Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals. | def parse(self, s):
"""
Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals.
"""
# TODO: can we use xml.utils.iso8601 or something similar?
from luigi import date_... |
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats. | def parse(self, input):
"""
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats.
"""
result = self._parseIso8601(input)
if not result:
result = self._parseSimple(input)
if result is not None:
... |
Converts datetime.timedelta to a string
:param x: the value to serialize. | def serialize(self, x):
"""
Converts datetime.timedelta to a string
:param x: the value to serialize.
"""
weeks = x.days // 7
days = x.days % 7
hours = x.seconds // 3600
minutes = (x.seconds % 3600) // 60
seconds = (x.seconds % 3600) % 60
... |
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value. | def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.
# A tuple string may come from a co... |
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target | def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputTe... |
Create a tar archive which will contain the files for the packages listed in packages. | def create_packages_archive(packages, filename):
"""
Create a tar archive which will contain the files for the packages listed in packages.
"""
import tarfile
tar = tarfile.open(filename, "w")
def add(src, dst):
logger.debug('adding to tar: %s -> %s', src, dst)
tar.add(src, dst)... |
A simple generator which flattens a sequence.
Only one level is flattened.
.. code-block:: python
(1, (2, 3), 4) -> (1, 2, 3, 4) | def flatten(sequence):
"""
A simple generator which flattens a sequence.
Only one level is flattened.
.. code-block:: python
(1, (2, 3), 4) -> (1, 2, 3, 4)
"""
for item in sequence:
if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes):
... |
Runs the job by invoking the command from the given arglist.
Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.
Throws HadoopJobError with information about the error
(including stdout and stderr from the process)
on failure and returns normally otherwise... | def run_and_track_hadoop_job(arglist, tracking_url_callback=None, env=None):
"""
Runs the job by invoking the command from the given arglist.
Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails.
Throws HadoopJobError with information about the error
(in... |
Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.... | def fetch_task_failures(tracking_url):
"""
Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we sho... |
Protected method | def _get_pool(self):
""" Protected method """
if self.pool:
return self.pool
if hadoop().pool:
return hadoop().pool |
Get the MapReduce runner for this job.
If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.
Otherwise, the LocalJobRunner which streams all data through the local machine
will be used (great for testing). | def job_runner(self):
# We recommend that you define a subclass, override this method and set up your own config
"""
Get the MapReduce runner for this job.
If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.
Otherwise, the LocalJobRunner which streams all da... |
Writer format is a method which iterates over the output records
from the reducer and formats them for output.
The default implementation outputs tab separated items. | def writer(self, outputs, stdout, stderr=sys.stderr):
"""
Writer format is a method which iterates over the output records
from the reducer and formats them for output.
The default implementation outputs tab separated items.
"""
for output in outputs:
try:
... |
Increments a Hadoop counter.
Since counters can be a bit slow to update, this batches the updates. | def incr_counter(self, *args, **kwargs):
"""
Increments a Hadoop counter.
Since counters can be a bit slow to update, this batches the updates.
"""
threshold = kwargs.get("threshold", self.batch_counter_default)
if len(args) == 2:
# backwards compatibility wi... |
Increments any unflushed counter values. | def _flush_batch_incr_counter(self):
"""
Increments any unflushed counter values.
"""
for key, count in six.iteritems(self._counter_dict):
if count == 0:
continue
args = list(key) + [count]
self._incr_counter(*args)
self._co... |
Increments a Hadoop counter.
Note that this seems to be a bit slow, ~1 ms
Don't overuse this function by updating very frequently. | def _incr_counter(self, *args):
"""
Increments a Hadoop counter.
Note that this seems to be a bit slow, ~1 ms
Don't overuse this function by updating very frequently.
"""
if len(args) == 2:
# backwards compatibility with existing hadoop jobs
grou... |
Dump instance to file. | def dump(self, directory=''):
"""
Dump instance to file.
"""
with self.no_unpicklable_properties():
file_name = os.path.join(directory, 'job-instance.pickle')
if self.__module__ == '__main__':
d = pickle.dumps(self)
module_name = os... |
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments will be splitted in key and value. | def _map_input(self, input_stream):
"""
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments wil... |
Iterate over input, collect values with the same key, and call the reducer for each unique key. | def _reduce_input(self, inputs, reducer, final=NotImplemented):
"""
Iterate over input, collect values with the same key, and call the reducer for each unique key.
"""
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.... |
Run the mapper on the hadoop node. | def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the mapper on the hadoop node.
"""
self.init_hadoop()
self.init_mapper()
outputs = self._map_input((line[:-1] for line in stdin))
if self.reducer == NotImplemented:
self.writer(outputs, ... |
Run the reducer on the hadoop node. | def run_reducer(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the reducer on the hadoop node.
"""
self.init_hadoop()
self.init_reducer()
outputs = self._reduce_input(self.internal_reader((line[:-1] for line in stdin)), self.reducer, self.final_reducer)
self.w... |
Reader which uses python eval on each part of a tab separated string.
Yields a tuple of python objects. | def internal_reader(self, input_stream):
"""
Reader which uses python eval on each part of a tab separated string.
Yields a tuple of python objects.
"""
for input_line in input_stream:
yield list(map(self.deserialize, input_line.split("\t"))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.