code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def call(self, cmd, **kwargs): if isinstance(cmd, basestring): cmd = cmd.split() self.log.info('Running %s', cmd) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) out, err = p.communicate() if ou...
A simple subprocess wrapper
def merge(self, other): newstart = min(self._start, other.start) newend = max(self._end, other.end) return Range(newstart, newend)
Merge this range object with another (ranges need not overlap or abut). :returns: a new Range object representing the interval containing both ranges.
def intersect(self, other): if not self.overlap(other): return None newstart = max(self._start, other.start) newend = min(self._end, other.end) return Range(newstart, newend)
Determine the interval of overlap between this range and another. :returns: a new Range object representing the overlapping interval, or `None` if the ranges do not overlap.
def overlap(self, other): if self._start < other.end and self._end > other.start: return True return False
Determine whether this range overlaps with another.
def contains(self, other): return self._start <= other.start and self._end >= other.end
Determine whether this range contains another.
def transform(self, offset): assert self._start + offset > 0, \ ('offset {} invalid; resulting range [{}, {}) is ' 'undefined'.format(offset, self._start+offset, self._end+offset)) self._start += offset self._end += offset
Shift this range by the specified offset. Note: the resulting range must be a valid interval.
def runningMedian(seq, M): seq = iter(seq) s = [] m = M // 2 #// does a truncated division like integer division in Python 2 # Set up list s (to be sorted) and load deque with first window of seq s = [item for item in islice(seq,M)] d = deque(s) # Simple lambda function to handle even...
Purpose: Find the median for the points in a sliding window (odd number in size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a running median (in a sliding window) is to be calculated M -- numbe...
def runningMean(seq, N, M): # Load deque (d) with first window of seq d = deque(seq[0:M]) means = [sum(d) / len(d)] # contains mean of first window # Now slide the window by one point to the right for each new position (each pass through # the loop). Stop when the item in the right end of the d...
Purpose: Find the mean for the points in a sliding window (fixed size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a mean (in a sliding window) is to be calculated (N items) N -- length of sequence ...
def behave(cmdline, cwd=".", **kwargs): assert isinstance(cmdline, six.string_types) return run("behave " + cmdline, cwd=cwd, **kwargs)
Run behave as subprocess command and return process/shell instance with results (collected output, returncode).
def get_field_template(self, bound_field, template_name=None): template_name = super().get_field_template(bound_field, template_name) if (template_name == self.field_template and isinstance(bound_field.field.widget, ( forms.RadioSelect, forms.CheckboxSelectM...
Uses a special field template for widget with multiple inputs. It only applies if no other template than the default one has been defined.
def printer(self): print " ID " + repr(self.id) if self.type == 0: print " Tag: - " print " Start State - " elif self.type == 1: print " Push " + repr(self.sym) elif self.type == 2: print " Pop State " + repr(self.sym) elif...
Prints PDA state attributes
def printer(self): i = 0 while i < self.n + 1: print "--------- State No --------" + repr(i) self.s[i].printer() i = i + 1
Prints PDA states and their attributes
def consume_input(self, mystr, stack=[], state=1, curchar=0, depth=0): mystrsplit = mystr.split(' ') if self.s[state].type == 1: stack.append(self.s[state].sym) if len(self.s[state].trans) > 0: state = self.s[state].trans[0] if self.parse(...
Consumes an input and validates if it is accepted Args: mystr (str): the input string to be consumes stack (list): the stack of symbols state (int): the current state of the PDA curchar (int): the index of the consumed character depth (int): the depth ...
def _CreateDatabase(self): goodlogging.Log.Info("DB", "Initialising new database", verbosity=self.logVerbosity) with sqlite3.connect(self._dbPath) as db: # Configuration tables db.execute("CREATE TABLE Config (" "Name TEXT UNIQUE NOT NULL, " "Value TEXT)") ...
Create all database tables.
def _ActionDatabase(self, cmd, args = None, commit = True, error = True): goodlogging.Log.Info("DB", "Database Command: {0} {1}".format(cmd, args), verbosity=self.logVerbosity) with sqlite3.connect(self._dbPath) as db: try: if args is None: result = db.execute(cmd) else: ...
Do action on database. Parameters ---------- cmd : string SQL command. args : tuple [optional : default = None] Arguments to be passed along with the SQL command. e.g. cmd="SELECT Value FROM Config WHERE Name=?" args=(fieldName, ) commit : boolean [optional : default...
def _PurgeTable(self, tableName): goodlogging.Log.Info("DB", "Deleting all entries from table {0}".format(tableName), verbosity=self.logVerbosity) self._ActionDatabase("DELETE FROM {0}".format(tableName))
Deletes all rows from given table without dropping table. Parameters ---------- tableName : string Name of table.
def GetConfigValue(self, fieldName): result = self._ActionDatabase("SELECT Value FROM Config WHERE Name=?", (fieldName, )) if result is None: return None elif len(result) == 0: return None elif len(result) == 1: goodlogging.Log.Info("DB", "Found database match in config table {0}...
Match given field name in Config table and return corresponding value. Parameters ---------- fieldName : string String matching Name column in Config table. Returns ---------- string or None If a match is found the corresponding entry in the Value column of the data...
def SetConfigValue(self, fieldName, value): currentConfigValue = self.GetConfigValue(fieldName) if currentConfigValue is None: goodlogging.Log.Info("DB", "Adding {0}={1} to database config table".format(fieldName, value), verbosity=self.logVerbosity) self._ActionDatabase("INSERT INTO Config VA...
Set value in Config table. If a entry already exists this is updated with the new value, otherwise a new entry is added. Parameters ---------- fieldName : string String to be inserted or matched against Name column in Config table. value : string Entry to be inserted or up...
def _AddToSingleColumnTable(self, tableName, columnHeading, newValue): match = None currentTable = self._GetFromSingleColumnTable(tableName) if currentTable is not None: for currentValue in currentTable: if currentValue == newValue: match = True if match is None: goo...
Add an entry to a table containing a single column. Checks existing table entries to avoid duplicate entries if the given value already exists in the table. Parameters ---------- tableName : string Name of table to add entry to. columnHeading : string Name of column heading...
def AddShowToTVLibrary(self, showName): goodlogging.Log.Info("DB", "Adding {0} to TV library".format(showName), verbosity=self.logVerbosity) currentShowValues = self.SearchTVLibrary(showName = showName) if currentShowValues is None: self._ActionDatabase("INSERT INTO TVLibrary (ShowName) VALUES ...
Add show to TVLibrary table. If the show already exists in the table a fatal error is raised. Parameters ---------- showName : string Show name to add to TV library table. Returns ---------- int Unique show id generated for show when it is added to the table. Used ...
def UpdateShowDirInTVLibrary(self, showID, showDir): goodlogging.Log.Info("DB", "Updating TV library for ShowID={0}: ShowDir={1}".format(showID, showDir)) self._ActionDatabase("UPDATE TVLibrary SET ShowDir=? WHERE ShowID=?", (showDir, showID))
Update show directory entry for given show id in TVLibrary table. Parameters ---------- showID : int Show id value. showDir : string Show directory name.
def SearchFileNameTable(self, fileName): goodlogging.Log.Info("DB", "Looking up filename string '{0}' in database".format(fileName), verbosity=self.logVerbosity) queryString = "SELECT ShowID FROM FileName WHERE FileName=?" queryTuple = (fileName, ) result = self._ActionDatabase(queryString, query...
Search FileName table. Find the show id for a given file name. Parameters ---------- fileName : string File name to look up in table. Returns ---------- int or None If a match is found in the database table the show id for this entry is returned, otherwise this...
def AddToFileNameTable(self, fileName, showID): goodlogging.Log.Info("DB", "Adding filename string match '{0}'={1} to database".format(fileName, showID), verbosity=self.logVerbosity) currentValues = self.SearchFileNameTable(fileName) if currentValues is None: self._ActionDatabase("INSERT INTO F...
Add entry to FileName table. If the file name and show id combination already exists in the table a fatal error is raised. Parameters ---------- fileName : string File name. showID : int Show id.
def SearchSeasonDirTable(self, showID, seasonNum): goodlogging.Log.Info("DB", "Looking up directory for ShowID={0} Season={1} in database".format(showID, seasonNum), verbosity=self.logVerbosity) queryString = "SELECT SeasonDir FROM SeasonDir WHERE ShowID=? AND Season=?" queryTuple = (showID, seasonNum...
Search SeasonDir table. Find the season directory for a given show id and season combination. Parameters ---------- showID : int Show id for given show. seasonNum : int Season number. Returns ---------- string or None If no match is found this returns No...
def AddSeasonDirTable(self, showID, seasonNum, seasonDir): goodlogging.Log.Info("DB", "Adding season directory ({0}) to database for ShowID={1}, Season={2}".format(seasonDir, showID, seasonNum), verbosity=self.logVerbosity) currentValue = self.SearchSeasonDirTable(showID, seasonNum) if currentValue i...
Add entry to SeasonDir table. If a different entry for season directory is found for the given show id and season number combination this raises a fatal error. Parameters ---------- showID : int Show id. seasonNum : int Season number. seasonDir : string Seaso...
def PrintAllTables(self): goodlogging.Log.Info("DB", "Database contents:\n") for table in self._tableDict.keys(): self._PrintDatabaseTable(table)
Prints contents of every table.
def _get_minidom_tag_value(station, tag_name): tag = station.getElementsByTagName(tag_name)[0].firstChild if tag: return tag.nodeValue return None
get a value from a tag (if it exists)
def _parse(data, obj_name, attr_map): parsed_xml = minidom.parseString(data) parsed_objects = [] for obj in parsed_xml.getElementsByTagName(obj_name): parsed_obj = {} for (py_name, xml_name) in attr_map.items(): parsed_obj[py_name] = _get_minidom_tag_value(obj, xml_name) ...
parse xml data into a python map
def get_all_stations(self, station_type=None): params = None if station_type and station_type in STATION_TYPE_TO_CODE_DICT: url = self.api_base_url + 'getAllStationsXML_WithStationType' params = { 'stationType': STATION_TYPE_TO_CODE_DICT[station_type] ...
Returns information of all stations. @param<optional> station_type: ['mainline', 'suburban', 'dart']
def get_all_current_trains(self, train_type=None, direction=None): params = None if train_type: url = self.api_base_url + 'getCurrentTrainsXML_WithTrainType' params = { 'TrainType': STATION_TYPE_TO_CODE_DICT[train_type] } else: ...
Returns all trains that are due to start in the next 10 minutes @param train_type: ['mainline', 'suburban', 'dart']
def get_station_by_name(self, station_name, num_minutes=None, direction=None, destination=None, stops_at=None): url = self.api_base_url + 'getStationDataByNameXML'...
Returns all trains due to serve station `station_name`. @param station_code @param num_minutes. Only trains within this time. Between 5 and 90 @param direction Filter by direction. Northbound or Southbound @param destination Filter by name of the destination stations @param stops...
def _prune_trains(self, trains, direction=None, destination=None, stops_at=None): pruned_data = [] for train in trains: append = True if direction is not None and train["direction"] != direction: append = False if destin...
Only return the data matching direction and / or destination. If stops_at is set this may do a number of extra HTTP requests @param trains list of trains to filter @param direction Filter by train direction. Northbound or Southbound @param destination Filter by name of the destination st...
def get_train_stops(self, train_code, date=None): if date is None: date = datetime.date.today().strftime("%d %B %Y") url = self.api_base_url + 'getTrainMovementsXML' params = { 'TrainId': train_code, 'TrainDate': date } response = re...
Get details for a train. @param train_code code for the trian @param date Date in format "15 oct 2017". If none use today
def fill_fields(self, **kwargs): for name, value in kwargs.items(): field = getattr(self, name) field.send_keys(value)
Fills the fields referenced by kwargs keys and fill them with the value
def selector(self, fieldname): finder = self._finders[fieldname] return (finder._by, finder._selector)
Gets a selector for the given page element as a tuple (by, selector)
def authorize_url(client_id=None, redirect_uri=None, state=None, scopes=None, show_dialog=False, http_client=None): params = { 'client_id': client_id or os.environ.get('SPOTIFY_CLIENT_ID'), 'redirect_uri': redirect_uri or os.environ.get('SPOTIFY_REDIRECT_URI'), 'state': state or str(uui...
Trigger authorization dialog :param str client_id: Client ID :param str redirect_uri: Application Redirect URI :param str state: Application State :param List[str] scopes: Scopes to request :param bool show_dialog: Show the dialog :param http_client: HTTP Client for requests :return str Aut...
def refresh(self): data = { 'grant_type': 'refresh_token', 'refresh_token': self._token.refresh_token } response = self.http_client.post(self.URL, data=data, auth=(self.client_id, self.client_secret)) response.raise_for_status() self._token = Tok...
Refresh the access token
def instance_of(cls): def check(value): return ( isinstance(value, cls), u"{value!r} is instance of {actual!s}, required {required!s}".format( value=value, actual=fullyQualifiedName(type(value)), required=fullyQualifiedName(cls), ...
Create an invariant requiring the value is an instance of ``cls``.
def provider_of(iface): def check(value): return ( iface.providedBy(value), u"{value!r} does not provide {interface!s}".format( value=value, interface=fullyQualifiedName(iface), ), ) return check
Create an invariant requiring the value provides the zope.interface ``iface``.
def temp_dir(suffix='', prefix='tmp', parent_dir=None, make_cwd=False): prev_cwd = os.getcwd() parent_dir = parent_dir if parent_dir is None else str(parent_dir) abs_path = tempfile.mkdtemp(suffix, prefix, parent_dir) path = pathlib.Path(abs_path) try: if make_cwd: os.chdir(...
Create a temporary directory and optionally change the current working directory to it. The directory is deleted when the context exits. The temporary directory is created when entering the context manager, and deleted when exiting it: >>> import temporary >>> with temporary.temp_dir() as temp_...
def openSafeReplace(filepath, mode='w+b'): tempfileName = None #Check if the filepath can be accessed and is writable before creating the #tempfile if not _isFileAccessible(filepath): raise IOError('File %s is not writtable' % (filepath, )) with tempfile.NamedTemporaryFile(delete=False,...
Context manager to open a temporary file and replace the original file on closing.
def _isFileAccessible(filepath): directory = os.path.dirname(filepath) if not os.access(directory, os.W_OK): #Return False if directory does not exist or is not writable return False if os.path.exists(filepath): if not os.access(filepath, os.W_OK): #Return False if f...
Returns True if the specified filepath is writable.
def writeJsonZipfile(filelike, data, compress=True, mode='w', name='data'): zipcomp = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED with zipfile.ZipFile(filelike, mode, allowZip64=True) as containerFile: containerFile.writestr(name, json.dumps(data, cls=MaspyJsonEncoder), ...
Serializes the objects contained in data to a JSON formated string and writes it to a zipfile. :param filelike: path to a file (str) or a file-like object :param data: object that should be converted to a JSON formated string. Objects and types in data must be supported by the json.JSONEncoder or ...
def writeBinaryItemContainer(filelike, binaryItemContainer, compress=True): allMetadata = dict() binarydatafile = io.BytesIO() #Note: It would be possible to sort the items here for index, binaryItem in enumerate(viewvalues(binaryItemContainer)): metadataList = _dumpArrayDictToFile(binaryda...
Serializes the binaryItems contained in binaryItemContainer and writes them into a zipfile archive. Examples of binaryItem classes are :class:`maspy.core.Ci` and :class:`maspy.core.Sai`. A binaryItem class has to define the function ``_reprJSON()`` which returns a JSON formated string representation of...
def _dumpArrayDictToFile(filelike, arrayDict): metadataList = list() for arrayKey in sorted(arrayDict): array = arrayDict[arrayKey] if array.ndim == 1: metadata = _dumpArrayToFile(filelike, array) else: metadata = _dumpNdarrayToFile(filelike, array) m...
Function to serialize and write ``numpy.array`` contained in a dictionary to a file. See also :func:`_dumpArrayToFile` and :func:`_dumpNdarrayToFile`. :param filelike: can be a file or a file-like object that provides the methods ``.write()`` and ``.tell()``. :param arrayDict: a dictionary which v...
def _dumpArrayToFile(filelike, array): bytedata = array.tobytes('C') start = filelike.tell() end = start + len(bytedata) metadata = {'start': start, 'end': end, 'size': array.size, 'dtype': array.dtype.name } filelike.write(bytedata) return metadata
Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to the filelike object and returns a dictionary with metadata, necessary to restore the ``numpy.array`` from the file. :param filelike: can be a file or a file-like object that provides the methods ``.write()`` and ``.tell()``. ...
def _dumpNdarrayToFile(filelike, ndarray): bytedata = ndarray.tobytes('C') start = filelike.tell() end = start + len(bytedata) metadata = {'start': start, 'end': end, 'size': ndarray.size, 'dtype': ndarray.dtype.name, 'shape': ndarray.shape } filelike.write(byted...
Serializes an N-dimensional ``numpy.array`` to bytes, writes the bytes to the filelike object and returns a dictionary with metadata, necessary to restore the ``numpy.array`` from the file. :param filelike: can be a file or a file-like object that provides the methods ``.write()`` and ``.tell()``. ...
def loadBinaryItemContainer(zippedfile, jsonHook): binaryItemContainer = dict() with zipfile.ZipFile(zippedfile, 'r') as containerZip: #Convert the zipfile data into a str object, necessary since #containerZip.read() returns a bytes object. metadataText = io.TextIOWrapper(containerZ...
Imports binaryItems from a zipfile generated by :func:`writeBinaryItemContainer`. :param zipfile: can be either a path to a file (a string) or a file-like object :param jsonHook: a custom decoding function for JSON formated strings of the binaryItems stored in the zipfile. :returns: a ...
def _arrayFromBytes(dataBytes, metadata): array = numpy.fromstring(dataBytes, dtype=numpy.typeDict[metadata['dtype']]) if 'shape' in metadata: array = array.reshape(metadata['shape']) return array
Generates and returns a numpy array from raw data bytes. :param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()`` :param metadata: a dictionary containing the data type and optionally the shape parameter to reconstruct a ``numpy.array`` from the raw data bytes. ``{"dtype": "floa...
def searchFileLocation(targetFileName, targetFileExtension, rootDirectory, recursive=True): expectedFileName = targetFileName.split('.')[0] + '.' + targetFileExtension targetFilePath = None if recursive: for dirpath, dirnames, filenames in os.walk(rootDirectory): ...
Search for a filename with a specified file extension in all subfolders of specified rootDirectory, returns first matching instance. :param targetFileName: #TODO: docstring :type targetFileName: str :param rootDirectory: #TODO: docstring :type rootDirectory: str :param targetFileExtension: #TOD...
def matchingFilePaths(targetfilename, directory, targetFileExtension=None, selector=None): targetFilePaths = list() targetfilename = os.path.splitext(targetfilename)[0] targetFileExtension = targetFileExtension.replace('.', '') matchExtensions = False if targetFileExtension i...
Search for files in all subfolders of specified directory, return filepaths of all matching instances. :param targetfilename: filename to search for, only the string before the last "." is used for filename matching. Ignored if a selector function is specified. :param directory: search dire...
def listFiletypes(targetfilename, directory): targetextensions = list() for filename in os.listdir(directory): if not os.path.isfile(joinpath(directory, filename)): continue splitname = filename.split('.') basename = splitname[0] extension = '.'.join(splitname[1:...
Looks for all occurences of a specified filename in a directory and returns a list of all present file extensions of this filename. In this cas everything after the first dot is considered to be the file extension: ``"filename.txt" -> "txt"``, ``"filename.txt.zip" -> "txt.zip"`` :param targetfilename:...
def findAllSubstrings(string, substring): #TODO: solve with regex? what about '.': #return [m.start() for m in re.finditer('(?='+substring+')', string)] start = 0 positions = [] while True: start = string.find(substring, start) if start == -1: break positions...
Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of substring starting positions in the template string
def toList(variable, types=(basestring, int, float, )): if isinstance(variable, types): return [variable] else: return variable
Converts a variable of type string, int, float to a list, containing the variable as the only element. :param variable: any python object :type variable: (str, int, float, others) :returns: [variable] or variable
def calcDeviationLimits(value, tolerance, mode): values = toList(value) if mode == 'relative': lowerLimit = min(values) * (1 - tolerance) upperLimit = max(values) * (1 + tolerance) elif mode == 'absolute': lowerLimit = min(values) - tolerance upperLimit = max(values) + t...
Returns the upper and lower deviation limits for a value and a given tolerance, either as relative or a absolute difference. :param value: can be a single value or a list of values if a list of values is given, the minimal value will be used to calculate the lower limit and the maximum value to...
def returnArrayFilters(arr1, arr2, limitsArr1, limitsArr2): posL = bisect.bisect_left(arr1, limitsArr1[0]) posR = bisect.bisect_right(arr1, limitsArr1[1]) matchMask = ((arr2[posL:posR] <= limitsArr2[1]) & (arr2[posL:posR] >= limitsArr2[0]) ) return posL, posR, matc...
#TODO: docstring :param arr1: #TODO: docstring :param arr2: #TODO: docstring :param limitsArr1: #TODO: docstring :param limitsArr2: #TODO: docstring :returns: #TODO: docstring
def applyArrayFilters(array, posL, posR, matchMask): return numpy.compress(matchMask, array[posL:posR], axis=0)
#TODO: docstring :param array: #TODO: docstring :param posL: #TODO: docstring :param posR: #TODO: docstring :param matchMask: #TODO: docstring :returns: ``numpy.array``, a subset of the input ``array``.
def averagingData(array, windowSize=None, averagingType='median'): assert averagingType in ['median', 'mean'] if windowSize is None: windowSize = int(len(array) / 50) if int(len(array) / 50) > 100 else 100 if averagingType == 'median': averagedData = runningMedian(array, windowSize) ...
#TODO: docstring :param array: #TODO: docstring :param windowSize: #TODO: docstring :param averagingType: "median" or "mean" :returns: #TODO: docstring
def open(self, filepath, mode='w+b'): #Check if the filepath can be accessed and is writable before creating #the tempfile if not _isFileAccessible(filepath): raise IOError('File %s is not writable' % (filepath,)) if filepath in self._files: with open(se...
Opens a file - will actually return a temporary file but replace the original file when the context is closed.
def default(self, obj): if hasattr(obj, '_reprJSON'): return obj._reprJSON() #Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj)
:returns: obj._reprJSON() if it is defined, else json.JSONEncoder.default(obj)
def processInput(self, dataAveraging=False, windowSize=None): self.dependentVar = numpy.array(self.dependentVarInput, dtype=numpy.float64 ) self.independentVar = numpy.array(self.independentVarInput, ...
#TODO: docstring :param dataAveraging: #TODO: docstring :param windowSize: #TODO: docstring
def generateSplines(self): _ = returnSplineList(self.dependentVar, self.independentVar, subsetPercentage=self.splineSubsetPercentage, cycles=self.splineCycles, minKnotPoints=self.splineMinKnotPoins, ...
#TODO: docstring
def corrArray(self, inputArray): outputArray = numpy.vstack([numpy.nan_to_num(currSpline(inputArray)) for currSpline in self.splines ]).mean(axis=0) return outputArray
#TODO: docstring :param inputArray: #TODO: docstring :returns: #TODO docstring
def fixminimized(self, alphabet): endstate = len(list(self.states)) for state in self.states: for char in alphabet: found = 0 for arc in state.arcs: if self.isyms.find(arc.ilabel) == char: found = 1 ...
After pyfst minimization, all unused arcs are removed, and all sink states are removed. However this may break compatibility. Args: alphabet (list): The input alphabet Returns: None
def _path_to_str(self, path): inp = '' for arc in path: i = self.isyms.find(arc.ilabel) # Ignore \epsilon transitions both on input if i != fst.EPSILON: inp += i return inp
Convert a path to the string representing the path Args: path (tuple): A tuple of arcs Returns: inp (str): The path concatenated as as string
def init_from_acceptor(self, acceptor): states = sorted( acceptor.states, key=attrgetter('initial'), reverse=True) for state in states: for arc in state.arcs: itext = acceptor.isyms.find(arc.ilabel) if itext in self...
Adds a sink state Args: alphabet (list): The input alphabet Returns: None
def consume_input(self, inp): cur_state = sorted( self.states, key=attrgetter('initial'), reverse=True)[0] while len(inp) > 0: found = False for arc in cur_state.arcs: if self.isyms.find(arc.ilabel) == inp[0]: ...
Return True/False if the machine accepts/reject the input. Args: inp (str): input string to be consumed Returns: bool: A true or false value depending on if the DFA accepts the provided input
def random_strings(self, string_length=1): str_list = [] for path in self.uniform_generate(string_length): str_list.append(self._path_to_str(path)) return str_list
Generate string_length random strings that belong to the automaton. Args: string_length (integer): The size of the random string Returns: str: The generated string
def save(self, txt_fst_filename): txt_fst = open(txt_fst_filename, 'w+') states = sorted(self.states, key=attrgetter('initial'), reverse=True) for state in states: for arc in state.arcs: itext = self.isyms.find(arc.ilabel) otext = self.osyms.f...
Save the machine in the openFST format in the file denoted by txt_fst_filename. Args: txt_fst_filename (str): The name of the file Returns: None
def load(self, txt_fst_filename): with open(txt_fst_filename, 'r') as txt_fst: for line in txt_fst: line = line.strip() splitted_line = line.split() if len(splitted_line) == 1: self[int(splitted_line[0])].final = True ...
Save the transducer in the text file format of OpenFST. The format is specified as follows: arc format: src dest ilabel olabel [weight] final state format: state [weight] lines may occur in any order except initial state must be first line Args: txt_fst_filena...
def persistent_menu(menu): if len(menu) > 3: raise Invalid('menu should not exceed 3 call to actions') if any(len(item['call_to_actions']) > 5 for item in menu if item['type'] == 'nested'): raise Invalid('call_to_actions is limited to 5 for sub-levels') for item in menu: if le...
more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu :param menu: :return:
def send_text_message(text, quick_replies): if len(text) > 640: raise ExceedLengthException( 'send message text should not exceed 640 character limit', limit=640, ) if isinstance(quick_replies, list): if len(quick_replies) > 10: raise Invalid('se...
more: https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message and https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies :param text: :param quick_replies: :return:
def refactor(self, symbol, value): if value: self.pset.add(symbol) else: self.pset.remove(symbol)
Args: symbol: value: Returns: None
def add_state(self): sid = len(self.states) self.states.append(SFAState(sid))
This function adds a new state
def add_arc(self, src, dst, char): assert type(src) == type(int()) and type(dst) == type(int()), \ "State type should be integer." while src >= len(self.states) or dst >= len(self.states): self.add_state() self.states[src].arcs.append(SFAArc(src, dst, char))
This function adds a new arc in a SFA state Args: src (int): The source state identifier dst (int): The destination state identifier char (str): The transition symbol Returns: None
def consume_input(self, inp): cur_state = self.states[0] for character in inp: found = False for arc in cur_state.arcs: if arc.guard.is_sat(character): cur_state = self.states[arc.dst_state] found = True ...
Return True/False if the machine accepts/reject the input. Args: inp (str): input string to be consumed Retunrs: bool: A true or false value depending on if the DFA accepts the provided input
def concretize(self): dfa = DFA(self.alphabet) for state in self.states: for arc in state.arcs: for char in arc.guard: dfa.add_arc(arc.src_state, arc.dst_state, char) for i in xrange(len(self.states)): if self.states[i].final:...
Transforms the SFA into a DFA Args: None Returns: DFA: The generated DFA
def _write(self, ret): self.redis.set('{0}:{1}'.format(ret['id'], ret['jid']), json.dumps(ret)) self.redis.lpush('{0}:{1}'.format(ret['id'], ret['fun']), ret['jid']) self.redis.sadd('minions', ret['id']) self.redis.sadd('jids', ret['jid'])
This function needs to correspond to this: https://github.com/saltstack/salt/blob/develop/salt/returners/redis_return.py#L88
def _initAddons(cls, recurse=True): for addon_module in cls.addonModules(recurse): projex.importmodules(addon_module)
Initializes the addons for this manager.
def addons(cls, recurse=True): cls.initAddons() prop = '_{0}__addons'.format(cls.__name__) out = {} # lookup base classes if recurse: for base in cls.__bases__: if issubclass(base, AddonManager): out.update(base.addons(rec...
Returns a dictionary containing all the available addons for this mixin class. If the optional recurse flag is set to True, then all the base classes will be searched for the given addon as well. :param recurse | <bool> :return {<str> name: <variant> addon, .....
def addonModules(cls, recurse=True): prop = '_{0}__addon_modules'.format(cls.__name__) out = set() # lookup base classes if recurse: for base in cls.__bases__: if issubclass(base, AddonManager): out.update(base.addonModules(recurs...
Returns all the modules that this addon class uses to load plugins from. :param recurse | <bool> :return [<str> || <module>, ..]
def byName(cls, name, recurse=True, default=None): cls.initAddons() prop = '_{0}__addons'.format(cls.__name__) try: return getattr(cls, prop, {})[name] except KeyError: if recurse: for base in cls.__bases__: if issubcla...
Returns the addon whose name matches the inputted name. If the optional recurse flag is set to True, then all the base classes will be searched for the given addon as well. If no addon is found, the default is returned. :param name | <str> recurse | ...
def initAddons(cls, recurse=True): key = '_{0}__addons_loaded'.format(cls.__name__) if getattr(cls, key, False): return cls._initAddons(recurse) setattr(cls, key, True)
Loads different addon modules for this class. This method should not be overloaded in a subclass as it also manages the loaded state to avoid duplicate loads. Instead, you can re-implement the _initAddons method for custom loading. :param recurse | <bool>
def registerAddon(cls, name, addon, force=False): prop = '_{0}__addons'.format(cls.__name__) cmds = getattr(cls, prop, {}) if name in cmds and not force: raise errors.AddonAlreadyExists(cls, name, addon) cmds[name] = addon try: if issubclass(add...
Registers the inputted addon to the class. :param name | <str> addon | <variant>
def registerAddonModule(cls, module): prop = '_{0}__addon_modules'.format(cls.__name__) mods = getattr(cls, prop, set()) mods.add(module) setattr(cls, prop, mods)
Registers a module to use to import addon subclasses from. :param module | <str> || <module>
def unregisterAddon(cls, name): prop = '_{0}__addons'.format(cls.__name__) cmds = getattr(cls, prop, {}) cmds.pop(name, None)
Unregisters the addon defined by the given name from the class. :param name | <str>
def unregisterAddonModule(cls, module): prop = '_{0}__addon_modules'.format(cls.__name__) mods = getattr(cls, prop, set()) try: mods.remove(module) except KeyError: pass
Unregisters the module to use to import addon subclasses from. :param module | <str> || <module>
def emit(self, record): if not logging.raiseExceptions: return logger = logging.getLogger(record.name) # raise an exception based on the error logging if logger.level <= record.levelno: err = record.msg[0] if not isinstance(err, Exception): ...
Throws an error based on the information that the logger reported, given the logging level. :param record: <logging.LogRecord>
def cli(ctx, stage): if not ctx.bubble: ctx.say_yellow('There is no bubble present, will not listen') raise click.Abort() SRC = None if stage in STAGES: try: SRC = ctx.cfg.CFG[stage].SOURCE except KeyError: pass if not SRC: ctx.say_...
listen to push requests for src and pull requests from target (experimental)
def get_field_label_css_class(self, bound_field): # If we render CheckboxInputs, Bootstrap requires a different # field label css class for checkboxes. if isinstance(bound_field.field.widget, forms.CheckboxInput): return 'form-check-label' return super().get_field_l...
Returns 'form-check-label' if widget is CheckboxInput. For all other fields, no css class is added.
def get_widget_css_class(self, field_name, field): # If we render CheckboxInputs, Bootstrap requires a different # widget css class for checkboxes. if isinstance(field.widget, forms.CheckboxInput): return 'form-check-input' # Idem for fileinput. if isinstanc...
Returns 'form-check-input' if widget is CheckboxInput or 'form-control-file' if widget is FileInput. For all other fields return the default value from the form property ("form-control").
def handle(self): if self.component_type == StreamComponent.SOURCE: msg = self.handler_function() return self.__send(msg) logger = self.logger data = self.__receive() if data is None: return False else: logger.debug("Call...
Handle a message :return: True if success, False otherwise
def realpath_with_context(path, context): if not os.path.isabs(path): # XXX ensure_workdir_exists(context) assert context.workdir path = os.path.join(context.workdir, os.path.normpath(path)) return path
Convert a path into its realpath: * For relative path: use :attr:`context.workdir` as root directory * For absolute path: Pass-through without any changes. :param path: Filepath to convert (as string). :param context: Behave context object (with :attr:`context.workdir`) :return: Converted path...
def posixpath_normpath(pathname): backslash = '\\' pathname2 = os.path.normpath(pathname) or "." if backslash in pathname2: pathname2 = pathname2.replace(backslash, '/') return pathname2
Convert path into POSIX path: * Normalize path * Replace backslash with slash :param pathname: Pathname (as string) :return: Normalized POSIX path.
def create_textfile_with_contents(filename, contents, encoding='utf-8'): ensure_directory_exists(os.path.dirname(filename)) if os.path.exists(filename): os.remove(filename) outstream = codecs.open(filename, "w", encoding) outstream.write(contents) if contents and not contents.endswith("...
Creates a textual file with the provided contents in the workdir. Overwrites an existing file.
def ensure_directory_exists(dirname, context=None): real_dirname = dirname if context: real_dirname = realpath_with_context(dirname, context) if not os.path.exists(real_dirname): os.makedirs(real_dirname) assert os.path.exists(real_dirname), "ENSURE dir exists: %s" % dirname ass...
Ensures that a directory exits. If it does not exist, it is automatically created.
def p_andnode_expression(self, t): '''andnode_expression : LB identlist RB ''' self.accu.add(Term('vertex', ["and(\""+t[2]+"\")"])) t[0] = "and(\""+t[2]+"\")f p_andnode_expression(self, t): '''andnode_expression : LB identlist RB ''' self.accu.add(Term('vertex', ["and(\""+t[2]+"\")"])) t[0] = ...
andnode_expression : LB identlist RB
def p_identlist(self, t): '''identlist : IDENT | NOT IDENT | IDENT AND identlist | NOT IDENT AND identlist ''' if len(t)==5 : #print(t[1],t[2],t[3],t[4]) t[0] = t[1]+t[2]+t[3]+t[4] elif len(t)==4 : #pri...
identlist : IDENT | NOT IDENT | IDENT AND identlist | NOT IDENT AND identlist
def deserialize(self, msg): 'deserialize output to a Python object' self.logger.debug('deserializing %s', msg) return json.loads(msgf deserialize(self, msg): 'deserialize output to a Python object' self.logger.debug('deserializing %s', msg) return json.loads(msg)
deserialize output to a Python object
def append_request_id(req, resp, resource, params): def get_headers(resp): if hasattr(resp, 'headers'): return resp.headers if hasattr(resp, '_headers'): return resp._headers return None if(isinstance(resp, Response) or (get_headers(resp) is not None)...
Append request id which got from response header to resource.req_ids list.