def test_get_default():
    value = 42
    assert get_default(value, 1, int) == value
    assert get_default(value, 'hello', str) == 'hello'
    assert isinstance(get_default(value, 1, int), int)
    assert isinstance(get_default(value, 'hello', str), str)
    assert get_default('...', 42, str) == 42
    assert get_default('---', 42, str, na_value='---') == 42
    assert isinstance(get_default('---', 42, str, na_value='---'), int)
Exemple #2
0
def test_detail_scatter_fix(fig, SCdata):
    """This test is to confirm the plt.scatter() fix continues to work.

    Error changed to Index error in matplotlib#11383"""
    from utils import get_default
    ax = fig.add_subplot(111)
    star = "Kepler-617"
    df, _ = SCdata
    df0 = df[df.Star == star]
    df = df.sample(5)
    df.append([df0])
    teffs = df["teff"].values
    for teff in teffs:
        color = get_default(teff, 5777, float)
        with pytest.raises((TypeError, IndexError)):
            ax.scatter([0], [1], c=color)

        # This checks that the new version with color in [] does not raise an error.
        ax.scatter([0], [1], c=[color])
Exemple #3
0
def detail_plot(df, tlow, thigh):

    hz1 = get_default(df['hz1'].values[0], -2, float)
    hz2 = get_default(df['hz2'].values[0], -1, float)
    color = get_default(df['teff'].values[0], 5777, float)
    tlow = get_default(max(2500, tlow), 2500, int)
    thigh = get_default(min(8500, thigh), 8500, int)

    R = df.iloc[0]['radius']
    r = [
        planetary_radius(mi, ri)
        for mi, ri in df.loc[:, ['plMass', 'plRadius']].values
    ]
    smas = df['sma'].values
    max_smas = max(smai for smai in smas
                   if isinstance(smai, (int, float)) and not np.isnan(smai))

    Rs = max(500, 500 * R)
    rs = [max(80, 30 * ri) for ri in r]

    fig, ax = plt.subplots(1, figsize=(14, 2))
    ax.scatter([0], [1],
               s=Rs,
               c=[color],
               vmin=tlow,
               vmax=thigh,
               cmap=cm.autumn)
    no_sma = []

    if 0 < hz1 < hz2:
        x = np.linspace(hz1, hz2, 10)
        y = np.linspace(0.9, 1.1, 10)
        z = np.array([[xi] * 10 for xi in x[::-1]]).T
        plt.contourf(x, y, z, 300, alpha=0.8, cmap=cm.summer)

    for i, sma in enumerate(smas):
        if np.isnan(sma):
            no_sma.append('{} has no SMA'.format(df['plName'].values[i]))
            continue
        if sma < hz1:
            dist = hz1 - sma
            ax.scatter(sma, [1],
                       s=rs[i],
                       c=[dist],
                       vmin=0,
                       vmax=hz1,
                       cmap=cm.autumn)
        elif hz1 <= sma <= hz2:
            ax.scatter(sma, [1], s=rs[i], c='k', alpha=0.8)
        else:
            dist = sma - hz2
            ax.scatter(sma, [1],
                       s=rs[i],
                       c=[dist],
                       vmin=hz2,
                       vmax=max_smas,
                       cmap=cm.winter_r)

    for planet in ss_planets.keys():
        s = ss_planets[planet][0]
        r = 30 * ss_planets[planet][1] / 2.
        r /= float(ss_planets['Jupiter'][1])
        ax.scatter(s, [0.95], s=r * 10, c='g')
        ax.text(s - 0.01, 0.97, planet, color='white')

    ax.set_xlim(0.0, max_smas * 1.2)
    ax.set_ylim(0.9, 1.1)
    ax.set_xlabel('Semi-major axis [AU]')
    ax.yaxis.set_major_formatter(plt.NullFormatter())
    ax.set_yticks([])
    ax.spines['left'].set_visible(False)
    ax.set_facecolor('black')
    plt.tight_layout()

    for i, text in enumerate(no_sma):
        ax.text(max_smas * 0.8, 1.05 - i * 0.02, text, color='white')

    return fig_to_html(fig)
