Example #1
1
    def correctName(self, check_name, movie_name):

        check_names = [check_name]
        try:
            check_names.append(re.search(r'([\'"])[^\1]*\1', check_name).group(0))
        except:
            pass

        for check_name in check_names:
            check_movie = fireEvent("scanner.name_year", check_name, single=True)

            try:
                check_words = filter(None, re.split("\W+", check_movie.get("name", "")))
                movie_words = filter(None, re.split("\W+", simplifyString(movie_name)))

                if (
                    len(check_words) > 0
                    and len(movie_words) > 0
                    and len(list(set(check_words) - set(movie_words))) == 0
                ):
                    return True
            except:
                pass

        return False
Example #2
1
    def KeepOneLeaf(this_node):

        keep_leaves = []
        leaf_dict = {}

        tree = this_node.tree
        leaves = this_node.leaf_nodes
        f_leaves = filter(lambda i: not i.is_rep, leaves)
        k_leaves = filter(lambda i: i.is_rep, leaves)

        # get filter counts
        for filt in this_node.tree.species_count.keys():
            leaf_dict[filt] = 0
        for leaf in f_leaves:
            leaf_dict[leaf.species] += 1

        if len(k_leaves) > 0:
            keep_leaves.append(k_leaves[0])

        # keep the eldest leaf (that isn't a representative of a
        # sub-cluster)
        keep_leaf = f_leaves[0]

        for leaf_ind in range(1, len(f_leaves)):
            this_leaf = f_leaves[leaf_ind]
            this_leaf.RemoveLeaf()

        keep_leaf.is_rep = True
        keep_leaves.append(keep_leaf)
        parent = this_node.GetParent()
        parent.AddLeaf(keep_leaf)

        return keep_leaves, leaf_dict
def intersectYASP(ListOfFile):
    """Pure intersection of all bpm names in all files """
    if len(ListOfFile) == 0:
        print "Nothing to intersect!!!!"
        sys.exit()
    h = ListOfFile[0].HNAME
    count = 0
    for b in ListOfFile:
        if len(b.HNAME) == 0:
            break
        else:
            h = filter(lambda x: x in h, b.HNAME)
            count = count + 1
        # h=filter(lambda x: x in h   , b.HNAME)
    turns = count
    v = ListOfFile[0].VNAME
    for b in ListOfFile:
        if len(b.VNAME) == 0:
            break
        else:
            v = filter(lambda x: x in v, b.VNAME)
        v = filter(lambda x: x in v, b.VNAME)

    print "Number of turns that can be used ", str(turns)

    return h, v, turns
Example #4
1
    def tasks_by_attribs(self, attribs, union=False):
        """This function find tasks by attribute strings.  Attribs can 
		be a single string, or a list of strings.  Union is true/false to 
		indiicateds if a union (or intersection) is returned. Defautls to intersection.
		Returns a list of Task objects."""
        # union = True = take the union of all attribs
        # union = false = take the join of
        _gLog.debug("find_by_attrib")

        if type(attribs) is not list:
            attribs = [attribs]

        retList = None

        for attribString in attribs:
            if attribString[0] != "@":
                attribString = "@" + attribString

            newSet = filter(lambda task: attribString in task.attribs, self.taskList)

            if retList is None:
                retList = newSet
            if union == True:
                toAdd = filter(lambda newTask: newTask not in retList, newSet)
                retList.extend(toAdd)
            else:
                retList = filter(lambda knownTask: knownTask in newSet, retList)

        return retList
Example #5
1
def create():
    out = []
    l = variables.keys()
    l.sort
    main_modules = filter(lambda x: modules[x].is_main, modules)
    finalize = "subroutine irp_finalize_%s\n" % (irp_id)
    for m in filter(lambda x: not modules[x].is_main, modules):
        finalize += " use %s\n" % (modules[m].name)
    for v in l:
        var = variables[v]
        var_in_main = False
        for m in main_modules:
            if var.fmodule == modules[m].name:
                var_in_main = True
                break
        if not var_in_main:
            if var.is_touched:
                out += var.toucher
            if var.dim != []:
                finalize += "  if (allocated(%s)) then\n" % v
                finalize += "    %s_is_built = .False.\n" % var.same_as
                finalize += "    deallocate(%s)\n" % v
                finalize += "  endif\n"
    finalize += "end\n"

    if out != []:
        out = map(lambda x: "%s\n" % (x), out)

    out += finalize

    if not same_file(FILENAME, out):
        file = open(FILENAME, "w")
        file.writelines(out)
        file.close()
