コード例 #1
0
    def testNe(self):
        set1 = Set()
        set1.insert(1)
        set1.insert(2)
        set1.insert(3)
        set1.insert(5)

        set2 = Set()
        set2.insert(7)
        set2.insert(6)
        set2.insert(8)
        set2.insert(9)

        # checks to see if the lists are not equal
        self.assertEqual(set1 != set2, True)

        set3 = Set()
        set3.insert(1)
        set3.insert(2)
        set3.insert(3)
        set3.insert(5)

        set4 = Set()
        set4.insert(1)
        set4.insert(2)
        set4.insert(3)
        set4.insert(5)

        # checks to see if they are not equal
        # the sets are equal so it will return false
        self.assertEqual(set3 != set4, False)
コード例 #2
0
ファイル: ParsedExpr.py プロジェクト: coowoole/gaedav
    def evaluate(self, context):
        """Evaluate the left, then if op =// the parsedStep, then the right, push context each time"""
        """Returns a node set"""

        rt = self._left.evaluate(context)
        if type(rt) != type([]):
            raise "Invalid Expression for a PathExpr %s" % str(self._left)

        origState = context.copyNodePosSize()
        if self._step:
            res = []
            l = len(rt)
            for ctr in range(l):
                r = rt[ctr]
                context.setNodePosSize((r,ctr+1,l))
                subRt = self._step.select(context)
                res = Set.Union(res,subRt)
            rt = res
        res = []
        l = len(rt)
        for ctr in range(l):
            r = rt[ctr]
            context.setNodePosSize((r,ctr+1,l))
            subRt = self._right.select(context)
            if type(subRt) != type([]):
                raise Exception("Right Expression does not evaluate to a Node Set")
            res = Set.Union(res,subRt)

        context.setNodePosSize(origState)
        return res
コード例 #3
0
 def _actionSet(self):
     if self.radioButton_Normal.isChecked:
         self.__labelName='Normal'
     if self.radioButton_Special.isChecked():
         self.__labelName='Special'
     self.set=Set.PrintSet()
     self.set.show()
コード例 #4
0
def bulkAddf(path, cardset=None):

    cards = []
    idz = 0
    isnew = False

    if cardset is not None:
        idz = int(cardset.getf()[-1]["id"])
        isnew = True

    f = open("path", "r")
    for x in f:
        x.split(",")
        typez = "flashcard"
        front = x[0]
        back = x[1]
        lastserved = datetime.now()
        percentwront = 0.0
        tags = x[2]
        body = {
            "type": typez,
            "front": front,
            "back": back,
            "lastserved": lastserved,
            "percentwrong": percentwrong,
            "tags": tags
        }
        card = {idz: body}
        cards.append(card)
    f.close()

    if isnew:
        temp = Set(cards, None)
コード例 #5
0
ファイル: Commander.py プロジェクト: Joe-lin-ezra/War-Game
def inputCommand(player, player2, ForS, command):  ##輸入指令
    while True:
        # command = input("請輸入指令\n")##讀取指令
        comList = command.split()  ##字串切割,切割成list
        comList[0] = comList[0].upper()
        if (comList[0] == "MOVE"):
            print("玩家要求移動")
            TorF = Move.move(player, comList[1], comList[2],
                             comList[3])  ##傳入player物件,player的army的ID,以及此軍隊的X和Y
            return TorF
        elif (comList[0] == "ATK"):
            print("玩家要求攻擊")
            TorF = ATK.atk(
                player, player2, comList[1],
                comList[2])  ##需要傳入自己player與對方player物件,並且傳入攻擊以及被攻擊軍隊的ID
            return TorF
        elif (comList[0] == "SET"):
            print("玩家要求設置軍隊")
            ##ForS first or second
            TorF = Set.set(player, ForS, comList[1], comList[2],
                           comList[3])  ##傳入要設定的玩家,極其要設定的該軍隊,即要設定的XY座標
            return TorF
        elif (comList[0] == "LEAVE"):
            print("玩家跳出輸入框")
            break
        else:
            print("指令輸入錯誤")
        # print(comList[0])