Exemple #4
0
import logging
import utils

DEFAULT = utils.get_default()
class MonitorLog(object):
    def __init__(self):
        self.log_path = DEFAULT['monitor_log']
        self.log_level = logging.DEBUG
        self.logger = logging.getLogger('MonitorLog')
        self.logger.setLevel(self.log_level)
        self.fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s","%Y-%m-%d %H:%M:%S")
    def file_log(self):
        fh = logging.FileHandler(self.log_path)
        fh.setLevel(self.log_level)
        fh.setFormatter(self.fmt)
        self.logger.addHandler(fh)
        return fh.stream,self.logger
    def stream_log(self):
        ch = logging.StreamHandler()
        ch.setLevel(self.log_level)
        ch.setFormatter(self.fmt)
        self.logger.addHandler(ch)
        return self.logger
   
monitor_obj = MonitorLog()
STREAM,FILE_LOG = monitor_obj.file_log()
STREAM_LOG = monitor_obj.stream_log()

if __name__ == '__main__':
    STREAM_LOG.info("info")
    STREAM_LOG.debug("debug")
Exemple #5
0
def detail_plot(df, tlow, thigh):

    hz1 = get_default(df['datetime'].values[0], -2, float)
    hz2 = get_default(df['outcome_datetime'].values[0], -1, float)
    color = get_default(df['los'].values[0], 5777, float)
    tlow = get_default(max(2500, tlow), 2500, int)
    thigh = get_default(min(8500, thigh), 8500, int)

    R = df.iloc[0]['los']
    r = [ri for ri in df.loc[:, ['los']].values]
    LOSs = df['los'].values
    max_LOSs = max([
        losi for losi in LOSs
        if isinstance(losi, (int, float)) and not np.isnan(losi)
    ])
    Rs = max(500, 500 * R)
    rs = [max(80, 30 * ri) for ri in r]

    fig, ax = plt.subplots(1, figsize=(14, 2))
    ax.scatter([0], [1],
               s=Rs,
               c=[color],
               vmin=tlow,
               vmax=thigh,
               cmap=cm.autumn)
    no_los = []

    if 0 < hz1 < hz2:
        x = np.linspace(hz1, hz2, 10)
        y = np.linspace(0.9, 1.1, 10)
        z = np.array([[xi] * 10 for xi in x[::-1]]).T
        plt.contourf(x, y, z, 300, alpha=0.8, cmap=cm.summer)

    for i, los in enumerate(LOSs):
        if np.isnan(los):
            no_los.append('{} has no LOS'.format(df['plName'].values[i]))
            continue
        if los < hz1:
            dist = hz1 - los
            ax.scatter(los, [1],
                       s=rs[i],
                       c=[dist],
                       vmin=0,
                       vmax=hz1,
                       cmap=cm.autumn)
        elif hz1 <= los <= hz2:
            ax.scatter(los, [1], s=rs[i], c='k', alpha=0.8)
        else:
            dist = los - hz2
            ax.scatter(los, [1],
                       s=rs[i],
                       c=[dist],
                       vmin=hz2,
                       vmax=max_LOSs,
                       cmap=cm.winter_r)

    for intake in ss_intake.keys():
        s = ss_intake[intake][0]
        r = 30 * ss_intake[intake][1] / 2.
        r /= float(ss_intake['Jupiter'][1])
        ax.scatter(s, [0.95], s=r * 10, c='g')
        ax.text(s - 0.01, 0.97, intake, color='white')

    ax.set_xlim(0.0, max_LOSs * 1.2)
    ax.set_ylim(0.9, 1.1)
    ax.set_xlabel('Date')
    ax.yaxis.set_major_formatter(plt.NullFormatter())
    ax.set_yticks([])
    ax.spines['left'].set_visible(False)
    # ax.set_facecolor('black')
    plt.tight_layout()

    for i, text in enumerate(no_los):
        ax.text(max_LOSs * 0.8, 1.05 - i * 0.02, text, color='white')

    return fig_to_html(fig)
