INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds a value over a range of rows.
def add(reader, writer, column, start, stop, value): """Adds a value over a range of rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. column: The column of data to modify. start: The first row in the range to modify. end: ...
Multiplies a value over a range of rows.
def scale(reader, writer, column, start, stop, multiple): """Multiplies a value over a range of rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. column: The column of data to modify. start: The first row in the range to modif...
Copies a range of values to a new location in the data set.
def copy(reader, writer, start, stop, insertLocation=None, tsCol=None): """Copies a range of values to a new location in the data set. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. start: The first row in the range to copy. stop:...
Samples n rows.
def sample(reader, writer, n, start=None, stop=None, tsCol=None, writeSampleOnly=True): """Samples n rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. n: The number of elements to sample. start: The first row in the ...
( helper function ) There are three different ways of thinking about the representation. Handle each case here.
def _initEncoder(self, w, minval, maxval, n, radius, resolution): """ (helper function) There are three different ways of thinking about the representation. Handle each case here.""" if n != 0: if (radius !=0 or resolution != 0): raise ValueError("Only one of n/radius/resolution can be speci...
Return the bit offset of the first bit to be set in the encoder output. For periodic encoders this can be a negative number when the encoded output wraps around.
def _getFirstOnBit(self, input): """ Return the bit offset of the first bit to be set in the encoder output. For periodic encoders, this can be a negative number when the encoded output wraps around. """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: if input < self.m...
See method description in base. py
def getBucketIndices(self, input): """ See method description in base.py """ if type(input) is float and math.isnan(input): input = SENTINEL_VALUE_FOR_MISSING_DATA if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] minbin = self._getFirstOnBit(input)[0] # For periodic encoder...
See method description in base. py
def encodeIntoArray(self, input, output, learn=True): """ See method description in base.py """ if input is not None and not isinstance(input, numbers.Number): raise TypeError( "Expected a scalar input but got input of type %s" % type(input)) if type(input) is float and math.isnan(input): ...
See the function description in base. py
def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ # For now, we simply assume any top-down output greater than 0 # is ON. Eventually, we will probably want to incorporate the strength # of each top-down output. tmpOutput = numpy.array(encoded[:self...
generate description from a text description of the ranges
def _generateRangeDescription(self, ranges): """generate description from a text description of the ranges""" desc = "" numRanges = len(ranges) for i in xrange(numRanges): if ranges[i][0] != ranges[i][1]: desc += "%.2f-%.2f" % (ranges[i][0], ranges[i][1]) else: desc += "%.2f"...
Return the interal _topDownMappingM matrix used for handling the bucketInfo () and topDownCompute () methods. This is a matrix one row per category ( bucket ) where each row contains the encoded output for that category.
def _getTopDownMapping(self): """ Return the interal _topDownMappingM matrix used for handling the bucketInfo() and topDownCompute() methods. This is a matrix, one row per category (bucket) where each row contains the encoded output for that category. """ # Do we need to build up our reverse ma...
See the function description in base. py
def getBucketValues(self): """ See the function description in base.py """ # Need to re-create? if self._bucketValues is None: topDownMappingM = self._getTopDownMapping() numBuckets = topDownMappingM.nRows() self._bucketValues = [] for bucketIdx in range(numBuckets): self._b...
See the function description in base. py
def getBucketInfo(self, buckets): """ See the function description in base.py """ # Get/generate the topDown mapping table #NOTE: although variable topDownMappingM is unused, some (bad-style) actions #are executed during _getTopDownMapping() so this line must stay here topDownMappingM = self._getTo...
See the function description in base. py
def topDownCompute(self, encoded): """ See the function description in base.py """ # Get/generate the topDown mapping table topDownMappingM = self._getTopDownMapping() # See which "category" we match the closest. category = topDownMappingM.rightVecProd(encoded).argmax() # Return that buck...
See the function description in base. py
def closenessScores(self, expValues, actValues, fractional=True): """ See the function description in base.py """ expValue = expValues[0] actValue = actValues[0] if self.periodic: expValue = expValue % self.maxval actValue = actValue % self.maxval err = abs(expValue - actValue) ...
Initialize all ephemeral members after being restored to a pickled state.
def _initEphemerals(self): """ Initialize all ephemeral members after being restored to a pickled state. """ ## We store the lists of segments updates, per cell, so that they can be # applied later during learning, when the cell gets bottom-up activation. # We store one list per cell. The lists ...
Populate serialization proto instance.
def write(self, proto): """Populate serialization proto instance. :param proto: (BacktrackingTMProto) the proto instance to populate """ proto.version = TM_VERSION self._random.write(proto.random) proto.numberOfCols = self.numberOfCols proto.cellsPerColumn = self.cellsPerColumn proto.in...
Deserialize from proto instance.
def read(cls, proto): """Deserialize from proto instance. :param proto: (BacktrackingTMProto) the proto instance to read from """ assert proto.version == TM_VERSION obj = object.__new__(cls) obj._random = Random() obj._random.read(proto.random) obj.numberOfCols = int(proto.numberOfCols)...
Reset the state of all cells.
def reset(self,): """ Reset the state of all cells. This is normally used between sequences while training. All internal states are reset to 0. """ if self.verbosity >= 3: print "\n==== RESET =====" self.lrnActiveState['t-1'].fill(0) self.lrnActiveState['t'].fill(0) self.lrnP...
Called at the end of learning and inference this routine will update a number of stats in our _internalStats dictionary including our computed prediction score.
def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState, colConfidence): """ Called at the end of learning and inference, this routine will update a number of stats in our _internalStats dictionary, including our computed prediction score. :param stats ...
Print an integer array that is the same shape as activeState.
def printState(self, aState): """ Print an integer array that is the same shape as activeState. :param aState: TODO: document """ def formatRow(var, i): s = '' for c in range(self.numberOfCols): if c > 0 and c % 10 == 0: s += ' ' s += str(var[c, i]) s += ...
Print a floating point array that is the same shape as activeState.
def printConfidence(self, aState, maxCols = 20): """ Print a floating point array that is the same shape as activeState. :param aState: TODO: document :param maxCols: TODO: document """ def formatFPRow(var, i): s = '' for c in range(min(maxCols, self.numberOfCols)): if c > 0...
Print up to maxCols number from a flat floating point array.
def printColConfidence(self, aState, maxCols = 20): """ Print up to maxCols number from a flat floating point array. :param aState: TODO: document :param maxCols: TODO: document """ def formatFPRow(var): s = '' for c in range(min(maxCols, self.numberOfCols)): if c > 0 and c ...
TODO: document: param printPrevious:: param printLearnState:: return:
def printStates(self, printPrevious = True, printLearnState = True): """ TODO: document :param printPrevious: :param printLearnState: :return: """ def formatRow(var, i): s = '' for c in range(self.numberOfCols): if c > 0 and c % 10 == 0: s += ' ' ...
TODO: document: param y:: return:
def printOutput(self, y): """ TODO: document :param y: :return: """ print "Output" for i in xrange(self.cellsPerColumn): for c in xrange(self.numberOfCols): print int(y[c, i]), print
TODO: document: param x:: return:
def printInput(self, x): """ TODO: document :param x: :return: """ print "Input" for c in xrange(self.numberOfCols): print int(x[c]), print
Print the parameter settings for the TM.
def printParameters(self): """ Print the parameter settings for the TM. """ print "numberOfCols=", self.numberOfCols print "cellsPerColumn=", self.cellsPerColumn print "minThreshold=", self.minThreshold print "newSynapseCount=", self.newSynapseCount print "activationThreshold=", self.act...
Print the list of [ column cellIdx ] indices for each of the active cells in state.
def printActiveIndices(self, state, andValues=False): """ Print the list of ``[column, cellIdx]`` indices for each of the active cells in state. :param state: TODO: document :param andValues: TODO: document """ if len(state.shape) == 2: (cols, cellIdxs) = state.nonzero() else: ...
Called at the end of inference to print out various diagnostic information based on the current verbosity level.
def printComputeEnd(self, output, learn=False): """ Called at the end of inference to print out various diagnostic information based on the current verbosity level. :param output: TODO: document :param learn: TODO: document """ if self.verbosity >= 3: print "----- computeEnd summary: ...
TODO: document: param c:: param i:: param onlyActiveSegments:: return:
def printCell(self, c, i, onlyActiveSegments=False): """ TODO: document :param c: :param i: :param onlyActiveSegments: :return: """ if len(self.cells[c][i]) > 0: print "Column", c, "Cell", i, ":", print len(self.cells[c][i]), "segment(s)" for j, s in enumerate...
TODO: document: param predictedOnly:: return:
def printCells(self, predictedOnly=False): """ TODO: document :param predictedOnly: :return: """ if predictedOnly: print "--- PREDICTED CELLS ---" else: print "--- ALL CELLS ---" print "Activation threshold=", self.activationThreshold, print "min threshold=", self....
: param c: ( int ) column index: param i: ( int ) cell index in column: param segIdx: ( int ) segment index to match
def getSegmentOnCell(self, c, i, segIdx): """ :param c: (int) column index :param i: (int) cell index in column :param segIdx: (int) segment index to match :returns: (list) representing the the segment on cell (c, i) with index ``segIdx``. :: [ [segmentID, sequenceSegme...
Store a dated potential segment update. The date ( iteration index ) is used later to determine whether the update is too old and should be forgotten. This is controlled by parameter segUpdateValidDuration.
def _addToSegmentUpdates(self, c, i, segUpdate): """ Store a dated potential segment update. The "date" (iteration index) is used later to determine whether the update is too old and should be forgotten. This is controlled by parameter ``segUpdateValidDuration``. :param c: TODO: document :param...
Computes output for both learning and inference. In both cases the output is the boolean OR of activeState and predictedState at t. Stores currentOutput for checkPrediction.: returns: TODO: document
def _computeOutput(self): """ Computes output for both learning and inference. In both cases, the output is the boolean OR of ``activeState`` and ``predictedState`` at ``t``. Stores ``currentOutput`` for ``checkPrediction``. :returns: TODO: document """ # TODO: This operation can be spe...
This function gives the future predictions for <nSteps > timesteps starting from the current TM state. The TM is returned to its original state at the end before returning.
def predict(self, nSteps): """ This function gives the future predictions for <nSteps> timesteps starting from the current TM state. The TM is returned to its original state at the end before returning. 1. We save the TM state. 2. Loop for nSteps a. Turn-on with lateral support from the...
Parameters: -------------------------------------------- retval: A dict with all the dynamic state variable names as keys and their values at this instant as values.
def _getTPDynamicState(self,): """ Parameters: -------------------------------------------- retval: A dict with all the dynamic state variable names as keys and their values at this instant as values. """ tpDynamicState = dict() for variableName in self._getTPDynamicS...
Set all the dynamic state variables from the <tpDynamicState > dict.
def _setTPDynamicState(self, tpDynamicState): """ Set all the dynamic state variables from the <tpDynamicState> dict. <tpDynamicState> dict has all the dynamic state variable names as keys and their values at this instant as values. We set the dynamic state variables in the tm object with these it...
Update our moving average of learned sequence length.
def _updateAvgLearnedSeqLength(self, prevSeqLength): """Update our moving average of learned sequence length.""" if self.lrnIterationIdx < 100: alpha = 0.5 else: alpha = 0.1 self.avgLearnedSeqLength = ((1.0 - alpha) * self.avgLearnedSeqLength + (alpha * prevS...
This backtracks our inference state trying to see if we can lock onto the current set of inputs by assuming the sequence started up to N steps ago on start cells.
def _inferBacktrack(self, activeColumns): """ This "backtracks" our inference state, trying to see if we can lock onto the current set of inputs by assuming the sequence started up to N steps ago on start cells. This will adjust @ref infActiveState['t'] if it does manage to lock on to a sequenc...
Update the inference active state from the last set of predictions and the current bottom - up.
def _inferPhase1(self, activeColumns, useStartCells): """ Update the inference active state from the last set of predictions and the current bottom-up. This looks at: - ``infPredictedState['t-1']`` This modifies: - ``infActiveState['t']`` :param activeColumns: (list) active bot...
Phase 2 for the inference state. The computes the predicted state then checks to insure that the predicted state is not over - saturated i. e. look too close like a burst. This indicates that there were so many separate paths learned from the current input columns to the predicted input columns that bursting on the cur...
def _inferPhase2(self): """ Phase 2 for the inference state. The computes the predicted state, then checks to insure that the predicted state is not over-saturated, i.e. look too close like a burst. This indicates that there were so many separate paths learned from the current input columns to the p...
Update the inference state. Called from: meth: compute on every iteration.
def _updateInferenceState(self, activeColumns): """ Update the inference state. Called from :meth:`compute` on every iteration. :param activeColumns: (list) active column indices. """ # Copy t to t-1 self.infActiveState['t-1'][:, :] = self.infActiveState['t'][:, :] self.infPredictedState['t...
A utility method called from learnBacktrack. This will backtrack starting from the given startOffset in our prevLrnPatterns queue.
def _learnBacktrackFrom(self, startOffset, readOnly=True): """ A utility method called from learnBacktrack. This will backtrack starting from the given startOffset in our prevLrnPatterns queue. It returns True if the backtrack was successful and we managed to get predictions all the way up to the c...
This backtracks our learning state trying to see if we can lock onto the current set of inputs by assuming the sequence started up to N steps ago on start cells.
def _learnBacktrack(self): """ This "backtracks" our learning state, trying to see if we can lock onto the current set of inputs by assuming the sequence started up to N steps ago on start cells. This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a sequence that started e...
Compute the learning active state given the predicted state and the bottom - up input.
def _learnPhase1(self, activeColumns, readOnly=False): """ Compute the learning active state given the predicted state and the bottom-up input. :param activeColumns list of active bottom-ups :param readOnly True if being called from backtracking logic. This tells us no...
Compute the predicted segments given the current set of active cells.
def _learnPhase2(self, readOnly=False): """ Compute the predicted segments given the current set of active cells. :param readOnly True if being called from backtracking logic. This tells us not to increment any segment duty cycles or queue up any up...
Update the learning state. Called from compute () on every iteration: param activeColumns List of active column indices
def _updateLearningState(self, activeColumns): """ Update the learning state. Called from compute() on every iteration :param activeColumns List of active column indices """ # Copy predicted and active states into t-1 self.lrnPredictedState['t-1'][:, :] = self.lrnPredictedState['t'][:, :] se...
Handle one compute possibly learning.
def compute(self, bottomUpInput, enableLearn, enableInference=None): """ Handle one compute, possibly learning. .. note:: It is an error to have both ``enableLearn`` and ``enableInference`` set to False .. note:: By default, we don't compute the inference output when learning ...
TODO: document
def learn(self, bottomUpInput, enableInference=None): """ TODO: document :param bottomUpInput: :param enableInference: :return: """ return self.compute(bottomUpInput, enableLearn=True, enableInference=enableInference)
This method goes through a list of segments for a given cell and deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining.
def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence, minNumSyns): """ This method goes through a list of segments for a given cell and deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns syna...
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining.
def trimSegments(self, minPermanence=None, minNumSyns=None): """ This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. :param minPermanence: (float) Any syn whose permanence is 0 or < ``mi...
Removes any update that would be for the given col cellIdx segIdx.
def _cleanUpdatesList(self, col, cellIdx, seg): """ Removes any update that would be for the given col, cellIdx, segIdx. NOTE: logically, we need to do this when we delete segments, so that if an update refers to a segment that was just deleted, we also remove that update from the update list. Howe...
Called when learning has been completed. This method just calls: meth: trimSegments and then clears out caches.
def finishLearning(self): """ Called when learning has been completed. This method just calls :meth:`trimSegments` and then clears out caches. """ # Keep weakly formed synapses around because they contain confidence scores # for paths out of learned sequenced and produce a better prediction than...
Find weakly activated cell in column with at least minThreshold active synapses.
def _getBestMatchingCell(self, c, activeState, minThreshold): """ Find weakly activated cell in column with at least minThreshold active synapses. :param c which column to look at :param activeState the active cells :param minThreshold minimum number of synapses required :retur...
For the given cell find the segment with the largest number of active synapses. This routine is aggressive in finding the best match. The permanence value of synapses is allowed to be below connectedPerm. The number of active synapses is allowed to be below activationThreshold but must be above minThreshold. The routin...
def _getBestMatchingSegment(self, c, i, activeState): """ For the given cell, find the segment with the largest number of active synapses. This routine is aggressive in finding the best match. The permanence value of synapses is allowed to be below connectedPerm. The number of active synapses is all...
Return the index of a cell in this column which is a good candidate for adding a new segment.
def _getCellForNewSegment(self, colIdx): """ Return the index of a cell in this column which is a good candidate for adding a new segment. When we have fixed size resources in effect, we insure that we pick a cell which does not already have the max number of allowed segments. If none exists, w...
Return a segmentUpdate data structure containing a list of proposed changes to segment s. Let activeSynapses be the list of active synapses where the originating cells have their activeState output = 1 at time step t. ( This list is empty if s is None since the segment doesn t exist. ) newSynapses is an optional argume...
def _getSegmentActiveSynapses(self, c, i, s, activeState, newSynapses=False): """ Return a segmentUpdate data structure containing a list of proposed changes to segment s. Let activeSynapses be the list of active synapses where the originating cells have their activeState output = 1 at time step t. ...
Choose n random cells to learn from.
def _chooseCellsToLearnFrom(self, c, i, s, n, activeState): """ Choose n random cells to learn from. This function is called several times while learning with timeStep = t-1, so we cache the set of candidates for that case. It's also called once with timeStep = t, and we cache that set of candidate...
Go through the list of accumulated segment updates and process them as follows:
def _processSegmentUpdates(self, activeColumns): """ Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update else if the cell received bottom-up, update its permanences else if it's still being predicted, leave it in th...
This function applies segment update information to a segment in a cell.
def _adaptSegment(self, segUpdate): """ This function applies segment update information to a segment in a cell. Synapses on the active list get their permanence counts incremented by permanenceInc. All other synapses get their permanence counts decremented by permanenceDec. We also increm...
Compute/ update and return the positive activations duty cycle of this segment. This is a measure of how often this segment is providing good predictions.
def dutyCycle(self, active=False, readOnly=False): """Compute/update and return the positive activations duty cycle of this segment. This is a measure of how often this segment is providing good predictions. :param active True if segment just provided a good prediction :param readOnly If True, c...
Add a new synapse
def addSynapse(self, srcCellCol, srcCellIdx, perm): """Add a new synapse :param srcCellCol source cell column :param srcCellIdx source cell index within the column :param perm initial permanence """ self.syns.append([int(srcCellCol), int(srcCellIdx), numpy.float32(perm)])
Returns a closure suitable for use as function/ method decorator for logging exceptions that leave the scope of the decorated function. Exceptions are logged at ERROR level.
def logExceptions(logger=None): """ Returns a closure suitable for use as function/method decorator for logging exceptions that leave the scope of the decorated function. Exceptions are logged at ERROR level. logger: user-supplied logger instance. Defaults to logging.getLogger. Usage Example: NOTE: l...
Returns a closure suitable for use as function/ method decorator for logging entry/ exit of function/ method.
def logEntryExit(getLoggerCallback=logging.getLogger, entryExitLogLevel=logging.DEBUG, logArgs=False, logTraceback=False): """ Returns a closure suitable for use as function/method decorator for logging entry/exit of function/method. getLoggerCallback: user-supplied callback ...
Returns a closure suitable for use as function/ method decorator for retrying a function being decorated.
def retry(timeoutSec, initialRetryDelaySec, maxRetryDelaySec, retryExceptions=(Exception,), retryFilter=lambda e, args, kwargs: True, logger=None, clientLabel=""): """ Returns a closure suitable for use as function/method decorator for retrying a function being decorated. timeoutSec...
Very simple patterns. Each pattern has numOnes consecutive bits on. The amount of overlap between consecutive patterns is configurable via the patternOverlap parameter.
def getSimplePatterns(numOnes, numPatterns, patternOverlap=0): """Very simple patterns. Each pattern has numOnes consecutive bits on. The amount of overlap between consecutive patterns is configurable, via the patternOverlap parameter. Parameters: -------------------------------------------------------------...
Create training sequences that share some elements in the middle.
def buildOverlappedSequences( numSequences = 2, seqLen = 5, sharedElements = [3,4], numOnBitsPerPattern = 3, patternOverlap = 0, seqOverlap = 0, ...
Create a bunch of sequences of various lengths all built from a fixed set of patterns.
def buildSequencePool(numSequences = 10, seqLen = [2,3,4], numPatterns = 5, numOnBitsPerPattern = 3, patternOverlap = 0, **kwargs ): """ Create a bunch of sequences of various lengths, a...
Create one or more TM instances placing each into a dict keyed by name.
def createTMs(includeCPP = True, includePy = True, numCols = 100, cellsPerCol = 4, activationThreshold = 3, minThreshold = 3, newSynapseCount = 3, initialPerm = 0.6, permanenceInc = 0.1, permane...
Check for diffs among the TM instances in the passed in tms dict and raise an assert if any are detected
def assertNoTMDiffs(tms): """ Check for diffs among the TM instances in the passed in tms dict and raise an assert if any are detected Parameters: --------------------------------------------------------------------- tms: dict of TM instances """ if len(tms) == 1: return if len(...
Train the TMs on the entire training set for nTrainRepetitions in a row. Then run the test set through inference once and return the inference stats.
def evalSequences(tms, trainingSequences, testSequences = None, nTrainRepetitions = 1, doResets = True, **kwargs): """Train the TMs on the entire training set for nTrainRepetitions in a row. Then run the test set through infe...
Decide whether a particular character needs to be quoted.
def needsquoting(c, quotetabs, header): """Decide whether a particular character needs to be quoted. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. """ if c in ' \t': return qu...
Quote a single character.
def quote(c): """Quote a single character.""" i = ord(c) return ESCAPE + HEX[i//16] + HEX[i%16]
Read input apply quoted - printable encoding and write to output.
def encode(input, output, quotetabs, header = 0): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs an...
Read input apply quoted - printable decoding and write to output. input and output are files with readline () and write () methods. If header is true decode underscore as space ( per RFC 1522 ).
def decode(input, output, header = 0): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() ...
Get the integer value of a hexadecimal number.
def unhex(s): """Get the integer value of a hexadecimal number.""" bits = 0 for c in s: if '0' <= c <= '9': i = ord('0') elif 'a' <= c <= 'f': i = ord('a')-10 elif 'A' <= c <= 'F': i = ord('A')-10 else: break bits = bits...
Encode a string using Base64.
def b64encode(s, altchars=None): """Encode a string using Base64. s is the string to encode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. gener...
Decode a Base64 encoded string.
def b64decode(s, altchars=None): """Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is ret...
Encode a string using Base32.
def b32encode(s): """Encode a string using Base32. s is the string to encode. The encoded string is returned. """ parts = [] quanta, leftover = divmod(len(s), 5) # Pad the last quantum with zero bits if necessary if leftover: s += ('\0' * (5 - leftover)) quanta += 1 for...
Decode a Base32 encoded string.
def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0...
Decode a Base16 encoded string.
def b16decode(s, casefold=False): """Decode a Base16 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded string is returned. A TypeError is raised if s is ...
Encode a file.
def encode(input, output): """Encode a file.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s)) if not ns: break s += ns line = binascii.b2a_base64...
Decode a file.
def decode(input, output): """Decode a file.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s)
Encode a string into multiple lines of base - 64 data.
def encodestring(s): """Encode a string into multiple lines of base-64 data.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return "".join(pieces)
Returns line lineno from source taking first_line into account or raises: exc: IndexError if lineno is out of range.
def source_line(self, lineno): """ Returns line ``lineno`` from source, taking ``first_line`` into account, or raises :exc:`IndexError` if ``lineno`` is out of range. """ line_begins = self._extract_line_begins() lineno = lineno - self.first_line if lineno >= 0 an...
Returns a line column tuple for a character offset into the source orraises: exc: IndexError if lineno is out of range.
def decompose_position(self, offset): """ Returns a ``line, column`` tuple for a character offset into the source, orraises :exc:`IndexError` if ``lineno`` is out of range. """ line_begins = self._extract_line_begins() lineno = bisect.bisect_right(line_begins, offset) - 1...
Returns a range identical to this one but indicating that it was expanded from the range expanded_from.
def chain(self, expanded_from): """ Returns a range identical to this one, but indicating that it was expanded from the range `expanded_from`. """ return Range(self.source_buffer, self.begin_pos, self.begin_pos, expanded_from=expanded_from)
Returns a zero - length range located just before the beginning of this range.
def begin(self): """ Returns a zero-length range located just before the beginning of this range. """ return Range(self.source_buffer, self.begin_pos, self.begin_pos, expanded_from=self.expanded_from)
Returns a zero - length range located just after the end of this range.
def end(self): """ Returns a zero-length range located just after the end of this range. """ return Range(self.source_buffer, self.end_pos, self.end_pos, expanded_from=self.expanded_from)
Returns a zero - based column number of the beginning of this range.
def column(self): """ Returns a zero-based column number of the beginning of this range. """ line, column = self.source_buffer.decompose_position(self.begin_pos) return column
Returns a [ * begin * * end * ) tuple describing the range of columns spanned by this range. If range spans more than one line returned * end * is the last column of the line.
def column_range(self): """ Returns a [*begin*, *end*) tuple describing the range of columns spanned by this range. If range spans more than one line, returned *end* is the last column of the line. """ if self.begin().line() == self.end().line(): return self.b...
Returns the line number of the beginning of this range.
def line(self): """ Returns the line number of the beginning of this range. """ line, column = self.source_buffer.decompose_position(self.begin_pos) return line
Returns the smallest possible range spanning both this range and other. Raises: exc: ValueError if the ranges do not belong to the same: class: Buffer.
def join(self, other): """ Returns the smallest possible range spanning both this range and other. Raises :exc:`ValueError` if the ranges do not belong to the same :class:`Buffer`. """ if self.source_buffer != other.source_buffer: raise ValueError if s...
Returns the lines of source code containing the entirety of this range.
def source_lines(self): """ Returns the lines of source code containing the entirety of this range. """ return [self.source_buffer.source_line(line) for line in range(self.line(), self.end().line() + 1)]
Return the rewritten source. May raise: class: RewriterConflict.
def rewrite(self): """Return the rewritten source. May raise :class:`RewriterConflict`.""" self._sort() self._check() rewritten, pos = [], 0 for range, replacement in self.ranges: rewritten.append(self.buffer.source[pos:range.begin_pos]) rewritten.append(...
An AST comparison function. Returns True if all fields in left are equal to fields in right ; if compare_locs is true all locations should match as well.
def compare(left, right, compare_locs=False): """ An AST comparison function. Returns ``True`` if all fields in ``left`` are equal to fields in ``right``; if ``compare_locs`` is true, all locations should match as well. """ if type(left) != type(right): return False if isinstance(le...
Visit a node or a list of nodes. Other values are ignored
def visit(self, obj): """Visit a node or a list of nodes. Other values are ignored""" if isinstance(obj, list): return [self.visit(elt) for elt in obj] elif isinstance(obj, ast.AST): return self._visit_one(obj)
Called if no explicit visitor function exists for a node.
def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field_name in node._fields: setattr(node, field_name, self.visit(getattr(node, field_name))) return node
Visit a node or a list of nodes. Other values are ignored
def visit(self, obj): """Visit a node or a list of nodes. Other values are ignored""" if isinstance(obj, list): return list(filter(lambda x: x is not None, map(self.visit, obj))) elif isinstance(obj, ast.AST): return self._visit_one(obj) else: return o...
Dummy implementation of thread. start_new_thread ().
def start_new_thread(function, args, kwargs={}): """Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it is caugh...