def test_to_String(self): """Test the to_String() method.""" assert to_String(1) == "1", to_String(1) assert to_String([1, 2, 3]) == str([1, 2, 3]), to_String([1, 2, 3]) assert to_String("foo") == "foo", to_String("foo") s1 = UserString('blah') assert to_String(s1) == s1, s1 assert to_String(s1) == 'blah', s1 class Derived(UserString): pass s2 = Derived('foo') assert to_String(s2) == s2, s2 assert to_String(s2) == 'foo', s2 if HasUnicode: s3 = UserString(unicode('bar')) assert to_String(s3) == s3, s3 assert to_String(s3) == unicode('bar'), s3 assert isinstance(to_String(s3), unicode), \ type(to_String(s3)) if HasUnicode: s4 = unicode('baz') assert to_String(s4) == unicode('baz'), to_String(s4) assert isinstance(to_String(s4), unicode), \ type(to_String(s4))
def __init__(self, value: Any = None, id: Optional[UID] = None): if value is None: value = "" UserString.__init__(self, value) self._id: UID = id if id else UID()
def _str_constructor(loader, node): # store location of multiline string if node.style != '|': return loader.construct_scalar(node) obj = UserString(loader.construct_scalar(node)) obj.start_mark = node.start_mark obj.end_mark = node.end_mark return obj
class TestString(unittest.TestCase): @parameterized.expand([ ('', '', True), (' ', ' ', True), ('string', 'string', True), ('string', 'other_string', False), ('string', UserString('string'), True), (UserString('string'), UserString('other_string'), False), ]) def test_handle_strings(self, item1, item2, expected): result = approx(item1, item2) self.assertEqual(result, expected)
def run_graphite(args, *a): """ Create strings from running real text strings through Graphite """ logging.info("Running graphite on input data") strings = [] for inf in args.input: for d in args.directory: fname = os.path.join(d, inf) if not os.path.exists(fname): continue if fname.endswith(".xml") or fname.endswith(".ftml"): strings.extend(parseftml(fname, feats=args.feats)) else: with open(fname, "r") as fh: strings.extend([ UserString(x.strip()) for l in fh.readlines() for x in l.split() ]) if args.rtl or args.feats is not None: for s in strings: s.rtl = args.rtl if args.feats is not None: s.feats = args.feats break if args.jobs == 1: grfont = GrFont(args.font, 1 if args.rtl else 0) res = [makestring(grfont, s) for s in strings] else: pool = Pool(processes=args.jobs, initializer=initprocess, initargs=[args.font, args.rtl]) res = list(pool.imap_unordered(proc_makestring, strings)) return (res, )
class C(metaclass=MetaContainer): element_class = UserString # element_name = string c = C(strings=[ UserString('I'), UserString('love'), UserString('you') ], lasting='for ever') assert hasattr(c, 'strings') assert len(c) == c.n_elements for a in c: assert isinstance(a, UserString) c.regester_map('upper') assert hasattr(c, 'upper')
def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=DEFAULTS['default'], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source']): UserString.__init__(self, '') GenericOption.initialize(self, locals()) self.data = self.data or ''
def parseftml(fnameorstr, feats=None): """parse an FTML document into a list ftmlstrings Args: root : ElementTree Element object representing FTML document Returns: list of ftmlstring objects, each representing one <test>, in document order Within <string> elements it removes <em> markup and converts backslash-u notation to Unicode characters. <testgroup> divisions are ignored and tests from all <testgroups> are collected together. """ strs = [] if os.path.exists(fnameorstr): root = et.parse(fnameorstr) else: root = et.fromstring(fnameorstr) for test in root.findall('.//test'): s = "".join(test.find('string').itertext()) s = re.sub(r'\\u([a-fA-F0-9]{4,6})', lambda m: chr(int(m.group(1), 16)), s) stylename = test.get('stylename', None) if stylename is None: lfeats = None lang = None else: style = root.find(f'./head/styles/style[@name="{stylename}"]') lfeats = style.get('feats', None) if lfeats is not None: lfeats = dict(parseFeat(t.strip()) for t in lfeats.split(',')) if feats is not None: lfeats.update(feats) elif feats is not None: lfeats = feats else: lfeats = None lang = style.get('lang', None) rtl = test.get('rtl', "").lower() in ("true", "1") for w in s.split(): s = UserString(w) s.feats = lfeats s.lang = lang s.rtl = rtl strs.append(s) return strs
def __init__(self, mimeType): UserString.__init__(self, mimeType) self._type = None self._subtype = None self._structure = None slashIndex = mimeType.find('/') if (-1 < slashIndex): self._type = mimeType[:slashIndex] mimeType = mimeType[slashIndex + 1:] plusIndex = mimeType.find('+') if (-1 < plusIndex): self._subtype = mimeType[:plusIndex] self._structure = mimeType[plusIndex + 1:] else: self._structure = mimeType else: self._type = mimeType
def remove_empty_line(content: str): new_rss = UserString("") for line in content.split("\n"): if not line.strip(): continue if "mvn" in line: new_rss += line.strip() else: new_rss += line.rstrip() new_rss += "\n" return str(new_rss)
def test_is_String(self): assert is_String("") assert is_String(UserString('')) try: class mystr(str): pass except TypeError: pass else: assert is_String(mystr('')) assert not is_String({}) assert not is_String([]) assert not is_String(())
def test_integration_validate_identifier_user_string(self): try: validate_identifier(UserString('bar')) except TypeError as e: self.fail( "'validate_identifier()' raised TypeError unexpectedly! %s" % e ) except SyntaxError as e: self.fail( "'validate_identifier()' raised SyntaxError unexpectedly! %s" % e )
def test_is_String(self): assert is_String("") if HasUnicode: exec "assert is_String(u'')" assert is_String(UserString('')) try: class mystr(str): pass except TypeError: pass else: assert is_String(mystr('')) assert not is_String({}) assert not is_String([]) assert not is_String(())
def add_package_tag(content: str): new_ss = UserString("") for line in content.split("\n"): is_pkg = True if re.search(r"(mvn:)", line) is not None: is_pkg = False if re.search(r"(class:)", line) is not None: is_pkg = False if re.search(r"(mtd:)", line) is not None: is_pkg = False if is_pkg: p = re.compile(r"\s{12}(?P<package>[a-z0-9.:]*)", re.VERBOSE) res = p.sub(r" package: \g<package>\n", line) new_ss += res else: new_ss += line new_ss += "\n" return str(new_ss)
def test_to_String(self): """Test the to_String() method.""" assert to_String(1) == "1", to_String(1) assert to_String([1, 2, 3]) == str([1, 2, 3]), to_String([1, 2, 3]) assert to_String("foo") == "foo", to_String("foo") assert to_String(None) == 'None' # test low level string converters too assert to_str(None) == 'None' assert to_bytes(None) == b'None' s1 = UserString('blah') assert to_String(s1) == s1, s1 assert to_String(s1) == 'blah', s1 class Derived(UserString): pass s2 = Derived('foo') assert to_String(s2) == s2, s2 assert to_String(s2) == 'foo', s2
('', ), {}, ), ( "List", ([], ), {}, ), ( "Dict", ({}, ), {}, ), ( "UserString", (UserString(''), ), {}, ), ( "UserList", (UserList([]), ), {}, ), ( "UserDict", (UserDict({}), ), {}, ), ( "Object", (A(), ),
# https://docs.python.org/3/library/collections.html#collections.UserDict from collections import UserDict, UserList, UserString user_dict = UserDict({'name': 'zlikun', 'age': 120}) # <class 'collections.UserDict'> {'name': 'zlikun', 'age': 120} print(type(user_dict), user_dict) user_list = UserList(range(4)) # <class 'collections.UserList'> [0, 1, 2, 3] print(type(user_list), user_list) user_string = UserString('hello') # <class 'collections.UserString'> hello print(type(user_string), user_string)
# for k, v in kwargs.items(): # setattr(o, k, v) # if args: # o = super(MetaArray, self).__new__(args, dtype=self.element_class) # return o class MetaSet(MetaContainer): pass if __name__ == '__main__': from collections import UserString class C(metaclass=MetaContainer): element_class = UserString # element_name = string c = C(strings=[UserString('I'), UserString('love'), UserString('you')], lasting='for ever') print(c.element_class) print(C.strings) print(c.strings) print(c.lasting) print(c.elements) print(c.n_elements) print(c[1]) for a in c: print(a) c.regester_map('upper') print(c.upper())
def test_strings_are_not_list_like(self): for thing in ['string', UserString('user')]: assert_equal(is_list_like(thing), False, thing)
class SliceInfo(object): '''Represents a single slice on a partition or slice.''' MAX_SLICES = 8 MAX_VTOC = DiskSpace("2tb") BACKUP_SLICE = 2 x86_BOOT_SLICE = 8 x86_ALT_SLICE = 9 UNUSED = (None, None) UNUSED_TEXT = "Unused" DEFAULT_POOL = UserString("") ZPOOL = tgt.Slice.AZPOOL ZPOOL_TYPES = [ tgt.Slice.AZPOOL, tgt.Slice.EZPOOL, tgt.Slice.SZPOOL, tgt.Slice.CZPOOL ] ROOT_POOL = (ZPOOL, DEFAULT_POOL) LEGACY = "legacy" UFS = tgt.Slice.FS UFS_TEXT = "UFS" UNKNOWN = "???" TYPES = [UNUSED, ROOT_POOL] def __init__(self, slice_num=0, size=None, offset=None, blocksz=512, slice_type=None, readonly=False, unmountable=True, tag=None, tgt_slice=None): '''Constructor takes either a tgt_slice, which should be a tgt.Slice object, or a set of parameters. If tgt_slice is supplied, all other parameters are ignored. ''' self._tgt_slice = tgt_slice self._size = None self._offset = None self.previous_size = None if tgt_slice: size = str(tgt_slice.blocks * tgt_slice.geometry.blocksz) + "b" self.size = size offset = str(tgt_slice.offset * tgt_slice.geometry.blocksz) + "b" self.blocksz = tgt_slice.geometry.blocksz self.offset = offset self.number = tgt_slice.number self.readonly = tgt_slice.readonly self.type = (tgt_slice.type, tgt_slice.user) self.last_mount = tgt_slice.last_mount self.unmountable = tgt_slice.unmountable self.tag = tgt_slice.tag else: self.readonly = readonly if slice_type is None: slice_type = SliceInfo.UNUSED if len(slice_type) != 2: raise TypeError("slice_type must be tuple of length 2") self.type = slice_type self.unmountable = unmountable self.size = size self.blocksz = blocksz self.offset = offset self.number = slice_num self.last_mount = None self.tag = tag self.original_type = self.type def __str__(self): result = ["Slice Info (%s):" % self.number] result.append("Type: %s:%s" % self.type) result.append("Offset: %s" % self.offset) result.append("Size: %s" % self.size) return "\n".join(result) @staticmethod def compare(left, right): '''Returns an integer such that this method can be passed to list.sort() and the list will be sorted in disk layout order. The backup slice is always listed last ''' if isinstance(left, tgt.Slice): left = SliceInfo(left) if not isinstance(left, SliceInfo): return NotImplemented if isinstance(right, tgt.Slice): right = SliceInfo(right) if not isinstance(right, SliceInfo): return NotImplemented if left.number == SliceInfo.BACKUP_SLICE: return 1 elif right.number == SliceInfo.BACKUP_SLICE: return -1 left_off = left.offset.size_as("b") right_off = right.offset.size_as("b") if left_off < right_off: return -1 elif left_off > right_off: return 1 else: return 0 def get_offset(self): '''Return this slice's offset as a DiskSpace object''' return self._offset def set_offset(self, offset): '''Set this slice's offset. Must be either a DiskSpace object or a string that will be accepted by DiskSpace.__init__ ''' if isinstance(offset, DiskSpace): self._offset = deepcopy(offset) else: self._offset = DiskSpace(offset) def get_size(self): '''Returns this slice's size as a DiskSpace object''' return self._size def set_size(self, size): '''Set this slice's size. size must be either a DiskSpace or a string that will be accepted by DiskSpace.__init__ ''' if isinstance(size, DiskSpace): self._size = deepcopy(size) else: self._size = DiskSpace(size) def get_type(self): '''Returns this SliceInfo's 'type' Here for interface compatibility with PartitionInfo.get_type()''' return self.type def get_blocks(self): '''Return the number of blocks on this slice''' return int(self.size.size_as("b") / self.blocksz) size = property(get_size, set_size) offset = property(get_offset, set_offset) def get_description(self): '''Return a string suitable for representing this slice in a UI''' description = None if self.number == SliceInfo.BACKUP_SLICE: description = tgt.Slice.BACKUP elif self.type == SliceInfo.UNUSED: description = SliceInfo.UNUSED_TEXT elif self.type[0] == SliceInfo.UFS: if self.last_mount: description = self.last_mount else: description = SliceInfo.UFS_TEXT elif self.type[0] == tgt.Slice.UNKNOWN: if self.tag == tgt.Slice.UNKNOWN: description = SliceInfo.UNKNOWN else: description = self.tag elif self.type[1] and self.type[1] != tgt.Slice.UNKNOWN: description = self.type[1] else: description = self.type[0] return str(description) def cycle_type(self, parent, extra_types=None): '''Cycle this partition's type. If extra_types is given, it should be a list of additional types - these will be considered when cycling to the next type ''' if extra_types is None: extra_types = [] if self.number == SliceInfo.BACKUP_SLICE: return has_solaris_data = (parent.get_solaris_data() is not None) types = set() types.update(SliceInfo.TYPES) types.update(extra_types) types = list(types) types.sort() if self.type in types: logging.debug("type in types, cycling next") type_index = types.index(self.type) type_index = (type_index + 1) % len(types) self.type = types[type_index] logging.debug("now %s-%s", *self.type) else: logging.debug("type NOT in types, setting to types[0]") self.original_type = self.type self.type = types[0] if self.type == SliceInfo.UNUSED: self.previous_size = self.size self.size = "0GB" elif self.is_rpool(): if has_solaris_data: self.cycle_type(parent, extra_types) def get_endblock(self): '''Returns the ending 'offset' of this slice, as a DiskSpace''' try: start_pt = self.offset.size_as("b") end_pt = self.size.size_as("b") return DiskSpace(str(start_pt + end_pt) + "b") except AttributeError: raise AttributeError("%s does not have valid size data" % self.__class__.__name__) def get_max_size(self, parent): '''Return the maximum possible size this slice could consume, in gigabytes, based on adjacent unused space ''' if self.number == SliceInfo.BACKUP_SLICE: return self.size.size_as("gb") msg_str = "get_max_size:%s:" % self.number slices = parent.slices if self not in slices: raise ValueError("This slice not in the parent!") self_idx = slices.index(self) prev_slice = None next_slice = None # Search for the slice prior to this one with the largest "endblock" # Since existing slices may overlap, this could be any slice prior # to the current one. for slice_info in reversed(slices[:self_idx]): if (slice_info.type != SliceInfo.UNUSED and slice_info.number != SliceInfo.BACKUP_SLICE): if (prev_slice is None or slice_info.get_endblock() > prev_slice.get_endblock()): prev_slice = slice_info for slice_info in slices[self_idx + 1:]: if (slice_info.type != SliceInfo.UNUSED and slice_info.number != SliceInfo.BACKUP_SLICE): next_slice = slice_info break if prev_slice is None: msg_str += "prev_part=None:start_pt=0:" start_pt = 0 else: msg_str += "prev_part=%s:" % prev_slice.number start_pt = prev_slice.get_endblock().size_as("gb") msg_str += "start_pt=" + str(start_pt) + ":" if next_slice is None: msg_str += "next_part=None:end_pt=" for slice_info in reversed(slices): # Use the backup slice to define the absolute max size # any given slice can be. (This is usually the last slice, # hence the use of a reversed iterator) if slice_info.number == SliceInfo.BACKUP_SLICE: end_pt = slice_info.size.size_as("gb") break else: # Default to the parent's size if there happens to be no S2 end_pt = parent.size.size_as("gb") msg_str += str(end_pt) + ":" else: msg_str += "next_part=%s:" % next_slice.number end_pt = next_slice.offset.size_as("gb") msg_str += "end_pt=%s:" % end_pt max_space = end_pt - start_pt if max_space < 0: max_space = 0 msg_str += "max_size=%s" % max_space logging.debug(msg_str) return max_space def editable(self, dummy): '''Returns True if the installer is capable of resizing this Slice''' return self.is_rpool() def adjust_offset(self, parent): '''Adjust this slice's offset such that it no longer overlaps with prior or subsequent slices, by comparing this slice's offset with prior slices, and its endblock with subsequent ones. Additionally, any unused slices found are shifted to align with this slice's trailing edge, if needed. This function should only be called after ensuring that this slice's size is less than or equal its max_size (as given by get_max_size); the behavior of this function when attempting to adjust in both directions is undefined. Additionally, the slices on the parent should already be sorted in disk order. ''' if self.number == SliceInfo.BACKUP_SLICE: return parts = parent.get_parts() self_idx = parts.index(self) endblock = self.get_endblock() endblock_bytes = endblock.size_as("gb") unused_parts = [] pre_shift = 0 for part in parts[:self_idx]: if (part.type == SliceInfo.UNUSED or part.number == SliceInfo.BACKUP_SLICE): continue overlap = (part.get_endblock().size_as("gb") - self.offset.size_as("gb")) pre_shift = max(pre_shift, overlap) if pre_shift > 0: new_offset = self.offset.size_as("gb") + pre_shift self.offset = str(new_offset) + "gb" post_shift = None for part in parts[self_idx + 1:]: if part.offset.size_as("gb") < endblock_bytes: if part.type == SliceInfo.UNUSED: unused_parts.append(part) elif part.number != SliceInfo.BACKUP_SLICE: post_shift = endblock_bytes - part.offset.size_as("gb") break else: break else: # Check to ensure we don't slip past the end of the disk/partition max_endblock = parent.size.size_as("gb") if endblock_bytes > max_endblock: post_shift = endblock_bytes - max_endblock if post_shift is not None: new_offset = max(0, self.offset.size_as("gb") - post_shift) self.offset = str(new_offset) + "gb" new_endblock = self.get_endblock() for part in unused_parts: part.offset = new_endblock def to_tgt(self, parent): '''Transfer the install profile information to tgt format''' # Create tgt.Slice object if self.get_type() == SliceInfo.UNUSED: return None if not self.modified(): return self._tgt_slice # Don't need to include the 'backup' slice, libti will # automatically create one appropriately if self.number == SliceInfo.BACKUP_SLICE: return None # Something changed, need to create a new one geo = tgt.Geometry(parent.cylsz, self.blocksz) # offset must be a multiple of tgt.Geometry.cylsz off = int(self.offset.size_as("b") / self.blocksz) offset = round_to_multiple(off, geo.cylsz) blocks = round_to_multiple(self.get_blocks(), geo.cylsz) tag = tgt.Slice.UNASSIGNED slice_type = self.type[0] user = self.type[1] sl = tgt.Slice(geo, self.number, tag, slice_type, offset, blocks, modified=True, user=str(user), unmountable=self.unmountable, readonly=self.readonly) return (sl) def modified(self, off_by=UI_PRECISION): '''Returns False if and only if this SliceInfo was instantiated from a tgt.Slice, and this SliceInfo does not differ in substance from the tgt.Slice from which it was instantiated. Size, offset, type and number are compared to determine whether this slice has been modified. off_by - A string or DiskSpace indicating a rounding factor. Any size data (offset, size) that differs by less than the given amount is assumed to be unchanged. e.g., if the tgt.Slice indicates a size of 10.05GB and this SliceInfo has a size of 10.1GB, and off_by is the default of 0.1GB, then it is assumed that the represented slice has not changed. (The original tgt.Slice size should be used, for accuracy) ''' if self._tgt_slice is None: return True if not isinstance(off_by, DiskSpace): off_by = DiskSpace(off_by) off_by_bytes = off_by.size_as("b") if self.number != self._tgt_slice.number: return True if self.type[0] != self._tgt_slice.type: return True if self.type[1] != self._tgt_slice.user: return True tgt_size = self._tgt_slice.blocks * self._tgt_slice.geometry.blocksz if abs(tgt_size - self.size.size_as("b")) > off_by_bytes: return True tgt_offset = self._tgt_slice.offset * self._tgt_slice.geometry.blocksz if abs(tgt_offset - self.offset.size_as("b")) > off_by_bytes: return True return False def destroyed(self, off_by=UI_PRECISION): '''Returns True if this slice previously had data, and has also been modified. ''' if self.is_rpool(): return True return (self._tgt_slice is not None and self.modified(off_by)) def is_rpool(self): '''Returns True this slice is the default pool ''' return (self.type[0] in SliceInfo.ZPOOL_TYPES and self.type[1] == SliceInfo.DEFAULT_POOL) def is_solaris_data(self): return self.is_rpool()
def __init__(self, value): UserString.__init__(self, value)
# Function to stop deleltion def remove(self, s=None): raise RuntimeError("Deletion not allowed") # Function to stop pop def pop(self, s=None): raise RuntimeError("Deletion not allowed") ### UserString ### # Creating a UserString from collections import UserString string1 = "asgjfgsafsaguifauifa" user_string = UserString(string1) user_string.data #Access the string1 content ## Creating a string class with modified behavior -> Mutable String class Mystring(UserString): # Function to append def append(self, s): self.data += s # Function to remove def remove(self, s): self.data = self.data.replace(s, "")
def __init__(self): UserString.__init__(self, '')
def __init__(self, value): value = value[1::] UserString.__init__(self, value)
def __radd__(self, other): return Bitstring(UserString(other).__add__(self), self.byteorder, auto_fill=self.auto_fill)
args = parser.parse_args() tt = ttLib.TTFont(args.font) cmap = tt.getGlyphOrder() strings = [] for inf in args.input: for d in (['.'] + args.directory): fname = os.path.join(d, inf) if not os.path.exists(fname): continue if fname.endswith(".xml") or fname.endswith(".ftml"): strings.extend(parseftml(fname)) else: with open(fname, "r") as fh: strings.extend([ UserString(x.strip()) for l in fh.readlines() for x in l.split() ]) break if args.single: grfont = GrFont(args.font, 1 if args.rtl else 0) res = [makestring(grfont, s) for s in strings] else: pool = Pool(initializer=initprocess, initargs=[args.font, args.rtl, strings]) res = pool.imap_unordered(proc_makestring, strings) if args.text: with open(args.outfile, "w") as fh: for s in res: fh.write(s.asStr(cmap) + "\n")
def test_string_likes(self): for thing in ['', 'a', u'\xe4', UserString('us'), MutableString('ms')]: assert_equals(is_str_like(thing), True, thing)
def encode(self, encoding=None, errors=None): if self.forced_encoding is not None: encoding = self.forced_encoding return UserString.encode(self, encoding=encoding, errors=errors)
def __getitem__(self, index): return Bitstring(UserString.__getitem__(self, index), self.byteorder)
def test_integration_is_list_like_user_string_false(self): obj = UserString('testing') self.assertFalse(is_list_like(obj))
from collections import UserString d = 12344 # Creating an UserDict userS = UserString(d) print(userS.data) # Creating an empty UserDict userS = UserString("") print(userS.data) # Creating a Mutable String class Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to rmeove from # string def remove(self, s): self.data = self.data.replace(s, "") # Driver's code s1 = Mystring("Dinosaur") print("Original String:", s1.data)
def __init__(self, *args, **kwargs): self.forced_encoding = kwargs.pop('force_encoding', None) UserString.__init__(self, *args, **kwargs)
def __init__(self, code_str): UserString.__init__(self, re.sub(r"(\s|[-_])", "", code_str).upper())