docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Add given string parameters to the internal list.
Args:
string (list of str or str): A string or list of strings to add to the parameters. | def add_string_parameters(self, string):
if isinstance(string, list):
for x in string:
self.add_string_parameters(x)
return
self._parameters.append("{ \"value\": \"" + string + "\" }") | 487,966 |
Set the type of agent to spawn in Holodeck. Currently accepted agents are: DiscreteSphereAgent, UAVAgent,
and AndroidAgent.
Args:
agent_type (str): The type of agent to spawn. | def set_type(self, agent_type):
type_str = SpawnAgentCommand.__type_keys[agent_type]
self.add_string_parameters(type_str) | 487,968 |
Set the weather type.
Args:
weather_type (str): The weather type. | def set_type(self, weather_type):
weather_type.lower()
exists = self.has_type(weather_type)
if exists:
self.add_string_parameters(weather_type) | 487,973 |
Resolves python 2 issue with json loading in unicode instead of string
Args:
value (str): Unicode value to be converted
Returns:
(str): converted string | def convert_unicode(value):
if isinstance(value, dict):
return {convert_unicode(key): convert_unicode(value)
for key, value in value.iteritems()}
elif isinstance(value, list):
return [convert_unicode(item) for item in value]
elif isinstance(value, unicode):
retur... | 487,983 |
Adds a sensor to a particular agent. This only works if the world you are running also includes
that particular sensor on the agent.
Args:
agent_name (str): The name of the agent to add the sensor to.
sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to a... | def add_state_sensors(self, agent_name, sensors):
if isinstance(sensors, list):
for sensor in sensors:
self.add_state_sensors(agent_name, sensor)
else:
if agent_name not in self._sensor_map:
self._sensor_map[agent_name] = dict()
... | 487,992 |
Queues a spawn agent command. It will be applied when `tick` or `step` is called next.
The agent won't be able to be used until the next frame.
Args:
agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn.
location (np.ndarray or list): The position to s... | def spawn_agent(self, agent_definition, location):
self._should_write_to_command_buffer = True
self._add_agents(agent_definition)
command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type)
self._commands.add_command(command_to_send) | 487,993 |
Queue up a change fog density command. It will be applied when `tick` or `step` is called next.
By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the
world, it will be automatically created with the given density.
Args:
densit... | def set_fog_density(self, density):
if density < 0 or density > 1:
raise HolodeckException("Fog density should be between 0 and 1")
self._should_write_to_command_buffer = True
command_to_send = ChangeFogDensityCommand(density)
self._commands.add_command(command_to_s... | 487,994 |
Queue up a change day time command. It will be applied when `tick` or `step` is called next.
By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere
or directional light in the world, the command will not function properly but will not cause a crash.
... | def set_day_time(self, hour):
self._should_write_to_command_buffer = True
command_to_send = DayTimeCommand(hour % 24)
self._commands.add_command(command_to_send) | 487,995 |
Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next.
The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a
day will be roughly equivalent to the number of minutes given.
Args:
... | def start_day_cycle(self, day_length):
if day_length <= 0:
raise HolodeckException("The given day length should be between above 0!")
self._should_write_to_command_buffer = True
command_to_send = DayCycleCommand(True)
command_to_send.set_day_length(day_length)
... | 487,996 |
Set the control scheme for a specific agent.
Args:
agent_name (str): The name of the agent to set the control scheme for.
control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`) | def set_control_scheme(self, agent_name, control_scheme):
if agent_name not in self.agents:
print("No such agent %s" % agent_name)
else:
self.agents[agent_name].set_control_scheme(control_scheme) | 488,000 |
Write input to the command buffer. Reformat input string to the correct format.
Args:
to_write (str): The string to write to the command buffer. | def _write_to_command_buffer(self, to_write):
# TODO(mitch): Handle the edge case of writing too much data to the buffer.
np.copyto(self._command_bool_ptr, True)
to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file.
input_bytes = str.encode(to_... | 488,008 |
Sets the control scheme for the agent. See :obj:`ControlSchemes`.
Args:
index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`. | def set_control_scheme(self, index):
self._current_control_scheme = index % self._num_control_schemes
self._control_scheme_buffer[0] = self._current_control_scheme | 488,010 |
Teleports the agent to a specific location, with a specific rotation.
Args:
location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters.
If None, keeps the current location. Defaults to None.
rotation (np.ndarray, optional):... | def teleport(self, location=None, rotation=None):
val = 0
if location is not None:
val += 1
np.copyto(self._teleport_buffer, location)
if rotation is not None:
np.copyto(self._rotation_buffer, rotation)
val += 2
self._teleport_bool... | 488,011 |
Returns the rdfs.label value of an entity (class or property), if existing.
Defaults to DEFAULT_LANGUAGE. Returns the RDF.Literal resource
Args:
language: 'en', 'it' etc..
getall: returns a list of all labels rather than a string | def entityLabel(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
if getall:
temp = []
for o in rdfGraph.objects(anEntity, RDFS.label):
temp += [o]
return temp
else:
for o in rdfGraph.objects(anEntity, RDFS.label):
if getattr(o, 'language'... | 488,247 |
Returns the rdfs.comment value of an entity (class or property), if existing.
Defaults to DEFAULT_LANGUAGE. Returns the RDF.Literal resource
Args:
language: 'en', 'it' etc..
getall: returns a list of all labels rather than a string | def entityComment(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
if getall:
temp = []
for o in rdfGraph.objects(anEntity, RDFS.comment):
temp += [o]
return temp
else:
for o in rdfGraph.objects(anEntity, RDFS.comment):
if getattr(o, 'lan... | 488,248 |
Perform a GET request, optionally providing query-string params.
Args:
path (str): A path that gets appended to ``base_url``.
params (dict, optional): Dictionary of param names to values.
Example:
api_client.get('/users', params={'active': True})
Returns:
... | def get(self, path, params=None, headers=None):
response = requests.get(
self._url_for(path),
params=params,
headers=self._headers(headers)
)
self._handle_errors(response)
return response | 488,462 |
Perform a POST request, providing a body, which will be JSON-encoded.
Args:
path (str): A path that gets appended to ``base_url``.
body (dict): Dictionary that will be JSON-encoded and sent as the body.
Example:
api_client.post('/users', body={'name': 'Billy Jean'})
... | def post(self, path, body, headers=None):
response = requests.post(
self._url_for(path),
data=json.dumps(body),
headers=self._headers(headers)
)
self._handle_errors(response)
return response | 488,463 |
Create a creditor bank account.
Creates a new creditor bank account object.
Args:
params (dict, optional): Request body.
Returns:
ListResponse of CreditorBankAccount instances | def create(self,params=None, headers=None):
path = '/creditor_bank_accounts'
if params is not None:
params = {self._envelope_key(): params}
try:
response = self._perform_request('POST', path, params, headers,
re... | 488,467 |
List creditor bank accounts.
Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your
creditor bank accounts.
Args:
params (dict, optional): Query string parameters.
Returns:
CreditorBankAccount | def list(self,params=None, headers=None):
path = '/creditor_bank_accounts'
response = self._perform_request('GET', path, params, headers,
retry_failures=True)
return self._resource_for(response) | 488,468 |
Get a single creditor bank account.
Retrieves the details of an existing creditor bank account.
Args:
identity (string): Unique identifier, beginning with "BA".
params (dict, optional): Query string parameters.
Returns:
ListResponse of CreditorBankAcc... | def get(self,identity,params=None, headers=None):
path = self._sub_url_params('/creditor_bank_accounts/:identity', {
'identity': identity,
})
response = self._perform_request('GET', path, params, headers,
retry_... | 488,469 |
Update a payment.
Updates a payment object. This accepts only the metadata parameter.
Args:
identity (string): Unique identifier, beginning with "PM".
params (dict, optional): Request body.
Returns:
ListResponse of Payment instances | def update(self,identity,params=None, headers=None):
path = self._sub_url_params('/payments/:identity', {
'identity': identity,
})
if params is not None:
params = {self._envelope_key(): params}
response = self._perform_request('PUT'... | 488,479 |
General optimization function for Theano.
Parameters:
params - parameters
gradients - gradients
config - training config
Returns:
Theano updates
:type config: deepy.TrainerConfig or dict | def optimize_updates(params, gradients, config=None, shapes=None):
if config and isinstance(config, dict):
config = TrainerConfig(config)
# Clipping
if config:
clip_value = config.get("gradient_clipping", None)
if clip_value:
clip_constant = T.constant(clip_value, ... | 489,063 |
Create a optimizing function receives gradients.
Parameters:
params - parameters
config - training configuration
Returns:
updating function receives gradients | def optimize_function(params, config=None):
gs = [dim_to_var(p.ndim) for p in params]
updates, _ = optimize_updates(params, gs, config)
return theano.function(gs, [], updates=updates) | 489,064 |
Get baseline model.
Parameters:
model - model path
Returns:
network | def get_network(model=None, std=0.005, disable_reinforce=False, random_glimpse=False):
network = NeuralClassifier(input_dim=28 * 28)
network.stack_layer(FirstGlimpseLayer(std=std, disable_reinforce=disable_reinforce, random_glimpse=random_glimpse))
if model and os.path.exists(model):
network.lo... | 489,097 |
Pad data set to specified length.
Parameters:
length - max length, a just to the max length in the batch if length is -1 | def pad_dataset(subset, side="right", length=-1):
assert length == -1 or length > 0
if type(subset[0][0][0]) in [float, int, np.int64, np.int32, np.float32]:
return _pad_2d(subset, side, length)
else:
return _pad_3d(subset, side, length) | 489,189 |
Initialize the controller.
Args:
port (int): batches in one training step
easgd_alpha (float) | def __init__(self, port=CONTROLLER_PORT, easgd_alpha=0.5,
# Following arguments can be received from workers
start_halving_at=6, end_at=10, sync_freq=10, halving_freq=1,
valid_freq=1500, learning_rate=0.1, log_path=None):
Controller.__init__(self, por... | 489,198 |
Create a basic network.
Parameters:
input_dim - dimension of input variable
model - a short hand to specify the model
config - network configuration
input_tensor - specify the tensor of input if it's special | def __init__(self, input_dim=0, model=None, input_tensor=None, monitors=None,
cost=None, output=None, outputs=None, blocks=None, input_vars=None, target_vars=None):
from deepy.core.neural_var import NeuralVariable
from deepy.core.tensor_conversion import convert_to_theano_var
... | 489,436 |
Gets the result of the task.
Arguments:
timeout: Maximum seconds to wait for a result before raising a
TimeoutError. If set to None, this will wait forever. If the
queue doesn't store results and timeout is None, this call will
never return. | def result(self, timeout=None):
start = time.time()
while True:
task = self.get_task()
if not task or task.status not in (FINISHED, FAILED):
if not timeout:
continue
elif time.time() - start < timeout:
... | 489,672 |
Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables to retain after all
transformations are applied. | def apply_transformations(collection, transformations, select=None):
for t in transformations:
kwargs = dict(t)
func = kwargs.pop('name')
cols = kwargs.pop('input', None)
if isinstance(func, string_types):
if func in ('and', 'or'):
func += '_'
... | 490,348 |
Add to the pool of available configuration files for BIDSLayout.
Args:
kwargs: dictionary specifying where to find additional config files.
Keys are names, values are paths to the corresponding .json file.
Example:
> add_config_paths(my_config='/path/to/config')
> layout = ... | def add_config_paths(**kwargs):
for k, path in kwargs.items():
if not os.path.exists(path):
raise ValueError(
'Configuration file "{}" does not exist'.format(k))
if k in cf.get_option('config_paths'):
raise ValueError('Configuration {!r} already exists'.... | 490,369 |
Returns the BIDSFile object with the specified path.
Args:
filename (str): The path of the file to retrieve. Must be either
an absolute path, or relative to the root of this BIDSLayout.
scope (str, list): Scope of the search space. If passed, only
BIDSLay... | def get_file(self, filename, scope='all'):
filename = os.path.abspath(os.path.join(self.root, filename))
layouts = self._get_layouts_in_scope(scope)
for ly in layouts:
if filename in ly.files:
return ly.files[filename]
return None | 490,380 |
Returns the scanning repetition time (TR) for one or more runs.
Args:
derivatives (bool): If True, also checks derivatives images.
selectors: Optional keywords used to constrain the selected runs.
Can be any arguments valid for a .get call (e.g., BIDS entities
... | def get_tr(self, derivatives=False, **selectors):
# Constrain search to functional images
selectors.update(suffix='bold', datatype='func')
scope = None if derivatives else 'raw'
images = self.get(extensions=['.nii', '.nii.gz'], scope=scope,
**selectors)... | 490,386 |
Index metadata for the specified file.
Args:
f (BIDSFile, str): A BIDSFile or path to an indexed file.
overwrite (bool): If True, forces reindexing of the file even if
an entry already exists. | def index_file(self, f, overwrite=False):
if isinstance(f, six.string_types):
f = self.layout.get_file(f)
if f.path in self.file_index and not overwrite:
return
if 'suffix' not in f.entities: # Skip files without suffixes
return
md = self.... | 490,391 |
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:
A list of SparseRunVariables, one per unique value in the
groupe... | def split(self, grouper):
data = self.to_df(condition=True, entities=True)
data = data.drop('condition', axis=1)
subsets = []
for i, (name, g) in enumerate(data.groupby(grouper)):
name = '%s.%s' % (self.name, name)
col = self.__class__(name=name, data=g,... | 490,401 |
Truncate internal arrays to keep only the specified rows.
Args:
rows (array): An integer or boolean array identifying the indices
of rows to keep. | def select_rows(self, rows):
self.values = self.values.iloc[rows]
self.index = self.index.iloc[rows, :]
for prop in self._property_columns:
vals = getattr(self, prop)[rows]
setattr(self, prop, vals) | 490,403 |
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 DenseRunVariable.
Returns:
A DenseRunVariable. | def to_dense(self, sampling_rate):
duration = int(math.ceil(sampling_rate * self.get_duration()))
ts = np.zeros(duration, dtype=self.values.dtype)
onsets = np.round(self.onset * sampling_rate).astype(int)
durations = np.round(self.duration * sampling_rate).astype(int)
... | 490,405 |
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 becomes necessary
to resample DenseRunVariables. Either an integer or 'auto' (see
merge_variables docstri... | def merge_collections(collections, force_dense=False, sampling_rate='auto'):
if len(listify(collections)) == 1:
return collections
levels = set([c.level for c in collections])
if len(levels) > 1:
raise ValueError("At the moment, it's only possible to merge "
"C... | 490,419 |
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
concatenated together).
Returns:
A list of Variables. | def merge_variables(variables, **kwargs):
var_dict = OrderedDict()
for v in variables:
if v.name not in var_dict:
var_dict[v.name] = []
var_dict[v.name].append(v)
return [merge_variables(vars_, **kwargs)
for vars_ in list(var_dict.... | 490,421 |
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.
entities (DataFrame): An optional second DataFrame containing
entity information.
s... | def from_df(cls, data, entities=None, source='contrast'):
variables = []
for col in data.columns:
_data = pd.DataFrame(data[col].values, columns=['amplitude'])
if entities is not None:
_data = pd.concat([_data, entities], axis=1, sort=True)
va... | 490,423 |
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 be one of:
'name': Returns a list of names of matching variables.
'variable': Re... | def match_variables(self, pattern, return_type='name'):
pattern = re.compile(pattern)
vars_ = [v for v in self.variables.values() if pattern.search(v.name)]
return vars_ if return_type.startswith('var') \
else [v.name for v in vars_] | 490,427 |
Returns a count of unique values or files.
Args:
files (bool): When True, counts all files mapped to the Entity.
When False, counts all unique values.
Returns: an int. | def count(self, files=False):
return len(self.files) if files else len(self.unique()) | 490,470 |
Return the appropriate child class given a subdirectory path.
Args:
path (str): The path to the subdirectory.
Returns: An uninstantiated BIDSNode or one of its subclasses. | 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 None:
return BIDSNode
... | 490,480 |
Initializes a new instance of the class.
Args:
instrumentation_key (str). the instrumentation key to use for this telemetry client.\n
telemetry_channel (:class:`channel.TelemetryChannel`). the optional telemetry channel to be used instead of
constructing a default one. | def __init__(self, instrumentation_key, telemetry_channel=None):
if instrumentation_key:
if isinstance(instrumentation_key, channel.TelemetryChannel):
telemetry_channel = instrumentation_key
instrumentation_key = None
else:
raise Exception... | 490,548 |
Send information about a single event that has occurred in the context of the application.
Args:
name (str). the data to associate to this event.\n
properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n
measurements... | 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.measurements = measurements
self.trac... | 490,551 |
Sends a single trace statement.
Args:
name (str). the trace statement.\n
properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n
severity (str). the severity level of this trace, one of DEBUG, INFO, WARNING, ERROR, C... | 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:
data.severity_level = channel.contracts.Me... | 490,553 |
The severity_level property.
Args:
value (int). the property value. | def severity_level(self, value):
if value == self._defaults['severityLevel'] and 'severityLevel' in self._values:
del self._values['severityLevel']
else:
self._values['severityLevel'] = value | 490,559 |
The problem_id property.
Args:
value (string). the property value. | def problem_id(self, value):
if value == self._defaults['problemId'] and 'problemId' in self._values:
del self._values['problemId']
else:
self._values['problemId'] = value | 490,560 |
The properties property.
Args:
value (hash). the property value. | def properties(self, value):
if value == self._defaults['properties'] and 'properties' in self._values:
del self._values['properties']
else:
self._values['properties'] = value | 490,562 |
The measurements property.
Args:
value (hash). the property value. | def measurements(self, value):
if value == self._defaults['measurements'] and 'measurements' in self._values:
del self._values['measurements']
else:
self._values['measurements'] = value | 490,564 |
The id property.
Args:
value (string). the property value. | 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 | 490,565 |
The locale property.
Args:
value (string). the property value. | 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 | 490,566 |
The model property.
Args:
value (string). the property value. | 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 | 490,567 |
The oem_name property.
Args:
value (string). the property value. | 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 | 490,568 |
The os_version property.
Args:
value (string). the property value. | 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 | 490,569 |
Adds the passed in item object to the queue and notifies the :func:`sender` to start an asynchronous
send operation by calling :func:`start`.
Args:
item (:class:`contracts.Envelope`) the telemetry envelope object to send to the service. | def put(self, item):
QueueBase.put(self, item)
if self.sender:
self.sender.start() | 490,571 |
The role property.
Args:
value (string). the property value. | 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 | 490,573 |
The role_instance property.
Args:
value (string). the property value. | 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 | 490,574 |
Initializes a new instance of the class.
Args:
service_endpoint_uri (str) the address of the service to send telemetry data to. | def __init__(self, service_endpoint_uri):
self._service_endpoint_uri = service_endpoint_uri
self._queue = None
self._send_buffer_size = 100
self._timeout = 10 | 490,575 |
Immediately sends the data passed in to :func:`service_endpoint_uri`. If the service request fails, the
passed in items are pushed back to the :func:`queue`.
Args:
data_to_send (Array): an array of :class:`contracts.Envelope` objects to send to the service. | 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' : 'application/json; charset=utf-8' })
try:
... | 490,576 |
Initialize a new instance of the extension.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | def __init__(self, app=None):
self._key = None
self._endpoint_uri = None
self._channel = None
self._requests_middleware = None
self._trace_log_handler = None
self._exception_telemetry_client = None
if app:
self.init_app(app) | 490,583 |
Initializes the extension for the provided Flask application.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | 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)
queue = AsynchronousQueue(sender)
self... | 490,584 |
Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
is set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | 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=self._channel)
app.wsgi_app = self._r... | 490,585 |
Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | 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)
app.logger.addHandler(self._trace_log_handl... | 490,586 |
Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING``
is set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | 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._channel)
@app.errorhandler(Exception)
... | 490,587 |
The run_location property.
Args:
value (string). the property value. | def run_location(self, value):
if value == self._defaults['runLocation'] and 'runLocation' in self._values:
del self._values['runLocation']
else:
self._values['runLocation'] = value | 490,589 |
The message property.
Args:
value (string). the property value. | def message(self, value):
if value == self._defaults['message'] and 'message' in self._values:
del self._values['message']
else:
self._values['message'] = value | 490,590 |
The parent_id property.
Args:
value (string). the property value. | 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 | 490,591 |
The synthetic_source property.
Args:
value (string). the property value. | 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.operation.syntheticSource'] = value | 490,592 |
The correlation_vector property.
Args:
value (string). the property value. | 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.operation.correlationVector'] = value | 490,593 |
Initializes a new instance of the class.
Args:
sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue.
persistence_path (str) if set, persist the queue on disk into the provided directory. | def __init__(self, sender, persistence_path=''):
if persistence_path and PersistQueue is None:
raise ValueError('persistence_path argument requires persist-queue dependency to be installed')
elif persistence_path:
self._queue = PersistQueue(persistence_path)
else... | 490,604 |
Adds the passed in item object to the queue and calls :func:`flush` if the size of the queue is larger
than :func:`max_queue_length`. This method does nothing if the passed in item is None.
Args:
item (:class:`contracts.Envelope`) item the telemetry envelope object to send to the service. | def put(self, item):
if not item:
return
self._queue.put(item)
if self._queue.qsize() >= self._max_queue_length:
self.flush() | 490,605 |
Initialize a new instance of the class.
Args:
instrumentation_key (str). the instrumentation key to use while sending telemetry to the service. | def __init__(self, instrumentation_key, *args, **kwargs):
if not instrumentation_key:
raise Exception('Instrumentation key was required but not provided')
telemetry_channel = kwargs.get('telemetry_channel')
if 'telemetry_channel' in kwargs:
del kwargs['telemetry_... | 490,608 |
Emit a record.
If a formatter is specified, it is used to format the record. If exception information is present, an Exception
telemetry object is sent instead of a Trace telemetry object.
Args:
record (:class:`logging.LogRecord`). the record to format and send. | 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.lineno,
'level': record.levelname,
... | 490,609 |
Initializes a new instance of the class.
Args:
context (:class:`TelemetryContext') the telemetry context to use when sending telemetry data.\n
queue (:class:`QueueBase`) the queue to enqueue the resulting :class:`contracts.Envelope` to. | def __init__(self, context=None, queue=None):
self._context = context or TelemetryContext()
self._queue = queue or SynchronousQueue(SynchronousSender()) | 490,611 |
The base_type property.
Args:
value (string). the property value. | def base_type(self, value):
if value == self._defaults['baseType'] and 'baseType' in self._values:
del self._values['baseType']
else:
self._values['baseType'] = value | 490,614 |
The ip property.
Args:
value (string). the property value. | 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 | 490,615 |
The ver property.
Args:
value (int). the property value. | def ver(self, value):
if value == self._defaults['ver'] and 'ver' in self._values:
del self._values['ver']
else:
self._values['ver'] = value | 490,616 |
The sample_rate property.
Args:
value (float). the property value. | def sample_rate(self, value):
if value == self._defaults['sampleRate'] and 'sampleRate' in self._values:
del self._values['sampleRate']
else:
self._values['sampleRate'] = value | 490,617 |
The seq property.
Args:
value (string). the property value. | def seq(self, value):
if value == self._defaults['seq'] and 'seq' in self._values:
del self._values['seq']
else:
self._values['seq'] = value | 490,618 |
The ikey property.
Args:
value (string). the property value. | def ikey(self, value):
if value == self._defaults['iKey'] and 'iKey' in self._values:
del self._values['iKey']
else:
self._values['iKey'] = value | 490,619 |
The tags property.
Args:
value (hash). the property value. | def tags(self, value):
if value == self._defaults['tags'] and 'tags' in self._values:
del self._values['tags']
else:
self._values['tags'] = value | 490,621 |
The data property.
Args:
value (object). the property value. | def data(self, value):
if value == self._defaults['data'] and 'data' in self._values:
del self._values['data']
else:
self._values['data'] = value | 490,622 |
The account_id property.
Args:
value (string). the property value. | def account_id(self, value):
if value == self._defaults['ai.user.accountId'] and 'ai.user.accountId' in self._values:
del self._values['ai.user.accountId']
else:
self._values['ai.user.accountId'] = value | 490,623 |
The auth_user_id property.
Args:
value (string). the property value. | def auth_user_id(self, value):
if value == self._defaults['ai.user.authUserId'] and 'ai.user.authUserId' in self._values:
del self._values['ai.user.authUserId']
else:
self._values['ai.user.authUserId'] = value | 490,624 |
The sdk_version property.
Args:
value (string). the property value. | def sdk_version(self, value):
if value == self._defaults['ai.internal.sdkVersion'] and 'ai.internal.sdkVersion' in self._values:
del self._values['ai.internal.sdkVersion']
else:
self._values['ai.internal.sdkVersion'] = value | 490,625 |
The agent_version property.
Args:
value (string). the property value. | def agent_version(self, value):
if value == self._defaults['ai.internal.agentVersion'] and 'ai.internal.agentVersion' in self._values:
del self._values['ai.internal.agentVersion']
else:
self._values['ai.internal.agentVersion'] = value | 490,626 |
The node_name property.
Args:
value (string). the property value. | def node_name(self, value):
if value == self._defaults['ai.internal.nodeName'] and 'ai.internal.nodeName' in self._values:
del self._values['ai.internal.nodeName']
else:
self._values['ai.internal.nodeName'] = value | 490,627 |
Initializes a new instance of the class.
Args:
sender (String) service_endpoint_uri the address of the service to send telemetry data to. | def __init__(self, service_endpoint_uri=None):
self._send_interval = 1.0
self._send_remaining_time = 0
self._send_time = 3.0
self._lock_send_remaining_time = Lock()
SenderBase.__init__(self, service_endpoint_uri or DEFAULT_ENDPOINT_URL) | 490,628 |
The source property.
Args:
value (string). the property value. | def source(self, value):
if value == self._defaults['source'] and 'source' in self._values:
del self._values['source']
else:
self._values['source'] = value | 490,631 |
The name property.
Args:
value (string). the property value. | def name(self, value):
if value == self._defaults['name'] and 'name' in self._values:
del self._values['name']
else:
self._values['name'] = value | 490,632 |
The url property.
Args:
value (string). the property value. | def url(self, value):
if value == self._defaults['url'] and 'url' in self._values:
del self._values['url']
else:
self._values['url'] = value | 490,633 |
The ns property.
Args:
value (string). the property value. | def ns(self, value):
if value == self._defaults['ns'] and 'ns' in self._values:
del self._values['ns']
else:
self._values['ns'] = value | 490,638 |
The kind property.
Args:
value (:class:`DataPointType.measurement`). the property value. | def kind(self, value):
if value == self._defaults['kind'] and 'kind' in self._values:
del self._values['kind']
else:
self._values['kind'] = value | 490,639 |
The count property.
Args:
value (int). the property value. | def count(self, value):
if value == self._defaults['count'] and 'count' in self._values:
del self._values['count']
else:
self._values['count'] = value | 490,640 |
The min property.
Args:
value (float). the property value. | def min(self, value):
if value == self._defaults['min'] and 'min' in self._values:
del self._values['min']
else:
self._values['min'] = value | 490,641 |
The max property.
Args:
value (float). the property value. | def max(self, value):
if value == self._defaults['max'] and 'max' in self._values:
del self._values['max']
else:
self._values['max'] = value | 490,642 |
The std_dev property.
Args:
value (float). the property value. | def std_dev(self, value):
if value == self._defaults['stdDev'] and 'stdDev' in self._values:
del self._values['stdDev']
else:
self._values['stdDev'] = value | 490,643 |
Initialize a new instance of the class.
Args:
instrumentation_key (str). the instrumentation key to use while sending telemetry to the service.\n
wsgi_application (func). the WSGI application that we're wrapping. | def __init__(self, instrumentation_key, wsgi_application, *args, **kwargs):
if not instrumentation_key:
raise Exception('Instrumentation key was required but not provided')
if not wsgi_application:
raise Exception('WSGI application was required but not provided')
... | 490,644 |
Callable implementation for WSGI middleware.
Args:
environ (dict). a dictionary containing all WSGI environment properties for this request.\n
start_response (func). a function used to store the status, HTTP headers to be sent to the client and optional exception information.
R... | def __call__(self, environ, start_response):
start_time = datetime.datetime.utcnow()
name = environ.get('PATH_INFO') or '/'
closure = {'status': '200 OK'}
http_method = environ.get('REQUEST_METHOD', 'GET')
self.client.context.operation.id = str(uuid.uuid4())
# o... | 490,645 |
The perf_total property.
Args:
value (string). the property value. | def perf_total(self, value):
if value == self._defaults['perfTotal'] and 'perfTotal' in self._values:
del self._values['perfTotal']
else:
self._values['perfTotal'] = value | 490,646 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.