Example #1
0
def main():

    pygame.init()
    pantalla = pygame.display.set_mode((width, height))
    salir = False
    reloj = pygame.time.Clock()
    spawn_counter = 0
    spawn = 120

    '''Para la implementacion en el juego real esto tiene que cambiarse puesto a que 
    de esta manera solo deja implementar un sprite del mismo tipo a la vez'''
    sandrook = Sand(5)
    sand_rooks.add(sandrook)
    rockrook = Rock(5)
    rock_rooks.add(rockrook)
    firerook = Fire(5)
    fire_rooks.add(firerook)
    waterrook = Water(5)
    water_rooks.add(waterrook)
    rooks.add(waterrook, rockrook, firerook, waterrook)


    while salir != True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                salir = True

        reloj.tick(FPS)
        pantalla.fill(white)
        print(sand_attacks)
        print(sand_rooks)


        '''Para la implementacion en el juego real esto tiene que cambiarse puesto a que 
            de esta manera siempre van a aparecer los sprites y no va a ser de manera
            aleatoria.'''
        sandrook.spawn = True
        rockrook.spawn = True
        firerook.spawn = True
        waterrook.spawn = True
        if sandrook.spawn == True:
            sand_rooks.update(pantalla)
            sand_attacks.update(pantalla)
            sandrook.attack()
        if rockrook.spawn == True:
            rock_rooks.update(pantalla)
            rock_attacks.update(pantalla)
            rockrook.attack()
        if firerook.spawn == True:
            fire_rooks.update(pantalla)
            fire_attacks.update(pantalla)
            firerook.attack()
        if waterrook.spawn == True:
            water_rooks.update(pantalla)
            water_attacks.update(pantalla)
            waterrook.attack()

        pygame.display.update()

    pygame.quit()
Example #2
0
 def __init__(self, username: str, password: str, proxy: str = ""):
     mobile_emulation = {"deviceName": "Nexus 5"}
     from selenium.webdriver.chrome.options import Options
     mobile_emulation = {
         "deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0},
         "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"}
     chrome_options = Options()
     chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
     if proxy != "":
         chrome_options = webdriver.ChromeOptions()
         chrome_options.add_argument('--proxy-server=%s' % proxy)
     self.chrome = webdriver.Chrome(chrome_options=chrome_options)
     self.chrome.set_window_size(300, 1000)
     print("Logging in...")
     self.username = username
     self.password = password
     self.firebase = Fire(bot=self)
     stats = self.get_user_stats()
     self.following = stats["following"]
     self.followers = stats["followers"]
     self.posts = stats["posts"]
     # if not os.path.isdir("logs"):
     #     os.mkdir("logs")
     # log_path = "logs/" + username + ".log"
     # open(log_path, 'a').close()
     # logging.basicConfig(filename=log_path, level=logging.INFO)
     self.login(username, password)
     self.whitelist = self.firebase.get_whitelist()
Example #3
0
    async def on_ready(self):
        """
            Implementing discord.Client on_ready() that is called when the bot is ready

            We do any additional post-initialization set-up here
        """
        print('Logged on as {0}!'.format(self.user))
        self.sharedFire = Fire()
        self.timeLogger = TimeLogger(self.sharedFire)
        self.discordPoints = DiscordPoints(self.sharedFire)
        self.discordBets = DiscordBets(self.sharedFire)
        self.miscCommands = MiscCommands(self.sharedFire)
        self.loop.create_task(self.__track_time())
Example #4
0
 def __init__(self, rank, fires_wild, n_comp_nodes, machine_with_vertex):
     """
     NOTE: get_vertex_rank is a function. This way we can use this class in
             a flexible way.
     """
     self.rank = rank
     self.killed = False
     self.fires_wild = fires_wild
     self.num_compute_nodes = n_comp_nodes
     self.graph_reader = GraphInterpreter()
     self.partitioned_graph = Graph(self)
     self.fire_step = 10
     self.fire = Fire(self, self.partitioned_graph)
     self.machine_with_vertex = machine_with_vertex
 def __init__(self):
     '''
     小车功能初始化
     '''
     Fire.__init__(self, Fire_Pin=37)
     Hc_Sr501.__init__(self, Hc_Sr501_Pin=32)
     Moter.__init__(self,
                    Left_Pin=33,
                    Left_Pwm_Pin=35,
                    Right_Pin=29,
                    Right_Pwm_Pin=31)
     Tem_Hum.__init__(self, Tem_Hum_Pin=36)
     Servo.__init__(self, Servo_Pin=40)
     Mq_2.__init__(self, Mq_2_Pin=38)
     Network.Get_Socket(self, Socket_Ip="10.4.250.237", Sockeet_Port=2001)
