def get_connection(source):
    '''
    Get a DB connection from the CLI args or defaults to postgres:///mydb

    '''
    source.engine = create_engine(source.db_name)
    ui.header('Connecting to database %s' % source.db_name)

    if not database_exists(source.engine.url):
        create_database(source.engine.url)
        ui.item("Creating database %s" % source.db_name)

    Session = sessionmaker()
    Session.configure(bind=source.engine)

    source.session = Session()

    gis_q = 'SELECT PostGIS_version();'
    # Check for PostGIS support
    try:
        source.session.execute(gis_q)
        source.geo = True
    except OperationalError:
        source.geo = False
    except ProgrammingError:
        source.geo = False
    source.session.commit()

    if source.geo:
        ui.item('PostGIS is installed. Geometries will be imported '
                'as PostGIS geoms.')
Exemple #2
0
def alist(): #function för att printa en del utav ui
    ui.clear() #Clear call
    ui.line(False)  # printar en linje gjord utav -
    ui.header("ARTIST DATABASE")
    ui.line(True)  # printar en linje gjord utav *
    web.getart() #kallar på funktionen som tar fram listna av artister
    ui.line(False)  # printar en linje gjord utav -
    ui.echo("| Press enter to return ")  # Printar våra val
    ui.line(False)  # printar en linje gjord utav -
    ui.prompt()
Exemple #3
0
def ainspect(): #function för att printa en del utav ui
    ui.clear() #Clear call
    ui.line(False)  # printar en linje gjord utav *
    ui.header("ARTIST DATABASE")
    ui.line(True)  # printar en linje gjord utav -
    web.inspectart() #kallar på funktionen som tar fram informationen på specifika artister.
    ui.line(False)  # printar en linje gjord utav *
    ui.echo("| Press enter to return ")  # Printar våra val
    ui.line(False)  # printar en linje gjord utav *
    ui.prompt()
def get_binding(source):
    '''
    Translate the source's metadata into a SQLAlchemy binding

    This looks at each column type in the metadata and creates a
    SQLAlchemy binding with columns to match. For now it fails loudly if it
    encounters a column type we've yet to map to its SQLAlchemy type.
    '''

    record_fields = {
        '__tablename__': source.tbl_name,
        '_pk_': Column(Integer, primary_key=True)
    }

    ui.header('Setting up new table, "%s", from %s source fields' %
              (source.tbl_name, source.name))

    for col_name, col_type in source.metadata:

        if isinstance(col_type, type(Geometry())) and not source.geo:
            try:
                source.session.execute("CREATE EXTENSION POSTGIS;")
                ui.item(
                    "Adding PostGIS extension to support %s column." \
                    % col_name)
                source.session.commit()
                source.geo = True
            except:
                msg = (
                    '"%s" is a %s column but your database doesn\'t support '
                    'PostGIS so it\'ll be skipped.') % (
                        col_name,
                        col_type,
                    )
                ui.item(msg)
                continue

        if col_name.startswith(':@computed'):
            ui.item('Ignoring computed column "%s".' % col_name)

            continue

        try:

            assert (col_type
                    ), 'Unable to map %s type to a SQL type.' % (source.name)
            record_fields[col_name] = Column(col_type)

        except NotImplementedError as e:
            ui.item('%s' % str(e))

    source.binding = type('DataRecord', (declarative_base(), ), record_fields)
Exemple #5
0
def whatDiff():  #funktion för svårighetsgrad
    ui.header("Difficulty")
    ui.echo("1: Easy")
    ui.echo("2: Hard")
    difficulty = ui.prompt("Answer >")
    if difficulty == "1":
        APIget(easyAPI)  #svar 1 ger lättare frågor
    elif difficulty == "2":
        APIget(hardAPI)  #svar 2 ger svåra frågor
    else:
        ui.echo("Invalid input, try again")
        ui.line()
        whatDiff()  #om något annat än 1 eller 2 anges så körs den om
