Пример #1
0
def test_read_from_file():
    name = '/home/travis/build/jdafer98/AngieSF/angierp/ehttp'

    r = Repeater()
    q = r.read_from_file(name)

    assert q.find('HTTP') != -1
Пример #2
0
def angierp(filename, count, url, port, https):

    #name = 'ehttps'
    r = Repeater()
    for ii in range(count):
        if filename != None and url != None:
            try:
                content = r.read_from_file(filename)
            except:
                print("No se ha podido abrir el archivo: " + filename)
                exit(1)

            b = False if https == 0 else True

            if not b:
                print(
                    r.send_http(content, url,
                                80 if port == None else int(port)))
            else:
                print(
                    r.send_https(content, url,
                                 443 if port == None else int(port)))

        else:
            print(
                "Error: Los campos filename y url son necesarios. --help para más información"
            )
Пример #3
0
def test_se_detectan_interfaces():
    test_pass = False
    r = Repeater()
    e = "abc"

    r.set_endl(e)

    test_pass = e == r.ENDL
    assert test_pass
Пример #4
0
def test_send_http():
    name = '/home/travis/build/jdafer98/AngieSF/angierp/ehttp'

    test_pass = False
    r = Repeater()
    q = r.read_from_file(name)

    qq = r.send_http(q, 'info.cern.ch', 80)

    assert qq.find('200') != -1
Пример #5
0
def test_send_https():
    name = '/home/travis/build/jdafer98/AngieSF/angierp/ehttps'

    test_pass = False
    r = Repeater()
    q = r.read_from_file(name)

    qq = r.send_https(q, 'www.youtube.com', 443)

    assert qq.find('200') != -1
Пример #6
0
def test_json_batch():
    repeater = Repeater('http://nang.kicks-ass.net:7777', 'josh')
    print repeater.batch([('get_players', {}), ('get_banned', {"player_type": "player"})])
    repeater = Repeater('http://nang.kicks-ass.net:7777', 'josh')
    print repeater.batch([('get_players', {}), ('get_banned', {"player_type": "player"})])
    repeater = Repeater('http://nang.kicks-ass.net:7777', 'josh')
    print repeater.batch([('get_players', {}), ('get_banned', {"player_type": "player"})])
Пример #7
0
class TorrentInfoGUI(xbmcgui.WindowXMLDialog):
    def __init__(self, strXMLname, strFallbackPath, strDefaultName, bforeFallback=0):
        self.transmission = None
        self.torrent_id = None
        self.list = {}
        self.repeater = Repeater(1.0, self.updateTorrent)
    def setTorrent(self, transmission, t_id):
        self.transmission = transmission
        self.torrent_id = t_id
        self.repeater.start()
    def updateTorrent(self):
        pbar = self.getControl(219)
        list = self.getControl(220)
        labelName = self.getControl(1)
        labelStatus = self.getControl(2)
        torrent = self.transmission.info()[self.torrent_id]
        files = self.transmission.get_files(self.torrent_id)[self.torrent_id]

        statusline = "[%(status)s] %(down)s down (%(pct).2f%%), %(up)s up (Ratio: %(ratio).2f)" % \
            {'down': Bytes.format(torrent.downloadedEver), 'pct': torrent.progress, \
            'up': Bytes.format(torrent.uploadedEver), 'ratio': torrent.ratio, \
            'status': torrent.status}
        if torrent.status is 'downloading':
            statusline += " ETA: %(eta)s" % \
                    {'eta': torrent.eta}

        labelName.setLabel(torrent.name)
        labelStatus.setLabel(statusline)
        pbar.setPercent(torrent.progress)

        for i, file in files.iteritems():
            if i not in self.list:
                # Create a new list item
                l = xbmcgui.ListItem(label=file['name'])
                list.addItem(l)
                self.list[i] = l
            else:
                # Update existing list item
                l = self.list[i]
            l.setProperty('Progress', '[%3d%%]' % (file['completed'] * 100 / file['size']))
    def onInit(self):
        self.updateTorrent()
    def close(self):
        self.repeater.stop()
        super(TorrentInfoGUI, self).close()
    def onAction(self, action):
        if (action.getButtonCode() in CANCEL_DIALOG) or (action.getId() == KEY_MENU_ID):
            self.close()
            pass
    def onClick(self, controlID):
        pass
    def onFocus(self, controlID):
        pass
Пример #8
0
    def __init__(self):
        self.repeater = Repeater()
        self.debug_mode = True

        self.btns = {
            1: 'sw6',
            2: 'sw7',
            3: 'sw8',
            4: 'sw2',
            5: 'sw3',
            6: 'sw4'
        }
        self.rbtns = {v: k for k, v in self.btns.items()}
        self.leds = {
            1: 'ds3',
            2: 'ds6',
            3: 'ds9',
            4: 'ds1',
            5: 'ds4',
            6: 'ds7',
            7: 'ds2',
            8: 'ds5',
            9: 'ds8'
        }

        self.state = Game.IDLE

        self.repeater.register_handler('sw5', self.start_handler)
        self.repeater.register_handler('sw1', self.reset_handler)

        for btn in self.rbtns:
            self.repeater.register_handler(btn, self.btn_handler)

        self.num_players = 0
        self.curr_player = 0
        self.players = []
        self.scores = []

        self.len = 0
        self.sequence = []
        self.input_pos = 0

        self.timeout_event = None
        self.btn_events = {}

        self._start_time = time.time()

        self.blinker = None
        self.runner = None
Пример #9
0
 def test_Should_ReturnStaticValue_When_CreatedWithNonCallable(self):
     value = 'hello'
     repeater = Repeater(value)
     result = []
     result.append(next(repeater))
     result.append(next(repeater))
     self.assertEqual([value, value], result)
Пример #10
0
 def test_Should_ReturnResultFromCall_When_CreatedWithCallable(self):
     func = mock.Mock(spec=[])
     func.side_effect = [1, 2, 3]
     repeater = Repeater(func)
     result = []
     result.append(next(repeater))
     result.append(next(repeater))
     self.assertEqual([1, 2], result)