Example #6
0
def test():
    try:
        fps = 500
        surface = pygame.display.set_mode((320, 200))
        pygame.init()
        spheres = (Fire(surface, 2), )
        clock = pygame.time.Clock()
        pause = False
        while True:
            clock.tick()
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    sys.exit(0)
            keyinput = pygame.key.get_pressed()
            if keyinput is not None:
                if keyinput[pygame.K_ESCAPE]:
                    sys.exit(1)
            if pause is not True:
                for thing in spheres:
                    thing.update()
                pygame.display.update()
            pygame.display.set_caption("frame rate: %.2f frames per second" %
                                       clock.get_fps())
    except KeyboardInterrupt:
        print 'shutting down'
Example #7
0
class InstaBot:
    chrome: webdriver.Chrome
    authenticated = False
    username = ""
    access_token = ""
    firebase = ""
    password = ""
    whitelist: [str] = []
    following = 0
    followers = 0
    posts = 0
    verified = False

    def __init__(self, username: str, password: str, proxy: str = ""):
        mobile_emulation = {"deviceName": "Nexus 5"}
        from selenium.webdriver.chrome.options import Options
        mobile_emulation = {
            "deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0},
            "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"}
        chrome_options = Options()
        chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
        if proxy != "":
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument('--proxy-server=%s' % proxy)
        self.chrome = webdriver.Chrome(chrome_options=chrome_options)
        self.chrome.set_window_size(300, 1000)
        print("Logging in...")
        self.username = username
        self.password = password
        self.firebase = Fire(bot=self)
        stats = self.get_user_stats()
        self.following = stats["following"]
        self.followers = stats["followers"]
        self.posts = stats["posts"]
        # if not os.path.isdir("logs"):
        #     os.mkdir("logs")
        # log_path = "logs/" + username + ".log"
        # open(log_path, 'a').close()
        # logging.basicConfig(filename=log_path, level=logging.INFO)
        self.login(username, password)
        self.whitelist = self.firebase.get_whitelist()

    def login(self, username: str, password: str):
        self.chrome.get("https://www.instagram.com/accounts/login/")
        sleep(2)
        dom = self.chrome.find_element_by_class_name("rgFsT ")  # Specifies the location of the username and password
        user = dom.find_element_by_name('username')
        pwd = dom.find_element_by_name('password')
        user.clear()
        pwd.clear()
        user.send_keys(username)
        pwd.send_keys(password)
        pwd.send_keys(u'\ue007')
        sleep(1 + latency)
        url = self.chrome.current_url
        if "challenge" in url:
            self.verify_if_available()
        if "login" in url:
            self.check_login()
        # self.check_notification()

    def check_notification(self):
        self.chrome.implicitly_wait(200)
        notification = self.chrome.find_elements_by_class_name("aOOlW   HoLwm ")
        if len(notification) > 0:
            notification[0].click()

    def authenticate(self, username: str, password: str):
        self.chrome.get("https://api.instagram.com/oauth/authorize/?client_id=e9be1d873671481cadc31086049841aa&redirect_uri=http://www.google.com&response_type=code")
        self.chrome.implicitly_wait(200)
        usr = self.chrome.find_element_by_name('username')
        pwd = self.chrome.find_element_by_name('password')
        usr.clear()
        pwd.clear()
        usr.send_keys(username)
        pwd.send_keys(password)
        pwd.send_keys(u'\ue007')
        sleep(2)
        url = self.chrome.current_url
        key = url.split("=")
        key_len = len(key)
        key = key[key_len - 2] + "=" + key[key_len - 1]
        self.access_token = key

    def get_following(self, username: str):
        ret_list: [str] = []
        self.chrome.get("https://www.instagram.com/" + username)
        sleep(1)
        # following_btn = self.chrome.find_elements_by_class_name("-nal3 ")
        following_btn = self.chrome.find_elements_by_xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "g47SY lOXF2", " " ))]')
        if len(following_btn) > 0:
            following_btn[2].click()
            sleep(1)
            follow_list = self.chrome.find_elements_by_class_name("wo9IH")
            if len(follow_list) == 0:
                self.chrome.refresh()
                self.get_following(username)
            else:
                last_user_count = len(follow_list)
                while True:
                    for user in follow_list:
                        element_height = user.location["y"]
                        self.chrome.execute_script("window.scrollTo(0, " + str(element_height - 120) + ");")
                        username = str(user.text).split("\n")[0]
                        if username not in ret_list:
                            ret_list.append(username)
                        sleep(0.2)
                    follow_list = self.chrome.find_elements_by_class_name("wo9IH")
                    if len(follow_list) <= last_user_count:
                        return ret_list
                    else:
                        last_user_count = len(follow_list)
        else:
            self.get_following()
        return ret_list

    def check_login(self):
        dom = self.chrome.find_elements_by_class_name("rgFsT ")  # Specifies the location of the username and password
        if len(dom) > 0:
            print("Failed Login")
            sleep(2)
            self.login(username=self.username, password=self.password)

    def follow_from_post(self, post_link: str, count: int)->[str]:
        consec_fail = 0
        ret_list: [str] = []
        check_list: [str] = []
        self.chrome.get(post_link)
        sleep(1)
        like_btn = self.chrome.find_elements_by_class_name("zV_Nj")
        if len(like_btn) > 0:
            self.chrome.execute_script("arguments[0].click();", like_btn[0])
            sleep(2)
            follow_count = 0
            new_scroll = 0
            old_scroll = 1
            while new_scroll != old_scroll:
                old_scroll = self.chrome.execute_script("return window.pageYOffset;")
                user_list = self.chrome.find_elements_by_xpath(
                    '//*[contains(concat( " ", @class, " " ), concat( " ", "ZUqME", " " ))]')
                for user in user_list:
                    username = str(user.text).split("\n")[0]
                    if username in check_list:
                        continue
                    followed_user = self.follow_user_from_list(user_element=user)
                    if followed_user == "fail":
                        consec_fail += 1
                        if consec_fail >= 2:
                            consec_fail = 0
                            sleep_time = randint(120, 200)
                            print("Max Followed, sleeping for : " + str(sleep_time) + " seconds")
                            sleep(sleep_time)
                    if followed_user != "fail":
                        consec_fail = 0
                    if followed_user != "":
                        follow_count += 1
                        ret_list.append(followed_user)
                    if follow_count >= count:
                        print("Finished Process on post: " + post_link)
                        print("--- Followed: " + str(follow_count))
                        return ret_list
                    if username != None:
                        check_list.append(username)
                    new_scroll = self.chrome.execute_script("return window.pageYOffset;")
            return  ret_list

    def follow_user_from_list(self, user_element, updated_server=False)->str:
        try:
            element_height = user_element.location["y"]
            self.chrome.execute_script("window.scrollTo(0, " + str(element_height - 120) + ");")
            follow_btn = user_element.find_element_by_xpath(
                './/*[contains(concat( " ", @class, " " ), concat( " ", "L3NKy", " " ))]')
            follow_tex = str(follow_btn.text)
            if ("Following" in follow_tex) & ("Requested" in follow_tex):
                return ""
            sleep(1)
            sleep(randint(0, 2))
            element_text = str(user_element.text).split("\n")
            username = element_text[0]
            follow_text = element_text[2]
            if (username not in self.whitelist) & ("Following" not in follow_text) & ("Requested" not in follow_text):
                follow_btn = user_element.find_element_by_xpath('.//*[contains(concat( " ", @class, " " ), concat( " ", "L3NKy", " " ))]')
                self.chrome.execute_script("arguments[0].click();", follow_btn)
                sleep(2)
                follow_btn_2 = user_element.find_element_by_xpath('.//*[contains(concat( " ", @class, " " ), concat( " ", "L3NKy", " " ))]')
                if ("Following" in follow_btn_2.text) | ("Requested" in follow_btn_2.text):
                    print("Followed: " + username)
                    if updated_server:
                        self.firebase.set_statistics(follows=[username])
                    self.firebase.local_save(followed=[username])
                    return username
                else:
                    print("FAIL: Insta follow block")
                    return "fail"
        except Exception as e:
            print("FAIL: " + str(e))
            if "range" in str(e):
                sleep(0.25)
            print("---failed: follow user from list")
            return ""
        return ""

    def unfollow_users_from_profile(self, count: int)->[str]:
        unfollow_count = 0
        unfollow_list: [str] = []
        self.__go_to_following__()
        user_list = self.chrome.find_elements_by_class_name("wo9IH")
        for user in user_list:
            completion = self.__unfollow_user_from_list__(user)
            if completion != "":
                unfollow_count += 1
                unfollow_list.append(completion)
                if unfollow_count >= count:
                    return unfollow_list
        return unfollow_list

    def __go_to_following__(self):
        if self.username not in self.chrome.current_url:
            self.chrome.get("https://www.instagram.com/" + self.username + "/following/")
        sleep(2 + latency)
        header_btns = self.chrome.find_elements_by_class_name(" LH36I")
        header_btns[2].click()
        sleep(2 + latency)
        if "following" not in self.chrome.current_url:
            self.chrome.execute_script("arguments[0].click();", header_btns[2])
            sleep(2 + latency)
        user_list = self.chrome.find_elements_by_class_name("wo9IH")
        if len(user_list) == 0:
            self.chrome.refresh()
            self.__go_to_following__()

    def __unfollow_user_from_list__(self, user_element, update_server=False)->str:
        try:
            user_text = str(user_element.text).split("\n")
            username = user_text[0]
            follow_text = user_text[2]
            if ("Requested" in follow_text) | ("Following" in follow_text):
                if username not in self.whitelist:
                    follow_btn = user_element.find_element_by_xpath('.//*[contains(concat( " ", @class, " " ), concat( " ", "_8A5w5", " " ))]')
                    btn_height = follow_btn.location["y"]
                    self.chrome.execute_script("window.scrollTo(0, " + str(btn_height - 120) + ");")
                    sleep(0.5)
                    self.chrome.execute_script("arguments[0].click();", follow_btn)
                    self.__unfollow_user_from_list_secondary__()
                    sleep(2)
                    # We need to refresh the user_element after clicking the secondary one
                    new_user_list = self.chrome.find_elements_by_class_name("wo9IH")
                    for new_user_element in new_user_list:
                        new_username = str(new_user_element.text).split("\n")[0]
                        if username == new_username:
                            follow_btn = new_user_element.find_element_by_xpath('.//*[contains(concat( " ", @class, " " ), concat( " ", "_0mzm- sqdOP  L3NKy       ", " " ))]')
                            follow_btn_text = str(follow_btn.text)
                            if ("Requested" not in follow_btn_text) & ("Following" not in follow_btn_text):
                                print("Unfollowed: " + username)
                                if update_server:
                                    self.firebase.set_statistics(unfollows=[username])
                                self.firebase.local_save(unfollowed=[username])
                                return username
        except Exception as e:
            print(e)
            return ""

    def __unfollow_user_from_list_secondary__(self):
        second_unfollow = self.chrome.find_element_by_xpath('.//*[contains(concat( " ", @class, " " ), concat( " ", "aOOlW -Cab_   ", " " ))]')
        second_unfollow.click()

    def find_posts(self, count=3)->[str]:
        print("Searching for random user...")
        rando = self.__go_to_random_followed_user__()
        print("---found user: "******" ", @class, " " ), concat( " ", "v1Nh3 kIKUG  _bz0w", " " ))]')
        for post in displayed_posts:
            post_url_holder = post.find_element_by_xpath(".//a")
            url = post_url_holder.get_attribute("href")
            ret_posts.append(str(url))
            if len(ret_posts) >= count:
                return ret_posts
        return ret_posts

    def __scroll_from_user_list__(self, user_element):
        scroll_distance = user_element.location["y"] + (60 * 10) - 120
        self.chrome.execute_script("window.scrollTo(0, " + str(scroll_distance) + ");")

    def get_user_stats(self)->dict:
        if self.chrome.current_url != "https://www.instagram.com/" + self.username + "/":
            self.chrome.get("https://www.instagram.com/" + self.username)
        header_btns = self.chrome.find_elements_by_class_name(" LH36I")
        follower_count = str(header_btns[2].text).split("\n")[0]
        following_count = str(header_btns[1].text).split("\n")[0]
        post_count = str(header_btns[0].text).split("\n")[0]
        ret_val = {
            "followers": follower_count,
            "following": following_count,
            "posts": post_count
        }
        return ret_val

    def __get_search_list__(self, user_list):
        curr_scroll = self.chrome.execute_script("return window.pageYOffset;")
        search_list = []
        for user in user_list:
            if (user.location["y"] >= curr_scroll) & (user.location["y"] <= curr_scroll + 600):  # 600 is the visible scroll distance
                search_list.append(user)
            if user.location["y"] > curr_scroll + 600:
                for i in range(search_list.count(None)): search_list.remove(None)  # filter all of the None's from the search list (avoids issue)
                return search_list

    def __go_to_random_followed_user__(self)->str:
        random_num = randint(0, int(int(self.following) / 5))  # get random user from first 1/5th of the following list
        self.__go_to_following__()
        user_list = self.chrome.find_elements_by_class_name("wo9IH")
        user_count = 0
        search_list = self.__get_search_list__(user_list)
        while True:
            curr_count = 0
            for user in search_list:
                if user_count == random_num:
                    username = str(user.text).split("\n")[0]
                    self.chrome.get("https://www.instagram.com/" + username)
                    return username
                user_count += 1
                curr_count += 1
                if curr_count >= len(search_list):
                    self.__scroll_from_user_list__(user_element=user)
            user_list = self.chrome.find_elements_by_class_name("wo9IH")
            search_list = self.__get_search_list__(user_list)

    def verify_if_available(self):
        choice_options = self.chrome.find_elements_by_class_name("UuB0U ")
        email_text = ""
        phone_text = ""
        if len(choice_options) > 0:
            for choice in choice_options:
                if "Email" in choice.text:
                    email_text = choice.text
                if "Phone" in choice.text:
                    phone_text = choice.text
            self.firebase.set_management_value(ManagementLocations.verifier, str(email_text) + "\n" + str(phone_text))
        while not self.verified:
            sleep(1)

    def __verifier_click__(self, option: str):
        choice_options = self.chrome.find_elements_by_class_name("UuB0U ")
        for choice in choice_options:
            if option in str(choice.text):
                self.chrome.execute_script("arguments[0].click();", choice)
                choice.click()
                sleep(3)
                secuirty_btn = self.chrome.find_element_by_xpath(
                    '//*[contains(concat( " ", @class, " " ), concat( " ", "_5f5mN       jIbKX KUBKM      yZn4P   ", " " ))]')
                self.chrome.execute_script("arguments[0].click();", secuirty_btn)
                sleep(1)

    def __verifier_code_enter__(self, code: str):
        code_field = self.chrome.find_element_by_id("security_code")
        code_field.send_keys(code)
        code_field.send_keys(u'\ue007')
        sleep(2)
        if "challenge" not in self.chrome.current_url:
            self.verified = True
            self.firebase.set_management_value(ManagementLocations.verifier, "")
        else:
            print("Validation Failed, send notification")
