INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get the last known IP of this device
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")
Get the MAC address of this device
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")
Get the last 4 characters in the device mac address hex ( e. g. 00: 40: 9D: 58: 17: 5B - > 175B )
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. ...
Get the datetime of when this device was added to Device Cloud
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...
Get a tuple with device latitude and longitude... these may be None
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, ...
Add a device to a group if the group doesn t exist it is created
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()...
Add a tag to existing device tags. This method will not add a duplicate if already in the list.
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) ...
Remove tag from existing device 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...
Get the hostname that this connection is associated with
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]
Return an iterator over JSON items from a paginated resource
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 ...
Perform an HTTP GET request of the specified path in Device Cloud
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 `...
Perform an HTTP GET request with JSON headers of the specified path against Device Cloud
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/...
Perform an HTTP POST request of the specified path in Device Cloud
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 ...
Perform an HTTP PUT request of the specified path in Device Cloud
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 ...
Perform an HTTP DELETE request of the specified path in Device Cloud
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...
Property providing access to the: class:. StreamsAPI
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
Property providing access to the: class:. FileDataAPI
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
Property providing access to the: class:. DeviceCoreAPI
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
Property providing access to the: class:. ServerCommandInterfaceAPI
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
Property providing access to the: class:. FileSystemServiceAPI
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
Property providing access to the: class:. MonitorAPI
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
Returns a: class:. DeviceCoreAPI bound to this device cloud instance
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 ...
Query an asynchronous SCI job by ID
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...
Send an asynchronous SCI request and wraps the job in an object to manage it
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...
Send SCI request to 1 or more targets
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...
Write to stream using fmt and value if value is not None
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))
Given an ISO8601 string as returned by Device Cloud convert to a datetime object
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...
Convert input to either None or a datetime object
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...
Return an ISO - 8601 formatted string from the provided datetime object
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...
Return a generator over all results matching the provided condition
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....
Write a file to the file data store at the given path
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. ...
Delete a file or directory from the filedata store
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...
Emulation of os. walk behavior against Device Cloud filedata store
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...
Get the data associated with this filedata object
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...
Write a file into this directory
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...
Creates a TCP Monitor instance in Device Cloud for a given list of topics
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...
Creates a HTTP Monitor instance in Device Cloud for a given list of topics
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...
Return an iterator over all monitors matching the provided condition
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...
Attempts to find a Monitor in device cloud that matches the provided topics
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 ...
A function to get the python type to device cloud type converter function.
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...
A function to get Device Cloud type to python type converter function.
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...
Clear and update internal cache of stream objects
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: ...
Create a new data stream on Device Cloud
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...
Return a reference to a stream with the given stream_id if it exists
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 ...
Perform a bulk write ( or set of writes ) of a collection of data points
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...
Create a new DataPoint object from device cloud JSON data
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...
Rollup json data from the server looks slightly different
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...
Set the stream id associated with this data point
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
Set the description for this data point
def set_description(self, description): """Set the description for this data point""" self._description = validate_type(description, type(None), *six.string_types)
Set the quality for this sample
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...
Set the location for this data point
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: ...
Set the data type for ths data point
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 ...
Set the unit for this data point
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...
Convert this datapoint into a form suitable for pushing to device cloud
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...
Retrieve metadata about this stream from Device Cloud
def _get_stream_metadata(self, use_cached): """Retrieve metadata about this stream from Device Cloud""" if self._cached_data is None or not use_cached: try: self._cached_data = self._conn.get_json("/ws/DataStream/%s" % self._stream_id)["items"][0] except DeviceClo...
Get the data type of this stream if it exists
def get_data_type(self, use_cached=True): """Get the data type of this stream if it exists The data type is the type of data stored in this data stream. Valid types include: * INTEGER - data can be represented with a network (= big-endian) 32-bit two's-complement integer. Data with ...
Retrieve the dataTTL for this stream
def get_data_ttl(self, use_cached=True): """Retrieve the dataTTL for this stream The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream. A data point expires after the configured amount of time and is automatically deleted. :param bool use_cached: If...
Retrieve the rollupTtl for this stream
def get_rollup_ttl(self, use_cached=True): """Retrieve the rollupTtl for this stream The rollupTtl is the time to live (TTL) in seconds for the aggregate roll-ups of data points stored in the stream. A roll-up expires after the configured amount of time and is automatically deleted. ...
Return the most recent DataPoint value written to a stream
def get_current_value(self, use_cached=False): """Return the most recent DataPoint value written to a stream The current value is the last recorded data point for this stream. :param bool use_cached: If False, the function will always request the latest from Device Cloud. If True, ...
Delete this stream from Device Cloud along with its history
def delete(self): """Delete this stream from Device Cloud along with its history This call will return None on success and raise an exception in the event of an error performing the deletion. :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error ...
Delete the provided datapoint from this stream
def delete_datapoint(self, datapoint): """Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error """ datapoint = validate_type(datapoint, DataPoint) self._conn.delete("/ws/DataPoint/{stream_id}/{datap...
Delete datapoints from this stream between the provided start and end times
def delete_datapoints_in_time_range(self, start_dt=None, end_dt=None): """Delete datapoints from this stream between the provided start and end times If neither a start or end time is specified, all data points in the stream will be deleted. :param start_dt: The datetime after which da...
Write some raw data to a stream using the DataPoint API
def write(self, datapoint): """Write some raw data to a stream using the DataPoint API This method will mutate the datapoint provided to populate it with information available from the stream as it is available (but without making any new HTTP requests). For instance, we will add in in...
Read one or more DataPoints from a stream
def read(self, start_time=None, end_time=None, use_client_timeline=True, newest_first=True, rollup_interval=None, rollup_method=None, timezone=None, page_size=1000): """Read one or more DataPoints from a stream .. warning:: The data points from Device Cloud is a paged data set. ...
Return a single - quoted and escaped ( percent - encoded ) version of value
def _quoted(value): """Return a single-quoted and escaped (percent-encoded) version of value This function will also perform transforms of known data types to a representation that will be handled by Device Cloud. For instance, datetime objects will be converted to ISO8601. """ if isinstance(...
Compile this expression into a query string
def compile(self): """Compile this expression into a query string""" return "{lhs}{sep}{rhs}".format( lhs=self.lhs.compile(), sep=self.sep, rhs=self.rhs.compile(), )
Compile this expression into a query string
def compile(self): """Compile this expression into a query string""" return "{attribute}{sep}{value}".format( attribute=self.attribute, sep=self.sep, value=_quoted(self.value) )
Perform a read on input socket to consume headers and then return a tuple of message type message length.
def _read_msg_header(session): """ Perform a read on input socket to consume headers and then return a tuple of message type, message length. :param session: Push Session to read data for. Returns response type (i.e. PUBLISH_MESSAGE) if header was completely read, otherwise None if header was ...
Perform a read on input socket to consume message and then return the payload and block_id in a tuple.
def _read_msg(session): """ Perform a read on input socket to consume message and then return the payload and block_id in a tuple. :param session: Push Session to read data for. """ if len(session.data) == session.message_length: # Data Already completely read. Return return Tr...
Sends a ConnectionRequest to the iDigi server using the credentials established with the id of the monitor as defined in the monitor member.
def send_connection_request(self): """ Sends a ConnectionRequest to the iDigi server using the credentials established with the id of the monitor as defined in the monitor member. """ try: self.log.info("Sending ConnectionRequest for Monitor %s." ...
Creates a TCP connection to Device Cloud and sends a ConnectionRequest message
def start(self): """Creates a TCP connection to Device Cloud and sends a ConnectionRequest message""" self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id) if self.socket is not None: raise Exception("Socket already established for %s." % self) try: ...
Stop/ Close this session
def stop(self): """Stop/Close this session Close the socket associated with this session and puts Session into a state such that it can be re-established later. """ if self.socket is not None: self.socket.close() self.socket = None self.data =...
Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message.
def start(self): """ Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. """ self.log.info("Starting SSL Session for Monitor %s." % self.monitor_id) if self.socket is not None: raise Exception("Socket alrea...
Continually blocks until data is on the internal queue then calls the session s registered callback and sends a PublishMessageReceived if callback returned True.
def _consume_queue(self): """ Continually blocks until data is on the internal queue, then calls the session's registered callback and sends a PublishMessageReceived if callback returned True. """ while True: session, block_id, raw_data = self._queue.get() ...
Queues up a callback event to occur for a session with the given payload data. Will block if the queue is full.
def queue_callback(self, session, block_id, data): """ Queues up a callback event to occur for a session with the given payload data. Will block if the queue is full. :param session: the session with a defined callback function to call. :param block_id: the block_id of the mess...
Restarts and re - establishes session
def _restart_session(self, session): """Restarts and re-establishes session :param session: The session to restart """ # remove old session key, if socket is None, that means the # session was closed by user and there is no need to restart. if session.socket is not None:...
Indefinitely checks the writer queue for data to write to socket.
def _writer(self): """ Indefinitely checks the writer queue for data to write to socket. """ while not self.closed: try: sock, data = self._write_queue.get(timeout=0.1) self._write_queue.task_done() sock.send(data) ...
Traverses sessions to determine if any sockets were removed ( indicates a stopped session ). In these cases remove the session.
def _clean_dead_sessions(self): """ Traverses sessions to determine if any sockets were removed (indicates a stopped session). In these cases, remove the session. """ for sck in list(self.sessions.keys()): session = self.sessions[sck] if session.so...
While the client is not marked as closed performs a socket select on all PushSession sockets. If any data is received parses and forwards it on to the callback function. If the callback is successful a PublishMessageReceived message is sent.
def _select(self): """ While the client is not marked as closed, performs a socket select on all PushSession sockets. If any data is received, parses and forwards it on to the callback function. If the callback is successful, a PublishMessageReceived message is sent. ""...
Initializes the IO and Writer threads
def _init_threads(self): """Initializes the IO and Writer threads""" if self._io_thread is None: self._io_thread = Thread(target=self._select) self._io_thread.start() if self._writer_thread is None: self._writer_thread = Thread(target=self._writer) ...
Creates and Returns a PushSession instance based on the input monitor and callback. When data is received callback will be invoked. If neither monitor or monitor_id are specified throws an Exception.
def create_session(self, callback, monitor_id): """ Creates and Returns a PushSession instance based on the input monitor and callback. When data is received, callback will be invoked. If neither monitor or monitor_id are specified, throws an Exception. :param callback: Callbac...
Stops all session activity.
def stop(self): """Stops all session activity. Blocks until io and writer thread dies """ if self._io_thread is not None: self.log.info("Waiting for I/O thread to stop...") self.closed = True self._io_thread.join() if self._writer_thread is n...
Plots the original data in a graph above the plot of the dtw ed data
def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath): ''' Plots the original data in a graph above the plot of the dtw'ed data ''' _matplotlibCheck() plt.hold(True) fig, (ax0) = plt.subplots(nrows=1) # Old data plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red', ...
Preps data for use in f0Morph
def getPitchForIntervals(data, tgFN, tierName): ''' Preps data for use in f0Morph ''' tg = tgio.openTextgrid(tgFN) data = tg.tierDict[tierName].getValuesInIntervals(data) data = [dataList for _, dataList in data] return data
Resynthesizes the pitch track from a source to a target wav file
def f0Morph(fromWavFN, pitchPath, stepList, outputName, doPlotPitchSteps, fromPitchData, toPitchData, outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False, keepAveragePitch=False, sourcePitchDataList=None, minIntervalLength=0.3): ''' Resynthesizes the pi...
Converts text in the numbering format of pinyin ( ni3hao3 ) to text with the appropriate tone marks ( nǐhǎo ).
def decode(s): """ Converts text in the numbering format of pinyin ("ni3hao3") to text with the appropriate tone marks ("nǐhǎo"). """ s = s.lower() r = "" t = "" for c in s: if c >= 'a' and c <= 'z': t += c elif c == ':': try: if ...
Adjust peak height The foot of the accent is left unchanged and intermediate values are linearly scaled
def adjustPeakHeight(self, heightAmount): ''' Adjust peak height The foot of the accent is left unchanged and intermediate values are linearly scaled ''' if heightAmount == 0: return pitchList = [f0V for _, f0V in self.pointList] ...
Add a plateau A negative plateauAmount will move the peak backwards. A positive plateauAmount will move the peak forwards. All points on the side of the peak growth will also get moved. i. e. the slope of the peak does not change. The accent gets wider instead. If pitchSampFreq = None the plateau will only be specified...
def addPlateau(self, plateauAmount, pitchSampFreq=None): ''' Add a plateau A negative plateauAmount will move the peak backwards. A positive plateauAmount will move the peak forwards. All points on the side of the peak growth will also get moved. i.e. th...
Move the whole accent earlier or later
def shiftAccent(self, shiftAmount): ''' Move the whole accent earlier or later ''' if shiftAmount == 0: return self.pointList = [(time + shiftAmount, pitch) for time, pitch in self.pointList] # Update shift amounts ...
Erase points from another list that overlap with points in this list
def deleteOverlapping(self, targetList): ''' Erase points from another list that overlap with points in this list ''' start = self.pointList[0][0] stop = self.pointList[-1][0] if self.netLeftShift < 0: start += self.netLeftShift i...
Integrates the pitch values of the accent into a larger pitch contour
def reintegrate(self, fullPointList): ''' Integrates the pitch values of the accent into a larger pitch contour ''' # Erase the original region of the accent fullPointList = _deletePoints(fullPointList, self.minT, self.maxT) # Erase the new region of the accent ...
Convert file with crappy encoding to a new proper encoding ( or vice versa if you wish ).
def convert(filename, new_filename=None, overwrite=False, to_encoding='utf-8', force=True): """ Convert file with crappy encoding to a new proper encoding (or vice versa if you wish). filename -- the name, partial path or full path of the file you want to encode to a new encoding new_filename -- (optional)...
Detect the encoding of a file.
def detect(filename, include_confidence=False): """ Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence) """ f = open(filename) detection = chardet.detect(f.r...
Utility function for downloading files from the web and retaining the same filename.
def download(url, localFileName=None, localDirName=None): """ Utility function for downloading files from the web and retaining the same filename. """ localName = url2name(url) req = Request(url) r = urlopen(req) if r.info().has_key('Content-Disposition'): # If the response has ...
This is a unexposed function is responsibility for translation internal.
def _t(unistr, charset_from, charset_to): """ This is a unexposed function, is responsibility for translation internal. """ # if type(unistr) is str: # try: # unistr = unistr.decode('utf-8') # # Python 3 returns AttributeError when .decode() is called on a str # #...
Identify whether a string is simplified or traditional Chinese.
def identify(text): """Identify whether a string is simplified or traditional Chinese. Returns: None: if there are no recognizd Chinese characters. EITHER: if the test is inconclusive. TRAD: if the text is traditional. SIMP: if the text is simplified. BOTH: the text has ...
Puts every value in a list on a continuum between 0 and 1
def makeSequenceRelative(absVSequence): ''' Puts every value in a list on a continuum between 0 and 1 Also returns the min and max values (to reverse the process) ''' if len(absVSequence) < 2 or len(set(absVSequence)) == 1: raise RelativizeSequenceException(absVSequence) minV = min(ab...
Makes every value in a sequence absolute
def makeSequenceAbsolute(relVSequence, minV, maxV): ''' Makes every value in a sequence absolute ''' return [(value * (maxV - minV)) + minV for value in relVSequence]
Given normal pitch tier data puts the times on a scale from 0 to 1
def _makeTimingRelative(absoluteDataList): ''' Given normal pitch tier data, puts the times on a scale from 0 to 1 Input is a list of tuples of the form ([(time1, pitch1), (time2, pitch2),...] Also returns the start and end time so that the process can be reversed ''' timingSeq = [row[0] ...
Maps values from 0 to 1 to the provided start and end time
def _makeTimingAbsolute(relativeDataList, startTime, endTime): ''' Maps values from 0 to 1 to the provided start and end time Input is a list of tuples of the form ([(time1, pitch1), (time2, pitch2),...] ''' timingSeq = [row[0] for row in relativeDataList] valueSeq = [list(row[1:]) for row...