Example #1
0
def document_member(enum_member: Enum) -> None:
	"""
	Document a member of an enum by adding a comment to the end of the line that starts with ``doc:``.

	:param enum_member: A member of an ``Enum`` subclass
	"""

	if not isinstance(enum_member, Enum):
		raise TypeError(f"'an_enum' must be an 'Enum', not {type(enum_member)}!")

	if not INTERACTIVE:
		return None

	func_source = dedent(inspect.getsource(enum_member.__class__))

	in_docstring = False
	base_indent = None

	for line in func_source.split('\n'):

		indent, line = get_dedented_line(line)

		if line.startswith("class") or not line:
			continue

		all_tokens = get_tokens(line)
		base_indent = get_base_indent(base_indent, all_tokens, indent)
		# print(all_tokens)

		if enum_member.name not in line:
			continue

		if all_tokens[0][0] in pygments.token.Literal.String:
			if all_tokens[0][1] in {'"""', "'''"}:  # TODO: handle the other quotes appearing in docstring
				in_docstring = not in_docstring

		if all_tokens[0][0] in pygments.token.Name and in_docstring:
			continue
		elif all_tokens[0][0] not in pygments.token.Name:
			continue
		else:
			if indent > base_indent:  # type: ignore
				continue
		enum_vars, doc = parse_tokens(all_tokens)

		for var in enum_vars:
			# print(repr(var))
			if not var.startswith('@'):
				if var == enum_member.name:
					enum_member.__doc__ = doc

	return None
Example #2
0
def __generate_keyboard_layout_enum():
    layout_names = []
    for file_name in resources.contents(current_module):
        if file_name.endswith(YAML_EXTENSION):
            layout_names.append(file_name[:-len(YAML_EXTENSION)])

    layout_name_enum = Enum(
        'LayoutName',
        {layout_name.upper(): layout_name
         for layout_name in layout_names},
        type=str)
    layout_name_enum.__doc__ = ("An enum that holds the allowed layout names")
    return layout_name_enum
Example #3
0
def make_str_enum(name: str, values: List[str], doc: str = "") -> Type[str]:
    """Makes a string enumeration with particuluar values."""

    T = Enum(name, {v: v for v in values}, qualname=name, type=str)

    def __repr__(self: T) -> str:
        cn = type(self).__qualname__
        return f"{cn}({self.value!r})"

    T.__repr__ = __repr__
    T.__doc__ = doc

    return T
Example #4
0
def create_enum(path):
    """Convert a JSON-LD enumeration to an Enum"""
    with open(path) as fp:
        data = yaml.safe_load(fp)
    items = {}
    klass = None
    for idx, item in enumerate(data["@graph"]):
        if item["@type"] == "rdfs:Class":
            klass = item["@id"].replace("dandi:", "")
            klass_doc = item["rdfs:comment"]
        else:
            value = item["@id"].replace("dandi:", "")
            items[f"var{idx:02d}"] = value
    if klass is None or len(items) == 0:
        raise ValueError(f"YAML {path} did not generate a klass or items")
    newklass = Enum(klass, items)
    newklass.__doc__ = klass_doc
    return newklass
Example #5
0
def create_enum(data):
    """Convert a JSON-LD enumeration to an Enum"""
    items = {}
    klass = None
    for idx, item in enumerate(data["@graph"]):
        if item["@type"] == "rdfs:Class":
            klass = item["@id"].replace("dandi:", "")
            klass_doc = item["rdfs:comment"]
        else:
            key = item["@id"]
            if ":" in item["@id"]:
                key = item["@id"].split(":")[-1]
            if key in items:
                key = item["@id"].replace(":", "_")
            items[f"{key}"] = item["@id"]
    if klass is None or len(items) == 0:
        raise ValueError(f"Could not generate a klass or items from {data}")
    newklass = Enum(klass, items)
    newklass.__doc__ = klass_doc
    return newklass
Example #6
0
"""
from enum import Enum

from ansys import dpf
from ansys.grpc.dpf import result_info_pb2, result_info_pb2_grpc
from ansys.dpf.core import available_result
from ansys.dpf.core.mapping_types import map_unit_system
from ansys.dpf.core.cyclic_support import CyclicSupport
from ansys.dpf.core.common import __write_enum_doc__
from ansys.dpf.core.cache import class_handling_cache
from ansys.dpf.core.check_version import server_meet_version, version_requires

names = [m for m in result_info_pb2.PhysicsType.keys()]
physics_types = Enum("physics_types", names)
physics_types.__doc__ = __write_enum_doc__(
    physics_types,
    "``'Physics_types'`` enumerates the different types of physics that an analysis can have.",
)

names = [m for m in result_info_pb2.AnalysisType.keys()]
analysis_types = Enum("analysis_types", names)
analysis_types.__doc__ = __write_enum_doc__(
    physics_types,
    "``'Analysis_types'`` enumerates the different types of analysis.")


@class_handling_cache
class ResultInfo:
    """Represents the result information.

    This class describes the metadata of the analysis and the available results.