Пример #11
0
 def test_Should_Stop_When_FunctionRaisesStopIteration(self):
     func = mock.Mock(spec=[])
     func.side_effect = [1, 2, StopIteration]
     repeater = Repeater(func)
     result = []
     for x in repeater:
         result.append(x)
     self.assertEqual([1, 2], result)
Пример #12
0
 def test_Should_PropagateExceptionFromFunction_When_FunctionRaisesException(self):
     func = mock.Mock(spec=[])
     func.side_effect = [1, 2, TestException]
     repeater = Repeater(func)
     next(repeater)
     next(repeater)
     with self.assertRaises(TestException):
         next(repeater)
Пример #13
0
def check_events(screen, game_settings, squares, plants, bullets, icons):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if game_settings.game_active:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                for square in squares:
                    if square.plant_here == False:
                        if square.rect.collidepoint(mouse_x, mouse_y):
                            # print "Square: ",square.square_number;
                            if (game_settings.chosen_plant == 1):
                                sunflower = Sunflower(screen, square)
                                if game_settings.total_sun >= sunflower.sun_cost:
                                    plants.add(sunflower)
                                    square.plant_here = True
                                    game_settings.total_sun -= sunflower.sun_cost
                            elif (game_settings.chosen_plant == 2):
                                peashooter = Peashooter(screen, square)
                                if game_settings.total_sun >= peashooter.sun_cost:
                                    plants.add(peashooter)
                                    square.plant_here = True
                                    game_settings.total_sun -= peashooter.sun_cost
                            elif (game_settings.chosen_plant == 3):
                                snowpea = Snowpea(screen, square)
                                if game_settings.total_sun >= snowpea.sun_cost:
                                    plants.add(snowpea)
                                    square.plant_here = True
                                    game_settings.total_sun -= snowpea.sun_cost
                            elif (game_settings.chosen_plant == 4):
                                repeater = Repeater(screen, square)
                                if game_settings.total_sun >= repeater.sun_cost:
                                    plants.add(repeater)
                                    square.plant_here = True
                                    game_settings.total_sun -= repeater.sun_cost
                            elif (game_settings.chosen_plant == 5):
                                gatling = Gatling(screen, square)
                                if game_settings.total_sun >= gatling.sun_cost:
                                    plants.add(gatling)
                                    square.plant_here = True
                                    game_settings.total_sun -= gatling.sun_cost
                            elif (game_settings.chosen_plant == 6):
                                wallnut = Wallnut(screen, square)
                                if game_settings.total_sun >= wallnut.sun_cost:
                                    plants.add(wallnut)
                                    square.plant_here = True
                                    game_settings.total_sun -= wallnut.sun_cost
                    for icon in icons:
                        if icon.rect.collidepoint(mouse_x, mouse_y):
                            game_settings.chosen_plant = icon.slot
                # print mouse_x;
                # print mouse_y;
            elif event.type == pygame.MOUSEMOTION:
                # print event.pos;
                for square in squares:
                    if square.rect.collidepoint(event.pos):
                        game_settings.highlighted_square = square
Пример #14
0
    def __init__(self):
        self.feeds = {}
        self.dir = os.path.join(
            os.getenv("LOCALAPPDATA"),
            "myFeedReader/feeds") if not DEBUG else os.path.join("./feeds")
        self.sched = scheduler(time.time, time.sleep)
        self.repeater = Repeater(self.sched)
        self.lc = LiveConsole()
        self.setup_workspace()

        self.repeater.add(self.force_update, 10 * 60, -1, True, 1, None)

        t = Thread(target=(self.repeater.start), daemon=True)
        t.start()

        for k, v in FeedManager.comands.items():
            self.lc.new_command(k, v, self)

        self.lc.start()
Пример #15
0
 def add_due_task(self,
                  description,
                  due_dates,
                  days_delta=0,
                  exceptions=[],
                  enddate=None):
     self.due_tasks.append(DueTask(description,
                            due_dates,
                            Repeater(days_delta,
                                     exceptions,
                                     enddate) if days_delta else None,
                           completed = []))
     self.due_tasks.sort(key=lambda task: task.due_dates[0])
     self.dump()
Пример #16
0
 def add_event(self,
               description,
               starting_dates,
               duration=timedelta(hours=1),
               location=None,
               days_delta=0,
               exceptions=[],
               enddate=None):
     self.events.append(Event(description,
                              starting_dates,
                              duration,
                              location,
                              Repeater(days_delta,
                                       exceptions,
                                       enddate) if days_delta else None))
     self.events.sort(key=lambda event: (event.starting_dates[0], event.duration))
     self.dump()
Пример #17
0
    def onInit(self):
        p = xbmcgui.DialogProgress()
        p.create(_(0), _(1)) # 'Transmission', 'Connecting to Transmission'
        params = {
            'address': __settings__.getSetting('rpc_host'),
            'port': __settings__.getSetting('rpc_port'),
            'user': __settings__.getSetting('rpc_user'),
            'password': __settings__.getSetting('rpc_password')
        }
        import transmissionrpc
        try:
            self.transmission = transmissionrpc.Client(**params)
        except:
            p.close()
            self.close()
            d = xbmcgui.Dialog()
            (type, e, traceback) = sys.exc_info()

            message = _(9000) # Unexpected error
            if type is transmissionrpc.TransmissionError:
                if e.original:
                    if e.original.code is 401:
                        message = _(9002) # Invalid auth
                    else:
                        message = _(9001) # Unable to connect
                if d.yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            elif type is ValueError:
                # In python 2.4, urllib2.HTTPDigestAuthHandler will barf up a lung
                # if auth fails and the server wants non-digest authentication
                message = _(9002) # Invalid auth
                if d.yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            else:
                message = _(9000) # Unexpected error
                d.ok(_(2), message)

            return False
        p.close()
        self.updateTorrents()
        self.repeater = Repeater(1.0, self.updateTorrents)
        self.repeater.start()
