Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def send_error_email(subject, message, additional_recipients=None): recipients = _email_recipients(additional_recipients) sender = email().sender send_email( subject=subject, message=message, sender=sender, recipients=recipien...
[ "\n Sends an email to the configured error email, if it's configured.\n " ]
Please provide a description of the function:def format_task_error(headline, task, command, formatted_exception=None): if formatted_exception: formatted_exception = wrap_traceback(formatted_exception) else: formatted_exception = "" if email().format == 'html': msg_template = t...
[ "\n Format a message body for an error email related to a luigi.task.Task\n\n :param headline: Summary line for the message\n :param task: `luigi.task.Task` instance where this error occurred\n :param formatted_exception: optional string showing traceback\n\n :return: message body\n " ]
Please provide a description of the function:def exists(self, path): import hdfs try: self.client.status(path) return True except hdfs.util.HdfsError as e: if str(e).startswith('File does not exist: '): return False else: ...
[ "\n Returns true if the path exists and false otherwise.\n " ]
Please provide a description of the function:def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): if not parents or raise_if_exists: warnings.warn('webhdfs mkdir: parents/raise_if_exists not implemented') permission = int(oct(mode)[2:]) # Convert from int(decimal...
[ "\n Has no returnvalue (just like WebHDFS)\n " ]
Please provide a description of the function:def touchz(self, path): self.client.write(path, data='', overwrite=False)
[ "\n To touchz using the web hdfs \"write\" cmd.\n " ]
Please provide a description of the function:def open(self, mode): if mode not in ('r', 'w'): raise ValueError("Unsupported open mode '%s'" % mode) if mode == 'r': return self.format.pipe_reader(ReadableAzureBlobFile(self.container, self.blob, self.client, self.download_...
[ "\n Open the target for reading or writing\n\n :param char mode:\n 'r' for reading and 'w' for writing.\n\n 'b' is not supported and will be stripped if used. For binary mode, use `format`\n :return:\n * :class:`.ReadableAzureBlobFile` if 'r'\n * :cla...
Please provide a description of the function:def run(self): with self.output().open('w') as output: for _ in range(1000): output.write('{} {} {}\n'.format( random.randint(0, 999), random.randint(0, 999), random.rand...
[ "\n Generates bogus data and writes it into the :py:meth:`~.Streams.output` target.\n " ]
Please provide a description of the function:def requires(self): if self.use_spark: return AggregateArtistsSpark(self.date_interval) else: return AggregateArtists(self.date_interval)
[ "\n This task's dependencies:\n\n * :py:class:`~.AggregateArtists` or\n * :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set.\n\n :return: object (:py:class:`luigi.task.Task`)\n " ]
Please provide a description of the function:def get_path(self): md5_hash = hashlib.md5(self.task_id.encode()).hexdigest() logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id) return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
[ "\n Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments\n " ]
Please provide a description of the function:def done(self): logger.info('Marking %s as done', self) fn = self.get_path() try: os.makedirs(os.path.dirname(fn)) except OSError: pass open(fn, 'w').close()
[ "\n Creates temporary file to mark the task as `done`\n " ]
Please provide a description of the function:def exists(self, path): (bucket, key) = self._path_to_bucket_and_key(path) # root always exists if self._is_root(key): return True # file if self._exists(bucket, key): return True if self.isd...
[ "\n Does provided path exist on S3?\n " ]
Please provide a description of the function:def remove(self, path, recursive=True): if not self.exists(path): logger.debug('Could not delete %s; path does not exist', path) return False (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Buck...
[ "\n Remove a file or directory from S3.\n :param path: File or directory to remove\n :param recursive: Boolean indicator to remove object and children\n :return: Boolean indicator denoting success of the removal of 1 or more files\n " ]
Please provide a description of the function:def get_key(self, path): (bucket, key) = self._path_to_bucket_and_key(path) if self._exists(bucket, key): return self.s3.ObjectSummary(bucket, key)
[ "\n Returns the object summary at the path\n " ]
Please provide a description of the function:def put(self, local_path, destination_s3_path, **kwargs): self._check_deprecated_argument(**kwargs) # put the file self.put_multipart(local_path, destination_s3_path, **kwargs)
[ "\n Put an object stored locally to an S3 path.\n :param local_path: Path to source local file\n :param destination_s3_path: URL for target S3 location\n :param kwargs: Keyword arguments are passed to the boto function `put_object`\n " ]
Please provide a description of the function:def put_string(self, content, destination_s3_path, **kwargs): self._check_deprecated_argument(**kwargs) (bucket, key) = self._path_to_bucket_and_key(destination_s3_path) # put the file self.s3.meta.client.put_object( Key=...
[ "\n Put a string to an S3 path.\n :param content: Data str\n :param destination_s3_path: URL for target S3 location\n :param kwargs: Keyword arguments are passed to the boto3 function `put_object`\n " ]
Please provide a description of the function:def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs): self._check_deprecated_argument(**kwargs) from boto3.s3.transfer import TransferConfig # default part size for boto3 is 8Mb, changing it to fit ...
[ "\n Put an object stored locally to an S3 path\n using S3 multi-part upload (for files > 8Mb).\n :param local_path: Path to source local file\n :param destination_s3_path: URL for target S3 location\n :param part_size: Part size in bytes. Default: 8388608 (8MB)\n :param kwa...
Please provide a description of the function:def copy(self, source_path, destination_path, threads=DEFAULT_THREADS, start_time=None, end_time=None, part_size=DEFAULT_PART_SIZE, **kwargs): # don't allow threads to be less than 3 threads = 3 if threads < 3 else threads if s...
[ "\n Copy object(s) from one S3 location to another. Works for individual keys or entire directories.\n When files are larger than `part_size`, multipart uploading will be used.\n :param source_path: The `s3://` path of the directory or key to copy from\n :param destination_path: The `s3:...
Please provide a description of the function:def get(self, s3_path, destination_local_path): (bucket, key) = self._path_to_bucket_and_key(s3_path) # download the file self.s3.meta.client.download_file(bucket, key, destination_local_path)
[ "\n Get an object stored in S3 and write it to a local path.\n " ]
Please provide a description of the function:def get_as_bytes(self, s3_path): (bucket, key) = self._path_to_bucket_and_key(s3_path) obj = self.s3.Object(bucket, key) contents = obj.get()['Body'].read() return contents
[ "\n Get the contents of an object stored in S3 as bytes\n\n :param s3_path: URL for target S3 location\n :return: File contents as pure bytes\n " ]
Please provide a description of the function:def get_as_string(self, s3_path, encoding='utf-8'): content = self.get_as_bytes(s3_path) return content.decode(encoding)
[ "\n Get the contents of an object stored in S3 as string.\n\n :param s3_path: URL for target S3 location\n :param encoding: Encoding to decode bytes to string\n :return: File contents as a string\n " ]
Please provide a description of the function:def isdir(self, path): (bucket, key) = self._path_to_bucket_and_key(path) s3_bucket = self.s3.Bucket(bucket) # root is a directory if self._is_root(key): return True for suffix in (S3_DIRECTORY_MARKER_SUFFIX_0, ...
[ "\n Is the parameter S3 path a directory?\n " ]
Please provide a description of the function:def listdir(self, path, start_time=None, end_time=None, return_key=False): (bucket, key) = self._path_to_bucket_and_key(path) # grab and validate the bucket s3_bucket = self.s3.Bucket(bucket) key_path = self._add_path_delimiter(key)...
[ "\n Get an iterable with S3 folder contents.\n Iterable contains paths relative to queried path.\n :param path: URL for target S3 location\n :param start_time: Optional argument to list files with modified (offset aware) datetime after start_time\n :param end_time: Optional argume...
Please provide a description of the function:def exists(self, path, mtime=None): self._connect() if self.sftp: exists = self._sftp_exists(path, mtime) else: exists = self._ftp_exists(path, mtime) self._close() return exists
[ "\n Return `True` if file or directory at `path` exist, False otherwise.\n\n Additional check on modified time when mtime is passed in.\n\n Return False if the file's modified time is older mtime.\n " ]
Please provide a description of the function:def remove(self, path, recursive=True): self._connect() if self.sftp: self._sftp_remove(path, recursive) else: self._ftp_remove(path, recursive) self._close()
[ "\n Remove file or directory at location ``path``.\n\n :param path: a path within the FileSystem to remove.\n :type path: str\n :param recursive: if the path is a directory, recursively remove the directory and\n all of its descendants. Defaults to ``True``.\n ...
Please provide a description of the function:def _rm_recursive(self, ftp, path): wd = ftp.pwd() # check if it is a file first, because some FTP servers don't return # correctly on ftp.nlst(file) try: ftp.cwd(path) except ftplib.all_errors: # this...
[ "\n Recursively delete a directory tree on a remote server.\n\n Source: https://gist.github.com/artlogic/2632647\n " ]
Please provide a description of the function:def put(self, local_path, path, atomic=True): self._connect() if self.sftp: self._sftp_put(local_path, path, atomic) else: self._ftp_put(local_path, path, atomic) self._close()
[ "\n Put file from local filesystem to (s)FTP.\n " ]
Please provide a description of the function:def get(self, path, local_path): normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder and not os.path.exists(folder): os.makedirs(folder) tmp_local_path = local_path + '-luigi-tmp-%09d' % r...
[ "\n Download file from (s)FTP to local filesystem.\n " ]
Please provide a description of the function:def listdir(self, path='.'): self._connect() if self.sftp: contents = self._sftp_listdir(path) else: contents = self._ftp_listdir(path) self._close() return contents
[ "\n Gets an list of the contents of path in (s)FTP\n " ]
Please provide a description of the function:def open(self, mode): if mode == 'w': return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path)) elif mode == 'r': temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp') self.__tmp_path = temp...
[ "\n Open the FileSystem target.\n\n This method returns a file-like object which can either be read from or written to depending\n on the specified mode.\n\n :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will\n open the FileSystem...
Please provide a description of the function:def get_collection(self): db_mongo = self._mongo_client[self._index] return db_mongo[self._collection]
[ "\n Return targeted mongo collection to query on\n " ]
Please provide a description of the function:def read(self): result = self.get_collection().aggregate([ {'$match': {'_id': self._document_id}}, {'$project': {'_value': '$' + self._path, '_id': False}} ]) for doc in result: if '_value' not in doc: ...
[ "\n Read the target value\n Use $project aggregate operator in order to support nested objects\n " ]
Please provide a description of the function:def write(self, value): self.get_collection().update_one( {'_id': self._document_id}, {'$set': {self._path: value}}, upsert=True )
[ "\n Write value to the target\n " ]
Please provide a description of the function:def read(self): cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {self._field: True} ) return {doc['_id']: doc[se...
[ "\n Read the targets value\n " ]
Please provide a description of the function:def write(self, values): # Insert only for docs targeted by the target filtered = {_id: value for _id, value in values.items() if _id in self._document_ids} if not filtered: return bulk = self.get_collection().initialize...
[ "\n Write values to the targeted documents\n Values need to be a dict as : {document_id: value}\n " ]
Please provide a description of the function:def get_empty_ids(self): cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {'_id': True} ) return set(self._docume...
[ "\n Get documents id with missing targeted field\n " ]
Please provide a description of the function:def _section(cls, opts): if isinstance(cls.config, LuigiConfigParser): return False try: logging_config = cls.config['logging'] except (TypeError, KeyError, NoSectionError): return False logging.con...
[ "Get logging settings from config file section \"logging\"." ]
Please provide a description of the function:def setup(cls, opts=type('opts', (), { 'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG' })): logger = logging.getLogger('lu...
[ "Setup logging via CLI params and config." ]
Please provide a description of the function:def _cli(cls, opts): if opts.background: logging.getLogger().setLevel(logging.INFO) return True if opts.logdir: logging.basicConfig( level=logging.INFO, format=cls._log_format, ...
[ "Setup logging via CLI options\n\n If `--background` -- set INFO level for root logger.\n If `--logdir` -- set logging with next params:\n default Luigi's formatter,\n INFO level,\n output in logdir in `luigi-server.log` file\n " ]
Please provide a description of the function:def _conf(cls, opts): logging_conf = cls.config.get('core', 'logging_conf_file', None) if logging_conf is None: return False if not os.path.exists(logging_conf): # FileNotFoundError added only in Python 3.3 ...
[ "Setup logging via ini-file from logging_conf_file option." ]
Please provide a description of the function:def _default(cls, opts): logging.basicConfig(level=logging.INFO, format=cls._log_format) return True
[ "Setup default logger" ]
Please provide a description of the function:def _conf(cls, opts): if not opts.logging_conf_file: return False if not os.path.exists(opts.logging_conf_file): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/3.3.html#pep-3151-...
[ "Setup logging via ini-file from logging_conf_file option." ]
Please provide a description of the function:def _default(cls, opts): level = getattr(logging, opts.log_level, logging.DEBUG) logger = logging.getLogger('luigi-interface') logger.setLevel(level) stream_handler = logging.StreamHandler() stream_handler.setLevel(level) ...
[ "Setup default logger" ]
Please provide a description of the function:def get_configured_hdfs_client(): config = hdfs() custom = config.client conf_usinf_snakebite = [ "snakebite_with_hadoopcli_fallback", "snakebite", ] if six.PY3 and (custom in conf_usinf_snakebite): warnings.warn( ...
[ "\n This is a helper that fetches the configuration value for 'client' in\n the [hdfs] section. It will return the client that retains backwards\n compatibility when 'client' isn't configured.\n " ]
Please provide a description of the function:def tmppath(path=None, include_unix_username=True): addon = "luigitemp-%08d" % random.randrange(1e9) temp_dir = '/tmp' # default tmp dir if none is specified in config # 1. Figure out to which temporary directory to place configured_hdfs_tmp_dir = hdfs...
[ "\n @param path: target path for which it is needed to generate temporary location\n @type path: str\n @type include_unix_username: bool\n @rtype: str\n\n Note that include_unix_username might work on windows too.\n " ]
Please provide a description of the function:def _wait_for_consistency(checker): for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS): if checker(): return time.sleep(EVENTUAL_CONSISTENCY_SLEEP_INTERVAL) logger.warning('Exceeded wait for eventual GCS consistency - this may be a' ...
[ "Eventual consistency: wait until GCS reports something is true.\n\n This is necessary for e.g. create/delete where the operation might return,\n but won't be reflected for a bit.\n " ]
Please provide a description of the function:def move(self, source_path, destination_path): self.copy(source_path, destination_path) self.remove(source_path)
[ "\n Rename/move an object from one GCS location to another.\n " ]
Please provide a description of the function:def listdir(self, path): bucket, obj = self._path_to_bucket_and_key(path) obj_prefix = self._add_path_delimiter(obj) if self._is_root(obj_prefix): obj_prefix = '' obj_prefix_len = len(obj_prefix) for it in self._...
[ "\n Get an iterable with GCS folder contents.\n Iterable contains paths relative to queried path.\n " ]
Please provide a description of the function:def list_wildcard(self, wildcard_path): path, wildcard_obj = wildcard_path.rsplit('/', 1) assert '*' not in path, "The '*' wildcard character is only supported after the last '/'" wildcard_parts = wildcard_obj.split('*') assert len(wi...
[ "Yields full object URIs matching the given wildcard.\n\n Currently only the '*' wildcard after the last path delimiter is supported.\n\n (If we need \"full\" wildcard functionality we should bring in gsutil dependency with its\n https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/w...
Please provide a description of the function:def download(self, path, chunksize=None, chunk_callback=lambda _: False): chunksize = chunksize or self.chunksize bucket, obj = self._path_to_bucket_and_key(path) with tempfile.NamedTemporaryFile(delete=False) as fp: # We can't r...
[ "Downloads the object contents to local file system.\n\n Optionally stops after the first chunk for which chunk_callback returns True.\n " ]
Please provide a description of the function:def create_subprocess(self, command): def subprocess_setup(): # Python installs a SIGPIPE handler by default. This is usually not what # non-Python subprocesses expect. signal.signal(signal.SIGPIPE, signal.SIG_DFL) ...
[ "\n http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html\n " ]
Please provide a description of the function:def _finish(self): if self._process.returncode is None: self._process.stdin.flush() self._process.stdin.close() self._process.wait() self.closed = True
[ "\n Closes and waits for subprocess to exit.\n " ]
Please provide a description of the function:def check_complete(task, 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((task, is_complete))
[ "\n Checks if task is complete, puts the result to out_queue.\n " ]
Please provide a description of the function:def _add_task(self, *args, **kwargs): task_id = kwargs['task_id'] status = kwargs['status'] runnable = kwargs['runnable'] task = self._scheduled_tasks.get(task_id) if task: self._add_task_history.append((task, stat...
[ "\n Call ``self._scheduler.add_task``, but store the values too so we can\n implement :py:func:`luigi.execution_summary.summary`.\n " ]
Please provide a description of the function:def add(self, task, multiprocess=False, processes=0): if self._first_task is None and hasattr(task, 'task_id'): self._first_task = task.task_id self.add_succeeded = True if multiprocess: queue = multiprocessing.Manager...
[ "\n Add a Task for the worker to check and possibly schedule and run.\n\n Returns True if task and its dependencies were successfully scheduled or completed before.\n " ]
Please provide a description of the function:def _purge_children(self): 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 {}'.format(task_id, p.exitcode) p.task.trig...
[ "\n Find dead children and put a response on the result queue.\n\n :return:\n " ]
Please provide a description of the function:def _handle_next_task(self): self._idle_since = None while True: self._purge_children() # Deal with subprocess failures try: task_id, status, expl, missing, new_requirements = ( self._task...
[ "\n We have to catch three ways a task can be \"done\":\n\n 1. normal execution: the task runs/fails and puts a result back on the queue,\n 2. new dependencies: the task yielded new deps that were not complete and\n will be rescheduled and dependencies added,\n 3. child process...
Please provide a description of the function:def _keep_alive(self, get_work_response): if not self._config.keep_alive: return False elif self._assistant: return True elif self._config.count_last_scheduled: return get_work_response.n_pending_last_sched...
[ "\n Returns true if a worker should stay alive given.\n\n If worker-keep-alive is not set, this will always return false.\n For an assistant, it will always return the value of worker-keep-alive.\n Otherwise, it will return true for nonzero n_pending_tasks.\n\n If worker-count-uni...
Please provide a description of the function:def run(self): logger.info('Running Worker with %d processes', self.worker_processes) sleeper = self._sleeper() self.run_succeeded = True self._add_worker() while True: while len(self._running_tasks) >= self.wor...
[ "\n Returns True if all scheduled tasks were executed successfully.\n " ]
Please provide a description of the function:def _upgrade_schema(engine): inspector = reflection.Inspector.from_engine(engine) with engine.connect() as conn: # Upgrade 1. Add task_id column and index to tasks if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]: ...
[ "\n Ensure the database schema is up to date with the codebase.\n\n :param engine: SQLAlchemy engine of the underlying database.\n " ]
Please provide a description of the function:def find_all_by_parameters(self, task_name, session=None, **task_params): with self._session(session) as session: query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name) for (k, v) in six.iteritems(task_...
[ "\n Find tasks with the given task_name and the same parameters as the kwargs.\n " ]
Please provide a description of the function:def find_all_runs(self, session=None): with self._session(session) as session: return session.query(TaskRecord).all()
[ "\n Return all tasks that have been updated.\n " ]
Please provide a description of the function:def find_all_events(self, session=None): with self._session(session) as session: return session.query(TaskEvent).all()
[ "\n Return all running/failed/done events.\n " ]
Please provide a description of the function:def find_task_by_id(self, id, session=None): with self._session(session) as session: return session.query(TaskRecord).get(id)
[ "\n Find task with the given record ID.\n " ]
Please provide a description of the function:def get_authenticate_kwargs(oauth_credentials=None, http_=None): if oauth_credentials: authenticate_kwargs = { "credentials": oauth_credentials } elif http_: authenticate_kwargs = { "http": http_ } else...
[ "Returns a dictionary with keyword arguments for use with discovery\n\n Prioritizes oauth_credentials or a http client provided by the user\n If none provided, falls back to default credentials provided by google's command line\n utilities. If that also fails, tries using httplib2.Http()\n\n Used by `gc...
Please provide a description of the function:def _credentials(self): if self.aws_account_id and self.aws_arn_role_name: return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format( id=self.aws_account_id, role=self.aws_arn_role_name ) elif...
[ "\n Return a credential string for the provided task. If no valid\n credentials are set, raise a NotImplementedError.\n " ]
Please provide a description of the function:def do_prune(self): if self.prune_table and self.prune_column and self.prune_date: return True elif self.prune_table or self.prune_column or self.prune_date: raise Exception('override zero or all prune variables') else...
[ "\n Return True if prune_table, prune_column, and prune_date are implemented.\n If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.\n Prune (data newer than prune_date deleted) before copying new data in.\n " ]
Please provide a description of the function:def create_schema(self, connection): 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)
[ "\n Will create the schema in the database\n " ]
Please provide a description of the function:def create_table(self, connection): if len(self.columns[0]) == 1: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented " "for %r and columns types ...
[ "\n Override to provide code for creating the target table.\n\n By default it will be created using types (optionally)\n specified in columns.\n\n If overridden, use the provided connection object for\n setting up the table in order to create the table and\n insert data usi...
Please provide a description of the function:def run(self): if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path() output = self.output() connection = output.connect() cursor = connection.cursor() self.init_cop...
[ "\n If the target table doesn't exist, self.create_table\n will be called to attempt to create the table.\n " ]
Please provide a description of the function:def copy(self, cursor, f): logger.info("Inserting file: %s", f) colnames = '' if self.columns and len(self.columns) > 0: colnames = ",".join([x[0] for x in self.columns]) colnames = '({})'.format(colnames) cur...
[ "\n Defines copying from s3 into redshift.\n\n If both key-based and role-based credentials are provided, role-based will be used.\n ", "\n COPY {table} {colnames} from '{source}'\n CREDENTIALS '{creds}'\n {options}\n ;" ]
Please provide a description of the function:def does_schema_exist(self, connection): if '.' in self.table: query = ("select 1 as schema_exists " "from pg_namespace " "where nspname = lower(%s) limit 1") else: return True ...
[ "\n Determine whether the schema already exists.\n " ]
Please provide a description of the function:def does_table_exist(self, connection): if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and table_name = lower(%s) limit 1") ...
[ "\n Determine whether the table already exists.\n " ]
Please provide a description of the function:def init_copy(self, connection): if not self.does_schema_exist(connection): logger.info("Creating schema for %s", self.table) self.create_schema(connection) if not self.does_table_exist(connection): logger.info("C...
[ "\n Perform pre-copy sql - such as creating table, truncating, or removing data older than x.\n " ]
Please provide a description of the function:def post_copy(self, cursor): logger.info('Executing post copy queries') for query in self.queries: cursor.execute(query)
[ "\n Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc.\n " ]
Please provide a description of the function:def post_copy_metacolums(self, cursor): logger.info('Executing post copy metadata queries') for query in self.metadata_queries: cursor.execute(query)
[ "\n Performs post-copy to fill metadata columns.\n " ]
Please provide a description of the function:def copy(self, cursor, f): logger.info("Inserting file: %s", f) cursor.execute( % (self.table, f, self._credentials(), self.jsonpath, self.copy_json_options, self.copy_options))
[ "\n Defines copying JSON from s3 into redshift.\n ", "\n COPY %s from '%s'\n CREDENTIALS '%s'\n JSON AS '%s' %s\n %s\n ;" ]
Please provide a description of the function:def output(self): # uses class name as a meta-table return RedshiftTarget( host=self.host, database=self.database, user=self.user, password=self.password, table=self.__class__.__name__, ...
[ "\n Returns a RedshiftTarget representing the inserted dataset.\n\n Normally you don't override this.\n " ]
Please provide a description of the function:def run(self): connection = self.output().connect() # kill any sessions other than ours and # internal Redshift sessions (rdsdb) query = ("select pg_terminate_backend(process) " "from STV_SESSIONS " "...
[ "\n Kill any open Redshift sessions for the given database.\n " ]
Please provide a description of the function: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
[]
Please provide a description of the function: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))
[]
Please provide a description of the function:def run(self): 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 10 52 60", file=outfile) print("data 3 195 1 52 60"...
[ "\n The execution of this task will write 4 lines of data on this task's target output.\n " ]
Please provide a description of the function:def copy(self, path, dest, raise_if_exists=False): 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_all_data()[dest] = contents
[ "\n Copies the contents of a single file path to dest\n " ]
Please provide a description of the function:def remove(self, path, recursive=True, skip_trash=True): if recursive: to_delete = [] for s in self.get_all_data().keys(): if s.startswith(path): to_delete.append(s) for s in to_delete: ...
[ "\n Removes the given mockfile. skip_trash doesn't have any meaning.\n " ]
Please provide a description of the function:def move(self, path, dest, raise_if_exists=False): 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()[dest] = conten...
[ "\n Moves a single file from path to dest\n " ]
Please provide a description of the function:def listdir(self, path): return [s for s in self.get_all_data().keys() if s.startswith(path)]
[ "\n listdir does a prefix match of self.get_all_data(), but doesn't yet support globs.\n " ]
Please provide a description of the function:def move(self, path, raise_if_exists=False): self.fs.move(self.path, path, raise_if_exists)
[ "\n Call MockFileSystem's move command\n " ]
Please provide a description of the function:def _recursively_freeze(value): if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list) or isinstance(value, tuple): return tuple(_recursively_freeze(v) for v ...
[ "\n Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.\n " ]
Please provide a description of the function:def _get_value_from_config(self, section, name): conf = configuration.get_config() try: value = conf.get(section, name) except (NoSectionError, NoOptionError, KeyError): return _no_value return self.parse(va...
[ "Loads the default from the config. Returns _no_value if it doesn't exist" ]
Please provide a description of the function:def _value_iterator(self, task_name, param_name): cp_parser = CmdlineParser.get_instance() if cp_parser: dest = self._parser_global_dest(param_name, task_name) found = getattr(cp_parser.known_args, dest, None) yiel...
[ "\n Yield the parameter values, with optional deprecation warning as second tuple value.\n\n The parameter value will be whatever non-_no_value that is yielded first.\n " ]
Please provide a description of the function:def _parse_list(self, xs): if not self._is_batchable(): raise NotImplementedError('No batch method found') elif not xs: raise ValueError('Empty parameter list passed to parse_list') else: return self._batch...
[ "\n Parse a list of values from the scheduler.\n\n Only possible if this is_batchable() is True. This will combine the list into a single\n parameter value using batch method. This should never need to be overridden.\n\n :param xs: list of values to parse and combine\n :return: th...
Please provide a description of the function:def parse(self, s): return datetime.datetime.strptime(s, self.date_format).date()
[ "\n Parses a date string formatted like ``YYYY-MM-DD``.\n " ]
Please provide a description of the function:def serialize(self, dt): if dt is None: return str(dt) return dt.strftime(self.date_format)
[ "\n Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.\n " ]
Please provide a description of the function:def _add_months(self, date, months): year = date.year + (date.month + months - 1) // 12 month = (date.month + months - 1) % 12 + 1 return datetime.date(year=year, month=month, day=1)
[ "\n Add ``months`` months to ``date``.\n\n Unfortunately we can't use timedeltas to add months because timedelta counts in days\n and there's no foolproof way to add N months in days without counting the number of\n days per month.\n " ]
Please provide a description of the function:def normalize(self, dt): if dt is None: return None dt = self._convert_to_dt(dt) dt = dt.replace(microsecond=0) # remove microseconds, to avoid float rounding issues. delta = (dt - self.start).total_seconds() gr...
[ "\n Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at\n :py:attr:`~_DatetimeParameterBase.start`.\n " ]
Please provide a description of the function:def parse(self, val): s = str(val).lower() if s == "true": return True elif s == "false": return False else: raise ValueError("cannot interpret '{}' as boolean".format(val))
[ "\n Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case.\n " ]
Please provide a description of the function:def parse(self, s): # TODO: can we use xml.utils.iso8601 or something similar? from luigi import date_interval as d for cls in [d.Year, d.Month, d.Week, d.Date, d.Custom]: i = cls.parse(s) if i: retur...
[ "\n Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.\n\n see :py:mod:`luigi.date_interval`\n for details on the parsing of DateIntervals.\n " ]
Please provide a description of the function:def parse(self, input): result = self._parseIso8601(input) if not result: result = self._parseSimple(input) if result is not None: return result else: raise ParameterException("Invalid time delta - ...
[ "\n Parses a time delta from the input.\n\n See :py:class:`TimeDeltaParameter` for details on supported formats.\n " ]
Please provide a description of the function:def serialize(self, x): weeks = x.days // 7 days = x.days % 7 hours = x.seconds // 3600 minutes = (x.seconds % 3600) // 60 seconds = (x.seconds % 3600) % 60 result = "{} w {} d {} h {} m {} s".format(weeks, days, hours...
[ "\n Converts datetime.timedelta to a string\n\n :param x: the value to serialize.\n " ]
Please provide a description of the function:def parse(self, x): # Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case. # A tuple string may come from a config file or from cli execution. # t = ((1, 2), (3, 4)) # t_str = '((1,2),(3,4))'...
[ "\n Parse an individual value from the input.\n\n :param str x: the value to parse.\n :return: the parsed value.\n " ]
Please provide a description of the function:def run(self): count = {} # NOTE: self.input() actually returns an element for the InputText.output() target for f in self.input(): # The input() method is a wrapper around requires() that returns Target objects for line in f.op...
[ "\n 1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`\n 2. write the count into the :py:meth:`~.WordCount.output` target\n " ]