Exemplo n.º 1
0
def _define_grammar():

    from pyparsing import (
        Literal as Literal,
        Word,
        Optional,
        alphas,
        alphanums,
        delimitedList,
    )

    Separator = Literal("@").suppress()
    TagSeparator = Literal("?").suppress()

    Name = delimitedList(Word(alphas, alphanums + "_"),
                         PATH_DELIM,
                         combine=True).setResultsName("name")
    Tag = Word(alphas, alphanums + "_").setResultsName("tag")
    Selector = _selector_grammar.setResultsName("selector")

    SelectorType = (Literal("solids") | Literal("faces") | Literal("edges")
                    | Literal("vertices")).setResultsName("selector_kind")

    return (Name + Optional(TagSeparator + Tag) +
            Optional(Separator + SelectorType + Separator + Selector))
Exemplo n.º 2
0
 def __init__(
     self, 
     scale:Optinal(int)=0.8, 
     image_ext:Optional(str)='.jpg', 
     label_ext:Optional(str)='.txt'
 ) -> None:
     self.scale = scale
     self.image_ext = image_ext
     self.label_ext = label_ext
def make_bone(
    armature: bpy.types.Armature,
    name: str,
    head: Optional(Vector) = None,
    tail: Optional(Vector) = None,
    up: Optional(Vector) = None,
    parent: Optional(bpy.types.EditBone)
) -> bpy.types.EditBone:
    """
	Creates a new bone in the specified armature and returns the EditBone representing it.

	:param armature: The Armature data in which to create the new bone.
	:param name: Name of the new bone to create.
	:param head: If not None, the head position of the new bone.
	:param tail: If not None, the tail position of the new bone.
	:param up: If not None, the up vector of the new bone for roll calculation.
	:param parent: Parent EditBone of this new bone.
	:return: an EditBone.
	:throws: ValueError if head, tail, or up are not mathutils.Vectors, if the Armature is not in edit mode,
			or if a bone by the specified name already exists
	"""

    if not bpy.context.mode == 'EDIT':
        raise ValueError('Armature "{}" not in Edit mode.'.format(
            armature.name))

    for vector in head, tail, up:
        if vector and not isinstance(vector, Vector):
            raise ValueError(
                'head, tail, and up must be None or mathutils.Vector.')

    if name in armature.edit_bones:
        raise ValueError(
            'A bone named "{}" already exists in Armature "{}".'.format(
                name, armature.name))

    if head is None:
        head = Vector([0, 0, 0])

    if tail is None:
        tail = Vector([0, 2, 0])

    bone = armature.edit_bones.new()

    ## copies are here to protect against passing another bone.head or bone.tail
    bone.head = head.copy()
    bone.tail = tail.copy()

    if up:
        bone.align_roll(up)

    if parent:
        bone.parent = parent

    return bone
Exemplo n.º 4
0
    def __init__(self, ip_info):
        security_data = ip_info['security']

        self.is_proxy: bool = security_data['is_proxy']
        self.proxy_type: Optional(str) = security_data['proxy_type']
        self.is_crawler: bool = security_data['is_crawler']
        self.crawler_name: Optional(str) = security_data['crawler_name']
        self.crawler_type: Optional(str) = security_data['crawler_type']
        self.is_tor: bool = security_data['is_tor']
        self.threat_level: Optional(str) = security_data['threat_level']
        self.threat_types: list = security_data['threat_types']
Exemplo n.º 5
0
    def __init__(self, log: bool = True, log_level: str = "INFO") -> None:

        self._log_level: str = log_level.upper()

        # Following attributes are set in :func:``_initialize``
        self._ctx: Optional(plaidml.Context) = None
        self._supported_devices: Optional(List[plaidml._DeviceConfig]) = None
        self._all_devices: Optional(List[plaidml._DeviceConfig]) = None
        self._device_details: Optional(List[dict]) = None

        super().__init__(log=log)
Exemplo n.º 6
0
 def __init__(self: 'SemanticVersion',
              major: Counter = 0,
              minor: Optional(Counter) = 0,
              micro: Optional(Counter) = 0,
              prerelease: Optional[PreRelease] = None,
              build: Optional[Build] = None):
     self._major = major
     self._minor = minor
     self._micro = micro
     self._prerelease = PreRelease(prerelease) if prerelease else None
     self._build = Build(build) if build else None
