Exemple #1
0
 def __init__(self, file_path):
     self.file_path = file_path
     self.population_data = []
     self.json_data = []
     self.countries = Countries()
     ''' store a dictionary of each country population '''
     self.country_populations = {}
Exemple #2
0
def main(opts):
    try:
        country = format(" ", opts.country)
        city = format("_", opts.city)
        cc = Countries()
        country_code = cc.get_country(country)

        if opts.forecast:
            wf = WeatherForecast(opts.api_key)
            forecast_result = wf.forecast(city, country_code)
            show_result(forecast_result, city, country)

        if opts.hourly:
            wh = WeatherHourly(opts.api_key)
            hourly_result = wh.hourly(city, country_code)
            show_result(hourly_result, city, country)

        if opts.almanac:
            wl = WeatherAlmanac(opts.api_key)
            almanac_result = wl.almanac(city, country_code)
            print "******************** COUNTRY:" + country + " --- CITY: " + city + " ****************************"
            print "****************************** RECORDS ****************************"
            print almanac_result

        if opts.geolookup:
            print "******************** COUNTRY:" + country + " --- CITY: " + city + " ****************************"
            geo = GeoLookup(opts.api_key)
            print geo.geo(city, country_code)

    except KeyError:
        print "Some one of the values (Key, City, Country) are incorrect check and try again"
        sys.exit(-1)
    def set_aggregate_val(self, home_country: Countries, away_country: Countries, new_val):
        """Sets the aggregate value for the specified directed country pair"""
        # statement = "UPDATE " + self._agg_table_name + " SET `title_sentiment`=" + new_val + " WHERE `from`=" + home_country.get_iso_code() + " AND `to`=" + away_country.get_iso_code()
        self._cursor.execute("UPDATE " + self._agg_table_name + " SET `title_sentiment`=%s WHERE `from`=%s AND `to`=%s",
                             (new_val, home_country.get_iso_code(), away_country.get_iso_code()))

        # self._cursor.execute(statement)
        self._db.commit()
Exemple #4
0
def countriesPage():
    page = Countries(dsn = app.config['dsn'])
    if request.method == 'GET':
        page.createTable();
        return page.loadPage()
    elif 'addCountry' in request.form:
        name = request.form['name']
        abbreviation = request.form['abbreviation']
        continent = request.form['continent']
        return page.addCountry(name, abbreviation, continent)
    elif 'initTable' in request.form:
        return page.initTable()
    elif 'updateCountry' in request.form:
        name = request.form['name']
        newName = request.form['newName']
        abbreviation = request.form['abbreviation']
        continent = request.form['continent']
        return page.updateCountry(name, newName, abbreviation, continent)
    elif 'deleteCountry' in request.form:
        name = request.form['name']
        return page.deleteCountryName(name)
    elif 'searchCountry' in request.form:
        name = request.form['name']
        abbreviation = request.form['abbreviation']
        continent = request.form['continent']
        return page.searchCountry(name, abbreviation, continent)
Exemple #5
0
 def _make_resource(cls, folder, name, *args, **kw):
     root = ShopFolder._make_resource(cls, folder, name, **kw)
     # Payments module
     cls.payments_class._make_resource(cls.payments_class, folder,
                             '%s/payments' % name,
                             title={'en': u'Payment module'})
     # Modules
     Modules._make_resource(Modules, folder,
                   '%s/modules' % name, title={'en': u'Modules'})
     # Suppliers
     Suppliers._make_resource(Suppliers, folder,
                   '%s/suppliers' % name, title={'en': u'Suppliers'})
     # Customers
     Customers._make_resource(Customers, folder,
                   '%s/customers' % name, title={'en': u'Customers'})
     # Product Models
     ProductModels._make_resource(ProductModels, folder, '%s/products-models' % name,
                                 title={'en': u'Product Models'})
     # Orders
     Orders._make_resource(Orders, folder, '%s/orders' % name,
                           title={'en': u'Orders'})
     # ShopUser_Groups
     ShopUser_Groups._make_resource(ShopUser_Groups, folder, '%s/groups' % name,
                                     title={'en': u'User groups'})
     # Addresses
     Addresses._make_resource(Addresses, folder, '%s/addresses' % name,
                              title={'en': u'Addresses'})
     # Countries
     Countries._make_resource(Countries, folder, '%s/countries' % name,
                              title={'en': u'countries'})
     # Countries zone
     CountriesZones._make_resource(CountriesZones, folder,
             '%s/countries-zones' % name, title={'en': u'Countries Zones'})
     # EnumeratesFolder
     EnumeratesFolder._make_resource(EnumeratesFolder, folder,
                                 '%s/enumerates' % name, title={'en': u'Enumerates'})
     # Shipping
     Shippings._make_resource(Shippings, folder, '%s/shippings' % name,
                              title={'en': u'Shipping'})
     # Conditions of users
     WebPage._make_resource(WebPage, folder, '%s/terms-and-conditions-of-use' % name,
                             **{'title': {'fr': u'Conditions Générales de ventes',
                                          'en': u'Terms and conditions of user'},
                                'state': 'public'})
     # Default cross Selling configuration
     CrossSellingTable._make_resource(CrossSellingTable, folder,
                                      '%s/cross-selling' % name,
                                      title={'en': u'Cross selling'})
     # Taxes
     Taxes_TableResource._make_resource(Taxes_TableResource, folder, '%s/taxes' % name,
                             **{'title': {'fr': u'TVA',
                                          'en': u'Taxes'}})
     table = Taxes_TableHandler()
     table.add_record({'value': '19.6'})
     folder.set_handler('%s/taxes' % name, table)
