def fetch(self, country_id):
        fetch_state = False
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'client-secret.json', scope)
        sh = gspread.authorize(credentials).open_by_key(
            '1SjJG2RzITf8qAmYDU9RFnWVaMP9912y8KfbuJe8th-c')

        country_id = str(country_id)
        for ws_count, worksheet in enumerate(sh.worksheets()):
            # TODO write State By Country Here

            state_district = seeds.get_state_name(worksheet.title)
            state_name = "{0}/{1}".format(state_district[0], state_district[1])
            state_id = str(uuid.uuid4().hex)
            state = State(id=state_id,
                          object_id=state_id,
                          country_id=str(country_id),
                          name_mm_uni=str(state_name),
                          name_mm_zawgyi=Rabbit.uni2zg(state_name))
            cal_day_list = worksheet.col_values(1)
            hij_day_list = worksheet.col_values(2)
            sehri_time_list = worksheet.col_values(3)
            iftari_time_list = worksheet.col_values(4)

            db_session.add(state)
            db_session.commit()
            for i, (cal_day, hij_day, seh_time, iftar_time) in enumerate(
                    zip(cal_day_list, hij_day_list, sehri_time_list,
                        iftari_time_list)):
                if i is not 0:
                    article_id = str(uuid.uuid4().hex)
                    article = Day(
                        id=article_id,
                        object_id=article_id,
                        country_id=str(country_id),
                        state_id=str(state.object_id),
                        day=i,
                        day_mm=str(seeds.get_mm_num(i)),
                        sehri_time=str(seh_time + " am"),
                        sehri_time_desc="Sehri",
                        calendar_day=str(cal_day),
                        hijari_day=str(hij_day),
                        sehri_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါချည်ချိန်"),
                        sehri_time_desc_mm_uni="ဝါချည်ချိန်",
                        iftari_time=str(iftar_time + " pm"),
                        dua_mm_uni=Rabbit.zg2uni(seeds.daily_dua(i)["dua_mm"]),
                        dua_mm_zawgyi=Rabbit.uni2zg(
                            seeds.daily_dua(i)["dua_mm"]),
                        dua_ar=seeds.daily_dua(i)["dua_ar"],
                        dua_en=seeds.daily_dua(i)["dua_en"],
                        iftari_time_desc="Iftari",
                        iftari_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါဖြေချိန်"),
                        iftari_time_desc_mm_uni="ဝါဖြေချိန်")

                    db_session.add(article)
                    db_session.commit()
                    fetch_state = True

        return fetch_state
Beispiel #2
0
    def test_uni2zg(self):
        print("converting Unicode to Zawgyi")
        converted = Rabbit.uni2zg(u"မင်္ဂလာပါ")
        self.assertEqual(converted, u"မဂၤလာပါ")

        converted = Rabbit.uni2zg(u"ပြင်သစ်ဘာသာကီးဘုတ်")
        self.assertEqual(converted, u"ျပင္သစ္ဘာသာကီးဘုတ္")
Beispiel #3
0
    def __init__(self, width, height):
        self.width = width
        self.height = height
        unit_w = self.width / 10
        unit_h = self.height / 10
        offset = self.width / 16

        self.rabbits = [
            Rabbit(unit_w - offset, unit_h * 6, unit_h * 6, unit_h * 4.5,
                   width, height),
            Rabbit((unit_w * 2.8) - offset, unit_h * 7, unit_h * 7,
                   unit_h * 5.5, width, height),
            Rabbit((unit_w * 5) - offset, unit_h * 6, unit_h * 6, unit_h * 4.5,
                   width, height),
            Rabbit((unit_w * 6.8) - offset, unit_h * 7, unit_h * 7,
                   unit_h * 5.5, width, height),
            Rabbit((unit_w * 8.5) - offset, unit_h * 6, unit_h * 6,
                   unit_h * 4.5, width, height)
        ]
        self.score_objects = []

        self.score = 0
        self.timer = 0
        self.GAME_LENGTH = 60
        self.start_time = 0
        self.penalise_error = True
Beispiel #4
0
    def test_zg2uni(self):
        print("converting Zawgyi to Unicode")
        converted = Rabbit.zg2uni(u"မဂၤလာပါ")
        self.assertEqual(converted, u"မင်္ဂလာပါ")

        converted = Rabbit.zg2uni(u"ျပင္သစ္ဘာသာကီးဘုတ္")
        self.assertEqual(converted, u"ပြင်သစ်ဘာသာကီးဘုတ်")
Beispiel #5
0
    def update(self):
        self.ticks += 1

        if self.ticks % 10 == 0:
            self.plants[Species.Carrot].append(
                Food(random.uniform(50, self.width - 50),
                     random.uniform(50, self.height - 50)))

        for spec in self.animals.keys():
            for animal in self.animals[spec]:
                animal.update(self)
                if animal.state == "dead":
                    self.animals[spec].remove(animal)
                elif animal.state == "reproduced":
                    if animal._species == Species.Rabbit:
                        baby = Rabbit(animal.coord.x, animal.coord.y)
                        baby.genes = Genes.combineGenes(
                            animal.genes, animal.genes)
                        self.animals[spec].append(baby)
                    elif animal._species == Species.Fox:
                        self.animals[spec].append(
                            Fox(animal.coord.x, animal.coord.y))

        for spec in self.plants.keys():
            for plant in self.plants[spec]:
                if not plant.isAvailable():
                    self.plants[spec].remove(plant)

        self.recordPopulations()
