Example #1
1
class DictUtilitiesTest(unittest.TestCase):
    def test_inverse_dicts(self):
        self.dict1 = {1: [1, 2, 3], 2: [3, 4, 5]}
        self.dict2 = {2: [1], 3: [2], 4: [3, 4]}
        self.dict3 = {1: 2, 3: 4, 4: 4, 5: 4}
        self.dict4 = {2: 3, 4: 4}
        result = inverse_dicts(self.dict3)
        self.assertEqual({2: [1], 4: [3, 4, 5]}, result)

        result = inverse_dicts(self.dict1)
        self.assertEqual({1: [1], 2: [1], 3: [1, 2], 4: [2], 5: [2]}, result)

        result = inverse_dicts(self.dict3, self.dict4)
        self.assertEqual({2: [1], 3: [2], 4: [3, 4, 5, 4]}, result)

        result = inverse_dicts(self.dict1, self.dict2)
        self.assertEqual({1: [1, 2], 2: [1, 3], 3: [1, 2, 4], 4: [2, 4], 5: [2]}, result)

    def test_update_ordered_dict_key(self):
        self.ordered_dict = OrderedDict()
        self.ordered_dict["default"] = "Some stuff"
        self.ordered_dict["pythoncheck"] = "Somemore stuff"
        self.ordered_dict = update_ordered_dict_key(self.ordered_dict, "default", "coala")
        self.assertTrue("coala" in self.ordered_dict)
        self.assertEqual(
            "OrderedDict([('coala', 'Some stuff'), " "('pythoncheck', 'Somemore stuff')])", self.ordered_dict.__str__()
        )
        self.ordered_dict = update_ordered_dict_key(self.ordered_dict, "coala", "section")
        self.assertTrue("section" in self.ordered_dict)
        self.assertEqual(
            "OrderedDict([('section', 'Some stuff'), " "('pythoncheck', 'Somemore stuff')])",
            self.ordered_dict.__str__(),
        )
Example #2
1
class Graph:
    def __init__(self):
        self.nodes = OrderedDict()
        self.edges = OrderedDict()

    def add_edge(self, src, dst):
        if src in self.edges:
            self.edges[src].append(dst)
        else:
            self.edges[src] = [dst]

    def add_node(self, function_name):
        self.nodes[function_name] = True

    def __str__(self):
        return "edges : " + self.edges.__str__() + ", functions : " + list(self.nodes.keys()).__str__()

    def toDOT(self):
        # funcs = ';'.join(self.nodes.keys())
        funcs = ""
        for f in self.nodes.keys():
            funcs += f + ";"
        edges = ""
        for (key, value) in self.edges.items():
            for dst in value:
                edges += "  " + key + " -> " + dst + ";\n"

        tpl_str = """
digraph G {
  ranksep=.25;
  edge [arrowsize=.5]
  node [shape=circle, fontname="ArialNarrow",
        fontsize=12, fixedsize=true, height=.45];

  $func_list
$edge_list
}
"""
        tpl = Template(tpl_str)
        return tpl.substitute(func_list=funcs, edge_list=edges)
 def __str__(self):
     return self.name + "_" + OrderedDict.__str__(self)
Example #4
1
class ListofEntities(list):
    def __init__(self, typ):
        super(ListofEntities, self).__init__()
        from collections import OrderedDict

        self._dict_entities = OrderedDict()
        self._dict_entities_hash = {}
        self.typeItems = typ
        self.type_instance = typ()
        self.changed = []

    def _update_hashes(self):
        self._dict_entities_hash = {hash(v): v for k, v in self._dict_entities.items()}

    def __hash__(self):
        return hash(frozenset(self._dict_entities))

    def __str__(self):
        return self._dict_entities.__str__()

    def __repr__(self):
        return self._dict_entities.__repr__()

    def __unicode__(self):
        return self.__str__()

    def __getitem__(self, item):
        return self._dict_entities.values().__getitem__(item)

    def update_from_changed_entities(self, changed_entities):
        if changed_entities is None:
            return
        for entity in changed_entities:
            if hasattr(entity, "is_tombstone") and entity.is_tombstone:
                continue
            try:
                self._dict_entities[entity.id].update_from_changed_entities(entity)
            except KeyError:
                self._dict_entities[entity.id] = entity
        self._update_hashes()

    def get(self, entity_id):
        return self._dict_entities.get(entity_id)

    def extend(self, objects, track=True):
        if not all(isinstance(x, self.typeItems) for x in objects):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        for o in objects:
            self._dict_entities[o.id] = o
            self._dict_entities_hash[hash(o)] = o
        if track:
            self.changed.extend(objects)

    def append(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        self._dict_entities[o.id] = o
        self._dict_entities_hash[hash(o)] = o
        if track:
            self.changed.append(o)

    def delete(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        if o.id in self._dict_entities:
            del self._dict_entities[o.id]
        if hash(o) in self._dict_entities_hash:
            del self._dict_entities_hash[hash(o)]
        if track:
            o.is_tombstone = True
            self.changed.append(o)

    def modify(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        if o.id in self._dict_entities:
            h = hash(self._dict_entities[o.id])
            if h in self._dict_entities_hash:
                del self._dict_entities_hash[h]
            self._dict_entities[o.id] = o
            self._dict_entities_hash[hash(o)] = o
            if track:
                self.changed.append(o)

    def __iter__(self):
        return self._dict_entities.values().__iter__()

    def __len__(self):
        return len(self._dict_entities)

    def containsduplicate(self, item):
        if not isinstance(item, self.typeItems):
            return False
        else:
            return item._hash() in self._dict_entities_hash

    def __contains__(self, item):
        if not isinstance(item, self.typeItems):
            return False
        else:
            return item.id in self._dict_entities

    def get_changed_entities(self):
        return self.changed