Example #1
1
class FreqDict(object):
    def __init__(self, terms, reverse=False):
        assert type(terms) in [list, set, np.ndarray], "input must be list, set or ndarray."
        fd = defaultdict(int)
        for term in terms:
            fd[term] += 1
        self.__fd = OrderedDict()
        for k, v in sorted(fd.iteritems(), key=lambda d: d[1], reverse=reverse):
            self.__fd[k] = v

    def __getitem__(self, item):
        return self.__fd[item]

    def __iter__(self):
        return iter(self.__fd.iteritems())

    def keys(self):
        return self.__fd.keys()

    def values(self):
        return self.__fd.values()

    def print_freq_dict(self):
        for k, v in self.__fd.iteritems():
            print k, v

    def plot_pie(self):
        plt.pie(x=self.__fd.values(), labels=self.__fd.keys(), autopct="%1.1f%%", shadow=True)
        plt.show()
Example #2
1
def read_lemmas(lemma_descriptions_list, multiclass=False, return_joint=False):
    """
    Извлекает информацию из описаний лемм,
    полученных с помощью функции process_lemmas_file
    """
    data = OrderedDict()
    # в случае, когда одна лексема может иметь несколько парадигм,
    # сохраняем все такие парадигмы
    if not multiclass:

        def add(lst, x):
            if len(lst) == 0:
                lst.append(x)

    else:

        def add(lst, x):
            lst.append(x)

    for lemma, code, var_values in lemma_descriptions_list:
        if lemma in data:
            add(data[lemma], (code, var_values))
        else:
            data[lemma] = [(code, var_values)]
    if return_joint:
        return list(data.keys()), list(data.values())
    else:
        return (
            list(data.keys()),
            [list(x[0] for x in elem) for elem in data.values()],
            [list(x[1] for x in elem) for elem in data.values()],
        )
Example #3
1
def parse_meditation(lines):
    lines = [l for l in lines if l.strip() if l.strip()]
    title_line = lines[0]
    rest = lines[1:]
    slug, title = title_line.replace("//", "").strip().split("|")
    koans = OrderedDict()
    current = None
    comment_bracket_cnt = 0
    for line in rest:
        if line.strip().startswith("//"):
            current = line.replace("//", "").strip()
            koans[current] = {"hint": [], "code": [], "slug": current.split("|")[0], "name": current.split("|")[1]}
        elif line.strip().startswith("/*"):
            koans[current]["hint"].append(line)
            comment_bracket_cnt += 1
        elif line.strip().startswith("*/"):
            koans[current]["hint"].append(line)
            comment_bracket_cnt -= 1
        else:
            if comment_bracket_cnt != 0:
                koans[current]["hint"].append(line)
            else:
                koans[current]["code"].append(line)

    for koan in koans.values():
        koan["hint"] = "".join(koan["hint"])
        koan["code"] = "".join(koan["code"])

    ks = [Koan(k["slug"], k["name"], k["hint"], k["code"]) for k in koans.values()]
    m = Meditation(slug, title)
    for k in ks:
        m.add_koan(k)
    return m
Example #4
1
class RegexParser(ContentParserBase):
    rule_classes = []

    def __init__(self, **kwargs):
        self._rules = OrderedDict([(R.name, R()) for R in self.rule_classes])
        self.regex = r"|".join(["(?P<{}>{})".format(r.name, r.src) for r in self._rules.values()])

    def parse(self, content):
        for r in self._rules.values():
            r.pre_parse()
        return re.sub(self.regex, self.translate, content)

    def translate(self, match):
        word = match.group(0)
        for r in self._rules.values():
            if match.group(r.name) is not None:
                return r.translate(word, match)
        else:
            return word

    def context_data(self, rule_name, key=None, default_value=None):
        if rule_name in self._rules:
            context = self._rules[rule_name].context
            if key:
                return getattr(context, key, default_value)
            else:
                return context
        else:
            raise ValueError("The rule name {r} does not exist.".format(rule_name))