Exemple #6
0
class CountriesTest(unittest.TestCase):

    def setUp(self):
        self.countries_pt = Countries('pt')
        self.countries_en = Countries('en')

    def test_get_localized_list(self):
        self.assertEqual(self.countries_pt['BR'], 'Brasil')
        self.assertEqual(self.countries_pt['CX'], 'Ilha do Natal')
        self.assertEqual(self.countries_en['BR'], 'Brazil')
        self.assertEqual(self.countries_en['CX'], 'Christmas Island')

    def test_get_unknown_country(self):
        with self.assertRaises(KeyError):
            self.countries_pt['kk']

    def test_iteration(self):
        for code in self.countries_pt:
            self.assertEqual(code, 'AF')
            break

    def test_unpacking_iteration(self):
        for code, country in self.countries_pt.items():
            self.assertEqual(code, 'AF')
            self.assertEqual(country, u'Afeganistão')
            break

    def test_contains(self):
        self.assertTrue('BR' in self.countries_pt)
        self.assertFalse('KK' in self.countries_pt)



#TODO:
# given the country name, return its code
    def get_aggregate_val(self, home_country: Countries, away_country: Countries):
        statement = "SELECT * FROM " + self._agg_table_name + " WHERE `from`='" + home_country.get_iso_code() + "' AND `to`='" + away_country.get_iso_code() + "'"

        self._cursor.execute(statement)
        result = self._cursor.fetchall()
        if len(result) == 1:
            return result[0]
        return None
Exemple #8
0
	def __init__(self, input):
		continent = ''
		if input.has_key('continent'):
			continent = input['continent'].lower()
			del input['continent']
		countries = Countries.byContinent(continent)
		self.country_urls = [(country, Query._country_url % country['code'].lower() if country['code'] else '') for country in countries]
		# TODO make strategy_name and parameters separate parts of query
		for key in input:
			self.strategy_name = key
			self.parameters = input[key]
Exemple #9
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    msg_resp = MessagingResponse()
    msg = msg_resp.message()
    print(incoming_msg)
    countries = [c for c in Countries.values() if c in incoming_msg]

    print('Countries: {}'.format(countries))
    if 'help' in incoming_msg:
        msg.body(get_help_string())
    elif 'north korea' in incoming_msg:
        msg.body('North korea is a black box baby')
    elif len(countries) == 0:
        query_url = base_url + '/all'
        resp = requests.get(query_url)
        print(resp.content)
        if resp.status_code == 200 and b'not found' not in resp.content:
            print(resp.content)
            stats_str, _ = get_stats(resp)
            msg.body("World stats of COVID-19 as of now:\n" + stats_str)
        else:
            msg.body(
                "No data found for the given input. Might be a server error\n"
                + get_help_string())
    else:
        ret_string = ''
        count = 0
        raw_entries = []
        for country in countries:
            resp = requests.get(base_url + '/countries/{}'.format(country))
            print(resp.content)
            if resp.status_code == 200 and b'not found' not in resp.content:
                count += 1
                stats_str, raw = get_stats(resp)
                raw_entries.append(raw)
                ret_string += "COVID-19 statistics of {} as of now:\n".format(
                    country.capitalize()) + stats_str
        if 'compare' in incoming_msg:
            if len(countries) != 2:
                ret_string = 'To compare countries, you should give two country names.\n' \
                             'Given countries are {}'.format(', '.join(countries))
            else:
                comparison_str = _compare(countries[0], countries[1],
                                          raw_entries[0], raw_entries[1])
                ret_string += comparison_str

        if count != 0:
            msg.body(ret_string)
        else:
            msg.body(
                "No data found for the given string. Might be a server error\n"
                + get_help_string())
    return str(msg_resp)