Example #8
0
class DiscordClient(discord.Client):
    """
    Creates an instance of the "Bot"

    Attributes
    __________
    sharedFire: (Fire obj)
        Instance of the custom Fire class to fetch and update the database
    timeLogger: (TimeLogger obj)
        Instance of the TimeLogger class to display and parse information from
        the database
    miscCommands: (MiscCommands obj)
        Instance of the MiscCommands class to display random Misc. messages

    Functions
    __________
    async on_ready()
        Implementing discord.Client on_ready() that is called when the bot is ready
    async on_message()
        Implementing discord.Client on_message() that is called when a user messages
        in a server (discord.Guild)

    """
    sharedFire = None
    timeLogger = None
    miscCommands = None
    discordPoints = None
    discordBets = None

    async def on_ready(self):
        """
            Implementing discord.Client on_ready() that is called when the bot is ready

            We do any additional post-initialization set-up here
        """
        print('Logged on as {0}!'.format(self.user))
        self.sharedFire = Fire()
        self.timeLogger = TimeLogger(self.sharedFire)
        self.discordPoints = DiscordPoints(self.sharedFire)
        self.discordBets = DiscordBets(self.sharedFire)
        self.miscCommands = MiscCommands(self.sharedFire)
        self.loop.create_task(self.__track_time())

    async def __track_time(self):
        """
            Private helper function to help track time

            This function is called on a separate thread and loops every 60 seconds
        """

        await self.wait_until_ready()

        while not self.is_closed():
            try:
                for guild in self.guilds:
                    members = self.__filter_channel_members(guild)
                    self.sharedFire.incrementTimes(guild, members)
                await asyncio.sleep(60)
            except Exception as e:
                print("ERROR: ", str(e))
                await asyncio.sleep(60)

    def __filter_channel_members(self, guild):
        """
            Private helper function to filter members to track

            We do not increment times for individuals that are deafened, muted, or afk
        """

        members = []
        channels = guild.voice_channels

        for cur_channel in channels:
            if cur_channel.members:
                for member in cur_channel.members:
                    if not member.voice.self_deaf and not member.voice.afk and not member.voice.deaf:
                        members.append(member)

        return members

    async def on_message(self, message):
        """
            Implementing discord.Client on_message() that is called when a user messages
            in a server (discord.Guild)

            This is where all of the commands are called for the DiscordClient
        """

        if message.author == self.user:
            return

        if len(message.content) < 1:
            return

        if message.content[0] == '-':
            # ---------- MARK: - Miscellaneous Commands ----------
            if message.content.startswith('-hello'):
                s = 'Hello ' + str(message.author) + '\n' + self.miscCommands.getRandomCompliment()
                await message.channel.send(s)

            elif message.content.startswith('-help'):
                await message.channel.send(embed=self.miscCommands.getHelpMessage())

            elif message.content.startswith('-rob'):
                await message.channel.send("Rob is a qt3.14 :-)")

            elif message.content.startswith('-patch'):
                await message.channel.send(self.miscCommands.getPatchNotes())

            elif message.content.startswith('-feedback'):
                if len(message.content.split(" ", 1)) == 2:
                    feedBack = message.content.split(" ", 1)
                    await message.channel.send(self.miscCommands.sendFeedback(message.guild.id, message.author.id, feedBack[1]))
                else: 
                    await message.channel.send(embed=getUsageEmbed("-feedback [feedback message]"))

            elif message.content.startswith('-donkey'):
                splitMessage = message.content.split(" ", 1)
                if len(splitMessage) == 2:
                    donkeyUser = splitMessage[1]
                    await message.channel.send(donkeyUser, file=self.miscCommands.getDonkeyImage())
                else:
                    await message.channel.send(embed=getUsageEmbed("-donkey [discord user]"))

            # ---------- MARK: - TimeLogger Commands ----------
            elif message.content.startswith('-totallog'):
                msg = message.content
                msgAndPage = msg.split(" ")
                if len(msgAndPage) == 2:
                    await message.channel.send(embed=await self.timeLogger.getTotalLogEmbed(int(msgAndPage[1]), message.guild))
                else:
    	            await message.channel.send(embed=await self.timeLogger.getTotalLogEmbed(1, message.guild))

            elif message.content.startswith('-todaylog'):
                await message.channel.send(embed=await self.timeLogger.getTodayLogEmbed(message.guild))

            elif message.content.startswith('-weeklog'):
                msg = message.content
                msgAndPage = msg.split(" ")
                if len(msgAndPage) == 2:
                    await message.channel.send(embed=await self.timeLogger.getWeekLogEmbed(int(msgAndPage[1]), message.guild))
                else:
                    await message.channel.send(embed=await self.timeLogger.getWeekLogEmbed(1, message.guild))

            elif message.content.startswith('-mylog'):
                await message.channel.send(embed=self.timeLogger.getMyLogEmbed(message.guild, message.author))

            # ---------- MARK: - DiscordPoints Commands ----------
            elif message.content.startswith('-points'):
                msg = message.content
                msgAndPage = msg.split(" ")
                if len(msgAndPage) == 2:
                    await message.channel.send(embed=await self.discordPoints.getDiscordPointsEmbed(int(msgAndPage[1]), message.guild))
                else:
    	            await message.channel.send(embed=await self.discordPoints.getDiscordPointsEmbed(1, message.guild))

            elif message.content.startswith('-addreward'):
                msg = message.content
                commandAndReward = msg.split(" ", 1)

                if (message.author.guild_permissions.administrator):
                    if len(commandAndReward) == 2:
                        await message.channel.send(embed=self.discordPoints.createNewReward(message.guild, commandAndReward[1]))
                    else:
                        await message.channel.send(embed=getUsageEmbed("-addreward [Desired Reward] [Price of the Reward]\n\nexample: -addreward CSGO with friends 500"))
                else:
                    await message.channel.send(embed=getMissingPermissionsEmbed("Oops.. you have to be an admin to use this command"))

            elif message.content.startswith('-rewards'):
                await message.channel.send(embed=self.discordPoints.getRewardsEmbed(message.guild))

            elif message.content.startswith('-redeem'):
                msg = message.content
                commandAndRewardId = msg.split(" ")

                if len(commandAndRewardId) == 2:
                    await message.channel.send(embed=self.discordPoints.redeemReward(message.guild, message.author, commandAndRewardId[1]))
                else:
                    await message.channel.send(embed=getUsageEmbed("-redeemReward [Desired Reward Id]\n\nexample: -redeemReward 3"))

            # ---------- MARK: - DiscordBet Commands ----------
            elif message.content.startswith('-createbet'):
                msg = message.content
                commandAndBet = msg.split(" ", 1)
                if len(commandAndBet) == 2:
                    await message.channel.send(embed=await self.discordBets.createBet(message.guild, message.author, commandAndBet[1]))
                else:
                    await message.channel.send(embed=getUsageEmbed("-createbet [[Bet Description]] [[Option 1], [Option 2], ...]\n\nexample: -createbet [I will win this game] [yes, no]"))

            elif message.content.startswith('-closebet'):
                msg = message.content
                commandAndBet = msg.split(" ")
                if len(commandAndBet) == 2:
                    await message.channel.send(embed=await self.discordBets.closeBet(message.guild, message.author, commandAndBet[1]))
                else:
                    await message.channel.send(embed=getUsageEmbed("-closebet [Bet Id]"))

            elif message.content.startswith('-completebet'):
                msg = message.content
                commandAndBet = msg.split(" ")
                if len(commandAndBet) == 3:
                    await message.channel.send(embed=await self.discordBets.completeBet(message.guild, message.author, commandAndBet[1], commandAndBet[2]))
                else:
                    await message.channel.send(embed=getUsageEmbed("-completebet [Bet Id] [Winner Option Num]\n\nexample: -completebet 1 2"))

            elif message.content.startswith('-allbets'):
                await message.channel.send(embed=self.discordBets.getAllActiveBets(message.guild))

            elif message.content.startswith('-bet'):
                msg = message.content
                commandAndBet = msg.split(" ", 1)
                if len(commandAndBet) == 2:
                    await message.channel.send(embed=await self.discordBets.bet(message.guild, message.author, commandAndBet[1]))
                else: 
                    await message.channel.send(embed=getUsageEmbed("-bet [bet id] [option number] [discord points amount]\n\n example: -bet 3 2 500"))

            elif message.content.startswith('-mybets'):
                await message.channel.send(embed=self.discordBets.showBetForUser(message.guild, message.author))

            elif message.content.startswith('-showbet'):
                msg = message.content
                commandAndBet = msg.split(" ", 1)

                if len(commandAndBet) == 2:
                    await message.channel.send(embed=await self.discordBets.showBet(message.guild, commandAndBet[1]))
                else: 
                    await message.channel.send(embed=getUsageEmbed("-showbet [bet id]\n\n example: -showbet 7"))
