Пример #1
0
def get_events_text(events: List[Event]) -> str:
    dates = helpers.get_dates_in_week(events)
    events_text = ""
    for event_date in dates:
        nt_url = f"https://www.phoenixnewtimes.com/calendar?dateRange[]={event_date.strftime('%Y-%m-%d')}"
        events_text += f"**[{event_date.strftime('%A')} {event_date.strftime('%B %d')}]({nt_url})**\n\n"

        daily_events = sorted(list(filter(lambda _: _.event_date == event_date, events)), key=lambda x: x.event_time[0])
        categories_today = helpers.get_categories(daily_events)
        for category in categories_today:
            events_text += helpers.parse_category(category)
            events_by_category = filter(lambda _: _.category == category, daily_events)

            for current_event in events_by_category:
                if current_event.category.strip() in ["[MEETUP]", "[COMMUNITY]"]:
                    events_text += f"    * {current_event.title.strip()}"
                else:
                    events_text += f"    * [{current_event.title.strip()}]({current_event.link})"
                if current_event.location:
                    events_text += f" @{helpers.extract_venue(current_event.location)}, " \
                                   f"{helpers.extract_city(current_event.location)} "
                list_of_times = ", ".join(list(map(lambda x: x.strftime("%-I:%M%p"), sorted(current_event.event_time))))
                events_text += list_of_times
                if current_event.cost:
                    events_text += f" _({current_event.cost})_"

                events_text += "\n\n"
    return events_text
Пример #2
0
def add_item():
    categories = get_categories()
    if not categories:
        return redirect_flash('No categories, add one first.', status='error')

    if request.method == 'GET':
        return render_template('add_item.html', categories=categories)

    elif request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        category = request.form['category']

        if all([name, description, category]):  # is valid form
            item = Item(name=name,
                        description=description,
                        category_id=category)

            db.session.add(item)
            db.session.commit()

            return redirect_flash('Successfully updated item name')

        else:
            return redirect_flash('Wrong fields editing item.', status='error')
Пример #3
0
def index():
    categories = get_categories()
    last_items = Item.query.order_by(desc('created_at')).limit(10)

    is_logged, username = False, ''
    if 'username' in session:
        is_logged = True
        username = session['username']

    return render_template('index.html',
                           is_logged=is_logged,
                           username=username,
                           categories=categories,
                           last_items=last_items)
Пример #4
0
def categories(category_name):
    is_logged, username = False, ''
    if 'username' in session:
        is_logged = True
        username = session['username']

    categories = get_categories()
    category = Category.query.filter_by(name=category_name).first()

    items = category.items
    items_count = len(items)

    return render_template('category.html',
                           category_name=category_name,
                           categories=categories,
                           items_count=items_count,
                           is_logged=is_logged,
                           username=username,
                           items=items)
Пример #5
0
def diashow():
    with g.db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
        try:
            cursor.execute("""
              SELECT * FROM minicloud_diashow
              WHERE user_id = %s ORDER BY created_at DESC
              """, [ int(current_user.id) ])

            diashows = cursor.fetchall()

            return render_template( "gallery/diashow.html"
                                  , diashows = diashows
                                  , categories = get_categories()
                                  )

        except Exception as e:
            app.logger.error('Show in diashow failed: %s' % str(e))
            g.db.rollback()

    abort(500)
Пример #6
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.categories = get_categories()
        self.bind(opt_api=self.update_categories)
        self.fps_event = Clock.schedule_interval(self.print_fps, 1/2.0)
        self.sm = None
        self.bg_anim = (Animation(bg_col=[1,0,0], duration=2) +
                Animation(bg_col=[1,1,0], duration=2) +
                Animation(bg_col=[0, 1, 1], duration=2) +
                Animation(bg_col=[0, 0, 1], duration=2) +
                Animation(bg_col=[1, 0, 1], duration=2))
        self.bg_anim.repeat = True

        self.snd_machine = SoundMachine()
        #self.bg_anim.start(self)   # Will be started by first screen (Intro)

        self.callbacks = []

        # Register EXIT and SCREENSHOT handler
        self.add_callback(CEC_CMD_MAP["EXIT"], "ALL", lambda: App.get_running_app().stop())

        # Set window size if instructed
        if SET_SIZE:
            Window.size = (1920, 1080)
            Window.left = 0
            Window.top = 1

        # Get keyboard
        #self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        Window.bind(on_key_down=self._on_keyboard_down)

        # initialise libCEC
        if not DISABLE_CEC:
            from cec_control import pyCecClient
            self.lib = pyCecClient()
            self.lib.SetCommandCallback(lambda cmd: self.command_callback(cmd, 'cec'))

            # initialise libCEC and enter the main loop
            self.lib.InitLibCec()
Пример #7
0
def show():
    orphans = find_orphan_files(int(current_user.id))
    with g.db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
      try:

        cursor.execute("""
          SELECT category AS name, json_agg(json_build_object('id', id, 'uid', uid, 'title', title) ORDER BY updated_at ASC) AS files
          FROM minicloud_gallery WHERE user_id = %s GROUP BY category ORDER BY category ASC
          """, [ int(current_user.id) ])

        files = cursor.fetchall()

        return render_template( "gallery/show.html"
                              , files = files
                              , categories = get_categories()
                              )

      except Exception as e:
          app.logger.error('Show in gallery failed: %s' % str(e))
          g.db.rollback()

    abort(500)
Пример #8
0
def edit(uid):
    if request.method == "GET":
        with g.db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            cursor.execute("""
              SELECT id, title, description, uid, category FROM minicloud_gallery
              WHERE user_id = %s AND uid = %s LIMIT 1
              """, [int(current_user.id), uid])

            file = cursor.fetchone()

        return render_template( "gallery/edit.html"
                              , categories = get_categories()
                              , file = file
                              )

    if request.method == "POST":
        title = request.form['title']
        description = request.form['description']
        category = request.form['category']

        with g.db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            try:
                cursor.execute("""
                    UPDATE minicloud_gallery
                      SET title = %s, description = %s, category = %s
                    WHERE user_id = %s AND uid = %s
                    """, [title, description,  category, int(current_user.id), uid])

                g.db.commit()
                flash(['File modified'], 'info')

            except Exception as e:
                app.logger.error('Edit in gallery failed: %s' % str(e))
                g.db.rollback()
                flash(['Edit failed'], 'error')

        return redirect(url_for('gallery.show'))

    abort(501)
Пример #9
0
from helpers import get_categories, get_books_from_category, get_book_data
from helpers import write_csv, download_image
from os import makedirs

download_dir = './downloads/'
makedirs(download_dir, exist_ok=True)

url = 'http://books.toscrape.com/'

print('getting categories')
categories = get_categories(url)

for category in categories:
    print('\n' + 'getting books from ' + category['title'] + ':')
    books = get_books_from_category(category['url'])

    books_data = []
    for book in books:
        books_data.append(get_book_data(book, category['title']))
        print(' ' + books_data[-1]['title'])

    print('\n' + 'writing ' + category['title'] + '.csv')
    write_csv(download_dir + category['title'] + '.csv', books_data)

    print('')

    images_dir = download_dir + category['title'] + '/'
    makedirs(images_dir, exist_ok=True)

    for data in books_data:
        file_name = data['title'].replace("/", " - ") + ' - ' + \
Пример #10
0
import json
import sys


# Pass cli arguments

DISABLE_CEC = True if '--disable-cec' in sys.argv else False
USE_SAMPLE_DATA = True if '--use-sample-data' in sys.argv else False
SET_SIZE = True if '--set-size' in sys.argv else False

# Backend settings

BACKENDS = {
    "opentdb": {
        "url": "https://opentdb.com/api.php",
        "categories": get_categories()

    },
    "feduquizdb": {
        "url": "https://dillendapp.eu/feduquizdb/api/trivia",
        "categories": [["All", -1], ["General knowledge", 1],["Luxemburgensia", 2]]
    }
}


class GameButtons(Widget):

    game_root = ObjectProperty()

    def anim_all(self, direction, highlight=None, callback=None):
Пример #11
0
def show():
    utc = Config.UTCZONE
    zone = Config.ZONE
    today = datetime.utcnow().replace(
        tzinfo=utc).astimezone(zone).strftime('%-d. %B %Y, %H:%M')
    last = datetime.utcnow().replace(tzinfo=utc)
    uid = None
    previous = None
    forward = None
    text = ''
    category = 'Default'
    tags = []

    if 'uid' in request.args.keys():
        uid = request.args.get('uid')

    try:
        if uid:
            with g.db.cursor(
                    cursor_factory=psycopg2.extras.DictCursor) as cursor:
                cursor.execute(
                    """
                SELECT * FROM minicloud_notes WHERE user_id = %s AND uid = %s
                """, [current_user.id, uid])

                note = cursor.fetchone()
                if note:
                    last = note['created_at']
                    today = last.replace(tzinfo=utc).astimezone(zone).strftime(
                        '%-d. %B %Y, %H:%M')
                    uid = note['uid']
                    text = note['description']
                    category = note['category']
                    tags = note['tags']

        with g.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
            cursor.execute(
                """
            SELECT * FROM minicloud_notes WHERE user_id = %s
            AND created_at < %s ORDER BY created_at DESC LIMIT 1
            """, [current_user.id, last])

            data1 = cursor.fetchone()
            if data1: previous = data1['uid']

        with g.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
            cursor.execute(
                """
            SELECT * FROM minicloud_notes WHERE user_id = %s
            AND created_at > %s ORDER BY created_at ASC LIMIT 1
            """, [current_user.id, last])

            data2 = cursor.fetchone()
            if data2: forward = data2['uid']

    except Exception as e:
        app.logger.error('Show in notes failed: %s' % str(e))
        flash(['Show failed'], 'error')

    return render_template('notes/show.html',
                           today=today,
                           uid=uid,
                           text=text,
                           category=category,
                           categories=get_categories(),
                           tags=tags,
                           previous=previous,
                           forward=forward)