Example #5
1
 def recursive_split(rect_key, rect_coords, category_idx, split_dir, gap):
     """
     given a key of the boxes and the data to analyze,
     split the key into several keys stratificated by the given
     category in the assigned direction
     """
     ticks = []
     category = categories[category_idx]
     chiave = rect_key
     divisione = OrderedDict()
     for tipo in category:
         divisione[tipo] = 0.0
         for k, v in counted.items():
             if k[len(rect_key) - 1] != tipo:
                 continue
             if not all(k[k1] == v1 for k1, v1 in enumerate(rect_key[1:])):
                 continue
             divisione[tipo] += v
     totali = 1.0 * sum(divisione.values())
     if totali:  # check for empty categories
         divisione = OrderedDict((k, v / totali) for k, v in divisione.items())
     else:
         divisione = OrderedDict((k, 0.0) for k, v in divisione.items())
     prop = divisione.values()
     div_keys = divisione.keys()
     new_rects = split_rect(*rect_coords, proportion=prop, direction=split_dir, gap=gap)
     divisi = OrderedDict((chiave + (k,), v) for k, v in zip(div_keys, new_rects))
     d = split_dir == "h"
     ticks = [(k, O[d] + 0.5 * [h, w][d]) for k, (O, h, w) in zip(div_keys, new_rects)]
     return divisi, zip(*ticks)
def normDAGl2Test(G_test, power):
    kern = nx.get_edge_attributes(G_test, "kern_unnorm")
    tran = nx.get_edge_attributes(G_test, "tran")

    kern = OrderedDict(sorted(kern.items(), key=lambda t: t[0]))
    val = kern.values()
    key = kern.keys()

    tran = OrderedDict(sorted(tran.items(), key=lambda t: t[0]))
    tran = tran.values()

    val = np.asarray(val, dtype=float)
    tran = np.asarray(tran, dtype=float)
    tran = np.log(1 / tran)  # logarithm weighting
    tran[tran == np.inf] = 0
    tran[np.isnan(tran)] = 0

    if power == 2:
        tran = np.square(tran)

    if len(val.shape) == 2:
        # kern = val/tran[:, None]
        kern = val * tran[:, None]  # avoid numeric problems when using logarithm weighting
        kern = normalize(kern, norm="l2", axis=0)
    else:
        kern = val * tran
        kern = kern / np.linalg.norm(kern)

    kern = dict(zip(key, kern))
    nx.set_edge_attributes(G_test, "kern", kern)

    return G_test
Example #7
1
class UnitGroup(object):
    def __init__(self, items, default_index=0):
        self.units = OrderedDict(items)
        self.by_name = dict(reversed(i) for i in enumerate(self.units.keys()))
        self.by_scalefactor = dict(reversed(i) for i in enumerate(self.units.values()))
        self.__default_index = default_index

    def idx_by_name(self, name):
        return self.by_name[name]

    def idx_by_scale(self, scale):
        return self.by_scale[scale]

    def get_scale(self, idx):
        return list(self.units.values())[idx]

    def get_name(self, idx):
        return list(self.units.keys())[idx]

    @property
    def names(self):
        return list(self.units.keys())

    @property
    def default_index(self):
        return self.__default_index
Example #8
0
    def get_uniques(self, candidate_reporting_units):
        """
        Parses out unique candidates and ballot measures
        from a list of CandidateReportingUnit objects.
        """
        unique_candidates = OrderedDict()
        unique_ballot_measures = OrderedDict()

        for c in candidate_reporting_units:
            if c.is_ballot_measure:
                if not unique_ballot_measures.get(c.candidateid, None):
                    unique_ballot_measures[c.candidateid] = BallotMeasure(
                        last=c.last,
                        candidateid=c.candidateid,
                        polid=c.polid,
                        ballotorder=c.ballotorder,
                        polnum=c.polnum,
                        seatname=c.seatname,
                        description=c.description,
                    )
            else:
                if not unique_candidates.get(c.candidateid, None):
                    unique_candidates[c.candidateid] = Candidate(
                        first=c.first,
                        last=c.last,
                        candidateid=c.candidateid,
                        polid=c.polid,
                        ballotorder=c.ballotorder,
                        polnum=c.polnum,
                        party=c.party,
                    )

        candidates = [v for v in unique_candidates.values()]
        ballot_measures = [v for v in unique_ballot_measures.values()]
        return candidates, ballot_measures
