text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def package( self, name, version, extras=None """ Retrieve the release information. This is a heavy task which takes time. We have to download a package to get th...
try: index = self._packages.index( poetry.packages.Package(name, version, version) ) return self._packages[index] except ValueError: if extras is None: extras = [] release_info = self.get_release_info(name, ve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = logging.WARNING if output.is_debug(): level = logging.DEBUG elif output.is_very_verbose(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) ) if not file.exists(): raise RuntimeError('"{0}" does not exist.'.format(file.name)) data = self.post_data(f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_packages( self, name, # type: str constraint=None, # type: Union[VersionConstraint, str, None] extras=None, # type: Union[list, None] allow_prereleases=F...
if constraint is None: constraint = "*" if not isinstance(constraint, VersionConstraint): constraint = parse_constraint(constraint) if isinstance(constraint, VersionRange): if ( constraint.max is not None and constraint.max.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_package_info(self, name): # type: (str) -> dict """ Return the package information given its name. The information is returned from the cache if it exist...
if self._disable_cache: return self._get_package_info(name) return self._cache.store("packages").remember_forever( name, lambda: self._get_package_info(name) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_release_info(self, name, version): # type: (str, str) -> dict """ Return the release information given a package name and a version. The information is r...
if self._disable_cache: return self._get_release_info(name, version) cached = self._cache.remember_forever( "{}:{}".format(name, version), lambda: self._get_release_info(name, version) ) cache_version = cached.get("_cache_version", "0.0.0") if parse_con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]): fp.write(ep.replace(" ", "") + "\n") fp.write("\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock(self): # type: () -> Installer """ Prepare the installer for locking only. """
self.update() self.execute_operations(False) self._lock = True return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execute(self, operation): # type: (Operation) -> None """ Execute a given operation. """
method = operation.job_type getattr(self, "_execute_{}".format(method))(operation)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] for k, v in self._package.extras.items()} else: extras = self._locker.lock_data.get("extras", {}) extra_packages = [] for extra_name, packages in extras.items(): if extra_name not in self._extras: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): yield self._build_results(jobs, job)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() == status.lower(): yield self._build_results(jobs, job)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, old_path, new_path, raise_if_exists=False): """ Move file atomically. If source and destination are located on different filesystems, atomicity is...
if raise_if_exists and os.path.exists(new_path): raise FileAlreadyExists('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.mkdir(d) try: os.rename(old_path, new_path) except OSError as err:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(parentfolder) except OSError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() else: errors = '' return errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.readlines() else: outputs = '' return outputs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.output().path) args += ["bsub", "-q", self.queue_flag] args += ["-n", str(self.n_cpu_flag)] args += ["-M", str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, address=address, unix_socket=unix_socket, ) # prune work DAG every 60 seconds pruner = tornado.ioloop.PeriodicC...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_fields) # remove tabs fields = re.sp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.%d" % (self.output().path, i), 'r') as f: header = f.readline() if i == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(), headers=self._get_login_headers(), data=self._get_login_xml()) response.raise_for_status()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
params = {'q': query} response = requests.get(self._get_norm_query_url(), headers=self._get_rest_headers(), params=params, **kwargs) if response.status_code != requests.codes.ok: raise Ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs): """ Retrieves more results from a query that returned more results than the bat...
if identifier_is_url: # Don't use `self.base_url` here because the full URI is provided url = (u'https://{instance}{next_record_url}' .format(instance=self.hostname, next_record_url=next_records_identifier)) else: url = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_job_details(self, job_id): """ Gets all details for existing job :return: job info as xml """
response = requests.get(self._get_job_details_url(job_id)) response.raise_for_status() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
response = requests.post(self._get_abort_job_url(job_id), headers=self._get_abort_job_headers(), data=self._get_abort_job_xml()) response.raise_for_status() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 pul...
if not job_id or not self.has_active_session(): raise Exception("Can not create a batch without a valid job_id and an active session.") headers = self._get_create_batch_content_headers(file_type) headers['Content-Length'] = str(len(data)) response = requests.post(self._get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_batch_result_ids(self, job_id, batch_id): """ Get result IDs of a batch that has completed processing. """
response = requests.get(self._get_batch_results_url(job_id, batch_id), headers=self._get_batch_info_headers()) response.raise_for_status() root = ET.fromstring(response.text) result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Return...
if qstat_out.strip() == '': return 'u' lines = qstat_out.split('\n') # skip past header while not lines.pop(0).startswith('---'): pass for line in lines: if line: job, prior, name, user, state = line.strip().split()[0:5] if int(job) == int(job_id): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
today = datetime.date.today() with self.output().open('w') as output: for i in range(5): output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i, 'date': str(today)})) output.write('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 == "webhdfs": client_cache.client = hdfs_webhdfs_client.WebHdfsClient() elif configured_client == "snakebite": client_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email_ses(sender, subject, message, recipients, image_png): """ Sends notification through AWS SES. Does not handle access keys. Use either 1/ configura...
from boto3 import client as boto3_client client = boto3_client('ses') msg_root = generate_email(sender, subject, message, recipients, image_png) response = client.send_raw_email(Source=sender, Destinations=recipients, RawMessag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email_sns(sender, subject, message, topic_ARN, image_png): """ Sends notification through AWS SNS. Takes Topic ARN from recipients. Does not handle acce...
from boto3 import resource as boto3_resource sns = boto3_resource('sns') topic = sns.Topic(topic_ARN[0]) # Subject is max 100 chars if len(subject) > 100: subject = subject[0:48] + '...' + subject[-49:] response = topic.publish(Subject=subject, Message=message) logger.debug(("Me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_email(subject, message, sender, recipients, image_png=None): """ Decides whether to send notification. Notification is cancelled if there are no recipie...
notifiers = { 'ses': send_email_ses, 'sendgrid': send_email_sendgrid, 'smtp': send_email_smtp, 'sns': send_email_sns, } subject = _prefix(subject) if not recipients or recipients == (None,): return if _email_disabled_reason(): logger.info("Not sendi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=sender, recipients=recipients )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 headli...
if formatted_exception: formatted_exception = wrap_traceback(formatted_exception) else: formatted_exception = "" if email().format == 'html': msg_template = textwrap.dedent(''' <html> <body> <h2>{headline}</h2> <table style="border-top: 1px solid b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: '): return False else: raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touchz(self, path): """ To touchz using the web hdfs "write" cmd. """
self.client.write(path, data='', overwrite=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 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_when_reading, **self.azure_blob_options)) else: return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.join(self.temp_dir, str(self.unique.value), md5_hash)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 if self.isdir(path): return True logger.debug('Path %s does not exi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 pur...
(bucket, key) = self._path_to_bucket_and_key(s3_path) obj = self.s3.Object(bucket, key) contents = obj.get()['Body'].read() return contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 e...
content = self.get_as_bytes(s3_path) return content.decode(encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_MARKER_SUFFIX_0, S3_DIRECTORY_MARKER_SUFFIX_1): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 pass...
self._connect() if self.sftp: exists = self._sftp_exists(path, mtime) else: exists = self._ftp_exists(path, mtime) self._close() return exists
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) try: ftp.cwd(path) except ftplib.all_errors: # this is a file, we will just delete the file ftp.delete(path) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 specifi...
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_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_collection(self): """ Return targeted mongo collection to query on """
db_mongo = self._mongo_client[self._index] return db_mongo[self._collection]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, value): """ Write value to the target """
self.get_collection().update_one( {'_id': self._document_id}, {'$set': {self._path: value}}, upsert=True )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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[self._field] for doc in cursor}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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} ) return set(self._document_ids) - {doc['_id'] for doc in cursor}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 logging.config.dictConfig(logging_config) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(cls, opts=type('opts', (), { 'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG' })): """Setup logging via CLI params a...
logger = logging.getLogger('luigi') if cls._configured: logger.info('logging already configured') return False cls._configured = True if cls.config.getboolean('core', 'no_configure_logging', False): logger.info('logging disabled in settings') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if opts.background: logging.getLogger().setLevel(logging.INFO) return True if opts.logdir: logging.basicConfig( level=logging.INFO, format=cls._log_format, filename=os.path.join(opts.logdir, "luigi-server.log")) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_prefix = '' obj_prefix_len = len(obj_prefix) for it in self._list_iter(bucket, obj_prefix): yield self._add_path_delimiter(path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_wildcard(self, wildcard_path): """Yields full object URIs matching the given wildcard. Currently only the '*' wildcard after the last path delimiter is ...
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(wildcard_parts) == 2, "Only one '*' wildcard is supported" for it in self.listdir(path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, path, chunksize=None, chunk_callback=lambda _: False): """Downloads the object contents to local file system. Optionally stops after the first...
chunksize = chunksize or self.chunksize bucket, obj = self._path_to_bucket_and_key(path) with tempfile.NamedTemporaryFile(delete=False) as fp: # We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879 return_fp = _DeleteOnClo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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((task, is_complete))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 dependen...
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().Queue() pool = multiprocessing.Pool(processes=processes if processes > 0 else None) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 {}'.format(task_id, p.exitcode) p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg) elif p.timeout_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. F...
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_scheduled > 0 elif self._config.count_uniques: return get_work_response.n_unique...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: while len(self._running_tasks) >= self.worker_processes > 0: logger.debug('%d running tasks, w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 to tasks if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]: logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 == task_name) for (k, v) in six.iteritems(task_params): alias = sqlalchemy.orm.aliased(TaskParameter) query = query.join(alias).filter(alias.n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_authenticate_kwargs(oauth_credentials=None, http_=None): """Returns a dictionary with keyword arguments for use with discovery Prioritizes oauth_credenti...
if oauth_credentials: authenticate_kwargs = { "credentials": oauth_credentials } elif http_: authenticate_kwargs = { "http": http_ } else: # neither http_ or credentials provided try: # try default credentials c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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( id=self.aws_account_id, role=self.aws_arn_role_name ) elif self.aws_access_key_id and self.aws_secret_access_key: return 'a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ If the target table doesn't exist, self.create_table will be called to attempt to create the table. """
if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path() output = self.output() connection = output.connect() cursor = connection.cursor() self.init_copy(connection) self.copy(cursor, path) self.post_copy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def does_schema_exist(self, connection): """ Determine whether the schema already exists. """
if '.' in self.table: query = ("select 1 as schema_exists " "from pg_namespace " "where nspname = lower(%s) limit 1") else: return True cursor = connection.cursor() try: schema = self.table.split('.')[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def does_table_exist(self, connection): """ Determine whether the table already exists. """
if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and table_name = lower(%s) limit 1") else: query = ("select 1 as table_exists " "from pg_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_copy(self, connection): """ Perform pre-copy sql - such as creating table, truncating, or removing data older than x. """
if not self.does_schema_exist(connection): logger.info("Creating schema for %s", self.table) self.create_schema(connection) if not self.does_table_exist(connection): logger.info("Creating table %s", self.table) self.create_table(connection) if s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_copy_metacolums(self, cursor): """ Performs post-copy to fill metadata columns. """
logger.info('Executing post copy metadata queries') for query in self.metadata_queries: cursor.execute(query)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output(self): """ Returns a RedshiftTarget representing the inserted dataset. Normally you don't override this. """
# uses class name as a meta-table return RedshiftTarget( host=self.host, database=self.database, user=self.user, password=self.password, table=self.__class__.__name__, update_id=self.update_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Kill any open Redshift sessions for the given database. """
connection = self.output().connect() # kill any sessions other than ours and # internal Redshift sessions (rdsdb) query = ("select pg_terminate_backend(process) " "from STV_SESSIONS " "where db_name=%s " "and user_name != 'rdsdb' " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ The execution of this task will write 4 lines of data on this task's target output. """
with self.output().open('w') as outfile: print("data 0 200 10 50 60", file=outfile) print("data 1 190 9 52 60", file=outfile) print("data 2 200 10 52 60", file=outfile) print("data 3 195 1 52 60", file=outfile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, path, dest, raise_if_exists=False): """ Copies the contents of a single file path to dest """
if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data()[path] self.get_all_data()[dest] = contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, path, recursive=True, skip_trash=True): """ Removes the given mockfile. skip_trash doesn't have any meaning. """
if recursive: to_delete = [] for s in self.get_all_data().keys(): if s.startswith(path): to_delete.append(s) for s in to_delete: self.get_all_data().pop(s) else: self.get_all_data().pop(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, path, dest, raise_if_exists=False): """ Moves a single file from path to dest """
if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data().pop(path) self.get_all_data()[dest] = contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, path, raise_if_exists=False): """ Call MockFileSystem's move command """
self.fs.move(self.path, path, raise_if_exists)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recursively_freeze(value): """ Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. """
if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list) or isinstance(value, tuple): return tuple(_recursively_freeze(v) for v in value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_value_from_config(self, section, name): """Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config() try: value = conf.get(section, name) except (NoSectionError, NoOptionError, KeyError): return _no_value return self.parse(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _value_iterator(self, task_name, param_name): """ Yield the parameter values, with optional deprecation warning as second tuple value. The parameter value wi...
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) yield (self._parse_or_no_value(found), None) yield (self._get_value_from_config(task_name, param_na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_list(self, xs): """ Parse a list of values from the scheduler. Only possible if this is_batchable() is True. This will combine the list into a single ...
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_method(map(self.parse, xs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, s): """ Parses a date string formatted like ``YYYY-MM-DD``. """
return datetime.datetime.strptime(s, self.date_format).date()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_months(self, date, months): """ Add ``months`` months to ``date``. Unfortunately we can't use timedeltas to add months because timedelta counts in days ...
year = date.year + (date.month + months - 1) // 12 month = (date.month + months - 1) % 12 + 1 return datetime.date(year=year, month=month, day=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, val): """ Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case. """
s = str(val).lower() if s == "true": return True elif s == "false": return False else: raise ValueError("cannot interpret '{}' as boolean".format(val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, input): """ Parses a time delta from the input. See :py:class:`TimeDeltaParameter` for details on supported formats. """
result = self._parseIso8601(input) if not result: result = self._parseSimple(input) if result is not None: return result else: raise ParameterException("Invalid time delta - could not parse %s" % input)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, x): """ Converts datetime.timedelta to a string :param x: the value to serialize. """
weeks = x.days // 7 days = x.days % 7 hours = x.seconds // 3600 minutes = (x.seconds % 3600) // 60 seconds = (x.seconds % 3600) % 60 result = "{} w {} d {} h {} m {} s".format(weeks, days, hours, minutes, seconds) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, x): """ Parse an individual value from the input. :param str x: the value to parse. :return: the parsed value. """
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case. # A tuple string may come from a config file or from cli execution. # t = ((1, 2), (3, 4)) # t_str = '((1,2),(3,4))' # t_json_str = json.dumps(t) # t_json_str == '[[1, 2], [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_packages_archive(packages, filename): """ Create a tar archive which will contain the files for the packages listed in packages. """
import tarfile tar = tarfile.open(filename, "w") def add(src, dst): logger.debug('adding to tar: %s -> %s', src, dst) tar.add(src, dst) def add_files_for_package(sub_package_path, root_package_path, root_package_name): for root, dirs, files in os.walk(sub_package_path): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(sequence): """ A simple generator which flattens a sequence. Only one level is flattened. .. code-block:: python (1, (2, 3), 4) -> (1, 2, 3, 4) """
for item in sequence: if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes): for i in item: yield i else: yield item