• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.make_iter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中src.utils.utils.make_iter函数的典型用法代码示例。如果您正苦于以下问题:Python make_iter函数的具体用法?Python make_iter怎么用?Python make_iter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了make_iter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_object_with_player

 def get_object_with_player(self, ostring, exact=True, candidates=None):
     """
     Search for an object based on its player's name or dbref.
     This search
     is sometimes initiated by appending a * to the beginning of
     the search criterion (e.g. in local_and_global_search).
     search_string:  (string) The name or dbref to search for.
     """
     ostring = to_unicode(ostring).lstrip("*")
     # simplest case - search by dbref
     dbref = self.dbref(ostring)
     if dbref:
         return dbref
     # not a dbref. Search by name.
     cand_restriction = (
         candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q()
     )
     if exact:
         return self.filter(cand_restriction & Q(db_player__username__iexact=ostring))
     else:  # fuzzy matching
         ply_cands = self.filter(cand_restriction & Q(playerdb__username__istartswith=ostring)).values_list(
             "db_key", flat=True
         )
         if candidates:
             index_matches = string_partial_matching(ply_cands, ostring, ret_index=True)
             return [obj for ind, obj in enumerate(make_iter(candidates)) if ind in index_matches]
         else:
             return string_partial_matching(ply_cands, ostring, ret_index=False)
开发者ID:no-space,项目名称:evennia,代码行数:28,代码来源:manager.py


示例2: get_objs_with_db_property_value

    def get_objs_with_db_property_value(self, property_name, property_value, candidates=None, typeclasses=None):
        """
        Returns all objects having a given db field property.
        candidates - list of objects to search
        typeclasses - list of typeclass-path strings to restrict matches with
        """
        if isinstance(property_value, basestring):
            property_value = to_unicode(property_value)
        if isinstance(property_name, basestring):
            if not property_name.startswith("db_"):
                property_name = "db_%s" % property_name
        if hasattr(property_value, "dbobj"):
            property_value = property_value.dbobj
        querykwargs = {property_name: property_value}
        cand_restriction = (
            candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q()
        )
        type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q()
        try:
            return list(self.filter(cand_restriction & type_restriction & Q(**querykwargs)))
        except exceptions.FieldError:
            return []
        except ValueError:
            from src.utils import logger

            logger.log_errmsg(
                "The property '%s' does not support search criteria of the type %s."
                % (property_name, type(property_value))
            )
            return []
开发者ID:no-space,项目名称:evennia,代码行数:30,代码来源:manager.py


示例3: get_objs_with_attr_value

    def get_objs_with_attr_value(self, attribute_name, attribute_value, candidates=None, typeclasses=None):
        """
        Returns all objects having the valid attrname set to the given value.

        candidates - list of candidate objects to search
        typeclasses - list of typeclass-path strings to restrict matches with

        This uses the Attribute's PickledField to transparently search the database by matching
        the internal representation. This is reasonably effective but since Attribute values
        cannot be indexed, searching by Attribute key is to be preferred whenever possible.
        """
        cand_restriction = (
            candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q()
        )
        type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q()

        ## This doesn't work if attribute_value is an object. Workaround below

        if isinstance(attribute_value, (basestring, int, float, bool, long)):
            return self.filter(
                cand_restriction
                & type_restriction
                & Q(db_attributes__db_key=attribute_name, db_attributes__db_value=attribute_value)
            )
        else:
            # We have to loop for safety since the referenced lookup gives deepcopy error if attribute value is an object.
            global _ATTR
            if not _ATTR:
                from src.typeclasses.models import Attribute as _ATTR
            cands = list(self.filter(cand_restriction & type_restriction & Q(db_attributes__db_key=attribute_name)))
            results = [
                attr.objectdb_set.all() for attr in _ATTR.objects.filter(objectdb__in=cands, db_value=attribute_value)
            ]
            return chain(*results)
开发者ID:no-space,项目名称:evennia,代码行数:34,代码来源:manager.py


示例4: __init__

 def __init__(self, senders=None, receivers=None, channels=None, message="", header="", type="", lockstring="", hide_from=None):
     self.senders = senders and make_iter(senders) or []
     self.receivers = receivers and make_iter(receivers) or []
     self.channels = channels and make_iter(channels) or []
     self.type = type
     self.header = header
     self.message = message
     self.lock_storage = lockstring
     self.hide_from = hide_from and make_iter(hide_from) or []
     self.date_sent = datetime.now()
开发者ID:RetroRodent,项目名称:evennia,代码行数:10,代码来源:models.py