Example #6
1
def getNewznabProviderList(data):

    defaultList = [makeNewznabProvider(x) for x in getDefaultNewznabProviders().split("!!!")]
    providerList = filter(lambda x: x, [makeNewznabProvider(x) for x in data.split("!!!")])

    providerDict = dict(zip([x.name for x in providerList], providerList))

    for curDefault in defaultList:
        if not curDefault:
            continue

        # a 0 in the key spot indicates that no key is needed, so set this on the object
        if curDefault.key == "0":
            curDefault.key = ""
            curDefault.needs_auth = False

        if curDefault.name not in providerDict:
            curDefault.default = True
            providerList.append(curDefault)
        else:
            providerDict[curDefault.name].default = True
            providerDict[curDefault.name].name = curDefault.name
            providerDict[curDefault.name].url = curDefault.url
            providerDict[curDefault.name].needs_auth = curDefault.needs_auth

    return filter(lambda x: x, providerList)
Example #7
0
    def FilterMembersWithUnidentifiedTypes(self, database):
        """Removes unidentified types.

    Removes constants, attributes, operations and parents with unidentified
    types.
    """

        for interface in database.GetInterfaces():

            def IsIdentified(idl_node):
                node_name = idl_node.id if idl_node.id else "parent"
                for idl_type in idl_node.all(idlnode.IDLType):
                    type_name = idl_type.id
                    if type_name is not None and self._IsCompoundType(database, type_name):
                        continue
                    _logger.warn(
                        "removing %s in %s which has unidentified type %s" % (node_name, interface.id, type_name)
                    )
                    return False
                return True

            interface.constants = filter(IsIdentified, interface.constants)
            interface.attributes = filter(IsIdentified, interface.attributes)
            interface.operations = filter(IsIdentified, interface.operations)
            interface.parents = filter(IsIdentified, interface.parents)
    def _get_file_listing(self, phrase=None, new_only=True):
        self.jhep_list = []
        self.epjc_list = []
        self.files_list = []

        self.ftp.cd("data/in")

        if phrase:
            self.epjc_list.extend(filter(lambda x: phrase in x and ".zip" in x, self.ftp.ls("EPJC")[0]))
            self.jhep_list.extend(filter(lambda x: phrase in x and ".zip" in x, self.ftp.ls("JHEP")[0]))
        else:
            self.epjc_list.extend(filter(lambda x: ".zip" in x, self.ftp.ls("EPJC")[0]))
            self.jhep_list.extend(filter(lambda x: ".zip" in x, self.ftp.ls("JHEP")[0]))

        self.files_list.extend(map(lambda x: "EPJC/" + x, self.epjc_list))
        self.files_list.extend(map(lambda x: "JHEP/" + x, self.jhep_list))

        if new_only:
            tmp_our_dir = []
            for di in ["EPJC/", "JHEP/"]:
                try:
                    tmp_our_dir.extend(map(lambda x: di + x, listdir(join(CFG_TAR_FILES, di))))
                except OSError:  # folders does not exists nothing to do
                    pass

            self.files_list = set(self.files_list) - set(tmp_our_dir)

        return self.files_list
def writeCodeBlock(block, autoescape, namespace, localVars, indentLevel, out):
    cmds = filter(None, block)

    for i in xrange(len(cmds)):
        if isinstance(cmds[i], Substition):
            char = block[i].char

            if char == " ":
                cmds[i] = " "
            elif char == "\r":
                cmds[i] = "\\r"
            elif char == "\n":
                cmds[i] = "\\n"
            elif char == "\t":
                cmds[i] = "\\t"
            elif char == "{" or char == "}":
                cmds[i] = char
            elif char == "":
                cmds[i] = None
            else:
                raise char
                cmds[i] = None

    for cmd in filter(None, cmds):
        writeCommand(cmd, autoescape, namespace, localVars, indentLevel, out)