Beispiel #6
0
    def fetch(self, country_id):

        fname = join(dirname(dirname(abspath(__file__))), 'ramdhan-api/data',
                     'ramadan_timetable_sheet.xlsx')
        work_book = xlrd.open_workbook(fname)

        country_id = str(country_id)
        for ws_count, worksheet in enumerate(work_book.sheet_names()):
            # TODO write State By Country Here

            state_district = seeds.get_state_name(worksheet)
            state_name = "{0}/{1}".format(state_district[0], state_district[1])
            state_id = str(uuid.uuid4().hex)
            state = State(id=state_id,
                          object_id=state_id,
                          country_id=str(country_id),
                          name_mm_uni=str(state_name),
                          name_mm_zawgyi=Rabbit.uni2zg(state_name))
            sheet = work_book.sheet_by_index(ws_count)
            cal_day_list = sheet.col_values(0)
            hij_day_list = sheet.col_values(1)
            sehri_time_list = sheet.col_values(2)
            iftari_time_list = sheet.col_values(3)

            db_session.add(state)
            db_session.commit()
            for i, (cal_day, hij_day, seh_time, iftar_time) in enumerate(
                    zip(cal_day_list, hij_day_list, sehri_time_list,
                        iftari_time_list)):
                if i is not 0:
                    article_id = str(uuid.uuid4().hex)
                    article = Day(
                        id=article_id,
                        object_id=article_id,
                        country_id=str(country_id),
                        state_id=str(state.object_id),
                        day=i,
                        day_mm=str(seeds.get_mm_num(i)),
                        sehri_time=str(str(seh_time).strip() + " am"),
                        sehri_time_desc="Sehri",
                        calendar_day=str(date[i - 1]),
                        hijari_day=str(hij_day).strip(),
                        sehri_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါချည်ချိန်"),
                        sehri_time_desc_mm_uni="ဝါချည်ချိန်",
                        iftari_time=str(str(iftar_time).strip() + " pm"),
                        dua_mm_uni=Rabbit.zg2uni(seeds.daily_dua(i)["dua_mm"]),
                        dua_mm_zawgyi=Rabbit.uni2zg(
                            seeds.daily_dua(i)["dua_mm"]),
                        dua_ar=seeds.daily_dua(i)["dua_ar"],
                        dua_en=seeds.daily_dua(i)["dua_en"],
                        iftari_time_desc="Iftari",
                        iftari_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါဖြေချိန်"),
                        iftari_time_desc_mm_uni="ဝါဖြေချိန်")

                    db_session.add(article)
                    db_session.commit()
                    fetch_state = True

        return fetch_state
Beispiel #7
0
class RpcClient(object):

    def __init__(self, routing_key, host="localhost"):
        # routing_key - 'rpc_queue'
        self.routing_key = routing_key

        self.rabbit = Rabbit(host)
        # 队列名,随机
        self.callback_queue_name = self.rabbit.declare_queue(exclusive=True)
        self.rabbit.register_consumer(queue_name=self.callback_queue_name, callback=self.on_response)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.rabbit.close()

    def on_response(self, ch, method, props, body):
        """
        收到消息就调用
        :param ch: 管道内存对象地址
        :param method: 消息发给哪个queue
        :param props:
        :param body: 数据对象
        :return:
        """
        # 判断本机生成的ID与生产端发过来的ID是否相等
        if self.corr_id == props.correlation_id:
            # 将body值 赋值给self.response
            self.response = body

    def call(self, msg):
        """
        发送dict
        :param msg:
        :type msg: dict
        :return: dict
        """
        # 随机的字符串
        self.response = None
        self.corr_id = str(uuid.uuid4())

        # routing_key='rpc_queue' 发一个消息到rpc_queue内
        self.rabbit.channel.basic_publish(exchange='',
                                   routing_key=self.routing_key,
                                   properties=pika.BasicProperties(
                                       # 执行命令之后消费端将结果返回给self.callaback_queue这个队列中
                                       reply_to=self.callback_queue_name,
                                       # 生成UUID 发送给消费端
                                       correlation_id=self.corr_id,
                                   ),
                                   # 发的消息,必须传入字符串,不能传数字
                                   body=json.dumps(msg))

        # 监听数据
        while self.response is None:
            # 没有消息不阻塞
            self.rabbit.conn.process_data_events()
        return json.loads(str(self.response, encoding="utf-8"))
Beispiel #8
0
    def __init__(self, routing_key, host="localhost"):
        # routing_key - 'rpc_queue'
        self.routing_key = routing_key

        self.rabbit = Rabbit(host)
        # 队列名,随机
        self.callback_queue_name = self.rabbit.declare_queue(exclusive=True)
        self.rabbit.register_consumer(queue_name=self.callback_queue_name, callback=self.on_response)
Beispiel #9
0
def create_rabbit(ai_settings, screen, rabbits, rabbit_number, row_number):
    """create a rabbit"""
    rabbit = Rabbit(ai_settings, screen)
    rabbit_width = rabbit.rect.width
    rabbit.x = rabbit_width + 2 * rabbit_width * rabbit_number
    rabbit.rect.x = rabbit.x
    rabbit.rect.y = rabbit.rect.height + 2 * rabbit.rect.height\
        * row_number
    rabbits.add(rabbit)
Beispiel #10
0
 def __init__(self, queue_name):
     self._queue_name = queue_name
     channel = Rabbit().create_channel()
     channel.queue_declare(queue=queue_name, durable=True)
     self.channel = channel
     self.lock = Lock()
     self._current_time = None
     self.count_per_minute = None
     self._init_count()
     print(f'{self.__class__} 被实例化了')
    def _generate_shops(self, shops, is_zawgyi):
        is_zawgyi = str2bool(is_zawgyi)

        return [{
            "title":
            Rabbit.uni2zg(
                str(shop.get("name_uni")) + str(shop.get("description")))
            if is_zawgyi else str(shop.get("name_uni")) +
            str(shop.get("description")),
            "image_url":
            "http://source.unsplash.com/NEqPK_bF3HQ",
            "subtitle":
            Rabbit.uni2zg(
                str(shop.get("region_name")) + "တွင်ရှိပါသည်။ " +
                str(shop.get("description")))
            if is_zawgyi else shop.get("region_name") + "တွင်ရှိပါသည်။ " +
            shop.get("description"),
            "default_action": {
                "type":
                "web_url",
                "url":
                "https://ramadan-bazzar-web.web.app/shop/{0}/{1}".format(
                    shop.get("id"), is_zawgyi),
                "webview_height_ratio":
                "compact",
            },
            "buttons": [{
                "type":
                "web_url",
                "url":
                "https://ramadan-bazzar-web.web.app/shop/{0}/{1}".format(
                    shop.get("id"), is_zawgyi),
                "title":
                Rabbit.uni2zg("Menu ကြည့်မယ်")
                if is_zawgyi else "Menu ကြည့်မယ်",
            }, {
                "type":
                "postback",
                "title":
                Rabbit.uni2zg("ဆိုင်တွေထပ်ကြည့်မယ်")
                if is_zawgyi else "ဆိုင်တွေထပ်ကြည့်မယ်",
                "payload":
                self.NEXT_SHOPS
            }, {
                "type":
                "postback",
                "title":
                Rabbit.uni2zg("မကြည့်တော့ဘူး")
                if is_zawgyi else "မကြည့်တော့ဘူး",
                "payload":
                self.EXIT_SHOPS
            }]
        } for shop in shops]