示例5: func

    def func(self):
        "Implement function"

        caller = self.caller

        # all channels we have available to listen to
        channels = [chan for chan in ChannelDB.objects.get_all_channels() if chan.access(caller, "listen")]
        # print channels
        if not channels:
            self.msg("No channels available.")
            return
        # all channel we are already subscribed to
        subs = ChannelDB.objects.get_subscriptions(caller)
        # print subs

        if self.cmdstring == "comlist":
            # just display the subscribed channels with no extra info
            comtable = prettytable.PrettyTable(["{wchannel", "{wmy aliases", "{wdescription"])
            for chan in subs:
                clower = chan.key.lower()
                nicks = caller.nicks.get(category="channel")
                comtable.add_row(
                    [
                        "%s%s" % (chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or ""),
                        "%s".join(nick for nick in make_iter(nicks) if nick and nick.lower() == clower),
                        chan.db.desc,
                    ]
                )
            caller.msg(
                "\n{wChannel subscriptions{n (use {[email protected]{n to list all, {waddcom{n/{wdelcom{n to sub/unsub):{n\n%s"
                % comtable
            )
        else:
            # full listing (of channels caller is able to listen to)
            comtable = prettytable.PrettyTable(["{wsub", "{wchannel", "{wmy aliases", "{wlocks", "{wdescription"])
            for chan in channels:
                clower = chan.key.lower()
                nicks = caller.nicks.get(category="channel")
                nicks = nicks or []
                comtable.add_row(
                    [
                        chan in subs and "{gYes{n" or "{rNo{n",
                        "%s%s" % (chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or ""),
                        "%s".join(nick for nick in make_iter(nicks) if nick.lower() == clower),
                        str(chan.locks),
                        chan.db.desc,
                    ]
                )
            caller.msg(
                "\n{wAvailable channels{n (use {wcomlist{n,{waddcom{n and {wdelcom{n to manage subscriptions):\n%s"
                % comtable
            )
开发者ID:no-space,项目名称:evennia,代码行数:52,代码来源:comms.py


示例6: get_objs_with_key_or_alias

 def get_objs_with_key_or_alias(self, ostring, exact=True, candidates=None, typeclasses=None):
     """
     Returns objects based on key or alias match. Will also do fuzzy
     matching based on the utils.string_partial_matching function.
     candidates - list of candidate objects to restrict on
     typeclasses - list of typeclass path strings to restrict on
     """
     if not isinstance(ostring, basestring):
         if hasattr(ostring, "key"):
             ostring = ostring.key
         else:
             return []
     if is_iter(candidates) and not len(candidates):
         # if candidates is an empty iterable there can be no matches
         # Exit early.
         return []
     # build query objects
     candidates_id = [_GA(obj, "id") for obj in make_iter(candidates) if obj]
     cand_restriction = candidates != None and Q(pk__in=make_iter(candidates_id)) or Q()
     type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q()
     if exact:
         # exact match - do direct search
         return self.filter(
             cand_restriction
             & type_restriction
             & (
                 Q(db_key__iexact=ostring)
                 | Q(db_tags__db_key__iexact=ostring) & Q(db_tags__db_category__iexact="objectalias")
             )
         ).distinct()
     elif candidates:
         # fuzzy with candidates
         key_candidates = self.filter(cand_restriction & type_restriction)
     else:
         # fuzzy without supplied candidates - we select our own candidates
         key_candidates = self.filter(
             type_restriction & (Q(db_key__istartswith=ostring) | Q(db_tags__db_key__istartswith=ostring))
         ).distinct()
         candidates_id = [_GA(obj, "id") for obj in key_candidates]
     # fuzzy matching
     key_strings = key_candidates.values_list("db_key", flat=True)
     index_matches = string_partial_matching(key_strings, ostring, ret_index=True)
     if index_matches:
         return [obj for ind, obj in enumerate(key_candidates) if ind in index_matches]
     else:
         alias_candidates = self.filter(id__in=candidates_id, db_tags__db_category__iexact="objectalias")
         # print alias_candidates
         alias_strings = alias_candidates.values_list("db_key", flat=True)
         index_matches = string_partial_matching(alias_strings, ostring, ret_index=True)
         if index_matches:
             return [alias.db_obj for ind, alias in enumerate(alias_candidates) if ind in index_matches]
         return []
开发者ID:no-space,项目名称:evennia,代码行数:52,代码来源:manager.py


