Example #1
1
File: swig.py Project: jhbsz/ns3psm
def _swigEmitter(target, source, env):
    swigflags = env.subst("$SWIGFLAGS", target=target, source=source)
    flags = SCons.Util.CLVar(swigflags)
    for src in source:
        src = str(src.rfile())
        mnames = None
        if "-python" in flags and "-noproxy" not in flags:
            if mnames is None:
                mnames, directors = _find_modules(src)
            if directors:
                _add_director_header_targets(target, env)
            target.extend(map(lambda m, d=target[0].dir: d.File(m + ".py"), mnames))
        if "-java" in flags:
            if mnames is None:
                mnames, directors = _find_modules(src)
            if directors:
                _add_director_header_targets(target, env)
            java_files = map(lambda m: [m + ".java", m + "JNI.java"], mnames)
            java_files = SCons.Util.flatten(java_files)
            outdir = env.subst("$SWIGOUTDIR", target=target, source=source)
            if outdir:
                java_files = map(lambda j, o=outdir: os.path.join(o, j), java_files)
            java_files = map(env.fs.File, java_files)
            for jf in java_files:
                t_from_s = lambda t, p, s, x: t.dir
                SCons.Util.AddMethod(jf, t_from_s, "target_from_source")
            target.extend(java_files)
    return (target, source)
Example #2
1
    def dehydrate_members(self, bundle):
        rangesString = bundle.request.GET.get("ranges", None)
        fullRange = rangesString is None
        if not fullRange:
            ranges = map(
                lambda rangeString: [datetime.strptime(val, "%Y%m") if val else None for val in rangeString.split("-")],
                rangesString.split(","),
            )
            mks_values = dict(bundle.obj.get_mks_values(ranges))
        else:
            mks_values = dict(bundle.obj.get_mks_values())
        members = []
        for mk in Member.objects.filter(pk__in=mks_values.keys(), current_party__isnull=False).select_related(
            "current_party"
        ):
            # TODO: this sucks, performance wise
            current_party = mk.current_party
            mk_data = mks_values[mk.id]
            members.append(
                dict(
                    id=mk.id,
                    name=mk.name,
                    score=map(itemgetter("score"), mk_data) if type(mk_data) is not dict else mk_data["score"],
                    rank=map(itemgetter("rank"), mk_data) if type(mk_data) is not dict else mk_data["rank"],
                    volume=map(itemgetter("volume"), mk_data) if type(mk_data) is not dict else mk_data["volume"],
                    numvotes=map(itemgetter("numvotes"), mk_data) if type(mk_data) is not dict else mk_data["numvotes"],
                    absolute_url=mk.get_absolute_url(),
                    party=current_party.name,
                    party_url=current_party.get_absolute_url(),
                    party_id=current_party.pk,
                )
            )

        return members
def getDoing(_InstanceVariable, _DoClassVariable=None):

    # check
    DoClassesList = SYS.GetList(_DoClassVariable, SYS)
    if len(DoClassesList) == 0:
        DoClassesList = _InstanceVariable.__class__.MroDoerClassesList

        # Debug
    """
	print('l 83 Doer')
	print('DoClassesList is ',DoClassesList)
	print('')
	"""

    # return
    return collections.OrderedDict(
        SYS.sum(
            map(
                lambda __DoClass: zip(
                    __DoClass.DoingAttributeVariablesOrderedDict.keys(),
                    map(
                        lambda __DoneKeyStr: getattr(_InstanceVariable, __DoneKeyStr),
                        __DoClass.DoingAttributeVariablesOrderedDict.keys(),
                    ),
                ),
                DoClassesList,
            )
        )
    )
def partition_additional_stems(base_form_partition, stems):
    base_form = "".join(map(operator.itemgetter(1), base_form_partition))
    base_stem_found = False

    stems = split_stems(stems, True)
    new_stems = []
    for i, stem in enumerate(stems):
        name = None
        if type(stem) == tuple:
            name, stem = stem

        if base_form[: len(stem)] == stem:
            base_stem_found = True

        partition = partition_additional_stem(stem, base_form_partition)
        if partition is None:
            #            print(lineno(), stems, stem)
            return

        stem = " ".join(map(lambda p: p[0] + "_" + p[1], partition))
        if name is None:
            new_stems.append(stem)
        else:
            new_stems.append("{}={}".format(name, stem))

    if not base_stem_found:
        print(lineno(), template_name, base_form_partition, stems)
        return

    return new_stems