Пример #18
0
 def decode_repeater(repeater):
     return Repeater(
         repeater['days_delta'],
         list(map(decode_date, repeater['exceptions'])),
         decode_date(repeater['end_date'])
         if repeater['end_date'] else None)
Пример #19
0
 def send_to_repeater(self):
     request = self.history[self.history_list.curselection()[0]].request
     Repeater(self.window, request)
     with self.lock:
         self.addon.repeating = request.url
Пример #20
0
class FeedManager:

    comands = {
        "add":
        lambda self, link, name: self.add(link, name),
        "edit":
        lambda self, name, newlink: self.edit(name, newlink),
        # "edit": lambda self, name, newname: self.edit(name, newname),
        "del":
        lambda self, name: self.delete(name),
        "list":
        lambda self: self.listAll(),
        "open":
        lambda self, name: self.openAll() if name is None else self.open(name),
        "update":
        lambda self, name=None: self.update(name),
    }

    def __init__(self):
        self.feeds = {}
        self.dir = os.path.join(
            os.getenv("LOCALAPPDATA"),
            "myFeedReader/feeds") if not DEBUG else os.path.join("./feeds")
        self.sched = scheduler(time.time, time.sleep)
        self.repeater = Repeater(self.sched)
        self.lc = LiveConsole()
        self.setup_workspace()

        self.repeater.add(self.force_update, 10 * 60, -1, True, 1, None)

        t = Thread(target=(self.repeater.start), daemon=True)
        t.start()

        for k, v in FeedManager.comands.items():
            self.lc.new_command(k, v, self)

        self.lc.start()

    def setup_workspace(self):
        if not os.path.exists(self.dir):
            os.makedirs(self.dir)

        if not os.path.exists(os.path.join(
                self.dir, XSLT_PATH)) or XSLT_CONTENT != open(
                    os.path.join(self.dir, XSLT_PATH), "r").read():
            with open(os.path.join(self.dir, XSLT_PATH), "w") as f:
                f.write(XSLT_CONTENT)
        if not os.path.exists(os.path.join(
                self.dir, CSS_PATH)) or CSS_CONTENT != open(
                    os.path.join(self.dir, CSS_PATH), "r").read():
            with open(os.path.join(self.dir, CSS_PATH), "w") as f:
                f.write(CSS_CONTENT)

        for dirname in os.listdir(self.dir):
            if os.path.isdir(os.path.join(self.dir, dirname)):
                self.feeds[dirname] = Feed.from_shelve(
                    os.path.join(self.dir, dirname, "data.bin"),
                    self.lc.live_print)

    def add(self, link, name):
        return self.add_new_feed(link, name)

    def edit(self, name, newlink):
        return self.edit_feed_link(name, newlink)

    def delete(self, name):
        self.lc.live_print(
            f"Are you sure you want to delete {name}? This action cannot be undone (Y/n): ",
            nl=False)
        r = input("")
        if r == "Y":
            if self.delete_feed(name):
                self.lc.live_print(f"Feed {name} successfully removed.")
                return True
            else:
                self.lc.live_print(
                    f"Error while deleting feed {name}. Aborted.")
                return False
        self.lc.live_print("Action canceled")
        return False

    def listAll(self):
        feeds = self.get_all_feeds()
        for feed, link in feeds.items():
            self.lc.live_print(f"{feed}\t-> {link}")
        if (len(feeds.keys()) == 0):
            self.lc.live_print("No feeds watched at the moment.")

    def openAll(self):
        # TODO: Implement
        pass

    def open(self, name):
        webbrowser.open(f"http://127.0.0.1:8080/{name}/myFeed.xml")

    def updateAll(self):
        return self.force_update(None)

    def update(self, name):
        return self.force_update(name)

    def add_new_feed(self, link, name):
        if link:
            if name:
                new_feed = Feed(link, name, self.dir, self.lc.live_print)
                self.feeds[name] = new_feed
                self.force_update(new_feed.name)
                return True
        return False

    def edit_feed_link(self, name, newlink):
        if name in self.feeds.keys():
            feed = self.feeds[name]
            feed.link = newlink
            self.force_update(name)
            return True
        return False

    def delete_feed(self, name):
        if name in self.feeds.keys():
            try:
                rmtree(os.path.join(self.dir, name))
            except Exception:
                pass
            del self.feeds[name]
            return True
        return False

    def get_all_feeds(self):
        return dict(
            zip(map(lambda f: f.name, self.feeds.values()),
                map(lambda f: f.link, self.feeds.values())))

    def force_update(self, feedname=None):
        to_delete = []
        for k, v in self.feeds.items():
            if feedname is None or k == feedname:
                try:
                    v.update()
                except FileNotFoundError:
                    self.lc.live_print(
                        f"Error during update on feed {k}. Proceding with deletion."
                    )
                    to_delete.append(k)

        for error_feed in to_delete:
            self.delete_feed(error_feed)