Beispiel #12
0
    def convert(self):
        """ To handle the convert button press event """
        zg_input = self.root.ids.zawgyi_text
        uni_input = self.root.ids.unicode_text

        mode = "u" if uni_input.text != "" else "z"
        # If Unicode text input is entered then, convert it to Zawgyi

        if mode == "u":
            result = Rabbit.uni2zg(uni_input.text)
            zg_input.text = result
        elif mode == "z":
            result = Rabbit.zg2uni(zg_input.text)
            uni_input.text = result
Beispiel #13
0
    def test_api(self):
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'client-secret.json', scope)
        sh = gspread.authorize(credentials).open_by_key(
            '1SjJG2RzITf8qAmYDU9RFnWVaMP9912y8KfbuJe8th-c')
        work_sheets = sh.worksheets()

        assert len(work_sheets) == 14

        country_id = str(uuid.uuid4().hex)
        for ws_count, worksheet in enumerate(sh.worksheets()):
            # TODO write State By Country Here
            state_name = MockConfig().getStateName(worksheet.title)
            state_id = str(uuid.uuid4().hex)
            state = State(id=state_id,
                          object_id=state_id,
                          country_id=str(country_id),
                          name_mm_uni=str(state_name),
                          name_mm_zawgyi=Rabbit.uni2zg(state_name))
            cal_day_list = worksheet.col_values(1)
            hij_day_list = worksheet.col_values(2)
            sehri_time_list = worksheet.col_values(3)
            iftari_time_list = worksheet.col_values(4)

            for i, (cal_day, hij_day, seh_time, iftar_time) in enumerate(
                    zip(cal_day_list, hij_day_list, sehri_time_list,
                        iftari_time_list)):
                if i is not 0:
                    article_id = str(uuid.uuid4().hex)
                    article = Day(
                        id=article_id,
                        object_id=article_id,
                        country_id=str(country_id),
                        state_id=str(state.object_id),
                        day=i,
                        day_mm=str(MockConfig().get_mm_num(i)),
                        sehri_time=str(seh_time) + " am",
                        sehri_time_desc="Sehri",
                        sehri_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါချည်ချိန်"),
                        sehri_time_desc_mm_uni="ဝါချည်ချိန်",
                        iftari_time=str(iftar_time) + " pm",
                        dua_mm_uni=MockConfig().daily_dua(i)["dua_mm"],
                        dua_mm_zawgyi=Rabbit.uni2zg(
                            MockConfig().daily_dua(i)["dua_mm"]),
                        dua_ar=MockConfig().daily_dua(i)["dua_ar"],
                        dua_en=MockConfig().daily_dua(i)["dua_en"],
                        iftari_time_desc="Iftari",
                        iftari_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါဖြေချိန်"),
                        iftari_time_desc_mm_uni="ဝါဖြေချိန်")
	def __init__(self, srn_sz: (float, float), clock: pygame.time.Clock, screen: pygame.Surface):
		"""
		Initializes the World

		Args:
			srn_sz ( (float, float) ): Screen size
			clock (pygame.time.Clock): pygame Clock
			screen (pygame.Surface): pygame Screen
		"""

		self.running = True

		self._clock = clock
		self.screen = screen
		
		self.runtime = 0
		self.runtime_checkpoint = 0

		self.size = srn_sz
		self.rabbits = []
		self.wolves = []
		self.food = []

		for _ in range(20):
			self.rabbits.append(Rabbit(self, self._random_pos(), 2.5))

		for _ in range(6):
			self.wolves.append(Wolf(self, self._random_pos(), 3.0))

		for _ in range(80):
			self.food.append(Food(self, self._random_pos()))

		self._update_screen()