Example #5
1
 def computeErrors(cls, logText):
     warnings = {}
     currentModule = None
     warningsCurrentModule = []
     for line in StringIO.StringIO(logText):
         # Mostly get rid of the trailing \n
         line = line.strip("\n")
         if line.startswith(cls.prefixModuleName):
             # Save results for previous module
             if currentModule:
                 warnings[currentModule] = set(map(TwistedCheckerError, warningsCurrentModule))
             # Initial results for current module
             moduleName = line.replace(cls.prefixModuleName, "")
             currentModule = moduleName
             warningsCurrentModule = []
         elif re.search(cls.regexLineStart, line):
             warningsCurrentModule.append(line)
         else:
             if warningsCurrentModule:
                 warningsCurrentModule[-1] += "\n" + line
             else:
                 log.msg("Bad result format for %s" % currentModule)
     # Save warnings for last module
     if currentModule:
         warnings[currentModule] = set(map(TwistedCheckerError, warningsCurrentModule))
     return warnings
    def node_update_front(self):
        """
        Return a list of nodes on the update front, i.e. nodes scheduled for
        an update that have no ancestor which is either itself scheduled
        for update or is in a blocking state)

        .. note::
            The node's ancestors are only computed over enabled links.

        """
        scheme = self.scheme()

        blocking_nodes = set(self.blocking_nodes())

        dependents = partial(dependent_nodes, scheme)

        blocked_nodes = reduce(set.union, map(dependents, blocking_nodes), set(blocking_nodes))

        pending = set(self.pending_nodes())

        pending_downstream = reduce(set.union, map(dependents, pending), set())

        log.debug("Pending nodes: %s", pending)
        log.debug("Blocking nodes: %s", blocking_nodes)

        return list(pending - pending_downstream - blocked_nodes)
def make_examples_simple(data_dir, n_users, negative_examples_per_user=10):
    G = snap.LoadEdgeList(snap.PUNGraph, data_dir + "graph.txt", 0, 1)
    new_edges = defaultdict(dict)
    with open(data_dir + "new_edges.txt") as f:
        for line in f:
            u, b = map(int, line.split())
            new_edges[u][b] = 1

    businesses = map(int, util.load_json(data_dir + "business.json").keys())
    examples = defaultdict(dict)
    users = random.sample([NI.GetId() for NI in G.Nodes()], n_users)
    for u in users:
        examples[u] = new_edges[u]
        for i in range(negative_examples_per_user):
            b = random.choice(businesses)
            examples[u][b] = 0

    p, n = 0, 0
    for u in examples:
        for b in examples[u]:
            p += examples[u][b]
            n += 1 - examples[u][b]
    print "Positive:", p
    print "Negative:", n
    print "Data skew:", p / float(p + n)
    print "Sampling rate:", negative_examples_per_user / float(len(businesses))

    print "Writing examples..."
    util.write_json(examples, data_dir + "examples_simple.json")
def sqmat():
    """
    computes Squared values of each element in the matrix
    """
    test = input()
    for idx in range(test):
        matdim = input()
        maxsize = [0 for _ in range(matdim)]
        matrix = []
        for _ in range(matdim):
            mat = map(int, raw_input().split())
            assert len(mat) == matdim
            mat = map(square, mat)
            pos = 0
            for num in mat:
                length = len(str(num))
                if maxsize[pos] < length:
                    maxsize[pos] = length
                pos += 1
            matrix.append(mat)
        print "Quadrado da matriz #%i:" % (idx + 4)
        start = 0
        for opmat in matrix:
            pos = 0
            for val in opmat:
                print "{0:>{1}}".format(val, maxsize[pos]),
                pos += 1
            if start < matdim - 1:
                print ""
            start += 1
        print "\n"