Example #10
0
    def _calcYScaling(self):
        """Calculates y scaling. Can be used 'as-is' for most purposes.
        
        """
        # The filter is necessary because unfortunately the value 'None' is not
        # excluded from min and max (i.e., min(None, x) is not necessarily x).
        # The try block is necessary because min of an empty list throws a
        # ValueError exception.
        ymin = ymax = None
        for line in self.line_list:
            if line.line_type == "vector":
                try:
                    yline_max = max(abs(c) for c in filter(lambda v: v is not None, line.y))
                except ValueError:
                    yline_max = None
                yline_min = -yline_max if yline_max is not None else None
            else:
                try:
                    yline_min = min(filter(lambda v: v is not None, line.y))
                except ValueError:
                    yline_min = None
                try:
                    yline_max = max(filter(lambda v: v is not None, line.y))
                except ValueError:
                    yline_max = None
            ymin = min(yline_min, ymin) if ymin is not None else yline_min
            ymax = max(yline_max, ymax) if ymax is not None else yline_max

        if ymin is None and ymax is None:
            # No valid data. Pick an arbitrary scaling
            self.yscale = (0.0, 1.0, 0.2)
        else:
            self.yscale = weeplot.utilities.scale(ymin, ymax, self.yscale)
def listify(value):
    if isinstance(value, unicode):
        return filter(None, map(unicode.strip, value.split(";")))  # filter removes empty strings
    elif isinstance(value, list):
        return filter(None, map(unicode.strip, value[0].split(";")))
    else:
        return []
Example #12
0
    def getNext2UnlockByItems(self, itemCDs, unlocked=set(), xps=None, freeXP=0):
        filtered = filter(lambda item: item in self.__topItems, itemCDs)
        if not len(filtered) or not len(unlocked):
            return {}
        available = defaultdict(list)
        parentCDs = set(filter(lambda item: getTypeOfCompactDescr(item) == _VEHICLE, itemCDs))
        for item in filtered:
            if item in unlocked:
                parentCDs |= self.__topItems[item]

        for parentCD in parentCDs:
            if parentCD not in unlocked:
                continue
            nextLevel = self.__nextLevels[parentCD]
            topIDs = set()
            for childCD, (idx, xpCost, required) in nextLevel.iteritems():
                if childCD not in unlocked and required.issubset(unlocked):
                    topIDs.add(parentCD)
                    available[childCD].append(UnlockProps(parentCD, idx, xpCost, topIDs))

        result = {}
        for childCD, compare in available.iteritems():
            result[childCD] = self._findNext2Unlock(compare, xps=xps, freeXP=freeXP)

        return result
Example #13
0
def licenses_summary(results):
    summary = dict(unknown=0)
    for result in results:
        if any(keyword in result for keyword in ["and", "or"]):
            # split all licenses
            licenses = re.split(", |and |or ", result)
            for license in licenses:
                license = license.rstrip()
                key = filter(lambda x: re.search(x, license) is not None, Licenses)
                if len(key) > 0:
                    # if license already in dict then add it up
                    if license.replace(" ", "_") in summary.keys():
                        summary[license.replace(" ", "_")] += results[result]
                    else:
                        summary[license.replace(" ", "_")] = results[result]
                else:
                    summary["unknown"] += results[result]
        else:
            key = filter(lambda x: re.search(x, result) is not None, Licenses)
            if len(key) > 0:
                # if license already in dict then add it up
                if result.replace(" ", "_") in summary.keys():
                    summary[result.replace(" ", "_")] += results[result]
                else:
                    summary[result.replace(" ", "_")] = results[result]
            else:
                summary["unknown"] += results[result]
    return summary
Example #14
0
def licenses_summary_w_dual(results):
    summary = dict(unknown=0)
    for result in results:
        if any(keyword in result for keyword in ["and", "or"]):
            # verify all are standard
            licenses = re.split(", |and |or ", result)
            unknown = True  # verify all licenses in statement are standard
            for l in licenses:
                key = filter(lambda x: re.search(x, l) is not None, Licenses)
                if not key:
                    unknown = False
            if not unknown:
                summary["unknown"] += results[result]
            else:
                # search if result exists in dict but in different order
                found = None
                for key in summary.keys():
                    # replace spaces with _ as one loading the stats file
                    # later we don't break it correctly.
                    if set(result.split("_")) == set(key.split(" ")):
                        # key exists
                        found = key
                        break
                if found is not None:
                    summary[found] += results[result]
                else:
                    summary[result.replace(" ", "_")] = results[result]
        else:
            key = filter(lambda x: re.search(x, result) is not None, Licenses)
            # standard licenses
            if len(key) > 0:
                summary[result.replace(" ", "_")] = results[result]
            else:
                summary["unknown"] += results[result]
    return summary