# inputCommand()
コード例 #6
0
def parseSet(setObject, elements):
    weight = 1
    set = Set()
    for element in setObject.values:
        if (isinstance(element, Object)):
            childSet = parseSet(element, elements)
            set.addElement(childSet)
            continue

        if not (isinstance(element, Element)):
            raise Exception(
                "Error while post-parsing set data. Invalid structure type encountered. Please report this as a bug."
            )

        # setObject.name is obviously "set"
        if not (element.name in legalSetElements[setObject.name]):
            raise Exception(
                "Error while post-parsing set data. Element type " +
                element.name + " is not legal in scopeobject " +
                setObject.name)

        if (element.name == "elements"):
            setElements = parseElements(element.values, elements)

            for oelement in setElements:
                set.addElement(oelement)

        if (element.name == "weight"):
            weight = parseWeight(element.values)

    set.weight = weight
    return set
コード例 #7
0
    def testSub(self):
        set = Set()
        set.insert(1)
        set.insert(2)
        set.insert(3)
        set.insert(5)

        set2 = Set()
        set2.insert(1)
        set2.insert(3)
        set2.insert(4)

        set3 = Set()
        set3.insert(2)
        set3.insert(5)

        self.assertEqual(set - set2, set3)
コード例 #8
0
    def testIsSubsetOf(self):
        set = Set()
        set.insert(1)
        set.insert(2)
        set.insert(3)

        set2 = Set()
        set2.insert(2)
        set2.insert(3)

        # checks if set 2 is a subset of set, returns true
        self.assertEqual(set2.isSubsetOf(set), True)

        set2.insert(5)

        # after inserting a number, makes sure that set2 is not a sub set of set, return false
        self.assertEqual(set2.isSubsetOf(set), False)
コード例 #9
0
    def testLen(self):
        set = Set()
        set.insert(1)
        set.insert(2)
        set.insert(3)

        # makes sure it returns the right length
        self.assertEqual(len(set), 3)
コード例 #10
0
def test_rm():
    test_set.rm(6)
    test_set.rm(1)
    assert test_set == Set([2, 3, 4, 5])

    try:
        test_set.rm(10)
    except ValueError:
        assert True
コード例 #11
0
ファイル: SetBotPlugin.py プロジェクト: xiaowuc1/set-bot
def set_board_image_upload(board):
    board_names = Set.board_to_names(board)
    board_image = BoardGenerator.generate_board(board_names)
    return ('files.upload', {
        'title': 'Current board',
        'name': 'board.png',
        'file': board_image,
        'channels': CHANNEL,
    })
コード例 #12
0
ファイル: ParsedExpr.py プロジェクト: coowoole/gaedav
 def evaluate(self, context):
     lSet = self._left.evaluate(context)
     if type(lSet) != type([]):
         raise "Left Expression does not evaluate to a node set"
     rSet = self._right.evaluate(context)
     if type(rSet) != type([]):
         raise "Right Expression does not evaluate to a node set"
     set = Set.Union(lSet, rSet)
     set = Util.SortDocOrder(set)
     return set
コード例 #13
0
 def move(cls, board):
     board = board.board
     for c1 in board:
         for c2 in board:
             for c3 in board:
                 if c1 == c2 or c1 == c3 or c2 == c3:
                     continue
                 if Set.is_set((c1, c2, c3)):
                     return (c1, c2, c3)
     return None
コード例 #14
0
    def testContains(self):

        set = Set()
        set.insert(1)
        set.insert(2)
        set.insert(3)
        # Checks to see if 2 is in the set and will return true
        self.assertEqual(set.contains(2), True)
        # makes sure that 100 is not in the set and will return false
        self.assertEqual(set.contains(100), False)
コード例 #15
0
ファイル: Graphe.py プロジェクト: thmbob/TIPE-MPSI
def glouton(graphe) :
    n = ordre(graphe)
    visites = []
    composantes = []
    for p in range(n) :
        if p not in visites :
            visites.append(p)
            composantes.append(S.Set())
            composantes[-1].append(p)
            parcours(p, graphe, visites, composantes[-1])
    return composantes
コード例 #16
0
    def testInset(self):

        # checks to see if it adds something to the set
        set = Set()
        set.insert(2)
        self.assertEqual(set.setList, [2])
        set.insert(3)
        self.assertEqual(set.setList, [2, 3])
        # checks to make sure ir does not add duplicates
        set.insert(2)
        self.assertEqual(set.setList, [2, 3])
コード例 #17
0
    def testAdd(self):
        set = Set()
        set.insert(1)
        set.insert(2)
        set.insert(3)

        set2 = Set()
        set2.insert(1)
        set2.insert(3)
        set2.insert(4)

        set3 = Set()
        set3.insert(1)
        set3.insert(2)
        set3.insert(3)
        set3.insert(4)

        # makes sure it is adding correctly
        self.assertEqual(set + set2, set3)
        self.assertEqual(set + set, set)