Exemplo n.º 7
0
class IntegerGrader(Grader):
    """
    Numeric grader for integer values
    """

    fields = {
        'max': Optional(int),
        'min': Optional(int),
        'answer': int,
    }

    def grade(self, value):
        return 100 if self.answer == value else 0
Exemplo n.º 8
0
class NumericGrader(Grader):
    """
    Numeric float values.
    """

    fields = {
        'max': Optional(float),
        'min': Optional(float),
        'answer': float,
        'tolerance': 0.0
    }

    def grade(self, value):
        tol = self.tolerance
        return 100 if abs(value - self.answer) <= tol else 0
Exemplo n.º 9
0
class Delivery(BaseModel):
    user: UUID
    name: str
    post: str
    permission: str
    available: bool
    task: set() = None
    is_deleted: bool = False
    events: Optional(List[events.Event]) = []

    class Config:
        title = "Delivery"
        allow_mutations = False
        extra = "Forbid"

    def allocate(self, order: Shipping):
        if self.available == False:
            self.events.append(events.NotAvailable(self.user))
            return None
        else:
            self.task.add(order)

    def can_deliver(self, order: Shipping) -> bool:
        return self.available

    def remove_shipping(self, order: Shipping):
        if order in self.task:
            self.task.remove(order)
            self.available = True

    def mark_completed(self, order: Shipping):
        if order in self.task:
            self.task.remove(order)
            self.task.order.status = "Completed"
Exemplo n.º 10
0
def run(game: typing.Optional = None, rounds_total: int = 3):
    print('Welcome to the Brain Games!')

    if game is not None:
        print(game.DESCRIPTION)

    name = prompt.string('May I have your name? ')
    print(f'Hello {name}')

    if game is not None:
        current_round_num = 0

        while current_round_num < rounds_total:
            question, answer = game.prepare_round()

            print(f'Question: {question}')

            user_answer = prompt.string("Your answer: ")

            if user_answer == answer:
                print('Correct!')
                current_round_num += 1
            else:
                print(f"'{user_answer}' is wrong answer ;(. "
                      f"Correct answer was '{answer}'.\n"
                      f"Let's try again, {name}!")
                return

        print(f'Congratulations! {name}')
Exemplo n.º 11
0
def get_elasticsearch_client(url: str) -> Elasticsearch:
    if ELASTICSEARCH_AWS_HOSTED:
        credentials = boto3.Session().get_credentials()
        return Elasticsearch(
            hosts=[url],
            http_auth=AWS4Auth(
                credentials.access_key,
                credentials.secret_key,
                ELASTICSEARCH_AWS_REGION,
                "es",
                session_token=credentials.token,
            ),
            use_ssl=True,
            verify_certs=True,
            connection_class=RequestsHttpConnection,
        )
    else:
        api_key: Optional(Tuple[str, str]) = None
        if ELASTICSEARCH_API_KEY_ID and ELASTICSEARCH_API_KEY:
            api_key = (ELASTICSEARCH_API_KEY_ID, ELASTICSEARCH_API_KEY)
        return Elasticsearch(
            hosts=[url],
            timeout=ELASTICSEARCH_TIMEOUT,
            verify_certs=ELASTICSEARCH_VERIFY_CERTS,
            use_ssl=ELASTICSEARCH_USE_SSL,
            ssl_show_warn=ELASTICSEARCH_SSL_SHOW_WARN,
            ca_certs=ELASTICSEARCH_CA_CERTS,
            client_cert=ELASTICSEARCH_CLIENT_CERT,
            client_key=ELASTICSEARCH_CLIENT_KEY,
            api_key=api_key,
        )
Exemplo n.º 12
0
def kmp_algo(inp_string: str, substr: str) -> Optional(int):
    """
	Implementation of Knuth-Morrison-Pratt algorithm

	:param inp_string: String where substr is to be found (haystack)
	:param substr: substr to be found in inp_string (needle)
	:return: index where first occurrence of substr in inp_string started or None if not found
	"""
    def prefix_fun(prefix_str: str) -> List[int]:
        """
		Prefix function for KMP

		:param prefix_str: dubstring for prefix function
		:return: prefix values table
		"""
        prefix_str = [0] * len(inp_string)
        for i in range(1, len(prefix_str)):
            k = prefix_str[i - 1]
            while k > 0 and prefix_str[k] != inp_string[i]:
                k = prefix_str[k - 1]
            if prefix_str[k] == inp_string[i]:
                k = k + 1
            prefix_str[i] = k
        print(inp_string, substr, prefix_fun)
        return prefix_str
Exemplo n.º 13
0
class ReviewTextInfo(NamedTuple):
    """商品レビュー内の1文に関する情報

  Attributes:
    review_id (int): レビュー番号
    last_review_id (int): 最後のレビュー番号
    text_id (int): 文番号
    last_text_id (int): 最後の文番号
    star (float): 評価
    title (str): レビューのタイトル
    review (str): レビュー全文
    text (str): 対象としている文
    result Optional(Dict[str, Tuple(AttrExtractionResult, ...)]): 抽出結果
  """
    review_id: int
    last_review_id: int
    text_id: int
    last_text_id: int
    star: float
    title: str
    review: str
    text: str
    result: Optional(Dict[str, Tuple(AttrExtractionResult, ...)])

    @classmethod
    def from_dictionary(cls, dictionary: Dict[str, Any]):
        this = cls(**dictionary)
        result_dict = this.result
        for attr, results in result_dict.items():
            result_dict[attr] = AttrExtractionResult(*results)

        return this._replace(result=result_dict)
Exemplo n.º 14
0
def main():
    settings: Optional(Settings) = None
    try:
        module_path: str = os.path.dirname(
            os.path.realpath(inspect.getfile(inspect.currentframe())))
        settings = Settings(module_path)

        processChoices(settings)

        report_generated = False

        if settings.dump_document_structure:
            print("\n%s" % getDocumentStructureDocString(settings))

        if settings.mass_report or len(settings.mass_report_members) > 0:
            writeMassReport(settings)
            report_generated = True
        elif settings.isFirmwareBinaryDefined():
            exportDocument(settings)
            report_generated = True

        if settings.driver_template_file:
            settings.writeParameterTemplateFile(
                settings.driver_template_file,
                output_actual_values=report_generated)
    except Exception as exception:
        errorOutput(settings, exception, force_stacktrace=True)
        sys.exit(RETURN_CODE_UNRECOVERABLE_ERROR)
    else:
        print(f"{CHECKERED_FLAG} Done.")

    if error_handling.WARNINGS_OCCURRED:
        print(f"{WARNING} Watch out! Warnings occurred.")
        sys.exit(RETURN_CODE_WARNINGS_OCCURRED)
Exemplo n.º 15
0
def _GetSiteData (siteModule: typing.Optional) -> typing.Dict[str, typing.Any]:
	if siteModule is None:
		return dict()

	if hasattr(siteModule, "GetSiteData"):
		return siteModule.GetSiteData()

	return dict()
Exemplo n.º 16
0
def _GetModData(modModule: typing.Optional) -> typing.Dict[str, typing.Any]:
    if modModule is None:
        return dict()

    if hasattr(modModule, "GetModData"):
        return modModule.GetModData()

    return dict()
Exemplo n.º 17
0
 def selected_col(self)->Optional(str):
     """
     Get selected feature value
     :return: Selected feature name r None if Nothing selected
     """
     index = self.features_widget.currentIndex()
     if index < 1:
         return None
     return self.features[index]
Exemplo n.º 18
0
 def get_queue_by_id(queue_id: int) -> Optional(Queue):
     """
     Find the queue by the queue_id.\n
     Inputs:\n
     queue_id --> The id of the queue to look for.\n
     Returns:\n
     The queue object, return None if it is not in the database.\n
     """
     return Queue.query.filter_by(id=queue_id).first()