Example #7
0

class Uint128Struct(c.Structure):
    _fields_ = [("hi", c.c_uint64), ("lo", c.c_uint64)]


ObjT = Enum(
    'ObjT',
    [
        # These are the only conf object types we care about.
        ('PROCESS', 0x7200000000000001),
        ('SERVICE', 0x7300000000000001),
        ('SDEV', 0x6400000000000001),
        ('DRIVE', 0x6b00000000000001),
    ])
ObjT.__doc__ = 'Motr conf object types and their m0_fid.f_container values'


class HaNoteStruct(c.Structure):
    # Constants for no_state field values as they are described in ha/note.h

    # /** Object state is unknown. */
    M0_NC_UNKNOWN = 0
    # /** Object can be used normally. */
    M0_NC_ONLINE = 1
    # /**
    # * Object has experienced a permanent failure and cannot be
    # * recovered.
    # */
    M0_NC_FAILED = 2
    # /**
Example #8
0
        str = intro + " \n\n"
    str += "    Attributes\n" + "    -----------\n"
    for e in enum:
        str += "    " + e.name + " \n\n"
    return str


names = [m.lower() for m in base_pb2.Type.keys()]
names.append("fields_container")
names.append("scopings_container")
names.append("meshes_container")
types = Enum("types", names)
types.__doc__ = __write_enum_doc__(
    types,
    (
        "The ``'types'`` enum contains the available types passed "
        "through operators and workflows to DPF."
    ),
)

names = [(m.lower(), num) for m, num in base_pb2.Nature.items()]
natures = Enum("natures", names)
natures.__doc__ = __write_enum_doc__(
    natures,
    (
        "The ``'natures'`` enum contains the dimensionality types.\n "
        "It can be used to create a field of a given dimensionality."
    ),
)

names = [(m.lower(), num - 1) for m, num in field_definition_pb2.ShellLayers.items()]
Example #9
0
from enum import Enum
from typing import Any, List

from base import ChromeCommand

# Unique script identifier.
ScriptId = str

# Unique object identifier.
RemoteObjectId = str

UnserializableValue = Enum("UnserializableValue", "Infinity NaN -Infinity -0")
UnserializableValue.__doc__ = "Primitive value which cannot be JSON-stringified."


class RemoteObject:
    """Mirror object referencing original JavaScript object."""
    def __init__(self,
                 type: str,
                 subtype: str = None,
                 className: str = None,
                 value: Any = None,
                 unserializableValue: "UnserializableValue" = None,
                 description: str = None,
                 objectId: "RemoteObjectId" = None,
                 preview: "ObjectPreview" = None,
                 customPreview: "CustomPreview" = None):
        # Object type.
        self.type = type
        # Object subtype hint. Specified for <code>object</code> type values only.
        self.subtype = subtype
Example #10
0
File: eval.py Project: fooyou/tgen
"""
Evaluation (t-tree comparison functions).
"""

from __future__ import unicode_literals
from collections import defaultdict
from enum import Enum
from tgen.logf import log_debug
from tgen.tree import TreeData, TreeNode
import numpy as np
from alex.components.nlg.tectotpl.core.node import T


EvalTypes = Enum(b'EvalTypes', b'NODE DEP')
EvalTypes.__doc__ = """Evaluation flavors (node-only, dependency)"""


def collect_counts(ttree, eval_type=EvalTypes.NODE):
    """Collects counts of different node/dependency types in the given t-tree.

    @param ttree: the tree to collect counts from
    @param eval_type: if set to 'node' (default), count nodes (formemes, lemmas, dependency \
        direction), if set to 'dep', count dependencies (including parent's formeme, lemma, \
        dependency direction).
    @rtype: defaultdict
    """
    counts = defaultdict(int)
    for node in ttree.get_descendants():
        if eval_type == EvalTypes.NODE:
            node_id = (node.formeme, node.t_lemma, node > node.parent)