Example #9
0
class LiteUSBCrossbar(Module):
    def __init__(self):
        self.users = OrderedDict()
        self.master = LiteUSBMasterPort(8)
        self.dispatch_param = "dst"

    def get_port(self, dst):
        port = LiteUSBUserPort(8, dst)
        if dst in self.users.keys():
            raise ValueError("Destination {0:#x} already assigned".format(dst))
        self.users[dst] = port
        return port

    def do_finalize(self):
        # TX arbitrate
        sinks = [port.sink for port in self.users.values()]
        self.submodules.arbiter = Arbiter(sinks, self.master.source)

        # RX dispatch
        sources = [port.source for port in self.users.values()]
        self.submodules.dispatcher = Dispatcher(self.master.sink, sources, one_hot=True)
        cases = {}
        cases["default"] = self.dispatcher.sel.eq(0)
        for i, (k, v) in enumerate(self.users.items()):
            cases[k] = self.dispatcher.sel.eq(2 ** i)
        self.comb += Case(getattr(self.master.sink, self.dispatch_param), cases)
Example #10
0
def test_config_object_util(no_config_env):
    project = Project.objects.first()
    conf = ObjectConfig(project)
    assert conf.items() == conf.values() == conf.keys() == []
    # keys are returned order by key
    other_dict = OrderedDict()
    other_dict["foo.a"] = "bar"
    other_dict["foo.b"] = dict(bar=23)
    other_dict["foo.c"] = [1, 2, 3]
    conf["foo.a"] = "bar"
    conf["foo.b"] = dict(bar=23)
    conf["foo.c"] = [1, 2, 3]
    assert conf.items() == other_dict.items()
    assert conf.values() == other_dict.values()
    assert conf.keys() == other_dict.keys()
    assert [x for x in conf] == other_dict.keys()
    assert all(x in conf for x in other_dict)
    assert all(conf[k] == v for k, v in other_dict.items())
    assert all(conf.get(k) == v for k, v in other_dict.items())
    assert conf.get("DOESNOTEXIST") is None
    assert conf.get("DOESNOTEXIST", "foo") == "foo"
    with pytest.raises(KeyError):
        conf["DOESNOTEXIST"]
    assert ObjectConfig(project).items() == other_dict.items()
    assert ObjectConfig(project).values() == other_dict.values()
    assert ObjectConfig(project).keys() == other_dict.keys()
    assert [x for x in ObjectConfig(project)] == other_dict.keys()
    assert all(x in ObjectConfig(project) for x in other_dict)
    assert all(ObjectConfig(project)[k] == v for k, v in other_dict.items())
    assert all(ObjectConfig(project).get(k) == v for k, v in other_dict.items())
    assert ObjectConfig(project).get("DOESNOTEXIST") is None
    assert ObjectConfig(project).get("DOESNOTEXIST", "foo") == "foo"
    with pytest.raises(KeyError):
        ObjectConfig(project)["DOESNOTEXIST"]
Example #11
0
    def domain(self):
        """
        .. note::

            This does only work well with parameters which have a discrete domain.
        """
        d = OrderedDict()
        for i, des in enumerate(product(*[p.domain for p in self.parameters])):
            cde = CombinationDomainElement(self, des, icon=ORDERED_ICONS[i % len(ORDERED_ICONS)])
            d[cde.number] = cde

        for language, values in groupby(
            sorted(self.values, key=lambda v: v.valueset.language_pk), lambda i: i.valueset.language
        ):
            # values may contain multiple values for the same parameter, so we have to
            # group those, too.
            values_by_parameter = OrderedDict()
            for p in self.parameters:
                values_by_parameter[p.pk] = []
            for v in values:
                values_by_parameter[v.valueset.parameter_pk].append(v)
            for i, cv in enumerate(product(*values_by_parameter.values())):
                d[tuple(v.domainelement.number for v in cv)].languages.append(language)
                if i > 0:
                    # a language with multiple values, store a reference.
                    self.multiple.append(language)
        self.multiple = set(self.multiple)
        return d.values()
Example #12
0
class Cluster(object):
    def __init__(self, members):
        self.hash = hash
        self.members = OrderedDict(((self.hash(node), node) for node in members))

    def __len__(self):
        return sum((len(node) for node in self.members.values()))

    def __getitem__(self, key):
        return self.location(key)[key]

    def __setitem__(self, key, value):
        self.location(key)[key] = value

    def __delitem__(self, key):
        del self.location(key)[key]

    def location(self, key):
        """
        Returns where a given key should be stored.
        """
        hashed = self.hash(key)
        try:
            return last(takewhile(lambda pair: pair[0] <= hashed, self.members.items()))[1]
        except ValueError:
            # "wrap around" the ring of nodes to the last node if no nodes
            # have a hashed value that is lower than or equal to the hashed
            # value of the key
            return self.members.values()[-1]