Пример #21
0
class TransmissionGUI(xbmcgui.WindowXMLDialog):
    def __init__(self, strXMLname, strFallbackPath, strDefaultName, bforeFallback=0):
        self.list = {}
        self.torrents = {}
        self.repeater = None
    def onInit(self):
        p = xbmcgui.DialogProgress()
        p.create(_(0), _(1)) # 'Transmission', 'Connecting to Transmission'
        params = {
            'address': __settings__.getSetting('rpc_host'),
            'port': __settings__.getSetting('rpc_port'),
            'user': __settings__.getSetting('rpc_user'),
            'password': __settings__.getSetting('rpc_password')
        }
        import transmissionrpc
        try:
            self.transmission = transmissionrpc.Client(**params)
        except:
            p.close()
            self.close()
            d = xbmcgui.Dialog()
            (type, e, traceback) = sys.exc_info()

            message = _(9000) # Unexpected error
            if type is transmissionrpc.TransmissionError:
                if e.original:
                    if e.original.code is 401:
                        message = _(9002) # Invalid auth
                    else:
                        message = _(9001) # Unable to connect
                if d.yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            elif type is ValueError:
                # In python 2.4, urllib2.HTTPDigestAuthHandler will barf up a lung
                # if auth fails and the server wants non-digest authentication
                message = _(9002) # Invalid auth
                if d.yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            else:
                message = _(9000) # Unexpected error
                d.ok(_(2), message)

            return False
        p.close()
        self.updateTorrents()
        self.repeater = Repeater(1.0, self.updateTorrents)
        self.repeater.start()
    def updateTorrents(self):
        list = self.getControl(20)
        torrents = self.transmission.info()
        for i, torrent in torrents.iteritems():
            statusline = "[%(status)s] %(down)s down (%(pct).2f%%), %(up)s up (Ratio: %(ratio).2f)" % \
                {'down': Bytes.format(torrent.downloadedEver), 'pct': torrent.progress, \
                'up': Bytes.format(torrent.uploadedEver), 'ratio': torrent.ratio, \
                'status': torrent.status}
            if torrent.status is 'downloading':
                statusline += " ETA: %(eta)s" % \
                    {'eta': torrent.eta}
            if i not in self.list:
                # Create a new list item
                l = xbmcgui.ListItem(label=torrent.name, label2=statusline)
                list.addItem(l)
                self.list[i] = l
            else:
                # Update existing list item
                l = self.list[i]
            self.torrents = torrents
            l.setLabel(torrent.name)
            l.setLabel2(statusline)
            l.setProperty('TorrentID', str(i))
            l.setProperty('TorrentProgress', "%.2ff" % torrent.progress)
            l.setInfo('torrent', torrent.fields)
            l.setInfo('video', {'episode': int(torrent.progress)})

        removed = [id for id in self.list.keys() if id not in torrents.keys()]
        if len(removed) > 0:
            # Clear torrents from the list that have been removed
            for id in removed:
                del self.list[id]
            list.reset()
            for id, item in self.list.iteritems():
                list.addItem(item)

    def onClick(self, controlID):
        list = self.getControl(20)
        if (controlID == 11):
            # Add torrent
            d = xbmcgui.Dialog()
            f = d.browse(1, _(0), 'files', '.torrent')
            self.transmission.add_url(f)
        if (controlID == 12):
            # Remove selected torrent
            item = list.getSelectedItem()
            if item and xbmcgui.Dialog().yesno(_(0), 'Remove \'%s\'?' % self.torrents[int(item.getProperty('TorrentID'))].name):
                remove_data = xbmcgui.Dialog().yesno(_(0), 'Remove data as well?')
                self.transmission.remove(int(item.getProperty('TorrentID')), remove_data)
        if (controlID == 13):
            # Stop selected torrent
            item = list.getSelectedItem()
            if item:
                self.transmission.stop(int(item.getProperty('TorrentID')))
        if (controlID == 14):
            # Start selected torrent
            item = list.getSelectedItem()
            if item:
                t = int(item.getProperty('TorrentID'))
                self.transmission.start(int(item.getProperty('TorrentID')))
        if (controlID == 15):
            # Stop all torrents
            self.transmission.stop(self.torrents.keys())
        if (controlID == 16):
            # Start all torrents
            self.transmission.start(self.torrents.keys())
        if (controlID == 17):
            # Exit button
            self.close()
        if (controlID == 20):
            # A torrent was chosen, show details
            item = list.getSelectedItem()
            w = TorrentInfoGUI("script-Transmission-details.xml",os.getcwd() ,"Default")
            w.setTorrent(self.transmission, int(item.getProperty('TorrentID')))
            w.doModal()
            del w
    def onFocus(self, controlID):
        pass

    def onAction( self, action ):
        if ( action.getButtonCode() in CANCEL_DIALOG ):
            self.close()
    def close(self):
        if self.repeater:
            self.repeater.stop()
        super(TransmissionGUI, self).close()
Пример #22
0
 def __call__(self, source):
     return ConstructedLexer(self, Repeater(source))
Пример #23
0
# * Latitude
# * Longitude
#
# The first line of the file is a header and should be discarded.
# The fields are seperated by commas and quoted with double quotes.

f = urlopen(CSV_URL)

count = 0

data = csv.reader(f, delimiter=',', quotechar='"')
for row in data:
    count += 1
    if count == 1:
        continue
    repeater = Repeater(row[0])
    repeater.tx = float(row[3])
    repeater.rx = float(row[4])
    if row[10] != '':
        repeater.ctcss = float(row[10])
    if row[5] == "AV":
        repeater.mode = "FM"
    if row[5] == "DSTAR":
        repeater.mode = "DSTAR"
    if row[5] == "DMR":
        repeater.mode = "DMR"
    if row[5] == "DUALMODE":
        repeater.mode = "FM"
    repeater.locator = row[6]
    repeater.town = row[7]
    repeater.keeper = row[11]
Пример #24
0
        for line in repeater_data.split('\n'):
            unique_repeaters.add(line)

    return '\n'.join(unique_repeaters)

# Assuming these four locations will result in a complete set
data = assemble_repeater_data(["JO41AD", "JO53BJ", "JO62FD", "JN59EH"])

# Clean it up a bit
data = data.replace('\r', '')
data = data.replace('°', ' ')

for row in csv.reader(data.split('\n'), delimiter=';'):
    if len(row) != 9:
        continue
    repeater = Repeater(row[0])
    try:
        repeater.tx = float(row[1].replace(',', '.'))
    except ValueError:
        # Some data is just wrong or malformatted
        pass
    if (row[2] != '') and (row[2] != 'Beacon'):
        try:
            repeater.rx = float(row[2].replace(',', '.'))
        except ValueError:
            pass
    if row[8] == 'DMR':  # Unfortunately, most will be missing this
        repeater.mode = row[8]
    if row[7] != '':
        repeater.ctcss = float(row[7].replace(',', '.'))
        repeater.mode = "FM"
Пример #25
0
 def test_Should_ReturnInstance_When_Created(self):
     repeater = Repeater('hello')
     self.assertIsIterable(repeater)
Пример #26
0
from flask import Flask, request, render_template, jsonify
from repeater import Repeater
import time
from helpers import get_data_url, get_img_arr, get_np_arr