Example #11
0
from enum import Enum
from typing import Any, List

from base import ChromeCommand


class ScreenOrientation:
    """Screen orientation."""
    def __init__(self, type: str, angle: int):
        # Orientation type.
        self.type = type
        # Orientation angle.
        self.angle = angle

VirtualTimePolicy = Enum("VirtualTimePolicy", "advance pause pauseIfNetworkFetchesPending")
VirtualTimePolicy.__doc__ = "advance: If the scheduler runs out of immediate work, the virtual time base may fast forward to allow the next delayed task (if any) to run; pause: The virtual time base may not advance; pauseIfNetworkFetchesPending: The virtual time base may not advance if there are any pending resource fetches."

class setDeviceMetricsOverride(ChromeCommand):
    """Overrides the values of device screen dimensions (window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media query results)."""

    def __init__(self, width: int, height: int, deviceScaleFactor: float, mobile: bool, fitWindow: bool, scale: float=None, offsetX: float=None, offsetY: float=None, screenWidth: int=None, screenHeight: int=None, positionX: int=None, positionY: int=None, screenOrientation: "ScreenOrientation"=None):
        # Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.
        self.width = width
        # Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override.
        self.height = height
        # Overriding device scale factor value. 0 disables the override.
        self.deviceScaleFactor = deviceScaleFactor
        # Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more.
        self.mobile = mobile
        # Whether a view that exceeds the available browser window area should be scaled down to fit.
        self.fitWindow = fitWindow
Example #12
0
from __future__ import unicode_literals
from collections import defaultdict
from enum import Enum
from tgen.logf import log_debug
from tgen.logf import log_warn
from tgen.tree import TreeData, TreeNode
import numpy as np

try:
    from pytreex.core.node import T
except ImportError:
    log_warn('Pytreex modules not available, will not be able to evaluate trees.')


EvalTypes = Enum(b'EvalTypes', b'TOKEN NODE DEP')
EvalTypes.__doc__ = """Evaluation flavors (tokens, tree node-only, tree dependency)"""


def collect_counts(sent, eval_type=EvalTypes.NODE):
    """Collects counts of different node/dependency types in the given t-tree.

    @param sent: the tree/sentence to collect counts from
    @param eval_type: if set to EvalTypes.NODE (default), count nodes (formemes, lemmas, dependency \
        direction), if set to EvalTypes.DEP, count dependencies (including parent's formeme, lemma, \
        dependency direction), if set to EvalTypes.TOKEN, count just word forms (in list of tokens).
    @rtype: defaultdict
    """
    counts = defaultdict(int)
    nodes = sent if isinstance(sent, list) else sent.get_descendants()
    for node in nodes:
        if eval_type == EvalTypes.TOKEN:
    three = 3
    four = 4


AssertionOperator = Enum(
    "AssertionOperator",
    {
        "equal": "==",
        "==": "==",
        "<": "<",
        ">": ">",
        "<=": "<=",
        ">=": ">="
    },
)
AssertionOperator.__doc__ = """This is some Doc

This has was defined by assigning to __doc__."""


class CustomType:
    """This doc not used because converter method has doc."""
    @classmethod
    def parse(cls, value: Union[str, int]):
        """Converter method doc is used when defined."""
        return value


class CustomType2:
    """Class doc is used when converter method has no doc."""
    def __init__(self, value):
Example #14
0
        # Y coordinate of the event relative to the main frame's viewport. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport.
        self.y = y
        # X radius of the touch area (default: 1).
        self.radiusX = radiusX
        # Y radius of the touch area (default: 1).
        self.radiusY = radiusY
        # Rotation angle (default: 0.0).
        self.rotationAngle = rotationAngle
        # Force (default: 1.0).
        self.force = force
        # Identifier used to track touch sources between events, must be unique within an event.
        self.id = id


GestureSourceType = Enum("GestureSourceType", "default touch mouse")
GestureSourceType.__doc__ = """"""