Beispiel #15
0
    def create_world(self):
        for i in range(self.num_hunters):
            x = randint(2, self.FIELD_LENGTH - 2)
            y = randint(2, self.FIELD_WIDTH - 2)
            hunter = Hunter(x, y, 5, self.field, 'h', 'r', 5)
            self.field.objects_array[x][y] = hunter
            self.field.array[x][y] = 'h'
            self.hunters.append(hunter)

        for i in range(self.num_rabbits):
            x = randint(2, self.FIELD_LENGTH - 2)
            y = randint(2, self.FIELD_WIDTH - 2)
            rabbit = Rabbit(x, y, 6, self.field, 'r', 'c', 5)
            self.field.objects_array[x][y] = rabbit
            self.field.array[x][y] = 'r'
            self.rabbits.append(rabbit)

        for i in range(self.num_carrots):
            x = randint(2, self.FIELD_LENGTH - 2)
            y = randint(2, self.FIELD_WIDTH - 2)
            carrot = Carrot(x, y, self.field)
            self.field.array[x][y] = 'c'
            self.field.objects_array[x][y] = carrot
            self.carrots.append(carrot)
        self.carrots_clone = self.carrots
        self.update()
 def __init__(self, sender_id, bot):
     self.sender_id = sender_id
     self.bot = bot
     self.MSG_INITIAL_GREETING = Rabbit.uni2zg(
         "အစ်စလာမို့ အာလိုင်းကွန်း (Assalamualaikum)" \
         "Ramadan Bazaar Myanmar မှကြိုဆိုပါတယ်ခင်ဗျာ။ ပထမဦးစွာ အောက်မှာမြင်ရတဲ့ Font လေးရွေးပေးပါအုံး။")
     self.ZAW_GYI_PAYLOAD = "ZAW_GYI_PAYLOAD"
     self.UNICODE_PAYLOAD = "UNICODE_PAYLOAD"
 def _after_shop_selection_exit(self, is_zawgyi):
     is_zawgyi = str2bool(is_zawgyi)
     return [{
         "content_type":
         "text",
         "title":
         Rabbit.uni2zg("ဆိုင်တွေကိုကြည့်မယ်")
         if is_zawgyi else "ဆိုင်တွေကိုကြည့်မယ်",
         "image_url":
         "https://raw.githubusercontent.com/r-phyan-kwee-tech/ramadan-bazaar-mm/master/icons/ic_fork_knife.png",
         "payload":
         self.BROWSE_SHOPS
     }, {
         "content_type": "text",
         "title": Rabbit.uni2zg("အနီးနားမှာရှာမယ်")
         if is_zawgyi else "အနီးနားမှာရှာမယ်",
         "image_url":
         "https://raw.githubusercontent.com/r-phyan-kwee-tech/ramadan-bazaar-mm/master/icons/ic_location.png",
         "payload": self.SELECT_LOCATION_PAYLOAD
     }, {
         "content_type":
         "text",
         "title":
         Rabbit.uni2zg("ကျွန်တော်တို့အကြောင်း")
         if is_zawgyi else "ကျွန်တော်တို့အကြောင်း",
         "image_url":
         "https://raw.githubusercontent.com/r-phyan-kwee-tech/ramadan-bazaar-mm/master/icons/ic_info.png",
         "payload":
         self.ABOUT_US_PAYLOAD
     }, {
         "content_type": "text",
         "title": Rabbit.uni2zg("ဖောင့်ပြန်ရွေးရန်")
         if is_zawgyi else "ဖောင့်ပြန်ရွေးရန်",
         "image_url":
         "https://raw.githubusercontent.com/winhtaikaung/mm-exchange-rate-check-bot/master/icon_image/ic_unicode.png",
         "payload": self.FONT_SELECTION_PAYLOAD
     }, {
         "content_type": "text",
         "title":
         Rabbit.uni2zg("အကူအညီယူမည်။") if is_zawgyi else "အကူအညီယူမည်။",
         "image_url":
         "https://raw.githubusercontent.com/r-phyan-kwee-tech/ramadan-bazaar-mm/master/icons/ic_bouy_help.png",
         "payload": self.HELP
     }]
Beispiel #18
0
    def test_mm_num_gen(self):
        all_day = db_session.query(
            Day).filter(Day.id!=None).all()

        for i,r_day in enumerate(all_day):
            print(i)
            print(r_day.day)
            r_day.sehri_time_desc="Sehri"
            r_day.sehri_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါချည်ချိန်")
            r_day.sehri_time_desc_mm_uni="ဝါချည်ချိန်"
            from seeds import daily_dua
            r_day.dua_mm_uni=Rabbit.zg2uni(str(daily_dua(r_day.day)["dua_mm"]))
            r_day.dua_mm_zawgyi=daily_dua(r_day.day)["dua_mm"]
            r_day.dua_ar=daily_dua(r_day.day)["dua_ar"]
            r_day.dua_en=daily_dua(r_day.day)["dua_en"]
            r_day.iftari_time_desc="Iftari"
            r_day.iftari_time_desc_mm_zawgyi=Rabbit.uni2zg("ဝါဖြေချိန်")
            r_day.iftari_time_desc_mm_uni="ဝါဖြေချိန်"
            db_session.commit()
        print(all_day)
Beispiel #19
0
 def __init__(self,
              queue_name,
              consuming_function: Callable = None,
              threads_num=100,
              max_retry_times=3):
     """
     :param queue_name:
     :param consuming_function: 处理消息的函数,函数有且只能有一个参数,参数表示消息。是为了简单,放弃策略和模板来强制参数。
     :param threads_num:
     :param max_retry_times:
     """
     self._queue_name = queue_name
     self.consuming_function = consuming_function
     self.threadpool = ThreadPoolExecutor(threads_num)
     self._max_retry_times = max_retry_times
     print(f'{self.__class__} 被实例化')
     self.rabbitmq_helper = Rabbit()
     channel = self.rabbitmq_helper.create_channel()
     channel.queue_declare(queue=self._queue_name, durable=True)
     channel.basic_qos(prefetch_count=threads_num)
     self.channel = channel
Beispiel #20
0
def create_fleet(ai_settings, screen, police, rabbits):
    """create a family of rabbits"""
    """create rabbit and compute the number of rabbits
    per line """
    rabbit = Rabbit(ai_settings, screen)
    number_rabbits_x = get_number_rabbits_x(ai_settings, rabbit.rect.width)
    number_rows = get_number_rows(ai_settings, police.rect.height,
                                  rabbit.rect.height)

    # create a line of rabbits
    for row_number in range(number_rows):
        for rabbit_number in range(number_rabbits_x):
            create_rabbit(ai_settings, screen, rabbits, rabbit_number,
                          row_number)
 def _font_selection_payload(self):
     return [{
         "content_type": "text",
         "title": Rabbit.uni2zg("မြန်မာစာ"),
         "image_url":
         "https://raw.githubusercontent.com/winhtaikaung/mm-exchange-rate-check-bot/master/icon_image/ic_zawgyi.png",
         "payload": self.ZAW_GYI_PAYLOAD
     }, {
         "content_type": "text",
         "title": "မြန်မာစာ",
         "image_url":
         "https://raw.githubusercontent.com/winhtaikaung/mm-exchange-rate-check-bot/master/icon_image/ic_unicode.png",
         "payload": self.UNICODE_PAYLOAD
     }]