def get_binding(dataset_metadata, geo, dest, source):
    """Translate the Socrata API metadata into a SQLAlchemy binding

    This looks at each column type in the Socrata API response and creates a
    SQLAlchemy binding with columns to match. For now it fails loudly if it
    encounters a column type we've yet to map to its SQLAlchemy type."""
    if dest:
        table_name = dest        
    elif source == "Socrata":
        table_name = get_table_name(dataset_metadata['name'])

    record_fields = {
        '__tablename__': table_name,
        '_pk_': Column(Integer, primary_key=True)
    }

    ui.header(
        'Setting up new table, "%s", from %s source fields' % (table_name, source)
    )

    geo_types = ('location', 'point', 'multipolygon', 'esriFieldTypeGeometry')

    for col in dataset_metadata:
        if source == "Socrata":
            col_name = col['fieldName'].lower()
            col_type = col['dataTypeName']
        elif source == "HUD":
            col_name = col['name'].lower()
            col_type = col['type']

        if col_type in geo_types and geo is False:
            msg = (
                '"%s" is a %s column but your database doesn\'t support '
                'PostGIS so it\'ll be skipped.'
            ) % (col_name, col_type,)
            ui.item(msg)
            continue

        if col_name.startswith(':@computed'):
            ui.item('Ignoring computed column "%s".' % col_name)
            continue

        try:
            print(col_name, ": ", col_type)
            record_fields[col_name] = get_sql_col(col_type, source)

        except NotImplementedError as e:
            ui.item('%s' % str(e))
            continue

    return type('SocrataRecord', (declarative_base(),), record_fields)
def whatDifficulty():  #funktion för att välja svårighetsgrad
    ui.header("Difficulty")
    ui.echo("1: Easy")
    ui.echo("2: Hard")
    difficulty = ui.prompt("Answer >")
    if difficulty == "1":
        getApi(apiEasy)  #om man svarar 1 så används apin med lättare frågor
    elif difficulty == "2":
        getApi(apiHard)  #om man svarar 2 så används apin med svårare frågor
    else:
        ui.echo("Invalid input, try again")
        ui.line()
        whatDifficulty(
        )  #om något annat än 1 eller 2 anges så körsfunnktionen om
def insert_source(source):
    '''
    Gets the connection and binding and inserts data.
    '''

    get_connection(source)

    if not isinstance(source, sc.CenPy):
        get_binding(source)

    if source.engine.dialect.has_table(source.engine, source.tbl_name):
        print()
        warnings.warn(("Destination table already exists. Current table " +
                       "will be dropped and replaced."))
        print()
        if not isinstance(source, sc.CenPy):
            source.binding.__table__.drop(source.engine)

    try:
        if not isinstance(source, sc.CenPy):
            source.binding.__table__.create(source.engine)
    except ProgrammingError as e:

        raise CLIError('Error creating destination table: %s' % str(e))

    circle_bar = FillingCirclesBar('  ▶ Loading from source',
                                   max=source.num_rows)

    source.insert(circle_bar)

    circle_bar.finish()

    ui.item('Committing rows (this can take a bit for large datasets).')
    source.session.commit()

    success = 'Successfully imported %s rows.' % (source.num_rows)
    ui.header(success, color='\033[92m')
    if source.name == "Socrata" and source.client:
        source.client.close()

    return
def get_connection(db_str, dataset_metadata, source):
    """Get a DB connection from the CLI args and Socrata API metadata

    Uess the DB URL passed in by the user to generate a database connection.
    By default, returns a local SQLite database."""
    if db_str:
        engine = create_engine(db_str)
        ui.header('Connecting to database')
    else:
        default = default_db_str(source)
        ui.header('Connecting to database')
        engine = create_engine(default)
        ui.item('Using default SQLite database "%s".' % default)

    Session = sessionmaker()
    Session.configure(bind=engine)

    session = Session()

    # Check for PostGIS support
    gis_q = 'SELECT PostGIS_version();'
    try:
        session.execute(gis_q)
        geo_enabled = True
    except OperationalError:
        geo_enabled = False
    except ProgrammingError:
        geo_enabled = False
    finally:
        session.commit()

    if geo_enabled:
        ui.item(
            'PostGIS is installed. Geometries will be imported '
            'as PostGIS geoms.'
        )
    else:
        ui.item('Query "%s" failed. Geometry columns will be skipped.' % gis_q)

    return engine, session, geo_enabled
import ui  #importerar våra tidigare filer
import web

ui.line()
ui.header("ARTIST DATABASE")
ui.line()
ui.echo("Welcome to a world of")
ui.echo("Music!")
ui.line()
ui.echo("L", "List artists")
ui.echo("V", "View artist profile")
ui.echo("E", "Exit application")
a = ui.prompt("Selection")

running = "yes"  #sätter någonting vi kan loopa med

while running == "yes":
    b = web.get(
        "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"
    )  #tidigare url:en, b kommer alltid att uppdateras när vi frågar efter information
    if a.title() == "L":  #om valet är l eller L
        ui.line()
        ui.header("ARTIST DATABASE")
        ui.line()
        for x in b["artists"]:  #för alla värden i artists
            ui.echo(x["name"]
                    )  #letar den efter namn och skriver ut det som finns där
        ui.line(True)
        ui.echo("L", "List artists")
        ui.echo("V", "View artist profile")
        ui.echo("E", "Exit application")
#8.4
import ui  #importerar nödvändiga moudler och funktioner
import requests
import web

url = 'https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/'  # urlen

web.get(url)  # använder modulen
shutdown = False  # sätter shutdown variabeln till false för att vi inte vill att whileloopen ska stängas ner

artists = web.get(
    'https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/')[
        'artists']  #går in i urlen och in i artister

ui.line()  #skapar interface med ui.py
ui.header('Artist database')
ui.line()
ui.echo('Welcome to a world of')
ui.echo('Music')
ui.line()
ui.echo('L, List artists')
ui.echo('V, View artist profile')
ui.echo('E, Exit application')
ui.line()
choice = ui.promt('| Selection> ')
ui.line()
while shutdown == False:  # om shutdown variabeln är falsk vilket vi satte den till kör den whileloopen
    if choice.lower() == 'l':  #om man väljer l
        for i in artists:  #skriver ut alla artisters namn
            ui.echo(i['name'])
        ui.line()
Exemple #12
0
import requests  #importerar biblioteket requests
import web  #importerar web.py
import ui  #importerar ui.py

url = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"
artists = web.get(
    "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"
)["artists"]  #artists blir en variabel av svaret man får från apin som skickas till web.py och funktionen get

ui.line()
ui.header("ARTIST DB")
ui.line()
ui.echo("Welcome to a world of")
ui.echo("Music!")
ui.line()
ui.echo(" L | List artists")
ui.echo(" V | View artist profile")
ui.echo(" E | Exit application")
ui.line()
selection = ui.prompt(
    "Selection >")  #en input av användaret som bestämmer vad man vill göra

while True:
    if selection.lower() == "l":  #om inputen är l
        ui.line()
        ui.header("ARTIST DB")
        ui.line()
        for i in artists:  #för varje plats i listan artists
            ui.echo(i["name"])
        ui.line(True)
        ui.echo(" L | List artists")
Exemple #13
0
import requests
import ui
artists = []

idUrl = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"

artistsArr = requests.get(idUrl)
artistJson = artistsArr.json()["artists"]

for artist in artistJson:
    artists.append(artist["name"])

while True != False:
    ui.line(True)
    ui.header("Välkommen till artist-wiki")
    ui.line(True)

    nummer = 0
    for art in artists:
        ui.echo(art + " ----- " + str(nummer))
        nummer += 1
    u_inp = ui.prompt(
        "Ange en artists nummer eller 'exit' om du vill avsluta programmet> ")
    if "exit" in u_inp.lower():
        break
    else:
        try:

            a_artist = int(u_inp)

            ui.line()
def main():
    arguments = docopt(__doc__)

    site = arguments['<site>']

    if arguments['--HUD']:
        source = "HUD"
        dataset_id = site
        client = None
    if arguments['--Socrata']:
        source = "Socrata"
        client = Socrata(site, arguments.get('-a'))

    try:
        if arguments.get('ls'):
            datasets = list_datasets(client, site)
            print(tabulate(datasets, headers='keys', tablefmt='psql'))
        elif arguments.get('insert'):        
            if source == "Socrata":
                dataset_id = arguments['<dataset_id>']
                metadata = client.get_metadata(dataset_id)['columns']
            if source == "HUD":
                metadata = json.loads(
                    urllib.request.urlopen(site).read())['fields']

            engine, session, geo = \
                get_connection(arguments['-d'], metadata, source)
            
            if arguments['-t']:
                Binding = get_binding(
                    metadata, geo, arguments['-t'], source
                )
            else:
                Binding = get_binding(
                    metadata, geo, dataset_id, source
                )

            # Create the table
            try:
                Binding.__table__.create(engine)
            except ProgrammingError as e:
                # Catch these here because this is our first attempt to
                # actually use the DB
                if 'already exists' in str(e):
                    raise CLIError(
                        'Destination table already exists. Specify a new table'
                        ' name with -t.'
                    )
                raise CLIError('Error creating destination table: %s' % str(e))

            num_rows, data = get_data(source, dataset_id, client)
            bar = FillingCirclesBar('  ▶ Loading from source', max=num_rows)

            # Iterate the dataset and INSERT each page
            if source == "Socrata":
                for page in data:
                    insert_data(page, session, bar, Binding)

            if source == "HUD":
                insert_data(data, session, bar, Binding)

            bar.finish()

            ui.item(
                'Committing rows (this can take a bit for large datasets).'
            )
            session.commit()

            success = 'Successfully imported %s rows.' % (
                num_rows
            )
            ui.header(success, color='\033[92m')
        if client:
            client.close()
    except CLIError as e:
        ui.header(str(e), color='\033[91m')
Exemple #15
0
def outpttxt(header, echo):
    ui.header(header)
    ui.echo(echo)
    ui.line()
Exemple #16
0
import ui  #importerar ui.py

ui.line()
ui.header("Exempel")
ui.line(True)
ui.echo("Detta är ett exempel på hur")
ui.echo("ett gränssnitt kan se ut")
ui.line()
ui.header("..vad vill du göra?")
ui.line()
ui.echo("A | Visa inköpslista")
ui.echo("B | Lägg till vara")
ui.echo("C | Ta bort vara ")
ui.echo("X | Stäng programmet")
ui.line()
ui.prompt("Val")
#anrop till funktioner i ui.py
Exemple #17
0
        ui.echo("Invalid input, try again")
        ui.line()
        numbQ()  #funktionen körs om ogiltigt svar kommer in


def replace(str):  #tar bort onödiga tecken
    str = str.replace("&lt;", "<")
    str = str.replace("&gt;", ">")
    str = str.replace("&quot;", '"')
    str = str.replace("&#039;", "'")
    #vi uppdaterar str för varje rad med de riktiga teckena
    return str


ui.line()
ui.header("Frågesport")
ui.line()
whatDiff()
ui.line()
ui.header("Questions")
numbQ()
ui.line()
while True:  #frågesporten körs tills antalet frågor har uppnåtts, då stoppas den
    if count != int(questions):
        count += 1  #antalet gånger programmet har ställt en fråga, lägger till 1 när en ny fråga ställs
        NumbersGet()
        ui.echo(replace(QA[index]["fråga"]))  #frågan
        ui.echo("Alternatives:")
        AltGet(index)  #hämtar alternativ
        for i in alt:
            if i == QA[index]["correct"]:  #om rätt svar
import ui

ui.line()
ui.header("EXEMPEL")
ui.line(True)
ui.echo("Detta är ett exempel på hur")
ui.echo("ett grännsnitt kan se ut.")
ui.line()
ui.header(".. vad vill du göra?")
ui.line()
ui.echo("A | Visa inköpslista ")
ui.echo("B | Lägg till vara ")
ui.echo("C | Ta bort vara ")
ui.echo("X | Stäng programmet ")
ui.line()
ui.prompt("Val ")
Exemple #19
0
    return str


url = 'https://opentdb.com/api.php?amount=5&category=27&difficulty=easy&type=boolean'

fragor = web.get(url)[
    'results']  #gör om urlen till json och går in i results i dictionaryt

nummer = list(range(0, 5))
random.shuffle(nummer)  #blandar nummer från 0 till 5 i slumpmässig ordning

