Ejemplo n.º 1
0
def ea(day=None):
    earthquakes = []
    file_day = None

    # Returns yesterday if day is defined
    if day is None:
        day = date.today() - timedelta(days=1)
    else:
        day = datetime.strptime(day, "%Y-%m-%d")

    ea_file = os.path.join(Earthquake.data_folder, 'earthquakes_%s' % day.strftime("%Y-%m-%d"))

    if not os.path.exists(ea_file):
        try:
            Earthquake.get_daily_earthquakes(day.strftime("%Y-%m-%d"))
        except:
            pass

    if os.path.exists(ea_file):
        with open(ea_file) as f:
            earthquake_file_content = f.readlines() or None
        
        # Create objects
        for line in earthquake_file_content[1:]:
            earthquakes.append(Earthquake(line.split(',')))

    return template('index', earthquakes=earthquakes, day=day.strftime("%A %d %B %Y").capitalize())
Ejemplo n.º 2
0
def ea(day=None):
    earthquakes = []
    file_day = None

    # Returns yesterday if day is defined
    if day is None:
        day = date.today() - timedelta(days=1)
    else:
        day = datetime.strptime(day, "%Y-%m-%d")

    ea_file = os.path.join(Earthquake.data_folder,
                           'earthquakes_%s' % day.strftime("%Y-%m-%d"))

    if not os.path.exists(ea_file):
        try:
            Earthquake.get_daily_earthquakes(day.strftime("%Y-%m-%d"))
        except:
            pass

    if os.path.exists(ea_file):
        with open(ea_file) as f:
            earthquake_file_content = f.readlines() or None

        # Create objects
        for line in earthquake_file_content[1:]:
            earthquakes.append(Earthquake(line.split(',')))

    return template('index',
                    earthquakes=earthquakes,
                    day=day.strftime("%A %d %B %Y").capitalize())
Ejemplo n.º 3
0
def calculate():

    earthquake = Earthquake(seismic_events_list)
    coord, magnitude = earthquake.calculate_epicenter()

    magnitude = f"{magnitude:.2f}"
    print("Earthquake magnitude: %s" % magnitude)
    print("Coordinates of epicenter (lat,lon): %s" % (coord, ))

    return jsonify(status='success', lat=coord[0], lon=coord[1])
Ejemplo n.º 4
0
def update_list():
    for i in range(0, length):
        identifier = i
        magnitude = data['features'][i]['properties']['mag']
        place = data['features'][i]['properties']['place']
        longitude = data['features'][i]['geometry']['coordinates'][0]
        latitude = data['features'][i]['geometry']['coordinates'][1]
        earthquake_time = data['features'][i]['properties']['time']
        depth = data['features'][i]['geometry']['coordinates'][2]
        new_earthquake = Earthquake(identifier, magnitude, place, longitude,
                                    latitude, earthquake_time, depth)
        earthquake_list[i] = new_earthquake
Ejemplo n.º 5
0
def run():
    events = getEvents()
    eventList = []

    for event in events:
        seismicEvent = SeismicEvent(event['name'], event['coord'],
                                    event['ptime'], event['stime'],
                                    event['max_amp'])
        # seismicEvent.report()
        eventList.append(seismicEvent)
        print(f"STATION: %s , MAGNITUDE : {seismicEvent.magnitude:0.2f}" %
              seismicEvent.name)

    # tic = time.perf_counter()
    earthquake = Earthquake(eventList)
    coord, magnitude = earthquake.calculate_epicenter()
    # toc = time.perf_counter()

    magnitude = f"{magnitude:.2f}"

    print("Earthquake magnitude: %s" % magnitude)
    print("Coordinates of epicenter (lat,lon): %s" % (coord, ))
def parse_listing(listing):
    """ Return Earthquake object """

    db_id = listing["id"]
    properties = listing["properties"]

    title = properties["title"]
    magnitude = properties["mag"]

    raw_time = properties["time"] // 1000  # integer div by 1000 because it's in ms
    timestamp = datetime.utcfromtimestamp(raw_time)

    location = listing["geometry"]["coordinates"]
    latitude = location[1]
    longitude = location[0]
    depth = location[2]

    new_quake = Earthquake(db_id, title, magnitude, timestamp, latitude, longitude, depth)
    return new_quake