Exemple #6
0
def add_action(n_clicks_add, n_clicks_delete, monitoring_dropdown_value,
               restriction_dropdown_value, administration_dropdown_value,
               new_data, data, selected_rows):
    ctx = dash.callback_context
    triggered_component = ctx.triggered[0]['prop_id'].split('.')[0]

    if monitoring_dropdown_value == 'Weighing':
        data = action.Weighing.fetch(as_dict=True)
        columns = [{"name": i, "id": i} for i in action.Weighing.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.Weighing, c['id'])
            for c in columns
        }]

    elif monitoring_dropdown_value == 'HealthStatus':
        data = action.Weighing.HealthStatus.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in action.Weighing.HealthStatus.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.Weighing.HealthStatus, c['id'])
            for c in columns
        }]

    elif restriction_dropdown_value == 'WaterRestriction':
        data = action.WaterRestriction.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in action.WaterRestriction.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.WaterRestriction, c['id'])
            for c in columns
        }]

    elif restriction_dropdown_value == 'FoodRestriction':
        data = action.FoodRestriction.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in action.FoodRestriction.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.FoodRestriction, c['id'])
            for c in columns
        }]

    elif administration_dropdown_value == 'WaterAdministration':
        data = action.WaterAdministration.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in action.WaterAdministration.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.WaterAdministration, c['id'])
            for c in columns
        }]

    elif administration_dropdown_value == 'FoodAdministration':
        data = action.FoodAdministration.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in action.FoodAdministration.heading.names]
        data_add_action_table = [{
            c['id']: utils.get_default(action.FoodAdministration, c['id'])
            for c in columns
        }]

    if triggered_component == 'add-action-button':
        entry = {k: v for k, v in new_data[0].items() if v != ''}

        if monitoring_dropdown_value == 'Weighing':
            action.Weighing.insert1(entry)
            data = action.Weighing.fetch(as_dict=True)

        elif monitoring_dropdown_value == 'HealthStatus':
            for c in columns:
                if c['name'] in [
                        'fur', 'mobility', 'stress', 'suture_implant'
                ]:
                    c = c.update(presentation="dropdown")
            action.Weighing.HealthStatus.insert1(entry)
            data = action.Weighing.HealthStatus.fetch(as_dict=True)

        elif restriction_dropdown_value == 'WaterRestriction':
            action.WaterRestriction.insert1(entry)
            data = action.WaterRestriction.fetch(as_dict=True)

        elif restriction_dropdown_value == 'FoodRestriction':
            action.FoodRestriction.insert1(entry)
            data = action.FoodRestriction.fetch(as_dict=True)

        elif administration_dropdown_value == 'WaterAdministration':
            action.WaterAdministration.insert1(entry)
            data = action.WaterAdministration.fetch(as_dict=True)

        elif administration_dropdown_value == 'FoodAdministration':
            action.FoodAdministration.insert1(entry)
            data = action.FoodAdministration.fetch(as_dict=True)

    if triggered_component == 'delete-action-button' and selected_rows:
        print(selected_rows)

        if monitoring_dropdown_value == 'Weighing':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'weighing_time': data[selected_rows[0]]['weighing_time']
            }
            (action.Weighing & entry).delete()
            data = action.Weighing.fetch(as_dict=True)

        elif monitoring_dropdown_value == 'HealthStatus':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'computer_name': data[selected_rows[0]]['computer_name']
            }
            (action.Weighing.HealthStatus & entry).delete()
            data = action.Weighing.HealthStatus.fetch(as_dict=True)

        elif restriction_dropdown_value == 'WaterRestriction':
            entry = {
                'subject_id':
                data[selected_rows[0]]['subject_id'],
                'water_restr_start_time':
                data[selected_rows[0]]['water_restr_start_time']
            }
            (action.WaterRestriction & entry).delete()
            data = action.WaterRestriction.fetch(as_dict=True)

        elif restriction_dropdown_value == 'FoodRestriction':
            entry = {
                'subject_id':
                data[selected_rows[0]]['subject_id'],
                'food_restr_start_time':
                data[selected_rows[0]]['food_restr_start_time']
            }
            (action.FoodRestriction & entry).delete()
            data = action.FoodRestriction.fetch(as_dict=True)

        elif administration_dropdown_value == 'WaterAdministration':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'water_admin_time': data[selected_rows[0]]['water_admin_time']
            }
            (action.WaterAdministration & entry).delete()
            data = action.WaterAdministration.fetch(as_dict=True)

        elif administration_dropdown_value == 'FoodAdministration':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'food_admin_time': data[selected_rows[0]]['food_admin_time']
            }
            (action.FoodAdministration & entry).delete()
            data = action.FoodAdministration.fetch(as_dict=True)

    return data, columns, data_add_action_table, columns