class dispatchKeyEvent(ChromeCommand):
    """Dispatches a key event to the page."""
    def __init__(self,
                 type: str,
                 modifiers: int = None,
                 timestamp: float = None,
                 text: str = None,
                 unmodifiedText: str = None,
                 keyIdentifier: str = None,
                 code: str = None,
                 key: str = None,
                 windowsVirtualKeyCode: int = None,
                 nativeVirtualKeyCode: int = None,
Example #15
0
from enum import Enum
from typing import Any, List

from base import ChromeCommand

PressureLevel = Enum("PressureLevel", "moderate critical")
PressureLevel.__doc__ = "Memory pressure level."


class getDOMCounters(ChromeCommand):
    def __init__(self):
        pass


class setPressureNotificationsSuppressed(ChromeCommand):
    """Enable/disable suppressing memory pressure notifications in all processes."""
    def __init__(self, suppressed: bool):
        # If true, memory pressure notifications will be suppressed.
        self.suppressed = suppressed


class simulatePressureNotification(ChromeCommand):
    """Simulate a memory pressure notification in all processes."""
    def __init__(self, level: "PressureLevel"):
        # Memory pressure level of the notification.
        self.level = level
Example #16
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Usage: streamparser.py [FILE]

Consumes input from a file (first argument) or stdin, parsing and pretty printing the readings of lexical units found.
"""

import re, pprint, sys, itertools, fileinput
from enum import Enum
from collections import namedtuple


Knownness = Enum('Knownness', 'known unknown biunknown genunknown')
Knownness.__doc__ = """Level of knowledge associated with a lexical unit.
    Values:
        known
        unknown: Denoted by '*', analysis not available.
        biunknown: Denoted by '@', translation not available.
        genunknown: Denoted by '#', generated form not available.
"""


Reading = namedtuple('Reading', ['baseform', 'tags'])
Reading.__doc__ = """A single analysis of a token.
    Fields:
        baseform (str): The base form (lemma, lexical form, citation form) of the reading.
        tags (set of str): The morphological tags associated with the reading.
"""

Example #17
0
	               , 'float': ''
	               , 'double': 'd' }
	__machine_types__ = {'bool': dtype('uint32')
						,'int': dtype('int32')
						,'uint': dtype('uint32')
						,'float': dtype('float32')
						,'double': dtype('float64')}

	def __init__(self, value):
		self.prefix = self.__prefixes__[self.name]
		self.machine_type = self.__machine_types__[self.name]
		self.scalar_type = self
		self.opaque = False
scalar_doc = Scalar.__doc__
Scalar = Enum('Scalar', ((s, s) for s in scalar_types), type=Scalar)
Scalar.__doc__ = scalar_doc

floating_point_scalars = { Scalar.float, Scalar.double }

sampler_dims = range(1, 4)
sampler_data_types = {Scalar.float, Scalar.int, Scalar.uint}
sampler_types = [ "{}sampler{}D".format(scalar_type.prefix, ndim)
                  for scalar_type, ndim in cartesian(sampler_data_types, sampler_dims) ]
class Sampler(str, BasicType, Enum):
	'''The GLSL sampler types.

	Scalars difine the following attributes:

	*opaque*
	  Whether the datatype is an opaque type (:py:obj:`True`)
	'''
Example #18
0
from .base import ChromeCommand

from . import Target


class ServiceWorkerRegistration:
    """ServiceWorker registration."""
    def __init__(self, registrationId: str, scopeURL: str, isDeleted: bool):
        self.registrationId = registrationId
        self.scopeURL = scopeURL
        self.isDeleted = isDeleted


ServiceWorkerVersionRunningStatus = Enum("ServiceWorkerVersionRunningStatus",
                                         "stopped starting running stopping")
ServiceWorkerVersionRunningStatus.__doc__ = """"""

ServiceWorkerVersionStatus = Enum(
    "ServiceWorkerVersionStatus",
    "new installing installed activating activated redundant")
ServiceWorkerVersionStatus.__doc__ = """"""


class ServiceWorkerVersion:
    """ServiceWorker version."""
    def __init__(self,
                 versionId: str,
                 registrationId: str,
                 scriptURL: str,
                 runningStatus: "ServiceWorkerVersionRunningStatus",
                 status: "ServiceWorkerVersionStatus",
Example #19
0
from enum import Enum
from typing import Any, List

from .base import ChromeCommand

# An internal certificate ID value.
CertificateId = int

SecurityState = Enum("SecurityState",
                     "unknown neutral insecure warning secure info")
SecurityState.__doc__ = """The security level of a page or resource."""


class SecurityStateExplanation:
    """An explanation of an factor contributing to the security state."""
    def __init__(self, securityState: "SecurityState", summary: str,
                 description: str, hasCertificate: bool):
        # Security state representing the severity of the factor being explained.
        self.securityState = securityState
        # Short phrase describing the type of factor.
        self.summary = summary
        # Full text explanation of the factor.
        self.description = description
        # True if the page has a certificate.
        self.hasCertificate = hasCertificate


class InsecureContentStatus:
    """Information about insecure content on the page."""
    def __init__(self, ranMixedContent: bool, displayedMixedContent: bool,
                 ranContentWithCertErrors: bool,
Example #20
0
from enum import Enum
from typing import Any, List

from .base import ChromeCommand

from . import Network

ResourceType = Enum(
    "ResourceType",
    "Document Stylesheet Image Media Font Script TextTrack XHR Fetch EventSource WebSocket Manifest Other"
)
ResourceType.__doc__ = """Resource type as it was perceived by the rendering engine."""

# Unique frame identifier.
FrameId = str


class Frame:
    """Information about the Frame on the page."""
    def __init__(self,
                 id: str,
                 loaderId: "Network.LoaderId",
                 url: str,
                 securityOrigin: str,
                 mimeType: str,
                 parentId: str = None,
                 name: str = None):
        # Frame unique identifier.
        self.id = id
        # Identifier of the loader associated with this frame.
        self.loaderId = loaderId
Example #21
0
from authlib.jose import errors as jwt_errors
from fastapi.openapi.models import OAuthFlows
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.middleware.authentication import AuthenticationError
from starlette.requests import Request

from fastapi_aad_auth._base.state import AuthenticationState, User
from fastapi_aad_auth._base.validators.base import Validator

OAuthFlowType = Enum('OAuthFlowType',
                     {u: u
                      for u in OAuthFlows.__fields__.keys()})  # type: ignore
OAuthFlowType.__doc__ = 'Enumeration of OAuth Flows for OpenAPI\n\nOptions:\n\t' + '\n\t'.join(
    [f'* ``{u}``' for u in OAuthFlowType.__members__])


class InitOAuth(BaseModel):
    """OAuth information for openapi docs."""
    clientId: str
    scopes: str
    usePkceWithAuthorizationCodeGrant: bool


class TokenValidator(Validator, OAuth2AuthorizationCodeBearer):  # type: ignore
    """Validator for token based authentication."""
    def __init__(
        self,
        client_id: str,
        authorizationUrl: str,
Example #22
0
from __future__ import unicode_literals
from collections import defaultdict
from enum import Enum
from tgen.logf import log_debug
from tgen.logf import log_warn
from tgen.tree import TreeData, TreeNode
import numpy as np

try:
    from pytreex.core.node import T
except ImportError:
    log_warn(
        'Pytreex modules not available, will not be able to evaluate trees.')

EvalTypes = Enum(b'EvalTypes', b'TOKEN NODE DEP')
EvalTypes.__doc__ = """Evaluation flavors (tokens, tree node-only, tree dependency)"""


def collect_counts(sent, eval_type=EvalTypes.NODE):
    """Collects counts of different node/dependency types in the given t-tree.

    @param sent: the tree/sentence to collect counts from
    @param eval_type: if set to EvalTypes.NODE (default), count nodes (formemes, lemmas, dependency \
        direction), if set to EvalTypes.DEP, count dependencies (including parent's formeme, lemma, \
        dependency direction), if set to EvalTypes.TOKEN, count just word forms (in list of tokens).
    @rtype: defaultdict
    """
    counts = defaultdict(int)
    nodes = sent if isinstance(sent, list) else sent.get_descendants()
    for node in nodes:
        if eval_type == EvalTypes.TOKEN:
Example #23
0
    '''A fraction that represents minimum image comparison score to decide on an image match. Default is 0.7. Currently not processed.'''


class TimeUnit(Enum):
    '''
        Allowed time unit types.
    '''

    MILLI_SECONDS = auto()
    SECONDS = auto()
    MINUTES = auto()


class BrowserName(Enum):
    '''
        Allowed browser names for Gui Automation.
    '''

    CHROME = auto()
    FIREFOX = auto()


import locale
import re
__locales = [
    i.upper() for i in locale.locale_alias.keys() if re.match('^[\w_]+$', i)
]

Locale = Enum('Locale', dict(zip(__locales, range(len(__locales)))))
Locale.__doc__ = '''Allowed locale names in Arjuna.'''
Example #24
0
    "FsGb",
    "G",
    "GsAb",
    "A",
    "AsBb",
    "B",
]

_NOTES_DICT = {}

for i in range(int(len(_NOTE_FREQUENCIES) / 12)):
    for j in range(12):
        _NOTES_DICT[_NOTE_STRINGS[j] + str(i)] = _NOTE_FREQUENCIES[i * 12 + j]

NOTES = Enum("NOTES", _NOTES_DICT)
NOTES.__doc__ = """
    A collection of standard musical note frequencies
    As '#' is not valid in a variable name 's' is used instead
    Example: F sharp in the 6th octave would be NOTES.Fs6
              B flat in the 4th octave would be NOTES.Bb4
"""


class TUNES(Enum):
    """
    A collection of pre-programmed tunes the robot can play

    TUNES.UP = 1
    TUNES.DOWN = 2
    """
Example #25
0
from enum import Enum
from typing import Any, List

from base import ChromeCommand

import Runtime

DOMBreakpointType = Enum("DOMBreakpointType",
                         "subtree-modified attribute-modified node-removed")
DOMBreakpointType.__doc__ = "DOM breakpoint type."


class EventListener:
    """Object event listener."""
    def __init__(self,
                 type: str,
                 useCapture: bool,
                 passive: bool,
                 once: bool,
                 scriptId: "Runtime.ScriptId",
                 lineNumber: int,
                 columnNumber: int,
                 handler: "Runtime.RemoteObject" = None,
                 originalHandler: "Runtime.RemoteObject" = None,
                 removeFunction: "Runtime.RemoteObject" = None):
        # <code>EventListener</code>'s type.
        self.type = type
        # <code>EventListener</code>'s useCapture.
        self.useCapture = useCapture
        # <code>EventListener</code>'s passive flag.
        self.passive = passive
Example #26
0
from enum import Enum
from typing import Any, List

from .base import ChromeCommand

from . import Page
from . import DOM

StyleSheetId = str

StyleSheetOrigin = Enum("StyleSheetOrigin",
                        "injected user-agent inspector regular")
StyleSheetOrigin.__doc__ = """Stylesheet type: "injected" for stylesheets injected via extension, "user-agent" for user-agent stylesheets, "inspector" for stylesheets created by the inspector (i.e. those holding the "via inspector" rules), "regular" for regular stylesheets."""


class PseudoElementMatches:
    """CSS rule collection for a single pseudo style."""
    def __init__(self, pseudoType: "DOM.PseudoType", matches: List):
        # Pseudo element type.
        self.pseudoType = pseudoType
        # Matches of CSS rules applicable to the pseudo style.
        self.matches = matches


class InheritedStyleEntry:
    """Inherited CSS rule collection from ancestor node."""
    def __init__(self, matchedCSSRules: List, inlineStyle: "CSSStyle" = None):
        # Matches of CSS rules matching the ancestor node in the style inheritance chain.
        self.matchedCSSRules = matchedCSSRules
        # The ancestor node's inline style, if any, in the style inheritance chain.
        self.inlineStyle = inlineStyle
Example #27
0
from enum import Enum
from typing import Any, List

from .base import ChromeCommand

from . import DOM

# Unique accessibility node identifier.
AXNodeId = str

AXValueType = Enum("AXValueType", "boolean tristate booleanOrUndefined idref idrefList integer node nodeList number string computedString token tokenList domRelation role internalRole valueUndefined")
AXValueType.__doc__ = """Enum of possible property types."""

AXValueSourceType = Enum("AXValueSourceType", "attribute implicit style contents placeholder relatedElement")
AXValueSourceType.__doc__ = """Enum of possible property sources."""

AXValueNativeSourceType = Enum("AXValueNativeSourceType", "figcaption label labelfor labelwrapped legend tablecaption title other")
AXValueNativeSourceType.__doc__ = """Enum of possible native property sources (as a subtype of a particular AXValueSourceType)."""

class AXValueSource:
    """A single source for a computed AX property."""
    def __init__(self, type: "AXValueSourceType", value: "AXValue"=None, attribute: str=None, attributeValue: "AXValue"=None, superseded: bool=None, nativeSource: "AXValueNativeSourceType"=None, nativeSourceValue: "AXValue"=None, invalid: bool=None, invalidReason: str=None):
        # What type of source this is.
        self.type = type
        # The value of this property source.
        self.value = value
        # The name of the relevant attribute, if any.
        self.attribute = attribute
        # The value of the relevant attribute, if any.
        self.attributeValue = attributeValue
        # Whether this source is superseded by a higher priority source.
Example #28
0
from distutils.version import StrictVersion
from enum import Enum

import boto3

from hedwig.conf import settings
from hedwig.exceptions import ValidationError, CallbackNotFound
from hedwig.validator import FormatValidator

MessageType = Enum(
    'MessageType', {
        t[0].replace('.', '_').replace('-', '_'): t[0]
        for t in settings.HEDWIG_MESSAGE_ROUTING
    })

MessageType.__doc__ = "Enumeration representing the message types supported for this service. This is automatically " \
                      "created based on setting `HEDWIG_MESSAGE_ROUTING`"

_validator = None


def _get_validator():
    global _validator
    if _validator is None:
        _validator = settings.HEDWIG_DATA_VALIDATOR_CLASS()
    return _validator


_format_validator = FormatValidator()


class Metadata:
Example #29
0
        ">=": ">=",
        "contains": "*=",
        "*=": "*=",
        "starts": "^=",
        "^=": "^=",
        "should start with": "^=",
        "ends": "$=",
        "should end with": "$=",
        "$=": "$=",
        "matches": "$",
        "validate": "validate",
        "then": "then",
        "evaluate": "then",
    },
)
AssertionOperator.__doc__ = """
    Enum that defines the ``assertion_operator`` <`AssertionOperator`>.

    Currently supported assertion operators are:

    |      = Operator =   |   = Alternative Operators =       |              = Description =                                         | = Validate Equivalent =              |
    | ``==``              | ``equal``, ``should be``          | Checks if returned value is equal to expected value.                 | ``value == expected``                |
    | ``!=``              | ``inequal``, ``should not be``    | Checks if returned value is not equal to expected value.             | ``value != expected``                |
    | ``>``               | ``greater than``                  | Checks if returned value is greater than expected value.             | ``value > expected``                 |
    | ``>=``              |                                   | Checks if returned value is greater than or equal to expected value. | ``value >= expected``                |
    | ``<``               | ``less than``                     | Checks if returned value is less than expected value.                | ``value < expected``                 |
    | ``<=``              |                                   | Checks if returned value is less than or equal to expected value.    | ``value <= expected``                |
    | ``*=``              | ``contains``                      | Checks if returned value contains expected value as substring.       | ``expected in value``                |
    | ``^=``              | ``should start with``, ``starts`` | Checks if returned value starts with expected value.                 | ``re.search(f"^{expected}", value)`` |
    | ``$=``              | ``should end with``, ``ends``     | Checks if returned value ends with expected value.                   | ``re.search(f"{expected}$", value)`` |
    | ``matches``         |                                   | Checks if given RegEx matches minimum once in returned value.        | ``re.search(expected, value)``       |
Example #30
0
from . import Runtime
from . import Security

# Unique loader identifier.
LoaderId = str

# Unique request identifier.
RequestId = str

# Number of seconds since epoch.
Timestamp = float

class Headers: pass

ConnectionType = Enum("ConnectionType", "none cellular2g cellular3g cellular4g bluetooth ethernet wifi wimax other")
ConnectionType.__doc__ = """Loading priority of a resource request."""

CookieSameSite = Enum("CookieSameSite", "Strict Lax")
CookieSameSite.__doc__ = """Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies"""

class ResourceTiming:
    """Timing information for the request."""
    def __init__(self, requestTime: float, proxyStart: float, proxyEnd: float, dnsStart: float, dnsEnd: float, connectStart: float, connectEnd: float, sslStart: float, sslEnd: float, workerStart: float, workerReady: float, sendStart: float, sendEnd: float, pushStart: float, pushEnd: float, receiveHeadersEnd: float):
        # Timing's requestTime is a baseline in seconds, while the other numbers are ticks in milliseconds relatively to this requestTime.
        self.requestTime = requestTime
        # Started resolving proxy.
        self.proxyStart = proxyStart
        # Finished resolving proxy.
        self.proxyEnd = proxyEnd
        # Started DNS address resolve.
        self.dnsStart = dnsStart
Example #31
0
@enum.unique
class Patterns(Enum):
  """
  Defines some known regex pattern templates for common types of inline syntax.
  For example, a single group inline element (one capture group framed by
  something before and after the group).
  """
  escape = '(?<!\\\\)(?:\\\\\\\\)*{0}'
  single_group = '(?<!\\\\)(?:\\\\\\\\)*\\K{0}(.*?(?<!\\\\)(?:\\\\\\\\)*){1}'
  link = r'(?<!\\)(?:\\\\)*\K{0}\[(.*?(?<!\\)(?:\\\\)*)\]\((.*?(?<!\\)(?:\\\\)*)\)'
  double_group = r'(?<!\\)(?:\\\\)*\K\{0}(.*?(?<!\\)(?:\\\\)*){1}(.*?(?<!\\)(?:\\\\)*){2}'


Nesting = Enum('Nesting', 'FRAME POST SUB NONE')
Nesting.__doc__ = """
FRAME: element is intended to contain/frame the inside
       text, which means that subscriptions should be inherited from the parent.

POST: text in the block should be parsed AFTER this block is
      parsed. This is the default, and is suitable for most situations.

SUB: the inside of the text is parsed for child nodes (inline and
     block) first, and the corresponding sections are replaced with [|*|] style
     tags that are meant to be left UNTOUCHED. After this block is parsed,
     then the tags are replaced with the appropriate parsed sections. This could
     have also been called 'PRE', since it pre-parses the contents before
     calling the block's parsing function.

NONE: terminal element. The parser's output is taken verbatim, with out any
      further processing of its insides.
Example #32
0
class BackendNode:
    """Backend node with a friendly name."""
    def __init__(self, nodeType: int, nodeName: str,
                 backendNodeId: "BackendNodeId"):
        # <code>Node</code>'s nodeType.
        self.nodeType = nodeType
        # <code>Node</code>'s nodeName.
        self.nodeName = nodeName
        self.backendNodeId = backendNodeId


PseudoType = Enum(
    "PseudoType",
    "first-line first-letter before after backdrop selection first-line-inherited scrollbar scrollbar-thumb scrollbar-button scrollbar-track scrollbar-track-piece scrollbar-corner resizer input-list-button"
)
PseudoType.__doc__ = "Pseudo element type."

ShadowRootType = Enum("ShadowRootType", "user-agent open closed")
ShadowRootType.__doc__ = "Shadow root type."


class Node:
    """DOM interaction is implemented in terms of mirror objects that represent the actual DOM nodes. DOMNode is a base node mirror type."""
    def __init__(self,
                 nodeId: "NodeId",
                 backendNodeId: "BackendNodeId",
                 nodeType: int,
                 nodeName: str,
                 localName: str,
                 nodeValue: str,
                 childNodeCount: int = None,
Example #33
0
from enum import Enum
from typing import Any, List

from base import ChromeCommand

StorageType = Enum(
    "StorageType",
    "appcache cookies file_systems indexeddb local_storage shader_cache websql service_workers cache_storage all"
)
StorageType.__doc__ = "Enum of possible storage types."


class clearDataForOrigin(ChromeCommand):
    """Clears storage for origin."""
    def __init__(self, origin: str, storageTypes: str):
        # Security origin.
        self.origin = origin
        # Comma separated origin names.
        self.storageTypes = storageTypes
    Since [https://github.com/microsoft/playwright|Playwright] comes with a pack of builtin
    binaries for all browsers, no additional drivers e.g. geckodriver are needed.

    All these browsers that cover more than 85% of the world wide used browsers,
    can be tested on Windows, Linux and MacOS.
    Theres is not need for dedicated machines anymore.
    """

    chromium = auto()
    firefox = auto()
    webkit = auto()


ColorScheme = Enum("ColorScheme", ["dark", "light", "no-preference"])
ColorScheme.__doc__ = """Emulates 'prefers-colors-scheme' media feature.

        See [https://playwright.dev/docs/api/class-page?_highlight=emulatemedia#pageemulatemediaparams |emulateMedia(options)]
        for more details.

        Used by `New Context`. """


ScrollBehavior = Enum("ScrollBehavior", ["auto", "smooth"])
ScrollBehavior.__doc__ = """Enum that controls the behavior of scrolling.

``smooth`` """


class SizeFields(Enum):
    """Enum that defines how the returned size is filtered.

"""
Usage: streamparser.py [FILE]

Consumes input from a file (first argument) or stdin, parsing and pretty printing the readings of lexical units found.
"""

import re, pprint, sys, itertools, fileinput
from enum import Enum
from collections import namedtuple


Knownness = Enum('Knownness', 'known unknown biunknown genunknown')
try:
    Knownness.__doc__ = """Level of knowledge associated with a lexical unit.
    Values:
        known
        unknown: Denoted by '*', analysis not available.
        biunknown: Denoted by '@', translation not available.
        genunknown: Denoted by '#', generated form not available.
"""
except AttributeError:
    # Python 3.2 users have to read the source
    pass

SReading = namedtuple('SReading', ['baseform', 'tags'])
try:
    SReading.__doc__ = """A single subreading of an analysis of a token.
    Fields:
        baseform (str): The base form (lemma, lexical form, citation form) of the reading.