# Get instance of Repeater which can fetch and judge matches
repeater = Repeater()

# Support for gomix's 'front-end' and 'back-end' UI.
app = Flask(__name__, static_folder='public', template_folder='views')


@app.route('/')
def homepage():
    '''Displays the main page.'''
    return render_template('index.html')


@app.route('/actions', methods=['GET'])
def actions():
    '''API for getting suggested actions'''
    start_time = time.time()

    # The image sections before the mark at sizes appropriate to CNN layer
    befores = request.args.getlist('befores[]')
    # The mark made
    mark = request.args.get('mark')
    # The image sections after the mark at sizes appropriate to CNN layer
    afters = request.args.getlist('afters[]')
    # The current state of each AI canvas
    imgs = request.args.getlist('imgs[]')
Пример #27
0
def test_json():
    repeater = Repeater('http://nang.kicks-ass.net:7777', 'josh')
    print repeater.get('get_banned', {})
Пример #28
0
class TransmissionGUI(xbmcgui.WindowXMLDialog):
    def __init__(self, strXMLname, strFallbackPath, strDefaultName, bforeFallback=0):
        self.list = {}
        self.torrents = {}
        self.repeater = None
    def onInit(self):
        p = xbmcgui.DialogProgress()
        p.create(_(0), _(1)) # 'Transmission', 'Connecting to Transmission'
        params = {
            'address': __settings__.getSetting('rpc_host'),
            'port': __settings__.getSetting('rpc_port'),
            'user': __settings__.getSetting('rpc_user'),
            'password': __settings__.getSetting('rpc_password')
        }
        import transmissionrpc
        try:
            self.transmission = transmissionrpc.Client(**params)
        except:
            p.close()
            self.close()
            (type, e, traceback) = sys.exc_info()

            message = _(9000) # Unexpected error
            if type is transmissionrpc.TransmissionError:
                if e.original:
                    if e.original.code is 401:
                        message = _(9002) # Invalid auth
                    else:
                        message = _(9001) # Unable to connect
                if xbmcgui.Dialog().yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            elif type is ValueError:
                # In python 2.4, urllib2.HTTPDigestAuthHandler will barf up a lung
                # if auth fails and the server wants non-digest authentication
                message = _(9002) # Invalid auth
                if xbmcgui.Dialog().yesno(_(2), message, _(3)):
                    __settings__.openSettings()
            else:
                message = _(9000) # Unexpected error
                xbmcgui.Dialog().ok(_(2), message)

            return False
        p.close()
        self.updateTorrents()
        self.repeater = Repeater(1.0, self.updateTorrents)
        self.repeater.start()
    def updateTorrents(self):
        list = self.getControl(120)
        torrents = self.transmission.info()
        for i, torrent in torrents.iteritems():
            statusline = "[%(status)s] %(down)s down (%(pct).2f%%), %(up)s up (Ratio: %(ratio).2f)" % \
                {'down': Bytes.format(torrent.downloadedEver), 'pct': torrent.progress, \
                'up': Bytes.format(torrent.uploadedEver), 'ratio': torrent.ratio, \
                'status': torrent.status}
            if i not in self.list:
                # Create a new list item
                l = xbmcgui.ListItem(label=torrent.name, label2=statusline)
                list.addItem(l)
                self.list[i] = l
            else:
                # Update existing list item
                l = self.list[i]
            self.torrents = torrents
            statusicons = {'stopped': 'pause.png',
                           'seeding': 'ok.png',
                           'downloading': 'down.png'}
            l.setLabel(torrent.name)
            l.setLabel2(statusline)
            l.setProperty('TorrentStatusIcon', statusicons[torrent.status])
            l.setProperty('TorrentID', str(i))
            l.setProperty('TorrentProgress', "%.2f" % torrent.progress)
            l.setInfo('torrent', torrent.fields)
            l.setInfo('video', {'episode': int(torrent.progress)})

        removed = [id for id in self.list.keys() if id not in torrents.keys()]
        if len(removed) > 0:
            # Clear torrents from the list that have been removed
            for id in removed:
                del self.list[id]
            list.reset()
            for id, item in self.list.iteritems():
                list.addItem(item)
        list.setEnabled(bool(torrents))

    def onClick(self, controlID):
        list = self.getControl(120)
        if (controlID == 111):
            # Add torrent
            engines = [
                (_(200), None),
                (_(202), search.TPB),
                (_(203), search.Mininova),
                (_(204), search.TorrentReactor),
            ]
            selected = xbmcgui.Dialog().select(_(0), [i[0] for i in engines])
            if selected < 0:
                return
            engine = engines[selected][1]
            if not engine:
                filename = xbmcgui.Dialog().browse(1, _(0), 'files', '.torrent')
                try:
                    f = open(filename, 'r')
                    data = base64.b64encode(f.read())
                    self.transmission.add(data)
                except:
                    pass
            else:
                kb = xbmc.Keyboard('', engines[selected][0])
                kb.doModal()
                if not kb.isConfirmed():
                    return
                terms = kb.getText()
                p = xbmcgui.DialogProgress()
                p.create(_(0), _(290))
                try:
                    results = engine().search(terms)
                except:
                    p.close()
                    xbmcgui.Dialog().ok(_(0), _(292))
                    return
                p.close()
                if not results:
                    xbmcgui.Dialog().ok(_(0), _(291))
                    return
                selected = xbmcgui.Dialog().select(_(0), ['[S:%d L:%d] %s' % (t['seeds'], t['leechers'], t['name']) for t in results])
                if selected < 0:
                    return
                try:
                    self.transmission.add_uri(results[selected]['url'])
                except:
                    xbmcgui.Dialog().ok(_(0), _(293))
                    return
        if (controlID == 112):
            # Remove selected torrent
            item = list.getSelectedItem()
            if item and xbmcgui.Dialog().yesno(_(0), 'Remove \'%s\'?' % self.torrents[int(item.getProperty('TorrentID'))].name):
                remove_data = xbmcgui.Dialog().yesno(_(0), 'Remove data as well?')
                self.transmission.remove(int(item.getProperty('TorrentID')), remove_data)
        if (controlID == 113):
            # Stop selected torrent
            item = list.getSelectedItem()
            if item:
                self.transmission.stop(int(item.getProperty('TorrentID')))
        if (controlID == 114):
            # Start selected torrent
            item = list.getSelectedItem()
            if item:
                self.transmission.start(int(item.getProperty('TorrentID')))
        if (controlID == 115):
            # Stop all torrents
            self.transmission.stop(self.torrents.keys())
        if (controlID == 116):
            # Start all torrents
            self.transmission.start(self.torrents.keys())
        if (controlID == 117):
            # Exit button
            self.close()
        if (controlID == 120):
            # A torrent was chosen, show details
            item = list.getSelectedItem()
            w = TorrentInfoGUI("script-Transmission-details.xml", __settings__.getAddonInfo('path') ,"Default")
            w.setTorrent(self.transmission, int(item.getProperty('TorrentID')))
            w.doModal()
            del w
    def onFocus(self, controlID):
        pass

    def onAction( self, action ):
        if ( action.getButtonCode() in CANCEL_DIALOG ) or (action.getId() == KEY_MENU_ID):
            self.close()
    def close(self):
        if self.repeater:
            self.repeater.stop()
        super(TransmissionGUI, self).close()
