code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _get_representation_doc(self): if not self.representation: return 'N/A' fields = {} for name, field in self.representation.fields.items(): fields[name] = self._get_field_doc(field) return fields
Return documentation for the representation of the resource.
def _get_field_doc(self, field): fieldspec = dict() fieldspec['type'] = field.__class__.__name__ fieldspec['required'] = field.required fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} for validator in field.validators] return fieldspec
Return documentation for a field in the representation.
def _get_url_doc(self): resolver = get_resolver(None) possibilities = resolver.reverse_dict.getlist(self) urls = [possibility[0] for possibility in possibilities] return urls
Return a list of URLs that map to this resource.
def _get_method_doc(self): ret = {} for method_name in self.methods: method = getattr(self, method_name, None) if method: ret[method_name] = method.__doc__ return ret
Return method documentations.
def clean(df,error_rate = 0): df = df.copy() # Change colnames basics.clean_colnames(df) # Eventually use a more advanced function to clean colnames print('Changed colnames to {}'.format(df.columns)) # Remove extra whitespace obj_col_list = df.select_dtypes(include = 'object')...
Superficially cleans data, i.e. changing simple things about formatting. Parameters: df - DataFrame DataFrame to clean error_rate - float {0 <= error_rate <= 1}, default 0 Maximum amount of errors/inconsistencies caused explicitly by cleaning, expressed as a percentage of total dataf...
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display return subprocess.Popen(command, shell=shell, stdout=stdout, stderr=...
Execute a process using subprocess.Popen, setting the backend's DISPLAY
def pause(self, instance_id, keep_provisioned=True): try: if self._paused: log.debug("node %s is already paused", instance_id) return self._paused = True post_shutdown_action = 'Stopped' if keep_provisioned else \ 'Stop...
shuts down the instance without destroying it. The AbstractCloudProvider class uses 'stop' to refer to destroying a VM, so use 'pause' to mean powering it down while leaving it allocated. :param str instance_id: instance identifier :return: None
def restart(self, instance_id): try: if not self._paused: log.debug("node %s is not paused, can't restart", instance_id) return self._paused = False result = self._subscription._sms.start_role( service_name=self._cloud_...
restarts a paused instance. :param str instance_id: instance identifier :return: None
def stop_instance(self, instance_id): self._restore_from_storage(instance_id) if self._start_failed: raise Exception('stop_instance for node %s: failing due to' ' previous errors.' % instance_id) with self._resource_lock: try: ...
Stops the instance gracefully. :param str instance_id: instance identifier :return: None
def get_ips(self, instance_id): self._restore_from_storage(instance_id) if self._start_failed: raise Exception('get_ips for node %s: failing due to' ' previous errors.' % instance_id) ret = list() v_m = self._qualified_name_to_vm(instance...
Retrieves the private and public ip addresses for a given instance. Note: Azure normally provides access to vms from a shared load balancer IP and mapping of ssh ports on the vms. So by default, the Azure provider returns strings of the form 'ip:port'. However, 'stock' elasticlus...
def is_instance_running(self, instance_id): self._restore_from_storage(instance_id) if self._start_failed: raise Exception('is_instance_running for node %s: failing due to' ' previous errors.' % instance_id) try: v_m = self._qualified_...
Checks if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise
def _save_or_update(self): with self._resource_lock: if not self._config or not self._config._storage_path: raise Exception("self._config._storage path is undefined") if not self._config._base_name: raise Exception("self._config._base_name is unde...
Save or update the private state needed by the cloud provider.
def chunked(src, size, count=None, **kw): chunk_iter = chunked_iter(src, size, **kw) if count is None: return list(chunk_iter) else: return list(itertools.islice(chunk_iter, count))
Returns a list of *count* chunks, each with *size* elements, generated from iterable *src*. If *src* is not evenly divisible by *size*, the final chunk will have fewer than *size* elements. Provide the *fill* keyword argument to provide a pad value and enable padding, otherwise no padding will take plac...
def chunked_iter(src, size, **kw): # TODO: add count kwarg? if not is_iterable(src): raise TypeError('expected an iterable') size = int(size) if size <= 0: raise ValueError('expected a positive integer chunk size') do_fill = True try: fill_val = kw.pop('fill') ex...
Generates *size*-sized chunks from *src* iterable. Unless the optional *fill* keyword argument is provided, iterables not even divisible by *size* will have a final chunk that is smaller than *size*. >>> list(chunked_iter(range(10), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] >>> list(chunked_it...
def windowed_iter(src, size): # TODO: lists? (for consistency) tees = itertools.tee(src, size) try: for i, t in enumerate(tees): for _ in xrange(i): next(t) except StopIteration: return izip([]) return izip(*tees)
Returns tuples with length *size* which represent a sliding window over iterable *src*. >>> list(windowed_iter(range(7), 3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] If the iterable is too short to make a window of length *size*, then no window tuples are returned. >>> list(win...
def xfrange(stop, start=None, step=1.0): if not step: raise ValueError('step must be non-zero') if start is None: start, stop = 0.0, stop * 1.0 else: # swap when all args are used stop, start = start * 1.0, stop * 1.0 cur = start while cur < stop: yield c...
Same as :func:`frange`, but generator-based instead of returning a list. >>> tuple(xfrange(1, 3, step=0.75)) (1.0, 1.75, 2.5) See :func:`frange` for more details.
def frange(stop, start=None, step=1.0): if not step: raise ValueError('step must be non-zero') if start is None: start, stop = 0.0, stop * 1.0 else: # swap when all args are used stop, start = start * 1.0, stop * 1.0 count = int(math.ceil((stop - start) / step)) ...
A :func:`range` clone for float-based ranges. >>> frange(5) [0.0, 1.0, 2.0, 3.0, 4.0] >>> frange(6, step=1.25) [0.0, 1.25, 2.5, 3.75, 5.0] >>> frange(100.5, 101.5, 0.25) [100.5, 100.75, 101.0, 101.25] >>> frange(5, 0) [] >>> frange(5, 0, step=-1.25) [5.0, 3.75, 2.5, 1.25]
def backoff(start, stop, count=None, factor=2.0, jitter=False): if count == 'repeat': raise ValueError("'repeat' supported in backoff_iter, not backoff") return list(backoff_iter(start, stop, count=count, factor=factor, jitter=jitter))
Returns a list of geometrically-increasing floating-point numbers, suitable for usage with `exponential backoff`_. Exactly like :func:`backoff_iter`, but without the ``'repeat'`` option for *count*. See :func:`backoff_iter` for more details. .. _exponential backoff: https://en.wikipedia.org/wiki/Expone...
def partition(src, key=None): bucketized = bucketize(src, key) return bucketized.get(True, []), bucketized.get(False, [])
No relation to :meth:`str.partition`, ``partition`` is like :func:`bucketize`, but for added convenience returns a tuple of ``(truthy_values, falsy_values)``. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) >>> nonempty ['hi', 'bye'] *key* defaults to :class:`bool`, but can be caref...
def unique_iter(src, key=None): if not is_iterable(src): raise TypeError('expected an iterable, not %r' % type(src)) if key is None: key_func = lambda x: x elif callable(key): key_func = key elif isinstance(key, basestring): key_func = lambda x: getattr(x, key, x) ...
Yield unique elements from the iterable, *src*, based on *key*, in the order in which they first appeared in *src*. >>> repetitious = [1, 2, 3] * 10 >>> list(unique_iter(repetitious)) [1, 2, 3] By default, *key* is the object itself, but *key* can either be a callable or, for convenience, a st...
def one(src, default=None, key=None): ones = list(itertools.islice(filter(key, src), 2)) return ones[0] if len(ones) == 1 else default
Along the same lines as builtins, :func:`all` and :func:`any`, and similar to :func:`first`, ``one()`` returns the single object in the given iterable *src* that evaluates to ``True``, as determined by callable *key*. If unset, *key* defaults to :class:`bool`. If no such objects are found, *default* is ...
def same(iterable, ref=_UNSET): iterator = iter(iterable) if ref is _UNSET: ref = next(iterator, ref) return all(val == ref for val in iterator)
``same()`` returns ``True`` when all values in *iterable* are equal to one another, or optionally a reference value, *ref*. Similar to :func:`all` and :func:`any` in that it evaluates an iterable and returns a :class:`bool`. ``same()`` returns ``True`` for empty iterables. >>> same([]) True ...
def get_path(root, path, default=_UNSET): if isinstance(path, basestring): path = path.split('.') cur = root try: for seg in path: try: cur = cur[seg] except (KeyError, IndexError) as exc: raise PathAccessError(exc, seg, path) ...
Retrieve a value from a nested object via a tuple representing the lookup path. >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}} >>> get_path(root, ('a', 'b', 'c', 2, 0)) 3 The path format is intentionally consistent with that of :func:`remap`. One of get_path's chief aims is improved erro...
def unflatten(data, separator='.', replace=True): ''' Expand all compound keys (at any depth) into nested dicts In [13]: d = {'test.test2': {'k1.k2': 'val'}} In [14]: flange.expand(d) Out[14]: {'test.test2': {'k1': {'k2': 'val'}}} :param data: input dict :param separator: sepa...
Expand all compound keys (at any depth) into nested dicts In [13]: d = {'test.test2': {'k1.k2': 'val'}} In [14]: flange.expand(d) Out[14]: {'test.test2': {'k1': {'k2': 'val'}}} :param data: input dict :param separator: separator in compound keys :param replace: if true, remove the...
def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True): # if not k: # print '__query p k:', p, k # print p, k, accepted_keys, required_values, path, exact def as_values_iterable(v): if isinstance(v, dict): return v.values() elif isinst...
Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :param required_values: list of values where one must match v to satisfy query :param path: exact p...
def create_customer_group(cls, customer_group, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_customer_group_with_http_info(customer_group, **kwargs) else: (data) = cls._create_customer_group_with_http_info(customer_...
Create CustomerGroup Create a new CustomerGroup This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_customer_group(customer_group, async=True) >>> result = thread.get() :param asyn...
def delete_customer_group_by_id(cls, customer_group_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_customer_group_by_id_with_http_info(customer_group_id, **kwargs) else: (data) = cls._delete_customer_group_by_id_...
Delete CustomerGroup Delete an instance of CustomerGroup by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_customer_group_by_id(customer_group_id, async=True) >>> result = thre...
def get_customer_group_by_id(cls, customer_group_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_customer_group_by_id_with_http_info(customer_group_id, **kwargs) else: (data) = cls._get_customer_group_by_id_with_http...
Find CustomerGroup Return single instance of CustomerGroup by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_customer_group_by_id(customer_group_id, async=True) >>> result = threa...
def list_all_customer_groups(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_customer_groups_with_http_info(**kwargs) else: (data) = cls._list_all_customer_groups_with_http_info(**kwargs) return dat...
List CustomerGroups Return a list of CustomerGroups This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_customer_groups(async=True) >>> result = thread.get() :param async bool ...
def replace_customer_group_by_id(cls, customer_group_id, customer_group, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_customer_group_by_id_with_http_info(customer_group_id, customer_group, **kwargs) else: (data) =...
Replace CustomerGroup Replace all attributes of CustomerGroup This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_customer_group_by_id(customer_group_id, customer_group, async=True) >>> re...
def update_customer_group_by_id(cls, customer_group_id, customer_group, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_customer_group_by_id_with_http_info(customer_group_id, customer_group, **kwargs) else: (data) = c...
Update CustomerGroup Update attributes of CustomerGroup This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_customer_group_by_id(customer_group_id, customer_group, async=True) >>> result = ...
def _connect(self): # check for existing connection with GoogleCloudProvider.__gce_lock: if self._gce: return self._gce flow = OAuth2WebServerFlow(self._client_id, self._client_secret, GCE_SCOPE) # The `...
Connects to the cloud web services. If this is the first authentication, a web browser will be started to authenticate against google and provide access to elasticluster. :return: A Resource object with methods for interacting with the service.
def _get_image_url(self, image_id): gce = self._connect() filter = "name eq %s" % image_id request = gce.images().list(project=self._project_id, filter=filter) response = self._execute_request(request) response = self._wait_until_done(response) image_url = None ...
Gets the url for the specified image. Unfortunatly this only works for images uploaded by the user. The images provided by google will not be found. :param str image_id: image identifier :return: str - api url of the image
def create_free_shipping(cls, free_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_free_shipping_with_http_info(free_shipping, **kwargs) else: (data) = cls._create_free_shipping_with_http_info(free_shipping,...
Create FreeShipping Create a new FreeShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_free_shipping(free_shipping, async=True) >>> result = thread.get() :param async bo...
def delete_free_shipping_by_id(cls, free_shipping_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_free_shipping_by_id_with_http_info(free_shipping_id, **kwargs) else: (data) = cls._delete_free_shipping_by_id_with_...
Delete FreeShipping Delete an instance of FreeShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_free_shipping_by_id(free_shipping_id, async=True) >>> result = thread.g...
def get_free_shipping_by_id(cls, free_shipping_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_free_shipping_by_id_with_http_info(free_shipping_id, **kwargs) else: (data) = cls._get_free_shipping_by_id_with_http_info...
Find FreeShipping Return single instance of FreeShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_free_shipping_by_id(free_shipping_id, async=True) >>> result = thread.ge...
def list_all_free_shippings(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_free_shippings_with_http_info(**kwargs) else: (data) = cls._list_all_free_shippings_with_http_info(**kwargs) return data
List FreeShippings Return a list of FreeShippings This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_free_shippings(async=True) >>> result = thread.get() :param async bool ...
def replace_free_shipping_by_id(cls, free_shipping_id, free_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_free_shipping_by_id_with_http_info(free_shipping_id, free_shipping, **kwargs) else: (data) = cls._...
Replace FreeShipping Replace all attributes of FreeShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_free_shipping_by_id(free_shipping_id, free_shipping, async=True) >>> result ...
def update_free_shipping_by_id(cls, free_shipping_id, free_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_free_shipping_by_id_with_http_info(free_shipping_id, free_shipping, **kwargs) else: (data) = cls._up...
Update FreeShipping Update attributes of FreeShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_free_shipping_by_id(free_shipping_id, free_shipping, async=True) >>> result = threa...
def publish(dataset_uri): try: dataset = dtoolcore.DataSet.from_uri(dataset_uri) except dtoolcore.DtoolCoreTypeError: print("Not a dataset: {}".format(dataset_uri)) sys.exit(1) try: access_uri = dataset._storage_broker.http_enable() except AttributeError: p...
Return access URL to HTTP enabled (published) dataset. Exits with error code 1 if the dataset_uri is not a dataset. Exits with error code 2 if the dataset cannot be HTTP enabled.
def cli(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "dataset_uri", help="Dtool dataset URI" ) parser.add_argument( "-q", "--quiet", action="store_true", help="Only return the http URI" ) args = parser.parse_ar...
Command line utility to HTTP enable (publish) a dataset.
def execute(self): creator = make_creator(self.params.config, storage_path=self.params.storage) cluster_name = self.params.cluster try: cluster = creator.load_cluster(cluster_name) except (ClusterNotFound, ConfigurationError) as ex: ...
Load the cluster and build a GC3Pie configuration snippet.
def write_xml(self, outfile, encoding="UTF-8"): # we add the media namespace if we see any media items if any([key for item in self.items for key in vars(item) if key.startswith('media_') and getattr(item, key)]): self.rss_attrs["xmlns:media"] = "http://search.yahoo....
Write the Media RSS Feed's XML representation to the given file.
def _add_attribute(self, name, value, allowed_values=None): if value and value != 'none': if isinstance(value, (int, bool)): value = str(value) if allowed_values and value not in allowed_values: raise TypeError( "Attribute '"...
Add an attribute to the MediaContent element.
def check_complicance(self): # check Media RSS requirement: one of the following elements is # required: media_group | media_content | media_player | media_peerLink # | media_location. We do the check only if any media_... element is # set to allow non media feeds if(any...
Check compliance with Media RSS Specification, Version 1.5.1. see http://www.rssboard.org/media-rss Raises AttributeError on error.
def publish_extensions(self, handler): if isinstance(self.media_content, list): [PyRSS2Gen._opt_element(handler, "media:content", mc_element) for mc_element in self.media_content] else: PyRSS2Gen._opt_element(handler, "media:content", ...
Publish the Media RSS Feed elements as XML.
def get_conversations(self): cs = self.data["data"] res = [] for c in cs: res.append(Conversation(c)) return res
Returns list of Conversation objects
def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) try: total = next(it) except StopIteration: ...
Return running totals
def add_methods(methods_to_add): ''' use this to bulk add new methods to Generator ''' for i in methods_to_add: try: Generator.add_method(*i) except Exception as ex: raise Exception('issue adding {} - {}'.format(repr(i), ex)f add_methods(methods_to...
use this to bulk add new methods to Generator
def run(self): if KSER_METRICS_ENABLED == "yes": from prometheus_client import start_http_server logger.info("Metric.Starting...") start_http_server( os.getenv("KSER_METRICS_PORT", 8888), os.getenv("KSER_METRICS_ADDRESS", "0.0.0.0") ...
Run consumer
def walklevel(path, depth = -1, **kwargs): # if depth is negative, just walk if depth < 0: for root, dirs, files in os.walk(path, **kwargs): yield root, dirs, files # path.count works because is a file has a "/" it will show up in the list # as a ":"...
It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go. If depth is -1 (or less than 0), the full depth is walked.
def tree_construct(self, *args, **kwargs): l_files = [] d_constructCallback = {} fn_constructCallback = None for k, v in kwargs.items(): if k == 'l_files': l_files = v if k == 'constructCallback': fn_constr...
Processes the <l_files> list of files from the tree_probe() and builds the input/output dictionary structures. Optionally execute a constructCallback function, and return results
def dirsize_get(l_filesWithoutPath, **kwargs): str_path = "" for k,v in kwargs.items(): if k == 'path': str_path = v d_ret = {} l_size = [] size = 0 for f in l_filesWithoutPath: str_f = '%s/%s' % (str_path, f) if n...
Sample callback that determines a directory size.
def tree_analysisOutput(self, *args, **kwargs): fn_outputcallback = None for k, v in kwargs.items(): if k == 'outputcallback': fn_outputcallback = v index = 1 total = len(self.d_inputTree.keys()) for path, d_analysis in self....
An optional method for looping over the <outputTree> and calling an outputcallback on the analysis results at each path. Only call this if self.b_persisAnalysisResults is True.
def stats_compute(self, *args, **kwargs): totalElements = 0 totalKeys = 0 totalSize = 0 l_stats = [] d_report = {} for k, v in sorted(self.d_inputTreeCallback.items(), key = lambda kv: (kv[1]['dis...
Simply loop over the internal dictionary and echo the list size at each key (i.e. the number of files).
def inputReadCallback(self, *args, **kwargs): b_status = True filesRead = 0 for k, v in kwargs.items(): if k == 'l_file': l_file = v if k == 'path': str_path = v if len(args): at_data = args[0] str_path...
Test for inputReadCallback This method does not actually "read" the input files, but simply returns the passed file list back to caller
def inputAnalyzeCallback(self, *args, **kwargs): b_status = False filesRead = 0 filesAnalyzed = 0 for k, v in kwargs.items(): if k == 'filesRead': d_DCMRead = v if k == 'path': str_path = v if len(args)...
Test method for inputAnalzeCallback This method loops over the passed number of files, and optionally "delays" in each loop to simulate some analysis. The delay length is specified by the '--test <delay>' flag.
def outputSaveCallback(self, at_data, **kwargs): path = at_data[0] d_outputInfo = at_data[1] other.mkdir(self.str_outputDir) filesSaved = 0 other.mkdir(path) if not self.testType: str_outfile = '%s/file-ls.txt' ...
Test method for outputSaveCallback Simply writes a file in the output tree corresponding to the number of files in the input tree.
def check_required_params(self): for param in self.REQUIRED_FIELDS: if param not in self.params: raise ValidationError("Missing parameter: {} for {}".format( param, self.__class__.path )) for child in self.TASKS: for p...
Check if all required parameters are set
def _set_status(self, status, result=None): logger.info( "{}.SetStatus: {}[{}] status update '{}' -> '{}'".format( self.__class__.__name__, self.__class__.path, self.uuid, self.status, status ), extra=dict( kmsg=Message...
update operation status :param str status: New status :param cdumay_result.Result result: Execution result
def _prerun(self): self.check_required_params() self._set_status("RUNNING") logger.debug( "{}.PreRun: {}[{}]: running...".format( self.__class__.__name__, self.__class__.path, self.uuid ), extra=dict( kmsg=Message( ...
To execute before running message
def _onsuccess(self, result): self._set_status("SUCCESS", result) logger.info( "{}.Success: {}[{}]: {}".format( self.__class__.__name__, self.__class__.path, self.uuid, result ), extra=dict( kmsg=Message( se...
To execute on execution success :param cdumay_result.Result result: Execution result :return: Execution result :rtype: cdumay_result.Result
def _onerror(self, result): self._set_status("FAILED", result) logger.error( "{}.Failed: {}[{}]: {}".format( self.__class__.__name__, self.__class__.path, self.uuid, result ), extra=dict( kmsg=Message( self....
To execute on execution failure :param cdumay_result.Result result: Execution result :return: Execution result :rtype: cdumay_result.Result
def display(self): print("{}".format(self)) for task in self.tasks: print(" - {}".format(task))
dump operation
def next(self, task): uuid = str(task.uuid) for idx, otask in enumerate(self.tasks[:-1]): if otask.uuid == uuid: if self.tasks[idx + 1].status != 'SUCCESS': return self.tasks[idx + 1] else: uuid = self.tasks[idx...
Find the next task :param kser.sequencing.task.Task task: previous task :return: The next task :rtype: kser.sequencing.task.Task or None
def launch_next(self, task=None, result=None): if task: next_task = self.next(task) if next_task: return next_task.send(result=result) else: return self.set_status(task.status, result) elif len(self.tasks) > 0: retu...
Launch next task or finish operation :param kser.sequencing.task.Task task: previous task :param cdumay_result.Result result: previous task result :return: Execution result :rtype: cdumay_result.Result
def compute_tasks(self, **kwargs): params = self._prebuild(**kwargs) if not params: params = dict(kwargs) return self._build_tasks(**params)
perfrom checks and build tasks :return: list of tasks :rtype: list(kser.sequencing.operation.Operation)
def build(self, **kwargs): self.tasks += self.compute_tasks(**kwargs) return self.finalize()
create the operation and associate tasks :param dict kwargs: operation data :return: the controller :rtype: kser.sequencing.controller.OperationController
def serve_dtool_directory(directory, port): os.chdir(directory) server_address = ("localhost", port) httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler) httpd.serve_forever()
Serve the datasets in a directory over HTTP.
def cli(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "dataset_directory", help="Directory with datasets to be served" ) parser.add_argument( "-p", "--port", type=int, default=8081, help="Port to serve datasets ...
Command line utility for serving datasets in a directory over HTTP.
def generate_url(self, suffix): url_base_path = os.path.dirname(self.path) netloc = "{}:{}".format(*self.server.server_address) return urlunparse(( "http", netloc, url_base_path + "/" + suffix, "", "", ""))
Return URL by combining server details with a path suffix.
def generate_item_urls(self): item_urls = {} for i in self.dataset.identifiers: relpath = self.dataset.item_properties(i)["relpath"] url = self.generate_url("data/" + relpath) item_urls[i] = url return item_urls
Return dict with identifier/URL pairs for the dataset items.
def generate_overlay_urls(self): overlays = {} for o in self.dataset.list_overlay_names(): url = self.generate_url(".dtool/overlays/{}.json".format(o)) overlays[o] = url return overlays
Return dict with overlay/URL pairs for the dataset overlays.
def generate_http_manifest(self): base_path = os.path.dirname(self.translate_path(self.path)) self.dataset = dtoolcore.DataSet.from_uri(base_path) admin_metadata_fpath = os.path.join(base_path, ".dtool", "dtool") with open(admin_metadata_fpath) as fh: admin_metadata...
Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published).
def do_GET(self): if self.path.endswith("http_manifest.json"): try: manifest = self.generate_http_manifest() self.send_response(200) self.end_headers() self.wfile.write(manifest) except dtoolcore.DtoolCoreTypeError:...
Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json".
def indent(self, code, level=1): '''python's famous indent''' lines = code.split('\n') lines = tuple(self.indent_space*level + line for line in lines) return '\n'.join(linesf indent(self, code, level=1): '''python's famous indent''' lines = code.split('\n') lines = tuple(self.indent_s...
python's famous indent
def setup_database_connection( pathToYamlFile): import sys import logging import pymysql as ms # IMPORT THE YAML CONNECTION DICTIONARY try: logging.info( 'importing the yaml database connection dictionary from ' + pathToYamlFile) stream = file(pathToYamlFile...
*Start a database connection using settings in yaml file* Given the location of a YAML dictionary containing database credientials, this function will setup and return the connection* **Key Arguments:** - ``pathToYamlFile`` -- path to the YAML dictionary. **Return:** - ``dbConn`` -- conn...
def create_order_line_item(cls, order_line_item, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_order_line_item_with_http_info(order_line_item, **kwargs) else: (data) = cls._create_order_line_item_with_http_info(orde...
Create OrderLineItem Create a new OrderLineItem This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_order_line_item(order_line_item, async=True) >>> result = thread.get() :param as...
def delete_order_line_item_by_id(cls, order_line_item_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_order_line_item_by_id_with_http_info(order_line_item_id, **kwargs) else: (data) = cls._delete_order_line_item_b...
Delete OrderLineItem Delete an instance of OrderLineItem by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_order_line_item_by_id(order_line_item_id, async=True) >>> result = th...
def get_order_line_item_by_id(cls, order_line_item_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_order_line_item_by_id_with_http_info(order_line_item_id, **kwargs) else: (data) = cls._get_order_line_item_by_id_with...
Find OrderLineItem Return single instance of OrderLineItem by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_order_line_item_by_id(order_line_item_id, async=True) >>> result = thr...
def list_all_order_line_items(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_order_line_items_with_http_info(**kwargs) else: (data) = cls._list_all_order_line_items_with_http_info(**kwargs) return ...
List OrderLineItems Return a list of OrderLineItems This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_order_line_items(async=True) >>> result = thread.get() :param async bool ...
def replace_order_line_item_by_id(cls, order_line_item_id, order_line_item, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_order_line_item_by_id_with_http_info(order_line_item_id, order_line_item, **kwargs) else: (d...
Replace OrderLineItem Replace all attributes of OrderLineItem This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_order_line_item_by_id(order_line_item_id, order_line_item, async=True) >>>...
def update_order_line_item_by_id(cls, order_line_item_id, order_line_item, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_order_line_item_by_id_with_http_info(order_line_item_id, order_line_item, **kwargs) else: (dat...
Update OrderLineItem Update attributes of OrderLineItem This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_order_line_item_by_id(order_line_item_id, order_line_item, async=True) >>> result...
def is_grammar_generating(grammar, remove=False): # type: (Grammar, bool) -> bool g = ContextFree.remove_nongenerating_nonterminals(grammar, remove) return g.start is not None
Check if is grammar is generating. Generating grammar generates at least one sentence. :param grammar: Grammar to check. :param remove: True to remove nongenerating symbols from the grammar. :return: True if is grammar generating, false otherwise.
def remove_useless_symbols(grammar, inplace=False): # type: (Grammar, bool) -> Grammar grammar = ContextFree.remove_nongenerating_nonterminals(grammar, inplace) grammar = ContextFree.remove_unreachable_symbols(grammar, True) return grammar
Remove useless symbols from the grammar. Useless symbols are unreachable or nongenerating one. :param grammar: Grammar where to symbols remove :param inplace: True if transformation should be performed in place, false otherwise. False by default. :return: Grammar without useless ...
def prepare_for_cyk(grammar, inplace=False): # type: (Grammar, bool) -> Grammar grammar = ContextFree.remove_useless_symbols(grammar, inplace) grammar = ContextFree.remove_rules_with_epsilon(grammar, True) grammar = ContextFree.remove_unit_rules(grammar, True) grammar = ...
Take common context-free grammar and perform all the necessary steps to use it in the CYK algorithm. Performs following steps: - remove useless symbols - remove rules with epsilon - remove unit rules - remove useless symbols once more (as previous steps could change the grammar) ...
def retrieve_authorization_code(self, redirect_func=None): request_param = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, } if self.scope: request_param['scope'] = self.scope if self._extra_auth_params: ...
retrieve authorization code to get access token
def retrieve_token(self): if self.authorization_code: request_param = { "client_id": self.client_id, "client_secret": self.client_secret, "redirect_uri": self.redirect_uri, "code": self.authorization_code } ...
retrieve access token with code fetched via retrieve_authorization_code method.
def to_dict(self): '''Represents the setup section in form of key-value pairs. Returns ------- dict ''' mapping = dict() for attr in dir(self): if attr.startswith('_'): continue if not isinstance(getattr(self.__class__, att...
Represents the setup section in form of key-value pairs. Returns ------- dict
def key_file_private(self): '''str: path to the private key used by Ansible to connect to virtual machines (by default looks for a file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory) ''' if not hasattr(self, '_key_file_private'...
str: path to the private key used by Ansible to connect to virtual machines (by default looks for a file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory)
def key_file_public(self): '''str: path to the public key that will be uploaded to the cloud provider (by default looks for a ``.pub`` file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory) ''' if not hasattr(self, '_key_file_publ...
str: path to the public key that will be uploaded to the cloud provider (by default looks for a ``.pub`` file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory)
def tm_group(self): '''str: TissueMAPS system group (defaults to :attr:`tm_user <tmdeploy.config.AnsibleHostVariableSection.tm_user>`) ''' if self._tm_group is None: self._tm_group = self.tm_user return self._tm_grouf tm_group(self): '''str: TissueMAPS system ...
str: TissueMAPS system group (defaults to :attr:`tm_user <tmdeploy.config.AnsibleHostVariableSection.tm_user>`)
def db_group(self): '''str: database system group (defaults to :attr:`db_user <tmdeploy.config.AnsibleHostVariableSection.db_user>`) ''' if self._db_group is None: self._db_group = self.db_user return self._db_grouf db_group(self): '''str: database system grou...
str: database system group (defaults to :attr:`db_user <tmdeploy.config.AnsibleHostVariableSection.db_user>`)
def web_group(self): '''str: web system group (defaults to :attr:`web_user <tmdeploy.config.AnsibleHostVariableSection.web_user>`) ''' if self._web_group is None: self._web_group = self.web_user return self._web_grouf web_group(self): '''str: web system group ...
str: web system group (defaults to :attr:`web_user <tmdeploy.config.AnsibleHostVariableSection.web_user>`)
def mtime(path): if not os.path.exists(path): return -1 stat = os.stat(path) return stat.st_mtime
Get the modification time of a file, or -1 if the file does not exist.
def get_cached(path, cache_name=None, **kwargs): if gw2api.cache_dir and gw2api.cache_time and cache_name is not False: if cache_name is None: cache_name = path cache_file = os.path.join(gw2api.cache_dir, cache_name) if mtime(cache_file) >= time.time() - gw2api.cache_time: ...
Request a resource form the API, first checking if there is a cached response available. Returns the parsed JSON data.
def encode_item_link(item_id, number=1, skin_id=None, upgrade1=None, upgrade2=None): return encode_chat_link(gw2api.TYPE_ITEM, id=item_id, number=number, skin_id=skin_id, upgrade1=upgrade1, upgrade2=upgrade2)
Encode a chat link for an item (or a stack of items). :param item_id: the Id of the item :param number: the number of items in the stack :param skin_id: the id of the skin applied to the item :param upgrade1: the id of the first upgrade component :param upgrade2: the id of the second upgrade compon...
def encode_coin_link(copper, silver=0, gold=0): return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
Encode a chat link for an amount of coins.
def status(self, status): allowed_values = ["pending", "awaitingRetry", "successful", "failed"] if status is not None and status not in allowed_values: raise ValueError( "Invalid value for `status` ({0}), must be one of {1}" .format(status, allowed_va...
Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str
def create_store_credit_payment(cls, store_credit_payment, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_store_credit_payment_with_http_info(store_credit_payment, **kwargs) else: (data) = cls._create_store_credit_pa...
Create StoreCreditPayment Create a new StoreCreditPayment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_store_credit_payment(store_credit_payment, async=True) >>> result = thread.get(...