Exemple #7
0
def add_acquisition(n_clicks_add, n_clicks_delete, general_dropdown_value,
                    task_dropdown_value, instruments_dropdown_value, new_data,
                    data, selected_rows):
    ctx = dash.callback_context
    triggered_component = ctx.triggered[0]['prop_id'].split('.')[0]

    if general_dropdown_value == 'Session':
        data = acquisition.Session.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session, c['id'])
            for c in columns
        }]

    elif general_dropdown_value == 'User':
        data = acquisition.Session.User.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.User.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.User, c['id'])
            for c in columns
        }]

    elif general_dropdown_value == 'Reward':
        data = acquisition.Session.Reward.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Reward.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Reward, c['id'])
            for c in columns
        }]

    elif task_dropdown_value == 'Scara':
        data = acquisition.Session.Scara.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Scara.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Scara, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Camera':
        data = acquisition.Session.Camera.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Camera.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Camera, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'TwoPhoton':
        data = acquisition.Session.TwoPhoton.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.TwoPhoton.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.TwoPhoton, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Inscopix':
        data = acquisition.Session.Inscopix.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Inscopix.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Inscopix, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Nvoke':
        data = acquisition.Session.Nvoke.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Nvoke.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Nvoke, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Optogenetics':
        data = acquisition.Session.Optogenetics.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Optogenetics.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Optogenetics,
                                       c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Ephys':
        data = acquisition.Session.Ephys.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Ephys.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Ephys, c['id'])
            for c in columns
        }]

    elif instruments_dropdown_value == 'Calibration':
        data = acquisition.Session.Calibration.fetch(as_dict=True)
        columns = [{
            "name": i,
            "id": i
        } for i in acquisition.Session.Calibration.heading.names]
        data_add_acquisition_table = [{
            c['id']: utils.get_default(acquisition.Session.Calibration,
                                       c['id'])
            for c in columns
        }]

    if triggered_component == 'add-acquisition-button':
        entry = {k: v for k, v in new_data[0].items() if v != ''}

        if general_dropdown_value == 'Session':
            acquisition.Session.insert1(entry)
            data = acquisition.Session.fetch(as_dict=True)

        elif general_dropdown_value == 'User':
            acquisition.Session.User.insert1(entry)
            data = acquisition.Session.User.fetch(as_dict=True)

        elif general_dropdown_value == 'Reward':
            acquisition.Session.Reward.insert1(entry)
            data = acquisition.Session.Reward.fetch(as_dict=True)

        elif task_dropdown_value == 'Scara':
            acquisition.Session.Scara.insert1(entry)
            data = acquisition.Session.Scara.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Camera':
            acquisition.Session.Camera.insert1(entry)
            data = acquisition.Session.Camera.fetch(as_dict=True)

        elif instruments_dropdown_value == 'TwoPhoton':
            acquisition.Session.TwoPhoton.insert1(entry)
            data = acquisition.Session.TwoPhoton.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Inscopix':
            acquisition.Session.Inscopix.insert1(entry)
            data = acquisition.Session.Inscopix.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Nvoke':
            acquisition.Session.Nvoke.insert1(entry)
            data = acquisition.Session.Nvoke.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Optogenetics':
            acquisition.Session.Optogenetics.insert1(entry)
            data = acquisition.Session.Optogenetics.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Ephys':
            acquisition.Session.Ephys.insert1(entry)
            data = acquisition.Session.Ephys.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Calibration':
            acquisition.Session.Calibration.insert1(entry)
            data = acquisition.Session.Calibration.fetch(as_dict=True)

    if triggered_component == 'delete-acquisition-button' and selected_rows:
        print(selected_rows)

        if general_dropdown_value == 'Session':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session & entry).delete()
            data = acquisition.Session.fetch(as_dict=True)

        elif general_dropdown_value == 'User':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time'],
                'user': data[selected_rows[0]]['user']
            }
            (acquisition.Session.User & entry).delete()
            data = acquisition.Session.User.fetch(as_dict=True)

        elif general_dropdown_value == 'Reward':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time'],
                'reward_name': data[selected_rows[0]]['reward_name']
            }
            (acquisition.Session.Reward & entry).delete()
            data = acquisition.Session.Reward.fetch(as_dict=True)

        elif task_dropdown_value == 'Scara':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Scara & entry).delete()
            data = acquisition.Scara.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Camera':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time'],
                'camera_index': data[selected_rows[0]]['camera_index']
            }
            (acquisition.Session.Camera & entry).delete()
            data = acquisition.Session.Camera.fetch(as_dict=True)

        elif instruments_dropdown_value == 'TwoPhoton':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time'],
                'two_photon_name': data[selected_rows[0]]['two_photon_name']
            }
            (acquisition.Session.TwoPhoton & entry).delete()
            data = acquisition.Session.TwoPhoton.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Inscopix':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session.Inscopix & entry).delete()
            data = acquisition.Session.Inscopix.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Nvoke':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session.Nvoke & entry).delete()
            data = acquisition.Session.Nvoke.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Optogenetics':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session.Optogenetics & entry).delete()
            data = acquisition.Session.Optogenetics.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Ephys':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session.Ephys & entry).delete()
            data = acquisition.Session.Ephys.fetch(as_dict=True)

        elif instruments_dropdown_value == 'Calibration':
            entry = {
                'subject_id': data[selected_rows[0]]['subject_id'],
                'session_start_time':
                data[selected_rows[0]]['session_start_time']
            }
            (acquisition.Session.Calibration & entry).delete()
            data = acquisition.Session.Calibration.fetch(as_dict=True)

    return data, columns, data_add_acquisition_table, columns
