text
stringlengths
81
112k
Given a package name and optional version, returns the latest Package that matches def find_best_candidate( self, package_name, # type: str target_package_version=None, # type: Union[str, None] allow_prereleases=False, # type: bool ): # type: (...) -> Union[Package, boo...
Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters). def clean_link(self, url): """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20...
Retrieve the release information. This is a heavy task which takes time. We have to download a package to get the dependencies. We also need to download every file matching this release to get the various hashes. Note that, this will be cached so the subsequent operations ...
Initialize command. def run(self, i, o): # type: () -> int """ Initialize command. """ self.input = i self.output = PoetryStyle(i, o) for logger in self._loggers: self.register_logger(logging.getLogger(logger)) return super(BaseCommand, self).run(i...
Register a new logger. def register_logger(self, logger): """ Register a new logger. """ handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = log...
Register a package to a repository. def _register(self, session, url): """ Register a package to a repository. """ dist = self._poetry.file.parent / "dist" file = dist / "{}-{}.tar.gz".format( self._package.name, normalize_version(self._package.version.text) ...
Find packages on the remote server. def find_packages( self, name, # type: str constraint=None, # type: Union[VersionConstraint, str, None] extras=None, # type: Union[list, None] allow_prereleases=False, # type: bool ): # type: (...) -> List[Package] """ ...
Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server. def get_package_info(self, name): # type: (str) -> dict """ Return the package information given its name. The information is returned f...
Return the release information given a package name and a version. The information is returned from the cache if it exists or retrieved from the remote server. def get_release_info(self, name, version): # type: (str, str) -> dict """ Return the release information given a package name...
Build a wheel in the dist/ directory, and optionally upload it. def make(cls, poetry, env, io): """Build a wheel in the dist/ directory, and optionally upload it.""" cls.make_in(poetry, env, io)
Write entry_points.txt. def _write_entry_points(self, fp): """ Write entry_points.txt. """ entry_points = self.convert_entry_points() for group_name in sorted(entry_points): fp.write("[{}]\n".format(group_name)) for ep in sorted(entry_points[group_name])...
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. def _get_win_folder_from_registry(csidl_name): """ This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct an...
Prepare the installer for locking only. def lock(self): # type: () -> Installer """ Prepare the installer for locking only. """ self.update() self.execute_operations(False) self._lock = True return self
Execute a given operation. def _execute(self, operation): # type: (Operation) -> None """ Execute a given operation. """ method = operation.job_type getattr(self, "_execute_{}".format(method))(operation)
Returns all packages required by extras. Maybe we just let the solver handle it? def _get_extra_packages(self, repo): """ Returns all packages required by extras. Maybe we just let the solver handle it? """ if self._update: extras = {k: [d.name for d in v] ...
Returns the json representation of the dep graph def _fetch_json(self): """Returns the json representation of the dep graph""" print("Fetching from url: " + self.graph_url) resp = urlopen(self.graph_url).read() return json.loads(resp.decode('utf-8'))
Searches for jobs matching the given ``job_name_prefix``. def prefix_search(self, job_name_prefix): """Searches for jobs matching the given ``job_name_prefix``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: if job.startswith(job_name_prefix): ...
Searches for jobs matching the given ``status``. def status_search(self, status): """Searches for jobs matching the given ``status``.""" json = self._fetch_json() jobs = json['response'] for job in jobs: job_info = jobs[job] if job_info['status'].lower() == statu...
Move file atomically. If source and destination are located on different filesystems, atomicity is approximated but cannot be guaranteed. def move(self, old_path, new_path, raise_if_exists=False): """ Move file atomically. If source and destination are located on different files...
Rename ``path`` to ``dest``, but don't move it into the ``dest`` folder (if it is a folder). This method is just a wrapper around the ``move`` method of LocalTarget. def rename_dont_move(self, path, dest): """ Rename ``path`` to ``dest``, but don't move it into the ``dest`` fold...
Create all parent folders if they do not exist. def makedirs(self): """ Create all parent folders if they do not exist. """ normpath = os.path.normpath(self.path) parentfolder = os.path.dirname(normpath) if parentfolder: try: os.makedirs(paren...
Tracking is done by requesting each job and then searching for whether the job has one of the following states: - "RUN", - "PEND", - "SSUSP", - "EXIT" based on the LSF documentation def track_job(job_id): """ Tracking is done by requesting each job and then searching for whether the job...
Read in the error file from bsub def fetch_task_failures(self): """ Read in the error file from bsub """ error_file = os.path.join(self.tmp_dir, "job.err") if os.path.isfile(error_file): with open(error_file, "r") as f_err: errors = f_err.readlines() ...
Read in the output file def fetch_task_output(self): """ Read in the output file """ # Read in the output file if os.path.isfile(os.path.join(self.tmp_dir, "job.out")): with open(os.path.join(self.tmp_dir, "job.out"), "r") as f_out: outputs = f_out.re...
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.sp...
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`: the text, * `rating`: the...
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`) def output(self): """ Returns the target output for this task. ...
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:%...
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, ...
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_fiel...
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['recor...
Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a dictionary def _traverse_results(value, fields, row, path): """ Helper method for parse_results(). Traverses through ordered dict and recursively calls itself when encountering a diction...
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, res...
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 i...
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'" def query(self, query, **kwargs): """ Return the result of a Salesforce SOQL query as...
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 the Id of the next Salesforce object in the result, or a URL to th...
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 ...
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...
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 obj: Parent SF object :param external_id_field_name: Optional. def create_operation_job(self, operation, obj,...
Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml 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...
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 def abort_job(self, job_id): """ ...
Closes job :param job_id: job_id as returned by 'create_operation_job(...)' :return: close response as xml 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...
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 single batch upload size limit (10MB) and is done to ensure ...
Blocks until @batch_id is completed or failed. :param job_id: :param batch_id: :param sleep_time_seconds: :param max_wait_time_seconds: 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 ...
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_i...
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 used in 'get_batch_result(...)' def get_batch_result_ids(self, job_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: def get_batch_result(self, job_id, batch_id, result_id): """ Gets result back from Salesforce as whatever type was originally se...
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. def _parse_qstat_state(qstat_out, job_id): """Parse "state" column from `qstat` output for given job_id Returns state for the *fi...
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( ...
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_na...
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. def run(self): """ Writes data in JSON format into ...
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_con...
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.fo...
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. def send_email_ses(sender, subject, message, recipients, image_png): """ Sends notification ...
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/configuration.html. def send_email_sns(sender, subject, message, topic_ARN, image_png):...
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'. def send_email(subject, message, sender, recipients, image_png=None): """ Decides whether to send notifi...
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_emai...
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 string showing traceback :return: message body def format_task_error(headline, tas...
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)....
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') pe...
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 :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' * :class:`.AtomicAzureBlobFil...
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('...
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`) def requires(self): """ This task's dependencies: * :py:class:`~.Aggregate...
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() ...
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: ...
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): ...
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 ...
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 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...
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 argumen...
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...
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.downloa...
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 :retu...
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 i...
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...
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...
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 ot...
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:...
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() ...
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,...
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.make...
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) ...
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....
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': {'_...
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} ) r...
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 filt...
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} },...
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 (TypeErr...
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...
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...
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(loggi...
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 P...
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)...
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 [h...
@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 ...