Search is not available for this dataset
text
stringlengths
75
104k
def random(cls, origin=None, radius=1): ''' :origin: - optional Point subclass :radius: - optional float :return: Triangle Creates a triangle with random coordinates in the circle described by (origin,radius). If origin is unspecified, (0,0) is assumed. If the r...
def equilateral(cls, origin=None, side=1): ''' :origin: optional Point :side: optional float describing triangle side length :return: Triangle initialized with points comprising a equilateral triangle. XXX equilateral triangle definition ''' o =...
def isosceles(cls, origin=None, base=1, alpha=90): ''' :origin: optional Point :base: optional float describing triangle base length :return: Triangle initialized with points comprising a isosceles triangle. XXX isoceles triangle definition ''' ...
def C(self): ''' Third vertex of triangle, Point subclass. ''' try: return self._C except AttributeError: pass self._C = Point(0, 1) return self._C
def ABC(self): ''' A list of the triangle's vertices, list. ''' try: return self._ABC except AttributeError: pass self._ABC = [self.A, self.B, self.C] return self._ABC
def BA(self): ''' Vertices B and A, list. ''' try: return self._BA except AttributeError: pass self._BA = [self.B, self.A] return self._BA
def AC(self): ''' Vertices A and C, list. ''' try: return self._AC except AttributeError: pass self._AC = [self.A, self.C] return self._AC
def CA(self): ''' Vertices C and A, list. ''' try: return self._CA except AttributeError: pass self._CA = [self.C, self.A] return self._CA
def BC(self): ''' Vertices B and C, list. ''' try: return self._BC except AttributeError: pass self._BC = [self.B, self.C] return self._BC
def CB(self): ''' Vertices C and B, list. ''' try: return self._CB except AttributeError: pass self._CB = [self.C, self.B] return self._CB
def segments(self): ''' A list of the Triangle's line segments [AB, BC, AC], list. ''' return [Segment(self.AB), Segment(self.BC), Segment(self.AC)]
def circumcenter(self): ''' The intersection of the median perpendicular bisectors, Point. The center of the circumscribed circle, which is the circle that passes through all vertices of the triangle. https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 ...
def altitudes(self): ''' A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. ''' a = self.area * 2 return [a / self.a, a / self.b, a / self.c]
def isEquilateral(self): ''' True if all sides of the triangle are the same length. All equilateral triangles are also isosceles. All equilateral triangles are also acute. ''' if not nearly_eq(self.a, self.b): return False if not nearly_eq(self.b, s...
def swap(self, side='AB', inplace=False): ''' :side: - optional string :inplace: - optional boolean :return: Triangle with flipped side. The optional side paramater should have one of three values: AB, BC, or AC. Changes the order of the triangle's points, swapp...
def doesIntersect(self, other): ''' :param: other - Triangle or Line subclass :return: boolean Returns True iff: Any segment in self intersects any segment in other. ''' otherType = type(other) if issubclass(otherType, Triangle): for s in...
def perimeter(self): ''' Sum of the length of all sides, float. ''' return sum([a.distance(b) for a, b in self.pairs()])
def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1, window_size=None, float_descriptors=False, verbose=False, matlab_style=True): ''' Dense sift descriptors from an image. Returns: frames: num_frames x (2 or 3) matrix of x, y, (norm) descrs: n...
def rgb2gray(img): """Converts an RGB image to grayscale using matlab's algorithm.""" T = np.linalg.inv(np.array([ [1.0, 0.956, 0.621], [1.0, -0.272, -0.647], [1.0, -1.106, 1.703], ])) r_c, g_c, b_c = T[0] r, g, b = np.rollaxis(as_float_image(img), axis=-1) return r_c ...
def rgb2hsv(arr): """Converts an RGB image to HSV using scikit-image's algorithm.""" arr = np.asanyarray(arr) if arr.ndim != 3 or arr.shape[2] != 3: raise ValueError("the input array must have a shape == (.,.,3)") arr = as_float_image(arr) out = np.empty_like(arr) # -- V channel ou...
def _parse_command_response(response): """Parse an SCI command response into ElementTree XML This is a helper method that takes a Requests Response object of an SCI command response and will parse it into an ElementTree Element representing the root of the XML response. :param response: The reques...
def _parse_error_tree(error): """Parse an error ElementTree Node to create an ErrorInfo object :param error: The ElementTree error node :return: An ErrorInfo object containing the error ID and the message. """ errinf = ErrorInfo(error.get('id'), None) if error.text is not None: errinf.m...
def get_data(self): """Get the contents of this file :return: The contents of this file :rtype: six.binary_type """ target = DeviceTarget(self.device_id) return self._fssapi.get_file(target, self.path)[self.device_id]
def delete(self): """Delete this file from the device .. note:: After deleting the file, this object will no longer contain valid information and further calls to delete or get_data will return :class:`~.ErrorInfo` objects """ target = DeviceTarget(self.device_id) ...
def list_contents(self): """List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo object ldata = dirinfo.lis...
def parse_response(cls, response, device_id=None, fssapi=None, **kwargs): """Parse the server response for this ls command This will parse xml of the following form:: <ls hash="hash_type"> <file path="file_path" last_modified=last_modified_time ... /> ... ...
def parse_response(cls, response, **kwargs): """Parse the server response for this get file command This will parse xml of the following form:: <get_file> <data> asdfasdfasdfasdfasf </data> </get_file> or with an error...
def parse_response(cls, response, **kwargs): """Parse the server response for this put file command This will parse xml of the following form:: <put_file /> or with an error:: <put_file> <error ... /> </put_file> :param response: T...
def send_command_block(self, target, command_block): """Send an arbitrary file system command block The primary use for this method is to send multiple file system commands with a single web service request. This can help to avoid throttling. :param target: The device(s) to be targete...
def list_files(self, target, path, hash='any'): """List all files and directories in the path on the target :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path:...
def get_file(self, target, path, offset=None, length=None): """Get the contents of a file on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The...
def put_file(self, target, path, file_data=None, server_file=None, offset=None, truncate=False): """Put data into a file on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` ins...
def delete_file(self, target, path): """Delete a file from a device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the file to d...
def get_modified_items(self, target, path, last_modified_cutoff): """Get all files and directories from a path on the device modified since a given time :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud....
def exists(self, target, path, path_sep="/"): """Check if path refers to an existing path on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The...
def get_devices(self, condition=None, page_size=1000): """Iterates over each :class:`Device` for this device cloud account Examples:: # get a list of all devices all_devices = list(dc.devicecore.get_devices()) # build a mapping of devices by their vendor id using a...
def get_group_tree_root(self, page_size=1000): r"""Return the root group for this accounts' group tree This will return the root group for this tree but with all links between nodes (i.e. children starting from root) populated. Examples:: # print the group hierarchy to std...
def get_groups(self, condition=None, page_size=1000): """Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them ...
def provision_devices(self, devices): """Provision multiple devices with a single API call This method takes an iterable of dictionaries where the values in the dictionary are expected to match the arguments of a call to :meth:`provision_device`. The contents of each dictionary will be...
def from_json(cls, json_data): """Build and return a new Group object from json data (used internally)""" # Example Data: # { "grpId": "11817", "grpName": "7603_Digi", "grpDescription": "7603_Digi root group", # "grpPath": "\/7603_Digi\/", "grpParentId": "1"} return cls( ...
def print_subtree(self, fobj=sys.stdout, level=0): """Print this group node and the subtree rooted at it""" fobj.write("{}{!r}\n".format(" " * (level * 2), self)) for child in self.get_children(): child.print_subtree(fobj, level + 1)
def get_device_json(self, use_cached=True): """Get the JSON metadata for this device as a python data structure If ``use_cached`` is not True, then a web services request will be made synchronously in order to get the latest device metatdata. This will update the cached data for this d...
def get_tags(self, use_cached=True): """Get the list of tags for this device""" device_json = self.get_device_json(use_cached) potential_tags = device_json.get("dpTags") if potential_tags: return list(filter(None, potential_tags.split(","))) else: return [...
def is_connected(self, use_cached=True): """Return True if the device is currrently connect and False if not""" device_json = self.get_device_json(use_cached) return int(device_json.get("dpConnectionStatus")) > 0
def get_connectware_id(self, use_cached=True): """Get the connectware id of this device (primary key)""" device_json = self.get_device_json(use_cached) return device_json.get("devConnectwareId")
def get_device_id(self, use_cached=True): """Get this device's device id""" device_json = self.get_device_json(use_cached) return device_json["id"].get("devId")
def get_ip(self, use_cached=True): """Get the last known IP of this device""" device_json = self.get_device_json(use_cached) return device_json.get("dpLastKnownIp")
def get_mac(self, use_cached=True): """Get the MAC address of this device""" device_json = self.get_device_json(use_cached) return device_json.get("devMac")
def get_mac_last4(self, use_cached=True): """Get the last 4 characters in the device mac address hex (e.g. 00:40:9D:58:17:5B -> 175B) This is useful for use as a short reference to the device. It is not guaranteed to be unique (obviously) but will often be if you don't have too many devices. ...
def get_registration_dt(self, use_cached=True): """Get the datetime of when this device was added to Device Cloud""" device_json = self.get_device_json(use_cached) start_date_iso8601 = device_json.get("devRecordStartDate") if start_date_iso8601: return iso8601_to_dt(start_dat...
def get_latlon(self, use_cached=True): """Get a tuple with device latitude and longitude... these may be None""" device_json = self.get_device_json(use_cached) lat = device_json.get("dpMapLat") lon = device_json.get("dpMapLong") return (float(lat) if lat else None, ...
def add_to_group(self, group_path): """Add a device to a group, if the group doesn't exist it is created :param group_path: Path or "name" of the group """ if self.get_group_path() != group_path: post_data = ADD_GROUP_TEMPLATE.format(connectware_id=self.get_connectware_id()...
def add_tag(self, new_tags): """Add a tag to existing device tags. This method will not add a duplicate, if already in the list. :param new_tags: the tag(s) to be added. new_tags can be a comma-separated string or list """ tags = self.get_tags() orig_tag_cnt = len(tags) ...
def remove_tag(self, tag): """Remove tag from existing device tags :param tag: the tag to be removed from the list :raises ValueError: If tag does not exist in list """ tags = self.get_tags() tags.remove(tag) post_data = TAGS_TEMPLATE.format(connectware_id=sel...
def hostname(self): """Get the hostname that this connection is associated with""" from six.moves.urllib.parse import urlparse return urlparse(self._base_url).netloc.split(':', 1)[0]
def iter_json_pages(self, path, page_size=1000, **params): """Return an iterator over JSON items from a paginated resource Legacy resources (prior to V1) implemented a common paging interfaces for several different resources. This method handles the details of iterating over the paged ...
def get(self, path, **kwargs): """Perform an HTTP GET request of the specified path in Device Cloud Make an HTTP GET request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `...
def get_json(self, path, **kwargs): """Perform an HTTP GET request with JSON headers of the specified path against Device Cloud Make an HTTP GET request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/...
def post(self, path, data, **kwargs): """Perform an HTTP POST request of the specified path in Device Cloud Make an HTTP POST request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library ...
def put(self, path, data, **kwargs): """Perform an HTTP PUT request of the specified path in Device Cloud Make an HTTP PUT request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library ...
def delete(self, path, retries=DEFAULT_THROTTLE_RETRIES, **kwargs): """Perform an HTTP DELETE request of the specified path in Device Cloud Make an HTTP DELETE request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-r...
def streams(self): """Property providing access to the :class:`.StreamsAPI`""" if self._streams_api is None: self._streams_api = self.get_streams_api() return self._streams_api
def filedata(self): """Property providing access to the :class:`.FileDataAPI`""" if self._filedata_api is None: self._filedata_api = self.get_filedata_api() return self._filedata_api
def devicecore(self): """Property providing access to the :class:`.DeviceCoreAPI`""" if self._devicecore_api is None: self._devicecore_api = self.get_devicecore_api() return self._devicecore_api
def sci(self): """Property providing access to the :class:`.ServerCommandInterfaceAPI`""" if self._sci_api is None: self._sci_api = self.get_sci_api() return self._sci_api
def file_system_service(self): """Property providing access to the :class:`.FileSystemServiceAPI`""" if self._fss_api is None: self._fss_api = self.get_fss_api() return self._fss_api
def monitor(self): """Property providing access to the :class:`.MonitorAPI`""" if self._monitor_api is None: self._monitor_api = self.get_monitor_api() return self._monitor_api
def get_devicecore_api(self): """Returns a :class:`.DeviceCoreAPI` bound to this device cloud instance This provides access to the same API as :attr:`.DeviceCloud.devicecore` but will create a new object (with a new cache) each time called. :return: devicecore API object bound to this ...
def get_async_job(self, job_id): """Query an asynchronous SCI job by ID This is useful if the job was not created with send_sci_async(). :param int job_id: The job ID to query :returns: The SCI response from GETting the job information """ uri = "/ws/sci/{0}".format(job...
def send_sci_async(self, operation, target, payload, **sci_options): """Send an asynchronous SCI request, and wraps the job in an object to manage it :param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets, file_system, data_s...
def send_sci(self, operation, target, payload, reply=None, synchronous=None, sync_timeout=None, cache=None, allow_offline=None, wait_for_reconnect=None): """Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, q...
def conditional_write(strm, fmt, value, *args, **kwargs): """Write to stream using fmt and value if value is not None""" if value is not None: strm.write(fmt.format(value, *args, **kwargs))
def iso8601_to_dt(iso8601): """Given an ISO8601 string as returned by Device Cloud, convert to a datetime object""" # We could just use arrow.get() but that is more permissive than we actually want. # Internal (but still public) to arrow is the actual parser where we can be # a bit more specific par...
def to_none_or_dt(input): """Convert ``input`` to either None or a datetime object If the input is None, None will be returned. If the input is a datetime object, it will be converted to a datetime object with UTC timezone info. If the datetime object is naive, then this method will assume the obj...
def isoformat(dt): """Return an ISO-8601 formatted string from the provided datetime object""" if not isinstance(dt, datetime.datetime): raise TypeError("Must provide datetime.datetime object to isoformat") if dt.tzinfo is None: raise ValueError("naive datetime objects are not allowed beyon...
def get_filedata(self, condition=None, page_size=1000): """Return a generator over all results matching the provided condition :param condition: An :class:`.Expression` which defines the condition which must be matched on the filedata that will be retrieved from file data store....
def write_file(self, path, name, data, content_type=None, archive=False, raw=False): """Write a file to the file data store at the given path :param str path: The path (directory) into which the file should be written. :param str name: The name of the file to be written. ...
def delete_file(self, path): """Delete a file or directory from the filedata store This method removes a file or directory (recursively) from the filedata store. :param path: The path of the file or directory to remove from the file data store. """ path = v...
def walk(self, root="~/"): """Emulation of os.walk behavior against Device Cloud filedata store This method will yield tuples in the form ``(dirpath, FileDataDirectory's, FileData's)`` recursively in pre-order (depth first from top down). :param str root: The root path from which the s...
def get_data(self): """Get the data associated with this filedata object :returns: Data associated with this object or None if none exists :rtype: str (Python2)/bytes (Python3) or None """ # NOTE: we assume that the "embed" option is used base64_data = self._json_data.g...
def write_file(self, *args, **kwargs): """Write a file into this directory This method takes the same arguments as :meth:`.FileDataAPI.write_file` with the exception of the ``path`` argument which is not needed here. """ return self._fdapi.write_file(self.get_path(), *args, **k...
def create_tcp_monitor(self, topics, batch_size=1, batch_duration=0, compression='gzip', format_type='json'): """Creates a TCP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDat...
def create_http_monitor(self, topics, transport_url, transport_token=None, transport_method='PUT', connect_timeout=0, response_timeout=0, batch_size=1, batch_duration=0, compression='none', format_type='json'): """Creates a HTTP Monitor instance in Device Cloud for a given list of to...
def get_monitors(self, condition=None, page_size=1000): """Return an iterator over all monitors matching the provided condition Get all inactive monitors and print id:: for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == "DISABLED"): print(mon.get_id()) Get all t...
def get_monitor(self, topics): """Attempts to find a Monitor in device cloud that matches the provided topics :param topics: a string list of topics (e.g. ``['DeviceCore[U]', 'FileDataCore'])``) Returns a :class:`DeviceCloudMonitor` if found, otherwise None. """ for monitor in ...
def _get_encoder_method(stream_type): """A function to get the python type to device cloud type converter function. :param stream_type: The streams data type :return: A function that when called with the python object will return the serializable type for sending to the cloud. If there is no function f...
def _get_decoder_method(stream_type): """ A function to get Device Cloud type to python type converter function. :param stream_type: The streams data type :return: A function that when called with Device Cloud object will return the python native type. If there is no function for the given type, or the...
def _get_streams(self, uri_suffix=None): """Clear and update internal cache of stream objects""" # TODO: handle paging, perhaps change this to be a generator if uri_suffix is not None and not uri_suffix.startswith('/'): uri_suffix = '/' + uri_suffix elif uri_suffix is None: ...
def create_stream(self, stream_id, data_type, description=None, data_ttl=None, rollup_ttl=None, units=None): """Create a new data stream on Device Cloud This method will attempt to create a new data stream on Device Cloud. This method will only succeed if the stream does n...
def get_stream_if_exists(self, stream_id): """Return a reference to a stream with the given ``stream_id`` if it exists This works similar to :py:meth:`get_stream` but will return None if the stream is not already created. :param stream_id: The path of the stream on Device Cloud ...
def bulk_write_datapoints(self, datapoints): """Perform a bulk write (or set of writes) of a collection of data points This method takes a list (or other iterable) of datapoints and writes them to Device Cloud in an efficient manner, minimizing the number of HTTP requests that need to b...
def from_json(cls, stream, json_data): """Create a new DataPoint object from device cloud JSON data :param DataStream stream: The :class:`~DataStream` out of which this data is coming :param dict json_data: Deserialized JSON data from Device Cloud about this device :raises ValueError: i...
def from_rollup_json(cls, stream, json_data): """Rollup json data from the server looks slightly different :param DataStream stream: The :class:`~DataStream` out of which this data is coming :param dict json_data: Deserialized JSON data from Device Cloud about this device :raises ValueE...
def set_stream_id(self, stream_id): """Set the stream id associated with this data point""" stream_id = validate_type(stream_id, type(None), *six.string_types) if stream_id is not None: stream_id = stream_id.lstrip('/') self._stream_id = stream_id
def set_description(self, description): """Set the description for this data point""" self._description = validate_type(description, type(None), *six.string_types)
def set_quality(self, quality): """Set the quality for this sample Quality is stored on Device Cloud as a 32-bit integer, so the input to this function should be either None, an integer, or a string that can be converted to an integer. """ if isinstance(quality, *six.st...
def set_location(self, location): """Set the location for this data point The location must be either None (if no location data is known) or a 3-tuple of floating point values in the form (latitude-degrees, longitude-degrees, altitude-meters). """ if location is None: ...
def set_data_type(self, data_type): """Set the data type for ths data point The data type is actually associated with the stream itself and should not (generally) vary on a point-per-point basis. That being said, if creating a new stream by writing a datapoint, it may be beneficial to ...
def set_units(self, unit): """Set the unit for this data point Unit, as with data_type, are actually associated with the stream and not the individual data point. As such, changing this within a stream is not encouraged. Setting the unit on the data point is useful when the st...
def to_xml(self): """Convert this datapoint into a form suitable for pushing to device cloud An XML string will be returned that will contain all pieces of information set on this datapoint. Values not set (e.g. quality) will be ommitted. """ type_converter = _get_encoder_meth...