Beispiel #22
0
    def __init__(self, srn_sz: (float, float), clock: pygame.time.Clock,
                 screen: pygame.Surface, allCells):
        """
		Initializes the World

		Args:
			srn_sz ( (float, float) ): Screen size
			clock (pygame.time.Clock): pygame Clock
			screen (pygame.Surface): pygame Screen
		"""

        self.running = True

        self._clock = clock
        self.screen = screen

        self.runtime = 0
        self.runtime_checkpoint = 0

        self.size = srn_sz
        self.rabbits = []
        self.foxes = []
        self.food = []
        self.landcells = []
        self.shorecells = []
        self.watercells = []
        self.cells = allCells
        self._classify_terrain()
        for _ in range(20):

            rand_pos = random.choice(self.landcells)
            self.rabbits.append(
                Rabbit(self, (rand_pos.x, rand_pos.y),
                       self._random_speed()))  #2.5

        for _ in range(12):
            rand_pos = random.choice(self.landcells)
            self.foxes.append(
                Fox(self, (rand_pos.x, rand_pos.y),
                    self._random_speed()))  #3 self._random_pos()

        for _ in range(80):
            rand_pos = random.choice(self.landcells)
            self.food.append(Food(
                self, (rand_pos.x, rand_pos.y)))  #self._random_pos()

        self._update_screen()
Beispiel #23
0
def worker(rabbit_cfg, function):
    f = FunctionWrapper(
        function['module_path'], 
        function['module_name'], 
        function['function_name']
    )
    r = Rabbit(
        function=f,
        exchange=function['exchange'],
        queue=function['queue'], 
        routing_key=function.get('routing_key'),
        host=rabbit_cfg.get('host'),
        port=rabbit_cfg.get('port'),
        userid=rabbit_cfg.get('userid'),
        password=rabbit_cfg.get('password'),
        durable=rabbit_cfg.get('durable', True)
    )
    r.connect()
    r.declare()
    r.consume()
Beispiel #24
0
    def __init__(self, animal_start, plant_start, height, width):
        self.population_log = {}
        for k in self.animals.keys():
            self.population_log[k] = []

        self.height = height
        self.width = width
        Animal.HEIGHT = height
        Animal.WIDTH = width
        self.animals_alive = 123
        for i in range(animal_start):
            self.animals[Species.Rabbit].append(
                Rabbit(random.uniform(50, self.width - 50),
                       random.uniform(50, self.height - 50)))

        for i in range(plant_start):
            self.plants[Species.Carrot].append(
                Carrot(random.uniform(50, self.width - 50),
                       random.uniform(50, self.height - 50)))

        for i in range(2):
            self.animals[Species.Fox].append(
                Fox(random.uniform(50, self.width - 50),
                    random.uniform(50, self.height - 50)))
Beispiel #25
0
	def keysetup(self, key):
		sparefinalkeyindex = 4
		sparefinalkey = bytearray(16)
		self.finalprng = key[0:16]

		rabbit = Rabbit()
		rabbit.keysetup(key)
		finalkeydata = rabbit.prng(4*6*4)

		for i in xrange(6):
			self.finalkey[i] = []
			for j in xrange(4):
				index = i*16 + j*4
				d = b_to_int(finalkeydata[index:index+4])

				while 0xFFFFFFFA < d:
					# UNTESTED
					if sparefinalkeyindex == 4:
						print "..."
						sparefinalkey = rabbit.prng(16)
						sparefinalkeyindex = 0
					k = bytearray(4)
					k[0] = sparefinalkey[4*sparefinalkeyindex]
					k[1] = 0
					k[2] = 0
					k[3] = 0
					d = b_to_int2(k)
					sparefinalkeyindex += 1

				self.finalkey[i].append(d)

		levelkeydata = rabbit.prng(8*28*4)
		for i in xrange(28):
			self.levelkey[i] = []
			for j in xrange(4):
				index = 8*(4*i + j)
				self.levelkey[i].append(b_to_int64(levelkeydata[index:index+8]))
Beispiel #26
0
 def new_rabbit(self, x, y):
     self.objects_array[x][y] = Rabbit(x,y, 7, self, 'r', 'c', 5)
     self.array[x][y] = 'r'
Beispiel #27
0
 def test_uni2zg(self):
     print("converting Unicode to Zawgyi")
     converted = Rabbit.uni2zg(u"မင်္ဂလာပါ")
     self.assertEqual(converted, u"မဂၤလာပါ")
Beispiel #28
0
 def test_zg2uni(self):
     print("converting Zawgyi to Unicode")
     converted = Rabbit.zg2uni(u"မဂၤလာပါ")
     self.assertEqual(converted, u"မင်္ဂလာပါ")
