<commit_before>#!/usr/bin/env python3
"""This is a small program for monitoring observations and alerting a maintainer
if observations are not received within a specified time."""

import argparse
import configparser
import smtplib
import ssl
import sys
from datetime import datetime
from email.mime.text import MIMEText
from os.path import exists

import psycopg2


def get_latest_obs_time(config):
    """Returns the recording time latest observation."""
    with psycopg2.connect(host=config['Host'], database=config['Database'],
                          user=config['User'], password=config['Password']) as conn:
        with conn.cursor() as cursor:
            cursor.execute('SELECT recorded FROM observations ORDER BY id DESC LIMIT 1')
            return cursor.fetchone()[0]


def send_email(config, subject, message):
    """Sends an email with provided subject and message to specified recipients."""
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = config['Sender']
    msg['To'] = config['Recipient']

    context = ssl.create_default_context()
    try:
        server = smtplib.SMTP_SSL(config['Server'],
                                  port=465, context=context)
        server.login(config['User'], config['Password'])
        server.send_message(msg)
        server.quit()
    except smtplib.SMTPException as smtp_e:
        print('Failed to send email with subject "{}": {}'
              .format(subject, str(smtp_e)), file=sys.stderr)
        return False

    return True


def check_obs_time(config, last_obs_time):
    """Check last observation time and send an email if the threshold is
    exceeded. Returns 'True' when an email is sent and 'False' otherwise."""
    time_diff = datetime.now(tz=last_obs_time.tzinfo) - last_obs_time
    if int(time_diff.seconds / 60) > int(config['monitor']['Threshold']):
        if config['monitor']['EmailSent'] == 'False':
            if send_email(config['email'],
                          'env-logger inactivity warning',
                          'No observations have been received in the env-logger backend after {}.'
                          'Consider checking possible problems.'
                          .format(last_obs_time.isoformat())):
                return 'True'
            else:
                return 'False'
        else:
            return 'True'
    else:
        if config['monitor']['EmailSent'] == 'True':
            send_email(config['email'], 'env-logger back online',
                       'env-logger is back online at {}.'
                       .format(datetime.now().isoformat()))
        return 'False'

<commit_msg>Simplify observation monitor return value handling<commit_after>#!/usr/bin/env python3
"""This is a small program for monitoring observations and alerting a maintainer
if observations are not received within a specified time."""

import argparse
import configparser
import smtplib
import ssl
import sys
from datetime import datetime
from email.mime.text import MIMEText
from os.path import exists

import psycopg2


def get_latest_obs_time(config):
    """Returns the recording time latest observation."""
    with psycopg2.connect(host=config['Host'], database=config['Database'],
                          user=config['User'], password=config['Password']) as conn:
        with conn.cursor() as cursor:
            cursor.execute('SELECT recorded FROM observations ORDER BY id DESC LIMIT 1')
            return cursor.fetchone()[0]


def send_email(config, subject, message):
    """Sends an email with provided subject and message to specified recipients."""
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = config['Sender']
    msg['To'] = config['Recipient']

    context = ssl.create_default_context()
    try:
        server = smtplib.SMTP_SSL(config['Server'],
                                  port=465, context=context)
        server.login(config['User'], config['Password'])
        server.send_message(msg)
        server.quit()
    except smtplib.SMTPException as smtp_e:
        print('Failed to send email with subject "{}": {}'
              .format(subject, str(smtp_e)), file=sys.stderr)
        return False

    return True


def check_obs_time(config, last_obs_time):
    """Check last observation time and send an email if the threshold is
    exceeded. Returns 'True' when an email is sent and 'False' otherwise."""
    time_diff = datetime.now(tz=last_obs_time.tzinfo) - last_obs_time
    if int(time_diff.seconds / 60) > int(config['monitor']['Threshold']):
        if config['monitor']['EmailSent'] == 'False':
            return str(send_email(config['email'],
                                  'env-logger inactivity warning',
                                  'No observations have been received in the env-logger '
                                  'backend after {}. Consider checking possible problems.'
                                  .format(last_obs_time.isoformat())))
        return str(True)
    else:
        if config['monitor']['EmailSent'] == 'True':
            send_email(config['email'], 'env-logger back online',
                       'env-logger is back online at {}.'
                       .format(datetime.now().isoformat()))
        return str(False)


{'fraction_non_alphanumeric': 0.11005872324303845, 'fraction_numerical': 0.003788596325061565, 'mean_word_length': 2.5460040295500335, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3181978', 'n_tokens_mistral': 1388, 'n_tokens_neox': 1349, 'n_words': 417}