コード例 #18
0
ファイル: Legacy.py プロジェクト: firekg/is-it-optimal
def Probability_Task(hypo_table,
                     number_hypo,
                     number_feature,
                     number_label,
                     p_teacher_x_h,
                     knowledgeability,
                     iter=100):
    prob_map = {}
    feature_set = []

    # Assume there is a true hypo = hypo
    # Get all posible hypothesis in the hypo map
    for hypo_idx in range(len(hypo_table)):

        # Get the observable feature set
        for f in range(number_feature):
            feature_set.append(f)
        obs = 0
        prob = []
        select = []
        # Make a copy of the whole hypo table, and transform to a hypo_map
        hypo_map_copy = copy.deepcopy(hypo_table)
        while True:

            # Pass the hypo_copy to Set function
            num_hypo, num_feature, num_label, p_teacher_x_h, p_teacher_xy_h, p_learner_h_xy, p_y_xh, delta_g_h = Set.Set(
                hypo_map_copy, knowledgeability=knowledgeability)
            # Get the PT
            p_learner_h_xy = Set.Initstep(num_hypo, num_feature, num_label,
                                          p_y_xh)
            Knowledgeability_Task(num_hypo, num_feature, num_label,
                                  p_teacher_xy_h, p_teacher_x_h,
                                  p_learner_h_xy, p_y_xh, delta_g_h, iter)

            # Choose a feature
            new_hypo_idx = Observe.Get_Index(hypo_table, hypo_map_copy,
                                             hypo_idx)
            feature = Observe.Get_Feature(feature_set, new_hypo_idx,
                                          p_teacher_x_h)
            obs += 1
            prob_find, hypo_map_copy = Observe.Observe(hypo_map_copy,
                                                       new_hypo_idx,
                                                       hypo_table[hypo_idx],
                                                       feature, p_learner_h_xy)
            prob.append(prob_find)
            select.append(feature)

            # remove the feature in the feature set
            feature_set.remove(feature)
            if len(feature_set) == 0:
                prob_map[hypo_idx] = (prob, select)
                break
    return prob_map
コード例 #19
0
def test_run():
    with open("./tests/02", "r") as f:
        n_tables, n_queries = map(int, f.readline().split())
        print('test run results, output in map ./tests')
        counts = list(map(int, f.readline().split()))
        db = Set.Special_Set(counts)

        with open("./tests/02.b", "w") as g:
            for i in range(n_queries):
                dst, src = map(int, f.readline().split())
                # print('c: ', dst, src)
                db.Union(dst - 1, src - 1)
                print(db.max_row_count, file=g)
    def evaluate(self, context):
        res = []
        rt = self._left.select(context)
        l = len(rt)

        origState = context.copyNodePosSize()

        for ctr in range(l):
            context.setNodePosSize((rt[ctr], ctr + 1, l))
            subRt = self._middle.select(context)
            res = Set.Union(res, subRt)

        rt = res
        res = []
        l = len(rt)
        for ctr in range(l):
            context.setNodePosSize((rt[ctr], ctr + 1, l))
            subRt = self._right.select(context)
            res = Set.Union(res, subRt)

        context.setNodePosSize(origState)
        return res
コード例 #21
0
def main():
    n_tables, n_queries = map(int, input('give input: \n').split())
    counts = list(map(int, input().split()))
    assert len(counts) == n_tables
    database = Set.Special_Set(counts)

    # test files and examples all are 1-index based; convert to 0-index base.
    for i in range(n_queries):
        dst, src = map(int, input().split())
        database.Union(dst - 1, src - 1)
        print(database.max_row_count)

    # run a file in the test directory
    test_run()
コード例 #22
0
ファイル: SetBotPlugin.py プロジェクト: xiaowuc1/set-bot
def start_game_update(message, model):
    board, deck = Set.make_initial_deal()
    new_model = Model._replace(model,
                               is_playing=True,
                               board=board,
                               deck=deck,
                               user_to_set_count=collections.defaultdict(int))
    return (new_model, [
        chat_message(
            'Starting a game of SET! Type a three letter code like "abc" ' +
            'to call in a set with those corresponding cards. If you ' +
            'think there are no sets, type "no sets".'),
        set_board_image_upload(board),
    ])