Exemple #8
0
    def execute(self, *args, **options):
        if os.path.basename(sys.argv[0]) == 'snodas':
            self.snodas_command_error()
            return 1

        if options.get('version'):
            print('snodas version {}'.format(self.get_version()))
            return 2

        self.verbosity = options.get('verbosity')

        self.output_file = utils.get_default(
            options,
            'output_file',
            self.default_conf_file(),
        )

        self.vprint(2, 'Config file path will be {}'.format(self.output_file))

        conf_exists = os.path.isfile(self.output_file)

        if options.get('no_configure') and conf_exists:
            self.vprint(1,'Reusing existing configuration from {}'.format(self.output_file))
            self.settings = utils.load_conf_file(self.output_file)
        elif options.get('no_configure') and not conf_exists:
            print('ERROR: no-configure option specified '
                  'but configuration file does not exist.')
            return 3
        elif conf_exists and not options.get('overwrite_conf'):
            print('ERROR: configuration file already exists '
                  'and overwrite-conf option not specified.')
            return 4
        else:
            self.vprint(1, 'Generating configuration from install options')
            self.settings = self.extract_settings_from_options(options)

        self.print_conf()

        if options.get('make_env'):
            self.vprint(1, 'creating conda env')
            self.create_conda_env(options)
        else:
            self.vprint(
                1,
                'conda env creation skipped; '
                'installing to active python instance',
            )

        self.vprint(1, 'Installing project')
        self.install(options)

        if not options.get('no_configure'):
            self.write_conf_file()

        # print next steps for user
        self.vprint(1, '\nInstallation successful!')
        self.vprint(
            1,
            ('\nNext, activate the new conda env for the project:\n\n'
             '`activate {}`\n\n'
             '(`source` is required in a sh-like shell).\n\n'
             'Then, setup any required services for this instance:\n\n:'
             '`snodas createdb [options]  # creates a postgres DB`\n'
             '`snodas setupiis [options]  # creates a site in IIS`\n\n'
             'Once the services are configured, '
             'you can run a webserver or celery:\n\n'
             '`snodas runserver [options]'
             'To learn what options apply to each command, try:\n\n'
             '`snodas help <command>`'
             ).format(self.settings['INSTANCE_NAME'])
        )