Ejemplo n.º 7
0
def find_nearest(latitude, longitude, distance):
    # Create SQL cursor.
    cur = mysql.connect.cursor()

    # Euclidean distance b/w two points.
    # p = (p1, p2) ; q = (q1, q2)
    # d = sqrt((q1-p1)^2 + (q2-p2)^2)
    # d_sqrd = distance * distance

    last_month = datetime.datetime.now(
    ) - dateutil.relativedelta.relativedelta(months=3)
    last_month_first_date = last_month.replace(day=1)
    date = last_month_first_date.strftime("%Y-%m-%d")
    date_format = "%%Y-%%m-%%d"
    print(date)

    query = "SELECT id, title, mag, timestamp, latitude, longitude, depth \
            FROM earthquakes WHERE \
            POW(longitude-%s, 2) + POW(latitude-%s, 2) <= 1 \
            AND timestamp >= STR_TO_DATE(%s, '%%Y-%%m-%%d')"

    print(query)
    cur.execute(query, (longitude, latitude, date))
    results = cur.fetchall()
    logging.info(results)
    cur.close()

    # Create an array of all the earthquake occurrences.
    print("here!")
    occurences = []
    for occ in results:
        # [TODO] added a temp ID.
        print(occ[6])
        occurences.append(
            Earthquake(occ[0], occ[1], occ[2], occ[3], occ[4], occ[5], occ[6]))

    cur.close()

    # Returns an array of Earthquakes.
    return occurences
Ejemplo n.º 8
0
        for row in reader:

            event_type = row[14].strip()

            if event_type != EVENT_TYPE:
                continue

            magnitude = Decimal(row[4].strip())
            location_source = row[20].strip()
            occurred = convert_datetime(row[0].strip(),
                                        target_format='%Y-%m-%d',
                                        target_tz=TARGET_TZ)

            eq = Earthquake(date_occurred=occurred,
                            magnitude=magnitude,
                            event_type=event_type,
                            location_source=location_source)

            location_counts[eq.location_source] += 1
            date_counts[eq.date_occurred] += 1
            total_magnitudes[eq.location_source] += magnitude

            location_magnitudes[eq.location_source] = (
                total_magnitudes[eq.location_source] /
                location_counts[eq.location_source])

            # Question 4. Simulate callback being invoked
            AverageMagnitude.callback(row)

    if location_counts:
        out = 'Which location source had the most %s(s)?: %s' % (
Ejemplo n.º 9
0
# File for inserting data into the database manually

from earthquake import Earthquake
from app import db

# Create earthquakes
first_earthquake = Earthquake("Colombia", "Bogota", "29/01/2020", "16:04", 4.0)
second_earthquake = Earthquake("Ecuador", "Guayaquil", "30/01/2020", "08:48", 5.4)
third_earthquake = Earthquake("Italy", "Rome", "30/01/2020", "08:51", 7.5)


# Persist data
db.session.add(first_earthquake)
db.session.add(second_earthquake)
db.session.add(third_earthquake)

# Commit and close session
db.session.commit()
db.session.close()
Ejemplo n.º 10
0
def post_earthquake(data):
    new_earthquake = Earthquake(data['country'], data['city'], data['date'], data['time'], data['magnitude'])
    db.session.add(new_earthquake)
    db.session.commit()
    return EarthquakeSchema().dump(new_earthquake)
ca_file = creds.ca_file
cert_file = creds.cert_file
key_file = creds.key_file

# instantiate a kafka producer connection
producer = KafkaProducer(
    bootstrap_servers=bootstrap_server,
    security_protocol="SSL",
    ssl_cafile=ca_file,
    ssl_certfile=cert_file,
    ssl_keyfile=key_file,
    value_serializer=lambda m: json.dumps(m).encode('utf-8'))

# Instantiate an instance of Earthquake
quake = Earthquake(
    20
)  # after the initial grab, will wait 30 minutes between requests for new data. Earthquakes don't happen all that frequently - thankfully

# As per: https://github.com/aiven/aiven-kafka-connect-jdbc/blob/master/docs/sink-connector.md I need to set up schema info in the JSON
earthquake_db_schema = {
    "type":
    "struct",
    "fields": [{
        "field": "id",
        "type": "string",
        "optional": False
    }, {
        "field": "mag",
        "type": "float",
        "optional": False
    }, {
Ejemplo n.º 12
0
                            'endtime': user_endtime,
                            'latitude': user_latitude,
                            'longitude': user_longitude,
                            'maxradiuskm': user_maxradiuskm,
                            'minmagnitude': user_minmagnitude,
                        })

data = response.json()
count = 0
range_value = data['metadata']['count']
lst_of_earthquakes = []
for _ in range(range_value):
    place = data['features'][count]['properties']['place']
    date = data['features'][count]['properties']['time']
    magnitude = data['features'][count]['properties']['mag']
    earthquake = Earthquake(place, date, magnitude)
    lst_of_earthquakes.append(earthquake)
    count += 1

answer = input('Отсортировать по магнитуде или по времени? [M/T] ').lower()
if answer == 'm':
    lst_of_earthquakes.sort(key=lambda x: x.magnitude, reverse=True)
elif answer == 't':
    lst_of_earthquakes.sort(key=lambda x: x.date, reverse=True)

count = 1
place = colored(' место: ', 'green', attrs=['bold'])
date = colored('Дата: ', 'cyan', attrs=['bold'])
magnitude = colored('Магнитуда: ', 'yellow', attrs=['bold'])
for obj in lst_of_earthquakes:
    colored_count = colored(str(count), 'green', attrs=['bold'])