INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get the input and output frame, then call :py:meth:`transform`.
def process_frame(self): """Get the input and output frame, then call :py:meth:`transform`. """ input_name = self.inputs[0] output_name = self.outputs[0] in_frame = self.input_buffer[input_name].get() out_frame = self.outframe_pool[output_name].get() out_...
Determines whether this AD Group is valid. :returns: True and "" if this group is valid or False and a string description with the reason why it isn't valid otherwise.
def _get_valididty(self): """ Determines whether this AD Group is valid. :returns: True and "" if this group is valid or False and a string description with the reason why it isn't valid otherwise. """ try: self.ldap_connection.search(search_base...
Gets the passed attribute of this group. :param attribute_name: The name of the attribute to get. :type attribute_name: str :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of from the cache. Default Fals...
def get_attribute(self, attribute_name, no_cache=False): """ Gets the passed attribute of this group. :param attribute_name: The name of the attribute to get. :type attribute_name: str :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instea...
Returns a dictionary of this group's attributes. This method caches the attributes after the first search unless no_cache is specified. :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of from the cache. Default Fals...
def get_attributes(self, no_cache=False): """ Returns a dictionary of this group's attributes. This method caches the attributes after the first search unless no_cache is specified. :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of ...
Searches for a group and retrieves its distinguished name. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
def _get_group_dn(self, group_lookup_attribute_value): """ Searches for a group and retrieves its distinguished name. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** i...
Searches for a group and retrieve its members. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server's ...
def _get_group_members(self, page_size=500): """ Searches for a group and retrieve its members. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be...
Searches for a user and retrieves his distinguished name. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
def _get_user_dn(self, user_lookup_attribute_value): """ Searches for a user and retrieves his distinguished name. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if th...
Retrieves member information from the AD group object. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the s...
def get_member_info(self, page_size=500): """ Retrieves member information from the AD group object. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size ...
Attempts to add a member to the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory. ...
def add_member(self, user_lookup_attribute_value): """ Attempts to add a member to the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided accoun...
Retrieves all members from this node of the tree down.
def get_tree_members(self): """ Retrieves all members from this node of the tree down.""" members = [] queue = deque() queue.appendleft(self) visited = set() while len(queue): node = queue.popleft() if node not in visited: ...
Attempts to remove a member from the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory. ...
def remove_member(self, user_lookup_attribute_value): """ Attempts to remove a member from the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provide...
Attempts to add a child to the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory. ...
def add_child(self, group_lookup_attribute_value): """ Attempts to add a child to the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group ...
Attempts to remove a child from the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory. ...
def remove_child(self, group_lookup_attribute_value): """ Attempts to remove a child from the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provide...
Returns a list of all descendants of this group. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server'...
def get_descendants(self, page_size=500): """ Returns a list of all descendants of this group. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be ...
Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server's size l...
def get_children(self, page_size=500): """ Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the ...
Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (optional): Many servers have a limit on the number of res...
def child(self, group_name, page_size=500): """ Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (...
Returns this group's parent (up to the DC)
def parent(self): """ Returns this group's parent (up to the DC)""" # Don't go above the DC if ''.join(self.group_dn.split("DC")[0].split()) == '': return self else: parent_dn = self.group_dn.split(",", 1).pop() return ADGroup( ...
Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int
def ancestor(self, generation): """ Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int """ # Don't go below the current g...
Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6]
def ranges_to_set(lst): """ Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6] """ return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))
Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)]
def to_ranges(lst): """ Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)] """ for a, b in itertools.groupby(enumerate(lst), lambda t: t[1] - t[0]): b = list(b) yield b[0][1], b[-1][1]
recurse down the tree and return a list of the most deeply nested child nodes of the given triple
def deepest_node((subj, pred, obj), graph): """recurse down the tree and return a list of the most deeply nested child nodes of the given triple""" # i don't fully accept the premise that this docstring presents # i'm not a docstring literalist to_return = [] def _deepest_node((subj, pred, obj)...
Chained lookup of item on model If item has dots (eg: 'foo.bar.baz'), recursively call getattribute(): e = getattr(model, 'foo') e = getattr(e, 'bar') e = getattr(e, 'baz') At each step, check if e is a callable, and if so, use e()
def getattribute(model, item): """Chained lookup of item on model If item has dots (eg: 'foo.bar.baz'), recursively call getattribute(): e = getattr(model, 'foo') e = getattr(e, 'bar') e = getattr(e, 'baz') At each step, check if e is a callable, and if so, use e() """ elements = item....
Display a comma-separated list of models for M2M fields
def nice_display(item): """Display a comma-separated list of models for M2M fields""" if hasattr(item, 'all'): # RelatedManager: display a list return ', '.join(map(text_type, item.all())) return item
Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``countrycode.countrycode`` for details and other options. Raises ``ValueEr...
def normalizeCountry(country_str, target="iso3c", title_case=False): """Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``c...
Choose the most common item from the list, or the first item if all items are unique.
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
Obfuscates password from a database URL.
def safeDbUrl(db_url): """Obfuscates password from a database URL.""" url = urlparse(db_url) return db_url.replace(url.password, "****") if url.password else db_url
Read, parse and return given Json config file
def loadJson(self, filename): """ Read, parse and return given Json config file """ jsonConfig = {} if os.path.isfile(filename): jsonConfig = json.loads(' '.join(open(filename, 'r').readlines())) return jsonConfig
The model can't be changed once the export is created
def get_readonly_fields(self, request, obj=None): """The model can't be changed once the export is created""" if obj is None: return [] return super(ExportAdmin, self).get_readonly_fields(request, obj)
If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup
def response_add(self, request, obj, post_url_continue=POST_URL_CONTINUE): """If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup """ if '_a...
Pylint Validator that will fail any review if there are new Pylint errors in it (Pylint message starts with 'E:') :param new_data: :param old_data: :return:
def no_new_errors(new_data, old_data, strict=False): """ Pylint Validator that will fail any review if there are new Pylint errors in it (Pylint message starts with 'E:') :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if new_data['errors...
Verifies that the pylint score is above a given threshold. :param new_data: :param old_data: :return:
def above_score_threshold(new_data, old_data, strict=False, threshold=PYLINT_SCORE_THRESHOLD): """ Verifies that the pylint score is above a given threshold. :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if strict: for fscore, fname...
Run the new pylint data through given all current checkers, including comparisons to old pylint data.
def run(self, new_pylint_data, old_pylint_data): """ Run the new pylint data through given all current checkers, including comparisons to old pylint data. """ for validator in self.checkers: success, score, message = validator(new_pylint_data, old_pylint_data) ...
helper, get a list of (linetext, linenum) from a string with newlines
def _document_lines(self, text): """helper, get a list of (linetext, linenum) from a string with newlines """ inlines = text.split('\n') doc_lines = [(re.sub(r'^ +| +$', '', line), num) for line, num in zip(inlines, xrange(1, len(inlines)...
helper, open a file or url and return the content and identifier
def _get_document(self, source): """helper, open a file or url and return the content and identifier""" scheme_url = source if not source.startswith("http"): scheme_url = "http://%s" % source text = source try: text = urllib.urlopen(scheme_url).read() ...
Returns random unused port number.
def select_random(ports=None, exclude_ports=None): """ Returns random unused port number. """ if ports is None: ports = available_good_ports() if exclude_ports is None: exclude_ports = set() ports.difference_update(set(exclude_ports)) for port in random.sample(ports, min(l...
Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range.
def available_ports(low=1024, high=65535, exclude_ranges=None): """ Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range. """ if exclude_ranges is None: exclude_ranges = [] available = utils.ranges_t...
Returns a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded.
def good_port_ranges(ports=None, min_range_len=20, border=3): """ Returns a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded. """ min_range_len += border*2 if ports is None: ports = available_ports() ...
Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections.
def port_is_used(port, host='127.0.0.1'): """ Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections. """ unused = _can_bind(port, host) and _refuses_connection(port, host) return not unused
Get data for day (1-25) and year (>= 2015) User's session cookie is needed (puzzle inputs differ by user)
def get_data(session=None, day=None, year=None): """ Get data for day (1-25) and year (>= 2015) User's session cookie is needed (puzzle inputs differ by user) """ if session is None: user = default_user() else: user = User(token=session) if day is None: day = current_...
This year, if it's December. The most recent year, otherwise. Note: Advent of Code started in 2015
def most_recent_year(): """ This year, if it's December. The most recent year, otherwise. Note: Advent of Code started in 2015 """ aoc_now = datetime.datetime.now(tz=AOC_TZ) year = aoc_now.year if aoc_now.month < 12: year -= 1 if year < 2015: raise AocdError("Time tra...
Most recent day, if it's during the Advent of Code. Happy Holidays! Day 1 is assumed, otherwise.
def current_day(): """ Most recent day, if it's during the Advent of Code. Happy Holidays! Day 1 is assumed, otherwise. """ aoc_now = datetime.datetime.now(tz=AOC_TZ) if aoc_now.month != 12: log.warning("current_day is only available in December (EST)") return 1 day = min(aoc...
Returns tuple (day, year). Here be dragons! The correct date is determined with introspection of the call stack, first finding the filename of the module from which ``aocd`` was imported. This means your filenames should be something sensible, which identify the day and year unambiguously. The ex...
def get_day_and_year(): """ Returns tuple (day, year). Here be dragons! The correct date is determined with introspection of the call stack, first finding the filename of the module from which ``aocd`` was imported. This means your filenames should be something sensible, which identify the ...
Register a Linter class for file verification. :param linter: :return:
def register_linter(linter): """ Register a Linter class for file verification. :param linter: :return: """ if hasattr(linter, "EXTS") and hasattr(linter, "run"): LintFactory.PLUGINS.append(linter) else: raise LinterException("Linter does ...
Escapes certain filter characters from an LDAP query.
def escape_query(query): """Escapes certain filter characters from an LDAP query.""" return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
Recursively compiles the regexs in the pattern (p).
def _compile(self, p): """ Recursively compiles the regexs in the pattern (p). """ if self._is_value_filter(p) and p[0] == '=~': try: p[2] = re.compile(p[2]) except: # Python doesn't document exactly what exceptions re.compile throws ...
Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure.
def _validate(self, p): """ Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure. """ if self._is_operator(p): for operator_or_filter in (p[1] if p[0] != '!' else [p[1]]): if p[0] == '^': self._va...
Raises ValueError if 2 arguments are not passed to an XOR
def _validate_xor_args(self, p): """ Raises ValueError if 2 arguments are not passed to an XOR """ if len(p[1]) != 2: raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p))
Calls either _match_operator or _match_operand depending on the pattern (p) provided.
def _match(self, p, value): """ Calls either _match_operator or _match_operand depending on the pattern (p) provided. """ if self._is_operator(p): return self._match_operator(p, value) else: try: if self._is_value_filter(p): ...
Returns True or False if the operator (&, |, or ! with filters, or ^ with filters) matches the value dictionary
def _match_operator(self, p, value): """ Returns True or False if the operator (&, |, or ! with filters, or ^ with filters) matches the value dictionary """ if p[0] == '!': return self._OPERATOR_MAP[p[0]](self._match(p[1], value)) elif p[0] == '^': return ...
Returns True of False if value in the pattern p matches the filter.
def _match_value_filter(self, p, value): """ Returns True of False if value in the pattern p matches the filter. """ return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])
Builds a set of all field keys used in the pattern including nested fields. :param pattern: The kmatch pattern to get field keys from or None to use self.pattern :type pattern: list or None :returns: A set object of all field keys used in the pattern :rtype: set
def get_field_keys(self, pattern=None): """ Builds a set of all field keys used in the pattern including nested fields. :param pattern: The kmatch pattern to get field keys from or None to use self.pattern :type pattern: list or None :returns: A set object of all field keys used...
Initialise a :py:class:`Frame` from another :py:class:`Frame`. Copies the metadata and (a reference to) the data from :py:obj:`other`. Note that the data is not actually copied -- you must make a copy of the data before changing it. :param Frame other: The frame to copy.
def initialise(self, other): """Initialise a :py:class:`Frame` from another :py:class:`Frame`. Copies the metadata and (a reference to) the data from :py:obj:`other`. Note that the data is not actually copied -- you must make a copy of the data before changing it. :param Frame ...
Return image dimensions (height, width)
def size(self): """Return image dimensions (height, width)""" if isinstance(self.data, numpy.ndarray): h, w = self.data.shape[:2] elif isinstance(self.data, PIL.Image.Image): w, h = self.data.size() else: raise RuntimeError( 'Cannot get...
Get image data in :py:class:`numpy:numpy.ndarray` form. Note that if the image data is already in the correct format this can be a null operation. When converting to limited range types (``numpy.uint8``, ``numpy.uint16``) the data is clipped (limited) to the range. :keyword nu...
def as_numpy(self, dtype=None, copy=False): """Get image data in :py:class:`numpy:numpy.ndarray` form. Note that if the image data is already in the correct format this can be a null operation. When converting to limited range types (``numpy.uint8``, ``numpy.uint16``) the data ...
Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image`
def as_PIL(self): """Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image` """ if isinstance(se...
Read metadata from an XMP sidecar file or, if there is no sidecar, from the image/video file (if it has metadata). Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().from_file(path) :param str path: The image/video file path name....
def from_file(self, path): """Read metadata from an XMP sidecar file or, if there is no sidecar, from the image/video file (if it has metadata). Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().from_file(path) :param str...
Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name.
def to_file(self, path): """Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name. """ xmp_path = path + '.xmp' # remove any existing XMP file if os.path.exists(xmp_path): os.unlink(xmp_path) # attempt...
Copy metadata from another :py:class:`Metadata` object. Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().copy(other_md) :param Metadata other: The metadata to copy. :rtype: :py:class:`Metadata`
def copy(self, other): """Copy metadata from another :py:class:`Metadata` object. Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().copy(other_md) :param Metadata other: The metadata to copy. :rtype: :py:class:`Metadata`...
Get image dimensions from metadata. This is primarily used by the :py:class:`~pyctools.components.io.rawfilereader.RawFileReader` component, as raw video files don't have a header in which to store the dimensions. :returns: width, height. :rtype: :py:class:`int`, :py:c...
def image_size(self): """Get image dimensions from metadata. This is primarily used by the :py:class:`~pyctools.components.io.rawfilereader.RawFileReader` component, as raw video files don't have a header in which to store the dimensions. :returns: width, height. ...
Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML file. :param str tag: The tag...
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
Set a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML file. :param str tag: The tag...
def set(self, tag, value): """Set a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML ...
Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration. :type is_read_only: bool :param is_read_only: In case of redis sentinel, it returns connection to slave :return: Returns a StrictRedis connection
def get_connection(self, is_read_only=False) -> redis.StrictRedis: """ Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration. :type is_read_only: bool :param is_read_only: In case of redis sentinel, it returns connection to slave ...
filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well just filtering those out
def filter_bad_results(search_results, guessit_query): """ filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well ...
Calculates the hash for the given filename. Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes @param name: str Path to the file @return: str The calculated hash code, as an hex string.
def calculate_hash_for_file(name): ''' Calculates the hash for the given filename. Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes @param name: str Path to the file @return: str The calculated hash code, as an hex string. ''' longl...
Python 2.6 support: subprocess.check_output from Python 2.7.
def check_output(params): """ Python 2.6 support: subprocess.check_output from Python 2.7. """ popen = subprocess.Popen(params, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output, _ = popen.communicate() returncode = popen.poll() if returncode ...
Add config to an :py:class:`argparse.ArgumentParser` object. The parser’s :py:meth:`~argparse.ArgumentParser.add_argument` method is called for each config item. The argument name is constructed from the parent and item names, with a dot separator. :param argparse.ArgumentParse...
def parser_add(self, parser, prefix=''): """Add config to an :py:class:`argparse.ArgumentParser` object. The parser’s :py:meth:`~argparse.ArgumentParser.add_argument` method is called for each config item. The argument name is constructed from the parent and item names, with a dot ...
Set config from an :py:class:`argparse.Namespace` object. Call this method with the return value from :py:meth:`~argparse.ArgumentParser.parse_args`. :param argparse.Namespace args: The populated :py:class:`argparse.Namespace` object.
def parser_set(self, args): """Set config from an :py:class:`argparse.Namespace` object. Call this method with the return value from :py:meth:`~argparse.ArgumentParser.parse_args`. :param argparse.Namespace args: The populated :py:class:`argparse.Namespace` object. ...
Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a threadsafe manner while the comp...
def set_config(self, config): """Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a...
Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool
def update_config(self): """Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool """ res...
Gaussian filter generator core. Alternative to the :py:class:`GaussianFilter` component that can be used to make a non-reconfigurable resizer:: resize = Resize() resize.filter(GaussianFilterCore(x_sigma=1.5)) ... start(..., resize, ...) ... :keyword float x_sigma: ...
def GaussianFilterCore(x_sigma=0.0, y_sigma=0.0): """Gaussian filter generator core. Alternative to the :py:class:`GaussianFilter` component that can be used to make a non-reconfigurable resizer:: resize = Resize() resize.filter(GaussianFilterCore(x_sigma=1.5)) ... start(.....
Put a command on the queue to be called in the component's thread. :param callable command: the method to be invoked, e.g. :py:meth:`~Component.new_frame_event`.
def queue_command(self, command): """Put a command on the queue to be called in the component's thread. :param callable command: the method to be invoked, e.g. :py:meth:`~Component.new_frame_event`. """ if self._running: # queue event normally ...
Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` methods as required until ...
def start(self): """Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` metho...
Wait until the event loop terminates or ``timeout`` is reached. This method is not meaningful unless called from the Qt "main thread", which is almost certainly the thread in which the component was created. :keyword float timeout: timeout in seconds.
def join(self, timeout=3600): """Wait until the event loop terminates or ``timeout`` is reached. This method is not meaningful unless called from the Qt "main thread", which is almost certainly the thread in which the component was created. :keyword float timeout: timeo...
Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`IntraField` component is created.
def IntraField(config={}): """Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`In...
Initializes redis connection :param redis_host: Hostname of redis server :type redis_host: str :param redis_port: Port at which redis server is listening :type redis_port:int :param is_sentinel_redis: Parameter indicating if redis server is a sentinel server. Default is false ...
def init(cls, redis_host: str, redis_port: int, is_sentinel_redis=False, redis_sentinel_service="mymaster", redis_password=None): """ Initializes redis connection :param redis_host: Hostname of redis server :type redis_host: str :param redis_port: Port at which redi...
Creates a rate limiting rule with rate limiting period and attempt limit :param period: Rate limiting period in seconds :type period: int :param limit: Number of attempts permitted by rate limiting within a given period :type limit: int
def create(self, period: int, limit: int): """ Creates a rate limiting rule with rate limiting period and attempt limit :param period: Rate limiting period in seconds :type period: int :param limit: Number of attempts permitted by rate limiting within a given period :ty...
Checks if a namespace is rate limited or not with including/excluding the current call :param namespace: Rate limiting namespace :type namespace: str :param add_attempt: Boolean value indicating if the current call should be considered as an attempt or not :type add_attempt: bool ...
def __can_attempt(self, namespace: str, add_attempt=True) -> bool: """ Checks if a namespace is rate limited or not with including/excluding the current call :param namespace: Rate limiting namespace :type namespace: str :param add_attempt: Boolean value indicating if the curre...
Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate limiting rules, false otherwise
def is_rate_limited(self, namespace: str) -> bool: """ Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate...
Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') ...
Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar.
def main(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', ...
atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ;
def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token == '(': tokens.move() result = [Required(*parse_expr(tokens, options))] if tokens.move() ...
Find arguments that should accumulate values and fix them.
def fix_list_arguments(self): """Find arguments that should accumulate values and fix them.""" either = [list(c.children) for c in self.either.children] for case in either: case = [c for c in case if case.count(c) > 1] for a in [e for e in case if type(e) == Argument]: ...
Transform pattern into an equivalent, with only top-level Either.
def either(self): """Transform pattern into an equivalent, with only top-level Either.""" # Currently the pattern will not be equivalent, but more "narrow", # although good enough to reason about list arguments. if not hasattr(self, 'children'): return Either(Required(self)) ...
Add or updated the Image.
def syncImage(img, current, session): """Add or updated the Image.""" def _img_str(i): return "%s - %s" % (i.type, i.description) for db_img in current.images: img_info = (img.type, img.md5, img.size) db_img_info = (db_img.type, db_img.md5, db_img.size) if db_img_info == im...
Filter the form's column choices This is done at the formset level as there's no other way i could find to get the parent object (stored in self.instance), and the form at the same time.
def add_fields(self, form, index): """Filter the form's column choices This is done at the formset level as there's no other way i could find to get the parent object (stored in self.instance), and the form at the same time. """ super(ColumnFormSet, self).add_fields(for...
Walk source directory tree and convert each sub directory to a package name.
def find_packages(): """Walk source directory tree and convert each sub directory to a package name. """ packages = ['pyctools'] for root, dirs, files in os.walk(os.path.join('src', 'pyctools')): package = '.'.join(root.split(os.sep)[1:]) for name in dirs: packages.appen...
Make sure package hierarchy is a "pkgutil-style namespace package". For more detail see https://packaging.python.org/guides/packaging-namespace-packages/
def write_init_files(packages): """Make sure package hierarchy is a "pkgutil-style namespace package". For more detail see https://packaging.python.org/guides/packaging-namespace-packages/ """ init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__) try: from .__doc_...
From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port...
def extract_param(param, args, type=None): """ From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int...
Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages.
def get_nltk_builder(languages): """Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages. """ all_stemmers = [] all_stopwords_filters = [] all_word_characters = set() for language in languages: if language == "...
Register all supported languages to ensure compatibility.
def register_languages(): """Register all supported languages to ensure compatibility.""" for language in set(SUPPORTED_LANGUAGES) - {"en"}: language_stemmer = partial(nltk_stemmer, get_language_stemmer(language)) Pipeline.register_function(language_stemmer, "stemmer-{}".format(language))
Converts a number to its ordinal representation. :param value: number >>> print(ordinal(1)) 1st >>> print(ordinal(11)) 11th >>> print(ordinal(101)) 101st >>> print(ordinal(104)) 104th >>> print(ordinal(113)) 113th >>> print(ordinal(123)) 123rd
def ordinal(value): ''' Converts a number to its ordinal representation. :param value: number >>> print(ordinal(1)) 1st >>> print(ordinal(11)) 11th >>> print(ordinal(101)) 101st >>> print(ordinal(104)) 104th >>> print(ordinal(113)) 113th >>> print(ordinal(123)) ...
Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 %
def percentage(value, digits=2): ''' Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % ''' value = floa...
Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million
def word(value, digits=2): ''' Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million ''' convention = locale.localeconv() decimal_point = convention[...
Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude']).exclude [] >>> renames = parse_args...
def parse_args(*args, **kwargs): """ Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude'])...
Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace.
def _full_rename(args): """ Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace. """ return ( args.ns and all(map(args.rename.affects, args.ns)) )
Apply operation in db
def apply(db, op): """ Apply operation in db """ dbname = op['ns'].split('.')[0] or "admin" opts = bson.CodecOptions(uuid_representation=bson.binary.STANDARD) db[dbname].command("applyOps", [op], codec_options=opts)
Construct RenameSpec from a pair separated by equal sign ('=').
def from_spec(cls, string_spec): """ Construct RenameSpec from a pair separated by equal sign ('='). """ old_ns, new_ns = string_spec.split('=') return cls(old_ns, new_ns)
Query the oplog for items since ts and then return
def since(self, ts): """ Query the oplog for items since ts and then return """ spec = {'ts': {'$gt': ts}} cursor = self.query(spec) while True: # todo: trap InvalidDocument errors: # except bson.errors.InvalidDocument as e: # logging....
Determine if there are any ops before ts
def has_ops_before(self, ts): """ Determine if there are any ops before ts """ spec = {'ts': {'$lt': ts}} return bool(self.coll.find_one(spec))
Tail the oplog, starting from ts.
def since(self, ts): """ Tail the oplog, starting from ts. """ while True: items = super(TailingOplog, self).since(ts) for doc in items: yield doc ts = doc['ts']