Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def auto_model(layout, scan_length=None, one_vs_rest=False):
'''Create a simple default model for each of the tasks in a BIDSLayout.
Contrasts each trial type against all other trial types and trial types
at the run level and then uses t-tests at each other level... | [] |
Please provide a description of the function:def merge_variables(variables, name=None, **kwargs):
'''Merge/concatenate a list of variables along the row axis.
Parameters
----------
variables : :obj:`list`
A list of Variables to merge.
name : :obj:`str`
Optional name to assign to the... | [] |
Please provide a description of the function:def split(self, grouper):
''' Split the current SparseRunVariable into multiple columns.
Args:
grouper (iterable): list to groupby, where each unique value will
be taken as the name of the resulting column.
Returns:
... | [] |
Please provide a description of the function:def select_rows(self, rows):
''' Truncate internal arrays to keep only the specified rows.
Args:
rows (array): An integer or boolean array identifying the indices
of rows to keep.
'''
self.values = self.values.iloc... | [] |
Please provide a description of the function:def to_dense(self, sampling_rate):
''' Convert the current sparse column to a dense representation.
Returns: A DenseRunVariable.
Args:
sampling_rate (int, str): Sampling rate (in Hz) to use when
constructing the DenseRunVa... | [] |
Please provide a description of the function:def split(self, grouper):
'''Split the current DenseRunVariable into multiple columns.
Parameters
----------
grouper : :obj:`pandas.DataFrame`
Binary DF specifying the design matrix to use for splitting. Number
of rows... | [] |
Please provide a description of the function:def _build_entity_index(self, run_info, sampling_rate):
''' Build the entity index from run information. '''
index = []
interval = int(round(1000. / sampling_rate))
_timestamps = []
for run in run_info:
reps = int(math.cei... | [] |
Please provide a description of the function:def resample(self, sampling_rate, inplace=False, kind='linear'):
'''Resample the Variable to the specified sampling rate.
Parameters
----------
sampling_rate : :obj:`int`, :obj:`float`
Target sampling rate (in Hz).
inplace... | [] |
Please provide a description of the function:def to_df(self, condition=True, entities=True, timing=True, sampling_rate=None):
'''Convert to a DataFrame, with columns for name and entities.
Parameters
----------
condition : :obj:`bool`
If True, adds a column for condition nam... | [] |
Please provide a description of the function:def get_collections(self, unit, names=None, merge=False,
sampling_rate=None, **entities):
''' Retrieve variable data for a specified level in the Dataset.
Args:
unit (str): The unit of analysis to return variables for. Mus... | [] |
Please provide a description of the function:def get_or_create_node(self, level, entities, *args, **kwargs):
''' Retrieves a child Node based on the specified criteria, creating a
new Node if necessary.
Args:
entities (dict): Dictionary of entities specifying which Node to
... | [] |
Please provide a description of the function:def merge_collections(collections, force_dense=False, sampling_rate='auto'):
''' Merge two or more collections at the same level of analysis.
Args:
collections (list): List of Collections to merge.
sampling_rate (int, str): Sampling rate to use if it... | [] |
Please provide a description of the function:def merge_variables(variables, **kwargs):
''' Concatenates Variables along row axis.
Args:
variables (list): List of Variables to merge. Variables can have
different names (and all Variables that share a name will be
... | [] |
Please provide a description of the function:def to_df(self, variables=None, format='wide', fillna=np.nan, **kwargs):
''' Merge variables into a single pandas DataFrame.
Args:
variables (list): Optional list of column names to retain; if None,
all variables are returned.
... | [] |
Please provide a description of the function:def from_df(cls, data, entities=None, source='contrast'):
''' Create a Collection from a pandas DataFrame.
Args:
df (DataFrame): The DataFrame to convert to a Collection. Each
column will be converted to a SimpleVariable.
... | [] |
Please provide a description of the function:def clone(self):
''' Returns a shallow copy of the current instance, except that all
variables are deep-cloned.
'''
clone = copy(self)
clone.variables = {k: v.clone() for (k, v) in self.variables.items()}
return clone | [] |
Please provide a description of the function:def _index_entities(self):
''' Sets current instance's entities based on the existing index.
Note: Only entity key/value pairs common to all rows in all contained
Variables are returned. E.g., if a Collection contains Variables
extrac... | [] |
Please provide a description of the function:def match_variables(self, pattern, return_type='name'):
''' Return columns whose names match the provided regex pattern.
Args:
pattern (str): A regex pattern to match all variable names against.
return_type (str): What to return. Must... | [] |
Please provide a description of the function:def resample(self, sampling_rate=None, variables=None, force_dense=False,
in_place=False, kind='linear'):
''' Resample all dense variables (and optionally, sparse ones) to the
specified sampling rate.
Args:
sampling_rate ... | [] |
Please provide a description of the function:def to_df(self, variables=None, format='wide', sparse=True,
sampling_rate=None, include_sparse=True, include_dense=True,
**kwargs):
''' Merge columns into a single pandas DataFrame.
Args:
variables (list): Optional lis... | [] |
Please provide a description of the function:def _transform(self, var):
''' Rename happens automatically in the base class, so all we need to
do is unset the original variable in the collection. '''
self.collection.variables.pop(var.name)
return var.values | [] |
Please provide a description of the function:def replace_entities(entities, pattern):
ents = re.findall(r'\{(.*?)\}', pattern)
new_path = pattern
for ent in ents:
match = re.search(r'([^|<]+)(<.*?>)?(\|.*)?', ent)
if match is None:
return None
name, valid, default = ... | [
"\n Replaces all entity names in a given pattern with the corresponding\n values provided by entities.\n\n Args:\n entities (dict): A dictionary mapping entity names to entity values.\n pattern (str): A path pattern that contains entity names denoted\n by curly braces. Optional por... |
Please provide a description of the function:def build_path(entities, path_patterns, strict=False):
path_patterns = listify(path_patterns)
# Loop over available patherns, return first one that matches all
for pattern in path_patterns:
# If strict, all entities must be contained in the pattern
... | [
"\n Constructs a path given a set of entities and a list of potential\n filename patterns to use.\n\n Args:\n entities (dict): A dictionary mapping entity names to entity values.\n path_patterns (str, list): One or more filename patterns to write\n the file to. Entities should be r... |
Please provide a description of the function:def write_contents_to_file(path, contents=None, link_to=None,
content_mode='text', root=None, conflicts='fail'):
if root is None and not isabs(path):
root = os.getcwd()
if root:
path = join(root, path)
if exists(... | [
"\n Uses provided filename patterns to write contents to a new path, given\n a corresponding entity map.\n\n Args:\n path (str): Destination path of the desired contents.\n contents (str): Raw text or binary encoded string of contents to write\n to the new path.\n link_to (s... |
Please provide a description of the function:def generate(self, **kwargs):
descriptions = []
subjs = self.layout.get_subjects(**kwargs)
kwargs = {k: v for k, v in kwargs.items() if k != 'subject'}
for sid in subjs:
descriptions.append(self._report_subject(subject=si... | [
"Generate the methods section.\n\n Parameters\n ----------\n task_converter : :obj:`dict`, optional\n A dictionary with information for converting task names from BIDS\n filename format to human-readable strings.\n\n Returns\n -------\n counter : :obj:... |
Please provide a description of the function:def _report_subject(self, subject, **kwargs):
description_list = []
# Remove sess from kwargs if provided, else set sess as all available
sessions = kwargs.pop('session',
self.layout.get_sessions(subject=subject,... | [
"Write a report for a single subject.\n\n Parameters\n ----------\n subject : :obj:`str`\n Subject ID.\n\n Attributes\n ----------\n layout : :obj:`bids.layout.BIDSLayout`\n Layout object for a BIDS dataset.\n config : :obj:`dict`\n C... |
Please provide a description of the function:def _gamma_difference_hrf(tr, oversampling=50, time_length=32., onset=0.,
delay=6, undershoot=16., dispersion=1.,
u_dispersion=1., ratio=0.167):
from scipy.stats import gamma
dt = tr / oversampling
time_sta... | [
" Compute an hrf as the difference of two gamma functions\n\n Parameters\n ----------\n\n tr : float\n scan repeat time, in seconds\n\n oversampling : int, optional (default=16)\n temporal oversampling factor\n\n time_length : float, optional (default=32)\n hrf kernel length, in ... |
Please provide a description of the function:def spm_hrf(tr, oversampling=50, time_length=32., onset=0.):
return _gamma_difference_hrf(tr, oversampling, time_length, onset) | [
" Implementation of the SPM hrf model\n\n Parameters\n ----------\n tr : float\n scan repeat time, in seconds\n\n oversampling : int, optional\n temporal oversampling factor\n\n time_length : float, optional\n hrf kernel length, in seconds\n\n onset : float, optional\n ... |
Please provide a description of the function:def glover_hrf(tr, oversampling=50, time_length=32., onset=0.):
return _gamma_difference_hrf(tr, oversampling, time_length, onset,
delay=6, undershoot=12., dispersion=.9,
u_dispersion=.9, ratio=.35) | [
" Implementation of the Glover hrf model\n\n Parameters\n ----------\n tr : float\n scan repeat time, in seconds\n\n oversampling : int, optional\n temporal oversampling factor\n\n time_length : float, optional\n hrf kernel length, in seconds\n\n onset : float, optional\n ... |
Please provide a description of the function:def spm_time_derivative(tr, oversampling=50, time_length=32., onset=0.):
do = .1
dhrf = 1. / do * (spm_hrf(tr, oversampling, time_length, onset) -
spm_hrf(tr, oversampling, time_length, onset + do))
return dhrf | [
"Implementation of the SPM time derivative hrf (dhrf) model\n\n Parameters\n ----------\n tr: float\n scan repeat time, in seconds\n\n oversampling: int, optional\n temporal oversampling factor, optional\n\n time_length: float, optional\n hrf kernel length, in seconds\n\n onse... |
Please provide a description of the function:def glover_time_derivative(tr, oversampling=50, time_length=32., onset=0.):
do = .1
dhrf = 1. / do * (glover_hrf(tr, oversampling, time_length, onset) -
glover_hrf(tr, oversampling, time_length, onset + do))
return dhrf | [
"Implementation of the Glover time derivative hrf (dhrf) model\n\n Parameters\n ----------\n tr: float\n scan repeat time, in seconds\n oversampling: int,\n temporal oversampling factor, optional\n time_length: float,\n hrf kernel length, in seconds\n onset: float,\n on... |
Please provide a description of the function:def spm_dispersion_derivative(tr, oversampling=50, time_length=32., onset=0.):
dd = .01
dhrf = 1. / dd * (
- _gamma_difference_hrf(tr, oversampling, time_length,
onset, dispersion=1. + dd)
+ _gamma_difference_hrf(t... | [
"Implementation of the SPM dispersion derivative hrf model\n\n Parameters\n ----------\n tr: float\n scan repeat time, in seconds\n\n oversampling: int, optional\n temporal oversampling factor in seconds\n\n time_length: float, optional\n hrf kernel length, in seconds\n\n onse... |
Please provide a description of the function:def _sample_condition(exp_condition, frame_times, oversampling=50,
min_onset=-24):
# Find the high-resolution frame_times
n = frame_times.size
min_onset = float(min_onset)
n_hr = ((n - 1) * 1. / (frame_times.max() - frame_times.min()... | [
"Make a possibly oversampled event regressor from condition information.\n\n Parameters\n ----------\n exp_condition : arraylike of shape (3, n_events)\n yields description of events for this condition as a\n (onsets, durations, amplitudes) triplet\n\n frame_times : array of shape(n_scans)... |
Please provide a description of the function:def _resample_regressor(hr_regressor, hr_frame_times, frame_times):
from scipy.interpolate import interp1d
f = interp1d(hr_frame_times, hr_regressor)
return f(frame_times).T | [
" this function sub-samples the regressors at frame times\n\n Parameters\n ----------\n hr_regressor : array of shape(n_samples),\n the regressor time course sampled at high temporal resolution\n\n hr_frame_times : array of shape(n_samples),\n the corresponding time stamps\n\n frame_tim... |
Please provide a description of the function:def _orthogonalize(X):
if X.size == X.shape[0]:
return X
from scipy.linalg import pinv, norm
for i in range(1, X.shape[1]):
X[:, i] -= np.dot(np.dot(X[:, i], X[:, :i]), pinv(X[:, :i]))
# X[:, i] /= norm(X[:, i])
return X | [
" Orthogonalize every column of design `X` w.r.t preceding columns\n\n Parameters\n ----------\n X: array of shape(n, p)\n the data to be orthogonalized\n\n Returns\n -------\n X: array of shape(n, p)\n the data after orthogonalization\n\n Notes\n -----\n X is changed in place... |
Please provide a description of the function:def _regressor_names(con_name, hrf_model, fir_delays=None):
if hrf_model in ['glover', 'spm', None]:
return [con_name]
elif hrf_model in ["glover + derivative", 'spm + derivative']:
return [con_name, con_name + "_derivative"]
elif hrf_model i... | [
" Returns a list of regressor names, computed from con-name and hrf type\n\n Parameters\n ----------\n con_name: string\n identifier of the condition\n\n hrf_model: string or None,\n hrf model chosen\n\n fir_delays: 1D array_like, optional,\n Delays used in case of an FIR model\n\... |
Please provide a description of the function:def _hrf_kernel(hrf_model, tr, oversampling=50, fir_delays=None):
acceptable_hrfs = [
'spm', 'spm + derivative', 'spm + derivative + dispersion', 'fir',
'glover', 'glover + derivative', 'glover + derivative + dispersion',
None]
if hrf_mod... | [
" Given the specification of the hemodynamic model and time parameters,\n return the list of matching kernels\n\n Parameters\n ----------\n hrf_model : string or None,\n identifier of the hrf model\n\n tr : float\n the repetition time in seconds\n\n oversampling : int, optional\n ... |
Please provide a description of the function:def compute_regressor(exp_condition, hrf_model, frame_times, con_id='cond',
oversampling=50, fir_delays=None, min_onset=-24):
# this is the average tr in this session, not necessarily the true tr
tr = float(frame_times.max()) / (np.size(fra... | [
" This is the main function to convolve regressors with hrf model\n\n Parameters\n ----------\n exp_condition : array-like of shape (3, n_events)\n yields description of events for this condition as a\n (onsets, durations, amplitudes) triplet\n\n hrf_model : {'spm', 'spm + derivative', 'sp... |
Please provide a description of the function:def matches_entities(obj, entities, strict=False):
''' Checks whether an object's entities match the input. '''
if strict and set(obj.entities.keys()) != set(entities.keys()):
return False
comm_ents = list(set(obj.entities.keys()) & set(entities.keys()))... | [] |
Please provide a description of the function:def natural_sort(l, field=None):
'''
based on snippet found at http://stackoverflow.com/a/4836734/2445984
'''
convert = lambda text: int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
if field is not None:
key = geta... | [] |
Please provide a description of the function:def convert_JSON(j):
def camel_to_snake(s):
a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
return a.sub(r'_\1', s).lower()
def convertArray(a):
newArr = []
for i in a:
if isinstance(i,list):
... | [
" Recursively convert CamelCase keys to snake_case.\n From: https://stackoverflow.com/questions/17156078/converting-identifier-naming-between-camelcase-and-underscores-during-json-seria\n "
] |
Please provide a description of the function:def splitext(path):
li = []
path_without_extensions = os.path.join(os.path.dirname(path),
os.path.basename(path).split(os.extsep)[0])
extensions = os.path.basename(path).split(os.extsep)[1:]
li.append(path_without_extensions)
# li.append(exte... | [
"splitext for paths with directories that may contain dots.\n From https://stackoverflow.com/questions/5930036/separating-file-extensions-using-python-os-path-module"
] |
Please provide a description of the function:def check_path_matches_patterns(path, patterns):
''' Check if the path matches at least one of the provided patterns. '''
path = os.path.abspath(path)
for patt in patterns:
if isinstance(patt, six.string_types):
if path == patt:
... | [] |
Please provide a description of the function:def count(self, files=False):
return len(self.files) if files else len(self.unique()) | [
" Returns a count of unique values or files.\n\n Args:\n files (bool): When True, counts all files mapped to the Entity.\n When False, counts all unique values.\n Returns: an int.\n "
] |
Please provide a description of the function:def _matches(self, entities=None, extensions=None, regex_search=False):
if extensions is not None:
extensions = map(re.escape, listify(extensions))
extensions = '(' + '|'.join(extensions) + ')$'
if re.search(extensions, se... | [
"\n Checks whether the file matches all of the passed entities and\n extensions.\n\n Args:\n entities (dict): A dictionary of entity names -> regex patterns.\n extensions (str, list): One or more file extensions to allow.\n regex_search (bool): Whether to requir... |
Please provide a description of the function:def _get_child_class(self, path):
if self._child_entity is None:
return BIDSNode
for i, child_ent in enumerate(listify(self._child_entity)):
template = self.available_entities[child_ent].directory
if template is N... | [
" Return the appropriate child class given a subdirectory path.\n \n Args:\n path (str): The path to the subdirectory.\n \n Returns: An uninstantiated BIDSNode or one of its subclasses.\n "
] |
Please provide a description of the function:def index(self):
config_list = self.config
layout = self.layout
for (dirpath, dirnames, filenames) in os.walk(self.path):
# If layout configuration file exists, delete it
layout_file = self.layout.config_filename
... | [
" Index all files/directories below the current BIDSNode. "
] |
Please provide a description of the function:def general_acquisition_info(metadata):
out_str = ('MR data were acquired using a {tesla}-Tesla {manu} {model} '
'MRI scanner.')
out_str = out_str.format(tesla=metadata.get('MagneticFieldStrength',
'... | [
"\n General sentence on data acquisition. Should be first sentence in MRI data\n acquisition section.\n\n Parameters\n ----------\n metadata : :obj:`dict`\n The metadata for the dataset.\n\n Returns\n -------\n out_str : :obj:`str`\n Output string with scanner information.\n ... |
Please provide a description of the function:def func_info(task, n_runs, metadata, img, config):
if metadata.get('MultibandAccelerationFactor', 1) > 1:
mb_str = '; MB factor={}'.format(metadata['MultibandAccelerationFactor'])
else:
mb_str = ''
if metadata.get('ParallelReductionFactorIn... | [
"\n Generate a paragraph describing T2*-weighted functional scans.\n\n Parameters\n ----------\n task : :obj:`str`\n The name of the task.\n n_runs : :obj:`int`\n The number of runs acquired for this task.\n metadata : :obj:`dict`\n The metadata for the scan from the json asso... |
Please provide a description of the function:def anat_info(suffix, metadata, img, config):
n_slices, vs_str, ms_str, fov_str = get_sizestr(img)
seqs, variants = get_seqstr(config, metadata)
if 'EchoTime' in metadata.keys():
te = num_to_str(metadata['EchoTime']*1000)
else:
te = 'UNK... | [
"\n Generate a paragraph describing T1- and T2-weighted structural scans.\n\n Parameters\n ----------\n suffix : :obj:`str`\n T1 or T2.\n metadata : :obj:`dict`\n Data from the json file associated with the scan, in dictionary\n form.\n img : :obj:`nibabel.Nifti1Image`\n ... |
Please provide a description of the function:def dwi_info(bval_file, metadata, img, config):
# Parse bval file
with open(bval_file, 'r') as file_object:
d = file_object.read().splitlines()
bvals = [item for sublist in [l.split(' ') for l in d] for item in sublist]
bvals = sorted([int(v) for... | [
"\n Generate a paragraph describing DWI scan acquisition information.\n\n Parameters\n ----------\n bval_file : :obj:`str`\n File containing b-vals associated with DWI scan.\n metadata : :obj:`dict`\n Data from the json file associated with the DWI scan, in dictionary\n form.\n ... |
Please provide a description of the function:def fmap_info(metadata, img, config, layout):
dir_ = config['dir'][metadata['PhaseEncodingDirection']]
n_slices, vs_str, ms_str, fov_str = get_sizestr(img)
seqs, variants = get_seqstr(config, metadata)
if 'EchoTime' in metadata.keys():
te = num_... | [
"\n Generate a paragraph describing field map acquisition information.\n\n Parameters\n ----------\n metadata : :obj:`dict`\n Data from the json file associated with the field map, in dictionary\n form.\n img : :obj:`nibabel.Nifti1Image`\n The nifti image of the field map.\n c... |
Please provide a description of the function:def final_paragraph(metadata):
if 'ConversionSoftware' in metadata.keys():
soft = metadata['ConversionSoftware']
vers = metadata['ConversionSoftwareVersion']
software_str = ' using {soft} ({conv_vers})'.format(soft=soft, conv_vers=vers)
e... | [
"\n Describes dicom-to-nifti conversion process and methods generation.\n\n Parameters\n ----------\n metadata : :obj:`dict`\n The metadata for the scan.\n\n Returns\n -------\n desc : :obj:`str`\n Output string with scanner information.\n "
] |
Please provide a description of the function:def parse_niftis(layout, niftis, subj, config, **kwargs):
kwargs = {k: v for k, v in kwargs.items() if v is not None}
description_list = []
skip_task = {} # Only report each task once
for nifti_struct in niftis:
nii_file = nifti_struct.path
... | [
"\n Loop through niftis in a BIDSLayout and generate the appropriate description\n type for each scan. Compile all of the descriptions into a list.\n\n Parameters\n ----------\n layout : :obj:`bids.layout.BIDSLayout`\n Layout object for a BIDS dataset.\n niftis : :obj:`list` or :obj:`grabbi... |
Please provide a description of the function:def track_pageview(self, name, url, duration=0, properties=None, measurements=None):
data = channel.contracts.PageViewData()
data.name = name or NULL_CONSTANT_STRING
data.url = url
data.duration = duration
if properties:
... | [
"Send information about the page viewed in the application (a web page for instance).\n\n Args:\n name (str). the name of the page that was viewed.\\n\n url (str). the URL of the page that was viewed.\\n\n duration (int). the duration of the page view in milliseconds. (defaul... |
Please provide a description of the function:def track_exception(self, type=None, value=None, tb=None, properties=None, measurements=None):
if not type or not value or not tb:
type, value, tb = sys.exc_info()
if not type or not value or not tb:
try:
rais... | [
" Send information about a single exception that occurred in the application.\n\n Args:\n type (Type). the type of the exception that was thrown.\\n\n value (:class:`Exception`). the exception that the client wants to send.\\n\n tb (:class:`Traceback`). the traceback informat... |
Please provide a description of the function:def track_event(self, name, properties=None, measurements=None):
data = channel.contracts.EventData()
data.name = name or NULL_CONSTANT_STRING
if properties:
data.properties = properties
if measurements:
data.m... | [
" Send information about a single event that has occurred in the context of the application.\n\n Args:\n name (str). the data to associate to this event.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n ... |
Please provide a description of the function:def track_metric(self, name, value, type=None, count=None, min=None, max=None, std_dev=None, properties=None):
dataPoint = channel.contracts.DataPoint()
dataPoint.name = name or NULL_CONSTANT_STRING
dataPoint.value = value or 0
dataPo... | [
"Send information about a single metric data point that was captured for the application.\n\n Args:\n name (str). the name of the metric that was captured.\\n\n value (float). the value of the metric that was captured.\\n\n type (:class:`channel.contracts.DataPointType`). the... |
Please provide a description of the function:def track_trace(self, name, properties=None, severity=None):
data = channel.contracts.MessageData()
data.message = name or NULL_CONSTANT_STRING
if properties:
data.properties = properties
if severity is not None:
... | [
"Sends a single trace statement.\n\n Args:\n name (str). the trace statement.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n severity (str). the severity level of this trace, one of DEBUG, INFO, WARNI... |
Please provide a description of the function:def track_request(self, name, url, success, start_time=None, duration=None, response_code=None, http_method=None, properties=None, measurements=None, request_id=None):
data = channel.contracts.RequestData()
data.id = request_id or str(uuid.uuid4())
... | [
"Sends a single request that was captured for the application.\n\n Args:\n name (str). the name for this request. All requests with the same name will be grouped together.\\n\n url (str). the actual URL for this request (to show in individual request instances).\\n\n success ... |
Please provide a description of the function:def track_dependency(self, name, data, type=None, target=None, duration=None, success=None, result_code=None, properties=None, measurements=None, dependency_id=None):
dependency_data = channel.contracts.RemoteDependencyData()
dependency_data.id = dep... | [
"Sends a single dependency telemetry that was captured for the application.\n\n Args:\n name (str). the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.\\n\n data (str). the command initiated by thi... |
Please provide a description of the function:def severity_level(self, value):
if value == self._defaults['severityLevel'] and 'severityLevel' in self._values:
del self._values['severityLevel']
else:
self._values['severityLevel'] = value | [
"The severity_level property.\n \n Args:\n value (int). the property value.\n "
] |
Please provide a description of the function:def problem_id(self, value):
if value == self._defaults['problemId'] and 'problemId' in self._values:
del self._values['problemId']
else:
self._values['problemId'] = value | [
"The problem_id property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def properties(self):
if 'properties' in self._values:
return self._values['properties']
self._values['properties'] = copy.deepcopy(self._defaults['properties'])
return self._values['properties'] | [
"The properties property.\n \n Returns:\n (hash). the property value. (defaults to: {})\n "
] |
Please provide a description of the function:def properties(self, value):
if value == self._defaults['properties'] and 'properties' in self._values:
del self._values['properties']
else:
self._values['properties'] = value | [
"The properties property.\n \n Args:\n value (hash). the property value.\n "
] |
Please provide a description of the function:def measurements(self):
if 'measurements' in self._values:
return self._values['measurements']
self._values['measurements'] = copy.deepcopy(self._defaults['measurements'])
return self._values['measurements'] | [
"The measurements property.\n \n Returns:\n (hash). the property value. (defaults to: {})\n "
] |
Please provide a description of the function:def measurements(self, value):
if value == self._defaults['measurements'] and 'measurements' in self._values:
del self._values['measurements']
else:
self._values['measurements'] = value | [
"The measurements property.\n \n Args:\n value (hash). the property value.\n "
] |
Please provide a description of the function:def id(self, value):
if value == self._defaults['ai.device.id'] and 'ai.device.id' in self._values:
del self._values['ai.device.id']
else:
self._values['ai.device.id'] = value | [
"The id property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def locale(self, value):
if value == self._defaults['ai.device.locale'] and 'ai.device.locale' in self._values:
del self._values['ai.device.locale']
else:
self._values['ai.device.locale'] = value | [
"The locale property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def model(self, value):
if value == self._defaults['ai.device.model'] and 'ai.device.model' in self._values:
del self._values['ai.device.model']
else:
self._values['ai.device.model'] = value | [
"The model property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def oem_name(self, value):
if value == self._defaults['ai.device.oemName'] and 'ai.device.oemName' in self._values:
del self._values['ai.device.oemName']
else:
self._values['ai.device.oemName'] = value | [
"The oem_name property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def os_version(self, value):
if value == self._defaults['ai.device.osVersion'] and 'ai.device.osVersion' in self._values:
del self._values['ai.device.osVersion']
else:
self._values['ai.device.osVersion'] = value | [
"The os_version property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def put(self, item):
QueueBase.put(self, item)
if self.sender:
self.sender.start() | [
"Adds the passed in item object to the queue and notifies the :func:`sender` to start an asynchronous\n send operation by calling :func:`start`.\n\n Args:\n item (:class:`contracts.Envelope`) the telemetry envelope object to send to the service.\n "
] |
Please provide a description of the function:def flush(self):
self._flush_notification.set()
if self.sender:
self.sender.start() | [
"Flushes the current queue by notifying the :func:`sender` via the :func:`flush_notification` event.\n "
] |
Please provide a description of the function:def role(self, value):
if value == self._defaults['ai.cloud.role'] and 'ai.cloud.role' in self._values:
del self._values['ai.cloud.role']
else:
self._values['ai.cloud.role'] = value | [
"The role property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def role_instance(self, value):
if value == self._defaults['ai.cloud.roleInstance'] and 'ai.cloud.roleInstance' in self._values:
del self._values['ai.cloud.roleInstance']
else:
self._values['ai.cloud.roleInstance'] = value | [
"The role_instance property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def send(self, data_to_send):
request_payload = json.dumps([ a.write() for a in data_to_send ])
request = HTTPClient.Request(self._service_endpoint_uri, bytearray(request_payload, 'utf-8'), { 'Accept': 'application/json', 'Content-Type' : 'applicati... | [
" Immediately sends the data passed in to :func:`service_endpoint_uri`. If the service request fails, the\n passed in items are pushed back to the :func:`queue`.\n\n Args:\n data_to_send (Array): an array of :class:`contracts.Envelope` objects to send to the service.\n "
] |
Please provide a description of the function:def dummy_client(reason):
sender = applicationinsights.channel.NullSender()
queue = applicationinsights.channel.SynchronousQueue(sender)
channel = applicationinsights.channel.TelemetryChannel(None, queue)
return applicationinsights.TelemetryClient("0000... | [
"Creates a dummy channel so even if we're not logging telemetry, we can still send\n along the real object to things that depend on it to exist"
] |
Please provide a description of the function:def enable(instrumentation_key, *args, **kwargs):
if not instrumentation_key:
raise Exception('Instrumentation key was required but not provided')
global original_excepthook
global telemetry_channel
telemetry_channel = kwargs.get('telemetry_chann... | [
"Enables the automatic collection of unhandled exceptions. Captured exceptions will be sent to the Application\n Insights service before being re-thrown. Multiple calls to this function with different instrumentation keys result\n in multiple instances being submitted, one for each key.\n\n .. code:: pytho... |
Please provide a description of the function:def init_app(self, app):
self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)
if not self._key:
return
self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)
sender = AsynchronousSender(self._endpoint_uri)
q... | [
"\n Initializes the extension for the provided Flask application.\n\n Args:\n app (flask.Flask). the Flask application for which to initialize the extension.\n "
] |
Please provide a description of the function:def _init_request_logging(self, app):
enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)
if not enabled:
return
self._requests_middleware = WSGIApplication(
self._key, app.wsgi_app, telemetry_channel=s... | [
"\n Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``\n is set in the Flask config.\n\n Args:\n app (flask.Flask). the Flask application for which to initialize the extension.\n "
] |
Please provide a description of the function:def _init_trace_logging(self, app):
enabled = not app.config.get(CONF_DISABLE_TRACE_LOGGING, False)
if not enabled:
return
self._trace_log_handler = LoggingHandler(
self._key, telemetry_channel=self._channel)
... | [
"\n Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is\n set in the Flask config.\n\n Args:\n app (flask.Flask). the Flask application for which to initialize the extension.\n "
] |
Please provide a description of the function:def _init_exception_logging(self, app):
enabled = not app.config.get(CONF_DISABLE_EXCEPTION_LOGGING, False)
if not enabled:
return
exception_telemetry_client = TelemetryClient(
self._key, telemetry_channel=self._chan... | [
"\n Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING``\n is set in the Flask config.\n\n Args:\n app (flask.Flask). the Flask application for which to initialize the extension.\n "
] |
Please provide a description of the function:def flush(self):
if self._requests_middleware:
self._requests_middleware.flush()
if self._trace_log_handler:
self._trace_log_handler.flush()
if self._exception_telemetry_client:
self._exception_telemetry_... | [
"Flushes the queued up telemetry to the service.\n "
] |
Please provide a description of the function:def run_location(self, value):
if value == self._defaults['runLocation'] and 'runLocation' in self._values:
del self._values['runLocation']
else:
self._values['runLocation'] = value | [
"The run_location property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def message(self, value):
if value == self._defaults['message'] and 'message' in self._values:
del self._values['message']
else:
self._values['message'] = value | [
"The message property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def parent_id(self, value):
if value == self._defaults['ai.operation.parentId'] and 'ai.operation.parentId' in self._values:
del self._values['ai.operation.parentId']
else:
self._values['ai.operation.parentId'] = value | [
"The parent_id property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def synthetic_source(self, value):
if value == self._defaults['ai.operation.syntheticSource'] and 'ai.operation.syntheticSource' in self._values:
del self._values['ai.operation.syntheticSource']
else:
self._values['ai.operatio... | [
"The synthetic_source property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def correlation_vector(self, value):
if value == self._defaults['ai.operation.correlationVector'] and 'ai.operation.correlationVector' in self._values:
del self._values['ai.operation.correlationVector']
else:
self._values['ai.... | [
"The correlation_vector property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def put(self, item):
if not item:
return
self._queue.put(item)
if self._queue.qsize() >= self._max_queue_length:
self.flush() | [
"Adds the passed in item object to the queue and calls :func:`flush` if the size of the queue is larger\n than :func:`max_queue_length`. This method does nothing if the passed in item is None.\n\n Args:\n item (:class:`contracts.Envelope`) item the telemetry envelope object to send to the s... |
Please provide a description of the function:def get(self):
try:
item = self._queue.get_nowait()
except (Empty, PersistEmpty):
return None
if self._persistence_path:
self._queue.task_done()
return item | [
"Gets a single item from the queue and returns it. If the queue is empty, this method will return None.\n\n Returns:\n :class:`contracts.Envelope`. a telemetry envelope object or None if the queue is empty.\n "
] |
Please provide a description of the function:def enable(instrumentation_key, *args, **kwargs):
if not instrumentation_key:
raise Exception('Instrumentation key was required but not provided')
if instrumentation_key in enabled_instrumentation_keys:
logging.getLogger().removeHandler(enabled_i... | [
"Enables the Application Insights logging handler for the root logger for the supplied instrumentation key.\n Multiple calls to this function with different instrumentation keys result in multiple handler instances.\n\n .. code:: python\n\n import logging\n from applicationinsights.logging impor... |
Please provide a description of the function:def emit(self, record):
# the set of properties that will ride with the record
properties = {
'process': record.processName,
'module': record.module,
'fileName': record.filename,
'lineNumber': record.li... | [
"Emit a record.\n\n If a formatter is specified, it is used to format the record. If exception information is present, an Exception\n telemetry object is sent instead of a Trace telemetry object.\n\n Args:\n record (:class:`logging.LogRecord`). the record to format and send.\n ... |
Please provide a description of the function:def flush(self):
local_sender = self.sender
if not local_sender:
return
while True:
# get at most send_buffer_size items and send them
data = []
while len(data) < local_sender.send_buffer_size:
... | [
"Flushes the current queue by by calling :func:`sender`'s :func:`send` method.\n "
] |
Please provide a description of the function:def write(self, data, context=None):
local_context = context or self._context
if not local_context:
raise Exception('Context was required but not provided')
if not data:
raise Exception('Data was required but n... | [
"Enqueues the passed in data to the :func:`queue`. If the caller specifies a context as well, it will\r\n take precedence over the instance in :func:`context`.\r\n\r\n Args:\r\n data (object). data the telemetry data to send. This will be wrapped in an :class:`contracts.Envelope`\r\n ... |
Please provide a description of the function:def base_type(self, value):
if value == self._defaults['baseType'] and 'baseType' in self._values:
del self._values['baseType']
else:
self._values['baseType'] = value | [
"The base_type property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def ip(self, value):
if value == self._defaults['ai.location.ip'] and 'ai.location.ip' in self._values:
del self._values['ai.location.ip']
else:
self._values['ai.location.ip'] = value | [
"The ip property.\n \n Args:\n value (string). the property value.\n "
] |
Please provide a description of the function:def ver(self, value):
if value == self._defaults['ver'] and 'ver' in self._values:
del self._values['ver']
else:
self._values['ver'] = value | [
"The ver property.\n \n Args:\n value (int). the property value.\n "
] |
Please provide a description of the function:def sample_rate(self, value):
if value == self._defaults['sampleRate'] and 'sampleRate' in self._values:
del self._values['sampleRate']
else:
self._values['sampleRate'] = value | [
"The sample_rate property.\n \n Args:\n value (float). the property value.\n "
] |
Please provide a description of the function:def seq(self, value):
if value == self._defaults['seq'] and 'seq' in self._values:
del self._values['seq']
else:
self._values['seq'] = value | [
"The seq property.\n \n Args:\n value (string). the property value.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.