Example #15
0
def tokenize(text):
    tokens = word_tokenize(text)
    no_stopwords = filter(lambda x: x not in STOPWORDS, tokens)
    stemmed = map(lambda w: STEMMER.stem(w), no_stopwords)
    # s = set(stemmed)
    # stemmed = list(s)
    return filter(lambda x: len(x) > 1, stemmed)
Example #16
0
    def handle(self, *args, **options):
        if len(args) != 0:
            raise CommandError("This command doesn't expect arguments!")
        show_info = options["show_info"]
        list_pillows = options["list_pillows"]
        flip_all = options["flip_all"]
        flip_single = options["pillow_class"]
        code_red = options["code_red"]
        es = get_es()

        pillows = get_all_pillow_instances()
        aliased_pillows = filter(lambda x: isinstance(x, AliasedElasticPillow), pillows)

        if code_red:
            if (
                raw_input(
                    "\n".join(
                        [
                            "CODE RED!!!",
                            "Really delete ALL the elastic indices and pillow checkpoints?",
                            "The following pillows will be affected:",
                            "\n".join([type(p).__name__ for p in aliased_pillows]),
                            'This is a PERMANENT action. (Type "code red" to continue):',
                            "",
                        ]
                    )
                ).lower()
                == "code red"
            ):
                for pillow in aliased_pillows:
                    pillow.get_es_new().indices.delete(pillow.es_index)
                    print "deleted elastic index: {}".format(pillow.es_index)
                    checkpoint_id = pillow.checkpoint.checkpoint_id
                    if pillow.couch_db.doc_exist(checkpoint_id):
                        pillow.couch_db.delete_doc(checkpoint_id)
                        print "deleted checkpoint: {}".format(checkpoint_id)
            else:
                print "Safety first!"
            return

        if show_info:
            get_pillow_states(aliased_pillows).dump_info()
        if list_pillows:
            print aliased_pillows
        if flip_all:
            for pillow in aliased_pillows:
                assume_alias_for_pillow(pillow)
            print simplejson.dumps(es.get("_aliases"), indent=4)
        if flip_single is not None:
            pillow_class_name = flip_single
            pillow_to_use = filter(lambda x: x.__class__.__name__ == pillow_class_name, aliased_pillows)
            if len(pillow_to_use) != 1:
                print "Unknown pillow (option --pillow <name>) class string, the options are: \n\t%s" % ", ".join(
                    [x.__class__.__name__ for x in aliased_pillows]
                )
                sys.exit()

            target_pillow = pillow_to_use[0]
            assume_alias_for_pillow(target_pillow)
            print es.get("_aliases")
Example #17
0
    def setInput(self, index, value):
        temp = self.inputs[:]
        if index >= len(temp):
            temp.append(value)
            if not (
                temp.count(1) == 1
                or list(x.state for x in filter(lambda i: isinstance(i, Connector), temp)).count(1) == 1
            ):
                raise Exception("ERROR: Invalid Input")
                self.inputs.append(value)
            for i in range(len(self.outputType), int(math.log(len(self.inputs), 2))):
                self.outputType.append(0)
                self.outputConnector.append(None)
        else:
            temp[index] = value
            if not (
                temp.count(1) == 1
                or list(x.state for x in filter(lambda i: isinstance(i, Connector), temp)).count(1) == 1
            ):
                raise Exception("ERROR: Invalid Input")
                self.inputs[index] = value

        if isinstance(value, Connector):
            value.tap(self, "input")
            self.trigger()
