INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Build a bsub argument that will run lsf_runner. py on the directory we ve specified. | def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.... |
Generates: py: attr: ~. UserItemMatrix. data_size elements. Writes this data in \\ separated value format into the target: py: func: ~/. UserItemMatrix. output. | def run(self):
"""
Generates :py:attr:`~.UserItemMatrix.data_size` elements.
Writes this data in \\ separated value format into the target :py:func:`~/.UserItemMatrix.output`.
The data has the following elements:
* `user` is the default Elasticsearch id field,
* `track`... |
Returns the target output for this task. In this case a successful execution of this task will create a file in HDFS. | def output(self):
"""
Returns the target output for this task.
In this case, a successful execution of this task will create a file in HDFS.
:return: the target output for this task.
:rtype: object (:py:class:`~luigi.target.Target`)
"""
return luigi.contrib.hdfs.... |
convert UTC time string to time. struct_time: change datetime. datetime to time return time. struct_time type | def from_utc(utcTime, fmt=None):
"""convert UTC time string to time.struct_time: change datetime.datetime to time, return time.struct_time type"""
if fmt is None:
try_formats = ["%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"]
else:
try_formats = [fmt]
for fmt in try_formats:
try:
... |
Runs one instance of the API server. | def run(api_port=8082, address=None, unix_socket=None, scheduler=None):
"""
Runs one instance of the API server.
"""
if scheduler is None:
scheduler = Scheduler()
# load scheduler state
scheduler.load()
_init_api(
scheduler=scheduler,
api_port=api_port,
addr... |
Gets queried columns names. | def get_soql_fields(soql):
"""
Gets queried columns names.
"""
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE) # get fields
soql_fields = re.sub(' ', '', soql_fields.group()) # remove extra spaces
soql_fields = re.sub('\t', '', soql_fi... |
Traverses ordered dictionary calls _traverse_results () to recursively read into the dictionary depth of data | def parse_results(fields, data):
"""
Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data
"""
master = []
for record in data['records']: # for each 'record' in response
row = [None] * len(fields) # create null list the length of num... |
Helper method for parse_results (). | def _traverse_results(value, fields, row, path):
"""
Helper method for parse_results().
Traverses through ordered dict and recursively calls itself when encountering a dictionary
"""
for f, v in value.iteritems(): # for each item in obj
field_name = '{path}.{name}'.format(path=path, name=f... |
Merges the resulting files of a multi - result batch bulk query. | def merge_batch_results(self, result_ids):
"""
Merges the resulting files of a multi-result batch bulk query.
"""
outfile = open(self.output().path, 'w')
if self.content_type.lower() == 'csv':
for i, result_id in enumerate(result_ids):
with open("%s.%... |
Starts a Salesforce session and determines which SF instance to use for future requests. | def start_session(self):
"""
Starts a Salesforce session and determines which SF instance to use for future requests.
"""
if self.has_active_session():
raise Exception("Session already in progress.")
response = requests.post(self._get_login_url(),
... |
Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload. | def query(self, query, **kwargs):
"""
Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload.
:param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'"
"""
params = {'q': query}
... |
Retrieves more results from a query that returned more results than the batch maximum. Returns a dict decoded from the Salesforce response JSON payload. | def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs):
"""
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either t... |
Returns the full set of results for the query. This is a convenience wrapper around query (... ) and query_more (... ). The returned dict is the decoded JSON payload from the final call to Salesforce but with the totalSize field representing the full number of results retrieved and the records list representing the ful... | def query_all(self, query, **kwargs):
"""
Returns the full set of results for the `query`. This is a
convenience wrapper around `query(...)` and `query_more(...)`.
The returned dict is the decoded JSON payload from the final call to
Salesforce, but with the `totalSize` field repr... |
Allows you to make a direct REST call if you know the path Arguments:: param path: The path of the request. Example: sobjects/ User/ ABC123/ password: param params: dict of parameters to pass to the path | def restful(self, path, params):
"""
Allows you to make a direct REST call if you know the path
Arguments:
:param path: The path of the request. Example: sobjects/User/ABC123/password'
:param params: dict of parameters to pass to the path
"""
url = self._get_norm... |
Creates a new SF job that for doing any operation ( insert upsert update delete query ) | def create_operation_job(self, operation, obj, external_id_field_name=None, content_type=None):
"""
Creates a new SF job that for doing any operation (insert, upsert, update, delete, query)
:param operation: delete, insert, query, upsert, update, hardDelete. Must be lowercase.
:param ob... |
Gets all details for existing job | def get_job_details(self, job_id):
"""
Gets all details for existing job
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: job info as xml
"""
response = requests.get(self._get_job_details_url(job_id))
response.raise_for_status()
... |
Abort an existing job. When a job is aborted no more records are processed. Changes to data may already have been committed and aren t rolled back. | def abort_job(self, job_id):
"""
Abort an existing job. When a job is aborted, no more records are processed.
Changes to data may already have been committed and aren't rolled back.
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: abort response as xml
... |
Closes job | def close_job(self, job_id):
"""
Closes job
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: close response as xml
"""
if not job_id or not self.has_active_session():
raise Exception("Can not close job without valid job_id and an acti... |
Creates a batch with either a string of data or a file containing data. | def create_batch(self, job_id, data, file_type):
"""
Creates a batch with either a string of data or a file containing data.
If a file is provided, this will pull the contents of the file_target into memory when running.
That shouldn't be a problem for any files that meet the Salesforce... |
Blocks until | def block_on_batch(self, job_id, batch_id, sleep_time_seconds=5, max_wait_time_seconds=-1):
"""
Blocks until @batch_id is completed or failed.
:param job_id:
:param batch_id:
:param sleep_time_seconds:
:param max_wait_time_seconds:
"""
if not job_id or not... |
DEPRECATED: Use get_batch_result_ids | def get_batch_results(self, job_id, batch_id):
"""
DEPRECATED: Use `get_batch_result_ids`
"""
warnings.warn("get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids")
return self.get_batch_result_ids(job_id, batch_id)[0] |
Get result IDs of a batch that has completed processing. | def get_batch_result_ids(self, job_id, batch_id):
"""
Get result IDs of a batch that has completed processing.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param batch_id: batch_id as returned by 'create_batch(...)'
:return: list of batch result IDs to be us... |
Gets result back from Salesforce as whatever type was originally sent in create_batch ( xml or csv ).: param job_id:: param batch_id:: param result_id: | def get_batch_result(self, job_id, batch_id, result_id):
"""
Gets result back from Salesforce as whatever type was originally sent in create_batch (xml, or csv).
:param job_id:
:param batch_id:
:param result_id:
"""
response = requests.get(self._get_batch_result_... |
Parse state column from qstat output for given job_id | def _parse_qstat_state(qstat_out, job_id):
"""Parse "state" column from `qstat` output for given job_id
Returns state for the *first* job matching job_id. Returns 'u' if
`qstat` output is empty or job_id is not found.
"""
if qstat_out.strip() == '':
return 'u'
lines = qstat_out.split('... |
Submit shell command to SGE queue via qsub | def _build_qsub_command(cmd, job_name, outfile, errfile, pe, n_cpu):
"""Submit shell command to SGE queue via `qsub`"""
qsub_template = """echo {cmd} | qsub -o ":{outfile}" -e ":{errfile}" -V -r y -pe {pe} {n_cpu} -N {job_name}"""
return qsub_template.format(
cmd=cmd, job_name=job_name, outfile=outf... |
Dump instance to file. | def _dump(self, out_dir=''):
"""Dump instance to file."""
with self.no_unpicklable_properties():
self.job_file = os.path.join(out_dir, 'job-instance.pickle')
if self.__module__ == '__main__':
d = pickle.dumps(self)
module_name = os.path.basename(sy... |
Writes data in JSON format into the task s output target. | def run(self):
"""
Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created.
"""
today = date... |
Creates the client as specified in the luigi. cfg configuration. | def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT):
"""
Creates the client as specified in the `luigi.cfg` configuration.
"""
try:
return client_cache.client
except AttributeError:
configured_client = hdfs_config.get_configured_hdfs_client()
if configured_client == "w... |
For internal use only ( until further notice ) | def wrap_traceback(traceback):
"""
For internal use only (until further notice)
"""
if email().format == 'html':
try:
from pygments import highlight
from pygments.lexers import PythonTracebackLexer
from pygments.formatters import HtmlFormatter
with... |
Sends notification through AWS SES. | def send_email_ses(sender, subject, message, recipients, image_png):
"""
Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from bot... |
Sends notification through AWS SNS. Takes Topic ARN from recipients. | def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configur... |
Decides whether to send notification. Notification is cancelled if there are no recipients or if stdout is onto tty or if in debug mode. | def send_email(subject, message, sender, recipients, image_png=None):
"""
Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'.
"""
notifiers = {
... |
Sends an email to the configured error email if it s configured. | def send_error_email(subject, message, additional_recipients=None):
"""
Sends an email to the configured error email, if it's configured.
"""
recipients = _email_recipients(additional_recipients)
sender = email().sender
send_email(
subject=subject,
message=message,
sender... |
Format a message body for an error email related to a luigi. task. Task | def format_task_error(headline, task, command, formatted_exception=None):
"""
Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional st... |
Returns true if the path exists and false otherwise. | def exists(self, path):
"""
Returns true if the path exists and false otherwise.
"""
import hdfs
try:
self.client.status(path)
return True
except hdfs.util.HdfsError as e:
if str(e).startswith('File does not exist: '):
r... |
Has no returnvalue ( just like WebHDFS ) | def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False):
"""
Has no returnvalue (just like WebHDFS)
"""
if not parents or raise_if_exists:
warnings.warn('webhdfs mkdir: parents/raise_if_exists not implemented')
permission = int(oct(mode)[2:]) # Convert... |
To touchz using the web hdfs write cmd. | def touchz(self, path):
"""
To touchz using the web hdfs "write" cmd.
"""
self.client.write(path, data='', overwrite=False) |
Open the target for reading or writing | def open(self, mode):
"""
Open the target for reading or writing
:param char mode:
'r' for reading and 'w' for writing.
'b' is not supported and will be stripped if used. For binary mode, use `format`
:return:
* :class:`.ReadableAzureBlobFile` if 'r'... |
Generates bogus data and writes it into the: py: meth: ~. Streams. output target. | def run(self):
"""
Generates bogus data and writes it into the :py:meth:`~.Streams.output` target.
"""
with self.output().open('w') as output:
for _ in range(1000):
output.write('{} {} {}\n'.format(
random.randint(0, 999),
... |
This task s dependencies: | def requires(self):
"""
This task's dependencies:
* :py:class:`~.AggregateArtists` or
* :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set.
:return: object (:py:class:`luigi.task.Task`)
"""
if self.use_spark:
return Ag... |
Returns a temporary file path based on a MD5 hash generated with the task s name and its arguments | def get_path(self):
"""
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
"""
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
return os.path.... |
Creates temporary file to mark the task as done | def done(self):
"""
Creates temporary file to mark the task as `done`
"""
logger.info('Marking %s as done', self)
fn = self.get_path()
try:
os.makedirs(os.path.dirname(fn))
except OSError:
pass
open(fn, 'w').close() |
Does provided path exist on S3? | def exists(self, path):
"""
Does provided path exist on S3?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
# root always exists
if self._is_root(key):
return True
# file
if self._exists(bucket, key):
return True
i... |
Remove a file or directory from S3.: param path: File or directory to remove: param recursive: Boolean indicator to remove object and children: return: Boolean indicator denoting success of the removal of 1 or more files | def remove(self, path, recursive=True):
"""
Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files
"""
... |
Returns the object summary at the path | def get_key(self, path):
"""
Returns the object summary at the path
"""
(bucket, key) = self._path_to_bucket_and_key(path)
if self._exists(bucket, key):
return self.s3.ObjectSummary(bucket, key) |
Put an object stored locally to an S3 path.: param local_path: Path to source local file: param destination_s3_path: URL for target S3 location: param kwargs: Keyword arguments are passed to the boto function put_object | def put(self, local_path, destination_s3_path, **kwargs):
"""
Put an object stored locally to an S3 path.
:param local_path: Path to source local file
:param destination_s3_path: URL for target S3 location
:param kwargs: Keyword arguments are passed to the boto function `put_obje... |
Put a string to an S3 path.: param content: Data str: param destination_s3_path: URL for target S3 location: param kwargs: Keyword arguments are passed to the boto3 function put_object | def put_string(self, content, destination_s3_path, **kwargs):
"""
Put a string to an S3 path.
:param content: Data str
:param destination_s3_path: URL for target S3 location
:param kwargs: Keyword arguments are passed to the boto3 function `put_object`
"""
self._c... |
Put an object stored locally to an S3 path using S3 multi - part upload ( for files > 8Mb ).: param local_path: Path to source local file: param destination_s3_path: URL for target S3 location: param part_size: Part size in bytes. Default: 8388608 ( 8MB ): param kwargs: Keyword arguments are passed to the boto function... | def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs):
"""
Put an object stored locally to an S3 path
using S3 multi-part upload (for files > 8Mb).
:param local_path: Path to source local file
:param destination_s3_path: URL for target S3... |
Copy object ( s ) from one S3 location to another. Works for individual keys or entire directories. When files are larger than part_size multipart uploading will be used.: param source_path: The s3:// path of the directory or key to copy from: param destination_path: The s3:// path of the directory or key to copy to: p... | 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 | 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. | 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 with modified ( offset aware ) d... | 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. | 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. | 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. | 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. | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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: | 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. | 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. | 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 | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.