Пример #29
0
def proc_normal_msg(stream, subject, content, msg):
    react = reaction.get(content)
    if not (react is None):
        send_message(stream, subject, react)
        return
    chall = get_chall(stream, subject)
    if chall:
        if re.search(file_regex, content):
            chall.files.append(( \
             msg['sender_full_name'], msg['timestamp'], content))
        elif re.search(link_regex, content):
            chall.links.append(( \
             msg['sender_full_name'], msg['timestamp'], content))


repeater = Repeater(send_message, 3)


def msg_handler(msg):
    if msg['type'] != 'stream' or msg['sender_full_name'] == "CTF":
        return  # ignore private msg and msg sent by itself
    stream = msg['display_recipient']
    subject = msg['subject']
    content = msg['content']
    if content.find("@**CTF**") >= 0:
        res = client.add_subscriptions(streams=[{'name': stream}])
        if res['result'] != 'success':
            send_message(stream, subject, str(res))
        # add subscription if bot is mentioned
    if content[0] == '!':
        return proc_cmd(stream, subject, msg, content[1:].split())
Пример #30
0
irts_data = urllib2.urlopen("http://www.irts.ie/cgi/repeater.cgi?printable").read()
irts_soup = BeautifulSoup(irts_data)

geolocator = Nominatim()

repeater_rows = irts_soup.find_all('table')[0].find_all('tr')

count = 0

for row in repeater_rows:
    count = count + 1
    if count == 1:
        continue # Skip the header row
    fields = row.find_all('td')
    repeater = Repeater(fields[2].next_element.strip())
    if repeater.callsign[0:2] == "GB":
        continue # we get these anyway from ukrepeater
    repeater.rx = fields[1].next_element.next_element.next_element.strip()
    repeater.tx = fields[1].next_element.next_element.next_element.next_element.next_element.next_element.next_element.strip()
    activation = re.sub("\/", "", fields[3].next_element.strip())
    if activation == "Carrier":
        repeater.carrier = True
    elif activation == "1750Hz":
        repeater.burst = True
    else:
        repeater.ctcss = re.sub("Hz", "", activation)
    repeater.mode = "FM"
    repeater.town = fields[4].next_element.strip()
    location = geolocator.geocode(re.sub(",.*$", "", repeater.town) + ", Republic of Ireland", timeout=10)
    if location == None:
Пример #31
0
class Game:

    IDLE = 0
    INIT = 1
    START_SINGLE = 2
    SHOW_SINGLE = 3
    INPUT_SINGLE = 4
    SCORE = 5

    def __init__(self):
        self.repeater = Repeater()
        self.debug_mode = True

        self.btns = {
            1: 'sw6',
            2: 'sw7',
            3: 'sw8',
            4: 'sw2',
            5: 'sw3',
            6: 'sw4'
        }
        self.rbtns = {v: k for k, v in self.btns.items()}
        self.leds = {
            1: 'ds3',
            2: 'ds6',
            3: 'ds9',
            4: 'ds1',
            5: 'ds4',
            6: 'ds7',
            7: 'ds2',
            8: 'ds5',
            9: 'ds8'
        }

        self.state = Game.IDLE

        self.repeater.register_handler('sw5', self.start_handler)
        self.repeater.register_handler('sw1', self.reset_handler)

        for btn in self.rbtns:
            self.repeater.register_handler(btn, self.btn_handler)

        self.num_players = 0
        self.curr_player = 0
        self.players = []
        self.scores = []

        self.len = 0
        self.sequence = []
        self.input_pos = 0

        self.timeout_event = None
        self.btn_events = {}

        self._start_time = time.time()

        self.blinker = None
        self.runner = None

    def play(self):
        self.repeater.run()

    # Handlers

    def start_handler(self, _, value):
        print('Clicking start, state = %d' % self.state)
        if self.state != Game.IDLE or not value:
            return

        self._set_all(False)
        self._schedule(lambda: self.init_game(), 0, name='init_game')

    def reset_handler(self, _, value):
        if self.state == Game.IDLE or not value:
            return

        print('=' * 40 + '\nResetting the game.')

        self._schedule(lambda: self.init_game(), 0, name='init_game')

    def btn_handler(self, btn, value):
        if self.state not in (Game.INPUT_SINGLE, Game.INIT) or not value:
            return

        value = self.rbtns[btn]
        print('Handling user input: %d.' % value)

        self._set_all(False)
        self._clear_btn_events()

        self._set(value, True)
        self.btn_events[value] = self._schedule(lambda: self._set_all(False),
                                                0.5,
                                                name='clear_clicked_light')

        if self.timeout_event is not None:
            Clock.unschedule(self.timeout_event)
            self.timeout_event = None

        if self.state == Game.INPUT_SINGLE:
            if self.sequence[self.input_pos] == value:
                self.input_pos += 1
                print('A correct guess <%d>!' % value)

                if self.input_pos == self.len:
                    print(
                        'Correctly finished a sequence! Increasing game difficulty.'
                    )
                    self._schedule(lambda: self.start_single(
                        self.curr_player, self.len + 1),
                                   1,
                                   name='starting_next_level')
                else:
                    self.timeout_event = self._schedule(
                        lambda: self.display_error(
                            'Waited too long (over 3s), game over!'),
                        3,
                        name='input_timeout_error')
            else:
                self._schedule(lambda: self.display_error(
                    'Wrong guess: %d != %d!' %
                    (value, self.sequence[self.input_pos])),
                               0,
                               name='wrong_input_error')

        elif self.state == Game.INIT and value not in self.players:
            self.num_players += 1
            self.players.append(value)
            self.scores.append(0)
            self.timeout_event = self._schedule(lambda: self.init_single(0),
                                                3,
                                                name='finished_player_count')

    # Game steps

    def init_game(self):
        self.num_players = 0
        self.curr_player = 0
        self.scores = []
        self.players = []

        self._enable_btns()

        self._schedule(lambda: self._set_state(Game.INIT),
                       0,
                       name='start_player_count')

    def init_single(self, player):
        self.curr_player = player
        print('SELECTING PLAYER %d <%d/%d>' %
              (self.players[player], player + 1, self.num_players))

        self._clear_btn_events()
        self._disable_btns()

        self._set(self.players[player], True)
        self._schedule(lambda: self._set(self.players[player], False),
                       2,
                       name='clear_player_light')
        self._schedule(lambda: self.start_single(player, 1),
                       3,
                       name='start_player_game')

    def start_single(self, player, length):
        print('Starting a new game for player %d with len=%d.' %
              (player + 1, length))
        self.scores[player] = length - 1

        self.len = length
        self.sequence = [random.randint(1, 6) for _ in range(self.len)]
        self.state = Game.START_SINGLE

        self._clear_btn_events()
        self._disable_btns()

        self.blinker = Blinker(2, 2, self._set_all)
        self.blinker.blink()

        self._schedule(lambda: self._set_state(Game.SHOW_SINGLE),
                       3.9,
                       name='enter_show_state')
        self._schedule(lambda: self.display_item(0),
                       4,
                       name='display_first_item')

    def display_item(self, pos):
        item = self.sequence[pos]

        print('Displaying an item <%s> (%d/%d).' % (item, pos + 1, self.len))

        self._set(item, True)
        self._schedule(lambda: self._set(item, False),
                       0.5,
                       name='clear_displayed_led')

        if pos < self.len - 1:
            self._schedule(lambda: self.display_item(pos + 1),
                           0.75,
                           name='display_next_item')
        else:
            print('Whole sequence shown, will proceed to input.')
            self._schedule(lambda: self.init_clicks(), 2.5, name='init_clicks')

    def init_clicks(self):
        print('Initializing user input state.')

        self._schedule(lambda: self._set_all(True), 0, name='light_all')
        self._schedule(lambda: self._set_all(False), 1, name='clear_all')

        self.input_pos = 0

        self._schedule(lambda: self._set_state(Game.INPUT_SINGLE),
                       1,
                       name='start_input_mode')
        self._schedule(lambda: self._enable_btns(), 1, name='enable_btns')

    def display_error(self, msg):
        print('An error occurred: %s.' % msg)
        self.blinker = Blinker(0.1, 20, self._set_all)
        self.blinker.blink()
        print(
            'Status :: num_players = %d, curr_player = %d, players = %s, scores = %s\n'
            % (self.num_players, self.curr_player, self.players, self.scores))
        if self.curr_player < self.num_players - 1:
            self._schedule(lambda: self.init_single(self.curr_player + 1),
                           2,
                           name='start_next_player(error)')
        else:
            print('Final player played his game, ROUND OVER!!!')
            self.runner = Runner((7, 8, 9), 40, 0.0125, self._set)
            self.runner.run()
            self._schedule(lambda: self.display_winner(),
                           20 * 39 * 0.0125,
                           name='display_winner')

    def display_winner(self):
        print('<< And the winner is... >>')
        winner = max(range(self.num_players), key=lambda i: self.scores[i])
        print('<< PLAYER %d <%d/%d> with score %d! >>' %
              (self.players[winner], winner + 1, self.num_players,
               self.scores[winner]))
        self._set(self.players[winner], True)
        self.state = Game.IDLE

    # =========================================================================

    def _schedule(self, fn, by, *args, name=None):
        def f(dt):
            if self.debug_mode:
                print('> Executing <%s> at %.2f (delayed by %s).' %
                      (getattr(fn, '__qualname__', None) if name is None else
                       name, time.time() - self._start_time, by))
            fn(*args)

        return Clock.schedule_once(f, by)

    def _blink_once(self, val):
        def f(dt):
            self._set_all(val)

        return f

    # ==========================================================================

    def _set(self, i, value):
        self.repeater.set(self.leds[i], value)

    def _set_all(self, value):
        for id in self.leds.values():
            self.repeater.set(id, value)

    def _set_state(self, state):
        self.state = state

    def _disable_btns(self):
        print('Disabling all buttons.')
        for btn in self.btns.values():
            self.repeater.interface.ids[btn].disabled = True

    def _enable_btns(self):
        print('Enabling all buttons.')
        for btn in self.btns.values():
            self.repeater.interface.ids[btn].disabled = False

    # ==========================================================================

    def _clear_btn_events(self):
        for evnt in self.btn_events.values():
            Clock.unschedule(evnt)

    def _dbg(self, dt):
        print('> Debug after %s :: state = %s, seq = %s, pos = %s, len = %s.' %
              (dt, self.state, self.sequence, self.pos, self.len))