Example #18
0
    def applyDoubleCut(self, cut1, cut2, text="", minN=1, name1=None, name2=None, minN1=-1, minN2=-1):
        selectedObjects1 = filter(cut1, self.obj1)
        selectedObjects2 = filter(cut2, self.obj2)

        merged = set(selectedObjects1)
        merged.update(selectedObjects2)

        isOK = (len(merged) >= minN) and (len(selectedObjects1) >= minN1) and (len(selectedObjects2) >= minN2)
        if self.counter is not None:
            if text not in self.counter.dico:
                self.counter.register(text)

        if isOK:
            if self.counter is not None:
                self.counter.inc(text)
            self.obj1 = selectedObjects1
            self.obj2 = selectedObjects2
            if name1 is not None:
                setattr(self.event, name1, selectedObjects1)
            if name2 is not None:
                setattr(self.event, name2, selectedObjects2)

            return True
        else:
            self.obj1 = selectedObjects1
            self.obj2 = selectedObjects2
            if name1 is not None:
                setattr(self.event, name1, selectedObjects1)
            if name2 is not None:
                setattr(self.event, name2, selectedObjects2)

        return False
Example #19
0
def find_existing_cluster(conn, opts, cluster_name):
    print "Searching for existing Sparrow cluster..."
    reservations = conn.get_all_instances()
    frontend_nodes = []
    backend_nodes = []
    for res in reservations:
        active = [i for i in res.instances if is_active(i)]
        if len(active) > 0:
            group_names = [g.name for g in res.groups]
            if group_names == ["%s-frontends" % cluster_name]:
                frontend_nodes += res.instances
            elif group_names == ["%s-backends" % cluster_name]:
                backend_nodes += res.instances
    if frontend_nodes != [] and backend_nodes != []:
        print ("Found %d frontend and %s backend nodes" % (len(frontend_nodes), len(backend_nodes)))

        print "Frontends:"
        frontend_nodes = filter(lambda k: k.public_dns_name != "", frontend_nodes)
        for fe in frontend_nodes:
            print fe.public_dns_name
        print "Backends:"
        backend_nodes = filter(lambda k: k.public_dns_name != "", backend_nodes)
        for be in backend_nodes:
            print be.public_dns_name

        return (frontend_nodes, backend_nodes)
    else:
        print "ERROR: Could not find full cluster: fe=%s be=%s" % (frontend_nodes, backend_nodes)
        sys.exit(1)
Example #20
0
    def _extract_brightcove_urls(cls, webpage):
        """Return a list of all Brightcove URLs from the webpage """

        url_m = re.search(
            r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
            webpage,
        )
        if url_m:
            url = unescapeHTML(url_m.group(1))
            # Some sites don't add it, we can't download with this url, for example:
            # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
            if "playerKey" in url or "videoId" in url:
                return [url]

        matches = re.findall(
            r"""(?sx)<object
            (?:
                [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
                [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
            ).+?>\s*</object>""",
            webpage,
        )
        if matches:
            return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))

        return list(
            filter(
                None,
                [
                    cls._build_brighcove_url_from_js(custom_bc)
                    for custom_bc in re.findall(r"(customBC\.createVideo\(.+?\);)", webpage)
                ],
            )
        )
Example #21
0
    def get_tasks_and_comments(self, filename=None, encoding=None):
        """ """
        # -- setup values and load defaults
        fileText = None
        tasks = None
        if filename is None:
            filename = self.filename
        if encoding is None:
            encoding = self.encoding

            # ==  if we are a file, load it
        if os.path.isfile(filename):
            fileObj = codecs.open(filename, u"r", encoding)
            if fileObj is not None:
                self.lastRead = datetime.now()
                fileText = fileObj.read()
                fileObj.close()
                del fileObj

                # -- if we have any text, build objects from it
        if fileText is not None:
            fileLines = fileText.splitlines()
            fileLines = filter(lambda string: string != "", fileLines)

            # -- strip out comments, process them
            comments = filter(lambda string: string[0] == "#", fileLines)

            # -- take all non-comment lines, conver them into task objects
            taskLines = filter(lambda string: string[0] != "#", fileLines)
            tasks = map(lambda string: Task.from_raw_string(string), taskLines)

        return (tasks, comments)