コード例 #23
0
ファイル: Turn.py プロジェクト: sdutta21/hiro
    def create_test():
        """
        Creates a random array of 12 cards for testing purposes
        :return: Array of 12 randomly chosen cards from all 81 possibilities
        """
        card_array = []
        for i in range(1, 4):
            for j in range(1, 4):
                for k in range(1, 4):
                    for l in range(1, 4):
                        card = Set(Color(i), k, Shape(j), Fill(l), 0)
                        # print i, ")", card.shape.name, card.color.name, card.num, card.fill.name
                        card_array.append(card)

        return sample(card_array, 12)
コード例 #24
0
ファイル: Turn.py プロジェクト: sdutta21/hiro
    def create_cards(self):
        """
        Takes the image array from opencv.py and creates Set objects for all 12 cards

        :return: None
        """
        for i, c in enumerate(self.image_array):
            str = c[:4]
            # print(str[0], str[1], str[2], str[3])
            color = int(str[0])
            num = int(str[1])
            shape = int(str[2])
            fill = int(str[3])
            card = Set(Color(color), num, Shape(shape), Fill(fill),
                       self.coord_array[i])
            self.card_array.append(card)
コード例 #25
0
ファイル: Player.py プロジェクト: dogbyday/SET
def getLeastSet(board, deck, sets):
    minSet = -1
    minExistingSets = -1
    numSetsForSet = 0
    setNum = 0
    
    for eachSet in sets:
        cards = eachSet.returnSet()
        for card in cards:
            for secondCard in (board + deck):
                if secondCard != card:
                    thirdCard = Set.predictThird(card, secondCard)
                    if thirdCard in (board + deck):
                        numSetsForSet += 1
        if minExistingSets == -1 or numSetsForSet < minExistingSets:
            minExistingSets = numSetsForSet
            minSet = setNum
        numSetsForSet = 0
        setNum += 1
    return sets[minSet]
コード例 #26
0
ファイル: Commander.py プロジェクト: Joe-lin-ezra/War-Game
def inputCommand(player, player2, ForS, command, map, mapDetail):  ##輸入指令
    while True:
        ##debuger
        a = 0
        for a in range(len(player.army)):
            print("編號: ", a, "屬性: ", player.army[a].type, "移動: ",
                  player.army[a].moved, "攻擊: ", player.army[a].atked)

        ##debuger
        comList = command.split()  ##字串切割,切割成list
        comList[0] = comList[0].upper()
        num = len(comList)
        if (comList[0] == "MOVE" and num == 4):
            print("玩家要求移動")
            TorF = Move.move(player, player2, comList[1], comList[2],
                             comList[3],
                             map)  ##傳入player物件,player的army的ID,以及此軍隊的X和Y
            return TorF
        elif (comList[0] == "ATK" and num == 3):
            print("玩家要求攻擊")
            comList[2] = comList[2].upper()
            TorF = ATK.atk(player, player2, comList[1], comList[2],
                           map)  ##需要傳入自己player與對方player物件,並且傳入攻擊以及被攻擊軍隊的ID
            # player.army[0].atked = 0 ##無限攻擊
            return TorF
        elif (comList[0] == "SET" and num == 4):
            print("玩家要求設置軍隊")
            ##ForS first or second
            TorF = Set.set(player, player2, ForS, comList[1], comList[2],
                           comList[3], map,
                           mapDetail)  ##傳入要設定的玩家,極其要設定的該軍隊,即要設定的XY座標
            return TorF
        else:
            print("指令輸入錯誤")
            return False


# while True:
#     command = input("請輸入指令\n")##讀取指令
#     inputCommand(player1,player2,1,command)
コード例 #27
0
ファイル: Bot.py プロジェクト: rougetimelord/Bruh-Bot
    async def on_ready(self):
        log.info("Logged in as {}, with ID {}".format(self.user.name,
                                                      self.user.id))
        await self.change_presence(activity=discord.Activity(
            name="for bruh moments", type=discord.ActivityType.watching))

        self.servers = {}
        try:
            with open("servers.json", "r") as f:
                self.servers = json.load(f)
        except FileNotFoundError as e:
            log.exception("No server file yet")
            with open("servers.json", "w+") as f:
                json.dump(self.servers, f)

        self.intervals = {}

        for id, value in self.servers.items():
            if value["disappearing"]:
                self.intervals[id] = Set.Interval(value["wipe_time"],
                                                  self.wipe,
                                                  id=value["wipe_channel"])