Beispiel #29
0
	def finalize(self, iv):
		right = [[] for i in xrange(4)]
		buffermask = self.bitcount >> 7
		counter = 0
		level = 0
		rightfilled = False

		print self.bitcount
		self.bitcount += 8 * self.bufferindex
		if self.bufferindex > 0:
			if self.bufferindex <= 8:
				while self.bufferindex < 8:
					self.buffer[self.bufferindex] = 0
					self.bufferindex += 1

				for i in xrange(4):
					right[i] = b_to_int(self.buffer[0:4])
			else:
				while self.bufferindex < 16:
					self.buffer[self.bufferindex] = 0
					self.bufferindex += 1

				bufpart0 = b_to_int(self.buffer[0:4])
				bufpart1 = b_to_int(self.buffer[4:8])
				bufpart2 = b_to_int(self.buffer[8:12])

				for i in xrange(4):
					lk = self.levelkey[0][i]
					t1 = (lk + bufpart0) & 0xFFFFFFFF
					t2 = ((lk >> 32) + bufpart1) & 0xFFFFFFFF
					right[i] = (t1 * t2) + bufpart2
					print hex(right[i])

			rightfilled = True


			# print i, ":", hex(y[0]), hex(y[1]), hex(y[2]), hex(y[3])

		if buffermask == 0 and not self.bufferindex:
			for i in xrange(4):
				right[i] = 0
		else:
			while not rightfilled:
				if buffermask & 1:
					for i in xrange(4):
						right[i] = self.treebuffer[level][counter+i]
					rightfilled = True
				level += 1
				buffermask >>= 1

			while buffermask:
				if buffermask & 1:
					for i in xrange(4):
						t1 = (self.levelkey[level+1][counter] & 0xFFFFFFFF) + (self.treebuffer[level][counter] & 0xFFFFFFFF) & 0xFFFFFFFF
						t2 = (self.levelkey[level+1][counter] & 0xFFFFFFFF00000000) + (self.treebuffer[level][counter] & 0xFFFFFFFF00000000) & 0xFFFFFFFF
						right[i] += t1 * t2
						counter += 1
						if counter >= 4:
							counter -= 4
							level += 1
				else:
					level += 1
				buffermask >>= 1


		mac = bytearray(16)
		for i in xrange(4):
			t  = self.finalkey[0][i] * (right[i] & 0x07FFFFFF)
			t += self.finalkey[1][i] * ((right[i] >> 27) & 0x07FFFFFF)
			t += self.finalkey[2][i] * ((right[i] >> 54) | ((0x0001FFFF & self.bitcount) << 10))
			t += self.finalkey[3][i] * ((self.bitcount >> 17) & 0x07FFFFFF)
			t += self.finalkey[4][i] * (self.bitcount >> 44)
			t += self.finalkey[5][i]

			low = t & 0xFFFFFFFF

			r = (low + (5 * (t >> 32))) & 0xFFFFFFFF

			if r < low or r > 0xFFFFFFFA:
				r -= 0xFFFFFFFB


			p = int_to_b(r & 0xFFFFFFFF)
			mac[4*i:4*i+4] = p

		r = Rabbit()
		r.keysetup(self.finalprng)
		r.ivsetup(iv)
		return r.encrypt(mac)
Beispiel #30
0
def main():


    open_canvas()
    global mainback
    mainback = Mainback()
    global start
    start = False

    while(start == False):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)

    #클래스 선언
    global hero
    hero = Hero()
    rabbit = Rabbit()
    rabbit_group = [Rabbit() for i in range(600)]
    land = Land()
    wood = Wood()
    global torch
    torch = Torch()
    global fire
    fire = Fire()
    eskimo = Eskimo()
    attack_fire = Attack_fire()
    attack_fire_group = [Attack_fire() for i in range(100)]
    background = BackGround()
    global ui
    ui = Ui()
    firewood = Firewood()
    firewood_group = [Firewood() for i in range(600)]

    #변수 선언
    rabbit_group_counter = 0
    rabbit_group_collision_counter = 0
    attack_group_counter = 0
    attack_group_update_counter = 0
    attack_group_collision_counter = 0
    rabbit_alive_counter = 0
    attack_group_alive_check = False
    attack_group_alive_counter = 0
    attack_group_limit = 20
    rabbit_group_draw_counter = 0
    firewood_num_counter = 0
    firewood_num_update_counter = 0
    firewood_collide_counter = 0
    rabbit_group_counter2 = 0
    rabbit_jump = False
    rabbit_num = 10
    firewood_num = 10
    rack_block = 0
    eskimo_counter = 0


    global running
    running = True



    while running:
        #핸들 이벤트
        handle_events()

        #업데이트
        hero.update()
        background.update()
        land.update()
        wood.update()
        fire.update()
        torch.update()
        eskimo.update()
        ui.update(hero.x, hero.y, hero.ability)
        for rabbit in rabbit_group: # 토끼 업데이트
            if(rabbit_group_counter == rabbit_num):
                rabbit_group_counter = 0
                break
            if(rabbit.alive):
                rabbit.update()
            rabbit_group_counter += 1

        # for rabbit in rabbit_group: # 토끼 업데이트
        #     if(rabbit_group_counter2 == 1):
        #         print("%d" % rabbit.x)
        #         break
        #     rabbit_group_counter2 += 1

        for attack_fire in attack_fire_group: # 공격불 업데이트
            if(attack_group_update_counter == hero.attack_num):
                attack_fire.init_direction()
                attack_fire.alive = True # 공격불이 활성화 됨
                attack_fire.init_fire()
                attack_group_update_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.update()
            attack_group_update_counter += 1

        for firewood in firewood_group: # 장작 업데이트
            if(firewood_num_update_counter == firewood_num):
                firewood_num_update_counter = 0
                break
            firewood.update()
            firewood_num_update_counter += 1

        #함수
        for rabbit in rabbit_group: #토끼와 히어로의 충돌체크
            if(rabbit_group_collision_counter == rabbit_num):
                rabbit_group_collision_counter = 0
                break
            if(collision(rabbit, hero)):
                rabbit.y += 50
                mainback.hero_die = True
                mainback.die_sound()
                running = False
            rabbit_group_collision_counter += 1

        for rabbit in rabbit_group: # 토끼와 공격불의 충돌체크
            if(rack_block == rabbit_num):
                rack_block = 0
                break
            for attack_fire in attack_fire_group:
                if(attack_group_collision_counter == hero.attack_num):
                    attack_group_collision_counter = 0
                    break
                if(collision(rabbit, attack_fire) and rabbit.alive and attack_fire.alive):
                    attack_fire.alive = False
                    rabbit.alive = False
                    rabbit.die = True
                    hero.kill += 1
                attack_fire.die = False
                attack_group_collision_counter += 1
            rack_block += 1

        for attack_fire in attack_fire_group:
            if(eskimo_counter == hero.attack_num):
                eskimo_counter = 0
                break
            if(collision(eskimo, attack_fire)):
                 attack_fire.alive = False
                 eskimo.x -= 10
                 eskimo.hp -= 1
                 if(eskimo.hp == 0):
                    mainback.eskimo_die = True
                    running = False
                    mainback.win_sound()
            attack_fire.die = False
            eskimo_counter += 1
        if(collision(wood, hero)): # 나무와 주인공 충돌체크
            fire.collide = True
            if(ui.firewood_num != 0):
                fire.life += ui.firewood_num*250
                ui.firewood_num = 0
        else:
            fire.collide = False


        if(collision(eskimo, hero)): # 주인공과 에스키모 충돌체크
            mainback.hero_die = True
            running = False
            mainback.die_sound()

        for firewood in firewood_group: # 장작과 주인공 충돌체크
            if(firewood_collide_counter == firewood_num):
                firewood_collide_counter = 0
                break
            if(collision(firewood, hero) and firewood.die == False):
                ui.firewood_num += 1
                firewood.die = True
            firewood_collide_counter += 1

        for rabbit in rabbit_group: # 토끼 출현!
            if(rabbit_alive_counter == rabbit_num):
                break
            if(rabbit.die == False):
                rabbit.alive = True
                rabbit_alive_counter += 1

        if(fire.die): # 불이 꺼지면 토끼들이 마구마구 몰려온다.
            rabbit_num = 500

        for attack_fire in attack_fire_group: # 불 스킬 존재 유무
            if(attack_fire.alive):
                attack_group_alive_counter = 0
                break
            attack_group_alive_counter += 1
            if(attack_group_alive_counter == hero.attack_num):
                hero.attack_num = 0


        for attack_fire in attack_fire_group: # 화면 밖을 벗어나면 불 스킬 사망 판정
            if(attack_fire.x >= 900 or attack_fire.x <= -100):
                attack_fire.alive = False
        print("stage = %d" % background.stage)
        #스테이지
        if(hero.kill == 10 and background.stage == 1):
            print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
            rabbit_num += 20
            hero.ability += 10
            firewood_num += 5
            background.stage = 2
        if(hero.kill == 30 and background.stage == 2):
            rabbit_num += 30
            firewood_num += 10
            hero.ability += 10
            background.stage = 3
            background.stage3_music()
        if(hero.kill == 60 and background.stage == 3):
            rabbit_num += 40
            firewood_num += 15
            hero.ability += 10
            background.stage = 4
        if(hero.kill == 80 and background.stage == 4):
            rabbit_num += 50
            firewood_num += 20
            hero.ability += 10
            background.stage = 5
            eskimo.alive = True
            background.stage5_music()
        if(background.stage == 5):
            rabbit_jump = True

        if(rabbit_jump):
             for rabbit in rabbit_group:
                 rabbit.y += 5

        # print("%d" % hero.attack_num)
        print("킬 수 : %d num : %d" % (hero.kill, rabbit_num))
        clear_canvas()


        #그리기
        background.draw()
        fire.draw()
        wood.draw()
        torch.draw()
        hero.draw()
        eskimo.draw()
        # eskimo.draw_bb()
        # hero.draw_bb()
        for rabbit in rabbit_group: # 적토끼 출력
            if(rabbit_group_draw_counter == rabbit_num):
                rabbit_group_draw_counter = 0
                break
            if(rabbit.alive):
                rabbit.draw()
            rabbit_group_draw_counter += 1
            # rabbit.draw_bb()
        for attack_fire in attack_fire_group: # 공격 불 출력
            if(attack_group_counter == hero.attack_num):
                attack_group_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.draw()
            # attack_fire.draw_bb()
            attack_group_counter += 1
        for firewood in firewood_group: # 장작 출력
            if(firewood_num_counter == firewood_num):
                firewood_num_counter = 0
                break
            firewood.draw()
            firewood_num_counter += 1
        land.draw()
        ui.draw()



        update_canvas()

        delay(0.06)

    while(mainback.hero_die or mainback.eskimo_die):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)



    close_canvas()