Example #22
0
def do_image_create(gc, args):
    """Create a new image."""
    # Filter out None values
    fields = dict(filter(lambda x: x[1] is not None, vars(args).items()))

    fields["is_public"] = fields.get("is_public")

    if "is_protected" in fields:
        fields["protected"] = fields.pop("is_protected")

    raw_properties = fields.pop("property")
    fields["properties"] = {}
    for datum in raw_properties:
        key, value = datum.split("=", 1)
        fields["properties"][key] = value

    # Filter out values we can't use
    CREATE_PARAMS = glanceclient.v1.images.CREATE_PARAMS
    fields = dict(filter(lambda x: x[0] in CREATE_PARAMS, fields.items()))

    _set_data_field(fields, args)

    # Only show progress bar for local image files
    if fields.get("data") and args.progress:
        filesize = utils.get_file_size(fields["data"])
        fields["data"] = progressbar.VerboseFileWrapper(fields["data"], filesize)

    image = gc.images.create(**fields)
    _image_show(image, args.human_readable)
Example #23
0
    def scrape_members_senate_subcommittees(self, committee, url, chamber, term, cache={}):

        if cache:
            names = cache[committee["subcommittee"]]
            return Membernames.scrub(names)

        html = self.urlopen(url)
        doc = lxml.html.fromstring(html)

        # Commence horrific regex-based hackery to get subcommittee members.
        text = doc.xpath('//div[@class="content"]')[0].text_content()
        chunks = re.split(r"\s*Subcommittee.*", text)
        namelists = []
        for c in chunks:
            names = re.sub(r"\s*Members\s*", "", c)
            names = re.split(r"\s*(,|and)\s*", names)
            names = filter(lambda s: s not in [",", "and"], names)
            names = map(clean, names)
            if filter(None, names):
                namelists.append(names)

        committee_names = doc.xpath('//div[@class="content"]/h3/text()')
        for _committee, _names in zip(map(clean, committee_names), namelists):
            cache[_committee] = _names

        names = cache[committee["subcommittee"]]
        return Membernames.scrub(names)
Example #24
0
def do_image_update(gc, args):
    """Update a specific image."""
    # Filter out None values
    fields = dict(filter(lambda x: x[1] is not None, vars(args).items()))

    image_arg = fields.pop("image")
    image = utils.find_resource(gc.images, image_arg)

    if "is_protected" in fields:
        fields["protected"] = fields.pop("is_protected")

    raw_properties = fields.pop("property")
    fields["properties"] = {}
    for datum in raw_properties:
        key, value = datum.split("=", 1)
        fields["properties"][key] = value

    # Filter out values we can't use
    UPDATE_PARAMS = glanceclient.v1.images.UPDATE_PARAMS
    fields = dict(filter(lambda x: x[0] in UPDATE_PARAMS, fields.items()))

    if image.status == "queued":
        _set_data_field(fields, args)

        if args.progress:
            filesize = utils.get_file_size(fields["data"])
            fields["data"] = progressbar.VerboseFileWrapper(fields["data"], filesize)

    image = gc.images.update(image, purge_props=args.purge_props, **fields)
    _image_show(image, args.human_readable)
    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 automail_prize_contributors(event, prizes, mailTemplate, domain=settings.DOMAIN, sender=None, replyTo=None):
    sender, replyTo = event_sender_replyto_defaults(event, sender, replyTo)

    handlerDict = {}
    for prize in prizes:
        if prize.handler:
            prizeList = handlerDict.setdefault(prize.handler, [])
            prizeList.append(prize)
    for handler, prizeList in handlerDict.iteritems():
        denied = list(filter(lambda prize: prize.state == "DENIED", prizeList))
        formatContext = {
            "user_index_url": domain + reverse("user_index"),
            "event": event,
            "handler": handler,
            "accepted_prizes": list(filter(lambda prize: prize.state == "ACCEPTED", prizeList)),
            "denied_prizes": list(filter(lambda prize: prize.state == "DENIED", prizeList)),
            "reply_address": replyTo,
            "event": event,
        }
        post_office.mail.send(
            recipients=[handler.email],
            sender=sender,
            template=mailTemplate.name,
            context=formatContext,
            headers={"Reply-to": replyTo},
        )
        for prize in prizeList:
            prize.acceptemailsent = True
            prize.save()