示例7: dataReceived

    def dataReceived(self, string):
        """
        Method called when data is coming in over
        the websocket connection.

        Type of data is identified by a 3-character
        prefix.
            OOB - This is an Out-of-band instruction. If so,
                  the remaining string should be a json-packed
                  string on the form {oobfuncname: [args, ], ...}
            any other prefix (or lack of prefix) is considered
                  plain text data, to be treated like a game
                  input command.
        """
        if string[:3] == "OOB":
            string = string[3:]
            try:
                oobdata = json.loads(string)
                for (key, args) in oobdata.items():
                    #print "oob data in:", (key, args)
                    self.data_in(text=None, oob=(key, make_iter(args)))
            except Exception:
                log_trace("Websocket malformed OOB request: %s" % string)
        else:
            # plain text input
            self.data_in(text=string)
开发者ID:henghu-bai,项目名称:evennia,代码行数:26,代码来源:websocket_client.py


示例8: get_objs_with_key_or_alias

 def get_objs_with_key_or_alias(self, ostring, exact=True, candidates=None):
     """
     Returns objects based on key or alias match. Will also do fuzzy matching based on
     the utils.string_partial_matching function.
     """
     # build query objects
     candidates_id = [_GA(obj, "id") for obj in make_iter(candidates) if obj]
     cand_restriction = candidates and Q(pk__in=candidates_id) or Q()
     if exact:
         # exact match - do direct search
         return self.filter(cand_restriction & (Q(db_key__iexact=ostring) | Q(alias__db_key__iexact=ostring))).distinct()
     elif candidates:
         # fuzzy with candidates
         key_candidates = self.filter(cand_restriction)
     else:
         # fuzzy without supplied candidates - we select our own candidates
         key_candidates = self.filter(Q(db_key__istartswith=ostring) | Q(alias__db_key__istartswith=ostring)).distinct()
         candidates_id = [_GA(obj, "id") for obj in key_candidates]
     # fuzzy matching
     key_strings = key_candidates.values_list("db_key", flat=True)
     index_matches = string_partial_matching(key_strings, ostring, ret_index=True)
     if index_matches:
         return [obj for ind, obj in enumerate(key_candidates) if ind in index_matches]
     else:
         alias_candidates = self.model.alias_set.related.model.objects.filter(db_obj__pk__in=candidates_id)
         alias_strings = alias_candidates.values_list("db_key", flat=True)
         index_matches = string_partial_matching(alias_strings, ostring, ret_index=True)
         if index_matches:
             return [alias.db_obj for ind, alias in enumerate(alias_candidates) if ind in index_matches]
         return []
开发者ID:BGCX262,项目名称:zsmud-git,代码行数:30,代码来源:manager.py


示例9: cmdset_storage_set

 def cmdset_storage_set(self, value):
     """
     Setter. Allows for self.name = value. Stores as a comma-separated
     string.
     """
     _SA(self, "db_cmdset_storage", ",".join(str(val).strip() for val in make_iter(value)))
     _GA(self, "save")()
开发者ID:Aumnren,项目名称:evennia,代码行数:7,代码来源:models.py


示例10: create_tag

 def create_tag(self, key=None, category=None, data=None, tagtype=None):
     """
     Create a new Tag of the base type associated with this typedobject.
     This makes sure to create case-insensitive tags. If the exact same
     tag configuration (key+category+tagtype) exists on the model, a
     new tag will not be created, but an old one returned.  A data
     keyword is not part of the uniqueness of the tag and setting one
     on an existing tag will overwrite the old data field.
     """
     data = str(data) if data is not None else None
     # try to get old tag
     tag = self.get_tag(key=key, category=category, tagtype=tagtype)
     if tag and data is not None:
         # overload data on tag
         tag.db_data = data
         tag.save()
     elif not tag:
         # create a new tag
         global _Tag
         if not _Tag:
             from src.typeclasses.models import Tag as _Tag
         tag = _Tag.objects.create(
             db_key=key.strip().lower() if key is not None else None,
             db_category=category.strip().lower() if category and key is not None else None,
             db_data=data,
             db_tagtype=tagtype.strip().lower() if tagtype is not None else None)
         tag.save()
     return make_iter(tag)[0]
开发者ID:Archivis,项目名称:evennia,代码行数:28,代码来源:managers.py


示例11: remove_receiver

 def remove_receiver(self, obj):
     "Remove a sender or a list of senders"
     for o in make_iter(obj):
         try:
             self.senders.remove(o)
         except ValueError:
             pass  # nothing to remove
开发者ID:TheWhiteOx,项目名称:evennia,代码行数:7,代码来源:models.py


示例12: get_objs_with_key_and_typeclass

 def get_objs_with_key_and_typeclass(self, oname, otypeclass_path, candidates=None):
     """
     Returns objects based on simultaneous key and typeclass match.
     """
     cand_restriction = (
         candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q()
     )
     return self.filter(cand_restriction & Q(db_key__iexact=oname, db_typeclass_path__exact=otypeclass_path))