Пример #32
0
 def __init__(self, strXMLname, strFallbackPath, strDefaultName, bforeFallback=0):
     self.transmission = None
     self.torrent_id = None
     self.list = {}
     self.repeater = Repeater(1.0, self.updateTorrent)
Пример #33
0
class Game:

    IDLE = 0
    START = 1
    SHOW = 2
    INPUT = 3
    ERROR = 4

    def __init__(self):
        self.repeater = Repeater()
        self.state = Game.IDLE

        self.debug_mode = False

        self.btns = {
            1: 'sw6',
            2: 'sw7',
            3: 'sw8',
            4: 'sw2',
            5: 'sw3',
            6: 'sw4'
        }
        self.rbtns = {v: k for k, v in self.btns.items()}
        self.leds = {
            1: 'ds3',
            2: 'ds6',
            3: 'ds9',
            4: 'ds1',
            5: 'ds4',
            6: 'ds7',
            7: 'ds2',
            8: 'ds5',
            9: 'ds8'
        }

        self.repeater.register_handler('sw5', self.start_handler)
        self.repeater.register_handler('sw1', self.reset_handler)

        for btn in self.rbtns:
            self.repeater.register_handler(btn, self.btn_handler)

        self.len = 0
        self.sequence = []
        self.input_pos = 0

        self.timeout_event = None
        self.btn_events = {}

        self._start_time = time.time()

        self.blinker = None

    def play(self):
        self.repeater.run()

    def start_handler(self, _, value):
        if self.state != Game.IDLE or not value:
            return

        self._schedule(lambda: self.start(1), 0, name='start')

    def reset_handler(self, _, value):
        if self.state == Game.IDLE or not value:
            return

        print('=' * 40 + '\nResetting the game.')

        self._schedule(lambda: self.start(1), 0, name='start')

    def btn_handler(self, btn, value):
        if self.state != Game.INPUT or not value:
            return

        value = self.rbtns[btn]
        print('Handling user input: %d.' % value)

        self._set_all(False)
        self._clear_btn_events()

        self._set(value, True)
        self.btn_events[value] = self._schedule(lambda: self._set_all(False),
                                                0.5,
                                                name='clear_clicked_light')

        if self.timeout_event is not None:
            Clock.unschedule(self.timeout_event)
            self.timeout_event = None

        if self.sequence[self.input_pos] == value:
            self.input_pos += 1
            print('A correct guess <%d>!' % value)

            if self.input_pos == self.len:
                print(
                    'Correctly finished a sequence! Increasing game difficulty.'
                )
                self._schedule(lambda: self.start(self.len + 1),
                               1,
                               name='starting_next_level')
            else:
                self.timeout_event = self._schedule(lambda: self.display_error(
                    'Waited too long (over 3s), game over!'),
                                                    3,
                                                    name='input_timeout_error')
        else:
            self._schedule(lambda: self.display_error(
                'Wrong guess: %d != %d!' %
                (value, self.sequence[self.input_pos])),
                           0,
                           name='wrong_input_error')

    def start(self, length):
        print('Starting a new game with len=%d.' % length)

        self.len = length
        self.sequence = [random.randint(1, 6) for _ in range(self.len)]
        self.state = Game.START

        self._clear_btn_events()
        self._disable_btns()

        self.blinker = Blinker(2, 2, self._set_all)
        self.blinker.blink()

        self._schedule(lambda: self._set_state(Game.SHOW),
                       3.9,
                       name='enter_show_state')
        self._schedule(lambda: self.display_item(0),
                       4,
                       name='display_first_item')

    def display_item(self, pos):
        item = self.sequence[pos]

        print('Displaying an item <%s> (%d/%d).' % (item, pos + 1, self.len))

        self._set(item, True)
        self._schedule(lambda: self._set(item, False),
                       0.5,
                       name='clear_displayed_led')

        if pos < self.len - 1:
            self._schedule(lambda: self.display_item(pos + 1),
                           0.75,
                           name='display_next_item')
        else:
            print('Whole sequence shown, will proceed to input.')
            self._schedule(lambda: self.init_clicks(), 2.5, name='init_clicks')

    def init_clicks(self):
        print('Initializing user input state.')

        self._schedule(lambda: self._set_all(True), 0, name='light_all')
        self._schedule(lambda: self._set_all(False), 1, name='clear_all')

        self.input_pos = 0

        self._schedule(lambda: self._set_state(Game.INPUT),
                       1,
                       name='start_input_mode')
        self._schedule(lambda: self._enable_btns(), 1, name='enable_btns')

    def display_error(self, msg):
        print('An error occurred: %s.' % msg)
        self.blinker = Blinker(0.1, 20, self._set_all)
        self.blinker.blink()
        self._schedule(lambda: self.start(1),
                       2,
                       name='start_from_scratch(error)')

    # =========================================================================

    def _schedule(self, fn, by, *args, name=None):
        def f(dt):
            if self.debug_mode:
                print('> Executing <%s> at %.2f (delayed by %s).' %
                      (getattr(fn, '__qualname__', None) if name is None else
                       name, time.time() - self._start_time, by))
            fn(*args)

        return Clock.schedule_once(f, by)

    def _blink_once(self, val):
        def f(dt):
            self._set_all(val)

        return f

    # ==========================================================================

    def _set(self, i, value):
        self.repeater.set(self.leds[i], value)

    def _set_all(self, value):
        for id in self.leds.values():
            self.repeater.set(id, value)

    def _set_state(self, state):
        self.state = state

    def _disable_btns(self):
        print('Disabling all buttons.')
        for btn in self.btns.values():
            self.repeater.interface.ids[btn].disabled = True

    def _enable_btns(self):
        print('Enabling all buttons.')
        for btn in self.btns.values():
            self.repeater.interface.ids[btn].disabled = False

    # ==========================================================================

    def _clear_btn_events(self):
        for evnt in self.btn_events.values():
            Clock.unschedule(evnt)

    def _dbg(self, dt):
        print('> Debug after %s :: state = %s, seq = %s, pos = %s, len = %s.' %
              (dt, self.state, self.sequence, self.pos, self.len))