Example #27
0
File: views.py Project: kfairch/hue
def jobbrowser(request):
    """
  jobbrowser.jsp - a - like.
  """
    # TODO(bc): Is this view even reachable?
    def check_job_state(state):
        return lambda job: job.status == state

    status = request.jt.cluster_status()
    alljobs = []  # get_matching_jobs(request)
    runningjobs = filter(check_job_state("RUNNING"), alljobs)
    completedjobs = filter(check_job_state("COMPLETED"), alljobs)
    failedjobs = filter(check_job_state("FAILED"), alljobs)
    killedjobs = filter(check_job_state("KILLED"), alljobs)
    jobqueues = request.jt.queues()

    return render(
        "jobbrowser.html",
        request,
        {
            "clusterstatus": status,
            "queues": jobqueues,
            "alljobs": alljobs,
            "runningjobs": runningjobs,
            "failedjobs": failedjobs,
            "killedjobs": killedjobs,
            "completedjobs": completedjobs,
        },
    )
Example #28
0
def collectCategoriesAndSpokes(paths, klass, displaymode):
    """collects categories and spokes to be displayed on this Hub

       :param paths: dictionary mapping categories, spokes, and hubs to their
       their respective search path(s)
       :return: dictionary mapping category class to list of spoke classes
       :rtype: dictionary[category class] -> [ list of spoke classes ]
    """
    ret = {}
    # Collect all the categories this hub displays, then collect all the
    # spokes belonging to all those categories.
    if displaymode == DISPLAY_MODE_TEXT:
        categories = sorted(
            filter(lambda c: c.displayOnHubTUI == klass.__name__, collect_categories(paths["categories"], displaymode)),
            key=lambda c: c.sortOrder,
        )
    else:
        categories = sorted(
            filter(lambda c: c.displayOnHubGUI == klass.__name__, collect_categories(paths["categories"], displaymode)),
            key=lambda c: c.sortOrder,
        )
    for c in categories:
        ret[c] = collect_spokes(paths["spokes"], c.__name__)

    return ret
 def do_mythtv_item_remove(self, args):
     """Removes an item from Miro by file name or Channel and title"""
     for item in views.watchableItems:
         if isinstance(args, list):
             if filter(self.is_not_punct_char, item.get_channel_title(True).lower()) == filter(
                 self.is_not_punct_char, args[0].lower()
             ) and (filter(self.is_not_punct_char, item.get_title().lower())).startswith(
                 filter(self.is_not_punct_char, args[1].lower())
             ):
                 break
         elif filter(self.is_not_punct_char, item.get_filename().lower()) == filter(
             self.is_not_punct_char, args.lower()
         ):
             break
     else:
         logging.info(u"No item named %s" % args)
         return
     if item.is_downloaded():
         if self.simulation:
             logging.info(
                 u"Simulation: Item (%s - %s) has been removed from Miro"
                 % (item.get_channel_title(True), item.get_title())
             )
         else:
             item.expire()
             self.statistics[u"Miro_videos_deleted"] += 1
             logging.info(u"%s has been removed from Miro" % item.get_title())
     else:
         logging.info(u"%s is not downloaded" % item.get_title())
Example #30
0
def handle_entity(entity, entityDB, apple, options):
    if entity.view_url is not None:
        return

    if entity.subcategory == "album":
        results = apple.lookup(id=entity.aid, media="music", entity="song", transform=True)
        results = filter(lambda r: r.entity.subcategory == "song", results)
        entity.tracks = list(result.entity.title for result in results)

        results = apple.lookup(id=entity.aid, media="music", entity="album", transform=True)
        results = filter(lambda r: r.entity.subcategory == "album" and r.entity.aid == entity.aid, results)

    if entity.subcategory == "song":
        results = apple.lookup(id=entity.aid, media="music", entity="song", transform=True)
        results = filter(lambda r: r.entity.subcategory == "song" and r.entity.aid == entity.aid, results)

    if entity.subcategory == "artist":
        results = apple.lookup(id=entity.aid, media="music", entity="allArtist", transform=True)
        results = filter(lambda r: r.entity.subcategory == "artist" and r.entity.aid == entity.aid, results)

    if len(results) == 1:
        utils.log("SUCCESS: %s (%s)" % (entity.title, entity.subcategory))
        entity.view_url = results[0].entity.view_url

        if not options.noop:
            entityDB.updateEntity(entity)
    else:
        utils.log("FAIL: %s (%s)" % (entity.title, entity.subcategory))