Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def task_list(self, status='', upstream_status='', limit=True, search=None, max_shown_tasks=None, **kwargs): if not search: count_limit = max_shown_tasks or self._config.max_shown_tasks pre_count = self._state.get_ac...
[ "\n Query for a subset of tasks by status.\n " ]
Please provide a description of the function:def resource_list(self): self.prune() resources = [ dict( name=resource, num_total=r_dict['total'], num_used=r_dict['used'] ) for resource, r_dict in six.iteritems(self.resources...
[ "\n Resources usage info and their consumers (tasks).\n " ]
Please provide a description of the function:def resources(self): ''' get total resources and available ones ''' used_resources = self._used_resources() ret = collections.defaultdict(dict) for resource, total in six.iteritems(self._resources): ret[resource]['total'] = total ...
[]
Please provide a description of the function:def task_search(self, task_str, **kwargs): self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -1: serialized = self._serialize_task(task.id,...
[ "\n Query for a subset of tasks by task_id.\n\n :param task_str:\n :return:\n " ]
Please provide a description of the function:def exists(self): path = self.path if '*' in path or '?' in path or '[' in path or '{' in path: logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; " "override exists() ...
[ "\n Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise.\n\n This method is implemented by using :py:attr:`fs`.\n " ]
Please provide a description of the function:def temporary_path(self): num = random.randrange(0, 1e10) slashless_path = self.path.rstrip('/').rstrip("\\") _temp_path = '{}-luigi-tmp-{:010}{}'.format( slashless_path, num, self._trailing_slash()) ...
[ "\n A context manager that enables a reasonably short, general and\n magic-less way to solve the :ref:`AtomicWrites`.\n\n * On *entering*, it will create the parent directories so the\n temporary_path is writeable right away.\n This step uses :py:meth:`FileSystem.mkdir`.\n ...
Please provide a description of the function:def marker_index_document_id(self): params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id) return hashlib.sha1(params.encode('utf-8')).hexdigest()
[ "\n Generate an id for the indicator document.\n " ]
Please provide a description of the function:def touch(self): self.create_marker_index() self.es.index(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id(), body={ 'update_id': self.update_id, ...
[ "\n Mark this update as complete.\n\n The document id would be sufficent but,\n for documentation,\n we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well.\n " ]
Please provide a description of the function:def exists(self): try: self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id()) return True except elasticsearch.NotFoundError: logger.debug('Marker document not found...
[ "\n Test, if this task has been run.\n " ]
Please provide a description of the function:def create_marker_index(self): if not self.es.indices.exists(index=self.marker_index): self.es.indices.create(index=self.marker_index)
[ "\n Create the index that will keep track of the tasks if necessary.\n " ]
Please provide a description of the function:def ensure_hist_size(self): if self.marker_index_hist_size == 0: return result = self.es.search(index=self.marker_index, doc_type=self.marker_doc_type, body={'query': { ...
[ "\n Shrink the history of updates for\n a `index/doc_type` combination down to `self.marker_index_hist_size`.\n " ]
Please provide a description of the function:def _docs(self): iterdocs = iter(self.docs()) first = next(iterdocs) needs_parsing = False if isinstance(first, six.string_types): needs_parsing = True elif isinstance(first, dict): pass else: ...
[ "\n Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`,\n add those attributes here, if necessary.\n " ]
Please provide a description of the function:def create_index(self): es = self._init_connection() if not es.indices.exists(index=self.index): es.indices.create(index=self.index, body=self.settings)
[ "\n Override to provide code for creating the target index.\n\n By default it will be created without any special settings or mappings.\n " ]
Please provide a description of the function:def delete_index(self): es = self._init_connection() if es.indices.exists(index=self.index): es.indices.delete(index=self.index)
[ "\n Delete the index, if it exists.\n " ]
Please provide a description of the function:def output(self): return ElasticsearchTarget( host=self.host, port=self.port, http_auth=self.http_auth, index=self.index, doc_type=self.doc_type, update_id=self.update_id(), ...
[ "\n Returns a ElasticsearchTarget representing the inserted dataset.\n\n Normally you don't override this.\n " ]
Please provide a description of the function:def run(self): if self.purge_existing_index: self.delete_index() self.create_index() es = self._init_connection() if self.mapping: es.indices.put_mapping(index=self.index, doc_type=self.doc_type, ...
[ "\n Run task, namely:\n\n * purge existing index, if requested (`purge_existing_index`),\n * create the index, if missing,\n * apply mappings, if given,\n * set refresh interval to -1 (disable) for performance reasons,\n * bulk index in batches of size `chunk_size` (2000),\...
Please provide a description of the function:def _get_with_default(self, method, section, option, default, expected_type=None, **kwargs): try: try: # Underscore-style is the recommended configuration style option = option.replace('-', '_') ret...
[ "\n Gets the value of the section/option using method.\n\n Returns default if value is not found.\n\n Raises an exception if the default value is not None and doesn't match the expected_type.\n " ]
Please provide a description of the function:def __track_job(self): while not self.__verify_job_has_started(): time.sleep(self.__POLL_TIME) self.__logger.debug("Waiting for Kubernetes job " + self.uu_name + " to start") self.__print_kubectl_hints() status = self...
[ "Poll job status while active" ]
Please provide a description of the function:def __verify_job_has_started(self): # Verify that the job started self.__get_job() # Verify that the pod started pods = self.__get_pods() assert len(pods) > 0, "No pod scheduled by " + self.uu_name for pod in pods: ...
[ "Asserts that the job has successfully started" ]
Please provide a description of the function:def __get_job_status(self): # Figure out status and return it job = self.__get_job() if "succeeded" in job.obj["status"] and job.obj["status"]["succeeded"] > 0: job.scale(replicas=0) if self.print_pod_logs_on_exit: ...
[ "Return the Kubernetes job status" ]
Please provide a description of the function:def engine(self): pid = os.getpid() conn = SQLAlchemyTarget._engine_dict.get(self.connection_string) if not conn or conn.pid != pid: # create and reset connection engine = sqlalchemy.create_engine( self...
[ "\n Return an engine instance, creating it if it doesn't exist.\n\n Recreate the engine connection if it wasn't originally created\n by the current process.\n " ]
Please provide a description of the function:def touch(self): if self.marker_table_bound is None: self.create_marker_table() table = self.marker_table_bound id_exists = self.exists() with self.engine.begin() as conn: if not id_exists: ins...
[ "\n Mark this update as complete.\n " ]
Please provide a description of the function:def create_marker_table(self): if self.marker_table is None: self.marker_table = luigi.configuration.get_config().get('sqlalchemy', 'marker-table', 'table_updates') engine = self.engine with engine.begin() as con: me...
[ "\n Create marker table if it doesn't exist.\n\n Using a separate connection since the transaction might have to be reset.\n " ]
Please provide a description of the function:def create_table(self, engine): def construct_sqla_columns(columns): retval = [sqlalchemy.Column(*c[0], **c[1]) for c in columns] return retval needs_setup = (len(self.columns) == 0) or (False in [len(c) == 2 for c in self.co...
[ "\n Override to provide code for creating the target table.\n\n By default it will be created using types specified in columns.\n If the table exists, then it binds to the existing table.\n\n If overridden, use the provided connection object for setting up the table in order to\n ...
Please provide a description of the function:def copy(self, conn, ins_rows, table_bound): bound_cols = dict((c, sqlalchemy.bindparam("_" + c.key)) for c in table_bound.columns) ins = table_bound.insert().values(bound_cols) conn.execute(ins, ins_rows)
[ "\n This method does the actual insertion of the rows of data given by ins_rows into the\n database. A task that needs row updates instead of insertions should overload this method.\n :param conn: The sqlalchemy connection object\n :param ins_rows: The dictionary of rows with the keys in...
Please provide a description of the function:def main(args=sys.argv): try: # Set up logging. logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a directory that exists" do_work_on_compute_n...
[ "Run the work() method from the class instance in the file \"job-instance.pickle\".\n " ]
Please provide a description of the function:def rename(self, path, raise_if_exists=False): if isinstance(path, HdfsTarget): path = path.path if raise_if_exists and self.fs.exists(path): raise RuntimeError('Destination exists: %s' % path) self.fs.rename(self.path...
[ "\n Does not change self.path.\n\n Unlike ``move_dir()``, ``rename()`` might cause nested directories.\n See spotify/luigi#522\n " ]
Please provide a description of the function:def move(self, path, raise_if_exists=False): self.rename(path, raise_if_exists=raise_if_exists)
[ "\n Alias for ``rename()``\n " ]
Please provide a description of the function:def is_writable(self): if "/" in self.path: # example path: /log/ap/2013-01-17/00 parts = self.path.split("/") # start with the full path and then up the tree until we can check length = len(parts) ...
[ "\n Currently only works with hadoopcli\n " ]
Please provide a description of the function:def _partition_tasks(worker): task_history = worker._add_task_history pending_tasks = {task for(task, status, ext) in task_history if status == 'PENDING'} set_tasks = {} set_tasks["completed"] = {task for (task, status, ext) in task_history if status == ...
[ "\n Takes a worker and sorts out tasks based on their status.\n Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker\n " ]
Please provide a description of the function:def _populate_unknown_statuses(set_tasks): visited = set() for task in set_tasks["still_pending_not_ext"]: _depth_first_search(set_tasks, task, visited)
[ "\n Add the \"upstream_*\" and \"not_run\" statuses my mutating set_tasks.\n " ]
Please provide a description of the function:def _depth_first_search(set_tasks, current_task, visited): visited.add(current_task) if current_task in set_tasks["still_pending_not_ext"]: upstream_failure = False upstream_missing_dependency = False upstream_run_by_other_worker = False ...
[ "\n This dfs checks why tasks are still pending.\n " ]
Please provide a description of the function:def _get_str(task_dict, extra_indent): summary_length = execution_summary().summary_length lines = [] task_names = sorted(task_dict.keys()) for task_family in task_names: tasks = task_dict[task_family] tasks = sorted(tasks, key=lambda x:...
[ "\n This returns a string for each status\n ", "\n This is to make sure that there is no really long task in the output\n " ]
Please provide a description of the function:def _ranging_attributes(attributes, param_class): next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes} in_first = attributes.difference(next_attributes) in_second = next_attributes.difference(attributes) if len(in_fi...
[ "\n Checks if there is a continuous range\n " ]
Please provide a description of the function:def _get_comments(group_tasks): comments = {} for status, human in _COMMENTS: num_tasks = _get_number_of_tasks_for(status, group_tasks) if num_tasks: space = " " if status in _PENDING_SUB_STATUSES else "" comments[statu...
[ "\n Get the human readable comments and quantities for the task types.\n " ]
Please provide a description of the function:def _get_run_by_other_worker(worker): task_sets = _get_external_workers(worker).values() return functools.reduce(lambda a, b: a | b, task_sets, set())
[ "\n This returns a set of the tasks that are being run by other worker\n " ]
Please provide a description of the function:def _get_external_workers(worker): worker_that_blocked_task = collections.defaultdict(set) get_work_response_history = worker._get_work_response_history for get_work_response in get_work_response_history: if get_work_response['task_id'] is None: ...
[ "\n This returns a dict with a set of tasks for all of the other workers\n " ]
Please provide a description of the function:def _group_tasks_by_name_and_status(task_dict): group_status = {} for task in task_dict: if task.task_family not in group_status: group_status[task.task_family] = [] group_status[task.task_family].append(task) return group_status
[ "\n Takes a dictionary with sets of tasks grouped by their status and\n returns a dictionary with dictionaries with an array of tasks grouped by\n their status and task name\n " ]
Please provide a description of the function:def _tasks_status(set_tasks): if set_tasks["ever_failed"]: if not set_tasks["failed"]: return LuigiStatusCode.SUCCESS_WITH_RETRY else: if set_tasks["scheduling_error"]: return LuigiStatusCode.FAILED_AND_SCHEDUL...
[ "\n Given a grouped set of tasks, returns a LuigiStatusCode\n " ]
Please provide a description of the function:def task_id_str(task_family, params): # task_id is a concatenation of task family, the first values of the first 3 parameters # sorted by parameter name and a md5hash of the family/parameters as a cananocalised json. param_str = json.dumps(params, separators...
[ "\n Returns a canonical string used to identify a particular task\n\n :param task_family: The task family (class name) of the task\n :param params: a dict mapping parameter names to their serialized values\n :return: A unique, shortened identifier corresponding to the family and params\n " ]
Please provide a description of the function:def externalize(taskclass_or_taskobject): # Seems like with python < 3.3 copy.copy can't copy classes # and objects with specified metaclass http://bugs.python.org/issue11480 compatible_copy = copy.copy if six.PY3 else copy.deepcopy copied_value = compat...
[ "\n Returns an externalized version of a Task. You may both pass an\n instantiated task object or a task class. Some examples:\n\n .. code-block:: python\n\n class RequiringTask(luigi.Task):\n def requires(self):\n task_object = self.clone(MyTask)\n return ex...
Please provide a description of the function:def getpaths(struct): if isinstance(struct, Task): return struct.output() elif isinstance(struct, dict): return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct)) elif isinstance(struct, (list, tuple)): return struct...
[ "\n Maps all Tasks in a structured data object to their .output().\n " ]
Please provide a description of the function:def flatten(struct): if struct is None: return [] flat = [] if isinstance(struct, dict): for _, result in six.iteritems(struct): flat += flatten(result) return flat if isinstance(struct, six.string_types): retu...
[ "\n Creates a flat list of all all items in structured output (dicts, lists, items):\n\n .. code-block:: python\n\n >>> sorted(flatten({'a': 'foo', 'b': 'bar'}))\n ['bar', 'foo']\n >>> sorted(flatten(['foo', ['bar', 'troll']]))\n ['bar', 'foo', 'troll']\n >>> flatten('foo')\...
Please provide a description of the function:def flatten_output(task): r = flatten(task.output()) if not r: for dep in flatten(task.requires()): r += flatten_output(dep) return r
[ "\n Lists all output targets by recursively walking output-less (wrapper) tasks.\n\n FIXME order consistently.\n " ]
Please provide a description of the function:def get_bite(self): config = hdfs_config.hdfs() if self.pid != os.getpid() or not self._bite: client_kwargs = dict(filter( lambda k_v: k_v[1] is not None and k_v[1] != '', six.iteritems({ 'hadoop_versio...
[ "\n If Luigi has forked, we have a different PID, and need to reconnect.\n ", "\n This is fully backwards compatible with the vanilla Client and can be used for a non HA cluster as well.\n This client tries to read ``${HADOOP_PATH}/conf/hdfs-site.xml`` to get the addres...
Please provide a description of the function:def move(self, path, dest): parts = dest.rstrip('/').split('/') if len(parts) > 1: dir_path = '/'.join(parts[0:-1]) if not self.exists(dir_path): self.mkdir(dir_path, parents=True) return list(self.get_...
[ "\n Use snakebite.rename, if available.\n\n :param path: source file(s)\n :type path: either a string or sequence of strings\n :param dest: destination file (single input) or directory (multiple)\n :type dest: string\n :return: list of renamed items\n " ]
Please provide a description of the function:def rename_dont_move(self, path, dest): from snakebite.errors import FileAlreadyExistsException try: self.get_bite().rename2(path, dest, overwriteDest=False) except FileAlreadyExistsException: # Unfortunately python2 d...
[ "\n Use snakebite.rename_dont_move, if available.\n\n :param path: source path (single input)\n :type path: string\n :param dest: destination path\n :type dest: string\n :return: True if succeeded\n :raises: snakebite.errors.FileAlreadyExistsException\n " ]
Please provide a description of the function:def remove(self, path, recursive=True, skip_trash=False): return list(self.get_bite().delete(self.list_path(path), recurse=recursive))
[ "\n Use snakebite.delete, if available.\n\n :param path: delete-able file(s) or directory(ies)\n :type path: either a string or a sequence of strings\n :param recursive: delete directories trees like \\\\*nix: rm -r\n :type recursive: boolean, default is True\n :param skip_...
Please provide a description of the function:def chmod(self, path, permissions, recursive=False): if type(permissions) == str: permissions = int(permissions, 8) return list(self.get_bite().chmod(self.list_path(path), permissions, recursive))
[ "\n Use snakebite.chmod, if available.\n\n :param path: update-able file(s)\n :type path: either a string or sequence of strings\n :param permissions: \\\\*nix style permission number\n :type permissions: octal\n :param recursive: change just listed entry(ies) or all in dir...
Please provide a description of the function:def chown(self, path, owner, group, recursive=False): bite = self.get_bite() if owner: if group: return all(bite.chown(self.list_path(path), "%s:%s" % (owner, group), recurse=recursive...
[ "\n Use snakebite.chown/chgrp, if available.\n\n One of owner or group must be set. Just setting group calls chgrp.\n\n :param path: update-able file(s)\n :type path: either a string or sequence of strings\n :param owner: new owner, can be blank\n :type owner: string\n ...
Please provide a description of the function:def count(self, path): try: res = self.get_bite().count(self.list_path(path)).next() dir_count = res['directoryCount'] file_count = res['fileCount'] content_size = res['spaceConsumed'] except StopIterat...
[ "\n Use snakebite.count, if available.\n\n :param path: directory to count the contents of\n :type path: string\n :return: dictionary with content_size, dir_count and file_count keys\n " ]
Please provide a description of the function:def get(self, path, local_destination): return list(self.get_bite().copyToLocal(self.list_path(path), local_destination))
[ "\n Use snakebite.copyToLocal, if available.\n\n :param path: HDFS file\n :type path: string\n :param local_destination: path on the system running Luigi\n :type local_destination: string\n " ]
Please provide a description of the function:def get_merge(self, path, local_destination): return list(self.get_bite().getmerge(path=path, dst=local_destination))
[ "\n Using snakebite getmerge to implement this.\n :param path: HDFS directory\n :param local_destination: path on the system running Luigi\n :return: merge of the directory\n " ]
Please provide a description of the function:def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): result = list(self.get_bite().mkdir(self.list_path(path), create_parent=parents, mode=mode)) if raise_if_exists and "ile exists" in re...
[ "\n Use snakebite.mkdir, if available.\n\n Snakebite's mkdir method allows control over full path creation, so by\n default, tell it to build a full path to work like ``hadoop fs -mkdir``.\n\n :param path: HDFS path to create\n :type path: string\n :param parents: create an...
Please provide a description of the function:def listdir(self, path, ignore_directories=False, ignore_files=False, include_size=False, include_type=False, include_time=False, recursive=False): bite = self.get_bite() for entry in bite.ls(self.list_path(path), recu...
[ "\n Use snakebite.ls to get the list of items in a directory.\n\n :param path: the directory to list\n :type path: string\n :param ignore_directories: if True, do not yield directory entries\n :type ignore_directories: boolean, default is False\n :param ignore_files: if Tru...
Please provide a description of the function:def instance(cls, *args, **kwargs): if cls._instance is None: cls._instance = cls(*args, **kwargs) loaded = cls._instance.reload() logging.getLogger('luigi-interface').info('Loaded %r', loaded) return cls._instanc...
[ " Singleton getter " ]
Please provide a description of the function:def load_task(module, task_name, params_str): if module is not None: __import__(module) task_cls = Register.get_task_cls(task_name) return task_cls.from_str_params(params_str)
[ "\n Imports task dynamically given a module and a task name.\n " ]
Please provide a description of the function:def task_family(cls): if not cls.get_task_namespace(): return cls.__name__ else: return "{}.{}".format(cls.get_task_namespace(), cls.__name__)
[ "\n Internal note: This function will be deleted soon.\n " ]
Please provide a description of the function:def _get_reg(cls): # We have to do this on-demand in case task names have changed later reg = dict() for task_cls in cls._reg: if not task_cls._visible_in_registry: continue name = task_cls.get_task_fa...
[ "Return all of the registered classes.\n\n :return: an ``dict`` of task_family -> class\n " ]
Please provide a description of the function:def _set_reg(cls, reg): cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS]
[ "The writing complement of _get_reg\n " ]
Please provide a description of the function:def get_task_cls(cls, name): task_cls = cls._get_reg().get(name) if not task_cls: raise TaskClassNotFoundException(cls._missing_task_msg(name)) if task_cls == cls.AMBIGUOUS_CLASS: raise TaskClassAmbigiousException('Ta...
[ "\n Returns an unambiguous class or raises an exception.\n " ]
Please provide a description of the function:def get_all_params(cls): for task_name, task_cls in six.iteritems(cls._get_reg()): if task_cls == cls.AMBIGUOUS_CLASS: continue for param_name, param_obj in task_cls.get_params(): yield task_name, (not ...
[ "\n Compiles and returns all parameters for all :py:class:`Task`.\n\n :return: a generator of tuples (TODO: we should make this more elegant)\n " ]
Please provide a description of the function:def _editdistance(a, b): r0 = range(0, len(b) + 1) r1 = [0] * (len(b) + 1) for i in range(0, len(a)): r1[0] = i + 1 for j in range(0, len(b)): c = 0 if a[i] is b[j] else 1 r1[j + 1] = ...
[ " Simple unweighted Levenshtein distance " ]
Please provide a description of the function:def _module_parents(module_name): ''' >>> list(Register._module_parents('a.b')) ['a.b', 'a', ''] ''' spl = module_name.split('.') for i in range(len(spl), 0, -1): yield '.'.join(spl[0:i]) if module_name: ...
[]
Please provide a description of the function:def _get_task_statuses(task_ids, cluster): response = client.describe_tasks(tasks=task_ids, cluster=cluster) # Error checking if response['failures'] != []: raise Exception('There were some failures:\n{0}'.format( response['failures'])) ...
[ "\n Retrieve task statuses from ECS API\n\n Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids\n " ]
Please provide a description of the function:def _track_tasks(task_ids, cluster): while True: statuses = _get_task_statuses(task_ids, cluster) if all([status == 'STOPPED' for status in statuses]): logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids))) break ...
[ "Poll task status until STOPPED" ]
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 not specified" % self.table) elif...
[ "\n Override to provide code for creating the target table.\n\n By default it will be created using types (optionally) specified in columns.\n\n If overridden, use the provided connection object for setting up the table in order to\n create the table and insert data using the same transa...
Please provide a description of the function:def init_copy(self, connection): # TODO: remove this after sufficient time so most people using the # clear_table attribtue will have noticed it doesn't work anymore if hasattr(self, "clear_table"): raise Exception("The clear_tab...
[ "\n Override to perform custom queries.\n\n Any code here will be formed in the same transaction as the main copy, just prior to copying data.\n Example use cases include truncating the table or removing all data older than X in the database\n to keep a rolling window of data available i...
Please provide a description of the function:def common_params(task_instance, task_cls): if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_instance_param_names = dict(task_instance.get_params()).keys() task_cls_params_dict = dict(task_c...
[ "\n Grab all the values in task_instance that are found in task_cls.\n " ]
Please provide a description of the function:def delegates(task_that_delegates): if not hasattr(task_that_delegates, 'subtasks'): # This method can (optionally) define a couple of delegate tasks that # will be accessible as interfaces, meaning that the task can access # those tasks and ...
[ " Lets a task call methods on subtask(s).\n\n The way this works is that the subtask is run as a part of the task, but\n the task itself doesn't have to care about the requirements of the subtasks.\n The subtask doesn't exist from the scheduler's point of view, and\n its dependencies are instead require...
Please provide a description of the function:def previous(task): params = task.get_params() previous_params = {} previous_date_params = {} for param_name, param_obj in params: param_value = getattr(task, param_name) if isinstance(param_obj, parameter.DateParameter): pr...
[ "\n Return a previous Task of the same family.\n\n By default checks if this task family only has one non-global parameter and if\n it is a DateParameter, DateHourParameter or DateIntervalParameter in which case\n it returns with the time decremented by 1 (hour, day or interval)\n " ]
Please provide a description of the function:def create_hadoopcli_client(): version = hdfs_config.get_configured_hadoop_version() if version == "cdh4": return HdfsClient() elif version == "cdh3": return HdfsClientCdh3() elif version == "apache1": return HdfsClientApache1() ...
[ "\n Given that we want one of the hadoop cli clients (unlike snakebite),\n this one will return the right one.\n " ]
Please provide a description of the function:def exists(self, path): cmd = load_hadoop_cmd() + ['fs', '-stat', path] logger.debug('Running file existence check: %s', subprocess.list2cmdline(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, ...
[ "\n Use ``hadoop fs -stat`` to check file existence.\n " ]
Please provide a description of the function:def mkdir(self, path, parents=True, raise_if_exists=False): try: self.call_check(load_hadoop_cmd() + ['fs', '-mkdir', path]) except hdfs_error.HDFSCliError as ex: if "File exists" in ex.stderr: if raise_if_exis...
[ "\n No explicit -p switch, this version of Hadoop always creates parent directories.\n " ]
Please provide a description of the function:def run_hive(args, check_return_code=True): cmd = load_hive_cmd() + args p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if check_return_code and p.returncode != 0: raise HiveCommandError...
[ "\n Runs the `hive` from the command line, passing in the given args, and\n returning stdout.\n\n With the apache release of Hive, so of the table existence checks\n (which are done using DESCRIBE do not exit with a return code of 0\n so we need an option to ignore the return code and just return std...
Please provide a description of the function:def run_hive_script(script): if not os.path.isfile(script): raise RuntimeError("Hive script: {0} does not exist.".format(script)) return run_hive(['-f', script])
[ "\n Runs the contents of the given script in hive and returns stdout.\n " ]
Please provide a description of the function:def prepare_outputs(self, job): outputs = flatten(job.output()) for o in outputs: if isinstance(o, FileSystemTarget): parent_dir = os.path.dirname(o.path) if parent_dir and not o.fs.exists(parent_dir): ...
[ "\n Called before job is started.\n\n If output is a `FileSystemTarget`, create parent directories so the hive command won't fail\n " ]
Please provide a description of the function:def path(self): location = self.client.table_location(self.table, self.database) if not location: raise Exception("Couldn't find location for table: {0}".format(str(self))) return location
[ "\n Returns the path to this table in HDFS.\n " ]
Please provide a description of the function:def touch(self): marker_key = self.marker_key() self.redis_client.hset(marker_key, 'update_id', self.update_id) self.redis_client.hset(marker_key, 'date', datetime.datetime.now()) if self.expire is not None: self.redis_cl...
[ "\n Mark this update as complete.\n\n We index the parameters `update_id` and `date`.\n " ]
Please provide a description of the function:def global_instance(cls, cmdline_args, allow_override=False): orig_value = cls._instance assert (orig_value is None) or allow_override new_value = None try: new_value = CmdlineParser(cmdline_args) cls._instance...
[ "\n Meant to be used as a context manager.\n " ]
Please provide a description of the function:def _possibly_exit_with_help(parser, known_args): if known_args.core_help or known_args.core_help_all: parser.print_help() sys.exit()
[ "\n Check if the user passed --help[-all], if so, print a message and exit.\n " ]
Please provide a description of the function:def relpath(self, current_file, rel_path): script_dir = os.path.dirname(os.path.abspath(current_file)) rel_path = os.path.abspath(os.path.join(script_dir, rel_path)) return rel_path
[ "\n Compute path given current file and relative path.\n " ]
Please provide a description of the function:def args(self): arglist = [] for k, v in six.iteritems(self.requires_hadoop()): arglist.append('--' + k) arglist.extend([t.output().path for t in flatten(v)]) arglist.extend(['--output', self.output()]) arglist...
[ "\n Returns an array of args to pass to the job.\n " ]
Please provide a description of the function:def add_event(self, event): if not isinstance(event, event_pb2.Event): raise TypeError("Expected an event_pb2.Event proto, " " but got %s" % type(event)) self._async_writer.write(event.SerializeToString())
[ "Adds an event to the event file.\n\n Args:\n event: An `Event` protocol buffer.\n " ]
Please provide a description of the function:def write(self, bytestring): '''Enqueue the given bytes to be written asychronously''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.put(bytestring)
[]
Please provide a description of the function:def flush(self): '''Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written. ''' with self._lock: if self._closed: raise IOError('Writer is closed') ...
[]
Please provide a description of the function:def close(self): '''Closes the underlying writer, flushing any pending writes first.''' if not self._closed: with self._lock: if not self._closed: self._closed = True self._worker.stop() ...
[]
Please provide a description of the function:def _extract_device_name_from_event(event): plugin_data_content = json.loads( tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content)) return plugin_data_content['device']
[ "Extract device name from a tf.Event proto carrying tensor value." ]
Please provide a description of the function:def _comm_tensor_data(device_name, node_name, maybe_base_expanded_node_name, output_slot, debug_op, tensor_value, wall_time): output_slot ...
[ "Create a dict() as the outgoing data in the tensor data comm route.\n\n Note: The tensor data in the comm route does not include the value of the\n tensor in its entirety in general. Only if a tensor satisfies the following\n conditions will its entire value be included in the return value of this\n method:\n ...
Please provide a description of the function:def add_graph(self, run_key, device_name, graph_def, debug=False): graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) if not run_key in graph_dict: graph_dict[run_key] = dict() # Mapping device_na...
[ "Add a GraphDef.\n\n Args:\n run_key: A key for the run, containing information about the feeds,\n fetches, and targets.\n device_name: The name of the device that the `GraphDef` is for.\n graph_def: An instance of the `GraphDef` proto.\n debug: Whether `graph_def` consists of the debu...
Please provide a description of the function:def get_graphs(self, run_key, debug=False): graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) graph_wrappers = graph_dict.get(run_key, {}) graph_defs = dict() for device_name, wrapper in graph_w...
[ "Get the runtime GraphDef protos associated with a run key.\n\n Args:\n run_key: A Session.run kay.\n debug: Whether the debugger-decoratedgraph is to be retrieved.\n\n Returns:\n A `dict` mapping device name to `GraphDef` protos.\n " ]
Please provide a description of the function:def get_graph(self, run_key, device_name, debug=False): return self.get_graphs(run_key, debug=debug).get(device_name, None)
[ "Get the runtime GraphDef proto associated with a run key and a device.\n\n Args:\n run_key: A Session.run kay.\n device_name: Name of the device in question.\n debug: Whether the debugger-decoratedgraph is to be retrieved.\n\n Returns:\n A `GraphDef` proto.\n " ]
Please provide a description of the function:def get_maybe_base_expanded_node_name(self, node_name, run_key, device_name): device_name = tf.compat.as_str(device_name) if run_key not in self._run_key_to_original_graphs: raise ValueError('Unknown run_key: %s' % run_key) if device_name not in self._...
[ "Obtain possibly base-expanded node name.\n\n Base-expansion is the transformation of a node name which happens to be the\n name scope of other nodes in the same graph. For example, if two nodes,\n called 'a/b' and 'a/b/read' in a graph, the name of the first node will\n be base-expanded to 'a/b/(b)'.\n...
Please provide a description of the function:def on_core_metadata_event(self, event): core_metadata = json.loads(event.log_message.message) input_names = ','.join(core_metadata['input_names']) output_names = ','.join(core_metadata['output_names']) target_nodes = ','.join(core_metadata['target_nodes...
[ "Implementation of the core metadata-carrying Event proto callback.\n\n Args:\n event: An Event proto that contains core metadata about the debugged\n Session::Run() in its log_message.message field, as a JSON string.\n See the doc string of debug_data.DebugDumpDir.core_metadata for details.\n...
Please provide a description of the function:def on_graph_def(self, graph_def, device_name, wall_time): # For now, we do nothing with the graph def. However, we must define this # method to satisfy the handler's interface. Furthermore, we may use the # graph in the future (for instance to provide a gra...
[ "Implementation of the GraphDef-carrying Event proto callback.\n\n Args:\n graph_def: A GraphDef proto. N.B.: The GraphDef is from\n the core runtime of a debugged Session::Run() call, after graph\n partition. Therefore it may differ from the GraphDef available to\n the general TensorBo...
Please provide a description of the function:def on_value_event(self, event): if not event.summary.value: logger.info('The summary of the event lacks a value.') return None # The node name property in the event proto is actually a watch key, which # is a concatenation of several pieces of ...
[ "Records the summary values based on an updated message from the debugger.\n\n Logs an error message if writing the event to disk fails.\n\n Args:\n event: The Event proto to be processed.\n " ]
Please provide a description of the function:def add_debugged_source_file(self, debugged_source_file): # TODO(cais): Should the key include a host name, for certain distributed # cases? key = debugged_source_file.file_path self._source_file_host[key] = debugged_source_file.host self._source_f...
[ "Add a DebuggedSourceFile proto." ]
Please provide a description of the function:def get_op_traceback(self, op_name): if not self._graph_traceback: raise ValueError('No graph traceback has been received yet.') for op_log_entry in self._graph_traceback.log_entries: if op_log_entry.name == op_name: return self._code_def_to_...
[ "Get the traceback of an op in the latest version of the TF graph.\n\n Args:\n op_name: Name of the op.\n\n Returns:\n Creation traceback of the op, in the form of a list of 2-tuples:\n (file_path, lineno)\n\n Raises:\n ValueError: If the op with the given name cannot be found in the ...
Please provide a description of the function:def get_file_tracebacks(self, file_path): if file_path not in self._source_file_content: raise ValueError( 'Source file of path "%s" has not been received by this instance of ' 'SourceManager.' % file_path) lineno_to_op_names_and_stack...
[ "Get the lists of ops created at lines of a specified source file.\n\n Args:\n file_path: Path to the source file.\n\n Returns:\n A dict mapping line number to a list of 2-tuples,\n `(op_name, stack_position)`\n `op_name` is the name of the name of the op whose creation traceback\n ...
Please provide a description of the function:def query_tensor_store(self, watch_key, time_indices=None, slicing=None, mapping=None): return self._tensor_store.query(watch_key, ...
[ "Query tensor store for a given debugged tensor value.\n\n Args:\n watch_key: The watch key of the debugged tensor being sought. Format:\n <node_name>:<output_slot>:<debug_op>\n E.g., Dense_1/MatMul:0:DebugIdentity.\n time_indices: Optional time indices string By default, the lastest time...