Example #9
1
    def test_smart_strings(self):
        """Lxml smart strings return values"""

        class SmartStringsSelector(Selector):
            _lxml_smart_strings = True

        body = """<body>
                    <div class='one'>
                      <ul>
                        <li>one</li><li>two</li>
                      </ul>
                    </div>
                    <div class='two'>
                      <ul>
                        <li>four</li><li>five</li><li>six</li>
                      </ul>
                    </div>
                  </body>"""

        response = HtmlResponse(url="http://example.com", body=body)

        # .getparent() is available for text nodes and attributes
        # only when smart_strings are on
        x = self.sscls(response)
        li_text = x.xpath("//li/text()")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), div_class)))

        x = SmartStringsSelector(response)
        li_text = x.xpath("//li/text()")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), div_class)))
def main():
    parser = argparser()
    args = parser.parse_args()

    try:
        nbFeat = -1
        with open(args.filename) as f:
            input = [[int(a) for a in line.strip().split()] for line in f]
            for k in range(0, len(input)):
                input[k] = input[k][3:]
                nbFeat = max(nbFeat, *input[k])
        if args.outputfile == "":
            print "{0} {1}".format(nbFeat + 1, len(input))  # Format => <nbFeat> <nbSamples>\n
            print "\n".join(
                ["{0} {1}".format(len(row), " ".join(map(str, row))) for row in input]
            )  # Format => <length> <f1> ... <fn>
        else:
            with open(args.outputfile, "w") as f:
                f.write("{0} {1}\n".format(nbFeat + 1, len(input)))  # Format => <nbFeat> <nbSamples>\n
                f.write(
                    "\n".join(["{0} {1}".format(len(row), " ".join(map(str, row))) for row in input])
                )  # Format => <length> <f1> ... <fn>

    except Exception as e:
        print >> sys.stderr, "Oops, something wrong!", e
        print >> sys.stderr, sys.exc_info()
        sys.exit(0)
Example #11
0
def topological_sort(elems):
    """ Return a list of elements sorted so that their dependencies are listed
    before them in the result.

    :param elems: specifies the elements to sort with their dependencies; it is
        a dictionary like `{element: dependencies}` where `dependencies` is a
        collection of elements that must appear before `element`. The elements
        of `dependencies` are not required to appear in `elems`; they will
        simply not appear in the result.

    :returns: a list with the keys of `elems` sorted according to their
        specification.
    """
    # the algorithm is inspired by [Tarjan 1976],
    # http://en.wikipedia.org/wiki/Topological_sorting#Algorithms
    result = []
    visited = set()

    def visit(n):
        if n not in visited:
            visited.add(n)
            if n in elems:
                # first visit all dependencies of n, then append n to result
                map(visit, elems[n])
                result.append(n)

    map(visit, elems)

    return result