开发者ID:no-space,项目名称:evennia,代码行数:8,代码来源:manager.py


示例13: func

 def func(self, *args, **kwargs):
     "decorator. Returns result or None."
     self.__doc__ = method.__doc__
     matches = method(self, *args, **kwargs)
     dbobj = matches and make_iter(matches)[0] or None
     if dbobj:
         return (hasattr(dbobj, "typeclass") and dbobj.typeclass) or dbobj
     return None
开发者ID:AHecky3,项目名称:evennia,代码行数:8,代码来源:managers.py


示例14: no_look_target

    def no_look_target(self):
        "Hook method for default look without a specified target"
        # caller is always a player at this point.
        player = self.player
        sessid = self.sessid
        # get all our characters and sessions
        characters = player.db._playable_characters
        if None in characters:
            # clean up list if character object was deleted in between
            characters = [character for character in characters if character]
            player.db._playable_characters = characters

        sessions = player.get_all_sessions()
        is_su = player.is_superuser

        # text shown when looking in the ooc area
        string = "Account {g%s{n (you are Out-of-Character)" % (player.key)

        nsess = len(sessions)
        string += nsess == 1 and "\n\n{wConnected session:{n" or "\n\n{wConnected sessions (%i):{n" % nsess
        for isess, sess in enumerate(sessions):
            csessid = sess.sessid
            addr = "%s (%s)" % (sess.protocol_key, isinstance(sess.address, tuple) and str(sess.address[0]) or str(sess.address))
            string += "\n %s %s" % (sessid == csessid and "{w%s{n" % (isess + 1) or (isess + 1), addr)
        string += "\n\n {whelp{n - more commands"
        string += "\n {wooc <Text>{n - talk on public channel"

        if is_su or len(characters) < MAX_NR_CHARACTERS:
            if not characters:
                string += "\n\n You don't have any characters yet. See {whelp @charcreate{n for creating one."
            else:
                string += "\n {[email protected] <name> [=description]{n - create new character"

        if characters:
            string_s_ending = len(characters) > 1 and "s" or ""
            string += "\n {[email protected] <character>{n - enter the game ({[email protected]{n to get back here)"
            if is_su:
                string += "\n\nAvailable character%s (%i/unlimited):" % (string_s_ending, len(characters))
            else:
                string += "\n\nAvailable character%s%s:"  % (string_s_ending,
                         MAX_NR_CHARACTERS > 1 and " (%i/%i)" % (len(characters), MAX_NR_CHARACTERS) or "")

            for char in characters:
                csessid = char.sessid.get()
                if csessid:
                    # character is already puppeted
                    sessi = player.get_session(csessid)
                    for sess in utils.make_iter(sessi):
                        sid = sess in sessions and sessions.index(sess) + 1
                        if sess and sid:
                            string += "\n - {G%s{n [%s] (played by you in session %i)" % (char.key, ", ".join(char.permissions.all()), sid)
                        else:
                            string += "\n - {R%s{n [%s] (played by someone else)" % (char.key, ", ".join(char.permissions.all()))
                else:
                    # character is "free to puppet"
                    string += "\n - %s [%s]" % (char.key, ", ".join(char.permissions.all()))
        string = ("-" * 68) + "\n" + string + "\n" + ("-" * 68)
        self.msg(string)
开发者ID:RetroRodent,项目名称:evennia,代码行数:58,代码来源:player.py


