def link_to(matchobj: Match) -> str: return r"%s<a href='?%s' class='nocode'>%s</a>%s" % ( matchobj.group(1), self.req_qs(link, use_stored=False), e_html(link), matchobj.group(1), )
def _match2date(self, match: Match, reference: datetime) -> DateTimeResolutionResult: result = DateTimeResolutionResult() holiday_str = self.config.sanitize_holiday_token( match.group('holiday').lower()) if not holiday_str: return result year = reference.year year_num = match.group('year') year_chinese = match.group('yearchs') year_relative = match.group('yearrel') has_year = False if year_num: has_year = True if self.config.get_swift_year(year_num) == 0: year_num = year_num[0:len(year_num) - 1] year = self.__convert_year(year_num, False) elif year_chinese: has_year = True if self.config.get_swift_year(year_chinese) == 0: year_chinese = year_chinese[0:len(year_chinese) - 1] year = self.__convert_year(year_chinese, True) elif year_relative: has_year = True year += self.config.get_swift_year(reference.year) if 100 > year >= 90: year += 1900 elif year < 100 and year < 20: year += 2000 timex = '' date = reference if holiday_str in self.__fixed_holiday_dictionary: date = self.__fixed_holiday_dictionary[holiday_str](year) timex = f'-{DateTimeFormatUtil.to_str(date.month, 2)}-{DateTimeFormatUtil.to_str(date.day, 2)}' elif holiday_str in self.config.holiday_func_dictionary: date = self.config.holiday_func_dictionary[holiday_str](year) timex = self.config.variable_holidays_timex_dictionary[holiday_str] else: return result if has_year: result.timex = DateTimeFormatUtil.to_str(year, 4) + timex result.future_value = datetime(year, date.month, date.day) result.past_value = datetime(year, date.month, date.day) else: result.timex = 'XXXX' + timex result.future_value = self.__get_date_value( date, reference, holiday_str, 1, lambda d, r: d < r) result.past_value = self.__get_date_value(date, reference, holiday_str, -1, lambda d, r: d >= r) result.success = True return result
def get_object_html( cls, match: Match, use_preretrieved_html: bool = False, ) -> str: """Return a model instance's HTML based on a placeholder in the admin.""" if not cls.get_admin_placeholder_regex().match(match.group(0)): raise ValueError( f'{match} does not match {cls.admin_placeholder_regex}') if use_preretrieved_html: # Return the pre-retrieved HTML (already included in placeholder) preretrieved_html = match.group(PlaceholderGroups.HTML) if preretrieved_html: return preretrieved_html.strip() logging.info( f'Could not use preretrieved HTML for ' f'{match.group(PlaceholderGroups.MODEL_NAME)} ' f'({match.group(PlaceholderGroups.PK)}); querying db instead.') key = match.group(PlaceholderGroups.PK).strip() logging.info(f'Retrieving object HTML for {cls.__name__} {key}...') try: model_instance = cls.objects.get(pk=key) object_html = model_instance.html logging.debug(f'Retrieved object HTML: {object_html}') except ObjectDoesNotExist as e: logging.error(f'Unable to retrieve object HTML; {e}') return '' return object_html
def _map(matching: Match) -> Tuple[Optional[CodeBlock], Optional[str]]: code_block = matching.group(2) language = matching.group(1) rest = matching.group(3) if rest == "": rest = None return CodeBlock(text=code_block, language=language), rest
def _map(matching: Match) -> Tuple[Optional[LinkBlock], Optional[str]]: title = matching.group(1) link = matching.group(2) rest = matching.group(3) if rest == "": rest = None return LinkBlock(text=title, link=link), rest
def _filter_id_illegal_character_replacement(self, m: typing.Match) -> str: if m.group(1) is not None: return '_{}'.format(m.group(1)) elif m.group(2) is not None: return '_' * len(m.group(2)) else: return self.encode_character(m.group(0))
def _before_sentence_tokenizer(self, regex_match: Match) -> str: """ Given a match on `l'abbé` returns `l風0abbé` where 風 is the character mask and 0 the index of the apostrophe in the match_apostrophes value """ return regex_match.group(1) + \ self.char_registry[self.char_registry.APOSTROPHE_CONSTANT] + \ str(self.apostrophes.index(regex_match.group(2))) + \ regex_match.group(3)
def _map( matching: Match ) -> Tuple[Optional[FallbackTextBlock], Optional[str]]: text_block = matching.group(1) rest = matching.group(2) if rest == "": rest = None return FallbackTextBlock(text=text_block), rest
def _map( matching: Match ) -> Tuple[Optional[InlinedCodeBlock], Optional[str]]: code_block = matching.group(1) rest = matching.group(2) if rest == "": rest = None return InlinedCodeBlock(text=code_block), rest
def sub(m: Match) -> str: if m.group(1) == 'ref': return { 'layouts': 'https://sw.kovidgoyal.net/kitty/index.html#layouts', 'sessions': 'https://sw.kovidgoyal.net/kitty/index.html#sessions', 'functional': 'https://sw.kovidgoyal.net/kitty/keyboard-protocol.html#functional-key-definitions', }[m.group(2)] return str(m.group(2))
def sub(m: Match) -> str: key = m.group(1) result = env.get(key) if result is None: result = os.environ.get(key) if result is None: result = m.group() return result
def _adjust_match(self, match: Match, static_partition: str = None): region = match.group("Region") partition = self._partition_lookup( region) if static_partition is None else static_partition service = match.group("Service") account_id = match.group("AccountID") resource_path = match.group("ResourcePath") return f"arn:{partition}:{service}:{region}:{account_id}:{resource_path}"
def process_greeting(self, match: Match, user: UserBase) -> str: greeting = match.group(1) name = match.group(2) if name is not None: user_name = user.name return "{0}, {1}.".format(greeting, user_name) return "{0}!".format(random.choice(_GREETINGS))
def sub(m: Match) -> str: key = m.group(1) or m.group(2) result = env.get(key) if result is None and fallback_to_os_env: result = os.environ.get(key) if result is None: result = m.group() return result
def repl(m: Match) -> str: name = m.group(1) if name in pos: position = pos[name] else: position = pos.setdefault(name, len(result)) result.append(name) return m.group(0).replace(":" + name, "${}".format(position))
def _fetch_type_sub(cls, cls_in: Type[T], match: Match) -> Optional[Type[T]]: if match.group(cls._SUBMATCH_INDEX_TYPE_SUB): return cls._str_to_type(cls_in, match.group(cls._SUBMATCH_INDEX_TYPE_SUB)) else: return None
def __anonymize_selection_screenshot_filename(self, match: Match, format_str: str) -> str: # Entity IDs are 1-indexed img_id = int(match.group(1)) + 1 timestamp = match.group(2) player_id = match.group(3) anonymized_participant_id = self.__anonymize_player_id(player_id) return format_str.format(img_id, timestamp, anonymized_participant_id)
def _handle_path_param(self, match: Match) -> str: self._type_mapping[match.group(1)] = \ ResourcePath._TYPE_MAPPING.get(match.group(2), ResourcePath._TYPE_MAPPING["str"])[1] try: return f"(?P<{match.group(1)}>" + ResourcePath._TYPE_MAPPING[ match.group(2)][0] + ")" except KeyError: raise ResourcePath.UnknownPathParamTypeAnnotation(match.group(2))
def make_link(m: typing.Match) -> str: url = m.group(1) proto = m.group(2) if require_protocol and not proto: return url # not protocol, no linkify if proto and proto not in permitted_protocols: return url # bad protocol, no linkify href = m.group(1) if not proto: href = "http://" + href # no proto specified, use http if callable(extra_params): params = " " + extra_params(href).strip() else: params = extra_params # clip long urls. max_len is just an approximation max_len = 30 if shorten and len(url) > max_len: before_clip = url if proto: proto_len = len(proto) + 1 + len(m.group(3) or "") # +1 for : else: proto_len = 0 parts = url[proto_len:].split("/") if len(parts) > 1: # Grab the whole host part plus the first bit of the path # The path is usually not that interesting once shortened # (no more slug, etc), so it really just provides a little # extra indication of shortening. url = ( url[:proto_len] + parts[0] + "/" + parts[1][:8].split("?")[0].split(".")[0] ) if len(url) > max_len * 1.5: # still too long url = url[:max_len] if url != before_clip: amp = url.rfind("&") # avoid splitting html char entities if amp > max_len - 5: url = url[:amp] url += "..." if len(url) >= len(before_clip): url = before_clip else: # full url is visible on mouse-over (for those who don't # have a status bar, such as Safari by default) params += ' title="%s"' % href return u'<a href="%s"%s>%s</a>' % (href, params, url)
def _match2date(self, match: Match, reference: datetime) -> DateTimeResolutionResult: result = DateTimeResolutionResult() holiday_str = self.config.sanitize_holiday_token(match.group('holiday').lower()) year_str = match.group('year') order_str = match.group('order') year = None has_year = False if year_str: year = int(year_str) has_year = True elif order_str: swift = self.config.get_swift_year(order_str) if swift < -1: return result year = reference.year + swift has_year = True else: year = reference.year holiday_key = next(iter([key for key, values in self.config.holiday_names.items() if holiday_str in values]), None) if holiday_key: timex_str = '' value = reference func = self.config.holiday_func_dictionary.get(holiday_key) if func: value = func(year) timex_str = self.config.variable_holidays_timex_dictionary.get(holiday_key) if not timex_str: timex_str = f'-{FormatUtil.to_str(value.month, 2)}-{FormatUtil.to_str(value.day, 2)}' else: return result if value == DateUtils.min_value: result.timex = '' result.future_value = DateUtils.min_value result.past_value = DateUtils.min_value result.success = True return result if has_year: result.timex = FormatUtil.to_str(year, 4) + timex_str result.future_value = datetime(year, value.month, value.day) result.past_value = result.future_value result.success = True return result result.timex = 'XXXX' + timex_str result.future_value = self.__get_future_value(value, reference, holiday_key) result.past_value = self.__get_past_value(value, reference, holiday_key) result.success = True return result return result
def _extract(cls: Type[RegexExtractorType], match: Match) -> Dict[str, Any]: rev = match.group("revision") return { "major": int(match.group("major")), "minor": int(match.group("minor")), "build": int(match.group("build") or 0), "revision": int(rev) if rev else None, }
def callback(match: Match) -> str: name = match.group("name").lower() if name in ["here", "everyone", "channel"]: return f"<!{name}>" else: for user in self.users.values(): if user.name == name: return f"<@{user.id}>" return match.group(0)
def __anonymize_turn_screenshot_filename(self, match: Match, format_str: str) -> str: # Round IDs are 1-indexed; Each individual screenshot is actually of the next turn, so add 1 to each ID round_id = int(match.group(1)) + 2 timestamp = match.group(2) player_id = match.group(3) anonymized_participant_id = self.__anonymize_player_id(player_id) return format_str.format(round_id, timestamp, anonymized_participant_id)
def sub(m: Match) -> str: if m.group(1) == 'ref': return { 'layouts': 'https://sw.kovidgoyal.net/kitty/index.html#layouts', 'sessions': 'https://sw.kovidgoyal.net/kitty/index.html#sessions', }[m.group(2)] return str(m.group(2))
def apply(self, match: Match): operator = match.group(1) operators = ["+", "-", "*", "/"] if operator in operators: modifier = int(match.group(2)) return RollSpec(modifier=modifier, operation=operator) else: modifier = int(match.group(2)) return RollSpec(modifier=modifier, operation="+")
def transform(x: Match) -> str: prefix: str = x.group(1) first_char: str = x.group(2) if to_upper: first_char = first_char.upper() elif to_lower: first_char = first_char.lower() return prefix + first_char
def get_sub(key: Match) -> Optional[Union[str, List[str], int, float]]: filename = key.group(1) + '.config.json' keyname = key.group(2) try: with open(filename) as f: cfg = json.load(f) except FileNotFoundError: cfg = {} return cfg.get(keyname, get(keyname))
def yarn_warning_parser(match: typing.Match) -> LivyLogParseResult: """Warning message from YARN.""" time = datetime.datetime.strptime(match.group(1), "%a %b %d %H:%M:%S %z %Y") return LivyLogParseResult( created=time, level=logging.WARNING, name="YARN", message=match.group(2), )
def rfc_reference(self, match: Match, lineno: int) -> ImplicitResult: """Handle reference to a RFC (Request For Comments), e.g. `RFC 2822`__ """ text = match.group(0) if text.startswith("RFC"): rfcnum = int(match.group("rfcnum")) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text) return [nodes.reference(unescape(text, True), unescaped, refuri=ref)]
def repl(match: Match) -> str: indent = match.group("indent") newline = match.group("newline") != "" props = props_in_tag(match.group()) # Get content from file if file_name := props.get("file", None): file_path = f"src/{file_name}" print_indent(f"Inserting from file {file_path}") content = open(file_path, "r").read()
def _replacement_map_func(match_obj: Match) -> str: """Maps the replace_from match to the replace_to string. :param match_obj: The replacement character as a regex match object, to be used as a key. return: The matching value, a string from the replacements dictionary. """ # Preserve the spacing in group one, but swap the matched char(s) # with their replacement from the dict return match_obj.group(1) + replacement_dict[match_obj.group(2)]
def _from_match( cls, match: Match, *, origin: Optional[str] = None, ) -> 'Target': path = RecordPath(match.group('path')) flags_group = match.group('flags') try: flags = FlagContainer.split_flags_string( flags_group, relative_flags=False ) except FlagError as error: raise TargetError( "Error while parsing target '{}' flags." .format(match.group(0))) from error if any(flag.startswith('-') for flag in flags): raise RuntimeError return cls(path, flags, origin=origin)
def _derive_from_match( self, match: Match, *, origin: Optional[str] = None, ) -> 'Target': try: subpath = RecordPath(self.path, match.group('path')) except RecordPathError as error: raise TargetError(self, match.group(0)) from error flags_group = match.group('flags') try: flags = FlagContainer.split_flags_string(flags_group) except FlagError as error: raise TargetError(self, match.group(0)) from error subflags = self.flags.delta_mixed(flags=flags, origin=origin) return self.__class__(subpath, subflags)
def escape_repl(m: Match, prefix: str) -> str: """Translate a string escape sequence, e.g. \t -> the tab character. Assume that the Match object is from escape_re. """ seq = m.group(1) if len(seq) == 1 and seq in escape_map: # Single-character escape sequence, e.g. \n. return escape_map[seq] elif seq.startswith('x'): # Hexadecimal sequence \xNN. return chr(int(seq[1:], 16)) elif seq.startswith('u'): # Unicode sequence \uNNNN. if 'b' not in prefix: return chr(int(seq[1:], 16)) else: return '\\' + seq else: # Octal sequence. ord = int(seq, 8) if 'b' in prefix: # Make sure code is no larger than 255 for bytes literals. ord = ord % 256 return chr(ord)
def _convert_entity(m: typing.Match) -> str: if m.group(1) == "#": try: if m.group(2)[:1].lower() == 'x': return chr(int(m.group(2)[1:], 16)) else: return chr(int(m.group(2))) except ValueError: return "&#%s;" % m.group(2) try: return _HTML_UNICODE_MAP[m.group(2)] except KeyError: return "&%s;" % m.group(2)
def substitute_one(m:Match): name=m.group(1) if name not in args: return m.group() return self._to_rdf(args[name], prefixes).n3()
def from_match(cls, match: Match) -> 'RouteNode': place = match.group('place').strip(QUOTES_AND_WHITESPACE) visited = bool(match.group('strikethrough')) skipped = match.group('skipped') is not None skip_reason = match.group('skip_reason') or ('' if skipped else None) return cls(name=place, visited=visited, skip_reason=skip_reason)
def link_to(matchobj: Match) -> str: return r"%s<a href='?%s' class='nocode'>%s</a>%s" % ( matchobj.group(1), self.req_qs(link, use_stored=False), e_html(link), matchobj.group(1))