_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252500
DataGenerator.getAllRecords
validation
def getAllRecords(self): """Returns all the records""" values=[] numRecords = self.fields[0].numRecords
python
{ "resource": "" }
q252501
DataGenerator.addValuesToField
validation
def addValuesToField(self, i, numValues): """Add values to the field i.""" assert(len(self.fields)>i)
python
{ "resource": "" }
q252502
DataGenerator.getSDRforValue
validation
def getSDRforValue(self, i, j): """Returns the sdr for jth value at column i"""
python
{ "resource": "" }
q252503
DataGenerator.getZeroedOutEncoding
validation
def getZeroedOutEncoding(self, n): """Returns the nth encoding with the predictedField zeroed out""" assert all(field.numRecords>n for field in self.fields) encoding
python
{ "resource": "" }
q252504
DataGenerator.getTotaln
validation
def getTotaln(self): """Returns the cumulative n for all the fields in the dataset"""
python
{ "resource": "" }
q252505
DataGenerator.getTotalw
validation
def getTotalw(self): """Returns the cumulative w for all the fields in the dataset"""
python
{ "resource": "" }
q252506
DataGenerator.getEncoding
validation
def getEncoding(self, n): """Returns the nth encoding""" assert (all(field.numEncodings>n for field in self.fields)) encoding
python
{ "resource": "" }
q252507
DataGenerator.getAllEncodings
validation
def getAllEncodings(self): """Returns encodings for all the records""" numEncodings=self.fields[0].numEncodings assert (all(field.numEncodings==numEncodings for field in
python
{ "resource": "" }
q252508
DataGenerator.saveRecords
validation
def saveRecords(self, path='myOutput'): """Export all the records into a csv file in numenta format. Example header format: fieldName1 fieldName2 fieldName3 date string float T S Parameters: -----------------------------------------------------------------...
python
{ "resource": "" }
q252509
DataGenerator.removeAllRecords
validation
def removeAllRecords(self): """Deletes all the values in the dataset""" for field in self.fields:
python
{ "resource": "" }
q252510
_field.encodeValue
validation
def encodeValue(self, value, toBeAdded=True): """Value is encoded as a sdr using the encoding parameters of the Field"""
python
{ "resource": "" }
q252511
_field._setTypes
validation
def _setTypes(self, encoderSpec): """Set up the dataTypes and initialize encoders""" if self.encoderType is None: if self.dataType in ['int','float']: self.encoderType='adaptiveScalar' elif self.dataType=='string': self.encoderType='category' elif self.dataType in ['date', 'da...
python
{ "resource": "" }
q252512
_field._initializeEncoders
validation
def _initializeEncoders(self, encoderSpec): """ Initialize the encoders""" #Initializing scalar encoder if self.encoderType in ['adaptiveScalar', 'scalar']: if 'minval' in encoderSpec: self.minval = encoderSpec.pop('minval') else: self.minval=None if 'maxval' in encoderSpec: ...
python
{ "resource": "" }
q252513
loadExperiment
validation
def loadExperiment(path): """Loads the experiment description file from the path. :param path: (string) The path to a directory containing a description.py file or the file itself. :returns: (config, control) """ if not os.path.isdir(path): path = os.path.dirname(path)
python
{ "resource": "" }
q252514
loadExperimentDescriptionScriptFromDir
validation
def loadExperimentDescriptionScriptFromDir(experimentDir): """ Loads the experiment description python script from the given experiment directory. :param experimentDir: (string) experiment directory path :returns: module of the
python
{ "resource": "" }
q252515
_loadDescriptionFile
validation
def _loadDescriptionFile(descriptionPyPath): """Loads a description file and returns it as a module. descriptionPyPath: path of description.py file to load """ global g_descriptionImportCount if not os.path.isfile(descriptionPyPath): raise RuntimeError(("Experiment description file %s does not exist or ...
python
{ "resource": "" }
q252516
ResultsDB.getModelIDFromParamsHash
validation
def getModelIDFromParamsHash(self, paramsHash): """ Return the modelID of the model with the given paramsHash, or None if not found. Parameters: --------------------------------------------------------------------- paramsHash: paramsHash to look for retval: modelId, or None if not found ...
python
{ "resource": "" }
q252517
ResultsDB.bestModelIdAndErrScore
validation
def bestModelIdAndErrScore(self, swarmId=None, genIdx=None): """Return the model ID of the model with the best result so far and it's score on the optimize metric. If swarm is None, then it returns the global best, otherwise it returns the best for the given swarm for all generatons up to and including ...
python
{ "resource": "" }
q252518
ResultsDB.getParticleInfo
validation
def getParticleInfo(self, modelId): """Return particle info for a specific modelId. Parameters: --------------------------------------------------------------------- modelId: which model Id retval: (particleState, modelId, errScore, completed, matured)
python
{ "resource": "" }
q252519
ResultsDB.getParticleInfos
validation
def getParticleInfos(self, swarmId=None, genIdx=None, completed=None, matured=None, lastDescendent=False): """Return a list of particleStates for all particles we know about in the given swarm, their model Ids, and metric results. Parameters: -------------------------------------...
python
{ "resource": "" }
q252520
ResultsDB.getOrphanParticleInfos
validation
def getOrphanParticleInfos(self, swarmId, genIdx): """Return a list of particleStates for all particles in the given swarm generation that have been orphaned. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of en...
python
{ "resource": "" }
q252521
ResultsDB.firstNonFullGeneration
validation
def firstNonFullGeneration(self, swarmId, minNumParticles): """ Return the generation index of the first generation in the given swarm that does not have numParticles particles in it, either still in the running state or completed. This does not include orphaned particles. Parameters: -------------...
python
{ "resource": "" }
q252522
ResultsDB.getResultsPerChoice
validation
def getResultsPerChoice(self, swarmId, maxGenIdx, varName): """ Return a dict of the errors obtained on models that were run with each value from a PermuteChoice variable. For example, if a PermuteChoice variable has the following choices: ['a', 'b', 'c'] The dict will have 3 elements. The keys ...
python
{ "resource": "" }
q252523
HypersearchV2._getStreamDef
validation
def _getStreamDef(self, modelDescription): """ Generate stream definition based on """ #-------------------------------------------------------------------------- # Generate the string containing the aggregation settings. aggregationPeriod = { 'days': 0, 'hours': 0, 'micr...
python
{ "resource": "" }
q252524
HypersearchV2._okToExit
validation
def _okToExit(self): """Test if it's OK to exit this worker. This is only called when we run out of prospective new models to evaluate. This method sees if all models have matured yet. If not, it will sleep for a bit and return False. This will indicate to the hypersearch worker that we should keep runn...
python
{ "resource": "" }
q252525
HypersearchV2.recordModelProgress
validation
def recordModelProgress(self, modelID, modelParams, modelParamsHash, results, completed, completionReason, matured, numRecords): """Record or update the results for a model. This is called by the HSW whenever it gets results info for another model, or updated results on a model that...
python
{ "resource": "" }
q252526
HypersearchV2.runModel
validation
def runModel(self, modelID, jobID, modelParams, modelParamsHash, jobsDAO, modelCheckpointGUID): """Run the given model. This runs the model described by 'modelParams'. Periodically, it updates the results seen on the model to the model database using the databaseAO (database Access Objec...
python
{ "resource": "" }
q252527
_engineServicesRunning
validation
def _engineServicesRunning(): """ Return true if the engine services are running """ process = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) stdout = process.communicate()[0] result = process.returncode if result != 0: raise RuntimeError("Unable to check for running client job manager") # ...
python
{ "resource": "" }
q252528
runWithJsonFile
validation
def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a JSON file containing configuration. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @param expJsonFilePath {string} Path to...
python
{ "resource": "" }
q252529
runWithPermutationsScript
validation
def runWithPermutationsScript(permutationsFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a permutations.py script. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @pa...
python
{ "resource": "" }
q252530
_backupFile
validation
def _backupFile(filePath): """Back up a file Parameters: ---------------------------------------------------------------------- retval: Filepath of the back-up """ assert os.path.exists(filePath) stampNum = 0 (prefix, suffix) = os.path.splitext(filePath) while True:
python
{ "resource": "" }
q252531
_iterModels
validation
def _iterModels(modelIDs): """Creates an iterator that returns ModelInfo elements for the given modelIDs WARNING: The order of ModelInfo elements returned by the iterator may not match the order of the given modelIDs Parameters: ------------------------------------------------------------...
python
{ "resource": "" }
q252532
_HyperSearchRunner._launchWorkers
validation
def _launchWorkers(self, cmdLine, numWorkers): """ Launch worker processes to execute the given command line Parameters: ----------------------------------------------- cmdLine: The command line for each worker numWorkers: number of workers to launch """ self._workers = [] for i in ran...
python
{ "resource": "" }
q252533
_HyperSearchRunner.__startSearch
validation
def __startSearch(self): """Starts HyperSearch as a worker or runs it inline for the "dryRun" action Parameters: ---------------------------------------------------------------------- retval: the new _HyperSearchJob instance representing the HyperSearch job """ # Thi...
python
{ "resource": "" }
q252534
_HyperSearchRunner.loadSavedHyperSearchJob
validation
def loadSavedHyperSearchJob(cls, permWorkDir, outputLabel): """Instantiates a _HyperSearchJob instance from info saved in file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporat...
python
{ "resource": "" }
q252535
_HyperSearchRunner.__saveHyperSearchJobID
validation
def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob): """Saves the given _HyperSearchJob instance's jobID to file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string fo...
python
{ "resource": "" }
q252536
_HyperSearchRunner.__loadHyperSearchJobID
validation
def __loadHyperSearchJobID(cls, permWorkDir, outputLabel): """Loads a saved jobID from file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for
python
{ "resource": "" }
q252537
_HyperSearchRunner.__getHyperSearchJobIDFilePath
validation
def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel): """Returns filepath where to store HyperSearch JobID Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into...
python
{ "resource": "" }
q252538
_ReportCSVWriter.emit
validation
def emit(self, modelInfo): """Emit model info to csv file Parameters: ---------------------------------------------------------------------- modelInfo: _NupicModelInfo instance retval: nothing """ # Open/init csv file, if needed if self.__csvFileObj is None: # sets up...
python
{ "resource": "" }
q252539
_HyperSearchJob.queryModelIDs
validation
def queryModelIDs(self): """Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A sequence of Nupic modelIDs
python
{ "resource": "" }
q252540
_PermutationUtils.getOptimizationMetricInfo
validation
def getOptimizationMetricInfo(cls, searchJobParams): """Retrives the optimization key name and optimization function. Parameters: --------------------------------------------------------- searchJobParams: Parameter for passing as the searchParams arg to Hypersear...
python
{ "resource": "" }
q252541
_NupicModelInfo.getAllMetrics
validation
def getAllMetrics(self): """Retrives a dictionary of metrics that combines all report and optimization metrics Parameters: ---------------------------------------------------------------------- retval: a dictionary of optimization metrics that were collected
python
{ "resource": "" }
q252542
Distributions.getData
validation
def getData(self, n): """Returns the next n values for the distribution as a list.""" records
python
{ "resource": "" }
q252543
ModelTerminator.getTerminationCallbacks
validation
def getTerminationCallbacks(self, terminationFunc): """ Returns the periodic checks to see if the model should continue running. Parameters: ----------------------------------------------------------------------- terminationFunc: The function that will be called in the model main loop ...
python
{ "resource": "" }
q252544
StreamReader.getDataRowCount
validation
def getDataRowCount(self): """ Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. """ inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return
python
{ "resource": "" }
q252545
PatternMachine.get
validation
def get(self, number): """ Return a pattern for a number. @param number (int) Number of pattern @return (set) Indices of on bits """
python
{ "resource": "" }
q252546
PatternMachine.addNoise
validation
def addNoise(self, bits, amount): """ Add noise to pattern. @param bits (set) Indices of on bits @param amount (float) Probability of switching an on bit with a random bit @return (set) Indices of on bits in noisy pattern """ newBits = set() for bit in
python
{ "resource": "" }
q252547
PatternMachine.numbersForBit
validation
def numbersForBit(self, bit): """ Return the set of pattern numbers that match a bit. @param bit (int) Index of bit @return (set) Indices of numbers """ if bit >= self._n: raise IndexError("Invalid bit") numbers = set()
python
{ "resource": "" }
q252548
PatternMachine.numberMapForBits
validation
def numberMapForBits(self, bits): """ Return a map from number to matching on bits, for all numbers that match a set of bits. @param bits (set) Indices of bits @return (dict) Mapping from number => on bits. """ numberMap = dict() for bit in bits: numbers = self.numbersForBit(bit...
python
{ "resource": "" }
q252549
PatternMachine.prettyPrintPattern
validation
def prettyPrintPattern(self, bits, verbosity=1): """ Pretty print a pattern. @param bits (set) Indices of on bits @param verbosity (int) Verbosity level @return (string) Pretty-printed text """ numberMap = self.numberMapForBits(bits) text = "" numberList = [] numberItems ...
python
{ "resource": "" }
q252550
PatternMachine._generate
validation
def _generate(self): """ Generates set of random patterns. """ candidates = np.array(range(self._n), np.uint32)
python
{ "resource": "" }
q252551
PatternMachine._getW
validation
def _getW(self): """ Gets a value of `w` for use in generating a pattern. """ w = self._w if
python
{ "resource": "" }
q252552
ConsecutivePatternMachine._generate
validation
def _generate(self): """ Generates set of consecutive patterns. """ n = self._n w = self._w assert type(w) is int, "List for w not supported"
python
{ "resource": "" }
q252553
SDRClassifier.inferSingleStep
validation
def inferSingleStep(self, patternNZ, weightMatrix): """ Perform inference for a single step. Given an SDR input and a weight matrix, return a predicted distribution. :param patternNZ: list of the active indices from the output below :param weightMatrix: numpy array of the weight matrix :return:...
python
{ "resource": "" }
q252554
SDRClassifier._calculateError
validation
def _calculateError(self, recordNum, bucketIdxList): """ Calculate error signal :param bucketIdxList: list of encoder buckets :return: dict containing error. The key is the number of steps The value is a numpy array of error at the output layer """ error = dict() targetDist = ...
python
{ "resource": "" }
q252555
sort
validation
def sort(filename, key, outputFile, fields=None, watermark=1024 * 1024 * 100): """Sort a potentially big file filename - the input file (standard File format) key - a list of field names to sort by outputFile - the name of the output file fields - a list of fields that should be included (all fields if None)...
python
{ "resource": "" }
q252556
_sortChunk
validation
def _sortChunk(records, key, chunkIndex, fields): """Sort in memory chunk of records records - a list of records read from the original dataset key - a list of indices to sort the records by chunkIndex - the index of the current chunk The records contain only the fields requested by the user. _sortChunk(...
python
{ "resource": "" }
q252557
_mergeFiles
validation
def _mergeFiles(key, chunkCount, outputFile, fields): """Merge sorted chunk files into a sorted output file chunkCount - the number of available chunk files outputFile the name of the sorted output file _mergeFiles() """ title() # Open all chun files files = [FileRecordStream('chunk_%d.csv' % i) for...
python
{ "resource": "" }
q252558
TemporalMemoryShim.compute
validation
def compute(self, activeColumns, learn=True): """ Feeds input record through TM, performing inference and learning. Updates member variables with new state. @param activeColumns (set) Indices of active columns in `t` """ bottomUpInput = numpy.zeros(self.numberOfCols, dtype=dtype) bottomUpIn...
python
{ "resource": "" }
q252559
ConsolePrinterMixin.cPrint
validation
def cPrint(self, level, message, *args, **kw): """Print a message to the console. Prints only if level <= self.consolePrinterVerbosity Printing with level 0 is equivalent to using a print statement, and should normally be avoided. :param level: (int) indicating the urgency of the message with ...
python
{ "resource": "" }
q252560
GeospatialCoordinateEncoder.coordinateForPosition
validation
def coordinateForPosition(self, longitude, latitude, altitude=None): """ Returns coordinate for given GPS position. :param: longitude (float) Longitude of position :param: latitude (float) Latitude of position :param: altitude (float) Altitude of position
python
{ "resource": "" }
q252561
GeospatialCoordinateEncoder.radiusForSpeed
validation
def radiusForSpeed(self, speed): """ Returns radius for given speed. Tries to get the encodings of consecutive readings to be adjacent with some overlap. :param: speed (float) Speed (in meters per second) :returns: (int) Radius for given speed """ overlap = 1.5 coordinatesPerTimest...
python
{ "resource": "" }
q252562
Serializable.readFromFile
validation
def readFromFile(cls, f, packed=True): """ Read serialized object from file. :param f: input file :param packed: If true, will assume content is packed :return: first-class instance initialized from proto obj """ # Get capnproto schema from instance schema = cls.getSchema() # Read ...
python
{ "resource": "" }
q252563
Serializable.writeToFile
validation
def writeToFile(self, f, packed=True): """ Write serialized object to file. :param f: output file :param packed: If true, will pack contents. """ # Get capnproto schema from instance schema = self.getSchema() # Construct new message, otherwise refered to as `proto` proto = schema.n...
python
{ "resource": "" }
q252564
requireAnomalyModel
validation
def requireAnomalyModel(func): """ Decorator for functions that require anomaly models. """ @wraps(func) def _decorator(self, *args, **kwargs): if not self.getInferenceType() == InferenceType.TemporalAnomaly: raise RuntimeError("Method required a TemporalAnomaly model.") if self._getAnomalyClass...
python
{ "resource": "" }
q252565
HTMPredictionModel.anomalyRemoveLabels
validation
def anomalyRemoveLabels(self, start, end, labelFilter): """ Remove labels from the anomaly classifier within this model. Removes all records if ``labelFilter==None``, otherwise only removes the labels equal to ``labelFilter``. :param start: (int) index to start removing labels :param end: (int)...
python
{ "resource": "" }
q252566
HTMPredictionModel.anomalyAddLabel
validation
def anomalyAddLabel(self, start, end, labelName): """ Add labels from the anomaly classifier within this model. :param start: (int) index to start label :param end: (int) index to end label
python
{ "resource": "" }
q252567
HTMPredictionModel.anomalyGetLabels
validation
def anomalyGetLabels(self, start, end): """ Get labels from the anomaly classifier within this model. :param start:
python
{ "resource": "" }
q252568
HTMPredictionModel._anomalyCompute
validation
def _anomalyCompute(self): """ Compute Anomaly score, if required """ inferenceType = self.getInferenceType() inferences = {} sp = self._getSPRegion() score = None if inferenceType == InferenceType.NontemporalAnomaly: score = sp.getOutputData("anomalyScore")[0] #TODO move from SP ...
python
{ "resource": "" }
q252569
HTMPredictionModel._removeUnlikelyPredictions
validation
def _removeUnlikelyPredictions(cls, likelihoodsDict, minLikelihoodThreshold, maxPredictionsPerStep): """Remove entries with 0 likelihood or likelihood less than minLikelihoodThreshold, but don't leave an empty dict. """ maxVal = (None, None) for (k, v) in likelihoods...
python
{ "resource": "" }
q252570
HTMPredictionModel._getClassifierRegion
validation
def _getClassifierRegion(self): """ Returns reference to the network's Classifier region """ if (self._netInfo.net
python
{ "resource": "" }
q252571
HTMPredictionModel._addAnomalyClassifierRegion
validation
def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable): """ Attaches an 'AnomalyClassifier' region to the network. Will remove current 'AnomalyClassifier' region if it exists. Parameters ----------- network - network to add the AnomalyClassifier region params - parameter...
python
{ "resource": "" }
q252572
PermuteChoices.setResultsPerChoice
validation
def setResultsPerChoice(self, resultsPerChoice): """Setup our resultsPerChoice history based on the passed in resultsPerChoice. For example, if this variable has the following choices: ['a', 'b', 'c'] resultsPerChoice will have up to 3 elements, each element is a tuple containing (choiceValu...
python
{ "resource": "" }
q252573
BasicPredictionMetricsLogger._translateMetricsToJSON
validation
def _translateMetricsToJSON(self, metrics, label): """ Translates the given metrics value to JSON string metrics: A list of dictionaries per OPFTaskDriver.getMetrics(): Returns: JSON string representing the given metrics object. """ # Transcode the MetricValueElement values into JSO...
python
{ "resource": "" }
q252574
_BasicPredictionWriter.setLoggedMetrics
validation
def setLoggedMetrics(self, metricNames): """ Tell the writer which metrics should be written Parameters: ----------------------------------------------------------------------- metricsNames: A list of metric lables to be written """
python
{ "resource": "" }
q252575
_BasicPredictionWriter.__getDictMetaInfo
validation
def __getDictMetaInfo(self, inferenceElement, inferenceDict): """Get field metadate information for inferences that are of dict type""" fieldMetaInfo = [] inferenceLabel = InferenceElement.getLabel(inferenceElement) if InferenceElement.getInputElement(inferenceElement): fieldMetaInfo.append(Field...
python
{ "resource": "" }
q252576
_FileUtils.createExperimentInferenceDir
validation
def createExperimentInferenceDir(cls, experimentDir): """ Creates the inference output directory for the given experiment experimentDir: experiment directory path that contains description.py Returns: path of the inference output directory
python
{ "resource": "" }
q252577
_allow_new_attributes
validation
def _allow_new_attributes(f): """A decorator that maintains the attribute lock state of an object It coperates with the LockAttributesMetaclass (see bellow) that replaces the __setattr__ method with a custom one that checks the _canAddAttributes counter and allows setting new attributes only if _canAddAttribut...
python
{ "resource": "" }
q252578
generateRandomInput
validation
def generateRandomInput(numRecords, elemSize = 400, numSet = 42): """ Generates a set of input record Params: numRecords - how many records to generate elemSize - the size of each record (num 0s or 1s) numSet - how many 1s in each record Returns: a list of inputs """ inputs = ...
python
{ "resource": "" }
q252579
appendInputWithSimilarValues
validation
def appendInputWithSimilarValues(inputs): """ Creates an 'one-off' record for each record in the inputs. Appends new records to the same inputs list. """ numInputs = len(inputs)
python
{ "resource": "" }
q252580
appendInputWithNSimilarValues
validation
def appendInputWithNSimilarValues(inputs, numNear = 10): """ Creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list """ numInputs = len(inputs) skipOne = False for i in xrange(numInputs): input = inputs[i] numChanged = 0 newInput = copy.deep...
python
{ "resource": "" }
q252581
modifyBits
validation
def modifyBits(inputVal, maxChanges): """ Modifies up to maxChanges number of bits in the inputVal """ changes = np.random.random_integers(0, maxChanges, 1)[0] if changes == 0: return inputVal inputWidth = len(inputVal) whatToChange = np.random.random_integers(0, 41, changes) runningIndex = -1 n...
python
{ "resource": "" }
q252582
getRandomWithMods
validation
def getRandomWithMods(inputSpace, maxChanges): """ Returns a random selection from the inputSpace with randomly modified up to maxChanges number of bits. """ size = len(inputSpace) ind = np.random.random_integers(0, size-1, 1)[0]
python
{ "resource": "" }
q252583
createRecordSensor
validation
def createRecordSensor(network, name, dataSource): """ Creates a RecordSensor region that allows us to specify a file record stream as the input source. """ # Specific type of region. Possible options can be found in /nupic/regions/ regionType = "py.RecordSensor" # Creates a json from specified dictiona...
python
{ "resource": "" }
q252584
createNetwork
validation
def createNetwork(dataSource): """Creates and returns a new Network with a sensor region reading data from 'dataSource'. There are two hierarchical levels, each with one SP and one TM. @param dataSource - A RecordStream containing the input data @returns a Network ready to run """ network = Network() # C...
python
{ "resource": "" }
q252585
runNetwork
validation
def runNetwork(network, numRecords, writer): """ Runs specified Network writing the ensuing anomaly scores to writer. @param network: The Network instance to be run @param writer: A csv.writer used to write to output file. """ sensorRegion = network.regions[_RECORD_SENSOR] l1SpRegion = network.regions[...
python
{ "resource": "" }
q252586
clean
validation
def clean(s): """Removes trailing whitespace on each line.""" lines = [l.rstrip() for l in
python
{ "resource": "" }
q252587
MetricsManager.getMetrics
validation
def getMetrics(self): """ Gets the current metric values :returns: (dict) where each key is the metric-name, and the values are it scalar value. Same as the output of :meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update` """ result = {} f...
python
{ "resource": "" }
q252588
MetricsManager.getMetricDetails
validation
def getMetricDetails(self, metricLabel): """ Gets detailed info about a given metric, in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. :param metricLabel: (string) label of the given metric (see :class:`~nupic.frameworks...
python
{ "resource": "" }
q252589
MetricsManager._addResults
validation
def _addResults(self, results): """ Stores the current model results in the manager's internal store Parameters: ----------------------------------------------------------------------- results: A ModelResults object that contains the current timestep's input/inferences """ # ...
python
{ "resource": "" }
q252590
MetricsManager._getGroundTruth
validation
def _getGroundTruth(self, inferenceElement): """ Get the actual value for this field Parameters: ----------------------------------------------------------------------- sensorInputElement: The inference element (part of the inference) that
python
{ "resource": "" }
q252591
MetricsManager.__constructMetricsModules
validation
def __constructMetricsModules(self, metricSpecs): """ Creates the required metrics modules Parameters: ----------------------------------------------------------------------- metricSpecs: A sequence of MetricSpec objects that specify which metric modules to instantiate """ if no...
python
{ "resource": "" }
q252592
InferenceShifter.shift
validation
def shift(self, modelResult): """Shift the model result and return the new instance. Queues up the T(i+1) prediction value and emits a T(i) input/prediction pair, if possible. E.g., if the previous T(i-1) iteration was learn-only, then we would not have a T(i) prediction in our FIFO and would not b...
python
{ "resource": "" }
q252593
generateStats
validation
def generateStats(filename, maxSamples = None,): """ Collect statistics for each of the fields in the user input data file and return a stats dict object. Parameters: ------------------------------------------------------------------------------ filename: The path and name of the data file. m...
python
{ "resource": "" }
q252594
main
validation
def main(): """Run according to options in sys.argv and diff classifiers.""" initLogging(verbose=True) # Initialize PRNGs initExperimentPrng() # Mock out the creation of the SDRClassifier. @staticmethod def _mockCreate(*args, **kwargs): kwargs.pop('implementation', None)
python
{ "resource": "" }
q252595
_abbreviate
validation
def _abbreviate(text, threshold): """ Abbreviate the given text to threshold chars and append an ellipsis if its length exceeds threshold; used for logging; NOTE: the resulting text could be longer than threshold due to the
python
{ "resource": "" }
q252596
ClientJobsDAO.__getDBNameForVersion
validation
def __getDBNameForVersion(cls, dbVersion): """ Generates the ClientJobs database name for the given version of the database Parameters: ---------------------------------------------------------------- dbVersion: ClientJobs database version number retval: the ClientJobs database na...
python
{ "resource": "" }
q252597
ClientJobsDAO.connect
validation
def connect(self, deleteOldVersions=False, recreate=False): """ Locate the current version of the jobs DB or create a new one, and optionally delete old versions laying around. If desired, this method can be called at any time to re-create the tables from scratch, delete old versions of the database, et...
python
{ "resource": "" }
q252598
ClientJobsDAO._getMatchingRowsNoRetries
validation
def _getMatchingRowsNoRetries(self, tableInfo, conn, fieldsToMatch, selectFieldNames, maxRows=None): """ Return a sequence of matching rows with the requested field values from a table or empty sequence if nothing matched. tableInfo: Table information: a ClientJobsDAO....
python
{ "resource": "" }
q252599
ClientJobsDAO._getOneMatchingRowNoRetries
validation
def _getOneMatchingRowNoRetries(self, tableInfo, conn, fieldsToMatch, selectFieldNames): """ Return a single matching row with the requested field values from the the requested table or None if nothing matched. tableInfo: Table information: a ClientJobsDAO._TableInfo...
python
{ "resource": "" }