Example #13
0
def treasures():
    results = sqlrelay.execute_results(
        """
SELECT
   GROUP_ID
 , ITEM_ID
 , FREQUENCY
FROM
   ARPG_BT_TREASURE
"""
    )

    treasure_list = OrderedDict()
    for r in results:
        group_id = int(r[0])
        item_id = int(r[1])
        frequency = int(r[2])

        if treasure_list.has_key(group_id):
            treasure = treasure_list[group_id]
        else:
            treasure = OrderedDict()
            treasure_list[group_id] = treasure

        treasure[item_id] = {"frequency": frequency}

    # 토탈 확률계산
    for treasure in treasure_list.values():
        total = 0
        for item in treasure.values():
            total += item["frequency"]
        treasure["total"] = total

    return treasure_list
Example #14
0
def print_column_summary(experiments):
    """Print a list of all columns contained in the given experiments.

    Parameters
    ----------
    experiments : OrderedDict of {str: DataFrame}
        The key is expected to be an experiment identifier
        (e.g. a filename) and the value a pandas.DataFrame.

    """
    channels_per_experiment = OrderedDict([(fname, set(df.columns)) for fname, df in iteritems(experiments)])
    all_channels = reduce(set.union, channels_per_experiment.values())

    print("{} experiment(s):".format(len(experiments)))
    for i, fname in enumerate(experiments):
        print("    {}: {}".format(i, fname))
    print()
    print("Containing the following channels:")
    for ch in sorted(all_channels):
        # create a string indicating which experiments contain which
        #  channels
        indicator = []
        for i, channels in enumerate(channels_per_experiment.values()):
            if ch in channels:
                indicator.append(str(i))
            else:
                indicator.append(" ")
        indicator = ",".join(indicator)
        print("    {}: {}".format(indicator, ch))
class HasStopConditions(object):
    """A delegate that adds handling of stop conditions that are
    supplied as expression strings.
    """

    def __init__(self, parent):
        self._parent = parent
        self._stop_conditions = OrderedDict()

    def _item_count(self):
        """This is used by the replace function to determine if a delegate from the
        target object is 'empty' or not.  If it's empty then it's not an error if the
        replacing object doesn't have this delegate.
        """
        return len(self._stop_conditions)

    def add_stop_condition(self, exprstr):
        ident = _remove_spaces(exprstr)
        expr = ExprEvaluator(exprstr, scope=self._parent.parent)
        _check_expr(expr, self._parent)
        self._stop_conditions[ident] = expr

    def remove_stop_condition(self, expr_string):
        """Removes the stop condition matching the given string."""
        try:
            del self._stop_conditions[_remove_spaces(expr_string)]
        except KeyError:
            self._parent.raise_exception(
                "Stop condition '%s' was not found. Remove failed." % expr_string, AttributeError
            )

    def clear_stop_conditions(self):
        """Removes all stop conditions."""
        self._stop_conditions = OrderedDict()

    def get_stop_conditions(self):
        """Returns a list of stop condition strings."""
        return self._stop_conditions.keys()

    def eval_stop_conditions(self):
        """Returns a list of evaluated stop conditions."""
        return [c.evaluate() for c in self._stop_conditions.values()]

    def should_stop(self):
        """Return True if any of the stopping conditions evaluate to True."""
        for cond in self._stop_conditions.values():
            if cond.evaluate():  # and cond.refs_valid():
                return True
        return False

    def mimic(self, target):
        """Copy stop conditions from the target."""
        old_stop_cond = self._stop_conditions
        self.clear_stop_conditions()
        try:
            for exp in target.get_stop_conditions():
                self.add_stop_condition(exp)
        except Exception:
            self._stop_conditions = old_stop_cond
            raise