Exemple #10
0
    def __init__(self, parent=None):
        super(CountrySelector, self).__init__(parent)
        ui = Ui_CountrySelector()
        ui.setupUi(self)
        self.ui = ui

        self.countries = Countries()
        self.codes = sorted(self.countries['iso2c'])

        index = self.codes.index("NZ")

        ui.cmbCode.addItems(self.codes)
        ui.cmbCode.setCurrentIndex(index)

        self._on_selection(index)
        ui.cmbCode.currentIndexChanged.connect(self._on_selection)

        self.adjustSize()
Exemple #11
0
def _io_countries(mplot, density_per_country, country):
    color_per_country = _get_color_per_country(density_per_country)
    all_countries = Countries()
    for c in all_countries.countries:
        i_plastic = [
            i for i, s in enumerate(country) if s == c.attributes['SUBUNIT']
        ]
        if len(i_plastic) is not 0:
            c_color = color_per_country[i_plastic[0]]
            mplot.country(c, c_color)
            for i, small_island in enumerate(small_islands):
                if small_island == c.attributes['SUBUNIT']:
                    mplot.points(small_islands_lon[i],
                                 small_islands_lat[i],
                                 marker='o',
                                 facecolor=c_color,
                                 markersize=10)
        else:
            mplot.country(c, 'w')
Exemple #12
0
                hospital_beds=100,
                quarantine_rate=0,
                mean_quarantine=2,
                name='Belgium',
                travel_time=5)

EST = Population(persons_dict['8'],
                 shape9,
                 hospital_factor=0.05,
                 hospital_beds=1000,
                 quarantine_rate=0,
                 mean_quarantine=2,
                 name='Estonia',
                 travel_time=5)

cont = Countries([ES, DE, SE, FR, DK, CH, IT, BE, EST], travels=True)

# Plot interactions
#steps = 600
cont.interact(steps=800, plot=True, save=False)

for population in cont.populations:
    plt.figure()

    plt.bar(list(population.dead_age.keys()),
            population.dead_age.values(),
            color='g')
    plt.show()

    plt.figure()
Exemple #13
0
 def _make_resource(cls, folder, name, *args, **kw):
     root = ShopFolder._make_resource(cls, folder, name, **kw)
     # Payments module
     cls.payments_class._make_resource(cls.payments_class,
                                       folder,
                                       '%s/payments' % name,
                                       title={'en': u'Payment module'})
     # Modules
     Modules._make_resource(Modules,
                            folder,
                            '%s/modules' % name,
                            title={'en': u'Modules'})
     # Suppliers
     Suppliers._make_resource(Suppliers,
                              folder,
                              '%s/suppliers' % name,
                              title={'en': u'Suppliers'})
     # Customers
     Customers._make_resource(Customers,
                              folder,
                              '%s/customers' % name,
                              title={'en': u'Customers'})
     # Product Models
     ProductModels._make_resource(ProductModels,
                                  folder,
                                  '%s/products-models' % name,
                                  title={'en': u'Product Models'})
     # Orders
     Orders._make_resource(Orders,
                           folder,
                           '%s/orders' % name,
                           title={'en': u'Orders'})
     # ShopUser_Groups
     ShopUser_Groups._make_resource(ShopUser_Groups,
                                    folder,
                                    '%s/groups' % name,
                                    title={'en': u'User groups'})
     # Addresses
     Addresses._make_resource(Addresses,
                              folder,
                              '%s/addresses' % name,
                              title={'en': u'Addresses'})
     # Countries
     Countries._make_resource(Countries,
                              folder,
                              '%s/countries' % name,
                              title={'en': u'countries'})
     # Countries zone
     CountriesZones._make_resource(CountriesZones,
                                   folder,
                                   '%s/countries-zones' % name,
                                   title={'en': u'Countries Zones'})
     # EnumeratesFolder
     EnumeratesFolder._make_resource(EnumeratesFolder,
                                     folder,
                                     '%s/enumerates' % name,
                                     title={'en': u'Enumerates'})
     # Shipping
     Shippings._make_resource(Shippings,
                              folder,
                              '%s/shippings' % name,
                              title={'en': u'Shipping'})
     # Conditions of users
     WebPage._make_resource(
         WebPage, folder, '%s/terms-and-conditions-of-use' % name, **{
             'title': {
                 'fr': u'Conditions Générales de ventes',
                 'en': u'Terms and conditions of user'
             },
             'state': 'public'
         })
     # Default cross Selling configuration
     CrossSellingTable._make_resource(CrossSellingTable,
                                      folder,
                                      '%s/cross-selling' % name,
                                      title={'en': u'Cross selling'})
     # Taxes
     Taxes_TableResource._make_resource(
         Taxes_TableResource, folder, '%s/taxes' % name,
         **{'title': {
             'fr': u'TVA',
             'en': u'Taxes'
         }})
     table = Taxes_TableHandler()
     table.add_record({'value': '19.6'})
     folder.set_handler('%s/taxes' % name, table)