Beispiel #31
0
 def test(self):
     rabbit = Rabbit()
     rabbit.sendMessage()
     things = rabbit.relayMessage()
     things = things.decode("unicode_escape")
     self.assertFalse(things != "Hello World!")
Beispiel #32
0
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.lang import Builder
from kivy.config import Config

from rabbit import Rabbit
"""
Rabbit.uni2zg("မင်္ဂလာပါ")  # returns zg strings "မဂၤလာပါ"

Rabbit.zg2uni("မဂၤလာပါ")   # returns unicode strings "မင်္ဂလာပါ
"""

class UZConverter(App):
    def build(self):
        Config.set('graphics', 'width', '300')
        Config.set('graphics', 'height', '200')

        self.title = "Unicode to Zawgyi Converter"
        self.root = Builder.load_file("gui.kv")
        return self.root

    def convert(self):
        """ To handle the convert button press event """
        zg_input = self.root.ids.zawgyi_text
        uni_input = self.root.ids.unicode_text

        mode = "u" if uni_input.text != "" else "z"
        # If Unicode text input is entered then, convert it to Zawgyi

        if mode == "u":
Beispiel #33
0
 def __init__(self):
     self.__rabbit = Rabbit(host="localhost")
Beispiel #34
0
class RabbitmqConsumer(object):
    def __init__(self,
                 queue_name,
                 consuming_function: Callable = None,
                 threads_num=100,
                 max_retry_times=3):
        """
        :param queue_name:
        :param consuming_function: 处理消息的函数,函数有且只能有一个参数,参数表示消息。是为了简单,放弃策略和模板来强制参数。
        :param threads_num:
        :param max_retry_times:
        """
        self._queue_name = queue_name
        self.consuming_function = consuming_function
        self.threadpool = ThreadPoolExecutor(threads_num)
        self._max_retry_times = max_retry_times
        print(f'{self.__class__} 被实例化')
        self.rabbitmq_helper = Rabbit()
        channel = self.rabbitmq_helper.create_channel()
        channel.queue_declare(queue=self._queue_name, durable=True)
        channel.basic_qos(prefetch_count=threads_num)
        self.channel = channel

    def start_consuming_message(self):
        def callback(ch, method, properties, body):
            msg = body.decode()
            print(f'从rabbitmq取出的消息是:  {msg}')
            # ch.basic_ack(delivery_tag=method.delivery_tag)
            self.threadpool.submit(self.__consuming_function, ch, method,
                                   properties, msg)

        self.channel.basic_consume(
            on_message_callback=callback,
            queue=self._queue_name,
        )
        self.channel.start_consuming()

    @staticmethod
    def ack_message(channelx, delivery_tagx):
        """Note that `channel` must be the same pika channel instance via which
        the message being ACKed was retrieved (AMQP protocol constraint).
        """
        if channelx.is_open:
            channelx.basic_ack(delivery_tagx)
        else:
            # Channel is already closed, so we can't ACK this message;
            # log and/or do something that makes sense for your app in this case.
            pass

    def __consuming_function(self,
                             ch,
                             method,
                             properties,
                             msg,
                             current_retry_times=0):
        if current_retry_times < self._max_retry_times:
            # noinspection PyBroadException
            try:
                self.consuming_function(msg)
                # ch.basic_ack(delivery_tag=method.delivery_tag)
                self.rabbitmq_helper.conn.add_callback_threadsafe(
                    functools.partial(self.ack_message, ch,
                                      method.delivery_tag))
            except Exception as e:
                print(
                    f'函数 {self.consuming_function}  第{current_retry_times+1}次发生错误,\n 原因是{e}'
                )
                self.__consuming_function(ch, method, properties, msg,
                                          current_retry_times + 1)
        else:
            print(f'达到最大重试次数 {self._max_retry_times} 后,仍然失败')
            # ch.basic_ack(delivery_tag=method.delivery_tag)
            self.rabbitmq_helper.conn.add_callback_threadsafe(
                functools.partial(self.ack_message, ch, method.delivery_tag))
