_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252300
Vocabulary.id_to_word
validation
def id_to_word(self, word_id): """Returns the word string of an integer word id.""" if word_id
python
{ "resource": "" }
q252301
main_restore_embedding_layer
validation
def main_restore_embedding_layer(): """How to use Embedding layer, and how to convert IDs to vector, IDs to words, etc. """ # Step 1: Build the embedding matrix and load the existing embedding matrix. vocabulary_size = 50000 embedding_size = 128 model_file_name = "model_word2vec_50k_128" ...
python
{ "resource": "" }
q252302
createAndStartSwarm
validation
def createAndStartSwarm(client, clientInfo="", clientKey="", params="", minimumWorkers=None, maximumWorkers=None, alreadyRunning=False): """Create and start a swarm job. Args: client - A string identifying the calling client. There is a small limit for th...
python
{ "resource": "" }
q252303
getSwarmModelParams
validation
def getSwarmModelParams(modelID): """Retrieve the Engine-level model params from a Swarm model Args: modelID - Engine-level model ID of the Swarm model Returns: JSON-encoded string containing Model Params """ # TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir whe...
python
{ "resource": "" }
q252304
enableConcurrencyChecks
validation
def enableConcurrencyChecks(maxConcurrency, raiseException=True): """ Enable the diagnostic feature for debugging unexpected concurrency in acquiring ConnectionWrapper instances. NOTE: This MUST be done early in your application's execution, BEFORE any accesses to ConnectionFactory or connection policies from ...
python
{ "resource": "" }
q252305
_getCommonSteadyDBArgsDict
validation
def _getCommonSteadyDBArgsDict(): """ Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor. """ return dict( creator = pymysql, host = Configuration.get('nupic.cluster.database.host'), port = int(Configuration.get('nupic.cluster.database.port')), user = ...
python
{ "resource": "" }
q252306
_getLogger
validation
def _getLogger(cls, logLevel=None): """ Gets a logger for the given class in this module """ logger
python
{ "resource": "" }
q252307
ConnectionWrapper.release
validation
def release(self): """ Release the database connection and cursor The receiver of the Connection instance MUST call this method in order to reclaim resources """ self._logger.debug("Releasing: %r", self) # Discard self from set of outstanding instances if self._addedToInstanceSet: t...
python
{ "resource": "" }
q252308
ConnectionWrapper._trackInstanceAndCheckForConcurrencyViolation
validation
def _trackInstanceAndCheckForConcurrencyViolation(self): """ Check for concurrency violation and add self to _clsOutstandingInstances. ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is incremented """ global g_max_concurrency, g_max_concurrency_raise_exception assert g_max_c...
python
{ "resource": "" }
q252309
SingleSharedConnectionPolicy.close
validation
def close(self): """ Close the policy instance and its shared database connection. """ self._logger.info("Closing") if self._conn
python
{ "resource": "" }
q252310
SingleSharedConnectionPolicy.acquireConnection
validation
def acquireConnection(self): """ Get a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release(...
python
{ "resource": "" }
q252311
PooledConnectionPolicy.close
validation
def close(self): """ Close the policy instance and its database connection pool. """ self._logger.info("Closing") if self._pool is
python
{ "resource": "" }
q252312
PooledConnectionPolicy.acquireConnection
validation
def acquireConnection(self): """ Get a connection from the pool. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's rel...
python
{ "resource": "" }
q252313
PerTransactionConnectionPolicy.close
validation
def close(self): """ Close the policy instance. """ self._logger.info("Closing") if self._opened: self._opened = False else:
python
{ "resource": "" }
q252314
PerTransactionConnectionPolicy.acquireConnection
validation
def acquireConnection(self): """ Create a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's relea...
python
{ "resource": "" }
q252315
PerTransactionConnectionPolicy._releaseConnection
validation
def _releaseConnection(self, dbConn, cursor): """ Release database connection and cursor; passed as a callback to ConnectionWrapper """ self._logger.debug("Releasing connection") # Close
python
{ "resource": "" }
q252316
KNNAnomalyClassifierRegion._classifyState
validation
def _classifyState(self, state): """ Reclassifies given state. """ # Record is before wait period do not classifiy if state.ROWID < self.getParameter('trainRecords'): if not state.setByUser: state.anomalyLabel = [] self._deleteRecordsFromKNN([state]) return label = K...
python
{ "resource": "" }
q252317
KNNAnomalyClassifierRegion._constructClassificationRecord
validation
def _constructClassificationRecord(self, inputs): """ Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. Types for self.classificationVectorType: 1 - TM active cells in learn state 2 - SP columns concatenated with error from TM column predicti...
python
{ "resource": "" }
q252318
KNNAnomalyClassifierRegion._addRecordToKNN
validation
def _addRecordToKNN(self, record): """ Adds the record to the KNN classifier. """ knn = self._knnclassifier._knn prototype_idx = self._knnclassifier.getParameter('categoryRecencyList') category = self._labelListToCategoryNumber(record.anomalyLabel) # If record is already in the classifier,...
python
{ "resource": "" }
q252319
KNNAnomalyClassifierRegion._deleteRecordsFromKNN
validation
def _deleteRecordsFromKNN(self, recordsToDelete): """ Removes the given records from the classifier. parameters ------------ recordsToDelete - list of records to delete from the classififier """ prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')
python
{ "resource": "" }
q252320
KNNAnomalyClassifierRegion._deleteRangeFromKNN
validation
def _deleteRangeFromKNN(self, start=0, end=None): """ Removes any stored records within the range from start to end. Noninclusive of end. parameters ------------ start - integer representing the ROWID of the start of the deletion range, end - integer representing the ROWID of the end of the...
python
{ "resource": "" }
q252321
KNNAnomalyClassifierRegion._recomputeRecordFromKNN
validation
def _recomputeRecordFromKNN(self, record): """ returns the classified labeling of record """ inputs = { "categoryIn": [None], "bottomUpIn": self._getStateAnomalyVector(record), } outputs = {"categoriesOut": numpy.zeros((1,)), "bestPrototypeIndices":numpy.zeros((1,)), ...
python
{ "resource": "" }
q252322
KNNAnomalyClassifierRegion._labelToCategoryNumber
validation
def _labelToCategoryNumber(self, label): """ Since the KNN Classifier stores categories as numbers, we must store each label as a number. This method converts from a label to a unique number. Each label is assigned a unique bit so multiple labels may be assigned to a single record. """
python
{ "resource": "" }
q252323
KNNAnomalyClassifierRegion._labelListToCategoryNumber
validation
def _labelListToCategoryNumber(self, labelList): """ This method takes a list of labels and returns a unique category number. This enables this class to store a list of categories
python
{ "resource": "" }
q252324
KNNAnomalyClassifierRegion._categoryToLabelList
validation
def _categoryToLabelList(self, category): """ Converts a category number into a list of labels """ if category is None: return [] labelList = [] labelNum = 0 while category > 0: if category % 2 == 1:
python
{ "resource": "" }
q252325
KNNAnomalyClassifierRegion._getStateAnomalyVector
validation
def _getStateAnomalyVector(self, state): """ Returns a state's anomaly vertor converting it
python
{ "resource": "" }
q252326
KNNAnomalyClassifierRegion.getLabels
validation
def getLabels(self, start=None, end=None): """ Get the labels on classified points within range start to end. Not inclusive of end. :returns: (dict) with format: :: { 'isProcessing': boolean, 'recordLabels': list of results } ``isProcessing`` - current...
python
{ "resource": "" }
q252327
KNNAnomalyClassifierRegion.removeLabels
validation
def removeLabels(self, start=None, end=None, labelFilter=None): """ Remove labels from each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. Removes all records if ``labelFilter`` is None, otherwise only removes the labels equal to ``labelFilter``. This will r...
python
{ "resource": "" }
q252328
CategoryFilter.match
validation
def match(self, record): ''' Returns True if the record matches any of the provided filters ''' for field, meta in self.filterDict.iteritems(): index = meta['index'] categories = meta['categories'] for category in categories: # Record might be blank, handle this if not...
python
{ "resource": "" }
q252329
SpatialPooler.stripUnlearnedColumns
validation
def stripUnlearnedColumns(self, activeArray): """ Removes the set of columns who have never been active from the set of active columns selected in the inhibition round. Such columns cannot represent learned pattern and are therefore meaningless if only inference is required. This should not be done ...
python
{ "resource": "" }
q252330
SpatialPooler._updateMinDutyCycles
validation
def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. """ if self._globalInhibition
python
{ "resource": "" }
q252331
SpatialPooler._updateMinDutyCyclesGlobal
validation
def _updateMinDutyCyclesGlobal(self): """ Updates the minimum duty cycles in a global fashion. Sets the minimum duty cycles for the overlap all columns to be a percent of the maximum in the region, specified by minPctOverlapDutyCycle. Functionality it is equivalent to _updateMinDutyCyclesLocal, but ...
python
{ "resource": "" }
q252332
SpatialPooler._updateMinDutyCyclesLocal
validation
def _updateMinDutyCyclesLocal(self): """ Updates the minimum duty cycles. The minimum duty cycles are determined locally. Each column's minimum duty cycles are set to be a percent of the maximum duty cycles in the column's neighborhood. Unlike _updateMinDutyCyclesGlobal, here the values can be quite...
python
{ "resource": "" }
q252333
SpatialPooler._updateDutyCycles
validation
def _updateDutyCycles(self, overlaps, activeColumns): """ Updates the duty cycles for each column. The OVERLAP duty cycle is a moving average of the number of inputs which overlapped with the each column. The ACTIVITY duty cycles is a moving average of the frequency of activation for each column. ...
python
{ "resource": "" }
q252334
SpatialPooler._avgColumnsPerInput
validation
def _avgColumnsPerInput(self): """ The average number of columns per input, taking into account the topology of the inputs and columns. This value is used to calculate the inhibition radius. This function supports an arbitrary number of dimensions. If the number of column dimensions does not match t...
python
{ "resource": "" }
q252335
SpatialPooler._avgConnectedSpanForColumn1D
validation
def _avgConnectedSpanForColumn1D(self, columnIndex): """ The range of connected synapses for column. This is used to calculate the inhibition radius. This variation of the function only supports a 1 dimensional column topology. Parameters: ---------------------------- :param columnIndex: ...
python
{ "resource": "" }
q252336
SpatialPooler._avgConnectedSpanForColumn2D
validation
def _avgConnectedSpanForColumn2D(self, columnIndex): """ The range of connectedSynapses per column, averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function only supports a 2 dimensional column topology. Parameters: --------------------...
python
{ "resource": "" }
q252337
SpatialPooler._bumpUpWeakColumns
validation
def _bumpUpWeakColumns(self): """ This method increases the permanence values of synapses of columns whose activity level has been too low. Such columns are identified by having an overlap duty cycle that drops too much below those of their peers. The permanence values for such columns are increased...
python
{ "resource": "" }
q252338
SpatialPooler._raisePermanenceToThreshold
validation
def _raisePermanenceToThreshold(self, perm, mask): """ This method ensures that each column has enough connections to input bits to allow it to become active. Since a column must have at least 'self._stimulusThreshold' overlaps in order to be considered during the inhibition phase, columns without s...
python
{ "resource": "" }
q252339
SpatialPooler._initPermConnected
validation
def _initPermConnected(self): """ Returns a randomly generated permanence value for a synapses that is initialized in a connected state. The basic idea here is to initialize permanence values very close to synPermConnected so that a small number of learning steps could make it disconnected or connec...
python
{ "resource": "" }
q252340
SpatialPooler._initPermNonConnected
validation
def _initPermNonConnected(self): """ Returns a randomly generated permanence value for a synapses that is to be initialized in a non-connected state. """ p = self._synPermConnected * self._random.getReal64() # Ensure we don't have too much unnecessary precision. A full
python
{ "resource": "" }
q252341
SpatialPooler._initPermanence
validation
def _initPermanence(self, potential, connectedPct): """ Initializes the permanences of a column. The method returns a 1-D array the size of the input, where each entry in the array represents the initial permanence value between the input bit at the particular index in the array, and the column repr...
python
{ "resource": "" }
q252342
SpatialPooler._updateBoostFactorsGlobal
validation
def _updateBoostFactorsGlobal(self): """ Update boost factors when global inhibition is used """ # When global inhibition is enabled, the target activation level is # the sparsity of the spatial pooler if (self._localAreaDensity > 0): targetDensity = self._localAreaDensity else: ...
python
{ "resource": "" }
q252343
SpatialPooler._updateBoostFactorsLocal
validation
def _updateBoostFactorsLocal(self): """ Update boost factors when local inhibition is used """ # Determine the target activation level for each column # The targetDensity is the average activeDutyCycles of the neighboring # columns of each column. targetDensity = numpy.zeros(self._numColumns...
python
{ "resource": "" }
q252344
SpatialPooler._inhibitColumns
validation
def _inhibitColumns(self, overlaps): """ Performs inhibition. This method calculates the necessary values needed to actually perform inhibition and then delegates the task of picking the active columns to helper functions. Parameters: ---------------------------- :param overlaps: an array c...
python
{ "resource": "" }
q252345
SpatialPooler._inhibitColumnsGlobal
validation
def _inhibitColumnsGlobal(self, overlaps, density): """ Perform global inhibition. Performing global inhibition entails picking the top 'numActive' columns with the highest overlap score in the entire region. At most half of the columns in a local neighborhood are allowed to be active. Columns with ...
python
{ "resource": "" }
q252346
SpatialPooler._inhibitColumnsLocal
validation
def _inhibitColumnsLocal(self, overlaps, density): """ Performs local inhibition. Local inhibition is performed on a column by column basis. Each column observes the overlaps of its neighbors and is selected if its overlap score is within the top 'numActive' in its local neighborhood. At most half o...
python
{ "resource": "" }
q252347
SpatialPooler._getColumnNeighborhood
validation
def _getColumnNeighborhood(self, centerColumn): """ Gets a neighborhood of columns. Simply calls topology.neighborhood or topology.wrappingNeighborhood A subclass can insert different topology behavior by overriding this method. :param centerColumn (int) The center of the neighborhood. @...
python
{ "resource": "" }
q252348
SpatialPooler._getInputNeighborhood
validation
def _getInputNeighborhood(self, centerInput): """ Gets a neighborhood of inputs. Simply calls topology.wrappingNeighborhood or topology.neighborhood. A subclass can insert different topology behavior by overriding this method. :param centerInput (int) The center of the neighborhood. @ret...
python
{ "resource": "" }
q252349
Array
validation
def Array(dtype, size=None, ref=False): """Factory function that creates typed Array or ArrayRef objects dtype - the data type of the array (as string). Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64 size - the size of the array. Must be positive integer. """ def...
python
{ "resource": "" }
q252350
Region.getInputNames
validation
def getInputNames(self): """ Returns list of input names in spec.
python
{ "resource": "" }
q252351
Region.getOutputNames
validation
def getOutputNames(self): """ Returns list of output names in spec.
python
{ "resource": "" }
q252352
Region.getParameter
validation
def getParameter(self, paramName): """Get parameter value""" (setter, getter) = self._getParameterMethods(paramName) if getter is None:
python
{ "resource": "" }
q252353
Region.setParameter
validation
def setParameter(self, paramName, value): """Set parameter value""" (setter, getter) = self._getParameterMethods(paramName) if setter is None:
python
{ "resource": "" }
q252354
Network._getRegions
validation
def _getRegions(self): """Get the collection of regions in a network This is a tricky one. The collection of regions returned from from the internal network is a collection of internal regions. The desired collection is a collelcion of net.Region objects that also points to this network (net.networ...
python
{ "resource": "" }
q252355
SDRClassifierRegion.writeToProto
validation
def writeToProto(self, proto): """ Write state to proto object. :param proto: SDRClassifierRegionProto capnproto object """ proto.implementation = self.implementation proto.steps = self.steps proto.alpha = self.alpha proto.verbosity = self.verbosity
python
{ "resource": "" }
q252356
SDRClassifierRegion.readFromProto
validation
def readFromProto(cls, proto): """ Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object """ instance = cls() instance.implementation = proto.implementation instance.steps = proto.steps instance.stepsList = [int(i)
python
{ "resource": "" }
q252357
OPFModelRunner.run
validation
def run(self): """ Runs the OPF Model Parameters: ------------------------------------------------------------------------- retval: (completionReason, completionMsg) where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX equates. """ # ----------------...
python
{ "resource": "" }
q252358
OPFModelRunner.__runTaskMainLoop
validation
def __runTaskMainLoop(self, numIters, learningOffAt=None): """ Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning i...
python
{ "resource": "" }
q252359
OPFModelRunner._finalize
validation
def _finalize(self): """Run final activities after a model has run. These include recording and logging the final score""" self._logger.info( "Finished: modelID=%r; %r records processed. Performing final activities", self._modelID, self._currentRecordIndex + 1) # ==========================...
python
{ "resource": "" }
q252360
OPFModelRunner.__createModelCheckpoint
validation
def __createModelCheckpoint(self): """ Create a checkpoint from the current model, and store it in a dir named after checkpoint GUID, and finally store the GUID in the Models DB """ if self._model is None or self._modelCheckpointGUID is None: return # Create an output store, if one doesn't exist...
python
{ "resource": "" }
q252361
OPFModelRunner.__deleteModelCheckpoint
validation
def __deleteModelCheckpoint(self, modelID): """ Delete the stored checkpoint for the specified modelID. This function is called if the current model is now the best model, making the old model's checkpoint obsolete Parameters: --------------------------------------------------------------------...
python
{ "resource": "" }
q252362
OPFModelRunner.__getOptimizedMetricLabel
validation
def __getOptimizedMetricLabel(self): """ Get the label for the metric being optimized. This function also caches the label in the instance variable self._optimizedMetricLabel Parameters: ----------------------------------------------------------------------- metricLabels: A sequence of all the la...
python
{ "resource": "" }
q252363
OPFModelRunner._getFieldStats
validation
def _getFieldStats(self): """ Method which returns a dictionary of field statistics received from the input source. Returns: fieldStats: dict of dicts where the first level is the field name and the second level is the statistic. ie. fieldStats['pounds']['min'] """ fieldStats =...
python
{ "resource": "" }
q252364
OPFModelRunner._updateModelDBResults
validation
def _updateModelDBResults(self): """ Retrieves the current results and updates the model's record in the Model database. """ # ----------------------------------------------------------------------- # Get metrics metrics = self._getMetrics() # ----------------------------------------------...
python
{ "resource": "" }
q252365
OPFModelRunner.__checkIfBestCompletedModel
validation
def __checkIfBestCompletedModel(self): """ Reads the current "best model" for the job and returns whether or not the current model is better than the "best model" stored for the job Returns: (isBetter, storedBest, origResultsStr) isBetter: True if the current model is better than the stored ...
python
{ "resource": "" }
q252366
OPFModelRunner._writePrediction
validation
def _writePrediction(self, result): """ Writes the results of one iteration of a model. The results are written to this ModelRunner's in-memory cache unless this model is the "best model" for the job. If this model is the "best model", the predictions are written out to a permanent store via a predi...
python
{ "resource": "" }
q252367
OPFModelRunner.__flushPredictionCache
validation
def __flushPredictionCache(self): """ Writes the contents of this model's in-memory prediction cache to a permanent store via the prediction output stream instance """ if not self.__predictionCache: return # Create an output store, if one doesn't exist already
python
{ "resource": "" }
q252368
OPFModelRunner.__deleteOutputCache
validation
def __deleteOutputCache(self, modelID): """ Delete's the output cache associated with the given modelID. This actually clears up the resources associated with the cache, rather than deleting al the records in the cache Parameters: ----------------------------------------------------------------...
python
{ "resource": "" }
q252369
OPFModelRunner._initPeriodicActivities
validation
def _initPeriodicActivities(self): """ Creates and returns a PeriodicActivityMgr instance initialized with our periodic activities Parameters: ------------------------------------------------------------------------- retval: a PeriodicActivityMgr instance """ # Activity to upda...
python
{ "resource": "" }
q252370
OPFModelRunner.__checkCancelation
validation
def __checkCancelation(self): """ Check if the cancelation flag has been set for this model in the Model DB""" # Update a hadoop job counter at least once every 600 seconds so it doesn't # think our map task is dead print >>sys.stderr, "reporter:counter:HypersearchWorker,numRecords,50" # See ...
python
{ "resource": "" }
q252371
OPFModelRunner.__checkMaturity
validation
def __checkMaturity(self): """ Save the current metric value and see if the model's performance has 'leveled off.' We do this by looking at some number of previous number of recordings """ if self._currentRecordIndex+1 < self._MIN_RECORDS_TO_BE_BEST: return # If we are already mature, don't ...
python
{ "resource": "" }
q252372
OPFModelRunner.__setAsOrphaned
validation
def __setAsOrphaned(self): """ Sets the current model as orphaned. This is called when the scheduler is about to kill the process to reallocate the worker to a different process. """ cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN
python
{ "resource": "" }
q252373
HsState.readStateFromDB
validation
def readStateFromDB(self): """Set our state to that obtained from the engWorkerState field of the job record. Parameters: --------------------------------------------------------------------- stateJSON: JSON encoded state from job record """ self._priorStateJSON = self._hsObj._cjDAO.jo...
python
{ "resource": "" }
q252374
HsState.getFieldContributions
validation
def getFieldContributions(self): """Return the field contributions statistics. Parameters: --------------------------------------------------------------------- retval: Dictionary where the keys are the field names and the values are how much each field contributed to the best score. ...
python
{ "resource": "" }
q252375
HsState.getAllSwarms
validation
def getAllSwarms(self, sprintIdx): """Return the list of all swarms in the given sprint. Parameters: --------------------------------------------------------------------- retval: list of active swarm Ids in the given sprint """ swarmIds = [] for swarmId, info in
python
{ "resource": "" }
q252376
HsState.getCompletedSwarms
validation
def getCompletedSwarms(self): """Return the list of all completed swarms. Parameters: ---------------------------------------------------------------------
python
{ "resource": "" }
q252377
HsState.getCompletingSwarms
validation
def getCompletingSwarms(self): """Return the list of all completing swarms. Parameters: ---------------------------------------------------------------------
python
{ "resource": "" }
q252378
HsState.bestModelInSprint
validation
def bestModelInSprint(self, sprintIdx): """Return the best model ID and it's errScore from the given sprint, which may still be in progress. This returns the best score from all models in the sprint which have matured so far. Parameters: -------------------------------------------------------------...
python
{ "resource": "" }
q252379
HsState.setSwarmState
validation
def setSwarmState(self, swarmId, newStatus): """Change the given swarm's state to 'newState'. If 'newState' is 'completed', then bestModelId and bestErrScore must be provided. Parameters: --------------------------------------------------------------------- swarmId: swarm Id newStatus: ...
python
{ "resource": "" }
q252380
HsState.anyGoodSprintsActive
validation
def anyGoodSprintsActive(self): """Return True if there are any more good sprints still being explored. A 'good' sprint is one that is earlier than where we detected an increase in error from sprint to subsequent sprint. """ if
python
{ "resource": "" }
q252381
HsState.isSprintCompleted
validation
def isSprintCompleted(self, sprintIdx): """Return True if the given sprint has completed.""" numExistingSprints =
python
{ "resource": "" }
q252382
MultiEncoder.addEncoder
validation
def addEncoder(self, name, encoder): """ Adds one encoder. :param name: (string) name of encoder, should be unique :param encoder: (:class:`.Encoder`) the encoder to add """ self.encoders.append((name, encoder, self.width))
python
{ "resource": "" }
q252383
Spec.invariant
validation
def invariant(self): """Verify the validity of the node spec object The type of each sub-object is verified and then the validity of each node spec item is verified by calling it invariant() method. It also makes sure that there is at most one default input and one default output. """ # Ver...
python
{ "resource": "" }
q252384
Spec.toDict
validation
def toDict(self): """Convert the information of the node spec to a plain dict of basic types The description and singleNodeOnly attributes are placed directly in the result dicts. The inputs, outputs, parameters and commands dicts contain Spec item objects (InputSpec, OutputSpec, etc). Each such object...
python
{ "resource": "" }
q252385
ModelChooser.updateResultsForJob
validation
def updateResultsForJob(self, forceUpdate=True): """ Chooses the best model for a given job. Parameters ----------------------------------------------------------------------- forceUpdate: (True/False). If True, the update will ignore all the restrictions on the minimum time to updat...
python
{ "resource": "" }
q252386
createEncoder
validation
def createEncoder(): """Create the encoder instance for our test and return it.""" consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name="consumption",
python
{ "resource": "" }
q252387
ExperimentDescriptionAPI.__validateExperimentControl
validation
def __validateExperimentControl(self, control): """ Validates control dictionary for the experiment context""" # Validate task list taskList = control.get('tasks', None) if taskList is not None: taskLabelsList = [] for task in taskList: validateOpfJsonValue(task, "opfTaskSchema.json...
python
{ "resource": "" }
q252388
_matchReportKeys
validation
def _matchReportKeys(reportKeyREs=[], allReportKeys=[]): """ Extract all items from the 'allKeys' list whose key matches one of the regular expressions passed in 'reportKeys'. Parameters: ---------------------------------------------------------------------------- reportKeyREs: List of regular expressi...
python
{ "resource": "" }
q252389
_getReportItem
validation
def _getReportItem(itemName, results): """ Get a specific item by name out of the results dict. The format of itemName is a string of dictionary keys separated by colons, each key being one level deeper into the results dict. For example, 'key1:key2' would fetch results['key1']['key2']. If itemName
python
{ "resource": "" }
q252390
_handleModelRunnerException
validation
def _handleModelRunnerException(jobID, modelID, jobsDAO, experimentDir, logger, e): """ Perform standard handling of an exception that occurs while running a model. Parameters: ------------------------------------------------------------------------- jobID: ID f...
python
{ "resource": "" }
q252391
runModelGivenBaseAndParams
validation
def runModelGivenBaseAndParams(modelID, jobID, baseDescription, params, predictedField, reportKeys, optimizeKey, jobsDAO, modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None): """ This creates an experiment directory with a base.py description file created from 'baseDescriptio...
python
{ "resource": "" }
q252392
rCopy
validation
def rCopy(d, f=identityConversion, discardNoneKeys=True, deepCopy=True): """Recursively copies a dict and returns the result. Args: d: The dict to copy. f: A function to apply to values when copying that takes the value and the list of keys from the root of the dict to the value and returns a value...
python
{ "resource": "" }
q252393
rApply
validation
def rApply(d, f): """Recursively applies f to the values in dict d. Args: d: The dict to recurse over. f: A function to apply to values in d that takes the value and a list of keys from the root of the dict to the value. """ remainingDicts = [(d, ())] while len(remainingDicts) > 0: curren...
python
{ "resource": "" }
q252394
clippedObj
validation
def clippedObj(obj, maxElementSize=64): """ Return a clipped version of obj suitable for printing, This is useful when generating log messages by printing data structures, but don't want the message to be too long. If passed in a dict, list, or namedtuple, each element of the structure's string representat...
python
{ "resource": "" }
q252395
loadJsonValueFromFile
validation
def loadJsonValueFromFile(inputFilePath): """ Loads a json value from a file and converts it to the corresponding python object. inputFilePath: Path of the json file; Returns:
python
{ "resource": "" }
q252396
PeriodicActivityMgr.tick
validation
def tick(self): """ Activity tick handler; services all activities Returns: True if controlling iterator says it's okay to keep going; False to stop """ # Run activities whose time has come for act in self.__activities: if not act.iteratorHolder[0]: continue ...
python
{ "resource": "" }
q252397
rUpdate
validation
def rUpdate(original, updates): """Recursively updates the values in original with the values from updates.""" # Keep a list of the sub-dictionaries that need to be updated to avoid having # to use recursion (which could fail for dictionaries
python
{ "resource": "" }
q252398
dictDiffAndReport
validation
def dictDiffAndReport(da, db): """ Compares two python dictionaries at the top level and report differences, if any, to stdout da: first dictionary db: second dictionary Returns: The same value as returned by dictDiff() for the given args """ differences = dictDiff(da, db)...
python
{ "resource": "" }
q252399
dictDiff
validation
def dictDiff(da, db): """ Compares two python dictionaries at the top level and return differences da: first dictionary db: second dictionary Returns: None if dictionaries test equal; otherwise returns a dictionary as follows: { ...
python
{ "resource": "" }