Example #9
0
 def mario_fire(self):
     print("Fire is made now draw")
     self.fire_list.append(Fire(self.mario.x, self.mario.y))
Example #10
0
    def newFires(self, model, ffdi, time, configWeights):
        occ = numpy.interp(ffdi, self.vegetation.getFFDIRange(),
                           self.vegetation.getOccurrence()[time])

        sizeMean = 0.0
        sizeSD = 0.0
        initS = 0.0

        for w, weight in enumerate(configWeights):
            sizeMean += weight * numpy.interp(
                ffdi, self.vegetation.getFFDIRange(),
                self.vegetation.getInitialSizeMean()[w + 1])
            sizeSD += weight * numpy.interp(
                ffdi, self.vegetation.getFFDIRange(),
                self.vegetation.getInitialSizeSD()[w + 1])
            initS += weight * numpy.interp(
                ffdi, self.vegetation.getFFDIRange(),
                self.vegetation.getInitialSuccess()[w + 1])

        newFires = numpy.random.poisson(occ * self.area)
        newFiresList = []

        for f in range(newFires):
            success = True if initS > numpy.random.rand() else False
            size = math.exp(sizeMean + numpy.random.rand() * sizeSD)
            fire = Fire()
            fire.setLocation(self.randomPatchPoint())
            fire.setSize(size)
            fire.setInitialSize(size)
            fire.setFinalSize(size)
            fire.setExtinguished(success)
            fire.setPatchID(self.patchID)
            newFiresList.append(fire)

        return newFiresList