示例15: msg

    def msg(self, msgobj, header=None, senders=None, sender_strings=None,
            persistent=False, online=False, emit=False, external=False):
        """
        Send the given message to all players connected to channel. Note that
        no permission-checking is done here; it is assumed to have been
        done before calling this method. The optional keywords are not used if
        persistent is False.

        msgobj - a Msg/TempMsg instance or a message string. If one of the
                 former, the remaining keywords will be ignored. If a string,
                 this will either be sent as-is (if persistent=False) or it
                 will be used together with header and senders keywords to
                 create a Msg instance on the fly.
        senders - an object, player or a list of objects or players.
                 Optional if persistent=False.
        sender_strings - Name strings of senders. Used for external
                connections where the sender is not a player or object. When
                this is defined, external will be assumed.
        external - Treat this message agnostic of its sender.
        persistent (default False) - ignored if msgobj is a Msg or TempMsg.
                If True, a Msg will be created, using header and senders
                keywords. If False, other keywords will be ignored.
        online (bool) - If this is set true, only messages people who are
                online. Otherwise, messages all players connected. This can
                make things faster, but may not trigger listeners on players
                that are offline.
        emit (bool) - Signals to the message formatter that this message is
                not to be directly associated with a name.
        """
        if senders:
            senders = make_iter(senders)
        else:
            senders = []
        if isinstance(msgobj, basestring):
            # given msgobj is a string
            msg = msgobj
            if persistent and self.db.keep_log:
                msgobj = Msg()
                msgobj.save()
            else:
                # Use TempMsg, so this message is not stored.
                msgobj = TempMsg()
            msgobj.header = header
            msgobj.message = msg
            msgobj.channels = [self.dbobj]  # add this channel

        if not msgobj.senders:
            msgobj.senders = senders
        msgobj = self.pre_send_message(msgobj)
        if not msgobj:
            return False
        msgobj = self.message_transform(msgobj, emit=emit,
                                        sender_strings=sender_strings,
                                        external=external)
        self.distribute_message(msgobj, online=online)
        self.post_send_message(msgobj)
        return True
开发者ID:AHecky3,项目名称:evennia,代码行数:57,代码来源:comms.py


示例16: get_contents

    def get_contents(self, location, excludeobj=None):
        """
        Get all objects that has a location
        set to this one.

        excludeobj - one or more object keys to exclude from the match
        """
        exclude_restriction = Q(pk__in=[_GA(obj, "id") for obj in make_iter(excludeobj)]) if excludeobj else Q()
        return self.filter(db_location=location).exclude(exclude_restriction)
开发者ID:no-space,项目名称:evennia,代码行数:9,代码来源:manager.py


示例17: delete_script

 def delete_script(self, dbref):
     """
     This stops and deletes a specific script directly
     from the script database. This might be
     needed for global scripts not tied to
     a specific game object.
     """
     scripts = self.get_id(dbref)
     for script in make_iter(scripts):
         script.stop()
开发者ID:YourCyborg,项目名称:Sun-RPI,代码行数:10,代码来源:manager.py


示例18: get_objs_with_attr

 def get_objs_with_attr(self, attribute_name, candidates=None):
     """
     Returns all objects having the given attribute_name defined at all.
     Location should be a valid location object.
     """
     cand_restriction = (
         candidates != None
         and Q(db_attributes__db_obj__pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj])
         or Q()
     )
     return list(self.filter(cand_restriction & Q(db_attributes__db_key=attribute_name)))
开发者ID:no-space,项目名称:evennia,代码行数:11,代码来源:manager.py


示例19: create_message

def create_message(senderobj, message, channels=None,
                   receivers=None, locks=None, header=None):
    """
    Create a new communication message. Msgs are used for all
    player-to-player communication, both between individual players
    and over channels.
    senderobj - the player sending the message. This must be the actual object.
    message - text with the message. Eventual headers, titles etc
              should all be included in this text string. Formatting
              will be retained.
    channels - a channel or a list of channels to send to. The channels
             may be actual channel objects or their unique key strings.
    receivers - a player to send to, or a list of them. May be Player objects
               or playernames.
    locks - lock definition string
    header - mime-type or other optional information for the message

    The Comm system is created very open-ended, so it's fully possible
    to let a message both go to several channels and to several receivers
    at the same time, it's up to the command definitions to limit this as
    desired.
    """
    global _Msg
    if not _Msg:
        from src.comms.models import Msg as _Msg
    if not message:
        # we don't allow empty messages.
        return
    new_message = _Msg(db_message=message)
    new_message.save()
    for sender in make_iter(senderobj):
        new_message.senders = sender
    new_message.header = header
    for channel in make_iter(channels):
        new_message.channels = channel
    for receiver in make_iter(receivers):
        new_message.receivers = receiver
    if locks:
        new_message.locks.add(locks)
    new_message.save()
    return new_message
开发者ID:Mackyjin,项目名称:evennia,代码行数:41,代码来源:create.py


示例20: contents_get

    def contents_get(self, exclude=None):
        """
        Returns the contents of this object, i.e. all
        objects that has this object set as its location.
        This should be publically available.

        exclude is one or more objects to not return
        """
        if exclude:
            exclude = [obj.dbobj for obj in make_iter(exclude)]
            return ObjectDB.objects.get_contents(self, excludeobj=exclude)
        return ObjectDB.objects.get_contents(self)
开发者ID:Archivis,项目名称:evennia,代码行数:12,代码来源:models.py



注:本文中的src.utils.utils.make_iter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.to_str函数代码示例发布时间:2022-05-27
下一篇:
Python utils.inherits_from函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap