code
stringlengths
1
18.2k
def alignXY(self): """aligns XY pairs (or XYYY etc) by X value.""" # figure out what data we have and will align to xVals=[] xCols=[x for x in range(self.nCols) if self.colTypes[x]==3] yCols=[x for x in range(self.nCols) if self.colTypes[x]==0] xCols,yCols=np.array(xCols),np.array(yCols) for xCol in xCols: xVals.extend...
for col in range(xCol+1,self.nCols): if self.colTypes[col]==0: columnsToShift.append(col) else: break # determine how to move each row for row in range(len(oldData)): oldXvalue=oldData[row,xCol] if oldXvalue in xVals: newRow=xVals.index(oldXvalue) newData[newRow,columnsToShift]=oldData[row,columnsToShift] # commit chan...
def wiggle(self,noiseLevel=.1): """Slightly changes value of every cell in the worksheet. Used for testing.""" noise=(np.random.rand(*self.data.shape))-.5 self.data=self.data+noise*noiseLevel
def pull(self,bookName=None,sheetName=None): """pull data into this OR.SHEET from a real book/sheet in Origin""" # tons of validation if bookName is None and self.bookName: bookName=self.bookName if sheetName is None and self.sheetName: sheetName=self.sheetName if bookName is None: bookName=OR.activeBook() if bookName ...
self.bookName=bookName self.sheetName=sheetName self.desc=poSheet.GetLongName() self.colNames=[poCol.GetName() for poCol in poSheet.Columns()] self.colDesc=[poCol.GetLongName() for poCol in poSheet.Columns()] self.colUnits=[poCol.GetUnits() for poCol in poSheet.Columns()] self.colComments=[poCol.GetComments() for poCol...
def push(self,bookName=None,sheetName=None,overwrite=False): """pull this OR.SHEET into a real book/sheet in Origin""" # tons of validation if bookName: self.bookName=bookName if sheetName: self.sheetName=sheetName if not self.sheetName in OR.sheetNames(bookName): print("can't find [%s]%s!"%(bookName,sheetName)) return...
assign properties to each for i in range(len(self.colNames)): poSheet.InsertCol(i,self.colNames[i]) poSheet.Columns(i).SetName(self.colNames[i]) poSheet.Columns(i).SetLongName(self.colDesc[i]) poSheet.Columns(i).SetUnits(self.colUnits[i]) poSheet.Columns(i).SetComments(self.colComments[i]) poSheet.Columns(i).SetType(se...
def nRows(self): """returns maximum number of rows based on the longest colData""" if self.nCols: return max([len(x) for x in self.colData]) else: return 0
def data(self): """return all of colData as a 2D numpy array.""" data=np.empty((self.nRows,self.nCols),dtype=np.float) data[:]=np.nan # make everything nan by default for colNum,colData in enumerate(self.colData): validIs=np.where([np.isreal(v) for v in colData])[0] validData=np.ones(len(colData))*np.nan validData[vali...
def data(self,data): """Given a 2D numpy array, fill colData with it.""" assert type(data) is np.ndarray assert data.shape[1] == self.nCols for i in range(self.nCols): self.colData[i]=data[:,i].tolist()
def focusout(self, event): """Change style on focus out events.""" bc = self.style.lookup("TEntry", "bordercolor", ("!focus",)) dc = self.style.lookup("TEntry", "darkcolor", ("!focus",)) lc = self.style.lookup("TEntry", "lightcolor", ("!focus",)) self.style.configure("%s.spinbox.TFrame" % self.frame, bordercolor=bc, da...
def focusin(self, event): """Change style on focus in events.""" self.old_value = self.get() bc = self.style.lookup("TEntry", "bordercolor", ("focus",)) dc = self.style.lookup("TEntry", "darkcolor", ("focus",)) lc = self.style.lookup("TEntry", "lightcolor", ("focus",)) self.style.configure("%s.spinbox.TFrame" % self.fr...
def open(self): """ Obtains the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError """ if not self.handle: try: path = self.system_dir except AttributeError: path = '' self.__handle = lvm_init(pat...
def close(self): """ Closes the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError """ if self.handle: q = lvm_quit(self.handle) if q != 0: raise HandleError("Failed to close LVM handle.") self.__...
def get_vg(self, name, mode="r"): """ Returns an instance of VolumeGroup. The name parameter should be an existing volume group. By default, all volume groups are open in "read" mode:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") To open a volume group with write permissions set the mode parameter to "w":: ...
*Args:* * name (str): An existing volume group name. * mode (str): "r" or "w" for read/write respectively. Default is "r". *Raises:* * HandleError """ vg = VolumeGroup(self, name=name, mode=mode) return vg
def create_vg(self, name, devices): """ Returns a new instance of VolumeGroup with the given name and added physycal volumes (devices):: from lvm2py import * lvm = LVM() vg = lvm.create_vg("myvg", ["/dev/sdb1", "/dev/sdb2"]) *Args:* * name (str): A volume group name. * devices (list): A list of device paths. *Raises:* ...
HandleError("Failed to create VG.") for device in devices: if not os.path.exists(device): self._destroy_vg(vgh) raise ValueError("%s does not exist." % device) ext = lvm_vg_extend(vgh, device) if ext != 0: self._destroy_vg(vgh) raise CommitError("Failed to extend Volume Group.") try: self._commit_vg(vgh) except CommitE...
def remove_vg(self, vg): """ Removes a volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lvm.remove_vg(vg) *Args:* * vg (obj): A VolumeGroup instance. *Raises:* * HandleError, CommitError .. note:: The VolumeGroup instance must be in write mode, otherwise CommitError is raised. """ vg.open() ...
com != 0: vg.close() raise CommitError("Failed to commit changes to disk.") vg.close()
def vgscan(self): """ Probes the system for volume groups and returns a list of VolumeGroup instances:: from lvm2py import * lvm = LVM() vgs = lvm.vgscan() *Raises:* * HandleError """ vg_list = [] self.open() names = lvm_list_vg_names(self.handle) if not bool(names): return vg_list vgnames = [] vg = dm_list_first(names...
vg = dm_list_next(names, vg) self.close() for name in vgnames: vginst = self.get_vg(name) vg_list.append(vginst) return vg_list
def from_file(cls, path): """ Create a text from a file. Args: path (str): The file path. """ with open(path, 'r', errors='replace') as f: return cls(f.read())
def load_stopwords(self, path): """ Load a set of stopwords. Args: path (str): The stopwords file path. """ if path: with open(path) as f: self.stopwords = set(f.read().splitlines()) else: self.stopwords = set( pkgutil .get_data('textplot', 'data/stopwords.txt') .decode('utf8') .splitlines() )
def tokenize(self): """ Tokenize the text. """ self.tokens = [] self.terms = OrderedDict() # Generate tokens. for token in utils.tokenize(self.text): # Ignore stopwords. if token['unstemmed'] in self.stopwords: self.tokens.append(None) else: # Token: self.tokens.append(token) # Term: offsets = self.terms.setdefault(tok...
def term_counts(self): """ Returns: OrderedDict: An ordered dictionary of term counts. """ counts = OrderedDict() for term in self.terms: counts[term] = len(self.terms[term]) return utils.sort_dict(counts)
def term_count_buckets(self): """ Returns: dict: A dictionary that maps occurrence counts to the terms that appear that many times in the text. """ buckets = {} for term, count in self.term_counts().items(): if count in buckets: buckets[count].append(term) else: buckets[count] = [term] return buckets
def most_frequent_terms(self, depth): """ Get the X most frequent terms in the text, and then probe down to get any other terms that have the same count as the last term. Args: depth (int): The number of terms. Returns: set: The set of frequent terms. """ counts = self.term_counts() # Get the top X terms and the instan...
= set(list(counts.keys())[:depth]) end_count = list(counts.values())[:depth][-1] # Merge in all other words with that appear that number of times, so # that we don't truncate the last bucket - eg, half of the words that # appear 5 times, but not the other half. bucket = self.term_count_buckets()[end_count] return top_t...
def unstem(self, term): """ Given a stemmed term, get the most common unstemmed variant. Args: term (str): A stemmed term. Returns: str: The unstemmed token. """ originals = [] for i in self.terms[term]: originals.append(self.tokens[i]['unstemmed']) mode = Counter(originals).most_common(1) return mode[0][0]
def kde(self, term, bandwidth=2000, samples=1000, kernel='gaussian'): """ Estimate the kernel density of the instances of term in the text. Args: term (str): A stemmed term. bandwidth (int): The kernel bandwidth. samples (int): The number of evenly-spaced sample points. kernel (str): The kernel function. Returns: np.ar...
density estimator on the terms. kde = KernelDensity(kernel=kernel, bandwidth=bandwidth).fit(terms) # Score an evely-spaced array of samples. x_axis = np.linspace(0, len(self.tokens), samples)[:, np.newaxis] scores = kde.score_samples(x_axis) # Scale the scores to integrate to 1. return np.exp(scores) * (len(self.tokens...
def score_intersect(self, term1, term2, **kwargs): """ Compute the geometric area of the overlap between the kernel density estimates of two terms. Args: term1 (str) term2 (str) Returns: float """ t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) # Integrate the overlap. overlap = np.minimum(t1_kde,...
def score_cosine(self, term1, term2, **kwargs): """ Compute a weighting score based on the cosine distance between the kernel density estimates of two terms. Args: term1 (str) term2 (str) Returns: float """ t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) return 1-distance.cosine(t1_kde, t2_kde)
def score_braycurtis(self, term1, term2, **kwargs): """ Compute a weighting score based on the "City Block" distance between the kernel density estimates of two terms. Args: term1 (str) term2 (str) Returns: float """ t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) return 1-distance.braycurtis(t1_k...
def plot_term_kdes(self, words, **kwargs): """ Plot kernel density estimates for multiple words. Args: words (list): A list of unstemmed terms. """ stem = PorterStemmer().stem for word in words: kde = self.kde(stem(word), **kwargs) plt.plot(kde) plt.show()
def generate(self, field_name, field): """Tries to lookup a matching formfield generator (lowercase field-classname) and raises a NotImplementedError of no generator can be found. """ if hasattr(self, 'generate_%s' % field.__class__.__name__.lower()): generator = getattr( self, 'generate_%s' % field.__class__.__name__....
def _fixIndex(self, index, truncate=False): """ @param truncate: If true, negative indices which go past the beginning of the list will be evaluated as zero. For example:: >>> L = List([1,2,3,4,5]) >>> len(L) 5 >>> L._fixIndex(-9, truncate=True) 0 """ assert not isinstance(index, slice), 'slices are not supported (yet)...
index out of range') else: index = 0 return index
def overlapping(startAttribute, # X endAttribute, # Y startValue, # A endValue, # B ): """ Return an L{axiom.iaxiom.IComparison} (an object that can be passed as the 'comparison' argument to Store.query/.sum/.count) which will constrain a query against 2 attributes for ranges which overlap with the given arguments. For...
|-------------------| (c) (d) |--------| (e) (f) |--------| (g) (h) |---| (i) (j) |------| (k) (l) |-------------------------------------| (a) (l) |-----------------------------| (c) (b) |------------------------| (c) (a) |----| (b) (l) |---------| The query:: myStore.query( O, findOverlapping(O.X, O.Y, a, b)) Will ret...
If you want to pass attributes of different classes for startAttribute and endAttribute, read the implementation of this method to discover the additional join clauses required. This may be eliminated some day so for now, consider this method undefined over multiple classes.) In the database where this query is run, fo...
must be less than endValue. """ assert startValue <= endValue return OR( AND(startAttribute >= startValue, startAttribute <= endValue), AND(endAttribute >= startValue, endAttribute <= endValue), AND(startAttribute <= startValue, endAttribute >= endValue) )
def _tupleCompare(tuple1, ineq, tuple2, eq=lambda a,b: (a==b), ander=AND, orer=OR): """ Compare two 'in-database tuples'. Useful when sorting by a compound key and slicing into the middle of that query. """ orholder = [] for limit in range(len(tuple1)): eqconstraint = [ eq(elem1, elem2) for elem1, elem2 in zip(tuple1, ...
def truncate_rationale(rationale, max_length=MAX_RATIONALE_SIZE_IN_EVENT): """ Truncates the rationale for analytics event emission if necessary Args: rationale (string): the string value of the rationale max_length (int): the max length for truncation Returns: truncated_value (string): the possibly truncated version o...
else: return rationale, False
def validate_options(options): """ Validate the options that course author set up and return errors in a dict if there is any """ errors = [] if int(options['rationale_size']['min']) < 1: errors.append(_('Minimum Characters')) if int(options['rationale_size']['max']) < 0 or int(options['rationale_size']['max']) > MAX_R...
try: if options['algo']['num_responses'] != '#' and int(options['algo']['num_responses']) < 0: errors.append(_('Number of Responses')) except ValueError: errors.append(_('Not an Integer')) if not errors: return None else: return {'options_error': _('Invalid Option(s): ') + ', '.join(errors)}
def get_student_item_dict(self, anonymous_user_id=None): """Create a student_item_dict from our surrounding context. See also: submissions.api for details. Args: anonymous_user_id(str): A unique anonymous_user_id for (user, course) pair. Returns: (dict): The student item associated with this XBlock instance. This inclu...
expediency for LMS integration if hasattr(self, "xmodule_runtime"): course_id = self.get_course_id() # pylint:disable=E1101 if anonymous_user_id: student_id = anonymous_user_id else: student_id = self.xmodule_runtime.anonymous_student_id # pylint:disable=E1101 else: course_id = "edX/Enchantment_101/April_1" if self.sco...
def get_answers_for_student(student_item): """ Retrieve answers from backend for a student and question Args: student_item (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. Returns: Answers: answers for the student """ submissions = sub_api.get_submission...
def add_answer_for_student(student_item, vote, rationale): """ Add an answer for a student to the backend Args: student_item (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. vote (int): the option that student voted for rationale (str): the reason why th...
})
def _safe_get(self, revision, key): """ Get an answer data (vote or rationale) by revision Args: revision (int): the revision number for student answer, could be 0 (original) or 1 (revised) key (str); key for retrieve answer data, could be VOTE_KEY or RATIONALE_KEY Returns: the answer data or None if revision doesn't e...
def add_answer(self, vote, rationale): """ Add an answer Args: vote (int): the option that student voted for rationale (str): the reason why the student vote for the option """ self.raw_answers.append({ VOTE_KEY: vote, RATIONALE_KEY: rationale, })
def exceptionToString(e,silent=False): """when you "except Exception as e", give me the e and I'll give you a string.""" exc_type, exc_obj, exc_tb = sys.exc_info() s=("\n"+"="*50+"\n") s+="EXCEPTION THROWN UNEXPECTEDLY\n" s+=" FILE: %s\n"%os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] s+=" LINE: %s\n"%exc_tb.tb_l...
def createNew(cls, store, pathSegments): """ Create a new SubStore, allocating a new file space for it. """ if isinstance(pathSegments, basestring): raise ValueError( 'Received %r instead of a sequence' % (pathSegments,)) if store.dbdir is None: self = cls(store=store, storepath=None) else: storepath = store.newDirecto...
def createStore(self, debug, journalMode=None): """ Create the actual Store this Substore represents. """ if self.storepath is None: self.store._memorySubstores.append(self) # don't fall out of cache if self.store.filesdir is None: filesdir = None else: filesdir = (self.store.filesdir.child("_substore_files") .child(st...
def upgradeCatalog1to2(oldCatalog): """ Create _TagName instances which version 2 of Catalog automatically creates for use in determining the tagNames result, but which version 1 of Catalog did not create. """ newCatalog = oldCatalog.upgradeVersion('tag_catalog', 1, 2, tagCount=oldCatalog.tagCount) tags = newCatalog.st...
def tagNames(self): """ Return an iterator of unicode strings - the unique tag names which have been applied objects in this catalog. """ return self.store.query(_TagName, _TagName.catalog == self).getColumn("name")
def tagsOf(self, obj): """ Return an iterator of unicode strings - the tag names which apply to the given object. """ return self.store.query( Tag, AND(Tag.catalog == self, Tag.object == obj)).getColumn("name")
def loaded(self, oself, dbval): """ This method is invoked when the item is loaded from the database, and when a transaction is reverted which restores this attribute's value. @param oself: an instance of an item which has this attribute. @param dbval: the underlying database value which was retrieved. """ setattr(osel...
def _convertPyval(self, oself, pyval): """ Convert a Python value to a value suitable for inserting into the database. @param oself: The object on which this descriptor is an attribute. @param pyval: The value to be converted. @return: A value legal for this column in the database. """ # convert to dbval later, I guess...
= %s()] must not be None" % ( self.classname, self.attrname, self.__class__.__name__)) return self.infilter(pyval, oself, oself.store)
def _queryContainer(self, store): """ Generate and cache the subselect SQL and its arguments. Return the subselect SQL. """ if self._subselectSQL is None: sql, args = self.container._sqlAndArgs('SELECT', self.container._queryTarget) self._subselectSQL, self._subselectArgs = sql, args return self._subselectSQL
def _sequenceContainer(self, store): """ Smash whatever we got into a list and save the result in case we are executed multiple times. This keeps us from tripping up over generators and the like. """ if self._sequence is None: self._sequence = list(self.container) self._clause = ', '.join(['?'] * len(self._sequence)) r...
def _sequenceArgs(self, store): """ Filter each element of the data using the attribute type being tested for containment and hand back the resulting list. """ self._sequenceContainer(store) # Force _sequence to be valid return [self.attribute.infilter(pyval, None, store) for pyval in self._sequence]
def prepareInsert(self, oself, store): """ Prepare for insertion into the database by making the dbunderlying attribute of the item a relative pathname with respect to the store rather than an absolute pathname. """ if self.relative: fspath = self.__get__(oself) oself.__dirty__[self.attrname] = self, self.infilter(fspa...
def restore(self, time=None): """ Undeletes the object. Returns True if undeleted, False if it was already not deleted """ if self.deleted: time = time if time else self.deleted_at if time == self.deleted_at: self.deleted = False self.save() return True else: return False return False
def full_restore(self, using=None): using = using or router.db_for_write(self.__class__, instance=self) restore_counter = Counter() if self.deleted: time = self.deleted_at else: return restore_counter self.collector = models.deletion.Collector(using=using) self.collector.collect([self]) for model, instances in self.col...
in instances: restore_counter.update([instance._meta.model_name]) instance.restore(time=time) return sum(restore_counter.values()), dict(restore_counter) """ Restores itself, as well as objects that might have been deleted along with it if cascade is the deletion strategy """ self.collector = models.deletion.Collector(...
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection...
Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region(re...
def parse(self, output): """ Find stems for a given text. """ output = self._get_lines_with_stems(output) words = self._make_unique(output) return self._parse_for_simple_stems(words)
def validlocations(configuration=None): # type: () -> List[Dict] """ Read valid locations from HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[Dict]: A list of valid locations """ if Locations._validlocations is None: if configuration is None: config...
def get_location_from_HDX_code(code, locations=None, configuration=None): # type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str] """Get location from HDX location code Args: code (str): code for which to get location name locations (Optional[List[Dict]]): Valid locations list. Defaults to list do...
== locdict['name'].upper(): return locdict['title'] return None
def get_HDX_code_from_location(location, locations=None, configuration=None): # type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str] """Get HDX code for location Args: location (str): Location for which to get HDX code locations (Optional[List[Dict]]): Valid locations list. Defaults to list downl...
in locations: locationcode = locdict['name'].upper() if locationupper == locationcode: return locationcode for locdict in locations: if locationupper == locdict['title'].upper(): return locdict['name'].upper() return None
def get_HDX_code_from_location_partial(location, locations=None, configuration=None): # type: (str, Optional[List[Dict]], Optional[Configuration]) -> Tuple[Optional[str], bool] """Get HDX code for location Args: location (str): Location for which to get HDX code locations (Optional[List[Dict]]): Valid locations list. D...
hdx_code = Locations.get_HDX_code_from_location(location, locations, configuration) if hdx_code is not None: return hdx_code, True if locations is None: locations = Locations.validlocations(configuration) locationupper = location.upper() for locdict in locations: locationname = locdict['title'].upper() if locationupper...
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser( description='Validates dtFabric format definitions.') argument_parser.add_argument( 'source', nargs='?', action='store', metavar='PATH', default=None, help=( 'path of the file or d...
print('') return False logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(message)s') source_is_directory = os.path.isdir(options.source) validator = DefinitionsValidator() if source_is_directory: source_description = os.path.join(options.source, '*.yaml') else: source_description = options.source print...
def CheckDirectory(self, path, extension='yaml'): """Validates definition files in a directory. Args: path (str): path of the definition file. extension (Optional[str]): extension of the filenames to read. Returns: bool: True if the directory contains valid definitions. """ result = True if extension: glob_spec = os.pa...
def CheckFile(self, path): """Validates the definition in a file. Args: path (str): path of the definition file. Returns: bool: True if the file contains valid definitions. """ print('Checking: {0:s}'.format(path)) definitions_registry = registry.DataTypeDefinitionsRegistry() definitions_reader = reader.YAMLDataTypeDef...
errors.FormatError as exception: logging.warning( 'Unable to validate file: {0:s} with error: {1:s}'.format( path, exception)) return result
def styleattribute(self, element): """ returns css.CSSStyleDeclaration of inline styles, for html: @style """ css_text = element.get('style') if css_text: return cssutils.css.CSSStyleDeclaration(cssText=css_text) else: return None
def get_configuration(filename): """ Read configuration file :type filename: str :param filename: Path to the configuration file """ logger.debug('Reading configuration from {}'.format(filename)) conf = SafeConfigParser() conf.read(filename) if not conf: logger.error('Configuration file {} not found'.format(filename)) ...
in config file: {}'.format(err)) sys.exit(1) return config
def inline_css(html_message, encoding='unicode'): """ Inlines all CSS in an HTML string Given an HTML document with CSS declared in the HEAD, inlines it into the applicable elements. Used primarily in the preparation of styled emails. Arguments: html_message -- a string of HTML, including CSS """ document = etree.HTML(...
def _CheckByteStreamSize(self, byte_stream, byte_offset, data_type_size): """Checks if the byte stream is large enough for the data type. Args: byte_stream (bytes): byte stream. byte_offset (int): offset into the byte stream where to start. data_type_size (int): data type size. Raises: ByteStreamTooSmallError: if the b...
as exception: raise errors.MappingError(exception) if byte_stream_size - byte_offset < data_type_size: raise errors.ByteStreamTooSmallError( 'Byte stream too small requested: {0:d} available: {1:d}'.format( data_type_size, byte_stream_size))
def _GetByteStreamOperation(self): """Retrieves the byte stream operation. Returns: ByteStreamOperation: byte stream operation or None if unable to determine. """ byte_order_string = self.GetStructByteOrderString() format_string = self.GetStructFormatString() # pylint: disable=assignment-from-none if not format_string:...
def GetStructByteOrderString(self): """Retrieves the Python struct format string. Returns: str: format string as used by Python struct or None if format string cannot be determined. """ if not self._data_type_definition: return None return self._BYTE_ORDER_STRINGS.get( self._data_type_definition.byte_order, None)
def FoldByteStream(self, mapped_value, **unused_kwargs): """Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded into the byte stream. """ try: value = self.FoldValue(mapped_value) return self._...
def MapByteStream( self, byte_stream, byte_offset=0, context=None, **unused_kwargs): """Maps the data type on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContext]): data type map context. Returns: object: ma...
self._operation.ReadFrom(byte_stream[byte_offset:]) mapped_value = self.MapValue(*struct_tuple) except Exception as exception: error_string = ( 'Unable to read: {0:s} from byte stream at offset: {1:d} ' 'with error: {2!s}').format( self._data_type_definition.name, byte_offset, exception) raise errors.MappingError(error...
def FoldValue(self, value): """Folds the data type into a value. Args: value (object): value. Returns: object: folded value. Raises: ValueError: if the data type definition cannot be folded into the value. """ if value is False and self._data_type_definition.false_value is not None: return self._data_type_definition.fa...
def GetStructFormatString(self): """Retrieves the Python struct format string. Returns: str: format string as used by Python struct or None if format string cannot be determined. """ if self._data_type_definition.format == definitions.FORMAT_UNSIGNED: return self._FORMAT_STRINGS_UNSIGNED.get( self._data_type_definition...
def FoldByteStream(self, mapped_value, **unused_kwargs): """Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded into the byte stream. """ value = None try: if self._byte_order == definitions.BY...