Search is not available for this dataset
text
stringlengths
75
104k
def owsproxy_delegate(request): """ Delegates owsproxy request to external twitcher service. """ twitcher_url = request.registry.settings.get('twitcher.url') protected_path = request.registry.settings.get('twitcher.ows_proxy_protected_path', '/ows') url = twitcher_url + protected_path + '/proxy'...
def ows_security_tween_factory(handler, registry): """A tween factory which produces a tween which raises an exception if access to OWS service is not allowed.""" security = owssecurity_factory(registry) def ows_security_tween(request): try: security.check_request(request) ...
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ from pyramid.config import Configurator config = Configurator(settings=settings) # include twitcher components config.include('twitcher.config') config.include('twitcher.frontpage') confi...
def generate_token(self, valid_in_hours=1, data=None): """ Implementation of :meth:`twitcher.api.ITokenManager.generate_token`. """ data = data or {} access_token = self.tokengenerator.create_access_token( valid_in_hours=valid_in_hours, data=data, ...
def revoke_token(self, token): """ Implementation of :meth:`twitcher.api.ITokenManager.revoke_token`. """ try: self.store.delete_token(token) except Exception: LOGGER.exception('Failed to remove token.') return False else: r...
def revoke_all_tokens(self): """ Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`. """ try: self.store.clear_tokens() except Exception: LOGGER.exception('Failed to remove tokens.') return False else: re...
def register_service(self, url, data=None, overwrite=True): """ Implementation of :meth:`twitcher.api.IRegistry.register_service`. """ data = data or {} args = dict(data) args['url'] = url service = Service(**args) service = self.store.save_service(servic...
def unregister_service(self, name): """ Implementation of :meth:`twitcher.api.IRegistry.unregister_service`. """ try: self.store.delete_service(name=name) except Exception: LOGGER.exception('unregister failed') return False else: ...
def get_service_by_name(self, name): """ Implementation of :meth:`twitcher.api.IRegistry.get_service_by_name`. """ try: service = self.store.fetch_by_name(name=name) except Exception: LOGGER.error('Could not get service with name %s', name) ret...
def get_service_by_url(self, url): """ Implementation of :meth:`twitcher.api.IRegistry.get_service_by_url`. """ try: service = self.store.fetch_by_url(url=url) except Exception: LOGGER.error('Could not get service with url %s', url) return {} ...
def list_services(self): """ Implementation of :meth:`twitcher.api.IRegistry.list_services`. """ try: services = [service.params for service in self.store.list_services()] except Exception: LOGGER.error('List services failed.') return [] ...
def clear_services(self): """ Implementation of :meth:`twitcher.api.IRegistry.clear_services`. """ try: self.store.clear_services() except Exception: LOGGER.error('Clear services failed.') return False else: return True
def includeme(config): """ The callable makes it possible to include rpcinterface in a Pyramid application. Calling ``config.include(twitcher.rpcinterface)`` will result in this callable being called. Arguments: * ``config``: the ``pyramid.config.Configurator`` object. """ settings = ...
def save_service(self, service, overwrite=True): """ Store an OWS service in database. """ name = namesgenerator.get_sane_name(service.name) if not name: name = namesgenerator.get_random_name() if name in self.name_index: name = namesgenera...
def list_services(self): """ Lists all services in memory storage. """ my_services = [] for service in self.name_index.values(): my_services.append(Service(service)) return my_services
def fetch_by_name(self, name): """ Get service for given ``name`` from memory storage. """ service = self.name_index.get(name) if not service: raise ServiceNotFound return Service(service)
def _retrieve_certificate(self, access_token, timeout=3): """ Generates a new private key and certificate request, submits the request to be signed by the SLCS CA and returns the certificate. """ logger.debug("Retrieve certificate with token.") # Generate a new key pair ...
def tokenstore_factory(registry, database=None): """ Creates a token store with the interface of :class:`twitcher.store.AccessTokenStore`. By default the mongodb implementation will be used. :param database: A string with the store implementation name: "mongodb" or "memory". :return: An instance of...
def servicestore_factory(registry, database=None): """ Creates a service store with the interface of :class:`twitcher.store.ServiceStore`. By default the mongodb implementation will be used. :return: An instance of :class:`twitcher.store.ServiceStore`. """ database = database or 'mongodb' i...
def get_random_name(retry=False): """ generates a random name from the list of adjectives and birds in this package formatted as "adjective_surname". For example 'loving_sugarbird'. If retry is non-zero, a random integer between 0 and 100 will be added to the end of the name, e.g `loving_sugarbird3` ...
def _get_param(self, param, allowed_values=None, optional=False): """Get parameter in GET request.""" request_params = self._request_params() if param in request_params: value = request_params[param].lower() if allowed_values is not None: if value in allow...
def _get_version(self): """Find requested version in GET request.""" version = self._get_param(param="version", allowed_values=allowed_versions[self.params['service']], optional=True) if version is None and self._get_request_type() != "getcapabilities": ...
def _get_service(self): """Check mandatory service name parameter in POST request.""" if "service" in self.document.attrib: value = self.document.attrib["service"].lower() if value in allowed_service_types: self.params["service"] = value else: ...
def _get_request_type(self): """Find requested request type in POST request.""" value = self.document.tag.lower() if value in allowed_request_types[self.params['service']]: self.params["request"] = value else: raise OWSInvalidParameterValue("Request type %s is not...
def _get_version(self): """Find requested version in POST request.""" if "version" in self.document.attrib: value = self.document.attrib["version"].lower() if value in allowed_versions[self.params['service']]: self.params["version"] = value else: ...
def localize_datetime(dt, tz_name='UTC'): """Provide a timzeone-aware object for a given datetime and timezone name """ tz_aware_dt = dt if dt.tzinfo is None: utc = pytz.timezone('UTC') aware = utc.localize(dt) timezone = pytz.timezone(tz_name) tz_aware_dt = aware.astimez...
def baseurl(url): """ return baseurl of given url """ parsed_url = urlparse.urlparse(url) if not parsed_url.netloc or parsed_url.scheme not in ("http", "https"): raise ValueError('bad url') service_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip()) re...
def verify(self): """Verify ssl service certificate.""" value = self.get('verify', 'true') if isinstance(value, bool): verify = value elif value.lower() == 'true': verify = True elif value.lower() == 'false': verify = False else: ...
def tag(self, label, message=None): """Tag the current workdir state.""" notify.warning('Unsupported SCM: Make sure you apply the "{}" tag after commit!{}'.format( label, ' [message={}]'.format(message) if message else '', ))
def pep440_dev_version(self, verbose=False, non_local=False): """Return a PEP-440 dev version appendix to the main version number.""" # Always return a timestamp pep440 = '.dev{:%Y%m%d%H%M}'.format(datetime.now()) if not non_local: build_number = os.environ.get('BUILD_NUMBER...
def get_egg_info(cfg, verbose=False): """Call 'setup egg_info' and return the parsed meta-data.""" result = Bunch() setup_py = cfg.rootjoin('setup.py') if not os.path.exists(setup_py): return result egg_info = shell.capture("python {} egg_info".format(setup_py), echo=True if verbose else No...
def bump(ctx, verbose=False, pypi=False): """Bump a development version.""" cfg = config.load() scm = scm_provider(cfg.project_root, commit=False, ctx=ctx) # Check for uncommitted changes if not scm.workdir_is_clean(): notify.warning("You have uncommitted changes, will create a time-stamped...
def dist(ctx, devpi=False, egg=False, wheel=False, auto=True): """Distribute the project.""" config.load() cmd = ["python", "setup.py", "sdist"] # Automatically create wheels if possible if auto: egg = sys.version_info.major == 2 try: import wheel as _ wheel ...
def pex(ctx, pyrun='', upload=False, opts=''): """Package the project with PEX.""" cfg = config.load() # Build and check release ctx.run(": invoke clean --all build test check") # Get full version pkg_info = get_egg_info(cfg) # from pprint import pprint; pprint(dict(pkg_info)) version ...
def prep(ctx, commit=True): """Prepare for a release.""" cfg = config.load() scm = scm_provider(cfg.project_root, commit=commit, ctx=ctx) # Check for uncommitted changes if not scm.workdir_is_clean(): notify.failure("You have uncommitted changes, please commit or stash them!") # TODO C...
def pylint(ctx, skip_tests=False, skip_root=False, reports=False): """Perform source code checks via pylint.""" cfg = config.load() add_dir2pypath(cfg.project_root) if not os.path.exists(cfg.testjoin('__init__.py')): add_dir2pypath(cfg.testjoin()) namelist = set() for package in cfg.pro...
def workdir_is_clean(self, quiet=False): """ Check for uncommitted changes, return `True` if everything is clean. Inspired by http://stackoverflow.com/questions/3878624/. """ # Update the index self.run('git update-index -q --ignore-submodules --refresh', **RUN_KWARGS) ...
def tag(self, label, message=None): """Tag the current workdir state.""" options = ' -m "{}" -a'.format(message) if message else '' self.run_elective('git tag{} "{}"'.format(options, label))
def pep440_dev_version(self, verbose=False, non_local=False): """ Return a PEP-440 dev version appendix to the main version number. Result is ``None`` if the workdir is in a release-ready state (i.e. clean and properly tagged). """ version = capture("python setup.py --ve...
def description(_dummy_ctx, markdown=False): """Dump project metadata for Jenkins Description Setter Plugin.""" cfg = config.load() markup = 'md' if markdown else 'html' description_file = cfg.rootjoin("build/project.{}".format(markup)) notify.banner("Creating {} file for Jenkins...".format(descript...
def capture(cmd, **kw): """Run a command and return its stripped captured output.""" kw = kw.copy() kw['hide'] = 'out' if not kw.get('echo', False): kw['echo'] = False ignore_failures = kw.pop('ignore_failures', False) try: return invoke_run(cmd, **kw).stdout.strip() except e...
def run(cmd, **kw): """Run a command and flush its output.""" kw = kw.copy() kw.setdefault('warn', False) # make extra sure errors don't get silenced report_error = kw.pop('report_error', True) runner = kw.pop('runner', invoke_run) try: return runner(cmd, **kw) except exceptions.F...
def auto_detect(workdir): """ Return string signifying the SCM used in the given directory. Currently, 'git' is supported. Anything else returns 'unknown'. """ # Any additions here also need a change to `SCM_PROVIDERS`! if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path....
def provider(workdir, commit=True, **kwargs): """Factory for the correct SCM provider in `workdir`.""" return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)
def fail(message, exitcode=1): """Exit with error code and message.""" sys.stderr.write('ERROR: {}\n'.format(message)) sys.stderr.flush() sys.exit(exitcode)
def get_pypi_auth(configfile='~/.pypirc'): """Read auth from pip config.""" pypi_cfg = ConfigParser() if pypi_cfg.read(os.path.expanduser(configfile)): try: user = pypi_cfg.get('pypi', 'username') pwd = pypi_cfg.get('pypi', 'password') return user, pwd exc...
def watchdogctl(ctx, kill=False, verbose=True): """Control / check a running Sphinx autobuild process.""" tries = 40 if kill else 0 cmd = 'lsof -i TCP:{} -s TCP:LISTEN -S -Fp 2>/dev/null'.format(ctx.rituals.docs.watchdog.port) pidno = 0 pidinfo = capture(cmd, ignore_failures=True) while pidinfo...
def sphinx(ctx, browse=False, clean=False, watchdog=False, kill=False, status=False, opts=''): """Build Sphinx docs.""" cfg = config.load() if kill or status: if not watchdogctl(ctx, kill=kill): notify.info("No process bound to port {}".format(ctx.rituals.docs.watchdog.port)) re...
def confluence(ctx, no_publish=False, clean=False, opts=''): """Build Sphinx docs and publish to Confluence.""" cfg = config.load() if clean: ctx.run("invoke clean --docs") cmd = ['sphinx-build', '-b', 'confluence'] cmd.extend(['-E', '-a']) # force a full rebuild if opts: cmd....
def upload(ctx, browse=False, target=None, release='latest'): """Upload a ZIP of built docs (by default to PyPI, else a WebDAV URL).""" cfg = config.load() uploader = DocsUploader(ctx, cfg, target) html_dir = os.path.join(ctx.rituals.docs.sources, ctx.rituals.docs.build) if not os.path.isdir(html_d...
def _zipped(self, docs_base): """ Provide a zipped stream of the docs tree.""" with pushd(docs_base): with tempfile.NamedTemporaryFile(prefix='pythonhosted-', delete=False) as ziphandle: pass zip_name = shutil.make_archive(ziphandle.name, 'zip') notify.in...
def _to_pypi(self, docs_base, release): """Upload to PyPI.""" url = None with self._zipped(docs_base) as handle: reply = requests.post(self.params['url'], auth=get_pypi_auth(), allow_redirects=False, files=dict(content=(self.cfg.project.name + '.zip'...
def _to_webdav(self, docs_base, release): """Upload to WebDAV store.""" try: git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True) except subprocess.CalledProcessError: git_path = '' else: git_path = git_path.decode('a...
def upload(self, docs_base, release): """Upload docs in ``docs_base`` to the target of this uploader.""" return getattr(self, '_to_' + self.target)(docs_base, release)
def search_file_upwards(name, base=None): """ Search for a file named `name` from cwd or given directory to root. Return None if nothing's found. """ base = base or os.getcwd() while base != os.path.dirname(base): if os.path.exists(os.path.join(base, name)): return base ...
def add_dir2pypath(path): """Add given directory to PYTHONPATH, e.g. for pylint.""" py_path = os.environ.get('PYTHONPATH', '') if path not in py_path.split(os.pathsep): py_path = ''.join([path, os.pathsep if py_path else '', py_path]) os.environ['PYTHONPATH'] = py_path
def pushd(path): """ A context that enters a given directory and restores the old state on exit. The original directory is returned as the context variable. """ saved = os.getcwd() os.chdir(path) try: yield saved finally: os.chdir(saved)
def url_as_file(url, ext=None): """ Context manager that GETs a given `url` and provides it as a local file. The file is in a closed state upon entering the context, and removed when leaving it, if still there. To give the file name a specific extension, use `ext`; the exte...
def run(self, cmd, *args, **kwargs): """Run a command.""" runner = self.ctx.run if self.ctx else None return run(cmd, runner=runner, *args, **kwargs)
def run_elective(self, cmd, *args, **kwargs): """Run a command, or just echo it, depending on `commit`.""" if self._commit: return self.run(cmd, *args, **kwargs) else: notify.warning("WOULD RUN: {}".format(cmd)) kwargs = kwargs.copy() kwargs['echo'...
def banner(msg): """Emit a banner just like Invoke's `run(…, echo=True)`.""" if ECHO: _flush() sys.stderr.write("\033[1;7;32;40m{}\033[0m\n".format(msg)) sys.stderr.flush()
def info(msg): """Emit a normal message.""" _flush() sys.stdout.write(msg + '\n') sys.stdout.flush()
def warning(msg): """Emit a warning message.""" _flush() sys.stderr.write("\033[1;7;33;40mWARNING: {}\033[0m\n".format(msg)) sys.stderr.flush()
def error(msg): """Emit an error message to stderr.""" _flush() sys.stderr.write("\033[1;37;41mERROR: {}\033[0m\n".format(msg)) sys.stderr.flush()
def get_devpi_url(ctx): """Get currently used 'devpi' base URL.""" cmd = 'devpi use --urls' lines = ctx.run(cmd, hide='out', echo=False).stdout.splitlines() for line in lines: try: line, base_url = line.split(':', 1) except ValueError: notify.warning('Ignoring "{}...
def get_project_root(): """ Determine location of `tasks.py`.""" try: tasks_py = sys.modules['tasks'] except KeyError: return None else: return os.path.abspath(os.path.dirname(tasks_py.__file__))
def load(): """ Load and return configuration as a ``Bunch``. Values are based on ``DEFAULTS``, and metadata from ``setup.py``. """ cfg = Bunch(DEFAULTS) # TODO: override with contents of [rituals] section in setup.cfg cfg.project_root = get_project_root() if not cfg.project_root: ...
def glob2re(part): """Convert a path part to regex syntax.""" return "[^/]*".join( re.escape(bit).replace(r'\[\^', '[^').replace(r'\[', '[').replace(r'\]', ']') for bit in part.split("*") )
def parse_glob(pattern): """Generate parts of regex transformed from glob pattern.""" if not pattern: return bits = pattern.split("/") dirs, filename = bits[:-1], bits[-1] for dirname in dirs: if dirname == "**": yield "(|.+/)" else: yield glob2re(d...
def compile_glob(spec): """Convert the given glob `spec` to a compiled regex.""" parsed = "".join(parse_glob(spec)) regex = "^{0}$".format(parsed) return re.compile(regex)
def included(self, path, is_dir=False): """Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.""" inclusive = None for pattern in self.patterns: if pattern.is_dir == is_dir and pattern.matches(path): inclusive = patte...
def walk(self, **kwargs): """ Like `os.walk` and taking the same keyword arguments, but generating paths relative to the root. Starts in the fileset's root and filters based on its patterns. If ``with_root=True`` is passed in, the generated paths include the root...
def build(ctx, dput='', opts=''): """Build a DEB package.""" # Get package metadata with io.open('debian/changelog', encoding='utf-8') as changes: metadata = re.match(r'^([^ ]+) \(([^)]+)\) ([^;]+); urgency=(.+)$', changes.readline().rstrip()) if not metadata: notify.failure('Bad...
def clean(_dummy_ctx, docs=False, backups=False, bytecode=False, dist=False, # pylint: disable=redefined-outer-name all=False, venv=False, tox=False, extra=''): # pylint: disable=redefined-builtin """Perform house-keeping.""" cfg = config.load() notify.banner("Cleaning up project files") # Add ...
def build(ctx, docs=False): """Build the project.""" cfg = config.load() ctx.run("python setup.py build") if docs: for doc_path in ('docs', 'doc'): if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')): break else: doc_path = None if doc_p...
def freeze(ctx, local=False): """Freeze currently installed requirements.""" cmd = 'pip --disable-pip-version-check freeze{}'.format(' --local' if local else '') frozen = ctx.run(cmd, hide='out').stdout.replace('\x1b', '#') with io.open('frozen-requirements.txt', 'w', encoding='ascii') as out: o...
def isodate(datestamp=None, microseconds=False): """Return current or given time formatted according to ISO-8601.""" datestamp = datestamp or datetime.datetime.now() if not microseconds: usecs = datetime.timedelta(microseconds=datestamp.microsecond) datestamp = datestamp - usecs return d...
def _get_registered_executable(exe_name): """Windows allow application paths to be registered in the registry.""" registered = None if sys.platform.startswith('win'): if os.path.splitext(exe_name)[1].lower() != '.exe': exe_name += '.exe' import _winreg # pylint: disable=import-er...
def _cull(potential, matches, verbose=0): """Cull inappropriate matches. Possible reasons: - a duplicate of a previous match - not a disk file - not executable (non-Windows) If 'potential' is approved it is returned and added to 'matches'. Otherwise, None is returned. """ for...
def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements """Return a generator of full paths to the given command. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to ...
def which(command, path=None, verbose=0, exts=None): """Return the full path to the first match of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. ...
def step(self, key, chain): """ Perform a rachted step, replacing one of the internally managed chains with a new one. :param key: A bytes-like object encoding the key to initialize the replacement chain with. :param chain: The chain to replace. This parameter must b...
def decryptMessage(self, ciphertext, header, ad = None): """ Decrypt a message using this double ratchet session. :param ciphertext: A bytes-like object encoding the message to decrypt. :param header: An instance of the Header class. This should have been sent together with ...
def encryptMessage(self, message, ad = None): """ Encrypt a message using this double ratchet session. :param message: A bytes-like object encoding the message to encrypt. :param ad: A bytes-like object encoding the associated data to use for message authentication. Pass Non...
def step(self, other_pub): """ Perform a rachted step, calculating a new shared secret from the public key and deriving new chain keys from this secret. New Diffie-Hellman calculations are only performed if the public key is different from the previous one. :param other...
def next(self, data): """ Derive a new set of internal and output data from given input data and the data stored internally. Use the key derivation function to derive new data. The kdf gets supplied with the current key and the data passed to this method. :param data: A...
def load_and_dump(create_loader, create_dumper, load_and_dump_): """:return: a function that has the doc string of :paramref:`load_and_dump_` additional arguments to this function are passed on to :paramref:`load_and_dump_`. :param create_loader: a loader, e.g. :class:`knittingpattern.L...
def convert_image_to_knitting_pattern(path, colors=("white", "black")): """Load a image file such as a png bitmap of jpeg file and convert it to a :ref:`knitting pattern file <FileFormatSpecification>`. :param list colors: a list of strings that should be used as :ref:`colors <png-color>`. :param...
def connect_to(self, other_mesh): """Create a connection to an other mesh. .. warning:: Both meshes need to be disconnected and one needs to be a consumed and the other a produced mesh. You can check if a connection is possible using :meth:`can_connect_to`. .. seealso:: :me...
def can_connect_to(self, other): """Whether a connection can be established between those two meshes.""" assert other.is_mesh() disconnected = not other.is_connected() and not self.is_connected() types_differ = self._is_consumed_mesh() != other._is_consumed_mesh() return disconne...
def new_knitting_pattern_set_loader(specification=DefaultSpecification()): """Create a loader for a knitting pattern set. :param specification: a :class:`specification <knittingpattern.ParsingSpecification.ParsingSpecification>` for the knitting pattern set, default :class:`DefaultSpecificati...
def walk(knitting_pattern): """Walk the knitting pattern in a right-to-left fashion. :return: an iterable to walk the rows :rtype: list :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a knitting pattern to take the rows from """ rows_before = {} # key consumes fr...
def knitting_pattern(self, specification=None): """loads a :class:`knitting pattern <knittingpattern.KnittingPattern.KnittingPattern>` from the dumped content :param specification: a :class:`~knittingpattern.ParsingSpecification.ParsingSpecification` or :obj:`None` t...
def string(self): """:return: the dump as a string""" if self.__text_is_expected: return self._string() else: return self._bytes().decode(self.__encoding)
def _string(self): """:return: the string from a :class:`io.StringIO`""" file = StringIO() self.__dump_to_file(file) file.seek(0) return file.read()
def bytes(self): """:return: the dump as bytes.""" if self.__text_is_expected: return self.string().encode(self.__encoding) else: return self._bytes()
def _bytes(self): """:return: bytes from a :class:`io.BytesIO`""" file = BytesIO() self.__dump_to_file(file) file.seek(0) return file.read()
def file(self, file=None): """Saves the dump in a file-like object in text mode. :param file: :obj:`None` or a file-like object. :return: a file-like object If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO` is returned. If :paramref:`file` is not :obj:`None...
def _file(self, file): """Dump the content to a `file`. """ if not self.__text_is_expected: file = BytesWrapper(file, self.__encoding) self.__dump_to_file(file)
def binary_file(self, file=None): """Same as :meth:`file` but for binary content.""" if file is None: file = BytesIO() self._binary_file(file) return file