Search is not available for this dataset
text
stringlengths
75
104k
def with_context(exc, context): # type: (Exception, dict) -> Exception """ Attaches a ``context`` value to an Exception. Before: .. code-block:: python exc = Exception('Frog blast the vent core!') exc.context = { ... } raise exc After: .. code-block:: python ...
def SecurityLevel(): """ Generates a filter chain for validating a security level. """ return ( f.Type(int) | f.Min(1) | f.Max(3) | f.Optional(default=AddressGenerator.DEFAULT_SECURITY_LEVEL) )
def as_tryte_string(self): # type: () -> TryteString """ Returns a TryteString representation of the transaction. """ if not self.bundle_hash: raise with_context( exc=RuntimeError( 'Cannot get TryteString representation of {cls} ins...
def increment_legacy_tag(self): """ Increments the transaction's legacy tag, used to fix insecure bundle hashes when finalizing a bundle. References: - https://github.com/iotaledger/iota.lib.py/issues/84 """ self._legacy_tag = ( Tag.from_trits(add_tr...
def tag(self): # type: () -> Tag """ Determines the most relevant tag for the bundle. """ for txn in reversed(self): # type: ProposedTransaction if txn.tag: return txn.tag return Tag(b'')
def add_transaction(self, transaction): # type: (ProposedTransaction) -> None """ Adds a transaction to the bundle. If the transaction message is too long, it will be split automatically into multiple transactions. """ if self.hash: raise RuntimeError...
def add_inputs(self, inputs): # type: (Iterable[Address]) -> None """ Adds inputs to spend in the bundle. Note that each input may require multiple transactions, in order to hold the entire signature. :param inputs: Addresses to use as the inputs for this bu...
def finalize(self): # type: () -> None """ Finalizes the bundle, preparing it to be attached to the Tangle. """ if self.hash: raise RuntimeError('Bundle is already finalized.') if not self: raise ValueError('Bundle has no transactions.') ...
def sign_inputs(self, key_generator): # type: (KeyGenerator) -> None """ Sign inputs in a finalized bundle. """ if not self.hash: raise RuntimeError('Cannot sign inputs until bundle is finalized.') # Use a counter for the loop so that we can skip ahead as we ...
def sign_input_at(self, start_index, private_key): # type: (int, PrivateKey) -> None """ Signs the input at the specified index. :param start_index: The index of the first input transaction. If necessary, the resulting signature will be split across ...
def _create_input_transactions(self, addy): # type: (Address) -> None """ Creates transactions for the specified input address. """ self._transactions.append(ProposedTransaction( address=addy, tag=self.tag, # Spend the entire address balance; ...
def convert_value_to_standard_unit(value, symbol='i'): # type: (Text, Text) -> float """ Converts between any two standard units of iota. :param value: Value (affixed) to convert. For example: '1.618 Mi'. :param symbol: Unit symbol of iota to convert to. For example: 'Gi'. :re...
def modular_squareroot_in_FQ2(value: FQ2) -> FQ2: """ ``modular_squareroot_in_FQ2(x)`` returns the value ``y`` such that ``y**2 % q == x``, and None if this is not possible. In cases where there are two solutions, the value with higher imaginary component is favored; if both solutions have equal ima...
def compress_G1(pt: G1Uncompressed) -> G1Compressed: """ A compressed point is a 384-bit integer with the bit order (c_flag, b_flag, a_flag, x), where the c_flag bit is always set to 1, the b_flag bit indicates infinity when set to 1, the a_flag bit helps determine the y-coordinate when decompressin...
def decompress_G1(z: G1Compressed) -> G1Uncompressed: """ Recovers x and y coordinates from the compressed point. """ # b_flag == 1 indicates the infinity point b_flag = (z % POW_2_383) // POW_2_382 if b_flag == 1: return Z1 x = z % POW_2_381 # Try solving y coordinate from the ...
def compress_G2(pt: G2Uncompressed) -> G2Compressed: """ The compressed point (z1, z2) has the bit order: z1: (c_flag1, b_flag1, a_flag1, x1) z2: (c_flag2, b_flag2, a_flag2, x2) where - c_flag1 is always set to 1 - b_flag1 indicates infinity when set to 1 - a_flag1 helps determine the y-...
def decompress_G2(p: G2Compressed) -> G2Uncompressed: """ Recovers x and y coordinates from the compressed point (z1, z2). """ z1, z2 = p # b_flag == 1 indicates the infinity point b_flag1 = (z1 % POW_2_383) // POW_2_382 if b_flag1 == 1: return Z2 x1 = z1 % POW_2_381 x2 = z...
def prime_field_inv(a: int, n: int) -> int: """ Extended euclidean algorithm to find modular inverses for integers """ if a == 0: return 0 lm, hm = 1, 0 low, high = a % n, n while low > 1: r = high // low nm, new = hm - lm * r, high - low * r lm, low, hm, high...
def from_json_file(cls, filename): """ Load a lexicon from a JSON file. Args: filename (str): The path to a JSON dump. """ with open(filename, 'r') as fp: return cls(json.load(fp))
def find_word_groups(self, text, category, proximity=2): """ Given a string and a category, finds and combines words into groups based on their proximity. Args: text (str): Some text. tokens (list): A list of regex strings. Returns: list. The...
def find_synonym(self, word): """ Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: >>> syn = {...
def expand_abbreviations(self, text): """ Parse a piece of text and replace any abbreviations with their full word equivalents. Uses the lexicon.abbreviations dictionary to find abbreviations. Args: text (str): The text to parse. Returns: str: Th...
def get_component(self, text, required=False, first_only=True): """ Takes a piece of text representing a lithologic description for one component, e.g. "Red vf-f sandstone" and turns it into a dictionary of attributes. TODO: Generalize this so that we can use any typ...
def split_description(self, text): """ Split a description into parts, each of which can be turned into a single component. """ # Protect some special sequences. t = re.sub(r'(\d) ?in\. ', r'\1 inch ', text) # Protect. t = re.sub(r'(\d) ?ft\. ', r'\1 feet ', t) ...
def categories(self): """ Lists the categories in the lexicon, except the optional categories. Returns: list: A list of strings of category names. """ keys = [k for k in self.__dict__.keys() if k not in SPECIAL] return keys
def _repr_html_(self): """ Jupyter Notebook magic repr function. """ rows, c = '', '' s = '<tr><td><strong>{k}</strong></td><td style="{stl}">{v}</td></tr>' for k, v in self.__dict__.items(): if k == '_colour': k = 'colour' c =...
def _repr_html_row_(self, keys): """ Jupyter Notebook magic repr function as a row – used by ``Legend._repr_html_()``. """ tr, th, c = '', '', '' r = '<td style="{stl}">{v}</td>' h = '<th>{k}</th>' for k in keys: v = self.__dict__.get(k) ...
def random(cls, component): """ Returns a minimal Decor with a random colour. """ colour = random.sample([i for i in range(256)], 3) return cls({'colour': colour, 'component': component, 'width': 1.0})
def plot(self, fmt=None, fig=None, ax=None): """ Make a simple plot of the Decor. Args: fmt (str): A Python format string for the component summaries. fig (Pyplot figure): A figure, optional. Use either fig or ax, not both. ax (Pyplot axis): A...
def _repr_html_(self): """ Jupyter Notebook magic repr function. """ all_keys = list(set(itertools.chain(*[d.keys for d in self]))) rows = '' for decor in self: th, tr = decor._repr_html_row_(keys=all_keys) rows += '<tr>{}</tr>'.format(tr) ...
def builtin(cls, name): """ Generate a default legend. Args: name (str): The name of the legend you want. Not case sensitive. 'nsdoe': Nova Scotia Dept. of Energy 'canstrat': Canstrat 'nagmdm__6_2': USGS N. Am. Geol. Map Data Model ...
def builtin_timescale(cls, name): """ Generate a default timescale legend. No arguments. Returns: Legend: The timescale stored in `defaults.py`. """ names = { 'isc': TIMESCALE__ISC, 'usgs_isc': TIMESCALE__USGS_ISC, '...
def random(cls, components, width=False, colour=None): """ Generate a random legend for a given list of components. Args: components (list or Striplog): A list of components. If you pass a Striplog, it will use the primary components. If you pass a co...
def from_image(cls, filename, components, ignore=None, col_offset=0.1, row_offset=2): """ A slightly easier way to make legends from images. Args: filename (str) components (list) ignore (list): Colours...
def from_csv(cls, filename=None, text=None): """ Read CSV text and generate a Legend. Args: string (str): The CSV string. In the first row, list the properties. Precede the properties of the component with 'comp ' or 'component '. For example: colour, widt...
def to_csv(self): """ Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV. """ # We can't delegate this to Decor because we need to know the superset # of all Decor properties. There may be lots of blanks. header...
def max_width(self): """ The maximum width of all the Decors in the Legend. This is needed to scale a Legend or Striplog when plotting with widths turned on. """ try: maximum = max([row.width for row in self.__list if row.width is not None]) return maximum...
def get_decor(self, c, match_only=None): """ Get the decor for a component. Args: c (component): The component to look up. match_only (list of str): The component attributes to include in the comparison. Default: All of them. Returns: Dec...
def getattr(self, c, attr, default=None, match_only=None): """ Get the attribute of a component. Args: c (component): The component to look up. attr (str): The attribute to get. default (str): What to return in the event of no match. match_only (list ...
def get_colour(self, c, default='#eeeeee', match_only=None): """ Get the display colour of a component. Wraps `getattr()`. Development note: Cannot define this as a `partial()` because I want to maintain the order of arguments in `getattr()`. Args: c ...
def get_width(self, c, default=0, match_only=None): """ Get the display width of a component. Wraps `getattr()`. Development note: Cannot define this as a `partial()` because I want to maintain the order of arguments in `getattr()`. Args: c (component): The componen...
def get_component(self, colour, tolerance=0, default=None): """ Get the component corresponding to a display colour. This is for generating a Striplog object from a colour image of a striplog. Args: colour (str): The hex colour string to look up. tolerance (float):...
def plot(self, fmt=None): """ Make a simple plot of the legend. Simply calls Decor.plot() on all of its members. TODO: Build a more attractive plot. """ for d in self.__list: d.plot(fmt=fmt) return None
def _repr_html_(self): """ Jupyter Notebook magic repr function. """ rows = '' s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>' for k, v in self.__dict__.items(): rows += s.format(k=k, v=v) html = '<table>{}</table>'.format(rows) return...
def from_text(cls, text, lexicon, required=None, first_only=True): """ Generate a Component from a text string, using a Lexicon. Args: text (str): The text string to parse. lexicon (Lexicon): The dictionary to use for the categories and lexemes. ...
def summary(self, fmt=None, initial=True, default=''): """ Given a format string, return a summary description of a component. Args: component (dict): A component dictionary. fmt (str): Describes the format with a string. If no format is given, you will j...
def Rock(*args, **kwargs): """ Graceful deprecation for old class name. """ with warnings.catch_warnings(): warnings.simplefilter("always") w = "The 'Rock' class was renamed 'Component'. " w += "Please update your code." warnings.warn(w, DeprecationWarning, stacklevel=2)...
def _process_row(text, columns): """ Processes a single row from the file. """ if not text: return # Construct the column dictionary that maps each field to # its start, its length, and its read and write functions. coldict = {k: {'start': s, 'len': l, ...
def parse_canstrat(text): """ Read all the rows and return a dict of the results. """ result = {} for row in text.split('\n'): if not row: continue if len(row) < 8: # Not a real record. continue # Read the metadata for this row/ row_header =...
def get_template(name): """ Still unsure about best way to do this, hence cruft. """ text = re.sub(r'\r\n', r'\n', name) text = re.sub(r'\{([FISDE°].*?)\}', r'{{\1}}', text) return text
def __strict(self): """ Private method. Checks if striplog is monotonically increasing in depth. Returns: Bool. """ def conc(a, b): return a + b # Check boundaries, b b = np.array(reduce(conc, [[i.top.z, i.base.z] for i in self]))...
def unique(self): """ Property. Summarize a Striplog with some statistics. Returns: List. A list of (Component, total thickness thickness) tuples. """ all_rx = set([iv.primary for iv in self]) table = {r: 0 for r in all_rx} for iv in self: ...
def top(self): """ Property. """ # For backwards compatibility. with warnings.catch_warnings(): warnings.simplefilter("always") w = "Striplog.top is deprecated; please use Striplog.unique" warnings.warn(w, DeprecationWarning, stacklevel=2) ...
def __intervals_from_tops(self, tops, values, basis, components, field=None, ignore_nan=True): """ Private method. Take a se...
def _clean_longitudinal_data(cls, data, null=None): """ Private function. Make sure we have what we need to make a striplog. """ # Rename 'depth' or 'MD' if ('top' not in data.keys()): data['top'] = data.pop('depth', data.pop('MD', None)) # Sort everything ...
def from_petrel(cls, filename, stop=None, points=False, null=None, function=None, include=None, exclude=None, remap=None, ignore=None): """ Mak...
def _build_list_of_Intervals(cls, data_dict, stop=None, points=False, include=None, exclude=None, ignore=None, ...
def from_csv(cls, filename=None, text=None, dlm=',', lexicon=None, points=False, include=None, exclude=None, remap=None, function=None, null=None, ign...
def from_descriptions(cls, text, lexicon=None, source='CSV', dlm=',', points=False, abbreviations=False, complete=False, order='depth', ...
def from_image(cls, filename, start, stop, legend, source="Image", col_offset=0.1, row_offset=2, tolerance=0): """ Read an image and generate Striplog. Args: filename (str): An image file, preferably high-re...
def from_img(cls, *args, **kwargs): """ For backwards compatibility. """ with warnings.catch_warnings(): warnings.simplefilter("always") w = "from_img() is deprecated; please use from_image()" warnings.warn(w) return cls.from_image(*args, **kwa...
def _from_array(cls, a, lexicon=None, source="", points=False, abbreviations=False): """ DEPRECATING. Turn an array-like into a Striplog. It should have the following format (where ``base`` is optional): ...
def from_log(cls, log, cutoff=None, components=None, legend=None, legend_field=None, field=None, right=False, basis=None, source='Log'): """ Turn a 1D array into a stri...
def from_las3(cls, string, lexicon=None, source="LAS", dlm=',', abbreviations=False): """ Turn LAS3 'lithology' section into a Striplog. Args: string (str): A section from an LAS3 file. lexicon (Lexicon): The language...
def from_canstrat(cls, filename, source='canstrat'): """ Eat a Canstrat DAT file and make a striplog. """ with open(filename) as f: dat = f.read() data = parse_canstrat(dat) list_of_Intervals = [] for d in data[7]: # 7 is the 'card type' for litholo...
def copy(self): """Returns a shallow copy.""" return Striplog([i.copy() for i in self], order=self.order, source=self.source)
def to_csv(self, filename=None, as_text=True, use_descriptions=False, dlm=",", header=True): """ Returns a CSV string built from the summaries of the Intervals. Args: use_descriptions (bool): Whether to use d...
def to_las3(self, use_descriptions=False, dlm=",", source="Striplog"): """ Returns an LAS 3.0 section string. Args: use_descriptions (bool): Whether to use descriptions instead of summaries, if available. dlm (str): The delimiter. source (str)...
def to_log(self, step=1.0, start=None, stop=None, basis=None, field=None, field_function=None, dtype=None, table=None, legend=None, legend_field=None, matc...
def plot_points(self, ax, legend=None, field=None, field_function=None, undefined=0, **kwargs): """ Plotting, but only for points (as opposed to intervals). """ ys = [iv.top.z for iv in s...
def plot_tops(self, ax, legend=None, field=None, **kwargs): """ Plotting, but only for tops (as opposed to intervals). """ if field is None: raise StriplogError('You must provide a field to plot.') ys = [iv.top.z for iv in self] try: try: ...
def plot_field(self, ax, legend=None, field=None, **kwargs): """ Plotting, but only for tops (as opposed to intervals). """ if field is None: raise StriplogError('You must provide a field to plot.') try: try: xs = [getattr(iv.primary, fiel...
def plot_axis(self, ax, legend, ladder=False, default_width=1, match_only=None, colour=None, colour_function=None, cmap=None, default=None, ...
def get_data(self, field, function=None, default=None): """ Get data from the striplog. """ f = function or utils.null data = [] for iv in self: d = iv.data.get(field) if d is None: if default is not None: d = de...
def plot(self, legend=None, width=1.5, ladder=True, aspect=10, ticks=(1, 10), match_only=None, ax=None, return_fig=False, colour=None, cmap='viridis', default=None, ...
def read_at(self, d, index=False): """ Get the index of the interval at a particular 'depth' (though this might be an elevation or age or anything). Args: d (Number): The 'depth' to query. index (bool): Whether to return the index instead of the interval. ...
def depth(self, d): """ For backwards compatibility. """ with warnings.catch_warnings(): warnings.simplefilter("always") w = "depth() is deprecated; please use read_at()" warnings.warn(w) return self.read_at(d)
def extract(self, log, basis, name, function=None): """ 'Extract' a log into the components of a striplog. Args: log (array_like). A log or other 1D data. basis (array_like). The depths or elevations of the log samples. name (str). The name of the attribute t...
def find(self, search_term, index=False): """ Look for a regex expression in the descriptions of the striplog. If there's no description, it looks in the summaries. If you pass a Component, then it will search the components, not the descriptions or summaries. Case inse...
def __find_incongruities(self, op, index): """ Private method. Finds gaps and overlaps in a striplog. Called by find_gaps() and find_overlaps(). Args: op (operator): ``operator.gt`` or ``operator.lt`` index (bool): If ``True``, returns indices of intervals with ...
def find_overlaps(self, index=False): """ Find overlaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the overlaps as intervals. """ return self.__f...
def find_gaps(self, index=False): """ Finds gaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the gaps. A sort of anti-striplog. """ return self.__...
def prune(self, limit=None, n=None, percentile=None, keep_ends=False): """ Remove intervals below a certain limit thickness. In place. Args: limit (float): Anything thinner than this will be pruned. n (int): The n thinnest beds will be pruned. percentile (flo...
def anneal(self): """ Fill in empty intervals by growing from top and base. Note that this operation happens in-place and destroys any information about the ``Position`` (e.g. metadata associated with the top or base). See GitHub issue #54. """ strip = self.copy(...
def fill(self, component=None): """ Fill gaps with the component provided. Example t = s.fill(Component({'lithology': 'cheese'})) """ c = [component] if component is not None else [] # Make the intervals to go in the gaps. gaps = self.find_gaps() ...
def union(self, other): """ Makes a striplog of all unions. Args: Striplog. The striplog instance to union with. Returns: Striplog. The result of the union. """ if not isinstance(other, self.__class__): m = "You can only union striplo...
def intersect(self, other): """ Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection. """ if not isinstance(other, self.__class__): m = "You ...
def merge_overlaps(self): """ Merges overlaps by merging overlapping Intervals. The function takes no arguments and returns ``None``. It operates on the striplog 'in place' TODO: This function will not work if any interval overlaps more than one other intervals at e...
def merge_neighbours(self, strict=True): """ Makes a new striplog in which matching neighbours (for which the components are the same) are unioned. That is, they are replaced by a new Interval with the same top as the uppermost and the same bottom as the lowermost. Args ...
def thickest(self, n=1, index=False): """ Returns the thickest interval(s) as a striplog. Args: n (int): The number of thickest intervals to return. Default: 1. index (bool): If True, only the indices of the intervals are returned. You can use this to ind...
def hist(self, lumping=None, summary=False, sort=True, plot=True, legend=None, ax=None ): """ Plots a histogram and returns the data for it. Args: lumping (str): If given, the bins will be lum...
def bar(self, height='thickness', sort=False, reverse=False, legend=None, ax=None, figsize=None, **kwargs): """ Make a bar plot of thickness per interval. Args: height (str): The property of the primary component to plot. sort (bool or function): Eith...
def invert(self, copy=False): """ Inverts the striplog, changing its order and the order of its contents. Operates in place by default. Args: copy (bool): Whether to operate in place or make a copy. Returns: None if operating in-place, or an inverted co...
def crop(self, extent, copy=False): """ Crop to a new depth range. Args: extent (tuple): The new start and stop depth. Must be 'inside' existing striplog. copy (bool): Whether to operate in place or make a copy. Returns: Operates in p...
def quality(self, tests, alias=None): """ Run a series of tests and return the corresponding results. Based on curve testing for ``welly``. Args: tests (list): a list of functions. Returns: list. The results. Stick to booleans (True = pass) or ints. ...
def dict_repr_html(dictionary): """ Jupyter Notebook magic repr function. """ rows = '' s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>' for k, v in dictionary.items(): rows += s.format(k=k, v=v) html = '<table>{}</table>'.format(rows) return html
def hex_to_name(hexx): """ Convert hex to a color name, using matplotlib's colour names. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: str: The name of the colour, or None if not found. """ for n, h in defaults.COLOURS.items(): if (len(n) > 1) and ...
def rgb_to_hex(rgb): """ Utility function to convert (r,g,b) triples to hex. http://ageo.co/1CFxXpO Args: rgb (tuple): A sequence of RGB values in the range 0-255 or 0-1. Returns: str: The hex code for the colour. """ r, g, b = rgb[:3] if (r < 0) or (g < 0) or (b < 0)...
def loglike_from_image(filename, offset): """ Get a log-like stream of RGB values from an image. Args: filename (str): The filename of a PNG image. offset (Number): If < 1, interpreted as proportion of way across the image. If > 1, interpreted as pixels from left. Returns: ...
def tops_from_loglike(a, offset=0, null=None): """ Take a log-like stream of numbers or strings, and return two arrays: one of the tops (changes), and one of the values from the stream. Args: loglike (array-like): The input stream of loglike data. offset (int): Offset (down) from top at...