code stringlengths 1 18.2k |
|---|
not in self.weekend and date not in holidays: return date |
def is_work_day(self, date, division=None): """ True if the date is not a weekend or a known bank holiday :param date: the date to check :param division: see division constants; defaults to common holidays :return: bool """ return date.weekday() not in self.weekend and date not in ( holiday['date'] for holiday in self.... |
def get_all_regions_with_tiles(self): """ Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data """ for key in self.get_all_keys(): (layer, rx, ry) = struct.unpack('>BHH', key) if layer == 1: yield (rx, ry) |
def get_entity_uuid_coords(self, uuid): """ Returns the coordinates of the given entity UUID inside this world, or `None` if the UUID is not found. """ if uuid in self._entity_to_region_map: coords = self._entity_to_region_map[uuid] entities = self.get_entities(*coords) for entity in entities: if 'uniqueId' in entity.d... |
def _entity_to_region_map(self): """ A dict whose keys are the UUIDs (or just IDs, in some cases) of entities, and whose values are the `(rx, ry)` coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world. """ entity_to_region = {} for key in self.get_all_keys... |
stream = io.BytesIO(self.get(layer, rx, ry)) num_entities = sbon.read_varint(stream) for _ in range(num_entities): uuid = sbon.read_string(stream) if uuid in entity_to_region: raise ValueError('Duplicate UUID {}'.format(uuid)) entity_to_region[uuid] = (rx, ry) return entity_to_region |
def create_fuzzy_pattern(pattern): """ Convert a string into a fuzzy regular expression pattern. :param pattern: The input pattern (a string). :returns: A compiled regular expression object. This function works by adding ``.*`` between each of the characters in the input pattern and compiling the resulting expression i... |
def filtered_entries(self): """A list of :class:`PasswordEntry` objects that don't match the exclude list.""" return [ e for e in self.entries if not any(fnmatch.fnmatch(e.name.lower(), p.lower()) for p in self.exclude_list) ] |
def fuzzy_search(self, *filters): """ Perform a "fuzzy" search that matches the given characters in the given order. :param filters: The pattern(s) to search for. :returns: The matched password names (a list of strings). """ matches = [] logger.verbose( "Performing fuzzy search on %s (%s) ..", pluralize(len(filters), "... |
matches.append(entry) logger.log( logging.INFO if matches else logging.VERBOSE, "Matched %s using fuzzy search.", pluralize(len(matches), "password"), ) return matches |
def select_entry(self, *arguments): """ Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a password (a string) or :data:`None` (when no password matched the given `arguments`). """ matches = self.smart_search(*arguments) if len(matches) > 1: logger.i... |
return matches[0] |
def simple_search(self, *keywords): """ Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: The matched password names (a generator of strings). Only passwords whose names matches *all* of the given keywords are returned. """ matches = [] keywords = [k... |
) for entry in self.filtered_entries: normalized = entry.name.lower() if all(kw in normalized for kw in keywords): matches.append(entry) logger.log( logging.INFO if matches else logging.VERBOSE, "Matched %s using simple search.", pluralize(len(matches), "password"), ) return matches |
def smart_search(self, *arguments): """ Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: - :exc:`.NoMatchingPasswordError` when no matching passwo... |
produce any matches it will fall back to :func:`fuzzy_search()`. If no matches are found an exception is raised (see above). """ matches = self.simple_search(*arguments) if not matches: logger.verbose("Falling back from substring search to fuzzy search ..") matches = self.fuzzy_search(*arguments) if not matches: if len... |
any passwords yet! (no *.gpg files found)" raise EmptyPasswordStoreError(msg) return matches |
def entries(self): """A list of :class:`PasswordEntry` objects.""" passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name) |
def context(self): """ An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to the value of :attr:`directory`. - The environment ... |
self.ensure_directory_exists() # Prepare the environment variables. environment = {DIRECTORY_VARIABLE: self.directory} try: # Try to enable the GPG agent in headless sessions. environment.update(get_gpg_variables()) except Exception: # If we failed then let's at least make sure that the # $GPG_TTY environment variable ... |
def directory(self, value): """Normalize the value of :attr:`directory` when it's set.""" # Normalize the value of `directory'. set_property(self, "directory", parse_path(value)) # Clear the computed values of `context' and `entries'. clear_property(self, "context") clear_property(self, "entries") |
def entries(self): """A list of :class:`PasswordEntry` objects.""" timer = Timer() passwords = [] logger.info("Scanning %s ..", format_path(self.directory)) listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0") for filename in split(listing, "\0"): basename, extension = os.path.splitext(file... |
pluralize(len(passwords), "password"), timer) return natsort(passwords, key=lambda e: e.name) |
def ensure_directory_exists(self): """ Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist. """ if not os.path.isdir(self.directory): msg = "The password storage directory doesn't exist! (%s)" raise MissingPasswordStoreError(msg % self.directo... |
def format_text(self, include_password=True, use_colors=None, padding=True, filters=()): """ Format :attr:`text` for viewing on a terminal. :param include_password: :data:`True` to include the password in the formatted text, :data:`False` to exclude the password from the formatted text. :param use_colors: :data:`True` ... |
add empty lines before and after the entry and indent the entry's text with two spaces, :data:`False` to skip the padding. :param filters: An iterable of regular expression patterns (defaults to an empty tuple). If a line in the entry's text matches one of these patterns it won't be shown on the terminal. :returns: The... |
can use ANSI escape sequences. if use_colors is None: use_colors = terminal_supports_colors() # Extract the password (first line) from the entry. lines = self.text.splitlines() password = lines.pop(0).strip() # Compile the given patterns to case insensitive regular expressions # and use them to ignore lines that match ... |
in lines if not any(p.search(l) for p in patterns)] text = trim_empty_lines("\n".join(lines)) # Include the password in the formatted text? if include_password: text = "Password: %s\n%s" % (password, text) # Add the name to the entry (only when there's something to show). if text and not text.isspace(): title = " / ".j... |
text) # Highlight the entry's text using ANSI escape sequences. lines = [] for line in text.splitlines(): # Check for a "Key: Value" line. match = KEY_VALUE_PATTERN.match(line) if match: key = "%s:" % match.group(1).strip() value = match.group(2).strip() if use_colors: # Highlight the key. key = ansi_wrap(key, color=HI... |
tokens[i] = ansi_wrap(tokens[i], underline=True) # Replace the line with a highlighted version. line = key + " " + " ".join(tokens) if padding: line = " " + line lines.append(line) text = "\n".join(lines) text = trim_empty_lines(text) if text and padding: text = "\n%s\n" % text return text |
def get_diaginfo(diaginfo_file): """ Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- diaginfo_file : str Path to diaginfo.dat Returns ------- DataFrame containing the category information. """ widths = [rec.width for rec in diag_recs] col_... |
if not name.startswith('-')] diag_df = pd.read_fwf(diaginfo_file, widths=widths, names=col_names, dtypes=dtypes, comment="#", header=None, usecols=usecols) diag_desc = {diag.name: diag.desc for diag in diag_recs if not diag.name.startswith('-')} return diag_df, diag_desc |
def get_tracerinfo(tracerinfo_file): """ Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- tracerinfo_file : str Path to tracerinfo.dat Returns ------- DataFrame containing the tracer information. """ widths = [rec.width for rec in tracer_... |
if not name.startswith('-')] tracer_df = pd.read_fwf(tracerinfo_file, widths=widths, names=col_names, dtypes=dtypes, comment="#", header=None, usecols=usecols) # Check an edge case related to a bug in GEOS-Chem v12.0.3 which # erroneously dropped short/long tracer names in certain tracerinfo.dat outputs. # What we do h... |
tracer_df.dropna(subset=['tracer', 'scale']) only_na = tracer_df[~tracer_df.index.isin(na_free.index)] if len(only_na) > 0: warn("At least one row in {} wasn't decoded correctly; we strongly" " recommend you manually check that file to see that all" " tracers are properly recorded." .format(tracerinfo_file)) tracer_des... |
other diagnostics. def _assign_hydrocarbon(row): if row['C'] != 1: row['hydrocarbon'] = True row['molwt'] = C_MOLECULAR_WEIGHT else: row['hydrocarbon'] = False return row tracer_df = ( tracer_df .apply(_assign_hydrocarbon, axis=1) .assign(chemical=lambda x: x['molwt'].astype(bool)) ) return tracer_df, tracer_desc |
def read_from_bpch(filename, file_position, shape, dtype, endian, use_mmap=False): """ Read a chunk of data from a bpch output file. Parameters ---------- filename : str Path to file on disk containing the data file_position : int Position (bytes) where desired data chunk begins shape : tuple of ints Resultant (n-dimen... |
: dtype Dtype of data; for best results, pass a dtype which includes an endian indicator, e.g. `dtype = np.dtype('>f4')` endian : str Endianness of data; should be consistent with `dtype` use_mmap : bool Memory map the chunk of data to the file on disk, else read immediately Returns ------- Array with shape `shape` and... |
`filename`. """ offset = file_position + 4 if use_mmap: d = np.memmap(filename, dtype=dtype, mode='r', shape=shape, offset=offset, order='F') else: with FortranFile(filename, 'rb', endian) as ff: ff.seek(file_position) d = np.array(ff.readline('*f')) d = d.reshape(shape, order='F') # As a sanity check, *be sure* that t... |
{} does not have the right shape," " (expected {} but got {})" .format(filename, shape, d.shape)) return d |
def _read(self): """ Helper function to load the data referenced by this bundle. """ if self._dask: d = da.from_delayed( delayed(read_from_bpch, )( self.filename, self.file_position, self.shape, self.dtype, self.endian, use_mmap=self._mmap ), self.shape, self.dtype ) else: d = read_from_bpch( self.filename, self.file_p... |
def close(self): """ Close this bpch file. """ if not self.fp.closed: for v in list(self.var_data): del self.var_data[v] self.fp.close() |
def _read_metadata(self): """ Read the main metadata packaged within a bpch file, indicating the output filetype and its title. """ filetype = self.fp.readline().strip() filetitle = self.fp.readline().strip() # Decode to UTF string, if possible try: filetype = str(filetype, 'utf-8') filetitle = str(filetitle, 'utf-8') ... |
def _read_header(self): """ Process the header information (data model / grid spec) """ self._header_pos = self.fp.tell() line = self.fp.readline('20sffii') modelname, res0, res1, halfpolar, center180 = line self._attributes.update({ "modelname": str(modelname, 'utf-8').strip(), "halfpolar": halfpolar, "center180": cen... |
def _read_var_data(self): """ Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein. """ var_bundles = OrderedDict() var_attrs = OrderedDict() n_vars = 0 while self.fp.tell() < self.fsize: var_attr = OrderedDict() # read first and second h... |
number, unit, tau0, tau1, reserved = line[:6] dim0, dim1, dim2, dim3, dim4, dim5, skip = line[6:] var_attr['number'] = number # Decode byte-strings to utf-8 category_name = str(category_name, 'utf-8') var_attr['category'] = category_name.strip() unit = str(unit, 'utf-8') # get additional metadata from tracerinfo / diag... |
metadata match was made # if len(cat_df > 1): # raise ValueError( # "More than one category matching {} found in " # "diaginfo.dat".format( # category_name.strip() # ) # ) # Safe now to select the only row in the DataFrame cat = cat_df.T.squeeze() tracer_num = int(cat.offset) + int(number) diag_df = self.tracerinfo_df[... |
more than one # tracer metadata match was made # if len(diag_df > 1): # raise ValueError( # "More than one tracer matching {:d} found in " # "tracerinfo.dat".format(tracer_num) # ) # Safe now to select only row in the DataFrame diag = diag_df.T.squeeze() diag_attr = diag.to_dict() if not unit.strip(): # unit may be emp... |
tracerinfo var_attr.update(diag_attr) except: diag = {'name': '', 'scale': 1} var_attr.update(diag) var_attr['unit'] = unit vname = diag['name'] fullname = category_name.strip() + "_" + vname # parse metadata, get data or set a data proxy if dim2 == 1: data_shape = (dim0, dim1) # 2D field else: data_shape = (dim0, dim1... |
+ list(data_shape)) origin = (dim3, dim4, dim5) var_attr['origin'] = origin timelo, timehi = cf.tau2time(tau0), cf.tau2time(tau1) pos = self.fp.tell() # Note that we don't pass a dtype, and assume everything is # single-fp floats with the correct endian, as hard-coded var_bundle = BPCHDataBundle( data_shape, self.endia... |
final step if fullname in var_bundles: var_bundles[fullname].append(var_bundle) else: var_bundles[fullname] = [var_bundle, ] var_attrs[fullname] = var_attr n_vars += 1 self.var_data = var_bundles self.var_attrs = var_attrs |
def broadcast_1d_array(arr, ndim, axis=1): """ Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid. """ ext_arr = arr for i in range(ndim - 1): ext_a... |
def get_timestamp(time=True, date=True, fmt=None): """ Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the time/date choice and use as the format string... |
and date: fmt = time_format + " " + date_format elif time: fmt = time_format elif date: fmt = date_format else: raise ValueError("One of `date` or `time` must be True!") return datetime.now().strftime(fmt) |
def fix_attr_encoding(ds): """ This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer instead of a boolea... |
implicitly encoded. In future versions of this library, when upstream issues in decoding data wrapped in dask arrays is fixed, this won't be necessary and will be removed. """ def _maybe_del_attr(da, attr): """ Possibly delete an attribute on a DataArray if it's present """ if attr in da.attrs: del da.attrs[attr] retur... |
as attributes just fine """ Possibly coerce an attribute on a DataArray to an easier type to write to disk. """ # bool -> int if (attr in da.attrs) and (type(da.attrs[attr] == bool)): da.attrs[attr] = int(da.attrs[attr]) return da for v in ds.data_vars: da = ds[v] da = _maybe_del_attr(da, 'scale_factor') da = _maybe_de... |
attributes on time. if hasattr(ds, 'time'): times = ds.time times = _maybe_del_attr(times, 'units') return ds |
def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ if command_status not in range(256): raise ValueError("command_status must be an integer in the range 0-255") sys.stdout.write(AFTER_OUTPUT.format(command_status=command_stat... |
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry_title in orm.NewsEntryTitle.objects.all(): entry = NewsEntry.objects.get(pk=entry_title.entry.pk) entry.translate(entry_title.language) entry.title = entry_title.t... |
def get_cfcompliant_units(units, prefix='', suffix=''): """ Get equivalent units that are compatible with the udunits2 library (thus CF-compliant). Parameters ---------- units : string A string representation of the units. prefix : string Will be added at the beginning of the returned string (must be a valid udunits2 e... |
udunits2 expression). Returns ------- A string representation of the conforming units. References ---------- The udunits2 package : http://www.unidata.ucar.edu/software/udunits/ Notes ----- This function only relies on the table stored in :attr:`UNITS_MAP_CTM2CF`. Therefore, the units string returned by this function i... |
udunits in UNITS_MAP_CTM2CF: compliant_units = str.replace(compliant_units, gcunits, udunits) return prefix + compliant_units + suffix |
def get_valid_varname(varname): """ Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. Parameters ---------- varname : string variable name. Notes ----- Characters replacement is based on the table stored in :attr:`VARNAME_MAP_CHAR`. ""... |
def enforce_cf_variable(var, mask_and_scale=True): """ Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Parameters ---------- var ... |
the unit conversions provided Returns ------- out : xarray.Variable The original variable processed to conform to CF standards .. note:: This method borrows heavily from the ideas in ``xarray.decode_cf_variable`` """ var = as_variable(var) data = var._data # avoid loading by accessing _data instead of data dims = var.d... |
a "scale" value # for the units with this output. if 'scale' in attrs: scale = attrs.pop('scale') attrs['scale_factor'] = scale encoding['scale_factor'] = scale # TODO: Once the xr.decode_cf bug is fixed, we won't need to manually # handle masking/scaling if mask_and_scale: data = scale*data # Process units # TODO: How... |
udunits standard, and the CF conventions suggest using units # like 1e-6 for parts-per-million. But we potentially mix mass and # volume/molar mixing ratios in GEOS-Chem output, so we need a way # to handle that edge case. if 'unit' in attrs: unit = attrs.pop('unit') unit = get_cfcompliant_units(unit) attrs['units'] = ... |
# handle masking/scaling return Variable(dims, data, attrs, encoding=encoding) |
def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None): """ Returns all entries, which publication date has been hit or which have no date and which language matches the current language. """ if check_language: qs = NewsEntry.objects.language(language or get_language()).filter( is_pub... |
return qs.distinct().order_by('-pub_date') |
def recent(self, check_language=True, language=None, limit=3, exclude=None, kwargs=None, category=None): """ Returns recently published new entries. """ if category: if not kwargs: kwargs = {} kwargs['categories__in'] = [category] qs = self.published(check_language=check_language, language=language, kwargs=kwargs) if e... |
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 160: return u'{}...'.format(text... |
def render_news_placeholder(context, obj, name=False, truncate=False): # pragma: nocover # NOQA """ DEPRECATED: Template tag to render a placeholder from an NewsEntry object We don't need this any more because we don't have a placeholders M2M field on the model any more. Just use the default ``render_placeholder`` tag.... |
isinstance(name, int): # If the user doesn't want to use a placeholder name, but a cut, we # need to check if the user has used the name as a number truncate = name name = False if name: # If the name of the placeholder slot is given, get, render and # return it! try: result = safe(getattr(obj, name).render(context, No... |
else: # If no name is provided get the first placeholder with content for name in ['excerpt', 'content']: rendered = '' try: rendered = safe(getattr(obj, name).render(context, None)) except AttributeError: pass if rendered: result = rendered break if truncate: return truncatewords_html(result, truncate) return result |
def _requirement_filter_by_marker(req): # type: (pkg_resources.Requirement) -> bool """Check if the requirement is satisfied by the marker. This function checks for a given Requirement whether its environment marker is satisfied on the current platform. Currently only the python version and system platform are checked.... |
True |
def _requirement_find_lowest_possible(req): # type: (pkg_resources.Requirement) -> List[str] """Find lowest required version. Given a single Requirement, this function calculates the lowest required version to satisfy it. If the requirement excludes a specific version, then this version will not be used as the minimal ... |
""" version_dep = None # type: Optional[str] version_comp = None # type: Optional[str] for dep in req.specs: version = pkg_resources.parse_version(dep[1]) # we don't want to have a not supported version as minimal version if dep[0] == '!=': continue # try to use the lowest version available # i.e. for ">=0.8.4,>=0.9.7"... |
dep[0] assert (version_dep is None and version_comp is None) or \ (version_dep is not None and version_comp is not None) return [ x for x in (req.unsafe_name, version_comp, version_dep) if x is not None] |
def _requirements_sanitize(req_list): # type: (List[str]) -> List[str] """ Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info >>> _requirements_sanitize([ ... 'foo>... |
(pkg_resources.Requirement.parse(s) for s in req_list) if _requirement_filter_by_marker(req) ) return [" ".join(req) for req in filtered_req_list] |
def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """ if asyncio.iscoroutinefunction(func): return func else: @asyncio.coroutine def coroutine_function(evt): func(evt) yield return coroutine_functio... |
def location(self): """Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which is the UUID that at time of writing doesn't let you easily find the event). """ if self._location is None: self._location = "{}/{}-{}".format( self.stream, self... |
async def find_backwards(self, stream_name, predicate, predicate_label='predicate'): """Return first event matching predicate, or None if none exists. Note: 'backwards', both here and in Event Store, means 'towards the event emitted furthest in the past'. """ logger = self._logger.getChild(predicate_label) logger.info(... |
evt is not None: return evt uri = page.get_link("next") if uri is None: logger.warning("No matching event found") return None page = await self._fetcher.fetch(uri) |
def main(): """Command line interface for the ``qpass`` program.""" # Initialize logging to the terminal. coloredlogs.install() # Prepare for command line argument parsing. action = show_matching_entry program_opts = dict(exclude_list=[]) show_opts = dict(filters=[], use_clipboard=is_clipboard_supported()) verbosity = ... |
if option in ("-e", "--edit"): action = edit_matching_entry elif option in ("-l", "--list"): action = list_matching_entries elif option in ("-n", "--no-clipboard"): show_opts["use_clipboard"] = False elif option in ("-p", "--password-store"): stores = program_opts.setdefault("stores", []) stores.append(PasswordStore(di... |
elif option in ("-h", "--help"): usage(__doc__) return else: raise Exception("Unhandled option! (programming error)") if not (arguments or action == list_matching_entries): usage(__doc__) return except Exception as e: warning("Error: %s", e) sys.exit(1) # Execute the requested action. try: show_opts["quiet"] = verbosit... |
logger.error("%s", e) sys.exit(1) except KeyboardInterrupt: # If the user interrupted an interactive prompt they most likely did so # intentionally, so there's no point in generating more output here. sys.exit(1) |
def edit_matching_entry(program, arguments): """Edit the matching entry.""" entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name) |
def list_matching_entries(program, arguments): """List the entries matching the given keywords/patterns.""" output("\n".join(entry.name for entry in program.smart_search(*arguments))) |
def show_matching_entry(program, arguments, use_clipboard=True, quiet=False, filters=()): """Show the matching entry on the terminal (and copy the password to the clipboard).""" entry = program.select_entry(*arguments) if not quiet: formatted_entry = entry.format_text(include_password=not use_clipboard, filters=filters... |
def parse_parameters(payflowpro_response_data): """ Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects, and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will always be the Response object, ... |
the resulting dictionary probably indicates an error or oversight in the PayflowProObject definitions. """ def build_class(klass, unconsumed_data): known_att_names_set = set(klass.base_fields.keys()) available_atts_set = known_att_names_set.intersection(unconsumed_data) if available_atts_set: available_atts = dict() fo... |
in object.__class__.__subclasses__(PayflowProObject): obj = build_class(klass, unconsumed_data) if obj: result_objects.append(obj) # Special handling of RecurringPayments p_count = 1 payments = [] while ("p_result%d" % p_count) in unconsumed_data: payments.append(RecurringPayment( p_result = unconsumed_data.pop("p_resu... |
+= 1 if payments: result_objects.append(RecurringPayments(payments=payments)) return (result_objects, unconsumed_data,) |
def convert(document, canvas, items=None, tounicode=None): """ Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Return list ... |
items items = canvas.find_all() supported_item_types = \ set(["line", "oval", "polygon", "rectangle", "text", "arc"]) if tounicode is None: try: # python3 bytes tounicode = lambda x: x except NameError: # python2 tounicode = lambda text: str(text).encode("utf-8") elements = [] for item in items: # skip unsupported item... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.