INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return the PROJ.4 string which corresponds to the CRS. For example:: >>> print(get(21781).as_proj4()) +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \ +k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \ +towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs
def as_proj4(self): """ Return the PROJ.4 string which corresponds to the CRS. For example:: >>> print(get(21781).as_proj4()) +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \ +k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \ +towgs84=674.4,15.1,405.3,0,0,0,...
Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81]
def domain_of_validity(self): """ Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] """ # TODO: Generalise interface to return a polyg...
The :class:`GeodeticCRS` on which this projection is based.
def base_geodetic_crs(self): """The :class:`GeodeticCRS` on which this projection is based.""" base = self.element.find(GML_NS + 'baseGeodeticCRS') href = base.attrib[XLINK_NS + 'href'] return get(href)
The :class:`CartesianCS` which describes the coordinate axes.
def cartesian_cs(self): """The :class:`CartesianCS` which describes the coordinate axes.""" cs = self.element.find(GML_NS + 'cartesianCS') href = cs.attrib[XLINK_NS + 'href'] return get(href)
Log events to the console. Args: status (bool, Optional, Default=True) whether logging to console should be turned on(True) or off(False) level (string, Optional, Default=None) : level of logging; whichever level is chosen all higher levels will be logged. ...
def log_to_console(status=True, level=None): """Log events to the console. Args: status (bool, Optional, Default=True) whether logging to console should be turned on(True) or off(False) level (string, Optional, Default=None) : level of logging; whichever level is chosen...
Log events to a file. Args: status (bool, Optional, Default=True) whether logging to file should be turned on(True) or off(False) filename (string, Optional, Default=None) : path of file to log to level (string, Optional, Default=None) : level of logging;...
def log_to_file(status=True, filename=DEFAULT_LOG_FILE, level=None): """Log events to a file. Args: status (bool, Optional, Default=True) whether logging to file should be turned on(True) or off(False) filename (string, Optional, Default=None) : path of file to log to ...
Removes a `method` from the table by identity.
def remove(self, method: Method): """ Removes a `method` from the table by identity. """ self._table = [fld for fld in self._table if fld is not method]
Creates a new method from `name` and `descriptor`. If `code` is not ``None``, add a `Code` attribute to this method.
def create(self, name: str, descriptor: str, code: CodeAttribute=None) -> Method: """ Creates a new method from `name` and `descriptor`. If `code` is not ``None``, add a `Code` attribute to this method. """ method = Method(self._cf) name = self._cf.constant...
Read the MethodTable from the file-like object `source`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like object providing `read()`
def unpack(self, source: IO): """ Read the MethodTable from the file-like object `source`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like objec...
Write the MethodTable to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providing `write()`
def pack(self, out: IO): """ Write the MethodTable to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providing `...
Iterates over the methods table, yielding each matching method. Calling without any arguments is equivalent to iterating over the table. For example, to get all methods that take three integers and return void:: for method in cf.methods.find(args='III', returns='V'): print(m...
def find(self, *, name: str=None, args: str=None, returns: str=None, f: Callable=None) -> Iterator[Method]: """ Iterates over the methods table, yielding each matching method. Calling without any arguments is equivalent to iterating over the table. For example, to get all me...
Read the CodeAttribute from the byte string `info`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param info: A byte string containing an unparsed CodeAttribute.
def unpack(self, info): """ Read the CodeAttribute from the byte string `info`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param info: A byte string containing an unpa...
The `CodeAttribute` in packed byte string form.
def pack(self): """ The `CodeAttribute` in packed byte string form. """ with io.BytesIO() as file_out: file_out.write(pack( '>HHI', self.max_stack, self.max_locals, len(self._code) )) file...
Assembles an iterable of :class:`~jawa.util.bytecode.Instruction` objects into a method's code body.
def assemble(self, code): """ Assembles an iterable of :class:`~jawa.util.bytecode.Instruction` objects into a method's code body. """ with io.BytesIO() as code_out: for ins in code: write_instruction(code_out, code_out.tell(), ins) self._c...
Disassembles this method, yielding an iterable of :class:`~jawa.util.bytecode.Instruction` objects.
def disassemble(self, *, transforms=None) -> Iterator[Instruction]: """ Disassembles this method, yielding an iterable of :class:`~jawa.util.bytecode.Instruction` objects. """ if transforms is None: if self.cf.classloader: transforms = self.cf.classloa...
Set the value if a volume level is provided, else print the current volume level.
def _volume_command(ramp, volume): """ Set the value if a volume level is provided, else print the current volume level. """ if volume is not None: ramp.set_volume(float(volume)) else: print ramp.volume
Build a nice status message and print it to stdout.
def _status_command(cast, ramp): """ Build a nice status message and print it to stdout. """ if ramp.is_playing: play_symbol = u'\u25B6' else: play_symbol = u'\u2759\u2759' print u' %s %s by %s from %s via %s, %s of %s' % ( play_symbol, ramp.title, ramp.artist, ...
Read the options given on the command line and do the required actions. This method is used in the entry_point `cast`.
def main(): """ Read the options given on the command line and do the required actions. This method is used in the entry_point `cast`. """ opts = docopt(__doc__, version="cast 0.1") cast = pychromecast.PyChromecast(CHROMECAST_HOST) ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP) # Wa...
Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two t...
def untokenize(iterable): """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number an...
The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline can be a callable function terminat...
def tokenize(readline): """ The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline ...
Get powers of 2 that sum up to the given number. This function transforms given integer to a binary string. A reversed value limited to digits of binary number is extracted from it, and each of its characters is enumerated. Each digit is tested for not being 0. If the test passes, the index associ...
def get_powers_of_2(_sum): """Get powers of 2 that sum up to the given number. This function transforms given integer to a binary string. A reversed value limited to digits of binary number is extracted from it, and each of its characters is enumerated. Each digit is tested for not being 0. If the...
Query the DNSBL service for given value. :param host_object: an object representing host, created by self._host_factory :returns: an instance of dns.resolver.Answer for given value if it is listed. Otherwise, it returns None.
def _query(self, host_object): """Query the DNSBL service for given value. :param host_object: an object representing host, created by self._host_factory :returns: an instance of dns.resolver.Answer for given value if it is listed. Otherwise, it returns None. """ ...
Query the client for data of given host. :param host_object: an object representing a host value :param classification: if True: hpHosts is queried also for classification for given host, if listed :returns: content of response to GET request to hpHosts for data on the given hos...
def _query(self, host_object, classification=False): """Query the client for data of given host. :param host_object: an object representing a host value :param classification: if True: hpHosts is queried also for classification for given host, if listed :returns: content of resp...
Get address of a POST request to the service.
def _request_address(self): """Get address of a POST request to the service.""" if not self._request_address_val: template = ( 'https://sb-ssl.google.com/safebrowsing/api/lookup' '?client={0}&key={1}&appver={2}&pver={3}' ) self._request...
Perform a single POST request using lookup API. :param urls: a sequence of URLs to put in request body :returns: a response object :raises UnathorizedAPIKeyError: when the API key for this instance is not valid :raises HTTPError: if the HTTPError was raised for a HTTP code ...
def _query_once(self, urls): """Perform a single POST request using lookup API. :param urls: a sequence of URLs to put in request body :returns: a response object :raises UnathorizedAPIKeyError: when the API key for this instance is not valid :raises HTTPError: if the HT...
Test URLs for being listed by the service. :param urls: a sequence of URLs to be tested :returns: a tuple containing chunk of URLs and a response pertaining to them if the code of response was 200, which means at least one of the queried URLs is matched in either the phishing, ...
def _query(self, urls): """Test URLs for being listed by the service. :param urls: a sequence of URLs to be tested :returns: a tuple containing chunk of URLs and a response pertaining to them if the code of response was 200, which means at least one of the queried URLs is match...
Get classification for all matching URLs. :param urls: a sequence of URLs to test :return: a tuple containing matching URL and classification string pertaining to it
def _get_match_and_classification(self, urls): """Get classification for all matching URLs. :param urls: a sequence of URLs to test :return: a tuple containing matching URL and classification string pertaining to it """ for url_list, response in self._query(urls): ...
Get items for all listed URLs. :param urls: a sequence of URLs to be tested :returns: objects representing listed URLs :raises InvalidURLError: if there are any invalid URLs in the sequence
def lookup_matching(self, urls): """Get items for all listed URLs. :param urls: a sequence of URLs to be tested :returns: objects representing listed URLs :raises InvalidURLError: if there are any invalid URLs in the sequence """ for url, _class in self._get_matc...
Allow to register all subclasses of Pylot So we call it once initiating :param flask_or_import_name: Flask instance or import name -> __name__ :param directory: The directory containing your project's Views, Templates and Static :param config: string of config object. ie: "app.config.Dev...
def init(cls, flask_or_import_name, directory=None, config=None): """ Allow to register all subclasses of Pylot So we call it once initiating :param flask_or_import_name: Flask instance or import name -> __name__ :param directory: The directory containing your project's Views, Te...
To bind application that needs the 'app' object to init :param app: callable function that will receive 'Flask.app' as first arg
def bind_(cls, kls): """ To bind application that needs the 'app' object to init :param app: callable function that will receive 'Flask.app' as first arg """ if not hasattr(kls, "__call__"): raise TypeError("From Pylot.bind_: '%s' is not callable" % kls) cls._...
A view decorator to extend another view class or function to itself It will inherit all its methods and propeties and use them on itself -- EXAMPLES -- class Index(Pylot): pass index = Index() ::-> As decorator on classes :: @index.extends_ class A...
def extends_(cls, kls): """ A view decorator to extend another view class or function to itself It will inherit all its methods and propeties and use them on itself -- EXAMPLES -- class Index(Pylot): pass index = Index() ::-> As decorator on classe...
Shortcut to access the config in your class :param key: The key to access :param default: The default value when None :returns mixed:
def config_(cls, key, default=None): """ Shortcut to access the config in your class :param key: The key to access :param default: The default value when None :returns mixed: """ return cls._app.config.get(key, default)
Meta allows you to add meta data to site :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) (but can pick it up from config file) ...
def meta_(cls, **kwargs): """ Meta allows you to add meta data to site :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) (but...
To render data to the associate template file of the action view :param data: The context data to pass to the template :param view_template: The file template to use. By default it will map the classname/action.html :param layout: The body layout, must contain {% include __view_template__ %}
def render(cls, data={}, view_template=None, layout=None, **kwargs): """ To render data to the associate template file of the action view :param data: The context data to pass to the template :param view_template: The file template to use. By default it will map the classname/action.html...
Send simple message
def send(self, to, subject, body, reply_to=None, **kwargs): """ Send simple message """ if self.provider == "SES": self.mail.send(to=to, subject=subject, body=body, reply_to=reply_to, ...
Send Template message
def send_template(self, template, to, reply_to=None, **context): """ Send Template message """ if self.provider == "SES": self.mail.send_template(template=template, to=to, reply_to=reply_to, **context) elif self.provider == "FLASK-MAIL": ses_mail = ses_mai...
Generator process to read file
def file_reader(self): """Generator process to read file""" self.update_config() path = self.config['path'] fourcc = self.metadata.get('fourcc') xlen, ylen = self.metadata.image_size() # set bits per pixel and component dimensions if fourcc in ('BGR[24]',): ...
Context manager. Stores current dir, then changes to given directory. At the end it changes back. :param directory: :return:
def cd_ctx(directory): """ Context manager. Stores current dir, then changes to given directory. At the end it changes back. :param directory: :return: """ prevdir = os.path.abspath(os.curdir) if os.path.isdir(directory): os.chdir(directory) yield os.chdir(prevdir)
Displays pylint data to the console. :param pylint_data: :return:
def dump_to_console(pylint_data): """ Displays pylint data to the console. :param pylint_data: :return: """ for key, value in list(pylint_data.items()): if key not in ('errors', 'total', 'scores', 'average') and len(value) > 0: print("\n*********** {}".format(key)) ...
Post the data to gerrit. This right now is a stub, as I'll need to write the code to post up to gerrit. :param commit: Commit ID of the review. :param message: Message to accompany the review score. :param user: SSH User for posting to gerrit. :param gerrit: Hostname of the gerrit server. :para...
def post_to_gerrit(commit, score=0, message='', user='lunatest', gerrit=None): """ Post the data to gerrit. This right now is a stub, as I'll need to write the code to post up to gerrit. :param commit: Commit ID of the review. :param message: Message to accompany the review score. :param user: ...
Sorts a list of files into types. :param file_list: List of file paths. :return: {extension: [<list of file paths with that extension>]}
def sort_by_type(file_list): """ Sorts a list of files into types. :param file_list: List of file paths. :return: {extension: [<list of file paths with that extension>]} """ ret_dict = defaultdict(list) for filepath in file_list: _, ext = os.path.splitext(filepath) ret_dict[...
Note: Answers are only revealed after a correct submission. If you've have not already solved the puzzle, AocdError will be raised.
def _get_answer(self, part): """ Note: Answers are only revealed after a correct submission. If you've have not already solved the puzzle, AocdError will be raised. """ answer_fname = getattr(self, "answer_{}_fname".format(part)) if os.path.isfile(answer_fname): ...
Check out target into the current directory. Target can be a branch, review Id, or commit. :param repository: Current git repository. :param target: Review ID, commit, branch. :return: Return the most recent commit ID (top of the git log).
def checkout(repository, target): """ Check out target into the current directory. Target can be a branch, review Id, or commit. :param repository: Current git repository. :param target: Review ID, commit, branch. :return: Return the most recent commit ID (top of the git log). """ # git...
Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory.
def get_files_changed(repository, review_id): """ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List ...
Connect an output to any callable object. :param str output_name: the output to connect. Must be one of the ``'self'`` outputs in the ``linkages`` parameter. :param callable input_method: the thread-safe callable to invoke when :py:meth:`send` is called.
def connect(self, output_name, input_method): """Connect an output to any callable object. :param str output_name: the output to connect. Must be one of the ``'self'`` outputs in the ``linkages`` parameter. :param callable input_method: the thread-safe callable to invoke ...
Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines.
def bind(self, source, dest, destmeth): """Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines. """ self.connect(source, getattr(dest, destmeth))
See :py:meth:`pyctools.core.config.ConfigMixin.set_config`.
def set_config(self, config): """See :py:meth:`pyctools.core.config.ConfigMixin.set_config`.""" self.config.update(config) if self.config_map: for child_name in self.config_map: child_config = self._compound_children[child_name].get_config() for parent...
Start the component running.
def start(self): """Start the component running.""" for name, child in self._compound_children.items(): self.logger.debug('start %s (%s)', name, child.__class__.__name__) child.start()
Wait for the compound component's children to stop running. :param bool end_comps: only wait for the components that end a pipeline. This is useful for complex graphs where it is normal for some components not to terminate.
def join(self, end_comps=False): """Wait for the compound component's children to stop running. :param bool end_comps: only wait for the components that end a pipeline. This is useful for complex graphs where it is normal for some components not to terminate. """ ...
Yield ordered list of connections to one child. Each result is a ((component, output), (component, input)) tuple. :param string name: the component whose input connections are wanted.
def input_connections(self, name): """Yield ordered list of connections to one child. Each result is a ((component, output), (component, input)) tuple. :param string name: the component whose input connections are wanted. """ for input_name in self._compound_childr...
Yield ordered list of connections to one child. Each result is a ((component, output), (component, input)) tuple. :param string name: the component whose output connections are wanted.
def output_connections(self, name): """Yield ordered list of connections to one child. Each result is a ((component, output), (component, input)) tuple. :param string name: the component whose output connections are wanted. """ for output_name in self._compound_chi...
Generator process to read file
def file_reader(self): """Generator process to read file""" self.update_config() path = self.config['path'] # open file to get dimensions with self.subprocess( ['ffmpeg', '-v', 'info', '-y', '-an', '-vn', '-i', path, '-'], stdout=subprocess.PIPE, s...
Do the bulk of the work Exit status will be 1 if pylint fails. Exit status will be 0 if pylint passes. :param review_id: Target gerrit review ID. ex: refs/changes/99/299/3 :param repository: Git repository. :param branch: Git branch to compare to. :param user: SSH User that can connect to gerr...
def main(review_id, repository, branch="development", user='admin', gerrit=None): """ Do the bulk of the work Exit status will be 1 if pylint fails. Exit status will be 0 if pylint passes. :param review_id: Target gerrit review ID. ex: refs/changes/99/299/3 :param repository: Git repository. ...
Allows foreign keys to work in sqlite.
def set_sqlite_pragma(dbapi_connection, connection_record): """Allows foreign keys to work in sqlite.""" import sqlite3 if dbapi_connection.__class__ is sqlite3.Connection: cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close()
Iterate over all Library rows found in `session`. :param names: Optional sequence of names to filter on.
def iterall(Class, session, names=None): """Iterate over all Library rows found in `session`. :param names: Optional sequence of names to filter on. """ names = set(names if names else []) for lib in session.query(Class).filter(Class.id > NULL_LIB_ID).all(): if not na...
Initialize logging
def Logs(loggername, echo=True, debug=False, chatty=False, loglevel=logging.INFO, logfile=None, logpath=None, fileHandler=None): """Initialize logging """ log = logging.getLogger(loggername) if fileHandler is None: if logfile is None: logFilename = _ourName else: ...
Iterate over all triples in the graph and validate each one appropriately
def validate(self): """Iterate over all triples in the graph and validate each one appropriately """ log.info("{}\nValidating against {}" .format("-" * 100, self.schema_def.__class__.__name__)) if not self.schema_def: raise ValueError("No schema ...
compare triple to ontology, return error or None
def _check_triple(self, triple): """compare triple to ontology, return error or None""" subj, pred, obj = triple if self._should_ignore_predicate(pred): log.info("Ignoring triple with predicate '{}'" .format(self._field_name_from_uri(pred))) return ...
return error if class `cl` is not found in the ontology
def _validate_class(self, cl): """return error if class `cl` is not found in the ontology""" if cl not in self.schema_def.attributes_by_class: search_string = self._build_search_string(cl) err = self.err( "{0} - invalid class", self._field_name_from_uri(cl), ...
return error if `member` is not a member of any class in `classes`
def _validate_member(self, member, classes, instanceof): """return error if `member` is not a member of any class in `classes` """ log.info("Validating member %s" % member) stripped = self._get_stripped_attributes(member, classes) if self._field_name_from_uri(member) in ...
returns error if we've already seen the member `pred` on `subj`
def _validate_duplication(self, subj_and_pred, cl): """returns error if we've already seen the member `pred` on `subj`""" subj, pred = subj_and_pred log.info("Validating duplication of member %s" % pred) if (subj, pred) in self.checked_attributes: err = self.err("{0} - dupli...
helper, returns a list of all superclasses of a given class
def _superclasses_for_subject(self, graph, typeof): """helper, returns a list of all superclasses of a given class""" # TODO - this might be replacing a fairly simple graph API query where # it doesn't need to classes = [] superclass = typeof while True: found...
helper, returns the class type of subj
def _is_instance(self, triple): """helper, returns the class type of subj""" subj, pred, obj = triple input_pred_ns = self._namespace_from_uri(self._expand_qname(pred)) triples = self.graph.triples( (subj, rt.URIRef(self.schema_def.lexicon['type']), None) ) if...
helper, returns the name of an attribute (without namespace prefix)
def _field_name_from_uri(self, uri): """helper, returns the name of an attribute (without namespace prefix) """ # TODO - should use graph API uri = str(uri) parts = uri.split('#') if len(parts) == 1: return uri.split('/')[-1] or uri return parts[-1]
returns the expanded namespace prefix of a uri
def _namespace_from_uri(self, uri): """returns the expanded namespace prefix of a uri""" # TODO - this could be helped a bunch with proper use of the graph API # it seems a bit fragile to treat these as simple string-splits uri = str(uri) parts = uri.split('#') if len(par...
expand a qualified name's namespace prefix to include the resolved namespace root url
def _expand_qname(self, qname): """expand a qualified name's namespace prefix to include the resolved namespace root url""" if type(qname) is not rt.URIRef: raise TypeError("Cannot expand qname of type {}, must be URIRef" .format(type(qname))) for ...
Downloads ports data from IANA & Wikipedia and converts it to a python module. This function is used to generate _ranges.py.
def _write_unassigned_ranges(out_filename): """ Downloads ports data from IANA & Wikipedia and converts it to a python module. This function is used to generate _ranges.py. """ with open(out_filename, 'wt') as f: f.write('# auto-generated by port_for._download_ranges (%s)\n' % datetime.date....
Returns a set of all unassigned ports (according to IANA and Wikipedia)
def _unassigned_ports(): """ Returns a set of all unassigned ports (according to IANA and Wikipedia) """ free_ports = ranges_to_set(_parse_ranges(_iana_unassigned_port_ranges())) known_ports = ranges_to_set(_wikipedia_known_port_ranges()) return free_ports.difference(known_ports)
Returns used port ranges according to Wikipedia page. This page contains unofficial well-known ports.
def _wikipedia_known_port_ranges(): """ Returns used port ranges according to Wikipedia page. This page contains unofficial well-known ports. """ req = urllib2.Request(WIKIPEDIA_PAGE, headers={'User-Agent' : "Magic Browser"}) page = urllib2.urlopen(req).read().decode('utf8') # just find all...
Returns unassigned port ranges according to IANA.
def _iana_unassigned_port_ranges(): """ Returns unassigned port ranges according to IANA. """ page = urllib2.urlopen(IANA_DOWNLOAD_URL).read() xml = ElementTree.fromstring(page) records = xml.findall('{%s}record' % IANA_NS) for record in records: description = record.find('{%s}descri...
Converts a list of string ranges to a list of [low, high] tuples.
def _parse_ranges(ranges): """ Converts a list of string ranges to a list of [low, high] tuples. """ for txt in ranges: if '-' in txt: low, high = txt.split('-') else: low, high = txt, txt yield int(low), int(high)
Run through file list, and try to find a linter that matches the given file type. If it finds a linter, it will run it, and store the resulting data in a dictionary (keyed to file_type). :param files: :return: {file_extension: lint_data}
def run_linters(files): """ Run through file list, and try to find a linter that matches the given file type. If it finds a linter, it will run it, and store the resulting data in a dictionary (keyed to file_type). :param files: :return: {file_extension: lint_data} """ data = {} ...
Run through all matching validators. :param new_data: New lint data. :param old_data: Old lint data (before review) :return:
def run_validators(new_data, old_data): """ Run through all matching validators. :param new_data: New lint data. :param old_data: Old lint data (before review) :return: """ #{'validator_name': (success, score, message)} validation_data = {} for file_type, lint_data in list(new_data....
Since we need to use this sometimes
def original_unescape(self, s): """Since we need to use this sometimes""" if isinstance(s, basestring): return unicode(HTMLParser.unescape(self, s)) elif isinstance(s, list): return [unicode(HTMLParser.unescape(self, item)) for item in s] else: return ...
get list of allowed parameters
def get_standard(self): """get list of allowed parameters""" try: res = urlopen(PARSELY_PAGE_SCHEMA) except: return [] text = res.read() if isinstance(text, bytes): text = text.decode('utf-8') tree = etree.parse(StringIO(text)) ...
extract the parsely-page meta content from a page
def _get_parselypage(self, body): """extract the parsely-page meta content from a page""" parser = ParselyPageParser() ret = None try: parser.feed(body) except HTMLParseError: pass # ignore and hope we got ppage if parser.ppage is None: ...
return the local filename of the definition file for this schema if not present or older than expiry, pull the latest version from the web at self._ontology_file
def _read_schema(self): """return the local filename of the definition file for this schema if not present or older than expiry, pull the latest version from the web at self._ontology_file""" cache_filename = os.path.join( CACHE_ROOT, "%s.smt" % self._representation) ...
download an ontology definition from the web
def _pull_schema_definition(self, fname): """download an ontology definition from the web""" std_url = urlopen(self._ontology_file) cached_std = open(fname, "w+") cached_std.write(std_url.read()) cached_std.close()
place the ontology graph into a set of custom data structures for use by the validator
def parse_ontology(self): """place the ontology graph into a set of custom data structures for use by the validator""" start = time.clock() log.info("Parsing ontology file for %s" % self.__class__.__name__) for subj, pred, obj in self._schema_nodes(): if subj not in s...
parse self._ontology_file into a graph
def _schema_nodes(self): """parse self._ontology_file into a graph""" name, ext = os.path.splitext(self._ontology_file) if ext in ['.ttl']: self._ontology_parser_function = \ lambda s: rdflib.Graph().parse(s, format='n3') else: self._ontology_parse...
Take a given filename and return the normalized version of it. Where ~/ is expanded to the full OS specific home directory and all relative path elements are resolved.
def normalizeFilename(filename): """Take a given filename and return the normalized version of it. Where ~/ is expanded to the full OS specific home directory and all relative path elements are resolved. """ result = os.path.expanduser(filename) result = os.path.abspath(result) return result
Return only the network location portion of the given domain unless includeScheme is True
def baseDomain(domain, includeScheme=True): """Return only the network location portion of the given domain unless includeScheme is True """ result = '' url = urlparse(domain) if includeScheme: result = '%s://' % url.scheme if len(url.netloc) == 0: result += url.path e...
Naive search of the database for `query`. :return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list of the respective ORM type.
def search(session, query): """Naive search of the database for `query`. :return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list of the respective ORM type. """ flat_query = "".join(query.split()) artists = session.query(Artist).filter( or_(Arti...
Classic filter generator core. Alternative to the :py:class:`FilterGenerator` component that can be used to make a non-reconfigurable resizer:: resize = Resize(xup=2) resize.filter(FilterGeneratorCore(xup=2, xaperture=16)) ... start(..., resize, ...) ... :keyword i...
def FilterGeneratorCore(x_up=1, x_down=1, x_ap=1, x_cut=100, y_up=1, y_down=1, y_ap=1, y_cut=100): """Classic filter generator core. Alternative to the :py:class:`FilterGenerator` component that can be used to make a non-reconfigurable resizer:: resize = Resize(xup=2) ...
Use check_output to run pylint. Because pylint changes the exit code based on the code score, we have to wrap it in a try/except block. :param options: :return:
def pylint_raw(options): """ Use check_output to run pylint. Because pylint changes the exit code based on the code score, we have to wrap it in a try/except block. :param options: :return: """ command = ['pylint'] command.extend(options) proc = subprocess.Popen(command, stdout...
Runs pylint on the list of files and return a dictionary: {<filename>: [list of pylint errors], 'total': <int> - Total number of pylint messages, 'errors': <int> - Number of pylint errors, 'scores': (<filename>, score) - Individual score for each file.} :param file_list: ...
def run(self, file_list): """ Runs pylint on the list of files and return a dictionary: {<filename>: [list of pylint errors], 'total': <int> - Total number of pylint messages, 'errors': <int> - Number of pylint errors, 'scores': (<filename>, score) - Individual sco...
Print a message and prompt user for input. Return user input.
def prompt(message, default=None, strip=True, suffix=' '): """ Print a message and prompt user for input. Return user input. """ if default is not None: prompt_text = "{0} [{1}]{2}".format(message, default, suffix) else: prompt_text = "{0}{1}".format(message, suffix) input_value = get_i...
Prompt user to answer yes or no. Return True if the default is chosen, otherwise False.
def yesno(message, default='yes', suffix=' '): """ Prompt user to answer yes or no. Return True if the default is chosen, otherwise False. """ if default == 'yes': yesno_prompt = '[Y/n]' elif default == 'no': yesno_prompt = '[y/N]' else: raise ValueError("default must be 'ye...
Register a Validator class for file verification. :param validator: :return:
def register_validator(validator): """ Register a Validator class for file verification. :param validator: :return: """ if hasattr(validator, "EXTS") and hasattr(validator, "run"): ValidatorFactory.PLUGINS.append(validator) else: raise Val...
Generator process to write file
def file_writer(self, in_frame): """Generator process to write file""" self.update_config() path = self.config['path'] encoder = self.config['encoder'] fps = self.config['fps'] bit16 = self.config['16bit'] numpy_image = in_frame.as_numpy() ylen, xlen, bpc ...
HHI pre-interlace filter. A widely used prefilter to prevent line twitter when converting sequential images to interlace. Coefficients taken from: 'Specification of a Generic Format Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison, CEC RACE/HAMLET Deliverable no R2110/WP2/DS/S/006/...
def HHIPreFilter(config={}): """HHI pre-interlace filter. A widely used prefilter to prevent line twitter when converting sequential images to interlace. Coefficients taken from: 'Specification of a Generic Format Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison, CEC RACE/HAMLE...
Returns a list of ephemeral port ranges for current machine.
def port_ranges(): """ Returns a list of ephemeral port ranges for current machine. """ try: return _linux_ranges() except (OSError, IOError): # not linux, try BSD try: ranges = _bsd_ranges() if ranges: return ranges except (OSError, IO...
The actual event loop. Calls the ``owner``'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 :py:meth:`~Component.stop` is called. Finally the ``owner``'s :py:meth...
def run(self): """The actual event loop. Calls the ``owner``'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 :py:meth:`~Component.stop` is called. Finally the ``...
Send an output frame. The frame is sent to each input the output is connected to. If there are no connections this is a null operation with little overhead. :param str output_name: the output to use. Must be a member of :py:attr:`~Component.outputs`. :param Frame f...
def send(self, output_name, frame): """Send an output frame. The frame is sent to each input the output is connected to. If there are no connections this is a null operation with little overhead. :param str output_name: the output to use. Must be a member of :py:att...
Connect an output to any callable object. :py:meth:`on_connect` is called after the connection is made to allow components to do something when an output is conected. :param str output_name: the output to connect. Must be a member of :py:attr:`~Component.outputs`. :param c...
def connect(self, output_name, input_method): """Connect an output to any callable object. :py:meth:`on_connect` is called after the connection is made to allow components to do something when an output is conected. :param str output_name: the output to connect. Must be a member ...
Called by the event loop when it is started. Creates the output frame pools (if used) then calls :py:meth:`on_start`. Creating the output frame pools now allows their size to be configured before starting the component.
def start_event(self): """Called by the event loop when it is started. Creates the output frame pools (if used) then calls :py:meth:`on_start`. Creating the output frame pools now allows their size to be configured before starting the component. """ # create object pool...
Called by the event loop when it is stopped. Calls :py:meth:`on_stop`, then sends :py:data:`None` to each output to shut down the rest of the processing pipeline.
def stop_event(self): """Called by the event loop when it is stopped. Calls :py:meth:`on_stop`, then sends :py:data:`None` to each output to shut down the rest of the processing pipeline. """ self.logger.debug('stopping') try: self.on_stop() except E...
Is component the last one in a pipeline. When waiting for a network of components to finish processing it's not necessary to wait for every component to stop, and in many cases they won't all stop anyway. This method makes it easier to choose which components to wait for. See t...
def is_pipe_end(self): """Is component the last one in a pipeline. When waiting for a network of components to finish processing it's not necessary to wait for every component to stop, and in many cases they won't all stop anyway. This method makes it easier to choose which com...
Called by the event loop when new config is available.
def new_config_event(self): """Called by the event loop when new config is available. """ try: self.on_set_config() except Exception as ex: self.logger.exception(ex) raise StopIteration()
Called by the event loop when a new input or output frame is available. Inputs are correlated by comparing their frame numbers. If there is a complete set of inputs, and all output frame pools are ready, the :py:meth:`process_frame` method is called. If an input frame has a neg...
def new_frame_event(self): """Called by the event loop when a new input or output frame is available. Inputs are correlated by comparing their frame numbers. If there is a complete set of inputs, and all output frame pools are ready, the :py:meth:`process_frame` method is called...