_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q12400
PointCloudImage.open
train
def open(filename, frame='unspecified'): """Creates a PointCloudImage from a file. Parameters ---------- filename : :obj:`str` The file to load the data from. Must be one of .png, .jpg, .npy, or .npz. frame : :obj:`str` A string representing the frame of reference in which the new image lies. Returns
python
{ "resource": "" }
q12401
NormalCloudImage.to_normal_cloud
train
def to_normal_cloud(self): """Convert the image to a NormalCloud object. Returns ------- :obj:`autolab_core.NormalCloud` The corresponding NormalCloud. """ return NormalCloud(
python
{ "resource": "" }
q12402
NormalCloudImage.open
train
def open(filename, frame='unspecified'): """Creates a NormalCloudImage from a file. Parameters ---------- filename : :obj:`str` The file to load the data from. Must be one of .png, .jpg, .npy, or .npz. frame : :obj:`str` A string representing the frame of reference in which the new image lies. Returns
python
{ "resource": "" }
q12403
OrthographicIntrinsics.deproject
train
def deproject(self, depth_image): """Deprojects a DepthImage into a PointCloud. Parameters ---------- depth_image : :obj:`DepthImage` The 2D depth image to projet into a point cloud. Returns ------- :obj:`autolab_core.PointCloud` A 3D point cloud created from the depth image. Raises ------ ValueError If depth_image is not a valid DepthImage in the same reference frame as the camera. """ # check valid input if not isinstance(depth_image, DepthImage): raise ValueError('Must provide DepthImage object for projection') if depth_image.frame != self._frame: raise ValueError('Cannot deproject points in frame %s from camera with frame %s' %(depth_image.frame, self._frame)) # create homogeneous pixels
python
{ "resource": "" }
q12404
OrthographicIntrinsics.deproject_pixel
train
def deproject_pixel(self, depth, pixel): """Deprojects a single pixel with a given depth into a 3D point. Parameters ---------- depth : float The depth value at the given pixel location. pixel : :obj:`autolab_core.Point` A 2D point representing the pixel's location in the camera image. Returns ------- :obj:`autolab_core.Point` The projected 3D point. Raises ------ ValueError If pixel is not a valid 2D Point in the same reference frame as the camera.
python
{ "resource": "" }
q12405
OrthographicIntrinsics.save
train
def save(self, filename): """Save the CameraIntrinsics object to a .intr file. Parameters ---------- filename : :obj:`str` The .intr file to save the object to. Raises ------ ValueError If filename does not have the .intr extension. """ file_root, file_ext = os.path.splitext(filename) if file_ext.lower() != INTR_EXTENSION:
python
{ "resource": "" }
q12406
PhoXiSensor._connect_to_sensor
train
def _connect_to_sensor(self): """Connect to the sensor. """ name = self._device_name try: # Check if device is actively in list rospy.wait_for_service('phoxi_camera/get_device_list') device_list = rospy.ServiceProxy('phoxi_camera/get_device_list', GetDeviceList)().out if not str(name) in device_list: logging.error('PhoXi sensor {} not in list of active devices'.format(name)) return False success = rospy.ServiceProxy('phoxi_camera/connect_camera', ConnectCamera)(name).success if not success:
python
{ "resource": "" }
q12407
PhoXiSensor._depth_im_callback
train
def _depth_im_callback(self, msg): """Callback for handling depth images. """ try:
python
{ "resource": "" }
q12408
PhoXiSensor._normal_map_callback
train
def _normal_map_callback(self, msg): """Callback for handling normal maps. """ try:
python
{ "resource": "" }
q12409
RgbdDetection.image
train
def image(self, render_mode): """ Get the image associated with a particular render mode """ if render_mode == RenderMode.SEGMASK: return self.query_im elif render_mode == RenderMode.COLOR: return self.color_im elif render_mode
python
{ "resource": "" }
q12410
RgbdDetectorFactory.detector
train
def detector(detector_type): """ Returns a detector of the specified type. """ if detector_type == 'point_cloud_box': return PointCloudBoxDetector() elif detector_type == 'rgbd_foreground_mask_query': return RgbdForegroundMaskQueryImageDetector()
python
{ "resource": "" }
q12411
AlexNet._parse_config
train
def _parse_config(self, config): """ Parses a tensorflow configuration """ self._batch_size = config['batch_size'] self._im_height = config['im_height'] self._im_width = config['im_width'] self._num_channels = config['channels'] self._output_layer = config['out_layer'] self._feature_layer = config['feature_layer'] self._out_size = None if 'out_size' in config.keys(): self._out_size = config['out_size'] self._input_arr = np.zeros([self._batch_size, self._im_height, self._im_width, self._num_channels])
python
{ "resource": "" }
q12412
AlexNet._load
train
def _load(self): """ Loads a model into weights """ if self._model_filename is None: raise ValueError('Model filename not specified') # read the input image self._graph = tf.Graph() with self._graph.as_default(): # read in filenames reader = tf.train.NewCheckpointReader(self._model_filename) # load AlexNet weights weights = AlexNetWeights() weights.conv1W = tf.Variable(reader.get_tensor("Variable")) weights.conv1b = tf.Variable(reader.get_tensor("Variable_1")) weights.conv2W = tf.Variable(reader.get_tensor("Variable_2")) weights.conv2b = tf.Variable(reader.get_tensor("Variable_3")) weights.conv3W = tf.Variable(reader.get_tensor("Variable_4")) weights.conv3b = tf.Variable(reader.get_tensor("Variable_5")) weights.conv4W = tf.Variable(reader.get_tensor("Variable_6")) weights.conv4b = tf.Variable(reader.get_tensor("Variable_7")) weights.conv5W = tf.Variable(reader.get_tensor("Variable_8")) weights.conv5b
python
{ "resource": "" }
q12413
AlexNet._initialize
train
def _initialize(self): """ Open from caffe weights """ self._graph = tf.Graph() with self._graph.as_default(): self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width,
python
{ "resource": "" }
q12414
AlexNet.open_session
train
def open_session(self): """ Open tensorflow session. Exposed for memory management. """ with self._graph.as_default(): init =
python
{ "resource": "" }
q12415
AlexNet.close_session
train
def close_session(self): """ Close tensorflow session. Exposes for memory management. """
python
{ "resource": "" }
q12416
AlexNet.predict
train
def predict(self, image_arr, featurize=False): """ Predict a set of images in batches. Parameters ---------- image_arr : NxHxWxC :obj:`numpy.ndarray` input set of images in a num_images x image height x image width x image channels array (must match parameters of network) featurize : bool whether or not to use the featurization layer or classification output layer Returns ------- :obj:`numpy.ndarray` num_images x feature_dim containing the output values for each input image """ # setup prediction num_images = image_arr.shape[0] output_arr = None # predict by filling in image array in batches close_sess = False if not self._initialized and self._dynamic_load: self._load() with self._graph.as_default(): if self._sess is None: close_sess = True self.open_session() i = 0 while i < num_images: dim =
python
{ "resource": "" }
q12417
AlexNet.build_alexnet_weights
train
def build_alexnet_weights(self): """ Build a set of convnet weights for AlexNet """ net_data = self._net_data #conv1 #conv(11, 11, 96, 4, 4, padding='VALID', name='conv1') k_h = 11; k_w = 11; c_o = 96; s_h = 4; s_w = 4 conv1W = tf.Variable(net_data["conv1"][0]) conv1b = tf.Variable(net_data["conv1"][1]) #conv2 #conv(5, 5, 256, 1, 1, group=2, name='conv2') k_h = 5; k_w = 5; c_o = 256; s_h = 1; s_w = 1; group = 2 conv2W = tf.Variable(net_data["conv2"][0]) conv2b = tf.Variable(net_data["conv2"][1]) #conv3 #conv(3, 3, 384, 1, 1, name='conv3') k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 1 conv3W = tf.Variable(net_data["conv3"][0]) conv3b = tf.Variable(net_data["conv3"][1]) #conv4 #conv(3, 3, 384, 1, 1, group=2, name='conv4') k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 2 conv4W = tf.Variable(net_data["conv4"][0]) conv4b = tf.Variable(net_data["conv4"][1]) #conv5 #conv(3, 3, 256, 1, 1, group=2, name='conv5') k_h =
python
{ "resource": "" }
q12418
CNNBatchFeatureExtractor._forward_pass
train
def _forward_pass(self, images): """ Forward pass a list of images through the CNN """ # form image array num_images = len(images) if num_images == 0: return None for image in images: if not isinstance(image, Image): new_images = [] for image in images: if len(image.shape) > 2: new_images.append(ColorImage(image, frame='unspecified')) elif image.dtype == np.float32 or image.dtype == np.float64: new_images.append(DepthImage(image, frame='unspecified')) else: raise ValueError('Image type not understood') images = new_images break im_height = images[0].height im_width = images[0].width channels = images[0].channels tensor_channels = 3 image_arr = np.zeros([num_images, im_height, im_width, tensor_channels])
python
{ "resource": "" }
q12419
Engine.repositories
train
def repositories(self): """ Returns a DataFrame with the data about the repositories found at the specified repositories path in the form of siva files. >>> repos_df = engine.repositories :rtype: RepositoriesDataFrame """
python
{ "resource": "" }
q12420
Engine.blobs
train
def blobs(self, repository_ids=[], reference_names=[], commit_hashes=[]): """ Retrieves the blobs of a list of repositories, reference names and commit hashes. So the result will be a DataFrame of all the blobs in the given commits that are in the given references that belong to the given repositories. >>> blobs_df = engine.blobs(repo_ids, ref_names, hashes) Calling this function with no arguments is the same as: >>> engine.repositories.references.commits.tree_entries.blobs :param repository_ids: list of repository ids to filter by (optional) :type repository_ids: list of strings :param reference_names: list of reference names to filter by (optional) :type reference_names: list of strings :param commit_hashes: list of hashes to filter by (optional) :type commit_hashes: list of strings
python
{ "resource": "" }
q12421
Engine.from_metadata
train
def from_metadata(self, db_path, db_name='engine_metadata.db'): """ Registers in the current session the views of the MetadataSource so the data is obtained from the metadata database instead of reading the repositories with the DefaultSource. :param db_path: path to the folder that contains the database. :type db_path: str
python
{ "resource": "" }
q12422
SourcedDataFrame.__generate_method
train
def __generate_method(name): """ Wraps the DataFrame's original method by name to return the derived class instance. """ try: func = getattr(DataFrame, name) except AttributeError as e: # PySpark version is too old def func(self, *args, **kwargs): raise e return func wraps = getattr(functools, "wraps", lambda _: lambda f: f) # py3.4+ @wraps(func) def _wrapper(self, *args, **kwargs): dataframe = func(self, *args, **kwargs)
python
{ "resource": "" }
q12423
RepositoriesDataFrame.references
train
def references(self): """ Returns the joined DataFrame of references and repositories. >>> refs_df = repos_df.references :rtype: ReferencesDataFrame
python
{ "resource": "" }
q12424
RepositoriesDataFrame.remote_references
train
def remote_references(self): """ Returns a new DataFrame with only the remote references of the current repositories. >>> remote_refs_df = repos_df.remote_references
python
{ "resource": "" }
q12425
RepositoriesDataFrame.master_ref
train
def master_ref(self): """ Filters the current DataFrame references to only contain those rows whose reference is master. >>> master_df = repos_df.master_ref
python
{ "resource": "" }
q12426
ReferencesDataFrame.head_ref
train
def head_ref(self): """ Filters the current DataFrame to only contain those rows whose reference is HEAD. >>> heads_df = refs_df.head_ref
python
{ "resource": "" }
q12427
ReferencesDataFrame.master_ref
train
def master_ref(self): """ Filters the current DataFrame to only contain those rows whose reference is master. >>> master_df = refs_df.master_ref :rtype: ReferencesDataFrame
python
{ "resource": "" }
q12428
ReferencesDataFrame.ref
train
def ref(self, ref): """ Filters the current DataFrame to only contain those rows whose reference is the given reference name. >>> heads_df = refs_df.ref('refs/heads/HEAD') :param ref: Reference to get :type ref: str :rtype: ReferencesDataFrame
python
{ "resource": "" }
q12429
ReferencesDataFrame.all_reference_commits
train
def all_reference_commits(self): """ Returns the current DataFrame joined with the commits DataFrame, with all of the commits in all references. >>> commits_df = refs_df.all_reference_commits Take into account that getting all the commits will lead to a lot of repeated tree entries and blobs, thus making your query very slow.
python
{ "resource": "" }
q12430
ReferencesDataFrame.blobs
train
def blobs(self): """ Returns this DataFrame joined with the blobs DataSource. >>> blobs_df = refs_df.blobs
python
{ "resource": "" }
q12431
CommitsDataFrame.tree_entries
train
def tree_entries(self): """ Returns this DataFrame joined with the tree entries DataSource. >>> entries_df = commits_df.tree_entries :rtype: TreeEntriesDataFrame
python
{ "resource": "" }
q12432
BlobsDataFrame.classify_languages
train
def classify_languages(self): """ Returns a new DataFrame with the language data of any blob added to its row. >>> blobs_lang_df = blobs_df.classify_languages :rtype: BlobsWithLanguageDataFrame
python
{ "resource": "" }
q12433
BlobsDataFrame.extract_uasts
train
def extract_uasts(self): """ Returns a new DataFrame with the parsed UAST data of any blob added to its row.
python
{ "resource": "" }
q12434
UASTsDataFrame.query_uast
train
def query_uast(self, query, query_col='uast', output_col='result'): """ Queries the UAST of a file with the given query to get specific nodes. >>> rows = uasts_df.query_uast('//*[@roleIdentifier]').collect() >>> rows = uasts_df.query_uast('//*[@roleIdentifier]', 'foo', 'bar') :param query: xpath query :type query: str :param query_col: column containing the list of nodes to query :type query_col: str :param output_col: column to place the result of the query :type output_col: str
python
{ "resource": "" }
q12435
UASTsDataFrame.extract_tokens
train
def extract_tokens(self, input_col='result', output_col='tokens'): """ Extracts the tokens from UAST nodes. >>> rows = uasts_df.query_uast('//*[@roleIdentifier]').extract_tokens().collect() >>> rows = uasts_df.query_uast('//*[@roleIdentifier]', output_col='foo').extract_tokens('foo', 'bar') :param input_col: column containing the list of nodes to extract tokens from :type input_col: str
python
{ "resource": "" }
q12436
GSBlobStore.delete
train
def delete(self, bucket: str, key: str): """ Deletes an object in a bucket. If the operation definitely did not delete anything, return False. Any other return value is treated as something was possibly deleted. """ bucket_obj
python
{ "resource": "" }
q12437
API_WRAPPER.request
train
def request(self, shards, full_response, return_status_tuple=False): """Request the API This method is wrapped by similar functions """ try: resp = self._request(shards) if return_status_tuple: return (self._parser(resp, full_response), True) else: return self._parser(resp, full_response) except (ConflictError, CloudflareServerError, InternalServerError) as exc: # The Retry system if return_status_tuple: return (None, False) elif self.api_mother.do_retry:
python
{ "resource": "" }
q12438
API_WRAPPER.command
train
def command(self, command, full_response=False, **kwargs): # pragma: no cover """Method Interface to the command API for Nationstates""" command = Shard(c=command)
python
{ "resource": "" }
q12439
Nation.send_telegram
train
def send_telegram(telegram=None, client_key=None, tgid=None, key=None): # pragma: no cover """Sends Telegram. Can either provide a telegram directly, or provide the api details and created internally """
python
{ "resource": "" }
q12440
Nation.verify
train
def verify(self, checksum=None, token=None, full_response=False): """Wraps around the verify API""" payload = {"checksum":checksum, "a":"verify"} if token:
python
{ "resource": "" }
q12441
BlobStore.upload_file_handle
train
def upload_file_handle( self, bucket: str, key: str, src_file_handle: typing.BinaryIO, content_type: str=None, metadata: dict=None): """
python
{ "resource": "" }
q12442
S3BlobStore.find_next_missing_parts
train
def find_next_missing_parts( self, bucket: str, key: str, upload_id: str, part_count: int, search_start: int=1, return_count: int=1) -> typing.Sequence[int]: """ Given a `bucket`, `key`, and `upload_id`, find the next N missing parts of a multipart upload, where N=`return_count`. If `search_start` is provided, start the search at part M, where M=`search_start`. `part_count` is the number of parts expected for the upload. Note that the return value may contain fewer than N parts. """ if part_count < search_start: raise ValueError("") result = list() while True: kwargs = dict(Bucket=bucket, Key=key, UploadId=upload_id) # type: dict if search_start > 1: kwargs['PartNumberMarker'] = search_start - 1 # retrieve all the parts after the one we *think* we need to start from. parts_resp = self.s3_client.list_parts(**kwargs) # build a set of all the parts known to be uploaded, detailed in this request. parts_map = set() # type: typing.Set[int]
python
{ "resource": "" }
q12443
scanf_compile
train
def scanf_compile(format, collapseWhitespace=True): """ Translate the format into a regular expression For example: >>> format_re, casts = scanf_compile('%s - %d errors, %d warnings') >>> print format_re.pattern (\S+) \- ([+-]?\d+) errors, ([+-]?\d+) warnings Translated formats are cached for faster reuse """ format_pat = "" cast_list = [] i = 0 length = len(format) while i < length: found = None for token, pattern, cast in scanf_translate: found = token.match(format, i) if found: if cast: # cast != None cast_list.append(cast) groups = found.groupdict() or found.groups() if groups: pattern = pattern % groups format_pat += pattern
python
{ "resource": "" }
q12444
extractdata
train
def extractdata(pattern, text=None, filepath=None): """ Read through an entire file or body of text one line at a time. Parse each line that matches the supplied pattern string and ignore the rest. If *text* is supplied, it will be parsed according to the *pattern* string. If *text* is not supplied, the file at *filepath* will be opened and parsed. """ y = [] if text is None: textsource = open(filepath, 'r') else: textsource = text.splitlines() for line in textsource: match
python
{ "resource": "" }
q12445
Nationstates.nation
train
def nation(self, nation_name, password=None, autologin=None): """Setup access to the Nation API with the Nation object :param nation_name: Name of the nation :param password: (Optional) password for this nation
python
{ "resource": "" }
q12446
Nationstates.wa
train
def wa(self, chamber): """Setup access to the World Assembly API with the WorldAssembly object :param chamber: Chamber of the WA :type chamber: str, int :returns: WorldAssembly Object based off region_name :rtype: WorldAssembly
python
{ "resource": "" }
q12447
apply_patch
train
def apply_patch(diffs): """ Not ready for use yet """ pass if isinstance(diffs, patch.diff): diffs = [diffs] for diff in diffs: if diff.header.old_path == '/dev/null': text = [] else:
python
{ "resource": "" }
q12448
b64decode_url
train
def b64decode_url(istr): """ JWT Tokens may be truncated without the usual trailing padding '=' symbols. Compensate by padding to the nearest 4
python
{ "resource": "" }
q12449
_validate
train
def _validate(claims, validate_claims, expiry_seconds): """ Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided. """ if not validate_claims: return now = time() # TODO: implement support for clock skew # The exp (expiration time) claim identifies the expiration time on or # after which the JWT MUST NOT be accepted for processing. The # processing of the exp claim requires that the current date/time MUST # be before the expiration date/time listed in the exp claim. try: expiration_time = claims[CLAIM_EXPIRATION_TIME] except KeyError:
python
{ "resource": "" }
q12450
gauge
train
def gauge(key, gauge=None, default=float("nan"), **dims): """Adds gauge with dimensions to the global pyformance registry"""
python
{ "resource": "" }
q12451
count_calls_with_dims
train
def count_calls_with_dims(**dims): """Decorator to track the number of times a function is called with with dimensions. """ def counter_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): counter("%s_calls" %
python
{ "resource": "" }
q12452
meter_calls_with_dims
train
def meter_calls_with_dims(**dims): """Decorator to track the rate at which a function is called with dimensions. """ def meter_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): meter("%s_calls" %
python
{ "resource": "" }
q12453
hist_calls
train
def hist_calls(fn): """ Decorator to check the distribution of return values of a function. """ @functools.wraps(fn) def wrapper(*args, **kwargs): _histogram = histogram( "%s_calls" % pyformance.registry.get_qualname(fn)) rtn =
python
{ "resource": "" }
q12454
hist_calls_with_dims
train
def hist_calls_with_dims(**dims): """Decorator to check the distribution of return values of a function with dimensions. """ def hist_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): _histogram = histogram( "%s_calls" % pyformance.registry.get_qualname(fn), **dims)
python
{ "resource": "" }
q12455
time_calls_with_dims
train
def time_calls_with_dims(**dims): """Decorator to time the execution of the function with dimensions.""" def time_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): _timer = timer("%s_calls" %
python
{ "resource": "" }
q12456
MetricsRegistry.add
train
def add(self, key, metric, **dims): """Adds custom metric instances to the registry with dimensions which are not created with their constructors default arguments """
python
{ "resource": "" }
q12457
_BaseSignalFxIngestClient.send
train
def send(self, cumulative_counters=None, gauges=None, counters=None): """Send the given metrics to SignalFx. Args: cumulative_counters (list): a list of dictionaries representing the cumulative counters to report. gauges (list): a list of dictionaries representing the gauges to report. counters (list): a list of dictionaries representing the counters to report. """ if not gauges and not cumulative_counters and not counters:
python
{ "resource": "" }
q12458
_BaseSignalFxIngestClient.send_event
train
def send_event(self, event_type, category=None, dimensions=None, properties=None, timestamp=None): """Send an event to SignalFx. Args: event_type (string): the event type (name of the event time series). category (string): the category of the event. dimensions (dict): a map of event dimensions. properties (dict): a map of extra properties on that event. timestamp (float): timestamp when the event has occured """ if category and category not in SUPPORTED_EVENT_CATEGORIES: raise ValueError('Event category is not one of the supported' + 'types: {' + ', '.join(SUPPORTED_EVENT_CATEGORIES) + '}') data = { 'eventType': event_type, 'category': category,
python
{ "resource": "" }
q12459
_BaseSignalFxIngestClient.stop
train
def stop(self, msg='Thread stopped'): """Stop send thread and flush points for a safe exit.""" with self._lock: if not self._thread_running: return self._thread_running = False
python
{ "resource": "" }
q12460
ProtoBufSignalFxIngestClient._assign_value_by_type
train
def _assign_value_by_type(self, pbuf_obj, value, _bool=True, _float=True, _integer=True, _string=True, error_prefix=''): """Assigns the supplied value to the appropriate protobuf value type""" # bool inherits int, so bool instance check must be executed prior to # checking for integer types if isinstance(value, bool) and _bool is True: pbuf_obj.value.boolValue = value elif isinstance(value, six.integer_types) and \ not isinstance(value, bool) and _integer is True: if value < INTEGER_MIN or value > INTEGER_MAX: raise ValueError( ('{}: {} exceeds signed 64 bit integer range ' 'as defined by ProtocolBuffers ({} to {})') .format(error_prefix, str(value),
python
{ "resource": "" }
q12461
ProtoBufSignalFxIngestClient._assign_value
train
def _assign_value(self, pbuf_dp, value): """Assigns a value to the protobuf obj""" self._assign_value_by_type(pbuf_dp,
python
{ "resource": "" }
q12462
Computation.stream
train
def stream(self): """Iterate over the messages from the computation's output. Control and metadata messages are intercepted and interpreted to enhance this Computation's object knowledge of the computation's context. Data and event messages are yielded back to the caller as a generator. """ iterator = iter(self._stream) while self._state < Computation.STATE_COMPLETED: try: message = next(iterator) except StopIteration: if self._state < Computation.STATE_COMPLETED: self._stream = self._execute() iterator = iter(self._stream) continue if isinstance(message, messages.StreamStartMessage): self._state = Computation.STATE_STREAM_STARTED continue if isinstance(message, messages.JobStartMessage): self._state = Computation.STATE_COMPUTATION_STARTED self._id = message.handle yield message continue if isinstance(message, messages.JobProgressMessage): yield message continue if isinstance(message, messages.ChannelAbortMessage): self._state = Computation.STATE_ABORTED raise errors.ComputationAborted(message.abort_info) if isinstance(message, messages.EndOfChannelMessage): self._state = Computation.STATE_COMPLETED continue # Intercept metadata messages to accumulate received metadata... if isinstance(message, messages.MetadataMessage): self._metadata[message.tsid] = message.properties yield message continue # ...as well as expired-tsid messages to clean it up. if isinstance(message, messages.ExpiredTsIdMessage): if message.tsid in self._metadata: del self._metadata[message.tsid] yield message continue if isinstance(message, messages.InfoMessage): self._process_info_message(message.message) self._batch_count_detected = True if self._current_batch_message:
python
{ "resource": "" }
q12463
Computation._process_info_message
train
def _process_info_message(self, message): """Process an information message received from the computation.""" # Extract the output resolution from the appropriate message, if
python
{ "resource": "" }
q12464
SignalFlowClient.execute
train
def execute(self, program, start=None, stop=None, resolution=None, max_delay=None, persistent=False, immediate=False, disable_all_metric_publishes=None): """Execute the given SignalFlow program and stream the output back.""" params = self._get_params(start=start, stop=stop, resolution=resolution,
python
{ "resource": "" }
q12465
SignalFlowClient.preflight
train
def preflight(self, program, start, stop, resolution=None, max_delay=None): """Preflight the given SignalFlow program and stream the output back.""" params = self._get_params(start=start, stop=stop, resolution=resolution, maxDelay=max_delay)
python
{ "resource": "" }
q12466
SignalFlowClient.start
train
def start(self, program, start=None, stop=None, resolution=None, max_delay=None): """Start executing the given SignalFlow program without being attached to the output of the computation.""" params = self._get_params(start=start, stop=stop,
python
{ "resource": "" }
q12467
SignalFlowClient.attach
train
def attach(self, handle, filters=None, resolution=None): """Attach to an existing SignalFlow computation.""" params = self._get_params(filters=filters, resolution=resolution) c = computation.Computation(
python
{ "resource": "" }
q12468
SignalFlowClient.stop
train
def stop(self, handle, reason=None): """Stop a SignalFlow computation.""" params
python
{ "resource": "" }
q12469
SignalFxRestClient.get_metric_by_name
train
def get_metric_by_name(self, metric_name, **kwargs): """ get a metric by name Args: metric_name (string): name of metric Returns: dictionary of response """
python
{ "resource": "" }
q12470
SignalFxRestClient.update_metric_by_name
train
def update_metric_by_name(self, metric_name, metric_type, description=None, custom_properties=None, tags=None, **kwargs): """ Create or update a metric object Args: metric_name (string): name of metric type (string): metric type, must be one of 'gauge', 'counter', 'cumulative_counter' description (optional[string]): a description custom_properties (optional[dict]): dictionary of custom properties tags (optional[list of strings]): list of tags associated with metric """
python
{ "resource": "" }
q12471
SignalFxRestClient.get_dimension
train
def get_dimension(self, key, value, **kwargs): """ get a dimension by key and value Args: key (string): key of the dimension value (string): value of the dimension Returns: dictionary of response
python
{ "resource": "" }
q12472
SignalFxRestClient.get_metric_time_series
train
def get_metric_time_series(self, mts_id, **kwargs): """get a metric time series by id""" return self._get_object_by_name(self._MTS_ENDPOINT_SUFFIX,
python
{ "resource": "" }
q12473
SignalFxRestClient.get_tag
train
def get_tag(self, tag_name, **kwargs): """get a tag by name Args: tag_name (string): name of tag to get Returns:
python
{ "resource": "" }
q12474
SignalFxRestClient.update_tag
train
def update_tag(self, tag_name, description=None, custom_properties=None, **kwargs): """update a tag by name Args: tag_name (string): name of tag to update description (optional[string]): a description custom_properties (optional[dict]): dictionary of custom properties """ data
python
{ "resource": "" }
q12475
SignalFxRestClient.delete_tag
train
def delete_tag(self, tag_name, **kwargs): """delete a tag by name Args: tag_name (string): name of tag to delete """ resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),
python
{ "resource": "" }
q12476
SignalFxRestClient.get_organization
train
def get_organization(self, **kwargs): """Get the organization to which the user belongs Returns: dictionary of the response """
python
{ "resource": "" }
q12477
SignalFxRestClient.validate_detector
train
def validate_detector(self, detector): """Validate a detector. Validates the given detector; throws a 400 Bad Request HTTP error if the detector is invalid; otherwise doesn't return or throw anything. Args: detector (object): the detector model object. Will be serialized as
python
{ "resource": "" }
q12478
SignalFxRestClient.create_detector
train
def create_detector(self, detector): """Creates a new detector. Args: detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the response (created detector model).
python
{ "resource": "" }
q12479
SignalFxRestClient.update_detector
train
def update_detector(self, detector_id, detector): """Update an existing detector. Args: detector_id (string): the ID of the detector. detector (object): the detector model object. Will be serialized as
python
{ "resource": "" }
q12480
SignalFxRestClient.delete_detector
train
def delete_detector(self, detector_id, **kwargs): """Remove a detector. Args: detector_id (string): the ID of the detector. """ resp = self._delete(self._u(self._DETECTOR_ENDPOINT_SUFFIX,
python
{ "resource": "" }
q12481
SignalFxRestClient.get_detector_incidents
train
def get_detector_incidents(self, id, **kwargs): """Gets all incidents for a detector """ resp = self._get( self._u(self._DETECTOR_ENDPOINT_SUFFIX, id, 'incidents'),
python
{ "resource": "" }
q12482
SignalFxRestClient.clear_incident
train
def clear_incident(self, id, **kwargs): """Clear an incident. """ resp = self._put( self._u(self._INCIDENT_ENDPOINT_SUFFIX, id, 'clear'),
python
{ "resource": "" }
q12483
SignalFx.login
train
def login(self, email, password): """Authenticate a user with SignalFx to acquire a session token. Note that data ingest can only be done with an organization or team API access token, not with a user token obtained via this method. Args: email (string): the email login password (string): the password Returns a new, immediately-usable session token for the logged in user. """ r
python
{ "resource": "" }
q12484
SignalFx.rest
train
def rest(self, token, endpoint=None, timeout=None): """Obtain a metadata REST API client.""" from . import rest
python
{ "resource": "" }
q12485
SignalFx.ingest
train
def ingest(self, token, endpoint=None, timeout=None, compress=None): """Obtain a datapoint and event ingest client.""" from . import ingest if ingest.sf_pbuf: client = ingest.ProtoBufSignalFxIngestClient else: _logger.warn('Protocol Buffers not installed properly;
python
{ "resource": "" }
q12486
SignalFx.signalflow
train
def signalflow(self, token, endpoint=None, timeout=None, compress=None): """Obtain a SignalFlow API client.""" from . import signalflow compress = compress if compress is not None else self._compress return signalflow.SignalFlowClient( token=token,
python
{ "resource": "" }
q12487
MetricMetadata.register
train
def register(self, key, **kwargs): """Registers metadata for a metric and returns a composite key""" dimensions = dict((k, str(v)) for k, v in kwargs.items()) composite_key = self._composite_name(key, dimensions)
python
{ "resource": "" }
q12488
WebSocketTransport.opened
train
def opened(self): """Handler called when the WebSocket connection is opened. The first thing to do then is to authenticate ourselves.""" request = { 'type': 'authenticate', 'token': self._token,
python
{ "resource": "" }
q12489
WebSocketTransport.closed
train
def closed(self, code, reason=None): """Handler called when the WebSocket is closed. Status code 1000 denotes a normal close; all others are errors.""" if code != 1000: self._error = errors.SignalFlowException(code, reason) _logger.info('Lost WebSocket connection with %s (%s: %s).', self, code, reason) for c in self._channels.values():
python
{ "resource": "" }
q12490
get_aws_unique_id
train
def get_aws_unique_id(timeout=DEFAULT_AWS_TIMEOUT): """Determine the current AWS unique ID Args: timeout (int): How long to wait for a response from AWS metadata IP """ try: resp = requests.get(AWS_ID_URL, timeout=timeout).json() except requests.exceptions.ConnectTimeout:
python
{ "resource": "" }
q12491
fft
train
def fft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- a : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError if `axes` is larger than the last axis of `a`. See Also -------- numpy.fft : for definition of the DFT and conventions used. ifft : The inverse of `fft`. fft2 : The two-dimensional FFT. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. fftfreq : Frequency bins for given FFT parameters. Notes ----- FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when `n` is a power of 2, and the transform is therefore most efficient for these sizes. The DFT is defined, with the conventions used in this implementation, in the
python
{ "resource": "" }
q12492
ifft
train
def ifft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional inverse discrete Fourier Transform. This function computes the inverse of the one-dimensional *n*-point discrete Fourier transform computed by `fft`. In other words, ``ifft(fft(a)) == a`` to within numerical accuracy. For a general description of the algorithm and definitions, see `numpy.fft`. The input should be ordered in the same way as is returned by `fft`, i.e., * ``a[0]`` should contain the zero frequency term, * ``a[1:n//2]`` should contain the positive-frequency terms, * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in increasing order starting from the most negative frequency. Parameters ---------- a : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. See notes about padding issues. axis : int, optional Axis over which to compute the inverse DFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError
python
{ "resource": "" }
q12493
rfft
train
def rfft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional discrete Fourier Transform for real input. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Parameters ---------- a : array_like Input array n : int, optional Number of points along transformation axis in the input to use. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. If `n` is even, the length of the transformed axis is ``(n/2)+1``. If `n` is odd, the length is ``(n+1)/2``. Raises ------ IndexError If `axis` is larger than the last axis of `a`. See Also -------- numpy.fft : For definition of the DFT and conventions used. irfft : The inverse of `rfft`. fft : The one-dimensional FFT of general (complex) input. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. Notes ----- When the DFT is computed for purely real input, the output is Hermitian-symmetric, i.e. the negative frequency terms are just the complex conjugates of the corresponding positive-frequency terms, and the
python
{ "resource": "" }
q12494
irfft
train
def irfft(a, n=None, axis=-1, norm=None): """ Compute the inverse of the n-point DFT for real input. This function computes the inverse of the one-dimensional *n*-point discrete Fourier Transform of real input computed by `rfft`. In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical accuracy. (See Notes below for why ``len(a)`` is necessary here.) The input is expected to be in the form returned by `rfft`, i.e. the real zero-frequency term followed by the complex positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is Hermitian-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding positive frequency terms. Parameters ---------- a : array_like The input array. n : int, optional Length of the transformed axis of the output. For `n` output points, ``n//2+1`` input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If `n` is not given, it is determined from the length of the input along the axis specified by `axis`. axis : int, optional Axis over which to compute the inverse FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0
python
{ "resource": "" }
q12495
ihfft
train
def ihfft(a, n=None, axis=-1, norm=None): """ Compute the inverse FFT of a signal which has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT. Number of points along transformation axis in the input to use. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the inverse FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. If `n` is even, the length of the transformed axis is ``(n/2)+1``. If `n` is odd, the length is ``(n+1)/2``. See also -------- hfft, irfft Notes ----- `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal has Hermitian symmetry in the time domain and is
python
{ "resource": "" }
q12496
fftn
train
def fftn(a, s=None, axes=None, norm=None): """ Compute the N-dimensional discrete Fourier Transform. This function computes the *N*-dimensional discrete Fourier Transform over any number of axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT). Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). This corresponds to `n` for `fft(x, n)`. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the transform over that axis is performed multiple times. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` and `a`, as explained in the parameters section above. Raises ------ ValueError
python
{ "resource": "" }
q12497
ifftn
train
def ifftn(a, s=None, axes=None, norm=None): """ Compute the N-dimensional inverse discrete Fourier Transform. This function computes the inverse of the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifftn(fftn(a)) == a`` to within numerical accuracy. For a description of the definitions and conventions used, see `numpy.fft`. The input, analogously to `ifft`, should be ordered in the same way as is returned by `fftn`, i.e. it should have the term for zero frequency in all axes in the low-order corner, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency. Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). This corresponds to ``n`` for ``ifft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the IFFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the inverse transform over that axis is performed multiple times. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` or `a`, as explained in the parameters section above. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- numpy.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse. ifft : The one-dimensional inverse FFT.
python
{ "resource": "" }
q12498
fft2
train
def fft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional discrete Fourier Transform This function computes the *n*-dimensional discrete Fourier Transform over any axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT). By default, the transform is computed over the last two axes of the input array, i.e., a 2-dimensional FFT. Parameters ---------- a : array_like Input array, can be complex s : sequence of ints, optional Shape (length of each transformed axis) of the output (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). This corresponds to `n` for `fft(x, n)`. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in `axes` means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along
python
{ "resource": "" }
q12499
ifft2
train
def ifft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional inverse discrete Fourier Transform. This function computes the inverse of the 2-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a`` to within numerical accuracy. By default, the inverse transform is computed over the last two axes of the input array. The input, analogously to `ifft`, should be ordered in the same way as is returned by `fft2`, i.e. it should have the term for zero frequency in the low-order corner of the two axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of both axes, in order of decreasingly negative frequency. Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in `axes` means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or the last two axes if `axes` is not given. Raises ------ ValueError If `s` and `axes` have different length, or `axes` not given and ``len(s) != 2``. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also --------
python
{ "resource": "" }