Exemple #9
0
    def extract_settings_from_options(self, options):
        settings = {}

        settings['ENV'] = options.get('env') or utils.get_env_name()

        if not settings['ENV']:
            raise InstallError(
                'Could not extract env name from path and none specified.'
            )

        pyfile = settings['ENV'] + '.py'
        if not os.path.isfile(utils.get_settings_file(pyfile)):
            warnings.warn(
                'Could not find settings file for env named {}'
                .format(pyfile),
            )

        settings['DEBUG'] = (
            settings['ENV'] == 'development' or options.get('DEBUG')
        )

        settings['INSTANCE_NAME'] = utils.get_default(
            options,
            'instance_name',
            utils.get_instance_name(),
        )

        if not settings['INSTANCE_NAME']:
            raise InstallError(
                'Could not extract instance name from path and none specified.'
             )

        settings['SECRET_KEY'] = utils.get_default(
            options,
            'secret_key',
            utils.generate_secret_key(options.get('secret_key_length'))
        )

        settings['DATABASE_NAME'] = utils.get_default(
            options,
            'db_name',
            settings['INSTANCE_NAME'],
        )
        settings['DATABASE_USER'] = utils.get_default(
            options,
            'db_user',
            settings['DATABASE_NAME'],
        )
        settings['DATABASE_PASSWORD'] = utils.get_default(
            options,
            'db_password',
            get_password('Please enter the database user password: '******'DATABASE_HOST'] = utils.get_default(options, 'db_host', None)
        settings['DATABASE_PORT'] = utils.get_default(options, 'db_port', None)


        settings['SITE_DOMAIN_NAME'] = utils.get_default(
            options,
            'domain',
            input('Enter in the domain name for this project instance: '),
        )
        settings['SUBDOMAINS'] = []

        settings['ADDITIONAL_SETTINGS_FILES'] = utils.get_default(
            options,
            'additional_settings_file',
            [],
        )

        return settings
Exemple #10
0
#     if c['name'] in ['sex', 'strain']:
#         c.update(presentation="dropdown")

# add subject table style
add_acquisition_style = copy.deepcopy(table_style_template)
add_acquisition_style['style_table'].update({
    'minHeight': '80px',
    'height': '80px',
    'maxHeight': '80px',
})

add_acquisition_table = dash_table.DataTable(id='add-acquisition-table',
                                             columns=columns,
                                             data=[{
                                                 c['id']: utils.get_default(
                                                     acquisition.Session,
                                                     c['id'])
                                                 for c in columns
                                             }],
                                             **add_acquisition_style,
                                             editable=True)

## ----------------------------- add acquisition button ---------------------------------
add_acquisition_button = html.Button(children='Add an acquisition record',
                                     id='add-acquisition-button',
                                     n_clicks=0,
                                     style={'marginBottom': '0.5em'})

## ------------------------- deletion confirm dialogue ------------------------------
delete_acquisition_confirm = dcc.ConfirmDialog(
    id='delete-acquisition-confirm',
Exemple #11
0
# for c in columns:
#     if c['name'] in ['sex', 'strain']:
#         c.update(presentation="dropdown")

# add subject table style
add_action_style = copy.deepcopy(table_style_template)
add_action_style['style_table'].update({
    'minHeight': '80px',
    'height': '80px',
    'maxHeight': '80px',
})

add_action_table = dash_table.DataTable(id='add-action-table',
                                        columns=columns,
                                        data=[{
                                            c['id']: utils.get_default(
                                                action.Weighing, c['id'])
                                            for c in columns
                                        }],
                                        **add_action_style,
                                        editable=True)

## ----------------------------- add action button ---------------------------------
add_action_button = html.Button(children='Add an action record',
                                id='add-action-button',
                                n_clicks=0,
                                style={'marginBottom': '0.5em'})

## ------------------------- deletion confirm dialogue ------------------------------
delete_action_confirm = dcc.ConfirmDialog(
    id='delete-action-confirm',
    message='Are you sure you want to delete the record?',