_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q249700
DirectReader.readinto
train
def readinto(self, buf): """Zero-copy read directly into buffer.""" got = 0 vbuf = memoryview(buf) while got < len(buf): # next vol needed? if self._cur_avail == 0: if not self._open_next(): break # length for next ...
python
{ "resource": "" }
q249701
HeaderDecrypt.read
train
def read(self, cnt=None): """Read and decrypt.""" if cnt > 8 * 1024: raise BadRarFile('Bad count to header decrypt - wrong password?') # consume old data if cnt <= len(self.buf): res = self.buf[:cnt] self.buf = self.buf[cnt:] return res ...
python
{ "resource": "" }
q249702
Blake2SP.update
train
def update(self, data): """Hash data. """ view = memoryview(data) bs = self.block_size if self._buf: need = bs - len(self._buf) if len(view) < need:
python
{ "resource": "" }
q249703
Blake2SP.digest
train
def digest(self): """Return final digest value. """ if self._digest is None: if self._buf: self._add_block(self._buf) self._buf = EMPTY ctx = self._blake2s(0, 1, True)
python
{ "resource": "" }
q249704
Rar3Sha1.update
train
def update(self, data): """Process more data.""" self._md.update(data) bufpos = self._nbytes & 63 self._nbytes += len(data) if self._rarbug and len(data) > 64: dpos = self.block_size - bufpos
python
{ "resource": "" }
q249705
Rar3Sha1._corrupt
train
def _corrupt(self, data, dpos): """Corruption from SHA1 core.""" ws = list(self._BLK_BE.unpack_from(data, dpos)) for t in range(16, 80): tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16)
python
{ "resource": "" }
q249706
get_tags_recommendation
train
def get_tags_recommendation(request): """ Taggit autocomplete ajax view. Response objects are filtered based on query param. Tags are by default limited to 10, use TAGGIT_SELECTIZE_RECOMMENDATION_LIMIT settings to specify. """ query = request.GET.get('query') limit = settings.TAGGIT_SELECTIZ...
python
{ "resource": "" }
q249707
parse_tags
train
def parse_tags(tagstring): """ Parses tag input, with multiple word input being activated and delineated by commas and double quotes. Quotes take precedence, so they may contain commas. Returns a sorted list of unique tag names. Adapted from Taggit, modified to not split strings on spaces. ...
python
{ "resource": "" }
q249708
join_tags
train
def join_tags(tags): """ Given list of ``Tag`` instances, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contain DELIMITER will be double...
python
{ "resource": "" }
q249709
get_logger
train
def get_logger(name, namespace='{{project.package}}', log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): """Build a logger that outputs to a file and to the console,""" log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or os.getenv('LOG_LEVEL', log_level)) ...
python
{ "resource": "" }
q249710
Configuration.get
train
def get(cls, key, section=None, **kwargs): """ Retrieves a config value from dict. If not found twrows an InvalidScanbooconfigException. """ section = section or cls._default_sect if section not in cls._conf: cls._load(section=section) value = cls._co...
python
{ "resource": "" }
q249711
Configuration.keys
train
def keys(cls, section=None): """Get a list with all config keys""" section = section or cls._default_sect if section not in cls._conf:
python
{ "resource": "" }
q249712
Credential.get
train
def get(self): """Get a credential by file path""" args = self.get_parser.parse_args() cred = self.manager.get_credential(args)
python
{ "resource": "" }
q249713
Credential.put
train
def put(self): """Update a credential by file path""" cred_payload = utils.uni_to_str(json.loads(request.get_data()))
python
{ "resource": "" }
q249714
HttpClient.parse_response
train
def parse_response(self, response): """ Parse the response and build a `scanboo_common.http_client.HttpResponse` object. For successful responses, convert the json data into a dict. :param response: the `requests` response :return: [HttpResponse] response object
python
{ "resource": "" }
q249715
HttpClient.get_all
train
def get_all(self, path, data=None, limit=100): """Encapsulates GET all requests"""
python
{ "resource": "" }
q249716
HttpClient.get
train
def get(self, path, data=None): """Encapsulates GET requests""" data = data or {}
python
{ "resource": "" }
q249717
HttpClient.post
train
def post(self, path, data=None): """Encapsulates POST requests""" data = data or {} response
python
{ "resource": "" }
q249718
MarvinData.download_file
train
def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024): """ Download file from a given url """ local_file_name = local_file_name if local_file_name else url.split('/')[-1] filepath = os.path.join(cls.data_path, local_file_name) if not os.path.ex...
python
{ "resource": "" }
q249719
chunks
train
def chunks(lst, size): """Yield successive n-sized chunks from lst.""" for i in
python
{ "resource": "" }
q249720
_to_json_default
train
def _to_json_default(obj): """Helper to convert non default objects to json. Usage: simplejson.dumps(data, default=_to_json_default) """ # Datetime if isinstance(obj, datetime.datetime): return obj.isoformat() # UUID if isinstance(obj, uuid.UUID): return str(obj) ...
python
{ "resource": "" }
q249721
_from_json_object_hook
train
def _from_json_object_hook(obj): """Converts a json string, where datetime and UUID objects were converted into strings using the '_to_json_default', into a python object. Usage: simplejson.loads(data, object_hook=_from_json_object_hook) """ for key, value in obj.items(): # Check f...
python
{ "resource": "" }
q249722
check_path
train
def check_path(path, create=False): """ Check for a path on filesystem :param path: str - path name :param create: bool - create if do not exist :return: bool - path exists """ if not os.path.exists(path): if create:
python
{ "resource": "" }
q249723
url_encode
train
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """
python
{ "resource": "" }
q249724
Run.get
train
def get(self, id): """Get run by id""" run = self.backend_store.get_run(id) if not run: return abort(http_client.NOT_FOUND,
python
{ "resource": "" }
q249725
Run.delete
train
def delete(self, id): """Delete run by id""" run = self.backend_store.get_run(id) if not run: return abort(http_client.NOT_FOUND, message="Run {} doesn't exist".format(id)) if not self.manager.delete_run(run): return abort(http_client.BAD_...
python
{ "resource": "" }
q249726
RunList.get
train
def get(self): """Get run list""" LOG.info('Returning all ansible runs') response = [] for run in self.backend_store.list_runs():
python
{ "resource": "" }
q249727
RunList.post
train
def post(self): """Trigger a new run""" run_payload = utils.uni_to_str(json.loads(request.get_data())) run_payload['id'] = str(uuid.uuid4()) LOG.info('Triggering new ansible run %s', run_payload['id'])
python
{ "resource": "" }
q249728
get_spark_session
train
def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]): """Return a Spark Session object""" # Prepare spark context to be used import findspark findspark.init() from pyspark.sql import SparkSession
python
{ "resource": "" }
q249729
chunks
train
def chunks(seq, size): """ simple two-line alternative to
python
{ "resource": "" }
q249730
_trychar
train
def _trychar(char, fallback, asciimode=None): # nocover """ Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, a...
python
{ "resource": "" }
q249731
Timer.tic
train
def tic(self): """ starts the timer """ if self.verbose: self.flush() self.write('\ntic(%r)' % self.label)
python
{ "resource": "" }
q249732
Timer.toc
train
def toc(self): """ stops the timer """ elapsed = self._time() - self.tstart if self.verbose:
python
{ "resource": "" }
q249733
Timerit.reset
train
def reset(self, label=None): """ clears all measurements, allowing the object to be reused Args: label (str, optional) : optionally change the label Example: >>> from timerit import Timerit >>> import math >>> ti = Timerit(num=10, unit='u...
python
{ "resource": "" }
q249734
Timerit.call
train
def call(self, func, *args, **kwargs): """ Alternative way to time a simple function call using condensed syntax. Returns: self (timerit.Timerit): Use `min`, or `mean` to get a scalar. Use
python
{ "resource": "" }
q249735
Timerit.mean
train
def mean(self): """ The mean of the best results of each trial. Returns: float: mean of measured seconds Note: This is typically less informative than simply looking at the min. It is recommended to use min as the expectation value rather than ...
python
{ "resource": "" }
q249736
Timerit.std
train
def std(self): """ The standard deviation of the best results of each trial. Returns: float: standard deviation of measured seconds Note: As mentioned in the timeit source code, the standard deviation is not often useful. Typically the minimum value ...
python
{ "resource": "" }
q249737
Timerit.report
train
def report(self, verbose=1): """ Creates a human readable report Args: verbose (int): verbosity level. Either 1, 2, or 3. Returns: str: the report SeeAlso: timerit.Timerit.print Example: >>> import math >>> t...
python
{ "resource": "" }
q249738
parse_description
train
def parse_description(): """ Parse the description in the README file pandoc --from=markdown --to=rst --output=README.rst README.md CommandLine: python -c "import setup; print(setup.parse_description())" """ from os.path import
python
{ "resource": "" }
q249739
parse_requirements
train
def parse_requirements(fname='requirements.txt'): """ Parse the package dependencies listed in a requirements file but strips specific versioning information. CommandLine: python -c "import setup; print(setup.parse_requirements())" """ from os.path import dirname, join, exists impor...
python
{ "resource": "" }
q249740
benchmark
train
def benchmark(repeat=10): """Benchmark cyordereddict.OrderedDict against collections.OrderedDict """ columns = ['Test', 'Code', 'Ratio (stdlib / cython)'] res = _calculate_benchmarks(repeat) try:
python
{ "resource": "" }
q249741
_get_update_fields
train
def _get_update_fields(model, uniques, to_update): """ Get the fields to be updated in an upsert. Always exclude auto_now_add, auto_created fields, and unique fields in an update """ fields = { field.attname: field for field in model._meta.fields
python
{ "resource": "" }
q249742
_fill_auto_fields
train
def _fill_auto_fields(model, values): """ Given a list of models, fill in auto_now and auto_now_add fields for upserts. Since django manager utils passes Django's ORM, these values have to be automatically constructed """ auto_field_names = [ f.attname for f in model._meta.fields...
python
{ "resource": "" }
q249743
_sort_by_unique_fields
train
def _sort_by_unique_fields(model, model_objs, unique_fields): """ Sort a list of models by their unique fields. Sorting models in an upsert greatly reduces the chances of deadlock when doing concurrent upserts """ unique_fields = [ field for field in model._meta.fields if field....
python
{ "resource": "" }
q249744
_fetch
train
def _fetch( queryset, model_objs, unique_fields, update_fields, returning, sync, ignore_duplicate_updates=True, return_untouched=False ): """ Perfom the upsert and do an optional sync operation """ model = queryset.model if (return_untouched or sync) and returning is not True: return...
python
{ "resource": "" }
q249745
upsert
train
def upsert( queryset, model_objs, unique_fields, update_fields=None, returning=False, sync=False, ignore_duplicate_updates=True, return_untouched=False ): """ Perform a bulk upsert on a table, optionally syncing the results. Args: queryset (Model|QuerySet): A model or a queryset tha...
python
{ "resource": "" }
q249746
_get_upserts_distinct
train
def _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields): """ Given a list of model objects that were updated and model objects that were created, fetch the pks of the newly created models and return the two lists in a tuple """ # Keep track of the created models ...
python
{ "resource": "" }
q249747
_get_model_objs_to_update_and_create
train
def _get_model_objs_to_update_and_create(model_objs, unique_fields, update_fields, extant_model_objs): """ Used by bulk_upsert to gather lists of models that should be updated and created. """ # Find all of the objects to update and all of the objects to create model_objs_to_update, model_objs_to_c...
python
{ "resource": "" }
q249748
_get_prepped_model_field
train
def _get_prepped_model_field(model_obj, field): """ Gets the value of a field of a model obj that is prepared for the db. """ # Get the field field = model_obj._meta.get_field(field)
python
{ "resource": "" }
q249749
get_or_none
train
def get_or_none(queryset, **query_params): """ Get an object or return None if it doesn't exist. :param query_params: The query parameters used in the lookup. :returns: A model object if one exists with the query params, None otherwise. Examples: .. code-block:: python model_obj = g...
python
{ "resource": "" }
q249750
bulk_update
train
def bulk_update(manager, model_objs, fields_to_update): """ Bulk updates a list of model objects that are already saved. :type model_objs: list of :class:`Models<django:django.db.models.Model>` :param model_objs: A list of model objects that have been updated. fields_to_update: A list of fields...
python
{ "resource": "" }
q249751
upsert
train
def upsert(manager, defaults=None, updates=None, **kwargs): """ Performs an update on an object or an insert if the object does not exist. :type defaults: dict :param defaults: These values are set when the object is created, but are irrelevant when the object already exists. This field sho...
python
{ "resource": "" }
q249752
ManagerUtilsQuerySet.bulk_create
train
def bulk_create(self, *args, **kwargs): """ Overrides Django's bulk_create function to emit a post_bulk_operation signal when bulk_create is finished.
python
{ "resource": "" }
q249753
ManagerUtilsQuerySet.update
train
def update(self, **kwargs): """ Overrides Django's update method to emit a post_bulk_operation signal when it completes. """
python
{ "resource": "" }
q249754
AuthenticationMiddleware.process_request
train
def process_request(self, request): """ Log user in if `request` contains a valid login token. Return a HTTP redirect response that removes the token from the URL after a successful login when sessions are enabled, else ``None``. """ token = request.GET.get(TOKEN_NAME) ...
python
{ "resource": "" }
q249755
AuthenticationMiddleware.get_redirect
train
def get_redirect(request): """ Create a HTTP redirect response that removes the token from the URL. """ params = request.GET.copy()
python
{ "resource": "" }
q249756
UrlAuthBackendMixin.sign
train
def sign(self, data): """ Create an URL-safe, signed token from ``data``. """
python
{ "resource": "" }
q249757
UrlAuthBackendMixin.unsign
train
def unsign(self, token): """ Extract the data from a signed ``token``. """ if self.max_age is None: data = self.signer.unsign(token) else:
python
{ "resource": "" }
q249758
UrlAuthBackendMixin.get_revocation_key
train
def get_revocation_key(self, user): """ When the value returned by this method changes, this revocates tokens. It always includes the password so that changing the password revokes existing tokens. In addition, for one-time tokens, it also contains the last login dateti...
python
{ "resource": "" }
q249759
UrlAuthBackendMixin.create_token
train
def create_token(self, user): """ Create a signed token from a user. """ # The password is expected to be a secure hash but we hash it again # for additional safety. We default to MD5 to minimize the length of # the token. (Remember, if an attacker obtains the URL, he ca...
python
{ "resource": "" }
q249760
UrlAuthBackendMixin.parse_token
train
def parse_token(self, token): """ Obtain a user from a signed token. """ try: data = self.unsign(token) except signing.SignatureExpired: logger.debug("Expired token: %s", token) return except signing.BadSignature: logger.de...
python
{ "resource": "" }
q249761
ModelBackend.authenticate
train
def authenticate(self, request, url_auth_token=None): """ Check the token and return the corresponding user. """ try: return self.parse_token(url_auth_token) except TypeError: backend = "%s.%s" % (self.__module__, self.__class__.__name__)
python
{ "resource": "" }
q249762
_add_pos1
train
def _add_pos1(token): """ Adds a 'pos1' element to a frog token.
python
{ "resource": "" }
q249763
frog_to_saf
train
def frog_to_saf(tokens): """ Convert frog tokens into a new SAF document """ tokens = [_add_pos1(token) for token in tokens] module = {'module': "frog", "started": datetime.datetime.now().isoformat()} return {"header": {'format': "SAF",
python
{ "resource": "" }
q249764
copy_cwl_files
train
def copy_cwl_files(from_dir=CWL_PATH, to_dir=None): """Copy cwl files to a directory where the cwl-runner can find them. Args: from_dir (str): Path to directory where to copy files from (default: the cwl directory of nlppln). to_dir (str): Path to directory where the files should be...
python
{ "resource": "" }
q249765
main
train
def main(to_dir, from_dir): """Copy CWL files.""" num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir) if num > 0: click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
python
{ "resource": "" }
q249766
SortedThis.find
train
def find(self, datum): """Return sorted value of This if list or dict.""" if isinstance(datum.value, dict) and self.expressions: return datum if isinstance(datum.value, dict) or isinstance(datum.value, list): key = (functools.cmp_to_key(self._compare)
python
{ "resource": "" }
q249767
WorkflowGenerator.save
train
def save(self, fname, mode=None, validate=True, wd=False, inline=False, relative=True, pack=False, encoding='utf-8'): """Save workflow to file For nlppln, the default is to save workflows with relative paths. """ super(WorkflowGenerator, self).save(fname, ...
python
{ "resource": "" }
q249768
match
train
def match(pattern, data, **parse_kwargs): """Returns all matched values of pattern in data"""
python
{ "resource": "" }
q249769
match1
train
def match1(pattern, data, **parse_kwargs): """Returns first matched value of pattern in data or None if no matches"""
python
{ "resource": "" }
q249770
create_chunked_list
train
def create_chunked_list(in_dir, size, out_dir, out_name): """Create a division of the input files in chunks. The result is stored to a JSON file. """ create_dirs(out_dir) in_files = get_files(in_dir) chunks = chunk(in_files, size) division = {} for i, files in enumerate(chunks): ...
python
{ "resource": "" }
q249771
remove_ext
train
def remove_ext(fname): """Removes the extension from a filename """
python
{ "resource": "" }
q249772
out_file_name
train
def out_file_name(out_dir, fname, ext=None): """Return path of output file, given a directory, file name and extension. If fname is a path, it is converted to its basename. Args: out_dir (str): path to the directory where output should be written. fname (str): path to the input file. ...
python
{ "resource": "" }
q249773
get_files
train
def get_files(directory, recursive=False): """Return a list of all files in the directory.""" files_out = [] if recursive: for root, dirs, files in os.walk(os.path.abspath(directory)): files = [os.path.join(root, f) for f in files] files_out.append(files) files_out = ...
python
{ "resource": "" }
q249774
_reformat
train
def _reformat(p, buf): """ Apply format of ``p`` to data in 1-d array ``buf``. """ if numpy.ndim(buf) != 1: raise ValueError("Buffer ``buf`` must be 1-d.") if hasattr(p, 'keys'): ans = _gvar.BufferDict(p) if ans.size != len(buf):
python
{ "resource": "" }
q249775
_unpack_gvars
train
def _unpack_gvars(g): """ Unpack collection of GVars to BufferDict or numpy array. """ if g is not None:
python
{ "resource": "" }
q249776
_unpack_p0
train
def _unpack_p0(p0, p0file, prior): """ Create proper p0. Try to read from a file. If that doesn't work, try using p0, and then, finally, the prior. If the p0 is from the file, it is checked against the prior to make sure that all elements have the right shape; if not the p0 elements are adjusted (u...
python
{ "resource": "" }
q249777
_unpack_fcn
train
def _unpack_fcn(fcn, p0, y, x): """ reconfigure fitting fcn so inputs, outputs = flat arrays; hide x """ if y.shape is not None: if p0.shape is not None: def nfcn(p, x=x, fcn=fcn, pshape=p0.shape): po = p.reshape(pshape) ans = fcn(po) if x is False else fcn(x,...
python
{ "resource": "" }
q249778
nonlinear_fit.check_roundoff
train
def check_roundoff(self, rtol=0.25, atol=1e-6): """ Check for roundoff errors in fit.p. Compares standard deviations from fit.p and fit.palt to see if they agree to within relative tolerance ``rtol`` and absolute tolerance ``atol``. Generates a warning if they do not (in which c...
python
{ "resource": "" }
q249779
nonlinear_fit.plot_residuals
train
def plot_residuals(self, plot=None): """ Plot normalized fit residuals. The sum of the squares of the residuals equals ``self.chi2``. Individual residuals should be distributed about one, in a Gaussian distribution. Args: plot: :mod:`matplotlib` plotter. If ``None``...
python
{ "resource": "" }
q249780
nonlinear_fit.load_parameters
train
def load_parameters(filename): """ Load parameters stored in file ``filename``. ``p = nonlinear_fit.load_p(filename)`` is used to recover the values of fit parameters dumped using ``fit.dump_p(filename)`` (or ``fit.dump_pmean(filename)``) where ``fit`` is of type
python
{ "resource": "" }
q249781
nonlinear_fit.simulated_fit_iter
train
def simulated_fit_iter( self, n=None, pexact=None, add_priornoise=False, bootstrap=None, **kargs ): """ Iterator that returns simulation copies of a fit. Fit reliability is tested using simulated data which replaces the mean values in ``self.y`` with random numbers drawn...
python
{ "resource": "" }
q249782
nonlinear_fit.simulated_data_iter
train
def simulated_data_iter( self, n=None, pexact=None, add_priornoise=False, bootstrap=None ): """ Iterator that returns simulated data based upon a fit's data. Simulated data is generated from a fit's data ``fit.y`` by replacing the mean values in that data with random numbers ...
python
{ "resource": "" }
q249783
chained_nonlinear_fit.formatall
train
def formatall(self, *args, **kargs): " Add-on method for fits returned by chained_nonlinear_fit. " ans = '' for x in self.chained_fits: ans += 10 * '=' + ' ' + str(x) + '\n'
python
{ "resource": "" }
q249784
MultiFitter.set
train
def set(self, **kargs): """ Reset default keyword parameters. Assigns new default values from dictionary ``kargs`` to the fitter's keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters can also be included (or grouped together in dictionary ``fitterargs``). ...
python
{ "resource": "" }
q249785
MultiFitter.buildfitfcn
train
def buildfitfcn(self): """ Create fit function to fit models in list ``models``. """ def _fitfcn(p, flatmodels=self.flatmodels): ans = gvar.BufferDict()
python
{ "resource": "" }
q249786
MultiFitter.builddata
train
def builddata(self, mopt=None, data=None, pdata=None, prior=None): """ Rebuild pdata to account for marginalization. """ if pdata is None: if data is None: raise ValueError('no data or pdata') pdata = gvar.BufferDict() for m in self.flatmodels: ...
python
{ "resource": "" }
q249787
MultiFitter.buildprior
train
def buildprior(self, prior, mopt=None): """ Create prior to fit models in list ``models``. """ nprior = gvar.BufferDict() for m in self.flatmodels: nprior.update(m.buildprior( prior, mopt=mopt,
python
{ "resource": "" }
q249788
MultiFitter._flatten_models
train
def _flatten_models(tasklist): " Create 1d-array containing all disctinct models from ``tasklist``. " ans = gvar.BufferDict() for task, mlist in tasklist:
python
{ "resource": "" }
q249789
MultiFitter.flatten_models
train
def flatten_models(models): " Create 1d-array containing all disctinct models from ``models``. " if isinstance(models, MultiFitterModel): ans = [models] else:
python
{ "resource": "" }
q249790
MultiFitter.lsqfit
train
def lsqfit(self, data=None, pdata=None, prior=None, p0=None, **kargs): """ Compute least-squares fit of models to data. :meth:`MultiFitter.lsqfit` fits all of the models together, in a single fit. It returns the |nonlinear_fit| object from the fit. To see plots of the fit data divided ...
python
{ "resource": "" }
q249791
MultiFitter._compile_models
train
def _compile_models(models): """ Convert ``models`` into a list of tasks. Each task is tuple ``(name, data)`` where ``name`` indicates the task task and ``data`` is the relevant data for that task. Supported tasks and data: - ``'fit'`` and list of models - ``'...
python
{ "resource": "" }
q249792
MultiFitter.coarse_grain
train
def coarse_grain(G, ncg): """ Coarse-grain last index of array ``G``. Bin the last index of array ``G`` in bins of width ``ncg``, and replace each bin by its average. Return the binned results. Args: G: Array to be coarse-grained. ncg: Bin width for coarse-grain...
python
{ "resource": "" }
q249793
MultiFitter.process_data
train
def process_data(data, models): """ Convert ``data`` to processed data using ``models``. Data from dictionary ``data`` is processed by each model in list ``models``, and the results collected into a new dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit` and :meth:`MultiF...
python
{ "resource": "" }
q249794
MultiFitter.process_dataset
train
def process_dataset(dataset, models, **kargs): """ Convert ``dataset`` to processed data using ``models``. :class:`gvar.dataset.Dataset` (or similar dictionary) object ``dataset`` is processed by each model in list ``models``, and the results collected into a new dictionary ``pdata`` fo...
python
{ "resource": "" }
q249795
Linear.buildprior
train
def buildprior(self, prior, mopt=None, extend=False): " Extract the model's parameters from prior. " newprior = {} # allow for log-normal, etc priors intercept, slope = gv.get_dictkeys( prior, [self.intercept, self.slope] )
python
{ "resource": "" }
q249796
show_plot
train
def show_plot(t_array, th_array): """ Display theta vs t plot. """ th_mean = gv.mean(th_array) th_sdev = gv.sdev(th_array) thp = th_mean + th_sdev thm = th_mean - th_sdev plt.fill_between(t_array, thp, thm, color='0.8')
python
{ "resource": "" }
q249797
aggregated_records
train
def aggregated_records(all_records, key_fields=KEY_FIELDS): """ Yield dicts that correspond to aggregates of the flow records given by the sequence of FlowRecords in `all_records`. Skips incomplete records. This will consume the `all_records` iterator, and requires enough memory to be able to read i...
python
{ "resource": "" }
q249798
action_print
train
def action_print(reader, *args): """Simply print the Flow Log records to output.""" arg_count = len(args) if arg_count == 0: stop_after = 0 elif arg_count == 1:
python
{ "resource": "" }
q249799
action_ipset
train
def action_ipset(reader, *args): """Show the set of IPs seen in Flow Log records.""" ip_set = set() for record in reader:
python
{ "resource": "" }