Exemple #14
0
 def setUp(self):
     self.countries_pt = Countries('pt')
     self.countries_en = Countries('en')
Exemple #15
0
from cities import City

from users import User

from travels import Travels, Travel

from votes import Vote

from login import Login

cors = CORS(allow_origins_list=['http://localhost:9000'])

api = falcon.API(middleware=[cors.middleware])

api.add_route('/countries', Countries())

api.add_route('/country/{country}', Country())

api.add_route('/country/{country}/city/{city}', City())

api.add_route('/users/{query}', User())

api.add_route('/travel', Travel())

api.add_route('/travels', Travels())

api.add_route('/travel/vote', Vote())

api.add_route('/login', Login())
 def _get_directed_table_name(self, home_country: Countries, away_country: Countries):
     return "{}_to_{}".format(home_country.get_iso_code(), away_country.get_iso_code())
Exemple #17
0
class Populations:
    def __init__(self, file_path):
        self.file_path = file_path
        self.population_data = []
        self.json_data = []
        self.countries = Countries()
        ''' store a dictionary of each country population '''
        self.country_populations = {}

    def get_category(self, population):
        ''' return a category associated with the magnitude
        of a country's population. Note that the world display categories
        are partitioned into populations of under 10 million, under 100 million,
        under a billion, and over a billion. '''
        if population >= 1000000000:
            return 0
        elif population >= 100000000:
            return 1
        elif population >= 10000000:
            return 2
        else:
            return 3

    def get_contents(self):
        ''' get the contents of the loaded data, with
         country and population separated by colon '''
        for population_dictionary in self.json_data:
            if population_dictionary["Year"] == "2010":
                country_name = population_dictionary["Country Name"]
                population = int(float(population_dictionary["Value"]))
                category = self.get_category(population)
                country_code = self.countries.get_code(country_name)
                if country_code:
                    print(country_code + ": " + str(population))
                    self.country_populations[country_code] = (population,
                                                              category)
                else:
                    print("ERROR: " + country_name)
                self.population_data.append(country_name + " : " +
                                            str(population))
        return self.population_data

    def load_contents(self):
        ''' load the contents of the json information
        into a list and print the population for each country '''
        with open(self.file_path) as open_file:
            self.json_data = json.load(open_file)

    def render_contents(self):
        ''' map the population values in accordance with population.
        the 2-tuple values of country populations contains a value representing the
        population category for each country'''
        world_map_style = RotateStyle("#336699")
        world_map = pygal.maps.world.World(style=world_map_style,
                                           base_style=LightColorizedStyle)
        world_map.title = "World Population in 2010, by Country"
        world_map.add("0-10 million", {
            k: v[0]
            for k, v in self.country_populations.items() if v[1] == 3
        })
        world_map.add("10 million - 100 million", {
            k: v[0]
            for k, v in self.country_populations.items() if v[1] == 2
        })
        world_map.add("Over 100 million", {
            k: v[0]
            for k, v in self.country_populations.items() if v[1] == 1
        })
        world_map.add("Over a billion", {
            k: v[0]
            for k, v in self.country_populations.items() if v[1] == 0
        })

        world_map.render_to_file("world_population.svg")
Exemple #18
0
        for row in rows:
            if row[1] != "pg_stat_statements":
                cursor.execute("drop table " + row[1] + " cascade")

        connection.commit()
    return redirect(url_for('create_tables'))


if __name__ == '__main__':
    '''Container objects'''

    app.coaches = Coaches2(app)
    app.coaching = Coaching2(app)
    app.teams = Teams(app)
    app.players = Players(app)
    app.countries = Countries(app)
    app.leagues = Leagues(app)
    app.stadiums = Stadiums(app)
    app.officials = Officials(app)
    app.seasons = Seasons2(app)
    app.matches = Matches(app)
    app.statisticsTeam = StatisticsT(app)
    app.statisticsPlayer = StatisticsP(app)
    app.fixtures = Fixtures(app)
    app.squads = Squads(app)
    app.transfers = Transfers(app)

    VCAP_APP_PORT = os.getenv('VCAP_APP_PORT')
    if VCAP_APP_PORT is not None:
        port, debug = int(VCAP_APP_PORT), False
    else: