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))
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
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)
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
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']
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
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
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, )
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"
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)
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
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)
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]
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()
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 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
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
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:, :])
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)
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
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
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, )
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"
def read(self, file_name): """read an ac3d file. TODO: groups, nested kids""" # def convertObject(tokens): # pass def convertLMaterial(tokens): self.materials_list.append(tokens[1]) def convertLObj(tokens): self.new_object("", "") self._current_object._type = tokens[1] def convertLKids(tokens): self._current_object.kids = int(tokens[1]) def convertLData(tokens): pass def convertLName(tokens): self._current_object.name = tokens[1].strip('"\'') def convertLTexture(tokens): self._current_object.texture = tokens[1].strip('"\'') def _token2array(tokens, num): return np.array([float(item) for item in tokens[1:num + 1]]) def convertLTexrep(tokens): self._current_object.texrep = _token2array(tokens, 2) def convertLTexoff(tokens): self._current_object.texoff = _token2array(tokens, 2) def convertLRot(tokens): self._current_object.rot = _token2array(tokens, 9) def convertLCrease(tokens): self._current_object.crease = tokens[1] def convertLLoc(tokens): self._current_object.loc = _token2array(tokens, 3) def convertLUrl(tokens): self._current_object.url = tokens[1] def convertLVertex(tokens): self._current_object.node(tokens[0], tokens[1], tokens[2]) def convertSurf(tokens): assert (tokens[0] == 'SURF') assert (tokens[2] == 'mat') assert (tokens[4] == 'refs') self._current_object.face(nodes_uv_list=tokens[6], typ=tokens[1], mat_idx=tokens[3]) def convertIntegers(tokens): return int(tokens[0]) def convertFloats(tokens): try: return float(tokens[0]) except ValueError: logging.error(tokens[0]) integer = Word(nums).setParseAction(convertIntegers) string = Regex(r'"[^"]*"') floatNumber = Regex(r'[+-]?(\d+(\.\d*)?|(\.\d*))([eE][+-]\d+)?' ).setParseAction(convertFloats) anything = Regex(r'.*') debug = False # Relaxed see Tor_Ness_Lighthouse.xml lHeader = Regex('AC3Db[S]*') + LineEnd() lMaterial = ( Literal('MATERIAL') + anything + LineEnd()).setParseAction(convertLMaterial).setDebug(debug) lObject = (Literal('OBJECT') + Word(alphas)).setParseAction(convertLObj).setDebug(debug) lKids = (Literal('kids') + integer).setParseAction(convertLKids).setDebug(debug) lName = (Literal('name') + string).setParseAction(convertLName).setDebug(debug) lData = (Literal('data') + integer + LineEnd() + anything + LineEnd()).setParseAction(convertLData).setDebug(debug) lTexture = (Literal('texture') + string).setParseAction(convertLTexture).setDebug(debug) lTexrep = (Literal('texrep') + floatNumber + floatNumber).setParseAction(convertLTexrep).setDebug(debug) lTexoff = (Literal('texoff') + floatNumber + floatNumber).setParseAction(convertLTexoff).setDebug(debug) lRot = (Literal('rot') + floatNumber + floatNumber + floatNumber + floatNumber + floatNumber + floatNumber + floatNumber + floatNumber + floatNumber).setParseAction(convertLRot).setDebug(debug) lLoc = (Literal('loc') + floatNumber + floatNumber + floatNumber).setParseAction(convertLLoc) lCrease = (Literal('crease') + floatNumber).setParseAction(convertLCrease).setDebug(debug) lUrl = (Literal('url') + string).setParseAction(convertLUrl).setDebug(debug) lNumvert = Literal('numvert') + Word(nums) lVertex = (floatNumber + floatNumber + floatNumber).setParseAction(convertLVertex) lNumsurf = Literal('numsurf') + Word(nums) lSurf = Literal('SURF') + Word(alphanums) lMat = Literal('mat') + integer lRefs = Literal('refs') + integer lNodes = Group(integer + floatNumber + floatNumber) pObjectWorld = Group(lObject + Optional(lName) + lKids) pSurf = (lSurf + Optional(lMat) + lRefs + Group(OneOrMore(lNodes))).setParseAction(convertSurf) pObjectHeader = Group(lObject + Each([ Optional(lName), Optional(lData), Optional(lTexture), Optional(lTexrep), Optional(lTexoff), Optional(lRot), Optional(lLoc), Optional(lUrl), Optional(lCrease) ])) pObject = Group( pObjectHeader + Optional(lNumvert + Group(ZeroOrMore(lVertex)) + Optional(lNumsurf + Group(ZeroOrMore(pSurf)))) + lKids) # .setParseAction( convertObject ) pFile = lHeader + Group(OneOrMore(lMaterial)) + pObjectWorld \ + Group(OneOrMore(pObject)) try: self.p = pFile.parseFile(file_name) except IOError as e: logging.warning(e)
def __init__(self, log: bool = True) -> None: # Following attribute set in :func:``_initialize`` self._tf_devices: Optional(List[str]) = None super().__init__(log=log)
def __init__(self): """ expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* """ point = Literal(".") e = CaselessLiteral("E") fnumber = Combine( Word("+-" + nums, nums) + Optional(point + Optional(Word(nums))) + Optional(e + Word("+-" + nums, nums))) ident = Word(alphas, alphas + nums + "_$") mod = Literal("%") plus = Literal("+") minus = Literal("-") mult = Literal("*") iadd = Literal("+=") imult = Literal("*=") idiv = Literal("/=") isub = Literal("-=") div = Literal("/") lpar = Literal("(").suppress() rpar = Literal(")").suppress() addop = plus | minus multop = mult | div | mod iop = iadd | isub | imult | idiv expop = Literal("^") pi = CaselessLiteral("PI") expr = Forward() atom = ((Optional(oneOf("- +")) + (ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst)) | Optional(oneOf("- +")) + Group(lpar + expr + rpar)).setParseAction(self.pushUMinus) # by defining exponentiation as "atom [ ^ factor ]..." instead of # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right # that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor << atom + ZeroOrMore( (expop + factor).setParseAction(self.pushFirst)) term = factor + ZeroOrMore( (multop + factor).setParseAction(self.pushFirst)) expr << term + ZeroOrMore( (addop + term).setParseAction(self.pushFirst)) final = expr + ZeroOrMore((iop + expr).setParseAction(self.pushFirst)) # addop_term = ( addop + term ).setParseAction( self.pushFirst ) # general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term) # expr << general_term self.bnf = final # map operator symbols to corresponding arithmetic operations epsilon = 1e-12 self.opn = { "+": operator.add, "-": operator.sub, "+=": operator.iadd, "-=": operator.isub, "*": operator.mul, "*=": operator.imul, "/": operator.truediv, "/=": operator.itruediv, "^": operator.pow, "%": operator.mod, } self.fn = { "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "abs": abs, "trunc": lambda a: int(a), "round": round, "sgn": lambda a: abs(a) > epsilon and ((a > 0) - (a < 0)) or 0, "log": lambda a: math.log(a, 10), "ln": math.log, "log2": math.log2, }
def __init__(self, entity: Actor, item: Item, target_pos: Optional(Tuple[int, int]) = None): super().__init__(entity) self.item = item if not target_pos: target_pos = entity.position self.target_pos = target_pos
def __init__(self): self._head: Optional(str) = None self._tail: Optional(str) = None