Example #11
0
class ComputeNode:
    def __init__(self, rank, fires_wild, n_comp_nodes, machine_with_vertex):
        """
        NOTE: get_vertex_rank is a function. This way we can use this class in
                a flexible way.
        """
        self.rank = rank
        self.killed = False
        self.fires_wild = fires_wild
        self.num_compute_nodes = n_comp_nodes
        self.graph_reader = GraphInterpreter()
        self.partitioned_graph = Graph(self)
        self.fire_step = 10
        self.fire = Fire(self, self.partitioned_graph)
        self.machine_with_vertex = machine_with_vertex

    def __del__(self):
        for k, v in timer.items():
            logging.info(f"timer {k} {v:.2f}")

        for k, v in counter.items():
            logging.info(f"counter {k} {v}")

    def get_machine_log(self):
        return "On Machine " + str(self.rank) + "."

    def send_fire_to_remotes(self, machine_vertexes_to_receive):
        nodes_to_burn_locally = []
        logging.debug(self.get_machine_log() + " sending data")

        for i in range(1, self.num_compute_nodes + 1):
            if i != self.rank:
                data = comm.sendrecv(
                    machine_vertexes_to_receive[i],
                    dest=i,
                    sendtag=MPI_TAG.FROM_COMPUTE_TO_COMPUTE.value,
                    recvbuf=None,
                    source=i,
                    recvtag=MPI_TAG.FROM_COMPUTE_TO_COMPUTE.value,
                    status=None)
                if len(data) > 0:
                    nodes_to_burn_locally.extend(data)

        self.fire.merge(nodes_to_burn_locally)

    @timeit(timer=timer, counter=counter)
    def send_heartbeat(self, new_edges):
        # this send is non-blocking
        logging.debug("sending heartbeat")
        data = np.array(new_edges.list_rep())
        # record how many edges are sent
        counter["n_edge_in_send_heartbeat"] += data.shape[0]
        comm.send(data, dest=0, tag=MPI_TAG.HEARTBEAT.value)
        logging.debug("heartbeat sent")

    @timeit(timer=timer, counter=counter)
    def send_burn_requests(self):
        remote_vertices = self.fire.remote_vertices_to_burn
        machine_vertexes_to_receive = {}
        for machine in range(0, self.num_compute_nodes + 1):
            machine_vertexes_to_receive[machine] = []

        for vert in remote_vertices:
            machine_owning_vertex = self.machine_with_vertex[vert]
            machine_vertexes_to_receive[machine_owning_vertex].append(vert)

        self.send_fire_to_remotes(machine_vertexes_to_receive)
        self.fire.reset_remote_vertices_to_burn()

    def increase_fire_step(self):
        self.fire_step = min(40, self.fire_step * 2)
        logging.debug(f"setting fire step to {self.fire_step}")

    def lower_fire_step(self):
        self.fire_step = max(10, self.fire_step / 2)

    @timeit(timer=timer, counter=counter)
    def do_spread_steps(self, new_edges):
        # do 10 spread steps,
        # new_edges are updated every spread step by the fire
        fire_relight_exponent_old = self.fire.relight_exponent
        for i in range(self.fire_step):
            self.fire.spread(new_edges)

        if self.fire.relight_exponent > fire_relight_exponent_old:
            self.increase_fire_step()
        else:
            self.lower_fire_step()

    @timeit(timer=timer, counter=counter)
    def init_partition(self, path_to_edge_file):
        for vert_1, vert_2 in self.graph_reader.read_graph_file(
                path_to_edge_file):
            self.partitioned_graph.add_vertex_and_neighbor(vert_1, vert_2)

    def reset_fire(self):
        self.partitioned_graph.set_all_vertex_status(VertexStatus.NOT_BURNED)
        self.fire.ignite_random_node()

    @timeit(timer=timer, counter=counter)
    def receive_from_headnode(self):
        # blocking receive from headnode.
        logging.debug("about to receive from headnode")
        status = MPI.Status()
        comm.recv(source=0, tag=MPI.ANY_TAG, status=status)

        if status.Get_tag() == MPI_TAG.CONTINUE.value:
            logging.debug("continuing")
        elif status.Get_tag() == MPI_TAG.KILL.value:
            logging.debug(self.get_machine_log() + ".. received kill")
            self.fire.stop_burning()
            self.killed = True
        elif status.Get_tag() == MPI_TAG.RESET.value:
            self.reset_fire()
        logging.debug("received from headnode")

    @timeit(timer=timer, counter=counter)
    def do_tasks(self):
        # only ignites, has not started spreading
        self.fire.ignite_random_node()
        all_edges_sent = EdgeSet()
        while not self.killed:
            new_edges = EdgeSet()
            logging.debug(self.get_machine_log() +
                          ".. num_burning vertex ids = " +
                          str(len(self.fire.get_burning_vertex_ids())))
            self.do_spread_steps(new_edges)

            if self.fires_wild:
                self.send_burn_requests()

            logging.debug(self.get_machine_log() + ".. num edges sent = " +
                          str(len(new_edges.list_rep())))

            for edge in new_edges.edges:
                all_edges_sent.add_edge(edge[0], edge[1])

            self.send_heartbeat(new_edges)
            self.receive_from_headnode()

        logging.debug("num edges sent total = " +
                      str(len(all_edges_sent.list_rep())))