コード例 #28
0
ファイル: Player.py プロジェクト: dogbyday/SET
def getMostCard(board, deck, sets):
    minSet = -1
    maxExistingSets = -1
    numSetsForCard = 0
    setNum = 0
    
    for eachSet in sets:
        cards = eachSet.returnSet()
        for card in cards:
            for secondCard in (board + deck):
                if secondCard != card:
                    thirdCard = Set.predictThird(card, secondCard)
                    if thirdCard in (board + deck):
#                             print( card, secondCard, thirdCard)
                        numSetsForCard += 1
            if maxExistingSets == -1 or numSetsForCard > maxExistingSets:
                
                maxExistingSets = numSetsForCard
                minSet = setNum
        numSetsForCard = 0
        setNum += 1
    return sets[minSet]
コード例 #29
0
ファイル: Bot.py プロジェクト: SeattleDSA/encryptedbot_py
    def __init__(self) -> None:
        """Initializes the class."""
        self.callThreshold = int(os.getenv("CALL_THRESHOLD", 1))
        self.debug = os.getenv("DEBUG", "true").lower() == "true"
        self.reportLatency = os.getenv("REPORT_LATENCY",
                                       "false").lower() == "true"
        self.window_minutes = int(os.getenv("WINDOW_M", 5))
        self.timezone = pytz.timezone(os.getenv("TIMEZONE", "US/Pacific"))
        # The actual look back is the length of this lookback + lag compensation. For example: 300+45=345 seconds
        self.lookback = os.getenv("LOOKBACK_S", 300)

        self.cachedTweet: int = None
        self.cachedTime: datetime = None
        self.cache = TTLCache(maxsize=100, ttl=self.lookback)
        self.scraper = Scraper.Instance(self.BASE_URL, self.lookback)

        self.latency = [timedelta(seconds=0)]

        if not self.debug:
            # Does not need to be saved for later.
            # If the keys aren't in env this will still run.
            auth = tweepy.OAuthHandler(os.getenv("CONSUMER_KEY", ""),
                                       os.getenv("CONSUMER_SECRET", ""))
            auth.set_access_token(os.getenv("ACCESS_TOKEN_KEY", ""),
                                  os.getenv("ACCESS_TOKEN_SECRET", ""))
            self.api = tweepy.API(auth)
            # Test the authentication. This will gracefully fail if the keys aren't present.
            try:
                self.api.rate_limit_status()
            except TweepError as e:
                if e.api_code == 215:
                    log.error("No keys or bad keys")
                else:
                    log.error("Other API error: {}".format(e))
                exit(1)

        self.interval = Set.Interval(30, self._check)
コード例 #30
0
ファイル: test_All.py プロジェクト: madhi-naga/SE-2AA4
    def setup_method(self, method):
        self.s1 = Set([3, -6, 4, 0, 12, 9])
        self.e1 = ElmSet([ElementT.H, ElementT.O])

        self.m1 = MoleculeT(2, ElementT.H)
        self.m2 = MoleculeT(7, ElementT.O)
        self.m3 = MoleculeT(2, ElementT.H)
        self.m4 = MoleculeT(2, ElementT.O)
        self.m5 = MoleculeT(1, ElementT.O)

        self.c1 = CompoundT(MolecSet([self.m1, self.m2]))
        self.c2 = CompoundT(MolecSet([self.m3]))
        self.c3 = CompoundT(MolecSet([self.m4]))
        self.c4 = CompoundT(MolecSet([self.m3, self.m5]))

        # 2 H2 + O2 --> 2 H2O
        self.r1 = ReactionT([self.c2, self.c3], [self.c4])

        # 2 N --> N2
        self.m8 = MoleculeT(1, ElementT.N)
        self.m9 = MoleculeT(2, ElementT.N)
        self.c8 = CompoundT(MolecSet([self.m8]))
        self.c9 = CompoundT(MolecSet([self.m9]))
        self.r2 = ReactionT([self.c8], [self.c9])
コード例 #31
0
 def test_to_seq(self):
     s1 = Set([1, 2, 3, 4])
     s1 = s1.to_seq()
     assert s1 == [1, 2, 3, 4]
コード例 #32
0
 def test_equals(self):
     s1 = Set([1, 2, 3, 4])
     s2 = Set([1, 2, 3, 4])
     assert s1.equals(s2)