def _main (cmd) : from _TFL.Caller import Scope ### Usage example for `-regexp` and `-xformat`:: ### for f in *.tex; do ### VCMove $f $(python /swing/python/Date.py -regexp '(?P<prefix> .*)_(?P<date> \d{2}-[A-Za-z][a-z]{2}-\d{4}|\d{8})\.?(?P<ext> .*)' -xformat '%(date)s_%(prefix)s.%(ext)s' $f) ### done if cmd.regexp : regexp = Regexp (cmd.regexp, re.VERBOSE) if regexp.search (cmd.base_date) : base_date = regexp.date match_dict = regexp.groupdict () else : import sys print \ ( "`%s` doesn't match for `%s`" % (cmd.regexp, cmd.base_date) , file = sys.stderr ) sys.exit (9) else : base_date = cmd.base_date match_dict = {} base_date = Date.from_string (base_date) if cmd.offset : base_date += cmd.offset if cmd.delta_to : print ((base_date - cmd.delta_to).days) else : date = base_date.formatted (cmd.format) print (cmd.xformat % Scope (globs = match_dict, locls = vars ()))
def _main(cmd): from _TFL.Caller import Scope ### Usage example for `-regexp` and `-xformat`:: ### for f in *.tex; do ### VCMove $f $(python /swing/python/Date.py -regexp '(?P<prefix> .*)_(?P<date> \d{2}-[A-Za-z][a-z]{2}-\d{4}|\d{8})\.?(?P<ext> .*)' -xformat '%(date)s_%(prefix)s.%(ext)s' $f) ### done if cmd.regexp: regexp = Regexp(cmd.regexp, re.VERBOSE) if regexp.search(cmd.base_date): base_date = regexp.date match_dict = regexp.groupdict() else: import sys print \ ( "`%s` doesn't match for `%s`" % (cmd.regexp, cmd.base_date) , file = sys.stderr ) sys.exit(9) else: base_date = cmd.base_date match_dict = {} base_date = Date.from_string(base_date) if cmd.offset: base_date += cmd.offset if cmd.delta_to: print((base_date - cmd.delta_to).days) else: date = base_date.formatted(cmd.format) print(cmd.xformat % Scope(globs=match_dict, locls=vars()))
def _phone_multi_regexp (tail = "") : return Multi_Regexp \ ( Regexp ( r"^" + r"(?:" + _phone_cc_pat + " +|0 *)?" + _phone_ndc_pat + ((r" " + tail) if tail else "") + r"$" , re.UNICODE ) , Regexp ( r"^" + r"(?:" + _phone_cc_pat + "|0)? *" + r"\(" + _phone_ndc_pat + r"\) *" + tail + r"$" , re.UNICODE ) , Regexp ( r"^" + r"(?:" + _phone_cc_pat + "|0)? *" + r"/" + _phone_ndc_pat + r"/" + ("" if tail else "?") + " *" + tail + r"$" , re.UNICODE ) , Regexp ( r"^" + r"(?:" + _phone_cc_pat + "|0)? *" + r"-" + _phone_ndc_pat + r"-" + ("" if tail else "?") + " *" + tail + r"$" , re.UNICODE ) , Regexp ( r"^" + r"(?:" + _phone_cc_pat + "|0)? *" + ((r" +" + tail) if tail else "") + r"$" , re.UNICODE ) )
class _Date_Arg_(TFL.CAO.Str): """Argument or option with a (calendary) date value""" _real_name = "Date" _CAL_Type = Date _delta_pat = Regexp("^[-+]") def cook(self, value, cao=None): T = self._CAL_Type if value == "now": result = T() elif value: if self._delta_pat.match(value): import _CAL.Relative_Delta delta = CAL.Relative_Delta.from_string(value.lstrip("+")) now = T() result = now + delta if type(result) is not T: raise TypeError \ ( "Wrong delta %r forces Date_Time '%s', " "need Date instead" % (value, result) ) else: result = T.from_string(value) else: result = None return result
def __init__ (self, pattern, flags = 0, quote = 0) : if isinstance (pattern, Regexp) : regexp = pattern else : regexp = Regexp (pattern, flags, quote) self._regexp = regexp self.__super.__init__ (self.match)
class _Statement_(TFL.SDG.C.Node): """Model simple statement""" cgi = TFL.SDG.C.Node.Body trailing_semicol_pat = Regexp(r"""; *$""") scope = TFL.SDG.C.C children_group_names = \ ( TFL.SDG.C.Node.Body , )
class String_Swapper : """Swaps all occurences of two strings in some text""" def __init__ (self, s1, s2) : self.s1 = s1 self.s2 = s2 self._map = { s1 : s2, s2 : s1 } self._pat = Regexp ("(%s|%s)" % (re.escape (s1), re.escape (s2))) # end def __init__ def __call__ (self, text) : """Swap all occurences of `self.s1` and `self.s2` in `text`""" return self._pat.sub (self._replace, text) # end def __call__ def _replace (self, match) : return self._map [match.group (1)]
class String_Swapper: """Swaps all occurences of two strings in some text""" def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 self._map = {s1: s2, s2: s1} self._pat = Regexp("(%s|%s)" % (re.escape(s1), re.escape(s2))) # end def __init__ def __call__(self, text): """Swap all occurences of `self.s1` and `self.s2` in `text`""" return self._pat.sub(self._replace, text) # end def __call__ def _replace(self, match): return self._map[match.group(1)]
def __init__ (self, s1, s2) : self.s1 = s1 self.s2 = s2 self._map = { s1 : s2, s2 : s1 } self._pat = Regexp ("(%s|%s)" % (re.escape (s1), re.escape (s2)))
class _XML_Node_(TFL.SDG.Node): """Model a node of a XML document""" _real_name = "Node" attr_names = () attr_name_translate = {} base_indent = " " encoding = "utf-8" init_arg_defaults = dict \ ( description = None , ) _autoconvert = dict \ ( description = lambda s, k, v : s._convert (v, TFL.SDG.XML.Comment) , ) _list_of_formats = TFL.SDG.Node._list_of_formats + \ ( "xml_format", ) _xml_name_pat = Regexp("[A-Za-z_:][-_:.A-Za-z0-9]*") _special_char_pat = Regexp \ ("[<>]|(&(?! %s;))" % _xml_name_pat.pattern, re.X) _special_quot_pat = Regexp("&(amp|lt|gt|apos|quot);") _wordsep_pat = Regexp(r'(\s+)') def as_xml(self, base_indent=None, **kw): return self.formatted("xml_format", base_indent=base_indent, **kw) # end def as_xml def write_to_xml_stream(self, stream=None, gauge=None, **kw): """Write `self` and all elements in `self.children` to `stream`. """ self._write_to_stream(self.as_xml(**kw), stream, gauge) # end def write_to_xml_stream def _attr_iter(self): attr_values = \ ( [(a, getattr (self, a)) for a in self.attr_names] + sorted (pyk.iteritems (self.x_attrs)) ) if attr_values: translate = lambda a: self.attr_name_translate.get(a, a) for a, v in attr_values: if v is not None: k = translate(a) v = str(v).replace("'", """) yield u'''%s="%s"''' % (k, v) # end def _attr_iter def _attr_values(self, *args, **kw): ow = kw["output_width"] ia = kw["indent_anchor"] ht = kw["ht_width"] max_width = max(ow - ia - ht - 4, 4) pieces = [] width = 0 for attr_value in self._attr_iter(): attr_len = len(attr_value) if pieces and (width + attr_len) > max_width: yield " ".join(pieces) pieces = [] width = 0 width += attr_len + bool(pieces) pieces.append(attr_value) if pieces: yield " ".join(pieces) # end def _attr_values def _checked_xml_name(self, value): if not self._xml_name_pat.match(value): raise ValueError \ ( "`%s` doesn not match %s" % (value, self._xml_name_pat.pattern) ) return value # end def _checked_xml_name def _insert(self, child, index, children, delta=0): if child is not None: if isinstance(child, pyk.string_types): import _TFL._SDG._XML.Char_Data child = TFL.SDG.XML.Char_Data(child) self.__super._insert(child, index, children, delta) # end def _insert def _special_char_replacer(self, match): return { "&": "&", "<": "<", ">": ">", "'": "'", '"': """ }[match.group(0)] # end def _special_char_replacer def _special_quot_replacer(self, match): return { "&": "&", "<": "<", ">": ">", "'": "'", """: '"' }[match.group(0)]
def _main (cmd) : cmd_path = list (cmd.path or []) replacer = Re_Replacer (r"\.py[co]", ".py") a = cmd.argv [0] et = "" one_arg_p = len (cmd.argv) == 1 and not sos.path.isdir (a) if one_arg_p and not cmd.Extra_Interpreters : f = Filename (a) m = f.base py_version = " [py %s]" % \ ".".join (str (v) for v in sys.version_info [:3]) sys.path [0:0] = cmd_path mod_path = f.directory if f.directory else "./" if sos.path.exists \ (Filename ("__init__.py", default_dir = mod_path).name) : sys.path [0:0] = [sos.path.join (mod_path, "..")] sys.path [0:0] = [mod_path] flags = doctest.NORMALIZE_WHITESPACE if not cmd.nodiff : flags |= doctest.REPORT_NDIFF try : logging.disable (logging.WARNING) start = _timer () module = __import__ (m) module.expect_except = TFL.CAO.expect_except cases = len (getattr (module, "__test__", ())) or 1 f, t = doctest.testmod \ ( module , verbose = cmd.verbose , optionflags = flags ) exec_time = _timer () - start except KeyboardInterrupt : raise except Exception as exc : exec_time = _timer () - start if cmd.timing : et = " in %7.5fs" % (exec_time, ) msg = format_x % (replacer (a), py_version, exc, et) print (msg, file = sys.stderr) raise else : format = format_f if f else format_s if cmd.timing : et = " in %7.5fs" % (exec_time, ) print (replacer (format % TFL.Caller.Scope ()), file = sys.stderr) else : py_executables = [sys.executable] + list (cmd.Extra_Interpreters) py_version = "" head_pieces = sos.python_options () + \ [ __file__ , "-path %r" % (",".join (cmd_path), ) if cmd_path else "" ] for opt in ("nodiff", "timing", "verbose") : if getattr (cmd, opt) : head_pieces.append ("-" + opt) head = " ".join (hp for hp in head_pieces if hp) if cmd.summary : run_cmd = run_command_with_summary else : run_cmd = run_command if cmd.RExclude : x_pat = Regexp (cmd.RExclude) exclude = x_pat.search elif cmd.exclude : exclude = lambda a : fnmatch.fnmatch (a, cmd.exclude) else : exclude = lambda a : False def run_mod (a) : if exclude (a) : summary.excluded.append (a) print ("%s excluded" % (a, )) else : summary.modules += 1 for pyx in py_executables : run_cmd ("%s %s %s" % (pyx, head, a)) def run_mods (d) : for f in sorted (sos.listdir_exts (d, ".py")) : if has_doctest (f) : run_mod (f) if cmd.transitive : from _TFL.subdirs import subdirs def run_dir (d) : run_mods (d) for s in subdirs (d) : run_dir (s) else : run_dir = run_mods start = _timer () for a in cmd.argv : if sos.path.isdir (a) : run_dir (a) else : if has_doctest (a) : run_mod (a) if cmd.summary : format = format_f if summary.failed else format_s if cmd.timing : et = " in %7.5fs" % (_timer () - start, ) print ("=" * 79, file = sys.stderr) print \ ( format % TFL.Caller.Scope ( f = summary.failed , module = TFL.Record (__file__ = " ".join (cmd.argv)) , t = summary.total , cases = summary.cases , et = et ) , "[%s/%s modules fail]" % (len (summary.failures), summary.modules) , file = sys.stderr ) print \ ( " %s" % ("\n ".join ("%-68s : %s" % f for f in summary.failures)) , file = sys.stderr ) if summary.excluded : print \ (" %s excluded" % (", ".join (summary.excluded), ) , file = sys.stderr )
import _TFL.Caller import _TFL.CAO import _TFL.Package_Namespace from timeit import default_timer as _timer import doctest import logging import sys import subprocess import fnmatch TFL.Package_Namespace._check_clashes = False ### avoid spurious ImportErrors _doctest_pat = Regexp (r"^( *>>> |__test__ *=)", re.MULTILINE) summary = TFL.Record \ ( cases = 0 , excluded = [] , failed = 0 , failures = [] , modules = 0 , total = 0 ) format_f = """%(module.__file__)s fails %(f)s of %(t)s doc-tests in %(cases)s test-cases%(et)s%(py_version)s""" format_s = """%(module.__file__)s passes all of %(t)s doc-tests in %(cases)s test-cases%(et)s%(py_version)s""" format_x = """%s [py %s] raises exception `%r` during doc-tests%s""" sum_pat = Regexp \ ( "(?P<module>.+?) (?:fails (?P<failed>\d+)|passes all) of "
class A_Time_List(_A_Typed_List_): """List of times.""" typ = _("Time_List") C_range_sep = Regexp(r"(?: ?(?:-|–|\.\.) ?)") C_Type = A_Time
class Anlagen_Entry (_Mixin_, _Entry_) : cat = "Normal" rate_pattern = r"(?P<rate> [-+*/().0-9\s]+)" first_rate_pat = Regexp (rate_pattern, re.X) later_rate_pat = Regexp \ ( r"(?P<year> \d\d (?: \d\d)?) \s* : \s* " + rate_pattern , re.X ) _cat_pat = Regexp (r"C\[(?P<cat> [^]]+)\]", re.VERBOSE) def __init__ (self, line, anlagenverzeichnis) : try : ( self.desc, self.supplier, self.flags , self.birth_date, self.a_value, self.afa_spec, ifb , self.death_date ) = split_pat.split (line, 8) except ValueError as exc : print (line) raise death, _, d_reason = split_hst (self.death_date, "#") final = "31.12.2037" self.p_konto = self._get_p_konto (self.flags) self.birth_time = Date (self.birth_date) self.death_time = Date (death.strip () or final) self.death_reason = d_reason.strip () if d_reason else "" self.alive = self.death_time > anlagenverzeichnis.tail_time self.contemporary = \ ( self.birth_time <= anlagenverzeichnis.tail_time and self.death_time >= anlagenverzeichnis.head_time ) if int (self.death_time.year) < int (anlagenverzeichnis.year) : self._setup_dates (self.death_time.year) else : self._setup_dates (anlagenverzeichnis.year) self.half_date = "1.7.%s" % (self.birth_time.year, ) if "~" in self.flags : self.half_date = "1.1.%s" % (self.birth_time.year + 1, ) self.half_time = Date (self.half_date) self.desc = desc_cleaner (self.desc) currency_match = currency_pat.search (self.a_value) a_value = self.a_value source_currency = anlagenverzeichnis.source_currency if currency_match : source_currency = EU_Currency.Table [currency_match.group (1)] a_value = currency_pat.sub ("", a_value) if EUC.target_currency is not ATS : self.zero = source_currency (0.0) else : self.zero = source_currency (1.0) self.source_currency = source_currency self.birth_value = source_currency (TFL.r_eval (a_value)) self.new_value = source_currency (0.0) self.out_value = source_currency (0.0) if "G" in self.flags : self.ifb = FBiG (self, ifb, source_currency) else : self.ifb = IFB (self, ifb, source_currency) self._set_cat (self.flags) # end def __init__ @property def active (self) : return \ ( self.contemporary and (self.current_depreciation > 0 or self.base_rate == 0) ) # end def active def evaluate (self) : self._calc_rates () self.current_depreciation = \ self.birth_value * (self.current_rate / 100.0) if "=" not in self.flags : self.head_value = max \ ( self.birth_value * ((100.0 - self.past_total_rate) / 100.) , self.zero ) self.tail_value = self.head_value - self.current_depreciation if self.tail_value < self.zero : self.tail_value = self.zero self.current_depreciation -= self.zero else : self.head_value = self.tail_value = self.birth_value if self.birth_time >= self.head_time : self.head_value = self.source_currency (0.0) self.new_value = self.birth_value if not self.alive : self.out_value = self.tail_value self.tail_value = self.source_currency (0.0) if self.tail_value.target_currency.to_euro_factor != 1.0 : self.birth_value = self.birth_value.rounded_as_target () self.head_value = self.head_value.rounded_as_target () self.tail_value = self.tail_value.rounded_as_target () self.new_value = self.new_value.rounded_as_target () self.out_value = self.out_value.rounded_as_target () self.current_depreciation = \ self.current_depreciation.rounded_as_target () if self.ifb : self.ifb.round () # end def evaluate def _calc_rates (self) : rates = [x.strip () for x in self.afa_spec.split (",")] first_rate = rates [0] first_rate_pat = self.first_rate_pat later_rate_pat = self.later_rate_pat if not first_rate_pat.match (first_rate) : raise ValueError \ ("%s doesn't match a depreciation rate" % (first_rate, )) later_rates = [] for r in rates [1:] : if not later_rate_pat.match (r) : raise ValueError \ ("%s doesn't match a depreciation rate" % (r, )) y = Time_Tuple (later_rate_pat.year).year later_rates.append ((y, TFL.r_eval (later_rate_pat.rate) * 1.0)) y_rate = self.base_rate = TFL.r_eval (first_rate_pat.rate) * 1.0 if later_rates : later_rates.append ((self.target_year, later_rates [-1] [1])) else : later_rates.append ((self.target_year, y_rate)) y_rates = self.y_rates = \ [y_rate * ((0.5, 1.0) [self.birth_time < self.half_time])] if self.birth_time < self.head_time : current_year = self.birth_time.year + 1 for target_year, next_rate in later_rates : while current_year < target_year : y_rates.append (y_rate) current_year += 1 y_rate = self.base_rate = next_rate y_rates.append \ (y_rate * ((0.5, 1.0) [self.midd_time < self.death_time])) self.current_rate = y_rates [-1] past_total_rate = 0 for y_rate in y_rates [:-1] : past_total_rate += y_rate self.past_total_rate = min (past_total_rate, 100.0) if self.past_total_rate + self.current_rate > 100.0 : self.current_rate = 100.0 - self.past_total_rate # end def _calc_rates def _set_cat (self, flags) : pat = self._cat_pat if pat.search (flags) : self.cat = pat.cat
from _TFL import TFL from _TFL.pyk import pyk import _TFL._Meta.Object import _TFL._SDG import _TFL.Generators from _TFL.Record import Record from _TFL.predicate import relax, split_hst from _TFL.Regexp import * import sys import pdb _percent_pat = Regexp("(?<!%)%(?!%)") class _Formatter_(TFL.Meta.Object): """Root class of SDG formatters""" def __init__(self, indent_level, format_line): self.indent_level = indent_level self.format_line = format_line # end def __init__ def __repr__(self): return "%s %s> '%s'" % \ (self.kind, self.indent_level, self.format_line) # end def __repr__
def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 self._map = {s1: s2, s2: s1} self._pat = Regexp("(%s|%s)" % (re.escape(s1), re.escape(s2)))
# as metaclass # ««revision-date»»··· #-- from __future__ import absolute_import, division, print_function, unicode_literals from _TFL import TFL from _TFL.pyk import pyk import _TFL._Meta.M_Auto_Update_Combined import _TFL._Meta.M_Class import _TFL._SDG import _TFL._SDG.Formatter from _TFL.Regexp import * _indent_pat = Regexp (r">*") class M_Node (TFL.Meta.M_Auto_Update_Combined, TFL.Meta.M_Class) : """Meta class for SDG.Node classes""" __id = 0 _attrs_to_update_combine = ("init_arg_defaults", "_autoconvert") def __init__ (cls, name, bases, dict) : cls.__m_super.__init__ (name, bases, dict) cls._normalize_formats () # end def __init__ def __call__ (cls, * args, ** kw) : result = cls.__new__ (cls, * args, ** kw) cls.__id += 1
class A_Date_Time(_A_Date_): """Date-time value.""" example = "2010-10-10 06:42" typ = _("Date-Time") P_Type = datetime.datetime Q_Name = "DATE_TIME" syntax = _("yyyy-mm-dd hh:mm:ss, the time `hh:mm:ss` is optional") ui_length = 22 rfc3339_format = "%Y-%m-%dT%H:%M:%S" input_formats = tuple \ ( itertools.chain ( * ( (f + " %H:%M:%S", f + " %H:%M", f) for f in A_Date.input_formats ) ) ) + (rfc3339_format, ) utcoffset_fmt = "%+03d:%02d" utcoffset_pat = Regexp(r" *[-+](?P<oh>\d{2}):(?P<om>\d{2}) *$") _tuple_len = 6 ### plain old inheritance doesn't work here because ### _M_Structured_ doesn't support that _Attributes = _A_Date_._Attributes.__class__ \ ( "_Attributes" , (_A_DT_._Attributes, ) , dict (_A_Date_._Attributes.__dict__, ** _A_Time_._Attributes.__dict__) ) def as_rest_cargo_ckd(self, obj, *args, **kw): ### formatted according to ISO 8601, RFC 3339 value = self.kind.get_value(obj) if value is not None: offset = TFL.user_config.time_zone.utcoffset(value) v = value + offset oh, os = divmod(offset.total_seconds(), 3600) om = os // 60 fmt = self.rfc3339_format + (self.utcoffset_fmt % (oh, om)) return v.strftime(fmt) # end def as_rest_cargo_ckd @TFL.Meta.Class_and_Instance_Method def as_string(soc, value): if value is not None: ### In Python 3.5, `bool (t)` is never False -> compare to `t.min` v = value + TFL.user_config.time_zone.utcoffset(value) t = v.time() fmt = A_Date.input_formats [0] if t == t.min \ else soc._output_format () result = v.strftime(fmt) if result.endswith(":00"): result = result[:-3] return result return "" # end def as_string @TFL.Meta.Class_and_Instance_Method def cooked(soc, value): if not isinstance(value, datetime.datetime): if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) elif isinstance(value, pyk.string_types): try: value = soc._from_string(value) except ValueError: raise TypeError \ (_T ("Date/time expected, got %r") % (value, )) else: raise TypeError(_T("Date/time expected, got %r") % (value, )) return value # end def cooked @classmethod def now(cls): return datetime.datetime.utcnow() # end def now @TFL.Meta.Class_and_Instance_Method def value_range_delta(self, obj): from _CAL.Delta import Date_Time_Delta return Date_Time_Delta(1) # end def value_range_delta @TFL.Meta.Class_and_Instance_Method def _from_string(soc, s, obj=None): utcoffset = None utcoffset_pat = soc.utcoffset_pat if utcoffset_pat.search(s): oh = int(utcoffset_pat.oh) om = int(utcoffset_pat.om) s = s[:utcoffset_pat.start()] utcoffset = datetime.timedelta(0, (oh * 60 + om) * 60) result = super(A_Date_Time, soc)._from_string(s, obj) if utcoffset is None: utcoffset = TFL.user_config.time_zone.utcoffset(result) result -= utcoffset return result
from _CAL.Appointment import prio_pat, time_pat import _CAL.Appointment import _CAL.Date import _CAL.Date_Time import _CAL.Year import _TFL._Meta.Object import _TFL.CAO from _TFL.Filename import * from _TFL.predicate import * from _TFL.pyk import pyk from _TFL.Regexp import * from _TFL import sos day_sep = Regexp("^#", re.M) day_pat = Regexp(r"^ (?P<day>\d{4}/\d{2}/\d{2}) ") app_date_pat = Regexp \ ( r"(?P<date>" r"(?:" r"(?:" r"(?P<day> -? \d{1,2}) \." r"(?: (?P<month> \d{1,2}) \." r" (?: (?P<year> \d{4}))?" r")?" r")" r"|" r"(?:" r"(?P<weekday> Mon|Tue|Wed|Thu|Fri|Sat|Sun)" r"(?: [.#] (?P<week> [0-5]?\d))?" r")"
, re.X ) YYYYMMDD_pat = Regexp \ ( r"(?P<year> \d{4,4})" + r"(?P<month> \d{2,2})" + r"(?P<day> \d{2,2})" + _time_pat + r"$" , re.X ) _day_patterns = \ ( Regexp ( _dd_month_pat + r"[.]?" + _time_pat + r"$" , re.X | re.I ) , Regexp ( _dd_month_pat + r"\2" + r"(?P<year> \d{4,4})" + _time_pat + r"$" , re.X | re.I ) , Regexp ( _month_dd_pat + r"$" , re.X | re.I
from _PMA import Lib import _TFL.Filename import _TFL.sos from _TFL.pyk import pyk from _TFL.Regexp import * import mimetypes import subprocess default_type = "application/octet-stream" unencoded_mime_types = ("text/plain", "message/rfc822") _sep = TFL.sos.sep file__mime_pat = Regexp(r"^[^:]+: (?P<typ>[^;]+); charset=(?P<enc>.+)") mh_pat = Regexp(r"%sMH%s.*%s\d+$" % (_sep, _sep, _sep)) extension_map = {} def add_extensions(typ, enc, *extensions): for ext in extensions: extension_map[ext] = (typ, enc) # end def add_extensions add_extensions \ ("text/plain", None, ".pl", ".c", ".cc", ".h", ".el", ".lse", ".txt") add_extensions \
from _TFL import sos import _TFL.Accessor import _TFL.Ascii import _TFL.Caller import _TFL.CAO import _TFL.FCM import _TFL.Filename import _TFL._Meta.M_Class import _TFL._Meta.Property import textwrap import time import weakref _ws_pat = Regexp(r"\s+") now = time.time() def decoded_header(header): result = [] if header: for p, c in Lib.decode_header(header): enc = c or PMA.default_encoding if enc == "unknown": enc = PMA.default_encoding result.append(pyk.decoded(p, enc)) result = " ".join(result) return result
class _A_Time_(_A_DT_): """Common base class for time-valued attributes of an object.""" example = "06:42" completer = MOM.Attr.Completer_Spec(2) typ = _("Time") P_Type = datetime.time Q_Ckd_Type = MOM.Attr.Querier.Time Q_Name = "TIME" ui_length = 8 _midnight_pat = Regexp(r"^24(:00){0,2}$") _tuple_len = 6 _tuple_off = 3 class _Attributes(_A_DT_._Attributes): class hour(A_Int): """Hour specified by time.""" kind = Attr.Query query = Q.hour # end class hour class minute(A_Int): """Minute specified by time.""" kind = Attr.Query query = Q.minute # end class minute class second(A_Int): """Second specified by time.""" kind = Attr.Query query = Q.second # end class second # end class _Attributes class Pickler(TFL.Meta.Object): Type = datetime.time @classmethod def as_cargo(cls, attr_kind, attr_type, value): return value # end def as_cargo @classmethod def from_cargo(cls, scope, attr_kind, attr_type, cargo): if cargo is not None: if isinstance(cargo, datetime.datetime): cargo = cargo.time() return cargo # end def from_cargo # end class Pickler def as_rest_cargo_ckd(self, obj, *args, **kw): value = self.kind.get_value(obj) if value is not None: return pyk.text_type(value.strftime("%H:%M:%S")) # end def as_rest_cargo_ckd @TFL.Meta.Class_and_Instance_Method def as_string(soc, value): if value is not None and value == soc.P_Type.max: result = "24:00" else: ### when called for the class, `soc.__super` doesn't ### work while `super (_A_Time_, soc)` does result = super(_A_Time_, soc).as_string(value) if result.endswith(":00"): result = result[:-3] return result # end def as_string @TFL.Meta.Class_and_Instance_Method def cooked(soc, value): if isinstance(value, datetime.datetime): value = value.time() elif isinstance(value, pyk.string_types): try: value = soc._from_string(value) except ValueError: raise TypeError(_T("Time expected, got %r") % (value, )) elif not isinstance(value, datetime.time): raise TypeError(_T("Time expected, got %r") % (value, )) return value # end def cooked @classmethod def now(cls): return datetime.datetime.now().time() # end def now @TFL.Meta.Class_and_Instance_Method def value_range_delta(soc, obj): from _CAL.Delta import Time_Delta return Time_Delta(1) # end def value_range_delta @TFL.Meta.Class_and_Instance_Method def _from_string(soc, value, obj=None): try: return super(_A_Time_, soc)._from_string(value, obj) except Exception: if soc._midnight_pat.match(value): return soc.P_Type.max raise
class Alias_Mgr (TFL.Meta.Object) : """Model a collection of aliases""" _alias_sep = Regexp ("\n(?!\\s)") ### a new-line followed by non-whitespace _alias_pat = Regexp \ ( r"(?P<key> [-a-zA-Z0-9.]+)" r"\s* : \s*" r"(?P<value> .*)" , re.VERBOSE | re.DOTALL ) def __init__ (self, * files) : self.aliases = {} for f in files : self.add_alias_file (f) # end def __init__ def add_alias_buffer (self, buffer) : aliases = self.aliases pat = self._alias_pat for entry in self._alias_sep.split (buffer) : entry = entry.strip () if entry : if pat.match (entry) : key = pat.key vals = filter \ (None, [v.strip () for v in pat.value.split (",")]) if vals : aliases [key] = Alias (key, vals) # end def add_alias_buffer def add_alias_file (self, name) : path = sos.expanded_path (name) if sos.path.exists (path) : with open (path) as f : buffer = pyk.decoded (f.read ()) self.add_alias_buffer (buffer) # end def add_alias_file def get (self, key, default = None) : try : return self [key] except KeyError : return default # end def get def transitive_translation (self, alias) : """Return transitive translation of `alias`""" result = set () aliases = self.aliases for v in alias.email_addresses () : if v in aliases : result.update (self.transitive_translation (aliases [v])) else : result.add (v) return result # end def transitive_translation def __getitem__ (self, key) : map = self.aliases rn, ea = Lib.parseaddr (key) l, s, d = split_hst (ea, "@") if s : try : return map [l] except KeyError : pass return map [ea]
from _CAL import CAL from _TFL import TFL from _TFL.Regexp import * from _TFL._Meta.totally_ordered import totally_ordered import _TFL._Meta.Object time_pat = Regexp \ ( r"(?P<time> " r"(?: (?P<hh_head> \d{1,2}) (?: : (?P<mm_head> \d{2}))? )?" r"(?: -(?P<hh_tail> \d{1,2}) (?: : (?P<mm_tail> \d{2}))? )?" r")" , re.VERBOSE ) prio_pat = Regexp (r"(?P<prio> [A-Za-z0-9 ])", re.VERBOSE) entry_sep = Regexp ("^>", re.MULTILINE) entry_pat = Regexp \ ( r"[ ]+" + time_pat.pattern + r"?" + r"[ ]+" + prio_pat.pattern + r"[ ]<[ ]" + r"\s*" + r"(?P<activity> .*)" + "$" , re.VERBOSE | re.MULTILINE | re.DOTALL ) @totally_ordered class Appointment (TFL.Meta.Object) :