def chooseBestPicture(d):

    # get the stats from the pictures you're considering
    max_consider = 5
    files = os.listdir(d)[0:max_consider]
    files = map(lambda f: d + os.sep + f, files)  # add directory to filename
    stats = map(lambda f: countComponents(f), files)
    densities = map(lambda i: stats[i][1], range(max_consider))
    components = map(lambda i: stats[i][0], range(max_consider))
    disjoints = map(lambda i: stats[i][2], range(max_consider))

    # once you have the stats to consider, get rid of the highest one from
    # the components, the highest one from the densities, only way to override the rank
    # is to be more than 1 std dev below the mean
    # calculate the stats
    mean_c = avg(components)
    stdDev_c = standardDev(components)
    mean_d = avg(densities)
    stdDev_d = avg(densities)

    # get rid of the maxs
    files.pop(indexMax(components))
    densities.pop(indexMax(components))
    disjoints.pop(indexMax(components))
    files.pop(indexMax(densities))

    # files.pop(indexMax(disjoints))
    # densities.pop(indexMax(disjoints))
    # calculate the relative differences
    # return files[disjoints.index(min(disjoints))]
    print files[disjoints.index(min(disjoints))]
    """
def hexdump(data):
    printable = "".join(map(chr, range(33, 127)))
    data_len = len(data)
    dump = []
    while data:
        r = data[:8]
        data = data[8:]
        s = "   "
        s += ", ".join(map(lambda x: "0x%02x" % x, map(ord, r)))
        if data:
            s += ", "
        else:
            s += " " * (2 + 6 * (8 - len(r)))
        cm = ""
        for c in r:
            if c in printable:
                cm += c
            else:
                cm += "."
        if "*/" in cm:
            cm = cm.replace("*/", "./")
        if "/*" in cm:
            cm = cm.replace("/*", "/.")
        s += "/* %s */" % cm
        dump.append(s)
    return "\n".join(dump)
Example #14
0
def parse_range(number_string):
    """Parse a range and return a tuple with a low and high number as floats.

    We will also parse regular numbers, in which case the tuple will
    only have one item.
    """
    if type(number_string) in [int, float]:
        return (float(number_string), None)
    nums = convert.RANGE_MATCHER.split(number_string.strip())
    if len(nums) > 2:
        debug("WARNING: String %s does not appear to be a normal range." % number_string, 0)
        retval = map(convert.frac_to_float, nums)
        # filter any non-numbers before we take 1 and 3
        retval = filter(lambda x: x, retval)
        if len(retval) > 2:
            debug("Parsing range as %s-%s" % (retval[0], retval[-1]), 0)
            retval = retval[0], retval[-1]
    else:
        retval = map(convert.frac_to_float, nums)
    if len(retval) == 2:
        return tuple(retval)
    elif len(retval) == 1:
        return tuple(retval + [None])
    else:
        return (None, None)
Example #15
0
def getRevisionsFromDB(project, m, jdbc):
    dataFile = project + "-connector.data"
    if os.path.exists(dataFile):
        contents = open(dataFile).read()
    else:
        args = " '" + project + "' '" + m + "' "
        jdbc = "'" + jdbc + "'"
        cmd = genericsConnector + args + jdbc + " --git"
        print cmd
        fd = os.popen(cmd)
        contents = fd.read()
        dataFile = open(dataFile, "w")
        dataFile.write(contents)
        dataFile.close()
        if fd.close():
            raise Exception("command failed: " + cmd)
    lines = contents.split("\n")

    transactions = {}
    transaction = lines[0].split(";")[0]
    lastTransaction = transaction
    group = []
    for line in lines:
        if line == "":
            continue
        transaction, revision, file, date, state = line.split(";")
        if not transaction == lastTransaction:
            transactions[transaction] = group
            group = []
        group.append((transaction, revision, file, date, state))
        lastTransaction = transaction
        # last group
    transactions[transaction] = group
    print map(int, transactions.keys())
    return transactions
Example #16
0
 def _element_ns(self, n):
     """ handle an ElementNode with NS interface"""
     ## convert DOM namedNodeMap to SAX attributes NS
     prefix_list = []
     nnm = n.attributes
     attrs, qnames = {}, {}
     for a in nnm.values():
         a_uri = a.namespaceURI
         if a_uri == XMLNS_NS:
             prefix, val = a.localName, a.value
             self._cont_handler.startPrefixMapping(prefix, val)
             prefix_list.append(prefix)
             if self._ns_prfx:
                 name = (a_uri, prefix)
                 attrs[name] = val
                 qnames[name] = a.nodeName
         else:
             name = (a_uri, a.localName)
             attrs[name] = a.value
             qnames[name] = a.nodeName
     ## handle element NS
     name = (n.namespaceURI, n.localName)
     self._cont_handler.startElementNS(name, n.nodeName, AttributesNSImpl(attrs, qnames))
     self._from_dom(n.firstChild)
     self._cont_handler.endElementNS(name, n.nodeName)
     prefix_list.reverse()
     map(self._cont_handler.endPrefixMapping, prefix_list)
Example #17
0
def virshlist(*states):

    libvirt_states = {
        "running": libvirt.VIR_DOMAIN_RUNNING,
        "shutoff": libvirt.VIR_DOMAIN_SHUTOFF,
        "shutdown": libvirt.VIR_DOMAIN_SHUTDOWN,
        "paused": libvirt.VIR_DOMAIN_PAUSED,
        "nostate": libvirt.VIR_DOMAIN_NOSTATE,
        "blocked": libvirt.VIR_DOMAIN_BLOCKED,
        "crashed": libvirt.VIR_DOMAIN_CRASHED,
    }

    searchstates = list(libvirt_states[state] for state in states)

    conn = libvirt.openReadOnly(driver)
    if conn == None:
        print "Failed to open connection to the hypervisor"
        sys.exit(3)

    alldomains = map(conn.lookupByID, conn.listDomainsID())
    alldomains += map(conn.lookupByName, conn.listDefinedDomains())

    domains = []
    for domain in alldomains:
        if domain.info()[0] in searchstates:
            domains.append(domain.name())

    conn.close()

    return domains
Example #18
0
    def do_guess(self, guess, who):
        """ process a guess """

        answer_letters = map(lambda x: x, self.answer)
        clue_letters = map(lambda x: x, self.clue)

        if guess in self.letters:
            return guess + " has already been guessed"
        else:
            self.letters += guess

        for x in range(len(self.answer)):
            if clue_letters[x] == BLANK and answer_letters[x].lower() == guess.lower():
                clue_letters[x] = answer_letters[x]

        if " ".join(clue_letters) != self.clue:
            self.clue = " ".join(clue_letters)
            self.score(who, "GUESS", self.clue.count(guess))
            if BLANK not in self.clue:
                self.reset()
                return "Right, " + who + "! score: " + str(self.get_score(who))
            else:
                return "good guess, " + who + " (" + str(self.get_score(who)) + "): " + self.clue
        else:
            self.score(who, "GUESS")
            return "bad guess, " + who + " (" + str(self.get_score(who)) + ")"
Example #19
0
def flatten(list):
    """Flatten a list of elements into a uniqu list
    Author: Christophe Simonis (christophe@tinyerp.com)

    Examples::
    >>> flatten(['a'])
    ['a']
    >>> flatten('b')
    ['b']
    >>> flatten( [] )
    []
    >>> flatten( [[], [[]]] )
    []
    >>> flatten( [[['a','b'], 'c'], 'd', ['e', [], 'f']] )
    ['a', 'b', 'c', 'd', 'e', 'f']
    >>> t = (1,2,(3,), [4, 5, [6, [7], (8, 9), ([10, 11, (12, 13)]), [14, [], (15,)], []]])
    >>> flatten(t)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    """

    def isiterable(x):
        return hasattr(x, "__iter__")

    r = []
    for e in list:
        if isiterable(e):
            map(r.append, flatten(e))
        else:
            r.append(e)
    return r
Example #20
0
    def generate_abc(self):
        """Returns a list of available characters selected by user"""
        abc = []

        if self.dialog.chbox_use_digits.checkState() == Qt.Checked:
            abc.extend(map(str, range(0, 10)))

        if self.dialog.chbox_use_letters.checkState() == Qt.Checked:
            abc.extend(map(chr, range(97, 123)))
            abc.extend(map(chr, range(65, 91)))

        qcheckbox_class_name = type(QCheckBox()).__name__

        if self.dialog.chbox_use_symbols.checkState() == Qt.Checked:

            for check_box in self.dialog.groupBox_Symbols.children():

                if type(check_box).__name__ == qcheckbox_class_name:

                    if check_box.checkState() == Qt.Checked:

                        if check_box.text() == "space":
                            abc.append(" ")
                        elif check_box.text() == "\\":
                            abc.append("\\")
                        elif check_box.text() == "&&":
                            abc.append("&")
                        else:
                            abc.append(str(check_box.text()))
        return abc
Example #21
0
 def visit(n):
     if n not in visited:
         visited.add(n)
         if n in elems:
             # first visit all dependencies of n, then append n to result
             map(visit, elems[n])
             result.append(n)
    def _dev_int_context(self, ec):
        segment_choices = []
        for segment in self.segments:
            results = map(
                lambda x: reduce(operator.mul, map(lambda i: self.app_pool[x][i][ec[i]], xrange(self.feature_num)), 1),
                segment,
            )
            score = reduce(operator.mul, results, 1)
            segment_choices.append((segment, score))

        app_choices = []
        for app in self.app_pool.keys():
            score = reduce(operator.mul, map(lambda i: self.app_pool[app][i][ec[i]], xrange(self.feature_num)), 1)
            app_choices.append((app, score))

        int_context = []
        segment = nonrandom.choice(segment_choices)
        # turning_point = random.choice(xrange(1, self.l)) if random.random() > 0.3 else -1
        for i in xrange(self.l):
            # if i == turning_point:
            if random.random() > 0.9:
                segment = nonrandom.choice(filter(lambda x: x != segment, segment_choices))

            s = list(segment)
            for j in xrange(self.s):
                if random.random() < self.c:
                    s[j] = nonrandom.choice(app_choices) if random.random() > 0.7 else None
            s = filter(lambda x: x, s)
            if not s:
                s = list(segment)
            int_context.extend(s)

        return int_context
def computeDistanceMus21(melody_a, melody_b, parameters=["rhythm", "harmony", "contour"]):
    harmony_distance, rhythm_distance, contour_distance = 0, 0, 0

    if any("harmony" in parameters, "contour" in parameters):
        melody_a_midinotes = map(lambda x: x.midi, melody_a.pitches)
        melody_b_midinotes = map(lambda x: x.midi, melody_b.pitches)

    if "rhythm" in parameters:
        melody_a_durs = map(lambda x: x.duration.quarterLength, melody_a.flat.notes)
        melody_b_durs = map(lambda x: x.duration.quarterLength, melody_b.flat.notes)

    if "harmony" in parameters:
        harmony_distance, _ = DTW(melody_a_midinotes, melody_b_midinotes)

    if "rhythm" in parameters:
        rhythm_distance, _ = DTW(melody_a_durs, melody_b_durs)

    if "contour" in parameters:
        lick1_np = np.array(melody_a_midinotes)
        lick2_np = np.array(melody_b_midinotes)

        lick1_intervals = lick1_np[1:] - lick1_np[:-1]
        lick2_intervals = lick2_np[1:] - lick2_np[:-1]

        contour_distance, _ = DTW(lick1_intervals, lick2_intervals, intervalicDistance)

    return harmony_distance + rhythm_distance + contour_distance
 def get_env_context_distrs(self, logs, export=True):
     logs = map(lambda x: self._format(x), logs)
     env_context_distrs = map(lambda i: self._get_feature_distr(i, logs), range(3))
     if export:
         for i in xrange(len(self.feature_names)):
             self._export_att_weights(self.feature_names[i], env_context_distrs[i])
     return env_context_distrs
Example #25
0
def test_format(obj, precision=6):
    tf = lambda o: test_format(o, precision)
    delimit = lambda o: ", ".join(o)
    otype = type(obj)
    if otype is str:
        return "'%s'" % obj
    elif otype is float or otype is int:
        if otype is int:
            obj = float(obj)
        fstr = "%%.%df" % precision
        return fstr % obj
    elif otype is set:
        if len(obj) == 0:
            return "set()"
        return "{%s}" % delimit(sorted(map(tf, obj)))
    elif otype is dict:
        return "{%s}" % delimit(sorted(tf(k) + ": " + tf(v) for k, v in obj.items()))
    elif otype is list:
        return "[%s]" % delimit(map(tf, obj))
    elif otype is tuple:
        return "(%s%s)" % (delimit(map(tf, obj)), "," if len(obj) is 1 else "")
    elif otype.__name__ in ["Vec", "Mat"]:
        entries = delimit(map(tf, sorted(filter(lambda o: o[1] != 0, obj.f.items()))))
        return "<%s %s {%s}>" % (otype.__name__, test_format(obj.D), entries)
    else:
        return str(obj)
Example #26
0
    def _get_formatted_column_labels(self):
        from pandas.core.index import _sparsify

        def is_numeric_dtype(dtype):
            return issubclass(dtype.type, np.number)

        if isinstance(self.columns, MultiIndex):
            fmt_columns = self.columns.format(sparsify=False, adjoin=False)
            fmt_columns = zip(*fmt_columns)
            dtypes = self.frame.dtypes.values
            need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes)))
            str_columns = zip(
                *[[" " + y if y not in self.formatters and need_leadsp[x] else y for y in x] for x in fmt_columns]
            )
            if self.sparsify:
                str_columns = _sparsify(str_columns)

            str_columns = [list(x) for x in zip(*str_columns)]
        else:
            fmt_columns = self.columns.format()
            dtypes = self.frame.dtypes
            need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes)))
            str_columns = [
                [" " + x if col not in self.formatters and need_leadsp[x] else x]
                for col, x in zip(self.columns, fmt_columns)
            ]

        if self.show_index_names and self.has_index_names:
            for x in str_columns:
                x.append("")

        return str_columns
def setDone(_InstanceVariable, _DoClassVariable=None, **_KwargVariablesDict):

    # Debug
    """
	print('l 137 Doer setDone before check')
	print('_DoClassVariable is ',_DoClassVariable)
	print('')
	"""

    # check
    DoClassesList = SYS.GetList(_DoClassVariable, SYS)
    if len(DoClassesList) == 0:
        DoClassesList = _InstanceVariable.__class__.MroDoerClassesList

        # Debug
    """
	print('l 153 Doer')
	print('_DoClassVariable is ',_DoClassVariable)
	print('')
	"""

    # map
    map(
        lambda __DoClass: _InstanceVariable.setDefault(
            __DoClass,
            __DoClass.DoneAttributeVariablesOrderedDict.keys(),
            **dict(_KwargVariablesDict, **{"DefaultMutableBool": True})
        ),
        DoClassesList,
    )

    # return
    return _InstanceVariable
Example #28
0
        def next(meas_obj, tolerance, fa, future):
            start = time()

            tmp = list(meas_obj.eventTypes)
            while tmp:
                map(lambda et: tmp.remove(et), meas_obj.metadata.keys())
                sleep(5)

            """
            while '%'.join([meas_obj.selfRef, BANDWIDTH]) not in self.unisrt.metadata['existing'] and time() - start < tolerance:
                logger.info("The measurement has not run yet")
                logger.info("waiting for {sec} more seconds...".format(max(0, start + tolerance - time())))
                sleep(5)
            """

            remain = max(0, start + tolerance - time())
            if remain == 0:
                return None

            ret = {}
            fa_module = __import__(fa, fromlist=[fa])
            for et, md in meas_obj.metadata.iteritems():
                while not md["historical"]:
                    sleep(5)
                # to keep a unified return format
                ret[et] = {"forecasted": fa_module.calc(self.unisrt, meas_obj, md["historical"], future, remain)}

            return ret
Example #29
0
def test_add():
    x, y, a, b, c = map(Symbol, "xyabc")
    p, q, r = map(Wild, "pqr")

    e = a + b
    assert e.match(p + b) == {p: a}
    assert e.match(p + a) == {p: b}

    e = 1 + b
    assert e.match(p + b) == {p: 1}

    e = a + b + c
    assert e.match(a + p + c) == {p: b}
    assert e.match(b + p + c) == {p: a}

    e = a + b + c + x
    assert e.match(a + p + x + c) == {p: b}
    assert e.match(b + p + c + x) == {p: a}
    assert e.match(b) is None
    assert e.match(b + p) == {p: a + c + x}
    assert e.match(a + p + c) == {p: b + x}
    assert e.match(b + p + c) == {p: a + x}

    e = 4 * x + 5
    assert e.match(4 * x + p) == {p: 5}
    assert e.match(3 * x + p) == {p: x + 5}
    assert e.match(p * x + 5) == {p: 4}
Example #30
0
def index():
    if request.method == "GET":
        signature = request.args.get("signature")
        timestamp = request.args.get("timestamp")
        nonce = request.args.get("nonce")
        echostr = request.args.get("echostr")
        list = [Token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, list)
        hashcode = sha1.hexdigest()
        if hashcode == signature:
            return echostr
        else:
            return "error"
    else:
        rec = request.stream.read()
        xml_rec = ET.fromstring(rec)
        tou = xml_rec.find("ToUserName").text
        fromu = xml_rec.find("FromUserName").text
        info = xml_rec.find("Content").text
        if info == u"\u6210\u7ee9":
            content = u"\u8bf7\u6309\u4e0b\u9762\u683c\u5f0f\u8f93\u5165\u002c\u4f8b\u5982\u003a\u000d\u000a\u002b\u53f7\u4e5f\u8981\u5199\u54e6\uff01\uff01\uff01\u000d\u000a\u6210\u7ee9\u002b\u0031\u0033\u0030\u0036\u0030\u0031\u0031\u0031\u0031\u002b\u0031\u0031\u0031"
        else:
            s = info.split("+")[0]
            if s == u"\u6210\u7ee9":
                name = info.split("+")[1]
                pas = info.split("+")[2]
                content = chengji(name, pas)
            else:
                content = Tuling(info)
        xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
        response = make_response(xml_rep % (fromu, tou, str(int(time.time())), content))
        response.content_type = "application/xml"
        return response