i = 0  # väljer första siffran i listan
rightanswer = 0  #startar rätträknaren på noll

ui.line()
ui.header('Välkommen till Djurquizet')
ui.header('Du kommer att få fem frågor som handlar om djur')
ui.line(True)

while i < 5:  #körs 5 gånger och slutar sen
    rättsvar = fragor[nummer[i]][
        "correct_answer"]  #skapar en variabel som har rätt svar till rätt fråga
    ui.echo(escape(fragor[nummer[i]]["question"]))  #skriver ut första frågan
    svar1 = ui.promt(
        'Answer (true or false) : ')  # skapar en variabel med deltagarens svar
    if svar1.title(
    ) == rättsvar:  #om svaret med första bokstaven stor stämmer:
        print(rättsvar)
        print('Du har svarat rätt! ')
        ui.line()
        rightanswer += 1  #om man har rätt på frågan lägger den till 1 till rätträknaren
Exemple #20
0
import ui   # importerar ui
# använder funktioner från ui
ui.line()   # gör linje 
ui.header("EXEMPEL")    # skriver ut i mitten och med | på sidorna
ui.line(True)   # gör linje av sjärnor
ui.echo("Detta är ett exempel på hur")   # skriver ut med en | från början
ui.echo("ett grännsnitt kan se ut.") 
ui.line() 
ui.header("..vad vill du göra?") 
ui.line() 
ui.echo("A | Visa inköpslista") 
ui.echo("B | Lägg till vara") 
ui.echo("C | Ta bort vara") 
ui.echo("X | Stäng programmet") 
ui.line() 
ui.prompt("Val")    # finns möjlighet att göra input
Exemple #21
0
    ui.clear() #Clear call
    ui.line(False)  # printar en linje gjord utav *
    ui.header("ARTIST DATABASE")
    ui.line(True)  # printar en linje gjord utav -
    web.inspectart() #kallar på funktionen som tar fram informationen på specifika artister.
    ui.line(False)  # printar en linje gjord utav *
    ui.echo("| Press enter to return ")  # Printar våra val
    ui.line(False)  # printar en linje gjord utav *
    ui.prompt()



while True: #kör en stor while sålänge som end variabeln inte innehåller
    ui.clear() #Clear call
    ui.line(False) #printar en linje gjord utav -
    ui.header("Welcome to the Music Library") #printar en header
    ui.line(False)#printar en linje gjord utav -
    ui.line(False)#printar en linje gjord utav -
    ui.echo("| L | Lista alla Artister") #Printar våra val
    ui.echo("| V | Inspektera Artist ")#Printar våra val
    ui.echo("| E | Stäng av ")
    ui.line(False)
    choice = ui.prompt()#variable input så att du kan kalla på

    if choice == "L": #gör så att vi kan välja olika val
        alist() #kallar på functionen alist
    if choice == "V": #gör så att vi kan välja olika val.
        ainspect() #kallar på functionen ainspect
    if choice == "E":
        break
Exemple #22
0
	Usage:
        stock list_all 
		stock query_currency <code> 
		
	Options:
		-h, --help Show this screen 
		--version Show version
"""

from docopt import docopt, DocoptExit
import cmd
import stock
import click
import ui

ui.header()
ui.start()


def docopt_cmd(func):
    """
    This decorator is used to simplify the try/except block and pass the result
    of the docopt parsing to the called action
    """
    def fn(self, arg):
        try:
            opt = docopt(fn.__doc__, arg)

        except DocoptExit as e:
            # The DocoptExit is thrown when the args do not match
            # We print a message to the user and the usage block
def main():

    arguments = docopt(__doc__)

    try:

        if arguments['bulk_load']:

            load_yaml()

        else:

            #Create source objects
            if arguments['socrata']:
                source = sc.SocrataPortal(
                    arguments['<site>'], \
                    arguments['<dataset_id>'], \
                    arguments['--a'])

            if arguments['hud']:
                source = sc.HudPortal(arguments['<site>'])

            if arguments['excel']:
                source = sc.Excel(arguments['<location>'])

            if arguments['csv']:
                source = sc.Csv(arguments['<location>'])

            if arguments['shp']:
                source = sc.Shape(arguments['<location>'])

            if arguments['geojson']:
                source = sc.GeoJson(arguments['<location>'])

            if arguments['census']:
                place_mappings = {
                    '--m': 'msa',
                    '--c': 'csa',
                    '--n': 'county',
                    '--s': 'state',
                    '--p': 'placename'
                }
                for abb, place in place_mappings.items():
                    if arguments.get(abb):
                        place_type = place_mappings[abb]
                        place_arg = arguments[abb]
                        break
                if arguments['--l']:
                    level = arguments['--l']
                else:
                    level = 'tract'
                if arguments['decennial2010']:
                    source = sc.CenPy('Decennial2010', None, place_type,
                                      place_arg, level,
                                      arguments['<variables>'])
                elif arguments['acs']:
                    if arguments['--y']:
                        year = int(arguments['--y'])
                    else:
                        year = None
                    source = sc.CenPy('ACS', year, place_type, place_arg,
                                      level, [arguments['<variables>']])

            if arguments['--d']:
                source.db_name = arguments['--d']

            if arguments['--t']:
                source.tbl_name = arguments['--t']

            assert (source), "Source has not been defined."

            insert_source(source)

    except CLIError as e:
        ui.header(str(e), color='\033[91m')
Exemple #24
0
import ui
ui.line()  # i denna kod skriver vi bara ut alla funktioner vi gjort i ui.py
ui.header("Meddelande")
ui.line(True)
ui.echo("Hej Hej")
ui.echo("Hej då")
ui.line()
ui.header("Hallå")
ui.line()
ui.echo("A")
ui.echo("B")
ui.echo("C")
ui.echo("D")
ui.line()
ui.prompt("Val")
Exemple #25
0
import ui  # importerar ui och web
import web
# använder funktioner från ui
ui.line()
ui.header("ARTIST DATABASE")
ui.line()
ui.echo("Welcome to a world of")
ui.echo("Musice!")
ui.line()
ui.echo(" L | List artists")
ui.echo(" V | View artist profile")
ui.echo(" E | Exit application")
ui.line()
s = ui.prompt("Selection")
s
# urlen går genom get funktionen från web
url = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"
r = web.get(url)
# om man skriver in L
if s == "L" or s == "l":
    ui.clear()
    ui.line()
    ui.header("ARTIST DATABASE")
    ui.line()
    ui.echo("Ariana Grande")
    ui.echo("Avicii")
    ui.echo("Blink -182")
    ui.echo("Brad Paisley")
    ui.echo("Ed Sheeran")
    ui.echo("Imagine Dragons")
    ui.echo("Maroon 5")
Exemple #26
0
    parti_6.namn, parti_7.namn, parti_8.namn
]
ar = [
    parti_1p, parti_2p, parti_3p, parti_4p, parti_5p, parti_6p, parti_7p,
    parti_8p
]
# Skriver ut partiernas namn och antal röster i procent om de har mer är 4% av antalet
for f in ar:
    if f >= 4:
        ui.echo(pn[ar.index(f)] + " fick " + str(int(f)) + "%.")
# Variabel för att ta reda på vilken parti fick max röster
m = max(parti_1p, parti_2p, parti_3p, parti_4p, parti_5p, parti_6p, parti_7p,
        parti_8p)
ui.line()
# Skriver ut den parti som har max röster
ui.header("Största partiet är " + pn[ar.index(max(ar))] + " med " + str(m) +
          "%.")
# Tar reda på röster som varje block fick
s = parti_1p + parti_2p + parti_3p + parti_4p  # småpartier
o = parti_5p + parti_6p + parti_7p  # oljeblocket
i = parti_8p  # inget block
ui.line()
# Tar reda på vilket block som har max röster
if s > o and s > i:
    ui.header("Största blocket är Småpartierna med " + str(int(s)) + "%")
if o > s and o > i:
    ui.header("Största blocket är Oljeblocket med " + str(int(o)) + "%")
ui.line()
# Tar reda på vilken inriktning som har fler röster
if v > h:
    ui.header("De flesta har valt vänster med " + str(int(v)) + "%.")
elif v < h: