text
stringlengths
81
112k
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) ...
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, r...
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...
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 =...
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: Callback function to call when PublishMessage messages are rece...
Stops all session activity. Blocks until io and writer thread dies 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 =...
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 dat...
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 fromPitchData and toPitchData should be segmented according to the portions that you want to morph. The two lists must have the same number of sublists. Occurs over a three-step process. This function can act as a template for how ...
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 i...
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...
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. ...
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] ...
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.netLeftSh...
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.m...
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) the name of the new file to be generated using the new encoding overwrite -- if `new_filename` ...
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) def detect(filename, include_confidence=False): """ Detect the encoding of a file. Returns only the predicted c...
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 = ...
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') # # Py...
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 characters recognized as be...
Puts every value in a list on a continuum between 0 and 1 Also returns the min and max values (to reverse the process) 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...
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 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 def _makeTimingRelative(absoluteDataList): ''' Given normal pitch tier data, pu...
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),...] 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 f...
Returns the value in inputList that is closest to targetVal Iteratively splits the dataset in two, so it should be pretty fast def _getSmallestDifference(inputList, targetVal): ''' Returns the value in inputList that is closest to targetVal Iteratively splits the dataset in two, so it should ...
Finds the indicies for data points that are closest to each other. The inputs should be in relative time, scaled from 0 to 1 e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1] will output [0, 1, 1, 2] def _getNearestMappingIndexList(fromValList, toValList): ''' Finds the indicies for data points...
Iteratively morph fromList into toList using the values 0 to 1 in stepList stepList: a value of 0 means no change and a value of 1 means a complete change to the other value def morphDataLists(fromList, toList, stepList): ''' Iteratively morph fromList into toList using the values 0 to 1 in stepLi...
Morph one set of data into another, in a stepwise fashion A convenience function. Given a set of paired data lists, this will morph each one individually. Returns a single list with all data combined together. def morphChunkedDataLists(fromDataList, toDataList, stepList): ''' Morph one set of da...
Adjusts the values in fromPitchList to have the same average as toPitchList Because other manipulations can alter the average pitch, morphing the pitch is the last pitch manipulation that should be done After the morphing, the code removes any values below zero, thus the final average might no...
Changes the scale of values in one distribution to that of another ie The maximum value in fromDataList will be set to the maximum value in toDataList. The 75% largest value in fromDataList will be set to the 75% largest value in toDataList, etc. Small sample sizes will yield results that are...
Generates a series of points on a smooth curve that cross the given points numDegrees - the degrees of the fitted polynomial - the curve gets weird if this value is too high for the input n - number of points to output startTime/endTime/n - n points will be generated at evenly spaced ...
Get information about the 'extract' tier, used by several merge scripts def getIntervals(fn, tierName, filterFunc=None, includeUnlabeledRegions=False): ''' Get information about the 'extract' tier, used by several merge scripts ''' tg = tgio.openTextgrid(fn) tier = tg.tierDic...
Uses praat to morph duration in one file to duration in another Praat uses the PSOLA algorithm def changeDuration(fromWavFN, durationParameters, stepList, outputName, outputMinPitch, outputMaxPitch, praatEXE): ''' Uses praat to morph duration in one file to duration in another Praa...
Get intervals for source and target audio files Use this information to find out how much to stretch/shrink each source interval. The target values are based on the contents of toTGFN. def getMorphParameters(fromTGFN, toTGFN, tierName, filterFunc=None, useBlanks=False): ...
Get intervals for source and target audio files Use this information to find out how much to stretch/shrink each source interval. The target values are based on modfunc. def getManipulatedParamaters(tgFN, tierName, modFunc, filterFunc=None, useBlanks=False): ''' ...
A convenience function. Morphs interval durations of one tg to another. This assumes the two textgrids have the same number of segments. def textgridMorphDuration(fromTGFN, toTGFN): ''' A convenience function. Morphs interval durations of one tg to another. This assumes the two textgrids ha...
Returns the duration of a wav file (in seconds) def getSoundFileDuration(fn): ''' Returns the duration of a wav file (in seconds) ''' audiofile = wave.open(fn, "r") params = audiofile.getparams() framerate = params[2] nframes = params[3] duration = float(nframes) / framerate ...
u""" Split Chinese text at word boundaries. include_pos: also returns the Part Of Speech for each of the words. Some of the different parts of speech are: r: pronoun v: verb ns: proper noun etc... This all gets returned as a tuple: index 0: the split word ...
Returns a boolean indicating whether or not the string can be parsed by parse_atom to produce a static set. In the process of examining the string, the syntax of any special character uses is also checked. def is_special_atom(cron_atom, span): """ Returns a boolean indicating whether or not the string ...
Returns a set containing valid values for a given cron-style range of numbers. The 'minmax' arguments is a two element iterable containing the inclusive upper and lower limits of the expression. Examples: >>> parse_atom("1-5",(0,6)) set([1, 2, 3, 4, 5]) >>> parse_atom("*/6",(0,23)) set([0,...
Recomputes the sets for the static ranges of the trigger time. This method should only be called by the user if the string_tab member is modified. def compute_numtab(self): """ Recomputes the sets for the static ranges of the trigger time. This method should only be called by ...
Returns boolean indicating if the trigger is active at the given time. The date tuple should be in the local time. Unless periodicities are used, utc_offset does not need to be specified. If periodicities are used, specifically in the hour and minutes fields, it is crucial that the utc_o...
Show the structure of self.rules_list, only for debug. def show(self): """Show the structure of self.rules_list, only for debug.""" for rule in self.rules_list: result = ", ".join([str(check) for check, deny in rule]) print(result)
Run self.rules_list. Return True if one rule channel has been passed. Otherwise return False and the deny() method of the last failed rule. def run(self): """Run self.rules_list. Return True if one rule channel has been passed. Otherwise return False and the deny() method of t...
Set the meter indicator. Value should be between 0 and 1. def set_fraction(self, value): """Set the meter indicator. Value should be between 0 and 1.""" if value < 0: value *= -1 value = min(value, 1) if self.horizontal: width = int(self.width * value) ...
Update status informations in tkinter window. def update_status(self): """Update status informations in tkinter window.""" try: # all this may fail if the connection to the fritzbox is down self.update_connection_status() self.max_stream_rate.set(self.get_stream_rate...
Returns a human readable string of a byte-value. If 'num' is bits, set unit='bits'. def format_num(num, unit='bytes'): """ Returns a human readable string of a byte-value. If 'num' is bits, set unit='bits'. """ if unit == 'bytes': extension = 'B' else: # if it's not bytes, i...
Build a ContentDisposition from header values. def parse_headers(content_disposition, location=None, relaxed=False): """Build a ContentDisposition from header values. """ LOGGER.debug( 'Content-Disposition %r, Location %r', content_disposition, location) if content_disposition is None: ...
Build a ContentDisposition from a requests (PyPI) response. def parse_requests_response(response, **kwargs): """Build a ContentDisposition from a requests (PyPI) response. """ return parse_headers( response.headers.get('content-disposition'), response.url, **kwargs)
Generate a Content-Disposition header for a given filename. For legacy clients that don't understand the filename* parameter, a filename_compat value may be given. It should either be ascii-only (recommended) or iso-8859-1 only. In the later case it should be a character string (unicode in Python 2...
The filename from the Content-Disposition header. If a location was passed at instanciation, the basename from that may be used as a fallback. Otherwise, this may be the None value. On safety: This property records the intent of the sender. You shouldn't use th...
Returns a filename that is safer to use on the filesystem. The filename will not contain a slash (nor the path separator for the current platform, if different), it will not start with a dot, and it will have the expected extension. No guarantees that makes it "safe enough". No...
uptime in human readable format. def str_uptime(self): """uptime in human readable format.""" mins, secs = divmod(self.uptime, 60) hours, mins = divmod(mins, 60) return '%02d:%02d:%02d' % (hours, mins, secs)
Returns the upstream, downstream values as a tuple in bytes per second. Use this for periodical calling. def transmission_rate(self): """ Returns the upstream, downstream values as a tuple in bytes per second. Use this for periodical calling. """ sent = self.bytes_sent ...
Returns a tuple of human readable transmission rates in bytes. def str_transmission_rate(self): """Returns a tuple of human readable transmission rates in bytes.""" upstream, downstream = self.transmission_rate return ( fritztools.format_num(upstream), fritztools.format_...
Returns a tuple with the maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec. def max_bit_rate(self): """ Returns a tuple with the maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec. """ s...
Returns a human readable maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec. def str_max_bit_rate(self): """ Returns a human readable maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec. """ ...
Helper method to construct the appropriate SOAP-body to call a FritzBox-Service. def _body_builder(self, kwargs): """ Helper method to construct the appropriate SOAP-body to call a FritzBox-Service. """ p = { 'action_name': self.name, 'service_typ...
Calls the FritzBox action and returns a dictionary with the arguments. def execute(self, **kwargs): """ Calls the FritzBox action and returns a dictionary with the arguments. """ headers = self.header.copy() headers['soapaction'] = '%s#%s' % (self.service_type, self.name) ...
Evaluates the action-call response from a FritzBox. The response is a xml byte-string. Returns a dictionary with the received arguments-value pairs. The values are converted according to the given data_types. TODO: boolean and signed integers data-types from tr64 responses def parse_res...
Returns the FritzBox model name. def get_modelname(self): """Returns the FritzBox model name.""" xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName')) return self.root.find(xpath).text
Returns a list of FritzService-objects. def get_services(self): """Returns a list of FritzService-objects.""" result = [] nodes = self.root.iterfind( './/ns:service', namespaces={'ns': self.namespace}) for node in nodes: result.append(FritzService( ...
Reads the stateVariable information from the xml-file. The information we like to extract are name and dataType so we can assign them later on to FritzActionArgument-instances. Returns a dictionary: key:value = name:dataType def _read_state_variables(self): """ Reads the stateVa...
Returns a list of FritzAction instances. def get_actions(self): """Returns a list of FritzAction instances.""" self._read_state_variables() actions = [] nodes = self.root.iterfind( './/ns:action', namespaces={'ns': self.namespace}) for node in nodes: acti...
Returns a dictionary of arguments for the given action_node. def _get_arguments(self, action_node): """ Returns a dictionary of arguments for the given action_node. """ arguments = {} argument_nodes = action_node.iterfind( r'./ns:argumentList/ns:argument', namespaces...
Returns a FritzActionArgument instance for the given argument_node. def _get_argument(self, argument_node): """ Returns a FritzActionArgument instance for the given argument_node. """ argument = FritzActionArgument() argument.name = argument_node.find(self.nodename('name')).text...
Read and evaluate the igddesc.xml file and the tr64desc.xml file if a password is given. def _read_descriptions(self, password): """ Read and evaluate the igddesc.xml file and the tr64desc.xml file if a password is given. """ descfiles = [FRITZ_IGD_DESC_FILE] if ...
Get actions from services. def _read_services(self, services): """Get actions from services.""" for service in services: parser = FritzSCDPParser(self.address, self.port, service) actions = parser.get_actions() service.actions = {action.name: action for action in act...
Returns a alphabetical sorted list of tuples with all known service- and action-names. def actionnames(self): """ Returns a alphabetical sorted list of tuples with all known service- and action-names. """ actions = [] for service_name in sorted(self.services.keys...
Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type. def get_action_arguments(self, service_name, action_name): """ Returns a list of tuples with all known arguments for the g...
Executes the given action. Raise a KeyError on unkown actions. def call_action(self, service_name, action_name, **kwargs): """Executes the given action. Raise a KeyError on unkown actions.""" action = self.services[service_name].actions[action_name] return action.execute(**kwargs)
Returns a list of dicts with information about the known hosts. The dict-keys are: 'ip', 'name', 'mac', 'status' def get_hosts_info(self): """ Returns a list of dicts with information about the known hosts. The dict-keys are: 'ip', 'name', 'mac', 'status' """ result = []...
Finds executable in PATH Returns: string or None def find_executable(executable): ''' Finds executable in PATH Returns: string or None ''' logger = logging.getLogger(__name__) logger.debug("Checking executable '%s'...", executable) executable_path = _find_executable(ex...
Checks if jasper can connect a network server. Arguments: server -- (optional) the server to connect with (Default: "www.google.com") Returns: True or False def check_network_connection(server, port): ''' Checks if jasper can connect a network server. Arguments: ...
Checks if a python package or module is importable. Arguments: package_or_module -- the package or module name to check Returns: True or False def check_python_import(package_or_module): ''' Checks if a python package or module is importable. Arguments: package_or_module -- ...
Recursively inject aXe into all iframes and the top level document. :param script_url: location of the axe-core script. :type script_url: string def inject(self): """ Recursively inject aXe into all iframes and the top level document. :param script_url: location of the axe-cor...
Run axe against the current page. :param context: which page part(s) to analyze and/or what to exclude. :param options: dictionary of aXe options. def run(self, context=None, options=None): """ Run axe against the current page. :param context: which page part(s) to analyze and...
Return readable report of accessibility violations found. :param violations: Dictionary of violations. :type violations: dict :return report: Readable report of violations. :rtype: string def report(self, violations): """ Return readable report of accessibility violatio...
Write JSON to file with the specified name. :param name: Path to the file to be written to. If no path is passed a new JSON file "results.json" will be created in the current working directory. :param output: JSON object. def write_results(self, data, name=Non...
Creates an instance of an engine. There is a two-stage instantiation process with engines. 1. ``options``: The keyword options to instantiate the engine class 2. ``defaults``: The default configuration for the engine (options often depends on instantiated TTS engine) def create_engine(engi...
Classifies text by language. Uses preferred_languages weighting. def classify(self, txt): ''' Classifies text by language. Uses preferred_languages weighting. ''' ranks = [] for lang, score in langid.rank(txt): if lang in self.preferred_languages: sco...
Determines the preferred engine/voice for a language. def get_engine_for_lang(self, lang): ''' Determines the preferred engine/voice for a language. ''' for eng in self.engines: if lang in eng.languages.keys(): return eng raise TTSError('Could not mat...
Says the text. if ``lang`` is ``None``, then uses ``classify()`` to detect language. def say(self, txt, lang=None): ''' Says the text. if ``lang`` is ``None``, then uses ``classify()`` to detect language. ''' lang = lang or self.classify(txt) self.get_engine_fo...
Sets default configuration. Raises TTSError on error. def configure_default(self, **_options): ''' Sets default configuration. Raises TTSError on error. ''' language, voice, voiceinfo, options = self._configure(**_options) self.languages_options[language] = (vo...
Sets language-specific configuration. Raises TTSError on error. def configure(self, **_options): ''' Sets language-specific configuration. Raises TTSError on error. ''' language, voice, voiceinfo, options = self._configure(**_options) self.languages_options[lan...
Says the phrase, optionally allows to select/override any voice options. def say(self, phrase, **_options): ''' Says the phrase, optionally allows to select/override any voice options. ''' language, voice, voiceinfo, options = self._configure(**_options) self._logger.debug("Sayi...
Plays the sounds. :filename: The input file name :translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV. def play(self, filename, translate=False): # pragma: no cover ''' Plays the sounds. :filename: The input file na...
Get the appropriate collectd server (multi processed or not) def getCollectDServer(queue, cfg): """Get the appropriate collectd server (multi processed or not)""" server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer return server(queue, cfg)
Constant time comparison of bytes for py3, strings for py2 def _hashes_match(self, a, b): """Constant time comparison of bytes for py3, strings for py2""" if len(a) != len(b): return False diff = 0 if six.PY2: a = bytearray(a) b = bytearray(b) ...
Load metadata for all sites in given basin codes. def load_sites(*basin_ids): """ Load metadata for all sites in given basin codes. """ # Resolve basin ids to HUC8s if needed basins = [] for basin in basin_ids: if basin.isdigit() and len(basin) == 8: basins.append(basin) ...
Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath) def get_huc8(prefix): """ Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath) """ if not prefix.isdigit(): # Look up hucs by name name = prefix prefix = No...
Convert ACIS 'll' value into separate latitude and longitude. def parse(self): """ Convert ACIS 'll' value into separate latitude and longitude. """ super(AcisIO, self).parse() # This is more of a "mapping" step than a "parsing" step, but mappers # only allow one-to-one...
Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper) def map_value(self, field, value): """ Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper) """ if field == 'sids': # Site identifier...
ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names def get_field_names(self): """ ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names """ field_names = super(StationDataIO, self).get...
ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for iterating over "data" def usable_item(self, data): """ ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for it...
MultiStnData data results are arrays without explicit dates; Infer time series based on start date. def load_data(self, data): """ MultiStnData data results are arrays without explicit dates; Infer time series based on start date. """ dates = fill_date_range(self.start_...
Different field names depending on self.add setting (see load_data) For BaseIO def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in ...
Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates. def fill_date_range(start_date, end_date, date_format=None): """ Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates. """ if date...
Enforce rules and return parsed value def parse(self, value): """ Enforce rules and return parsed value """ if self.required and value is None: raise ValueError("%s is required!" % self.name) elif self.ignored and value is not None: warn("%s is ignored fo...
Parse date def parse(self, value): """ Parse date """ value = super(DateOpt, self).parse(value) if value is None: return None if isinstance(value, str): value = self.parse_date(value) if isinstance(value, datetime) and self.date_only: ...