def test():
    from collections import OrderedDict as StdlibOrderedDict

    ordered_dict = OrderedDict(((1, "a"), (2, "b"), (3, "c")))
    stdlib_ordered_dict = StdlibOrderedDict(((1, "a"), (2, "b"), (3, "c")))

    assert ordered_dict == stdlib_ordered_dict
    assert stdlib_ordered_dict == ordered_dict
    assert ordered_dict.items() == stdlib_ordered_dict.items()
    assert ordered_dict.keys() == stdlib_ordered_dict.keys()
    assert ordered_dict.values() == stdlib_ordered_dict.values()

    ordered_dict.move_to_end(1)

    assert ordered_dict != stdlib_ordered_dict
    # assert stdlib_ordered_dict != ordered_dict
    assert ordered_dict.items() != stdlib_ordered_dict.items()
    assert ordered_dict.keys() != stdlib_ordered_dict.keys()
    assert ordered_dict.values() != stdlib_ordered_dict.values()

    del stdlib_ordered_dict[1]
    stdlib_ordered_dict[1] = "a"

    assert ordered_dict == stdlib_ordered_dict
    assert stdlib_ordered_dict == ordered_dict
    assert ordered_dict.items() == stdlib_ordered_dict.items()
    assert ordered_dict.keys() == stdlib_ordered_dict.keys()
    assert ordered_dict.values() == stdlib_ordered_dict.values()

    assert ordered_dict == OrderedDict(stdlib_ordered_dict) == stdlib_ordered_dict
    assert ordered_dict == StdlibOrderedDict(ordered_dict) == stdlib_ordered_dict
Example #17
0
def fixgridsearch(hparamfile, generate):

    hparams = OrderedDict()
    dhparams = OrderedDict()

    for hparam in HparamReader(hparamfile):

        if "generate" not in hparam or hparam["generate"] in ["default", ""]:
            if hparam["generate"] == "":
                print "*** Warning ***"
                print "    Hyperparameter", hparam["hparam"]
                print "    Please set generation mode : default"

            hparam["generate"] = generate

        dhparams[hparam["hparam"]] = hparam.pop("default")

        name = hparam.pop("hparam")
        hparams[name] = hparams.get(name, []) + list(make_hparams(**hparam))

    values = np.zeros((sum([len(hparam) for hparam in hparams.values()]), len(hparams.keys())))

    j = 0
    for i, hparam in enumerate(hparams.items()):
        # set all default values
        values[j : j + len(hparam[1])] = np.array(dhparams.values())
        # set the value of the current hyper-parameter
        values[j : j + len(hparam[1]), i] = np.array(hparam[1])

        j += len(hparam[1])

    return hparams.keys(), values
Example #18
0
class Menu:
    """Menu is a collection of items in a Bootstrap pull-down menu.

    It allow mechanism for third party packages to register their own entries.
    """

    template = "admin/menu/menu.html"

    def __init__(self):
        self.entries = OrderedDict()

    # TODO: How to define entry type here to be Entry (circular)
    def add_entry(self, entry):
        self.entries[entry.id] = entry

    def has_items(self, request: Request) -> bool:
        """Has this menu any entries to draw."""
        return any(entry.is_enabled(request) for entry in self.entries.values())

    def get_entries(self) -> List:
        """Get Entry objects to be rendered in this menu.

        Sort return by natural name order.
        """
        return sorted(self.entries.values(), key=lambda e: e.label)

    def get_entry(self, id):
        """Get any of registered menu entries by its id."""
        return self.entries[id]
Example #19
0
    def cell(self, values):
        if not values:
            values = []
        values = list(values)
        self._cell_unvalidated = values

        filtered_areas = OrderedDict()
        filtered_cells = OrderedDict()
        for value in values:
            valid_area = CellAreaLookup.create(**value)
            if valid_area:
                existing = filtered_areas.get(valid_area.hashkey())
                if existing is not None and existing.better(valid_area):
                    pass
                else:
                    filtered_areas[valid_area.hashkey()] = valid_area
            valid_cell = CellLookup.create(**value)
            if valid_cell:
                existing = filtered_cells.get(valid_cell.hashkey())
                if existing is not None and existing.better(valid_cell):
                    pass
                else:
                    filtered_cells[valid_cell.hashkey()] = valid_cell
        self._cell_area = list(filtered_areas.values())
        self._cell = list(filtered_cells.values())
class ChoicesNumEnum(AbstractChoicesEnum, AbstractEnum):
    def __init__(self, *items):
        self.container = OrderedDict()
        super(ChoicesNumEnum, self).__init__()
        i = 0
        for item in items:
            if len(item) == 3:
                key, val, i = item
                if not isinstance(i, int):
                    raise ValueError("Last value of item must by integer")
            elif len(item) == 2:
                key, val = item
                i += 1
            else:
                raise ValueError("Wrong input data format")

            if i in (j for j, _ in self.container.values()):
                raise ValueError("Index %s already exists, please renumber choices")
            self.container[key] = (i, val)

    def _get_attr_val(self, name):
        return self.container[name][0]

    def _get_choices(self):
        return self.container.values()