Beispiel #35
0
def signin():
    Mongo.save_new_user("created by duohong")
    Rabbit.send_new_user("created by duohong")
    return "Created a user"
Beispiel #36
0
                    help="User for accessing RabbitMQ")
PARSER.add_argument("-p",
                    "--password",
                    required=False,
                    default=None,
                    type=str,
                    help="Password for accessing RabbitMQ")
PARSER.add_argument("-d",
                    "--debug",
                    action='store_true',
                    help="Put Flask into debug mode")
ARGS = PARSER.parse_args()

APP = Flask(__name__, static_url_path='/static')

RABBIT = Rabbit(host=ARGS.host, user=ARGS.user, password=ARGS.password)


@APP.route('/')
def index():
    return render_template('index.html')


@APP.route("/post", methods=["POST"])
def post():
    exchange = ""
    if request.values.get('exchange') is not None:
        exchange = request.values.get('exchange').strip()
    topic = request.values.get('topic').strip()
    message = request.values.get('message').strip()
    return json.dumps(
            parser.print_help()
            sys.exit(1)

    ip = get_ip(options.ip)
    if not ip:
        message = "Invalid ip source input: %s" % (options.ip)
        print message
        logger.error(message)
        sys.exit(1)
    host = options.host
    if not host:
        message = "Invalid host: %s" % (options.host)
        print message
        logger.error(message)
        sys.exit(1)
    jid = options.jid
    if not jid:
        message = "Invalid job id: %s" % (options.jid)
        print message
        logger.error(message)
        sys.exit(1)
    """
    Process monitor source and return main
    """
    time.sleep(300)
    """
    clear supervisord job config
    """
    rb = Rabbit(SYSTEM["LOG_QUEUE"])
    rb.push("100")
Beispiel #38
0
class Rabbit_receive(object):
    def __init__(self):
        self.__rabbit = Rabbit(host="localhost")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.__rabbit.close()

    def simple_mode(self, callback=None, queue_name="simple", durable=False):
        self.__rabbit.declare_queue(queue_name=queue_name, durable=durable)
        receive_callback = callback if callback is not None else self.on_simple_mode_callback
        self.__rabbit.consume(receive_callback,
                              queue_name=queue_name,
                              no_ack=True)
        self.__rabbit.start()

    def on_simple_mode_callback(self, ch, method, properties, body):
        print(" [x] Received %r" % body)

    def fanout_mode(self, callback=None, exchange_name="logs"):
        self.__rabbit.declare_exchange(exchange_name=exchange_name)
        result = self.__rabbit.declare_queue_exclusive()
        queue_name = result.method.queue
        self.__rabbit.bind(exchange=exchange_name, queue_name=queue_name)
        receive_callback = callback if callback is not None else self.on_simple_mode_callback
        self.__rabbit.consume(receive_callback,
                              queue_name=queue_name,
                              no_ack=True)
        self.__rabbit.start()

    def direct_mode(self,
                    callback=None,
                    exchange_name="direct_logs",
                    binding_keys=[]):
        self.__rabbit.declare_exchange(exchange_name=exchange_name,
                                       exchange_type="direct")
        result = self.__rabbit.declare_queue_exclusive()
        queue_name = result.method.queue
        for binding_key in binding_keys:
            self.__rabbit.bind(exchange=exchange_name,
                               queue_name=queue_name,
                               routing_key=binding_key)
        receive_callback = callback if callback is not None else self.on_simple_mode_callback
        self.__rabbit.consume(receive_callback,
                              queue_name=queue_name,
                              no_ack=True)
        self.__rabbit.start()

    def rpc_mode(self, callback=None, queue_name="rpc_queue"):
        self.__rabbit.declare_queue(queue_name=queue_name)
        self.__rabbit.qos()
        receive_callback = callback if callback is not None else self.on_rpc_mode_callback
        self.__rabbit.consume(receive_callback, queue_name=queue_name)
        self.__rabbit.start()

    def on_rpc_mode_callback(self, ch, method, props, body):
        print(" [.] received one msg (%s)" % body)
        response = body
        ch.basic_publish(exchange='',
                         routing_key=props.reply_to,
                         properties=pika.BasicProperties(
                             correlation_id=props.correlation_id),
                         body=str(response))
        ch.basic_ack(delivery_tag=method.delivery_tag)
Beispiel #39
0
 def test_rabbit(self):
     rabbit = Rabbit()
     rabbit.sendMessage()
     things = rabbit.relayMessage()
     self.failIf(things != "Hello World!")