code
stringlengths
1
18.2k
def edit(self): """ Edit file with default os application. """ if platform.system().lower() == 'windows': os.startfile(str(self.config_file)) else: if platform.system().lower() == 'darwin': call = 'open' else: call = 'xdg-open' subprocess.call([call, self.config_file])
def is_excluded(self, path, exclude=None): """ Return if path is in exclude pattern. """ for pattern in (exclude or self.exclude_pattern): if path.match(pattern): return True else: return False
def get_directories_with_extensions(self, start, extensions=None): """ Look for directories with image extensions in given directory and return a list with found dirs. .. note:: In deep file structures this might get pretty slow. """ return set([p.parent for ext in extensions for p in start.rglob(ext)])
def put_path(self, path): """ Given path identify in which environment the path belong to and append it. """ if self.is_package(path): logger.debug('PYTHON PACKAGE: {}'.format(path)) self.python_paths.append(path.parent) site.addsitedir(str(path.parent)) xbmdirs = self.get_directories_with_extensions( path, self.icon_e...
def traverse_path_for_valid_application_paths(self, top_path): """ For every path beneath top path that does not contain the exclude pattern look for python, mel and images and place them in their corresponding system environments. """ self.put_path(Path(top_path)) for p in self._walk(top_path): self.put_path(p)
def check_correct_host(self): """The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com """ if self._host == 'knoema.com': return url = self._get_url('/api/1.0/frontend/tags') req = urllib.request.Request(url) try: resp = url...
def get_dataset(self, datasetid): """The method is getting information about dataset byt it's id""" path = '/api/1.0/meta/dataset/{}' return self._api_get(definition.Dataset, path.format(datasetid))
def get_dimension(self, dataset, dimension): """The method is getting information about dimension with items""" path = '/api/1.0/meta/dataset/{}/dimension/{}' return self._api_get(definition.Dimension, path.format(dataset, dimension))
def get_daterange(self, dataset): """The method is getting information about date range of dataset""" path = '/api/1.0/meta/dataset/{}/daterange' return self._api_get(definition.DateRange, path.format(dataset))
def get_data(self, pivotrequest): """The method is getting data by pivot request""" path = '/api/1.0/data/pivot/' return self._api_post(definition.PivotResponse, path, pivotrequest)
def get_data_raw(self, request): """The method is getting data by raw request""" path = '/api/1.0/data/raw/' res = self._api_post(definition.RawDataResponse, path, request) token = res.continuation_token while token is not None: res2 = self.get_data_raw_with_token(token) res.series += res2.series token = res2.continuat...
def get_mnemonics (self, mnemonics): """The method get series by mnemonics""" path = '/api/1.0/data/mnemonics?mnemonics={0}' return self._api_get(definition.MnemonicsResponseList, path.format(mnemonics))
def upload_file(self, file): """The method is posting file to the remote server""" url = self._get_url('/api/1.0/upload/post') fcontent = FileContent(file) binary_data = fcontent.get_binary() headers = self._get_request_headers() req = urllib.request.Request(url, binary_data, headers) req.add_header('Content-type', fco...
def upload_verify(self, file_location, dataset=None): """This method is verifiing posted file on server""" path = '/api/1.0/upload/verify' query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location) if dataset: query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, data...
def upload_submit(self, upload_request): """The method is submitting dataset upload""" path = '/api/1.0/upload/save' return self._api_post(definition.DatasetUploadResponse, path, upload_request)
def upload_status(self, upload_id): """The method is checking status of uploaded dataset""" path = '/api/1.0/upload/status' query = 'id={}'.format(upload_id) return self._api_get(definition.DatasetUploadStatusResponse, path, query)
def upload(self, file_path, dataset=None, public=False): """Use this function to upload data to Knoema dataset.""" upload_status = self.upload_file(file_path) err_msg = 'Dataset has not been uploaded to the remote host' if not upload_status.successful: msg = '{}, because of the following error: {}'.format(err_msg, uplo...
break if ds_upload_result.status != 'successful': ver_err = '\r\n'.join(ds_upload_result.errors) msg = '{}, because of the following error(s): {}'.format(err_msg, ver_err) raise ValueError(msg) return ds_upload_result.dataset
def delete(self, dataset): """The method is deleting dataset by it's id""" url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset)) json_data = '' binary_data = json_data.encode() headers = self._get_request_headers() req = urllib.request.Request(url, binary_data, headers) resp = urllib.request.urlopen(re...
def verify(self, dataset, publication_date, source, refernce_url): """The method is verifying dataset by it's id""" path = '/api/1.0/meta/verifydataset' req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url) result = self._api_post(definition.DatasetVerifyResponse, path, req) if result.s...
def get_binary(self): """Return a binary buffer containing the file content""" content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"' stream = io.BytesIO() stream.write(_string_to_binary('--{}'.format(self.boundary))) stream.write(_crlf()) stream.write(_string_to_binary(content_disp.format(self.fil...
def _scratch_stream_name(self): """ A unique cache stream name for this QueryCache. Hashes the necessary facts about this QueryCache to generate a unique cache stream name. Different `query_function` implementations at different `bucket_width` values will be cached to different streams. TODO(marcua): This approach won'...
def _bucket_time(self, event_time): """ The seconds since epoch that represent a computed bucket. An event bucket is the time of the earliest possible event for that `bucket_width`. Example: if `bucket_width = timedelta(minutes=10)`, bucket times will be the number of seconds since epoch at 12:00, 12:10, ... on each da...
def _bucket_events(self, event_iterable): """ Convert an iterable of events into an iterable of lists of events per bucket. """ current_bucket_time = None current_bucket_events = None for event in event_iterable: event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD]) if current_bucket_time is None or current_buc...
def _cached_results(self, start_time, end_time): """ Retrieves cached results for any bucket that has a single cache entry. If a bucket has two cache entries, there is a chance that two different writers previously computed and cached a result since Kronos has no transaction semantics. While it might be safe to return ...
def compute_and_cache_missing_buckets(self, start_time, end_time, untrusted_time, force_recompute=False): """ Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. For any buckets where all events would...
untrusted_time=untrusted_time, force_recompute=force_recompute) for event in events: yield event
def retrieve_interval(self, start_time, end_time, compute_missing=False): """ Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. :param start_time: A datetime for the beginning of the range, aligned ...
def _execute(task): """A wrapper around exec This exists outside the Scheduler class because it is pickled after it is sent to the executor. """ print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id']) try: with get_app().app_context(): exec task['code'] in {}, {} print "[%s] -- %s -- COMPLETE" % (datetime.d...
def _loop(self, reader): """Main execution loop of the scheduler. The loop runs every second. Between iterations, the loop listens for schedule or cancel requests coming from Flask via over the gipc pipe (reader) and modifies the queue accordingly. When a task completes, it is rescheduled """ results = set() while True...
= int(task['interval']) if interval: run_at = now + datetime.timedelta(seconds=int(task['interval'])) self._schedule(task, next_run=run_at) else: err_msg = result.exception sys.stderr.write("ERROR: %s" % err_msg) email_msg = 'Task %s failed at %s\n\n%s' % ( task['id'], datetime.datetime.now(), err_msg ) send_mail(get_a...
def token_protected_endpoint(function): """Requires valid auth_token in POST to access An auth_token is built by sending a dictionary built from a Werkzeug.Request.form to the scheduler.auth.create_token function. """ @wraps(function) def decorated(*args, **kwargs): auth_token = request.form.get('auth_token') if not au...
def molmz(df, noise=10000): """ The mz of the molecular ion. """ d = ((df.values > noise) * df.columns).max(axis=1) return Trace(d, df.index, name='molmz')
def mzminus(df, minus=0, noise=10000): """ The abundances of ions which are minus below the molecular ion. """ mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus mol_ions[np.abs(mol_ions) < 0] = 0 d = np.abs(np.ones(df.shape) * df.columns - (mol_ions[np.newaxis].T * np.ones(df.shape))) < 1 d = (df.values...
def basemz(df): """ The mz of the most abundant ion. """ # returns the d = np.array(df.columns)[df.values.argmax(axis=1)] return Trace(d, df.index, name='basemz')
def coda(df, window, level): """ CODA processing from Windig, Phalp, & Payne 1996 Anal Chem """ # pull out the data d = df.values # smooth the data and standardize it smooth_data = movingaverage(d, df.index, window)[0] stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std() # scale the data to have unit len...
def tfclasses(): """ A mapping of mimetypes to every class for reading data files. """ # automatically find any subclasses of TraceFile in the same # directory as me classes = {} mydir = op.dirname(op.abspath(inspect.getfile(get_mimetype))) tfcls = {"<class 'aston.tracefile.TraceFile'>", "<class 'aston.tracefile.ScanLi...
def guess_initc(ts, f, rts=[]): """ ts - An AstonSeries that's being fitted with peaks f - The functional form of the peaks (e.g. gaussian) rts - peak maxima to fit; each number corresponds to one peak """ def find_side(y, loc=None): if loc is None: loc = y.argmax() ddy = np.diff(np.diff(y)) lft_loc, rgt_loc = loc - 2,...
ts.index, ts.values)) # sigma # peak_params['s'] = weight_mom(3, ts.index, ts.values) / sig ** 3 # peak_params['e'] = weight_mom(4, ts.index, ts.values) / sig ** 4 - 3 # TODO: better method of calculation of these? all_params = [] for rt in rts: peak_params = {'x': rt} # ts.index[ts.values.argmax()] top_idx = np.abs(ts...
def fit(ts, fs=[], all_params=[], fit_vars=None, alg='leastsq', make_bounded=True): """ Use a minimization algorithm to fit a AstonSeries with analytical functions. """ if fit_vars is None: fit_vars = [f._peakargs for f in fs] initc = [min(ts.values)] for f, peak_params, to_fit in zip(fs, all_params, fit_vars): if 'v' ...
else: fit_y += f(t, **peak_params) return fit_y - y def errfunc(p, t, y, all_params): return np.sum(errfunc_lsq(p, t, y, all_params) ** 2) if alg == 'simplex': fit_p, _ = fmin(errfunc, initc, args=(ts.index, ts.values, peak_params)) # elif alg == 'anneal': # fit_p, _ = anneal(errfunc, initc, args=(ts.index, ts.values, ...
fit_p.tolist() v = fit_pl.pop(0) # noqa fitted_params = [] for f, to_fit in zip(fs, fit_vars): fit_p_dict = {v: fit_pl.pop(0) for v in to_fit} # fit_p_dict['v'] = v if make_bounded and hasattr(f, '_pbounds'): fitted_params.append(_to_bound_p(fit_p_dict, f._pbounds)) else: fitted_params.append(fit_p_dict) # calculate r^...
def execute_greenlet_async(func, *args, **kwargs): """ Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`. """ global _GREENLET_EXECUTOR if _GREENLET_EXECUTOR is None: _GREENLET_EXECUTOR = GreenletExec...
def execute_process_async(func, *args, **kwargs): """ Executes `func` in a separate process. Memory and other resources are not available. This gives true concurrency at the cost of losing access to these resources. `args` and `kwargs` are """ global _GIPC_EXECUTOR if _GIPC_EXECUTOR is None: _GIPC_EXECUTOR = GIPCExecut...
def wait(results, num=None, timeout=None): """ Wait for results of async executions to become available/ready. `results`: List of AsyncResult instances returned by one of `execute_greenlet_async` or `execute_process_async`. `num`: Number of results to wait for. None implies wait for all results. `timeout`: Number of se...
def create(self, mention, max_message_length): """ Create a message :param mention: JSON object containing mention details from Twitter (or an empty dict {}) :param max_message_length: Maximum allowable length for created message :return: A random message created using a Markov chain generator """ message = [] def mess...
def receive(self, event_type, signature, data_str): """Receive a web hook for the event and signature. Args: event_type (str): Name of the event that was received (from the request ``X-HelpScout-Event`` header). signature (str): The signature that was received, which serves as authentication (from the request ``X-HelpS...
def validate_signature(self, signature, data, encoding='utf8'): """Validate the signature for the provided data. Args: signature (str or bytes or bytearray): Signature that was provided for the request. data (str or bytes or bytearray): Data string to validate against the signature. encoding (str, optional): If a strin...
def hook(name=None, priority=-1): """ Decorator """ def _hook(hook_func): return register_hook(name, hook_func=hook_func, priority=priority) return _hook
def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs): """ Train a doc2vec model on a list of files. """ kwargs = { 'size': 400, 'window': 8, 'min_count': 2, 'workers': 8 }.update(kwargs) n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for...
def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True): """ Generator to feed sentences to the dov2vec model. """ i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n) # We do minimal pre-processing here so the model can learn # punctuation li...
def open(self): """Open the device.""" self._serial.port = self._port self._serial.baudrate = self._baud self._serial.timeout = self._timeout self._serial.open() self._serial.flushInput() self._serial.flushOutput()
def _parse_info(line): """ The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] """ re_info = re.compile( r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1freq>\d+) ' + r'(?P<rfm1mode>.*)\)\]') info = { 'name': None, 'version': No...
def get_info(self): """Get current configuration info from 'v' command.""" re_info = re.compile(r'\[.*\]') self._write_cmd('v') while True: line = self._serial.readline() try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') match = re_info.match(line) if match: return self._parse...
def set_frequency(self, frequency, rfm=1): """Set frequency in kHz. The frequency can be set in 5kHz steps. """ cmds = {1: 'f', 2: 'F'} self._write_cmd('{}{}'.format(frequency, cmds[rfm]))
def set_datarate(self, rate, rfm=1): """Set datarate (baudrate).""" cmds = {1: 'r', 2: 'R'} self._write_cmd('{}{}'.format(rate, cmds[rfm]))
def set_toggle_interval(self, interval, rfm=1): """Set the toggle interval.""" cmds = {1: 't', 2: 'T'} self._write_cmd('{}{}'.format(interval, cmds[rfm]))
def set_toggle_mask(self, mode_mask, rfm=1): """Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed. """ cmds = {1: 'm', 2: 'M'} self._write_cmd('{}{}'.format(mode_mask, cmds[rfm]))
def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') if LaCrosseSensor.re_reading.match(lin...
def register_callback(self, sensorid, callback, user_data=None): """Register a callback for the specified sensor id.""" if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data))
def register_all(self, callback, user_data=None): """Register a callback for all sensors.""" self._callback = callback self._callback_data = user_data
def not_completed(f): """Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in """ @wraps(f) def check_if_complete(cls, *args, **kwargs): if cls.is_complete: raise FMBaseError('Transfer already completed.') return f(cls, *args, **kwargs) return check_if_complete
def _initialize(self): """Initialize transfer.""" payload = { 'apikey': self.session.cookies.get('apikey'), 'source': self.session.cookies.get('source') } if self.fm_user.logged_in: payload['logintoken'] = self.session.cookies.get('logintoken') payload.update(self.transfer_info) method, url = get_URL('init') res = geta...
def _parse_recipients(self, to): """Make sure we have a "," separated list of recipients :param to: Recipient(s) :type to: (str, list, :class:`pyfilemail.Contact`, :class:`pyfilemail.Group` ) :rtype: ``str`` """ if to is None: return None if isinstance(to, list): recipients = [] for recipient in to: if isinstance(recip...
def add_files(self, files): """Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list """ if isinstance(files, basestring): files = [files] zip_file = None if se...
def get_file_specs(self, filepath, keep_folders=False): """Gather information on files needed for valid transfer. :param filepath: Path to file in question :param keep_folders: Whether or not to maintain folder structure :type keep_folders: bool :type filepath: str, unicode :rtype: ``dict`` """ path, filename = os.path...
def get_files(self): """Get information on file in transfer from Filemail. :rtype: ``list`` of ``dict`` objects with info on files """ method, url = get_URL('get') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } res = geta...
def _get_zip_filename(self): """Create a filename for zip file when :class:Transfer.compress is set to ``True`` :rtype: str """ date = datetime.datetime.now().strftime('%Y_%m_%d-%H%M%S') zip_file = 'filemail_transfer_{date}.zip'.format(date=date) return zip_file
def send(self, auto_complete=True, callback=None): """Begin uploading file(s) and sending email(s). If `auto_complete` is set to ``False`` you will have to call the :func:`Transfer.complete` function at a later stage. :param auto_complete: Whether or not to mark transfer as complete and send emails to recipient(s) :par...
': ' if pm.COMMANDLINE: bar = ProgressBar(label=label, expected_size=fmfile['totalsize']) headers = {'Content-Type': m_encoder.content_type} res = self.session.post(url, params=fmfile, data=monitor, headers=headers) if res.status_code != 200: hellraiser(res) #logger.info('\r') if auto_complete: return self.complete() r...
def is_complete(self): """:rtype: ``bool`` ``True`` if transfer is complete""" if 'status' in self.transfer_info: self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE' return self._complete
def forward(self, to): """Forward prior transfer to new recipient(s). :param to: new recipients to a previous transfer. Use ``list`` or comma seperatde ``str`` or ``unicode`` list :type to: ``list`` or ``str`` or ``unicode`` :rtype: ``bool`` """ method, url = get_URL('forward') payload = { 'apikey': self.session.cookie...
def share(self, to, sender=None, message=None): """Share transfer with new message to new people. :param to: receiver(s) :param sender: Alternate email address as sender :param message: Meggase to new recipients :type to: ``list`` or ``str`` or ``unicode`` :type sender: ``str`` or ``unicode`` :type message: ``str`` or ...
def cancel(self): """Cancel the current transfer. :rtype: ``bool`` """ method, url = get_URL('cancel') payload = { 'apikey': self.config.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey') } res = getattr(self.session, method)(url, params=payload) if res.status_code == 20...
def rename_file(self, fmfile, newname): """Rename file in transfer. :param fmfile: file data from filemail containing fileid :param newname: new file name :type fmfile: ``dict`` :type newname: ``str`` or ``unicode`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMBaseError('fmfile must be a <dict>') metho...
def delete_file(self, fmfile): """Delete file from transfer. :param fmfile: file data from filemail containing fileid :type fmfile: ``dict`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMFileError('fmfile must be a <dict>') method, url = get_URL('file_delete') payload = { 'apikey': self.config.get('apik...
def update(self, message=None, subject=None, days=None, downloads=None, notify=None): """Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads al...
def download(self, files=None, destination=None, overwrite=False, callback=None): """Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) :param overwrite: replace existing files? :param callback: callback function that will receive tota...
def _download(self, fmfile, destination, overwrite, callback): """The actual downloader streaming content from Filemail. :param fmfile: to download :param destination: destination path :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arg...
chunk: break f.write(chunk) bytes_written += len(chunk) # Callback pg_callback(bytes_written)
def compress(self): """Compress files on the server side after transfer complete and make zip available for download. :rtype: ``bool`` """ method, url = get_URL('compress') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id } res = getat...
def from_pin(self, pin, timeout=5): """ Generate a sentence from PIN :param str pin: a string of digits :param float timeout: total time in seconds :return dict: { 'sentence': sentence corresponding to the PIN, 'overlap': overlapping positions, starting for 0 } >>> ToSentence().from_pin('3492') [("Helva's", False), ('m...
def from_keywords(self, keyword_list, strictness=2, timeout=3): """ Generate a sentence from initial_list. :param list keyword_list: a list of keywords to be included in the sentence. :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this f...
def _define_helper(flag_name, default_value, docstring, flagtype, required): """Registers 'flag_name' with 'default_value' and 'docstring'.""" option_name = flag_name if required else "--%s" % flag_name get_context_parser().add_argument( option_name, default=default_value, help=docstring, type=flagtype)
def DEFINE_string(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'string'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a string. docstring: A helpful message explaining the use of the flag. ""...
def DEFINE_integer(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag. """ _d...
def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name """Defines a flag of type 'boolean'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a boolean. docstring: A helpful message explaining the use of the flag. """ # Register ...
def DEFINE_float(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'float'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a float. docstring: A helpful message explaining the use of the flag. """ _...
def _get_subparsers(self, dest): """Get named subparsers.""" if not self._subparsers: self._subparsers = self.parser.add_subparsers(dest=dest) elif self._subparsers.dest != dest: raise KeyError( "Subparser names mismatch. You can only create one subcommand.") return self._subparsers
def get_subparser(self, name, dest="subcommand", **kwargs): """Get or create subparser.""" if name not in self.children: # Create the subparser. subparsers = self._get_subparsers(dest) parser = subparsers.add_parser(name, **kwargs) self.children[name] = NamedParser(name, parser) return self.children[name]
def build_attr_string(attrs, supported=True): '''Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table. ''' if not supported: return '' if type(attrs) == str: attrs = [attrs] result = '\033[' for attr in attrs: result += term_attributes[att...
def get_num_columns_and_rows(widths, gap_width, term_width): '''Given a list of string widths, a width of the minimum gap to place between them, and the maximum width of the output (such as a terminal width), calculate the number of columns and rows, and the width of each column, for the optimal layout. ''' def calc_lo...
0) # Start with one row ncols = len(widths) # Calculate the width of the longest row as the longest set of item widths # ncols long and gap widths (gap_width * ncols - 1) that fits within the # terminal width. while ncols > 0: longest_width, col_widths = calc_longest_width(widths, gap_width, ncols) if longest_width < t...
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '0000')) except ImportError: return None except IOError as e: return None return cr[1],...
def dict_to_nvlist(dict): '''Convert a dictionary into a CORBA namevalue list.''' result = [] for item in list(dict.keys()): result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item]))) return result
def nvlist_to_dict(nvlist): '''Convert a CORBA namevalue list into a dictionary.''' result = {} for item in nvlist : result[item.name] = item.value.value() return result
def filtered(path, filter): '''Check if a path is removed by a filter. Check if a path is in the provided set of paths, @ref filter. If none of the paths in filter begin with @ref path, then True is returned to indicate that the path is filtered out. If @ref path is longer than the filter, and starts with the filter, i...
def trim_filter(filter, levels=1): '''Trim @ref levels levels from the front of each path in @filter.''' trimmed = [f[levels:] for f in filter] return [f for f in trimmed if f]
def get(self, bug_number): """ Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will return a Bug object. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) """ ...
def put(self, bug): """ This method allows you to create or update a bug on Bugzilla. You will have had to pass in a valid username and password to the object initialisation and recieved back a token. :param bug: A Bug object either created by hand or by using get() If there is no valid token then a BugsyException will...