class ActionGroupResult(object):
    def __init__(self, actiongroup):
        self.actiongroup = actiongroup
        self._actionresults = OrderedDict()

    def __getitem__(self, actiongroup_name):
        return self._actionresults[actiongroup_name]

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

    @property
    def failed(self):
        for actionresult in self._actionresults.values():
            if actionresult.failed:
                return True
        return False

    def add_actionresult(self, actionresult):
        self._actionresults[actionresult.actionclass.get_name()] = actionresult

    def to_dict(self):
        resultlist = []
        for actionresult in self._actionresults.values():
            resultlist.append(actionresult.to_dict())
        return {"actiongroup_name": self.actiongroup.name, "results": resultlist}

    def __str__(self):
        return json.dumps(self.to_dict(), indent=4)
Example #22
0
def makeHistOfDoms(infname='training_ids_with_their_domains.csv',outfname='HistOfDoms.csv'):
    print 'makeHistOfDoms'+' '+infname
    outf=open(outfname,'w')
    writer=csv.writer(outf)
    inf=open(infname,'r')
    reader=csv.reader(inf)
    domList=getListOfTheColumn('all_domains.csv',0)
    nDoms=len(domList)
    yesList=OrderedDict()
    noList=OrderedDict()
    for i in domList:
        yesList[i]=0
    cnt=0
    for i in reader:
        cnt+=1
        for j in i[2:]:
            yesList[j]+=1
    for i in domList:
        yesList[i]=yesList[i]/float(cnt)
        noList[i]=1-yesList[i]
    writer.writerow(noList.keys())
    writer.writerow(noList.values())
    writer.writerow(yesList.values())
    inf.close()
    outf.close()
    out=dict()
    out['domIndex']=noList.keys()
    out['no']=noList.values()
    out['yes']=yesList.values()
    print 'done'
    return out
Example #23
0
def main(
    plot=False,
    savefig="None",
    geoms="fcs",
    nNs=7,
    Ns=None,
    nspecies="1,2,3",
    nstencils="3,5,7",
    verbose=False,
    **kwargs
):
    nstencils = [int(_) for _ in nstencils.split(",")]
    if Ns is None:
        Ns = [8 * (2 ** i) for i in range(nNs)]
    else:
        Ns = list(map(int, Ns.split(",")))
        nNs = len(Ns)
    nspecies = list(map(int, nspecies.split(",")))
    varied = OrderedDict([("nspecies", nspecies), ("N", Ns), ("geom", geoms), ("nstencil", nstencils)])

    kw1 = default_constant.copy()
    kw1.update(kwargs)

    results = {"varied_keys": list(varied.keys()), "varied_values": list(varied.values())}

    all_params = list(product(*varied.values()))
    for params in progress(all_params) if verbose else all_params:
        kw2 = kw1.copy()
        kw2.update(dict(zip(varied.keys(), params)))
        results[params] = integrate(**kw2)
    basename = os.path.splitext(os.path.basename(__file__))[0]
    pickle.dump(results, gzip.open(basename + ".pkl", "wb"))
Example #24
0
def get_upcoming_events(user=None):
    events = OrderedDict( (e.pk, e) for e in
        Event.objects.filter(
            date__gte=datetime.date.today())
        .annotate(Count('signup'))
        .select_subclasses())

    # get number coming
    tmp = (Event.objects.filter(pk__in=events.keys())
        .filter(signup__coming__in=[Signup.HOLE, Signup.DIRECT])
        .annotate(num_coming=Count('signup')))
    for e in tmp:
        events[e.pk].num_coming = e.num_coming

    if user is not None:
        # get if user has signed up
        tmp = user.signup_set.filter(
            event_id__in=events.keys())

        for e in events.values():
            e.user_signup = None
        for s in tmp:
            events[s.event_id].user_signup = s

    return events.values()
Example #25
0
class FormattedTableColumnSet(object):
    def __init__(self, table, values):
        self.columns = OrderedDict((n, FormattedTableColumn(n, p, table)) for n, p in values)

    def visible_columns(self):
        return [col for col in self.columns.values() if not col.hidden]

    def hidden_columns(self):
        return [col for col in self.columns.values() if col.hidden]

    def keys(self):
        return self.columns.keys()

    def __iter__(self):
        for value in self.columns.values():
            yield value

    def __contains__(self, item):
        return item in self.columns

    def __getitem__(self, item):
        return self.columns[item]

    def __getattr__(self, item):
        return self.columns[item]

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

    def __bool__(self):
        return len(self) > 0