Exemplo n.º 19
0
class PetForm(FlaskForm):

    name = StringField(
        "Pet Name", validators=[InputRequired(message="Name cannot be blank")])

    species = SelectField("Species",
                          choices=[('fish', 'Fish'), ('dog', 'Dog'),
                                   ('hedgehog', 'Hedgehog')])

    photo_url = StringField("Photo Url", validators=[URL(), Optional()])

    age = IntegerField("Pet Age",
                       validators=[Optional(),
                                   NumberRange(min=0, max=30)])

    notes = StringField("Notes")

    available = BooleanField("Is Available")
    def serialize_optional(self, context: TypeEvaluationContext, tt: OptionalType, obj: Any):
        from ..._gen.com.digitalasset.ledger.api.v1.value_pb2 import Optional
        ut = tt.type_parameter

        optional_message = Optional()
        if obj is not None:
            ctor, val = self._serialize_dispatch(context.append_path('?'), ut, obj)
            _set_value(optional_message.value, ctor, val)
        return 'optional', optional_message
 def convert_property(prop_name, prop):
     # it's datetime
     if "format" in prop and prop["format"] == "date-time":
         return "xsd:dataTime"
     # it's another object
     elif prop.get("type") is None and prop.get("$ref") is not None:
         prop_type = prop["$ref"].split("/")[-1]
         if defs is None or prop_type not in defs:
             raise RuntimeError(f"{prop_type} not found in defs.")
         if pipe:
             return self.from_json_schema(prop_type,
                                          defs[prop_type],
                                          pipe=True)
         else:
             self.from_json_schema(prop_type,
                                   defs[prop_type],
                                   subdoc=True)
             return self.object[prop_type]._to_dict()
     # it's enum
     elif prop.get("type") is None and prop.get("enum") is not None:
         # create enum name from snake case to camal case
         enum_name = prop_name.replace("_", " ").capitalize().replace(
             " ", "")
         enum_dict = {
             "@id": enum_name,
             "@type": "Enum",
             "@value": prop["enum"]
         }
         if pipe:
             return enum_dict
         else:
             self._contruct_class(enum_dict)
             return self.object[enum_name]._to_dict()
     # it's a List
     elif prop["type"] == "array":
         prop_type = convert_property(prop["items"])
         return {"@type": "List", "@class": prop_type}
     elif isinstance(prop["type"], list):
         prop_type = prop["type"]
         # it's Optional
         if "null" in prop_type:
             prop_type.remove("null")
             prop_type = prop_type[0]  # can only have one type
             # it's list in a 'type' so assume no ref
             return to_woql_type(
                 Optional.__getitem__(convert_dict[prop_type]))
         # THIS SHOULD BE TaggedUnion
         # elif len(prop_type) > 1:
         #     prop_type = to_woql_type(
         #         Union.__getitem__(*map(lambda x: convert_dict[x], prop_type))
         #     )
         # type is wrapped in a list
         else:
             return to_woql_type(convert_dict[prop_type[0]])
     else:
         return to_woql_type(convert_dict[prop["type"]])
Exemplo n.º 22
0
def __make_pydantic(cls):
    """
    Temporary wrapper function to convert an MSONable class into a PyDantic
    Model for the sake of building schemas
    """

    if any(cls == T for T in built_in_primitives):
        return cls

    if cls in prim_to_type_hint:
        return prim_to_type_hint[cls]

    if cls == Any:
        return Any

    if type(cls) == TypeVar:
        return cls

    if hasattr(cls, "__origin__") and hasattr(cls, "__args__"):

        args = tuple(__make_pydantic(arg) for arg in cls.__args__)
        if cls.__origin__ == Union:
            return Union.__getitem__(args)

        if cls.__origin__ == Optional and len(args) == 1:
            return Optional.__getitem__(args)

        if cls._name == "List":
            return List.__getitem__(args)

        if cls._name == "Tuple":
            return Tuple.__getitem__(args)

        if cls._name == "Set":
            return Set.__getitem__(args)

        if cls._name == "Sequence":
            return Sequence.__getitem__(args)

    if issubclass(cls, MSONable):
        if cls.__name__ not in STUBS:
            STUBS[cls] = MSONable_to_pydantic(cls)
        return STUBS[cls]

    if cls == ndarray:
        return List[Any]

    return cls
Exemplo n.º 23
0
def invoke_all(*, requests: List, region: Optional(str='us-east-1')):
    async def wrapper():
        async with aiohttp.ClientSession(raise_for_status=True) as session:
            invocations = run_invocations(
                requests=requests,
                default_region=region,
                session=session,
            )

            return await asyncio.gather(*invocations)

    loop = asyncio.get_event_loop()

    results = loop.run_until_complete(wrapper())

    return results