Example #26
0
class CaseInsensitiveOrderedDict(MutableMapping):
    """
    OrderedDict class for string keys that behaves in a case insensitive way.
    """

    def __init__(self, data=None, **kwargs):
        self._data = OrderedDict()
        if data is None:
            data = {}
        self.update(data, **kwargs)

    def __setitem__(self, key, value):
        self._data[key.lower()] = (key, value)

    def __getitem__(self, key):
        return self._data[key.lower()][1]

    def __delitem__(self, key):
        del self._data[key.lower()]

    def __iter__(self):
        return (casedkey for casedkey, mappedvalue in list(self._data.values()))

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

    def __repr__(self):
        return repr([(k, v) for (k, v) in list(self._data.values())])
class Counter:
    """
    Remembers the order in which it counted something
    """

    def __init__(self, startat=0):
        self._ordered = OrderedDict()
        self.startat = startat

    def add(self, key, step=1):
        if not key in self._ordered:
            self._ordered[key] = self.startat
        self._ordered[key] += step

    @property
    def maximum_in_order_added(self):
        """
        Returns a list of the highest-frequency items
        in the order in which they were added
        """
        if self._ordered.values():
            maximum = max(self._ordered.values())
        else:
            return []
        r = []
        for item in self._ordered:
            if self._ordered[item] == maximum and item not in r:
                r.append(item)
        return r
Example #28
0
def main():
    cfg = parser.parse("./pystatus.ini")
    VERSION = {"version": 1}
    print(dumps(VERSION))
    print("[")
    interval = float(cfg["PYSTATUS"].get("refresh", "1"))
    panel = OrderedDict()
    panel["time"] = time.Time(cfg["TIME"])
    panel["battery"] = battery.Battery(cfg["BATTERY"])
    panel["sound"] = sound.Sound(cfg["SOUND"])
    # panel['wifi'] = wifi.Wifi(cfg['WIFI'])
    panel["ethernet"] = ethernet.Ethernet(cfg["ETHERNET"])
    panel["cputemp"] = cputemp.CpuTemp(cfg["CPUTEMP"])
    panel["cpufan"] = cpufan.CpuFan(cfg["CPUFAN"])
    panel["ram"] = ram.RAM(cfg["RAM"])
    panel["vk"] = vk.VK(cfg["VK"])
    # panel['gmail'] = gmail.Gmail(cfg['GMAIL'])
    while True:
        start = t.time()
        visibled = list(filter(lambda i: i.visible, reversed(panel.values())))
        print(visibled, end=",\n")
        list(map(lambda i: i.refresh(), panel.values()))
        late = t.time() - start

        sleep((interval - late) if (interval - late) > 0 else interval)
        stdout.flush()
Example #29
0
    def get_all(cls, return_dict=False):
        items = OrderedDict()
        try:
            wp = WikiPage.get(*cls._get_wiki_config())
        except NotFound:
            return items if return_dict else items.values()
        wp_content = StringIO(wp.content)
        cfg = SafeConfigParser(allow_no_value=True)
        cfg.readfp(wp_content)

        for section in cfg.sections():
            def_values = {"id": section}
            for name, value in cfg.items(section):
                # coerce boolean variables
                if name in cls._bool_values:
                    def_values[name] = cfg.getboolean(section, name)
                else:
                    def_values[name] = value

            try:
                item = cls(**def_values)
            except TypeError:
                # a required variable wasn't set for this item, skip
                continue

            if item.is_enabled:
                items[section] = item

        return items if return_dict else items.values()
class DashboardClassManager(object):
    """
    Class to handle registered dashboards class.
    """

    _register = OrderedDict()

    def __init__(self):
        self._register = OrderedDict()

    def register(self, slug, rclass):
        if slug in self._register:
            raise ValueError("Slug already exists: %s" % slug)
        setattr(rclass, "slug", slug)
        self._register[slug] = rclass

    def get_dashboard(self, slug):
        # return class
        print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        print slug
        print self._register.values()
        return self._register.get(slug, None)

    def get_dashboards(self):
        # return clasess
        return self._register.values()