Exemplo n.º 24
0
 def preprocess_image_from_dir(
     self, 
     dir_path: str, 
     des_dir: Optional(str)='train_data'
 ) -> None:
     list_image_path = glob.glob(dir_path + '/*' + self.image_ext)
     list_image_path.sort()
     src_image_folder = os.path.join(des_dir, 'inputs')
     des_image_folder = os.path.join(des_dir, 'outputs')
     for image_path in list_image_path:
         image_name = image_path.split('/')[-1].replace('.jpg', '.png')
         print('Image name: {}'.format(image_name))
         image, labels = self.read_image_and_label(image_path)
         shape = image.shape
         density = self.preprocess_image(image, labels)
         cv2.imwrite(os.path.join(src_image_folder, image_name), image[shape[0] // 2:, :, :])
         cv2.imwrite(os.path.join(des_image_folder, image_name), density[shape[0] // 2:, :])
Exemplo n.º 25
0
def get_numbers_of_pyments_in_lines(
        xml_file: str) -> Tuple[Optional[List[int]], Optional[str]]:
    """Получаем номера строк, где встречается Плательщик и возвращаем line_list или None"""
    line_list: List[int] = list()
    xml_encoding: Optional(str) = None
    with open(xml_file, 'r', encoding='windows-1251') as file:
        for num, line in enumerate(file):
            encoding = find_encoding_in_string(line)
            if encoding:
                xml_encoding = encoding
            if "<Плательщик>" in line:
                line_list.append(num)
        logger.info("Кодировка документа {0}".format(xml_encoding))
    if line_list:
        return line_list, xml_encoding
    else:
        return None, xml_encoding
Exemplo n.º 26
0
 def _scan_file(self,
                results: ScanResults,
                user: NamedUser,
                org: Organization,
                repo: Repository,
                commitsha: str,
                filename: str,
                filelist: List[str]) -> None:
     file: Optional(ContentFile) = None
     content: str = None
     for scanner in self._scanners:
         if scanner.want(filename):
             if not file:
                 file = repo.get_contents(filename, ref=commitsha)
                 content = file.decoded_content.decode("utf-8")
             reposlug = "{}/{}".format(org.login, repo.name)
             result = scanner.check(reposlug, commitsha, file.sha, file.path, content, filelist)
             results.add(result)
Exemplo n.º 27
0
 def __init__(self,
              possible_actions: List[AVAILABLE_ACTION],
              game: GAME,
              prev_player: int = None,
              skip_actions=False,
              heuristic=None) -> None:
     self.children = {}
     self.possible_actions: Set[AVAILABLE_ACTION] = set(possible_actions)
     self._is_leaf: bool = True
     self.simulations: int = 0
     self.wins: int = 0
     self._state = game.get_state()
     self._terminating = game.done
     self.current_player = game.current_player
     self.prev_player = prev_player
     self.game = game
     self.skip_actions = skip_actions
     self.heuristic: Optional(List[float]) = heuristic(
         game._get_obs(), self.current_player) if heuristic else None
Exemplo n.º 28
0
def kmp_algo(inp_string: str, substr: str) -> Optional(int):
    """
	Implementation of Knuth-Morrison-Pratt algorithm

	:param inp_string: String where substr is to be found (haystack)
	:param substr: substr to be found in inp_string (needle)
	:return: index where first occurrence of substr in inp_string started or None if not found
	"""
    def prefix_fun(prefix_str: str) -> List[int]:
        """
		Prefix function for KMP

		:param prefix_str: dubstring for prefix function
		:return: prefix values table
		"""
        print(prefix_str)
        return []

    print(inp_string, substr, prefix_fun)
    return None
Exemplo n.º 29
0
def run_invocations(*, requests: List, base_url: str,
                    default_region: Optional(str), session):
    for request in requests:
        if not request.get('region') and not default_region:
            raise ValueError(
                'Must provide a region, either in the invocation arguments or'
                'as a default region when calling invoke_all')

        region = request.get('region') if type(request['region']) is str else \
            default_region

        base_url = LAMBDA_ENDPOINT.format(region=region)

        url = os.path.join(base_url, request['function_name'], 'invocations')

        yield invoke(
            url=url,
            payload=request['payload'],
            invocation_type=request['invocation_type'],
            session=session,
        )
Exemplo n.º 30
0
class Settings(BaseSettings):
    POSTGRES_SERVER: str
    POSTGRES_USER: str
    POSTGRES_PASSWORD: str
    POSTGRES_DB: str

    SQLALCHEMY_DATABASE_URI: Optional(PostgresDsn) = None

    @validator("SQLALCHEMY_DATABASE_URI", pre=True)
    def assemble_db_connection(cls, v: Optional[str],
                               values: Dict[str, Any]) -> Any:
        if isinstance(v, str):
            return v
        return PostgresDsn.build(scheme="postgresql",
                                 user=values.get("POSTGRES_USER"),
                                 password=values.get("POSTGRES_PASSWORD"),
                                 host=values.get("POSTGRES_SERVER"),
                                 path=f"/{values.get('POSTGRES_DB') or ''}")

    class Config:
        case_sensitive = True
        env_file = ".env"