text:
from __future__ import absolute_import, division, print_function, unicode_literals

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.ticker as tick

from shutil import copyfile
import datetime
import os
import glob
import re
import xmltodict
from pylab import rcParams

rcParams['figure.figsize'] = 15, 10

def barodistance(wellinfo):
    """Determines Closest Barometer to Each Well using wellinfo DataFrame"""
    barometers = {'barom': ['pw03', 'pw10', 'pw19'], 'X': [240327.49, 271127.67, 305088.9],
                  'Y': [4314993.95, 4356071.98, 4389630.71], 'Z': [1623.079737, 1605.187759, 1412.673738]}
    barolocal = pd.DataFrame(barometers)
    barolocal = barolocal.reset_index()
    barolocal.set_index('barom', inplace=True)

    wellinfo['pw03'] = np.sqrt((barolocal.loc['pw03', 'X'] - wellinfo['UTMEasting']) ** 2 + \
                               (barolocal.loc['pw03', 'Y'] - wellinfo['UTMNorthing']) ** 2 + \
                               (barolocal.loc['pw03', 'Z'] - wellinfo['G_Elev_m']) ** 2)
    wellinfo['pw10'] = np.sqrt((barolocal.loc['pw10', 'X'] - wellinfo['UTMEasting']) ** 2 + \
                               (barolocal.loc['pw10', 'Y'] - wellinfo['UTMNorthing']) ** 2 + \
                               (barolocal.loc['pw10', 'Z'] - wellinfo['G_Elev_m']) ** 2)
    wellinfo['pw19'] = np.sqrt((barolocal.loc['pw19', 'X'] - wellinfo['UTMEasting']) ** 2 + \
                               (barolocal.loc['pw19', 'Y'] - wellinfo['UTMNorthing']) ** 2 + \
                               (barolocal.loc['pw19', 'Z'] - wellinfo['G_Elev_m']) ** 2)
    wellinfo['closest_baro'] = wellinfo[['pw03', 'pw10', 'pw19']].T.idxmin()
    return wellinfo

def rollmeandiff(df1, p1, df2, p2, win):
    """Returns the rolling mean difference of two columns from two different dataframes
    Args:
        df1 (object):
            dataframe 1
        p1 (str):
            column in df1
        df2 (object):
            dataframe 2
        p2 (str):
            column in df2
        win (int):
            window in days

    Return:
        diff (float):
            difference
    """
    win = win * 60 * 24
    df1 = df1.resample('1Min').mean()
    df1 = df1.interpolate(method='time')
    df2 = df2.resample('1Min').mean()
    df2 = df2.interpolate(method='time')
    df1['rm' + p1] = df1[p1].rolling(window=win, center=True).mean()
    df2['rm' + p2] = df2[p2].rolling(window=win, center=True).mean()
    df3 = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
    df3 = df3[np.isfinite(df3['rm' + p1])]
    df4 = df3[np.isfinite(df3['rm' + p2])]
    df5 = df4['rm' + p1] - df4['rm' + p2]
    diff = round(df5.mean(), 3)
    del (df3, df4, df5)
    return diff

def jumpfix(df, meas, threashold=0.005, return_jump=False):
    """Removes jumps or jolts in time series data (where offset is lasting)
    Args:
        df (object):
            dataframe to manipulate
        meas (str):
            name of field with jolts
        threashold (float):
            size of jolt to search for
    Returns:
        df1: dataframe of corrected data
        jump: dataframe of jumps corrected in data
    """
    df1 = df.copy(deep=True)
    df1['delta' + meas] = df1.loc[:, meas].diff()
    jump = df1[abs(df1['delta' + meas]) > threashold]
    jump['cumul'] = jump.loc[:, 'delta' + meas].cumsum()
    df1['newVal'] = df1.loc[:, meas]

    for i in range(len(jump)):
        jt = jump.index[i]
        ja = jump['cumul'][i]
        df1.loc[jt:, 'newVal'] = df1[meas].apply(lambda x: x - ja, 1)
    df1[meas] = df1['newVal']
    if return_jump:
        print(jump)
        return df1, jump
    else:
        return df1

def smoother(df, p, win=30, sd=3):
    """Remove outliers from a pandas dataframe column and fill with interpolated values.
    warning: this will fill all NaN values in the DataFrame with the interpolate function

    Args:
        df (pandas.core.frame.DataFrame):
            Pandas DataFrame of interest
        p (string):
            column in dataframe with outliers
        win (int):
            size of window in days (default 30)
        sd (int):
            number of standard deviations allowed (default 3)

    Returns:
        Pandas DataFrame with outliers removed
    """
    df1 = df
    df1.loc[:, 'dp' + p] = df1.loc[:, p].diff()
    df1.loc[:, 'ma' + p] = df1.loc[:, 'dp' + p].rolling(window=win, center=True).mean()
    df1.loc[:, 'mst' + p] = df1.loc[:, 'dp' + p].rolling(window=win, center=True).std()
    for i in df.index:
        try:
            if abs(df1.loc[i, 'dp' + p] - df1.loc[i, 'ma' + p]) >= abs(df1.loc[i, 'mst' + p] * sd):
                df.loc[i, p] = np.nan
            else:
                df.loc[i, p] = df.loc[i, p]
        except ValueError:
            try:
                if abs(df1.loc[i, 'dp' + p] - df1.loc[i, 'ma' + p]) >= abs(df1.loc[:, 'dp' + p].std() * sd):
                    df.loc[i, p] = np.nan
                else:
                    df.loc[i, p] = df.loc[i, p]
            except ValueError:
                df.loc[i, p] = df.loc[i, p]

    try:
        df1 = df1.drop(['dp' + p, 'ma' + p, 'mst' + p], axis=1)
    except(NameError, ValueError):
        pass
    del df1
    try:
        df = df.drop(['dp' + p, 'ma' + p, 'mst' + p], axis=1)
    except(NameError, ValueError):
        pass
    df = df.interpolate(method='time', limit=30)
    df = df[1:-1]
    return df

def printmes(x):
    try:
        from arcpy import AddMessage
        AddMessage(x)
        print(x)
    except ModuleNotFoundError:
        print(x)

def compilefiles(searchdir,copydir,filecontains,filetypes=['lev','xle']):
    filecontains = list(filecontains)
    filetypes = list(filetypes)
    for pack in os.walk(searchdir):
        for name in filecontains:
            for i in glob.glob(pack[0]+'/'+'*{:}*'.format(name)):
                if i.split('.')[-1] in filetypes:
                    dater = str(datetime.datetime.fromtimestamp(os.path.getmtime(i)).strftime('%Y-%m-%d'))
                    rightfile = dater + "_" + os.path.basename(i)
                    if not os.path.exists(copydir):
                        print('Creating {:}'.format(copydir))
                        os.makedirs(copydir)
                    else:
                        pass
                    if os.path.isfile(os.path.join(copydir, rightfile)):
                        pass
                    else:
                        print(os.path.join(copydir, rightfile))
                        try:
                            copyfile(i, os.path.join(copydir, rightfile))
                        except:
                            pass
    printmes('Copy Complete!')
    return

def new_lev_imp(infile):
    with open(infile, "r") as fd:
        txt = fd.readlines()

    try:
        data_ind = txt.index('[Data]\n')
        # inst_info_ind = txt.index('[Instrument info from data header]\n')
        ch1_ind = txt.index('[CHANNEL 1 from data header]\n')
        ch2_ind = txt.index('[CHANNEL 2 from data header]\n')
        level = txt[ch1_ind + 1].split('=')[-1].strip().title()
        level_units = txt[ch1_ind + 2].split('=')[-1].strip().lower()
        temp = txt[ch2_ind + 1].split('=')[-1].strip().title()
        temp_units = txt[ch2_ind + 2].split('=')[-1].strip().lower()
        # serial_num = txt[inst_info_ind+1].split('=')[-1].strip().strip(".")
        # inst_num = txt[inst_info_ind+2].split('=')[-1].strip()
        # location = txt[inst_info_ind+3].split('=')[-1].strip()
        # start_time = txt[inst_info_ind+6].split('=')[-1].strip()
        # stop_time = txt[inst_info_ind+7].split('=')[-1].strip()

        df = pd.read_table(infile, parse_dates=[[0, 1]], sep='\s+', skiprows=data_ind + 2,
                           names=['Date', 'Time', level, temp],
                           skipfooter=1, engine='python')
        df.rename(columns={'Date_Time': 'DateTime'}, inplace=True)
        df.set_index('DateTime', inplace=True)

        if level_units == "feet" or level_units == "ft":
            df[level] = pd.to_numeric(df[level])
        elif level_units == "kpa":
            df[level] = pd.to_numeric(df[level]) * 0.33456
            printmes("Units in kpa, converting {:} to ft...".format(os.path.basename(infile)))
        elif level_units == "mbar":
            df[level] = pd.to_numeric(df[level]) * 0.0334552565551
        elif level_units == "psi":
            df[level] = pd.to_numeric(df[level]) * 2.306726
            printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
        elif level_units == "m" or level_units == "meters":
            df[level] = pd.to_numeric(df[level]) * 3.28084
            printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
        else:
            df[level] = pd.to_numeric(df[level])
            printmes("Unknown units, no conversion")

        if temp_units == 'Deg C' or temp_units == u'\N{DEGREE SIGN}' + u'C':
            df[temp] = df[temp]
        elif temp_units == 'Deg F' or temp_units == u'\N{DEGREE SIGN}' + u'F':
            printmes('Temp in F, converting {:} to C...'.format(os.path.basename(infile)))
            df[temp] = (df[temp] - 32.0) * 5.0 / 9.0
        df['name'] = infile
        return df
    except ValueError:
        printmes('File {:} has formatting issues'.format(infile))

def new_xle_imp(infile):
    """This function uses an exact file path to upload a xle transducer file.

    Args:
        infile (file):
            complete file path to input file

    Returns:
        A Pandas DataFrame containing the transducer data
    """
    # open text file
    with open(infile, "rb") as f:
        obj = xmltodict.parse(f, xml_attribs=True, encoding="ISO-8859-1")
    # navigate through xml to the data
    wellrawdata = obj['Body_xle']['Data']['Log']
    # convert xml data to pandas dataframe
    try:
        f = pd.DataFrame(wellrawdata)
    except ValueError:
        printmes('xle file {:} incomplete'.format(infile))
        return
    # CH 3 check
    try:
        ch3ID = obj['Body_xle']['Ch3_data_header']['Identification']
        f[str(ch3ID).title()] = f['ch3']
    except(KeyError, UnboundLocalError):
        pass

    # CH 2 manipulation
    try:
        ch2ID = obj['Body_xle']['Ch2_data_header']['Identification']
        f[str(ch2ID).title()] = f['ch2']
        ch2Unit = obj['Body_xle']['Ch2_data_header']['Unit']
        numCh2 = pd.to_numeric(f['ch2'])
        if ch2Unit == 'Deg C' or ch2Unit == u'\N{DEGREE SIGN}' + u'C':
            f[str(ch2ID).title()] = numCh2
        elif ch2Unit == 'Deg F' or ch2Unit == u'\N{DEGREE SIGN}' + u'F':
            printmes('Temp in F, converting to C')
            f[str(ch2ID).title()] = (numCh2 - 32) * 5 / 9
        f[str(ch2ID).title()] = pd.to_numeric(f[str(ch2ID).title()])
    except (KeyError,UnboundLocalError):
        printmes('No channel 2 for {:}'.format(infile))
    # CH 1 manipulation
    ch1ID = obj['Body_xle']['Ch1_data_header']['Identification']  # Usually level
    ch1Unit = obj['Body_xle']['Ch1_data_header']['Unit']  # Usually ft
    unit = str(ch1Unit).lower()

    if unit == "feet" or unit == "ft":
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1'])
    elif unit == "kpa":
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1']) * 0.33456
        printmes("Units in kpa, converting {:} to ft...".format(os.path.basename(infile)))
    elif unit == "mbar":
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1']) * 0.0334552565551
    elif unit == "psi":
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1']) * 2.306726
        printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
    elif unit == "m" or unit == "meters":
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1']) * 3.28084
        printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
    else:
        f[str(ch1ID).title()] = pd.to_numeric(f['ch1'])
        printmes("Unknown units, no conversion")

    # add extension-free file name to dataframe
    f['name'] = infile.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
    # combine Date and Time fields into one field
    f['DateTime'] = pd.to_datetime(f.apply(lambda x: x['Date'] + ' ' + x['Time'], 1))
    f[str(ch1ID).title()] = pd.to_numeric(f[str(ch1ID).title()])

    try:
        ch3ID = obj['Body_xle']['Ch3_data_header']['Identification']
        f[str(ch3ID).title()] = pd.to_numeric(f[str(ch3ID).title()])
    except(KeyError, UnboundLocalError):
        pass

    f = f.reset_index()
    f = f.set_index('DateTime')
    f['Level'] = f[str(ch1ID).title()]
    f = f.drop(['Date', 'Time', '@id', 'ch1', 'ch2', 'index', 'ms'], axis=1)

    return f

def new_csv_imp(infile):
    """This function uses an exact file path to upload a csv transducer file.

    Args:
        infile (file):
            complete file path to input file

    Returns:
        A Pandas DataFrame containing the transducer data
    """
    with open(infile, "r") as fd:
        txt = fd.readlines()
        if len(txt) > 1:
            if 'Serial' in txt[0]:
                print('{:} is Solinst'.format(infile))
                if 'UNIT: ' in txt[7]:
                    level_units = str(txt[7])[5:].strip().lower()
                if 'UNIT: ' in txt[12]:
                    temp_units = str(txt[12])[5:].strip().lower()
                f = pd.read_csv(infile, skiprows=13, parse_dates=[[0, 1]], usecols=[0, 1, 3, 4])
                print(f.columns)
                f['DateTime'] = pd.to_datetime(f['Date_Time'], errors='coerce')
                f.set_index('DateTime', inplace=True)
                f.drop('Date_Time', axis=1, inplace=True)
                f.rename(columns={'LEVEL': 'Level', 'TEMP': 'Temp'}, inplace=True)
                level = 'Level'
                temp = 'Temp'

                if level_units == "feet" or level_units == "ft":
                    f[level] = pd.to_numeric(f[level])
                elif level_units == "kpa":
                    f[level] = pd.to_numeric(f[level]) * 0.33456
                    printmes("Units in kpa, converting {:} to ft...".format(os.path.basename(infile)))
                elif level_units == "mbar":
                    f[level] = pd.to_numeric(f[level]) * 0.0334552565551
                elif level_units == "psi":
                    f[level] = pd.to_numeric(f[level]) * 2.306726
                    printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
                elif level_units == "m" or level_units == "meters":
                    f[level] = pd.to_numeric(f[level]) * 3.28084
                    printmes("Units in psi, converting {:} to ft...".format(os.path.basename(infile)))
                else:
                    f[level] = pd.to_numeric(f[level])
                    printmes("Unknown units, no conversion")

                if temp_units == 'Deg C' or temp_units == u'\N{DEGREE SIGN}' + u'C':
                    f[temp] = f[temp]
                elif temp_units == 'Deg F' or temp_units == u'\N{DEGREE SIGN}' + u'F':
                    printmes('Temp in F, converting {:} to C...'.format(os.path.basename(infile)))
                    f[temp] = (f[temp] - 32.0) * 5.0 / 9.0
                return f

            elif 'Date' in txt[1]:
                print('{:} is Global'.format(infile))
                f = pd.read_csv(infile, skiprows=1, parse_dates=[[0, 1]])
                # f = f.reset_index()
                f['DateTime'] = pd.to_datetime(f['Date_ Time'], errors='coerce')
                f = f[f.DateTime.notnull()]
                if ' Feet' in list(f.columns.values):
                    f['Level'] = f[' Feet']
                    f.drop([' Feet'], inplace=True, axis=1)
                elif 'Feet' in list(f.columns.values):
                    f['Level'] = f['Feet']
                    f.drop(['Feet'], inplace=True, axis=1)
                else:
                    f['Level'] = f.iloc[:, 1]
                # Remove first and/or last measurements if the transducer was out of the water
                # f = dataendclean(f, 'Level')
                flist = f.columns.tolist()
                if ' Temp C' in flist:
                    f['Temperature'] = f[' Temp C']
                    f['Temp'] = f['Temperature']
                    f.drop([' Temp C', 'Temperature'], inplace=True, axis=1)
                elif ' Temp F' in flist:
                    f['Temperature'] = (f[' Temp F'] - 32) * 5 / 9
                    f['Temp'] = f['Temperature']
                    f.drop([' Temp F', 'Temperature'], inplace=True, axis=1)
                else:
                    f['Temp'] = np.nan
                f.set_index(['DateTime'], inplace=True)
                f['date'] = f.index.to_julian_date().values
                f['datediff'] = f['date'].diff()
                f = f[f['datediff'] > 0]
                f = f[f['datediff'] < 1]
                # bse = int(pd.to_datetime(f.index).minute[0])
                # f = hourly_resample(f, bse)
                f.rename(columns={' Volts': 'Volts'}, inplace=True)
                f.drop([u'date', u'datediff', u'Date_ Time'], inplace=True, axis=1)
                return f
        else:
            print('{:} is unrecognized'.format(infile))

def new_trans_imp(infile):
    """This function uses an imports and cleans the ends of transducer file.

    Args:
        infile (file):
            complete file path to input file
        xle (bool):
            if true, then the file type should be xle; else it should be csv

    Returns:
        A Pandas DataFrame containing the transducer data
    """
    file_ext = os.path.splitext(infile)[1]
    try:
        if file_ext == '.xle':
            well = new_xle_imp(infile)
            well = dataendclean(well, 'Level')
        elif file_ext == '.lev':
            well = new_lev_imp(infile)
            well = dataendclean(well, 'Level')
        elif file_ext == '.csv':
            well = new_csv_imp(infile)
            well = dataendclean(well, 'Level')
        else:
            printmes('filetype not recognized')
            well = None
            pass
        return well
    except AttributeError:
        printmes('Bad File')
        return

def compilation(inputfile):
    """This function reads multiple xle transducer files in a directory and generates a compiled Pandas DataFrame.
    Args:
        inputfile (file):
            complete file path to input files; use * for wildcard in file name
    Returns:
        outfile (object):
            Pandas DataFrame of compiled data
    Example::
        >>> compilation('O:\\Snake Valley Water\\Transducer Data\\Raw_data_archive\\all\\LEV\\*baro*')
        picks any file containing 'baro'
    """

    # create empty dictionary to hold DataFrames
    f = {}

    # generate list of relevant files
    filelist = glob.glob(inputfile)

    # iterate through list of relevant files
    for infile in filelist:
        # run computations using lev files
        f[getfilename(infile)] = new_trans_imp(infile)
    # concatenate all of the DataFrames in dictionary f to one DataFrame: g
    g = pd.concat(f)
    # remove multiindex and replace with index=Datetime
    g = g.reset_index()
    g = g.set_index(['DateTime'])
    # drop old indexes
    g = g.drop(['level_0'], axis=1)
    # remove duplicates based on index then sort by index
    g['ind'] = g.index
    g.drop_duplicates(subset='ind', inplace=True)
    g.drop('ind', axis=1, inplace=True)
    g = g.sort_index()
    outfile = g
    return g

def dataendclean(df, x, inplace=False):
    """Trims off ends and beginnings of datasets that exceed 2.0 standard deviations of the first and last 30 values

    :param df: Pandas DataFrame
    :type df: pandas.core.frame.DataFrame
    :param x: Column name of data to be trimmed contained in df
    :type x: str
    :param inplace: if DataFrame should be duplicated
    :type inplace: bool

    :returns: df trimmed data
    :rtype: pandas.core.frame.DataFrame

    This function printmess a message if data are trimmed.
    """
    # Examine Mean Values
    if inplace:
        df = df
    else:
        df = df.copy()

    jump = df[abs(df.loc[:, x].diff()) > 1.0]
    try:
        for i in range(len(jump)):
            if jump.index[i] < df.index[50]:
                df = df[df.index > jump.index[i]]
                printmes("Dropped from beginning to " + str(jump.index[i]))
            if jump.index[i] > df.index[-50]:
                df = df[df.index < jump.index[i]]
                printmes("Dropped from end to " + str(jump.index[i]))
    except IndexError:
        printmes('No Jumps')
    return df

def getfilename(path):
    """This function extracts the file name without file path or extension

    Args:
        path (file):
            full path and file (including extension of file)

    Returns:
        name of file as string
    """
    return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]

def correct_be(site_number, well_table, welldata, be=None, meas='corrwl', baro='barometer'):
    if be:
        be = float(be)
    else:
        stdata = well_table[well_table['WellID'] == site_number]
        be = stdata['BaroEfficiency'].values[0]
    if be is None:
        be = 0
    else:
        be = float(be)

    if be == 0:
        welldata['BAROEFFICIENCYLEVEL'] = welldata[meas]
    else:
        welldata['BAROEFFICIENCYLEVEL'] = welldata[[meas, baro]].apply(lambda x: x[0] + be * x[1], 1)

    return welldata, be

def hourly_resample(df, bse=0, minutes=60):
    """
    resamples data to hourly on the hour
    Args:
        df:
            pandas dataframe containing time series needing resampling
        bse (int):
            base time to set; optional; default is zero (on the hour);
        minutes (int):
            sampling recurrence interval in minutes; optional; default is 60 (hourly samples)
    Returns:
        A Pandas DataFrame that has been resampled to every hour, at the minute defined by the base (bse)
    Description:
        see http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html for more info
        This function uses pandas powerful time-series manipulation to upsample to every minute, then downsample to every hour,
        on the hour.
        This function will need adjustment if you do not want it to return hourly samples, or iusgsGisf you are sampling more frequently than
        once per minute.
        see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
    """

    df = df.resample('1Min').mean().interpolate(method='time', limit=90)

    df = df.resample(str(minutes) + 'Min', closed='left', label='left', base=bse).mean()
    return df

def well_baro_merge(wellfile, barofile, barocolumn='Level', wellcolumn='Level', outcolumn='corrwl',
                    vented=False, sampint=60):
    """Remove barometric pressure from nonvented transducers.
    Args:
        wellfile (pd.DataFrame):
            Pandas DataFrame of water level data labeled 'Level'; index must be datetime
        barofile (pd.DataFrame):
            Pandas DataFrame barometric data labeled 'Level'; index must be datetime
        sampint (int):
            sampling interval in minutes; default 60

    Returns:
        wellbaro (Pandas DataFrame):
           corrected water levels with bp removed
    """

    # resample data to make sample interval consistent
    baro = hourly_resample(barofile, 0, sampint)
    well = hourly_resample(wellfile, 0, sampint)

    # reassign `Level` to reduce ambiguity
    baro = baro.rename(columns={barocolumn: 'barometer'})

    if 'TEMP' in baro.columns:
        baro.drop('TEMP', axis=1, inplace=True)
    elif 'Temperature' in baro.columns:
        baro.drop('Temperature', axis=1, inplace=True)

    # combine baro and well data for easy calculations, graphing, and manipulation
    wellbaro = pd.merge(well, baro, left_index=True, right_index=True, how='inner')

    wellbaro['dbp'] = wellbaro['barometer'].diff()
    wellbaro['dwl'] = wellbaro[wellcolumn].diff()
    first_well = wellbaro[wellcolumn][0]

    if vented:
        wellbaro[outcolumn] = wellbaro[wellcolumn]
    else:
        wellbaro[outcolumn] = wellbaro[['dbp', 'dwl']].apply(lambda x: x[1] - x[0], 1).cumsum() + first_well
    wellbaro.loc[wellbaro.index[0], outcolumn] = first_well
    return wellbaro

def one_well(well_file, baro_file, well_table, man_startdate, man_start_level, man_endate,  man_end_level, wellid, be=None):
    """
    imports one well with the right files and manual data
    :param well_file: raw file of well data (lev, csv, or xle)
    :param baro_file: barometric pressure dictionary of pandas dataframes
    :param well_table: table of well information
    :param man_startdate: first manual measurement date near data interval
    :param man_start_level: first manual measurement near data interval
    :param man_endate: last manual measurement date near data interval
    :param man_end_level: last manual measurement near data interval
    :param wellid: unique id for well (alternate id in well table)
    :param be: barometric efficiency of well; default is None
    :return: rowlist, df, man, be, drift
    """

    if os.path.splitext(well_file)[1] == '.xle':
        trans_type = 'Solinst'
    else:
        trans_type = 'Global Water'

    printmes('Trans type for well is {:}.'.format(trans_type))

    well = new_trans_imp(well_file)
    baro = new_trans_imp(baro_file)

    corrwl = well_baro_merge(well, baro, vented=(trans_type != 'Solinst'))

    if be:
        corrwl = correct_be(wellid, corrwl, be=be)
        corrwl['corrwl'] = corrwl['BAROEFFICIENCYLEVEL']

    stickup, well_elev = get_stickup_elev(wellid, well_table)

    man = pd.DataFrame(
        {'DateTime': [man_startdate, man_endate],
         'MeasuredDTW': [man_start_level, man_end_level]}).set_index('DateTime')
    printmes(man)
    man['Meas_GW_Elev'] = well_elev - (man['MeasuredDTW'] - stickup)

    man['MeasuredDTW'] = man['MeasuredDTW'] * -1

    dft = fix_drift(corrwl, man, meas='corrwl', manmeas='MeasuredDTW')
    drift = round(float(dft[1]['drift'].values[0]), 3)
    printmes('Drift for well {:} is {:}.'.format(wellid, drift))
    df = dft[0]

    rowlist, fieldnames = prepare_fieldnames(df, wellid, stickup, well_elev)

    return rowlist, df, man, be, drift

def calc_dtw(df, stickup, well_elev, level='Level', dtw='DTW_WL'):
    """

    :param df: pandas DataFrame of processed well data
    :param stickup: raw transducer level from new_trans_imp, new_xle_imp, or new_csv_imp functions
    :param well_elev: well elevation
    :param level: raw transducer level from new_trans_imp, new_xle_imp, or new_csv_imp functions
    :param dtw: drift-corrected depth to water from fix_drift function
    :return:
    """
    df['MEASUREDLEVEL'] = df[level]
    df['MEASUREDDTW'] = df[dtw] * -1
    df['DTWBELOWCASING'] = df['MEASUREDDTW']
    df['DTWBELOWGROUNDSURFACE'] = df['MEASUREDDTW'].apply(lambda x: x - stickup, 1)
    df['WATERELEVATION'] = df['DTWBELOWGROUNDSURFACE'].apply(lambda x: well_elev - x, 1)
    return df

def prep_fields(df,wellid):
    """
    Prepares dataframe fields for import
    :param df: pandas dataframe containing groundwater levels
    :param wellid: unique well id
    :return: subset, fieldnames
    """
    df['TAPE'] = 0
    df['LOCATIONID'] = wellid

    df.sort_index(inplace=True)

    fieldnames = ['READINGDATE', 'MEASUREDLEVEL', 'MEASUREDDTW', 'DRIFTCORRECTION',
                  'TEMP', 'LOCATIONID', 'DTWBELOWCASING', 'BAROEFFICIENCYLEVEL',
                  'DTWBELOWGROUNDSURFACE', 'WATERELEVATION', 'TAPE']

    if 'Temperature' in df.columns:
        df.rename(columns={'Temperature': 'TEMP'}, inplace=True)

    if 'TEMP' in df.columns:
        df['TEMP'] = df['TEMP'].apply(lambda x: np.round(x, 4), 1)
    else:
        df['TEMP'] = None

    if 'BAROEFFICIENCYLEVEL' in df.columns:
        pass
    else:
        df['BAROEFFICIENCYLEVEL'] = 0
    # subset bp df and add relevant fields
    df.index.name = 'READINGDATE'

    subset = df.reset_index()

    return subset, fieldnames

def prepare_fieldnames(df, wellid, stickup, well_elev, level='Level', dtw='DTW_WL'):
    """
    This function adds the necessary field names to import well data into the SDE database.
    :param df: pandas DataFrame of processed well data
    :param wellid: wellid (alternateID) of well in Stations Table
    :param level: raw transducer level from new_trans_imp, new_xle_imp, or new_csv_imp functions
    :param dtw: drift-corrected depth to water from fix_drift function
    :return: processed df with necessary field names for import
    """

    df['MEASUREDLEVEL'] = df[level]
    df['MEASUREDDTW'] = df[dtw] * -1
    df['DTWBELOWCASING'] = df['MEASUREDDTW']
    df['DTWBELOWGROUNDSURFACE'] = df['MEASUREDDTW'].apply(lambda x: x - stickup, 1)
    df['WATERELEVATION'] = df['DTWBELOWGROUNDSURFACE'].apply(lambda x: well_elev - x, 1)
    df['TAPE'] = 0
    df['LOCATIONID'] = wellid

    df.sort_index(inplace=True)

    fieldnames = ['READINGDATE', 'MEASUREDLEVEL', 'MEASUREDDTW', 'DRIFTCORRECTION',
                  'TEMP', 'LOCATIONID', 'DTWBELOWCASING', 'BAROEFFICIENCYLEVEL',
                  'DTWBELOWGROUNDSURFACE', 'WATERELEVATION', 'TAPE']

    if 'Temperature' in df.columns:
        df.rename(columns={'Temperature': 'TEMP'}, inplace=True)

    if 'TEMP' in df.columns:
        df['TEMP'] = df['TEMP'].apply(lambda x: np.round(x, 4), 1)
    else:
        df['TEMP'] = None

    if 'BAROEFFICIENCYLEVEL' in df.columns:
        pass
    else:
        df['BAROEFFICIENCYLEVEL'] = 0
    # subset bp df and add relevant fields
    df.index.name = 'READINGDATE'

    subset = df.reset_index()

    return subset, fieldnames

def getwellid(infile, wellinfo):
    """Specialized function that uses a well info table and file name to lookup a well's id number"""
    m = re.search("\d", getfilename(infile))
    s = re.search("\s", getfilename(infile))
    if m.start() > 3:
        wellname = getfilename(infile)[0:m.start()].strip().lower()
    else:
        wellname = getfilename(infile)[0:s.start()].strip().lower()
    wellid = wellinfo[wellinfo['Well'] == wellname]['WellID'].values[0]
    return wellname, wellid

def get_stickup_elev(site_number, well_table):
    stdata = well_table[well_table['AltLocationID'] == str(site_number)]
    stickup = float(stdata['Offset'].values[0])
    well_elev = float(stdata['Altitude'].values[0])
    return stickup, well_elev

def get_gw_elevs(site_number, well_table, manual, stable_elev=True):
    """
    Gets basic well parameters and most recent groundwater level data for a well id for dtw calculations.
    :param site_number: well site number in the site table
    :param manual: Pandas Dataframe of manual data
    :param table: pandas dataframe of site table;
    :param lev_table: groundwater level table; defaults to "UGGP.UGGPADMIN.UGS_GW_reading"
    :return: stickup, well_elev, be, maxdate, dtw, wl_elev
    """

    stdata = well_table[well_table['WellID'] == str(site_number)]
    man_sub = manual[manual['Location ID'] == int(site_number)]
    well_elev = float(stdata['Altitude'].values[0])

    if stable_elev:
        stickup = float(stdata['Offset'].values[0])
    else:
        stickup = man_sub['Current Stickup Height']

    # manual = manual['MeasuredDTW'].to_frame()
    man_sub.loc[:, 'MeasuredDTW'] = man_sub['Water Level (ft)'] * -1
    man_sub.loc[:, 'Meas_GW_Elev'] = man_sub['MeasuredDTW'].apply(lambda x: well_elev + (x + stickup), 1)

    return man_sub, stickup, well_elev

def fix_well(well_table, file, baro_out, wellid, manual, stbl_elev=True, barocol='MEASUREDLEVEL', mancol = ''):

    # import well file
    well = new_trans_imp(file)

    file_ext = os.path.splitext(file)[1]
    if file_ext == '.xle':
        trans_type = 'Solinst'
    else:
        trans_type = 'Global Water'

    try:
        baroid = well_table.loc[wellid, 'BaroLoggerType']
        printmes('{:}'.format(baroid))
        corrwl = well_baro_merge(well, baro_out[str(baroid)], barocolumn=barocol,
                                      vented=(trans_type != 'Solinst'))
    except:
        corrwl = well_baro_merge(well, baro_out['9003'], barocolumn=barocol,
                                      vented=(trans_type != 'Solinst'))

    # be, intercept, r = clarks(corrwl, 'barometer', 'corrwl')
    # correct barometric efficiency
    wls, be = correct_be(wellid, well_table, corrwl)

    # get manual groundwater elevations
    # man, stickup, well_elev = self.get_gw_elevs(wellid, well_table, manual, stable_elev = stbl_elev)
    stdata = well_table[well_table['WellID'] == str(wellid)]
    man_sub = manual[manual['Location ID'] == int(wellid)]
    well_elev = float(stdata['Altitude'].values[0]) # Should be in feet

    if stbl_elev:
        if stdata['Offset'].values[0] is None:
            stickup = 0
            printmes('Well ID {:} missing stickup!'.format(wellid))
        else:
            stickup = float(stdata['Offset'].values[0])
    else:

        stickup = man_sub.loc[man_sub.last_valid_index(), 'Current Stickup Height']

    # manual = manual['MeasuredDTW'].to_frame()
    man_sub.loc[:, 'MeasuredDTW'] = man_sub['Water Level (ft)'] * -1
    man_sub.loc[:, 'Meas_GW_Elev'] = man_sub['MeasuredDTW'].apply(lambda x: float(well_elev) + (x + float(stickup)),
                                                                  1)
    printmes('Stickup: {:}, Well Elev: {:}'.format(stickup, well_elev))

    # fix transducer drift

    dft = fix_drift(wls, man_sub, meas='BAROEFFICIENCYLEVEL', manmeas='MeasuredDTW')
    drift = np.round(float(dft[1]['drift'].values[0]), 3)

    df = dft[0]
    df.sort_index(inplace=True)
    first_index = df.first_valid_index()

    rowlist, fieldnames = prepare_fieldnames(df, wellid, stickup, well_elev)

    #    pass
    return rowlist, man_sub, be, drift

def fcl(df, dtObj):
    """Finds closest date index in a dataframe to a date object
    Args:
        df:
            DataFrame
        dtObj:
            date object

    taken from: http://stackoverflow.com/questions/15115547/find-closest-row-of-dataframe-to-given-time-in-pandas
    """
    return df.iloc[np.argmin(np.abs(pd.to_datetime(df.index) - dtObj))]  # remove to_pydatetime()

def fix_drift(well, manualfile, meas='Level', corrwl='corrwl', manmeas='MeasuredDTW', outcolname='DTW_WL'):
    """Remove transducer drift from nonvented transducer data. Faster and should produce same output as fix_drift_stepwise
    Args:
        well (pd.DataFrame):
            Pandas DataFrame of merged water level and barometric data; index must be datetime
        manualfile (pandas.core.frame.DataFrame):
            Pandas DataFrame of manual measurements
        meas (str):
            name of column in well DataFrame containing transducer data to be corrected
        manmeas (str):
            name of column in manualfile Dataframe containing manual measurement data
        outcolname (str):
            name of column resulting from correction
    Returns:
        wellbarofixed (pandas.core.frame.DataFrame):
            corrected water levels with bp removed
        driftinfo (pandas.core.frame.DataFrame):
            dataframe of correction parameters
    """
    # breakpoints = self.get_breakpoints(wellbaro, manualfile)
    breakpoints = []
    manualfile.index = pd.to_datetime(manualfile.index)
    manualfile.sort_index(inplace=True)

    wellnona = well.dropna(subset=[corrwl])

    if manualfile.first_valid_index() > wellnona.first_valid_index():
        breakpoints.append(wellnona.first_valid_index())

    for i in range(len(manualfile)):
        breakpoints.append(fcl(wellnona, manualfile.index[i]).name)

    if manualfile.last_valid_index() < wellnona.last_valid_index():
        breakpoints.append(wellnona.last_valid_index())

    breakpoints = pd.Series(breakpoints)
    breakpoints = pd.to_datetime(breakpoints)
    breakpoints.sort_values(inplace=True)
    breakpoints.drop_duplicates(inplace=True)
    # breakpoints = breakpoints.values
    bracketedwls, drift_features = {}, {}

    if well.index.name:
        dtnm = well.index.name
    else:
        dtnm = 'DateTime'
        well.index.name = 'DateTime'
    breakpoints = breakpoints.values
    manualfile.loc[:, 'julian'] = manualfile.index.to_julian_date()

    for i in range(len(breakpoints) - 1):
            # Break up pandas dataframe time series into pieces based on timing of manual measurements
        bracketedwls[i] = well.loc[
            (pd.to_datetime(well.index) > breakpoints[i]) & (pd.to_datetime(well.index) < breakpoints[i + 1])]
        df = bracketedwls[i]
        if len(df) > 0:
            df.sort_index(inplace=True)
            df.loc[:, 'julian'] = df.index.to_julian_date()

            last_trans = df.loc[df.last_valid_index(), meas]  # last transducer measurement
            first_trans = df.loc[df.first_valid_index(), meas]  # first transducer measurement
            first_trans_date = df.loc[df.first_valid_index(), 'julian']
            last_trans_date = df.loc[df.last_valid_index(), 'julian']

            first_man = fcl(manualfile, breakpoints[i])
            last_man = fcl(manualfile, breakpoints[i + 1])  # first manual measurment

            if df.first_valid_index() < manualfile.first_valid_index():
                first_man[manmeas] = None

            if df.last_valid_index() > manualfile.last_valid_index():
                last_man[manmeas] = None

            # intercept of line = value of first manual measurement
            if pd.isna(first_man[manmeas]):
                b = last_trans - last_man[manmeas]
                drift = 0.000001
                slope_man = 0
                slope_trans = 0
                new_slope = 0
            elif pd.isna(last_man[manmeas]):
                b = first_trans - first_man[manmeas]
                drift = 0.000001
                slope_man = 0
                slope_trans = 0
                new_slope = 0
            else:
                b = first_trans - first_man[manmeas]
                drift = ((last_trans - last_man[manmeas]) - b)
                slope_man = (first_man[manmeas] - last_man[manmeas]) / (first_man['julian'] - last_man['julian'])
                slope_trans = (first_trans - last_trans) / (first_trans_date - last_trans_date)
                new_slope = slope_trans - slope_man

            # slope of line = change in difference between manual and transducer over time;
            m = drift / (last_trans_date - first_trans_date)

            # datechange = amount of time between manual measurements
            df.loc[:, 'datechange'] = df['julian'].apply(lambda x: x - df.loc[df.index[0], 'julian'], 1)

            # bracketedwls[i].loc[:, 'wldiff'] = bracketedwls[i].loc[:, meas] - first_trans
            # apply linear drift to transducer data to fix drift; flipped x to match drift
            df.loc[:, 'DRIFTCORRECTION'] = df['datechange'].apply(lambda x: new_slope * x, 1)
            df.loc[:, outcolname] = df[meas] - (df['DRIFTCORRECTION'] + b)

            drift_features[i] = {'t_beg': breakpoints[i], 'man_beg': first_man.name, 't_end': breakpoints[i + 1],
                                 'man_end': last_man.name, 'slope_man': slope_man, 'slope_trans': slope_trans,
                                 'intercept': b, 'slope': m, 'new_slope': new_slope,
                                 'first_meas': first_man[manmeas], 'last_meas': last_man[manmeas],
                                 'drift': drift, 'first_trans': first_trans, 'last_trans': last_trans}
        else:
            pass

    wellbarofixed = pd.concat(bracketedwls)
    wellbarofixed.reset_index(inplace=True)
    wellbarofixed.set_index(dtnm, inplace=True)
    drift_info = pd.DataFrame(drift_features).T

    return wellbarofixed, drift_info

def jumpfixagg(df, meas, thresh=0.03, window=24, maxiter=15, return_jump=False):
    """This is a more aggressive version of the jumpfix function.
    It uses the diference between the average of two windows around the jump.
    It removes jumps or jolts in time series data (where offset is lasting).

    Args:
        df (object):
            dataframe to manipulate
        meas (str):
            name of field with jolts
        thresh (float):
            size of jolt to search for
        window (int):
            number of hours to average around the jump
        maxiter (int):
            max number of iterations to run remove jumps
        return_jump (bool):
            if True, returns a Dataframe showing jump locations and magnitudes
    Returns:
        df1: dataframe of corrected data
        jump: dataframe of jumps corrected in data
    """
    df1 = df.copy(deep=True)
    df1.loc[:, 'diff'] = df1[meas].diff()

    jump = df1[(abs(df1['diff']) >= thresh)]
    jump.loc[:, 'cumul'] = jump.loc[:, 'diff'].cumsum()
    jump1 = jump.copy(deep=True)
    jaa = 1000
    iterstart = 0

    while abs(jaa) > 1e-5:
        jas = []
        for i in jump.index:
            ja1 = df1.loc[i:i + datetime.timedelta(hours=window), meas].mean()
            ja2 = df1.loc[i - datetime.timedelta(hours=window):i, meas].mean()
            ja = ja1 - ja2
            jud = df1.loc[i]
            # ax1.scatter(jt,ja)
            df1.loc[i:, meas] = df1.loc[i:, meas].apply(lambda x: x - ja, 1)
            jas.append(ja)
        jaa = np.mean(jas)

        df1.loc[:, 'diff'] = df1.loc[:, meas].diff()
        jump = df1[(abs(df1['diff']) >= thresh)]
        jump.loc[:, 'cumul'] = jump.loc[:, 'diff'].cumsum()
        iterstart += 1
        if iterstart >= maxiter:
            break

    df1 = df1[abs(df1['diff']) <= thresh].resample('1H').asfreq().interpolate(method='time')

    if return_jump:
        print(jump1)
        return df1, jump1
    else:
        return df1

def compile_end_beg_dates(infile):
    """ Searches through directory and compiles transducer files, returning a dataframe of the file name,
    beginning measurement, and ending measurement. Complements xle_head_table, which derives these dates from an
    xle header.
    Args:
        folder (directory):
            folder containing transducer files
    Returns:
        A Pandas DataFrame containing the file name, beginning measurement date, and end measurement date
    Example::
        >>> compile_end_beg_dates('C:/folder_with_xles/')

    """
    filelist = glob.glob(infile)
    f = {}

    # iterate through list of relevant files
    for infile in filelist:
        f[getfilename(infile)] = new_trans_imp(infile)

    dflist = []
    for key, val in f.items():
        if val is not None:
            dflist.append((key, val.index[0], val.index[-1]))

    df = pd.DataFrame(dflist, columns=['filename', 'beginning', 'end'])
    return df

def xle_head_table(folder):
    """Creates a Pandas DataFrame containing header information from all xle files in a folder
    Args:
        folder (directory):
            folder containing xle files
    Returns:
        A Pandas DataFrame containing the transducer header data
    Example::
        >>> xle_head_table('C:/folder_with_xles/')
    """
    # open text file
    df = {}
    for infile in os.listdir(folder):

        # get the extension of the input file
        filename, filetype = os.path.splitext(folder + infile)
        basename = os.path.basename(folder + infile)
        if filetype == '.xle':
            # open text file
            with open(folder + infile, "rb") as f:
                d = xmltodict.parse(f, xml_attribs=True, encoding="ISO-8859-1")
            # navigate through xml to the data
            data = list(d['Body_xle']['Instrument_info_data_header'].values()) + list(
                d['Body_xle']['Instrument_info'].values())
            cols = list(d['Body_xle']['Instrument_info_data_header'].keys()) + list(
                d['Body_xle']['Instrument_info'].keys())

            df[basename[:-4]] = pd.DataFrame(data=data, index=cols).T
    allwells = pd.concat(df)
    allwells.index = allwells.index.droplevel(1)
    allwells.index.name = 'filename'
    allwells['trans type'] = 'Solinst'
    allwells['fileroot'] = allwells.index
    allwells['full_filepath'] = allwells['fileroot'].apply(lambda x: folder + x + '.xle', 1)

    return allwells

def csv_info_table(folder):
    csv = {}
    files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
    field_names = ['filename', 'Start_time', 'Stop_time']
    df = pd.DataFrame(columns=field_names)
    for file in files:
        fileparts = os.path.basename(file).split('.')
        filetype = fileparts[1]
        basename = fileparts[0]
        if filetype == 'csv':
            try:
                cfile = {}
                csv[basename] = new_csv_imp(os.path.join(folder, file))
                cfile['Battery_level'] = int(round(csv[basename].loc[csv[basename]. \
                                                   index[-1], 'Volts'] / csv[basename]. \
                                                   loc[csv[basename].index[0], 'Volts'] * 100, 0))
                cfile['Sample_rate'] = (csv[basename].index[1] - csv[basename].index[0]).seconds * 100
                cfile['filename'] = basename
                cfile['fileroot'] = basename
                cfile['full_filepath'] = os.path.join(folder, file)
                cfile['Start_time'] = csv[basename].first_valid_index()
                cfile['Stop_time'] = csv[basename].last_valid_index()
                cfile['Location'] = ' '.join(basename.split(' ')[:-1])
                cfile['trans type'] = 'Global Water'
                df = df.append(cfile, ignore_index=True)
            except:
                pass
    df.set_index('filename', inplace=True)
    return df, csv

class wellmod(object):
    def __init__(self):
        self.sde_conn = None
        self.well_file = None
        self.baro_file = None
        self.man_startdate = None
        self.man_enddate = None
        self.man_start_level = None
        self.man_end_level = None
        self.wellid = None
        self.xledir = None
        self.well_files = None
        self.wellname = None
        self.welldict = None
        self.filedict = None
        self.man_file = None
        self.save_location = None
        self.should_plot = None
        self.chart_out = None
        self.tol = None
        self.stbl = None
        self.ovrd = None
        self.toexcel = None
        self.baro_comp_file = None
        self.to_import = None
        self.idget = None

    def read_xle(self):
        well = new_xle_imp(self.well_file)
        well.to_csv(self.save_location)
        return

    def remove_bp(self):

        well = new_trans_imp(self.well_file)
        baro = new_trans_imp(self.baro_file)

        df = well_baro_merge(well, baro, barocolumn='Level', wellcolumn='Level', outcolumn='corrwl', vented=False,
                                  sampint=60)

        df.to_csv(self.save_location)

    def remove_bp_drift(self):

        well = new_trans_imp(self.well_file)
        baro = new_trans_imp(self.baro_file)

        man = pd.DataFrame(
            {'DateTime': [self.man_startdate, self.man_enddate],
             'MeasuredDTW': [self.man_start_level * -1, self.man_end_level * -1]}).set_index('DateTime')

        corrwl = well_baro_merge(well, baro, barocolumn='Level', wellcolumn='Level', outcolumn='corrwl',
                                      vented=False,
                                      sampint=60)

        dft = fix_drift(corrwl, man, meas='corrwl', manmeas='MeasuredDTW')
        drift = round(float(dft[1]['drift'].values[0]), 3)

        printmes("Drift is {:} feet".format(drift))
        dft[0].to_csv(self.save_location)

        if self.should_plot:
            pdf_pages = PdfPages(self.chart_out)

            # plot data
            df = dft[0]
            y1 = df['DTW_WL'].values
            y2 = df['barometer'].values
            x1 = df.index.values
            x2 = df.index.values

            x4 = man.index
            y4 = man['MeasuredDTW']
            fig, ax1 = plt.subplots()
            plt.xticks(rotation=70)
            ax1.scatter(x4, y4, color='purple')
            ax1.plot(x1, y1, color='blue', label='Water Level')
            ax1.set_ylabel('Depth to Water (ft)', color='blue')
            ax1.set_ylim(min(y1), max(y1))
            y_formatter = tick.ScalarFormatter(useOffset=False)
            ax1.yaxis.set_major_formatter(y_formatter)
            ax2 = ax1.twinx()
            ax2.set_ylabel('Barometric Pressure (ft)', color='red')
            ax2.plot(x2, y2, color='red', label='Barometric pressure (ft)')
            h1, l1 = ax1.get_legend_handles_labels()
            h2, l2 = ax2.get_legend_handles_labels()
            ax1.legend(h1 + h2, l1 + l2, loc=3)
            plt.xlim(df.first_valid_index() - datetime.timedelta(days=3),
                     df.last_valid_index() + datetime.timedelta(days=3))

            pdf_pages.savefig(fig)
            plt.close()
            pdf_pages.close()

    def get_ftype(self, x):
        if x[1] == 'Solinst':
            ft = '.xle'
        else:
            ft = '.csv'
        return self.filedict.get(x[0] + ft)


The Texas Animal Health Commission and the Texas Parks and Wildlife Department have confirmed that another whitetail deer, located in the 'index herd facility' in Medina County, has tested positive for CWD. The sample was processed by the Texas Veterinary Medical Diagnostic Laboratory in College Station, and has been sent to the National Veterinary Service Laboratories in Ames, Iowa, for confirmation. The sample was from a Tier One animal born at the facility.


The International Documents Taskforce (IDTF) focuses attention on problems and concerns related to international and foreign national government information. The IDTF provides a forum for the discussion of ideas, problems, and news in the field; serves as a force for initiating and supporting programs to increase the accessibility and use of this information; and works to improve bibliographic control and collection development for these information resources.
IGO search: A project using Google to create a search engine for Intergovernmental Organizations (IGOs). An additional search engine for NGOs has also been created. Code for both search engines is available on IGO search.
Publishing Policies and Practices: an IDTF project to document acquisitions and collection development information specific to international organizations, national governments and the vendors with whom they work.
United Nations Depository: Review of the distribution of United Nations publications to depository libraries.
Workspace: This is the space for IDTF working/living documents from various ad hoc groups, meeting presentations etc.
This page was last modified on 27 February 2018, at 10:41.


text:
vilensky.com.pl
KONSTANTIN VILENSKY is a composer, classic and jazz-pianist, professor of piano, harmony and orchestration. He is a member of the Union of Composers of USSR from 1984. Since 1991 – member of the Union of Composers of Ukraine. Member of the Russian Authors Society (Moscow). He was born in the family with the great music traditions. His grandfather, composer Ilya Vilensky was the first director of Philharmonic Society and organizer 3 dramatics theatres in Kiev. Famous artists visited their home like Vladimir Horovitz and Henryk Neuhaus. K.Vilensky graduated from Kiev State Conservatoire and completed post-graduate course. His professors were A.Shtogarenko (composition), R.Lysenko (piano). At that time he had consulted with well-known composers such as Rodion Shtchedrin, Aram Hatchaturian. From 1983 to 1995 he has taught harmony, orchestration and improvisation at the Kiev State Conservatoire. He is a composer and concert pianist virtuoso with a talent for combining classical and jazz performing practice. He plays and writes various kinds of music, from vocal-symphonic and symphonic to theatre, chamber and jazz music. He has given concert with such outstanding orchestras as the Royal Orchestra in Brussels, Jerusalem Symphony, Moscow Philharmonic. K.Vilensky has won numerous prizes at international music festivals such as: "Polish Classic 98" (Opole), Jewish Music Festival (London, July, 92, Jerusalem, August, 96) – the kind of composer, GOLOSEJEVO 88(Kiev), XI International Moscow Festival, SOLO-DUO-TRIO (Krakow,1989), "Falsterbo International Music Festival". He performed Beethoven's B major concerto for piano and orchestra in Falsterbo, Sweden, July 1998. He has made many radio and television appearances and recorded twelve discs – "Lunnyj serp" Melodiya, Moscow (1986), "All the things you are" Melodiya, Moscow (1988), "JAZZ Trio Duet Solo" KOHC (2001), "Konstantin Vilensky Works for Piano" (KOHC,2001) "Flute in love" (print in Israel 2003), "Bolling Vilensky" (Polish Radio, Warsaw, 2004), "Scott Joplin Ragtimes" (Radio Gdansk, Gdansk, 2005), "Mozart-Blues" (Israel,2008), K.Vilensky "Kashubian Suite" (Dziennik Bałtycki, 2018), "Classical Meets Jazz" (Soliton, 2019), "Solo" (Soliton, 2020), "Swinging Christmas" (Soliton, 2020). Since 1996-2001 K.Vilensky has been music director of dramatic theatre by Stefan Zeromski (Kielce,Poland). He is author of the musical "Kopciuszek" ("Cinderella"), chosen by the public as the best performance in 1997 such as "King Lear" in 2001. Music of the poems by A.Mickiewicz – "Ballads and romantic songs", which received high praise by critics both in London (Premiere was in London, February 1998) and Poland ("Polish Classic 1998", Opole, March-April 1998). Being the kind of piano composer he is, he has received great acknowledgement over the last couple of years by many famous pianists all over the world. Many pianists in various countries have played piano compositions by K.Vilensky. His most popular piano compositions such as: "SONATA" for piano … The step between works by the living Vilensky and the highly romantic Franz List, who died in 1886, was actually rather short. Both of them excels in difficult and heavy passages which require great technique and well developed musical competence. MASTERLY PIANO PERFORMANCE AT THE MARINE MUZEUM , Jane Betts BLT (Blekinge Läns Tidning) 29 august 1997 SWEDEN. VARIATIONS ON THE THEME BY PAGANINI" for piano, jazz-trio & symphony orchestra, "THE DEVIL'S DANCE" for two pianos, "CONCERT-FANTASY ON THE THEMES BY GERSHWIN" for piano, jazz-trio and symphony orchestra. One of his works is the treatment for piano of "THE FLIGHT OF THE BUMBLE BEE" by Rymski-Korsakov. In a short time, this work became very popular in many countries. Attraction of the creations by K.Vilensky consists of a combination of classic and jazz. The attractiveness of Konstantin Vilensky's musical oeuvre lies in the symbiosis that he achieves between classical and jazz music. Today, this musician's ambition is to build bridges between jazz and classical music. This is what distinguishes him from among the majority of "very serious" composers and what makes for his originality … (Ruch Muzyczny, Poland, 19th March 2000).

redpajama_set_name: RedPajamaCommonCrawl


This Elegant Lamp Features A Tapered Cut Crystal Column, Displayed With A Thick Crystal Sphere, Creating A Timeless Design That's Paired With Brushed Nickel Plated Details For An Updated Appeal. The Round Hardback Drum Shade Is A White Linen Fabric.
The Table Lamps Crista Crystal Lamp by Uttermost at Mueller Furniture in the Lake St. Louis, Wentzville, O'Fallon, MO, St.Charles, St.Louis Area, MO Furniture Store and Belleville, Shiloh, O'Fallon,IL area. Product availability may vary. Contact us for the most current availability on this product.


Disclosure: If you buy 286 GH/s by Crypto Star, the amounts are as follows. $22.88 costs (0.004226 BTC at today's exchange rate). This mining capacity generates around 0.218249099 BMC / 0.03 USD per day after removing maintenance.


text:
Share on Facebook(6.7k) Tweet Share Email Print
Justice Department Quietly Updates One Rule, Clears the Way for Executions by Firing Squad for Federal Crimes
By Samantha Chang, The Western Journal
Published November 30, 2020 at 11:49am
The Department of Justice has finalized amendments to authorize federal executions by firing squad.
Before the proposed new protocol, lethal injection was the most widely used method for capital punishment.
While the optics of a firing-squad execution may be harsh, experts say it's less prone to error, according to the Death Penalty Information Center. Therefore, they contend that it's actually more humane.
Executions via firing squads are simpler and more effective than lethal injections, which have a shocking 7.1 percent error rate.
Indeed, lethal injections had the highest rate of botched executions, according to research compiled by Austin Sarat, a professor of jurisprudence at Amherst College.
TRENDING: Twitter Employee Leaks Secretly Recorded Video Of Jack Dorsey Revealing Censorship Agenda
According to the Justice Department's amended rule, which takes effect on Dec. 24, "Federal executions are to be carried out by lethal injection 'or by any other manner prescribed by the law of the State in which the sentence was imposed,'" which in some states includes death by firing squad, electrocution or inhalation of nitrogen gas.
Presumptive president-elect Joe Biden "opposes the death penalty now and in the future" and will try to abolish it, his campaign press secretary told The Associated Press.
However, Biden stopped short of definitively declaring that he would pause all federal executions if he were installed as president.
Ironically, Democrats oppose the death penalty as cruel and inhumane, even though they gleefully supporting aborting a baby until the moment of birth.
Presumptive vice president-elect Kamala Harris — who has been slammed for throwing countless black men in jail during her controversial tenure as California attorney general — said there should be a federal moratorium on executions.
In 2019, when she was running for president in the Democratic primary election, Harris said there would no federal executions if she won the White House.
That was a major flip-flop for Harris, who staunchly defended the death penalty as California's attorney general.
Harris reversed her stance on the death penalty by playing the race card to pander to black and Latino voters, claiming they were more likely to be executed than white defendants. In so doing, Harris blasted the death penalty as "immoral, discriminatory, ineffective, and a gross misuse of taxpayer dollars."
Capital punishment is currently authorized by the federal government, the U.S. military and 28 states.
President Donald Trump has repeatedly called for the death penalty for cop killers.
"We believe the right punishment for all cop killers is called the death penalty," Trump said in 2018 at an event for law enforcement officials in Kansas City, Missouri.
Trump said he understands that capital punishment is controversial, but to him, it only makes sense to authorize the death of a thug who murders police.
"You know in some circles that is very controversial to say that — and we have all of the television cameras rolling back here — for me it's not even a little bit controversial," Trump said. "You kill a cop, and it's called the death penalty, OK."
The comical irony of Democrats opposing the death penalty for violent criminals while allowing babies to be torn out of their moms' uteruses until the moment of birth underscores the yawning chasm between the political left and the right.
Samantha Chang, The Western Journal
Rush Limbaugh Issues Dire Prediction About Future: 2022 Isn't Going to Save Us, 'Wake the Hell Up'
Report: Fed Prosecutor Reveals Capitol Rioters' Goal Was To 'Capture And Assassinate Elected Officials'


Assessor plat of Associated Almond Growers Independence Tract No. 5, Sheet 6 of 7 [13U] in Township 24S, Range 13E, Monterey County, California.
"Book No. 424; Township 24S, Range 13E, Plat of Associated Almond Growers Independence Tract No. 5, Sheet 6 of 7 [13U] - June 1920" (2018). Maps, Plats, Sketches & Surveys. 558.


For a Company able to display the name 'Mitsubishi Electric' and the famous red diamonds within its branding, the art of innovation should come as no surprise, but for Mitsubishi Electric, the goal of continuous improvement doesn't derive from a sense of personal status, rather than from a commitment to customers, business partners and the growth of the wider market.
Mitsubishi Electric comprises more than 130,000 employees across a truly worldwide footprint, turning over approximately US$37 billion each year. With 30 factories in Japan alone, its influence is unrivalled, but its values remain grounded.
"It all comes down to our policy of strong quality and the importance of delivering high quality products and services to market," opens and emphasises Mitsubishi Electric Europe BV's Marketing Director Factory Automation for EMEA, Klaus Petersen. "This notion has been part of the Mitsubishi Electric Group since its founding in 1921 and is confirmed by Mitsubishi Electric's customers to this day who testify that our products, once installed, just run and run and run!
The foremost reason attributed to such sustainable prominence is the Company's ability to merge production and development; the two arms working harmoniously and collaboratively at their Japanese headquarters in order to sing off the same hymn sheet, and work towards a common goal: quality.
"This is applicable to all the different business units we have," Petersen explains. "We of course have Factory Automation which is where I'm coming from and what I'm representing here in EMEA. But then, to name just the best known, you also have living environment systems like air conditioning systems, etc., while we are also active in the areas of elevators, transportation, energy, space, and of course we are a supplier to the automotive industry as well.
Such scope is rare in the industry but not unique. A select few competitors can indeed boast their own large ranges of products for their customers, which they then promote as part of a turnkey, 'one-size-fits-all' offering.
This is where Mitsubishi Electric differentiates itself though, in optimising its vast array of products and skills not to create a standardised remit, but to become the most flexible, customisable and customer-centric provider in the industry.
"We're a customer-oriented Company and this is pivotal when you look at the latest market trends, and how quickly they can change," Petersen says. "If you look at industry 4.0 or the Internet of Things (IoT), customers were very confused to begin with, and this makes these trends more of a customer requirement than a market requirement. So we target our offering to the customers, rather than generally to the market.
This philosophy is reflected in the groundbreaking initiative in place since 2003 called e-F@ctory. This allows - in cooperation with the Company's e-F@ctory Alliance partners - for example predictive maintenance solutions and smart services to be formed based on the specific applications, patterns and requirements of each particular customer; using data in real time to create information and solutions bespoke to each client's industry, market, systems and challenges in their digital transformation process.
The consideration of flexibility and collaboration begins in the production and development phase, with aspects of integration heavily promoted throughout Mitsubishi Electric's products in order to reduce the complexity of the end solutions. Instead of encouraging customers to learn, adopt and purchase numerous different controls for different applications, Mitsubishi Electric promotes a concept of integration in order to oversee all controls via one solution.
Continuous improvements of customer interactions also dictate internal drivers, with the Company constantly addressing its touch points and its interaction channels in order to enhance levels of communication and client satisfaction.
Both this and indeed the Company's internal ethos hark to yet another unique facet of Mitsubishi Electric: its Japanese origins and the unique Japanese business culture that still permeates the entire global Group.
"I've worked for German and American companies in the past but this is my first Japanese employer and it's a whole new world. It's very exciting and gives you a new view on how to operate professionally. It is a different universe from any other culture," Petersen notes. "It all starts with the Japanese culture which emphasises generating decisions as a Group rather than taking the lead from decisions made at the top of a structure, and the lower levels just accepting it.
The old saying by Peter Drucker, 'culture eats strategy for breakfast', rings true for Petersen, and it is instilled into each employee from their first day in the Company. An increasing number of employees are sent to Japan for a period of time to truly experience and embrace the culture and the way of doing business; while employees at the Japanese headquarters similarly come over to Europe to broaden their market understanding as well.
A similar cultural fit is required within Mitsubishi Electric's supply chain too, where substance and mutual win-win collaboration trumps size or status.
Everything that Mitsubishi Electric has championed, embraced, adhered to and encapsulated over the years is epitomised by the e-F@ctory concept; an idea that not only aligns with the Company's longstanding philosophies, but that does so in a way that differentiates the business from anything else available in the industry.
Alongside the e-F@ctory Alliance partners, Mitsubishi Electric is once again proving that a one-size-fits-all approach is not the Holy Grail when it comes to manufacturing operational excellence.
"Every sector, then every sub-sector, then every company within that sub-sector has its own set of unique requirements, so you can never truly meet every requirement with a one-size-fits-all approach," Petersen affirms. "Taking MES (manufacturing execution systems) as an example, these will differ completely whether you're in the automotive, pharma, chemicals, food & drink or whichever industry.
Already today and over the coming years, e-F@ctory will serve as the foundation of the progression that Mitsubishi Electric is striving for in mastering the opportunities brought about by industry 4.0 and IoT.
Petersen concludes: "We're living in a disruptive industry. Manufacturing organisations need to understand what they have to change today and implement these changes over the coming years to remain competitive.


text:
The Kid's Doctor: 'Concussion' Sparks Debate Among Football Parents
By SUE HUBBARD and Tom Condon
www.kidsdr.com |
As the end of football season nears, with bowl games for colleges and playoffs for the NFL, a week does not go by that we don't hear about a player who has been diagnosed with a concussion. The debate surrounding football players and concussions will only get louder as more people see the new the film "Concussion." The movie starring Will Smith will have broad appeal for kids and adults as it is a "sports thriller as well as a medical drama."
"Concussion" is the story of a doctor, Bennet Omalu, and his discovery that concussions cause long term neurological consequences and his persistence in fighting the NFL. He forced the NFL to admit to the problem, and his groundbreaking research has led to ongoing changes in the treatment of concussions both on and off the field.
As a parent of three sons (full disclosure here), I must admit that our youngest son played football. We had somehow managed to "dodge the football bullet" until the third boy came along.
He was the most athletic (his brothers would tell you that is because they taught him to play "up" with them in any sport), and started playing football in elementary school. (We are from Texas where football is king). Fortunately, or unfortunately, he was good, as was his team, and they all went on to play through middle school, where they won the league championship, and then into high school.
[Business] Problem Solved: Is he banned by Flipkart, or not? »
He loved the sport, and begged us to keep letting him play. Despite numerous conversations and our dismay that he wanted to continue to play football, he did play. Of course we "bought him the best helmets" (not knowing then that studies would show that that is not enough), and we prayed every time he took the field that he would not get hurt.
He did get hurt.
During his senior year he suffered a shoulder injury and had major surgery. Doctors took a tendon from his knee to put into his shoulder, and he vowed never to play again. He also figured out "that he was not the best player on the team," which does not mean you can't get hurt.
But, with all of the new studies and good data on CTE (chronic traumatic encephalopathy) related to head injuries and concussions, I called and asked him if he thought he had ever had a concussion. Certainly, we never noted anything, but again this was about 10 years ago. To my surprise, and in retrospect, he thinks he probably did "have a couple of concussive like events," but he never told anyone — not his parents, coach or trainer — about his symptoms. He only missed the end of his senior year due to his shoulder injury, not a concussion. Thankfully, he seems to be OK, is currently getting his MBA and does not even play recreational football.
Legislators want Connecticut to join multi-state agreement ending subsidies to lure businesses across state lines
After reviewing all of the new data and the guidelines for return to play (RTP) and seeing the kids I have screened for concussions kept out of games, I am not sure what I would do today if our child wanted to play football. That is the biggest question that parents are now facing. Do you LET your child play football knowing about the risk of head injuries and the possibility of long-term injury to a still developing brain? An injury that may not be reversible?
[Business] Car Talk: Slow and steady wins the Prius race »
The American Academy of Pediatrics has recently come out with a zero tolerance policy for head-first hits in football, and the Council on Sports Medicine and Fitness has written the policy on tackling in youth football (Pediatrics, Oct. 25, 2015), which includes seven recommendations to help make football safer. As Gregory Landry, M.D., one of the lead authors states, "Participants in football must decide whether the potential health risks of sustaining injuries are outweighed by the recreational benefits."
So, who is to decide? The parent, the underage child or both? Good questions, but there are many different opinions on the answers.
Submit questions at www.kidsdr.com.
End of an era: UTC delivers last quarterly financial results before April merger with Raytheon and its move to Massachusetts as rebranded Raytheon Technologies
Ex-president of Ferguson construction businesses sentenced to 20 months for cheating employees
Windsor Locks Police Welcome K-9 Abby


text:
Home of TheNFLGirl
19 down and still counting..
September 25, 2009 thenflgirl Leave a comment
Week 2 of the new season..wow how I missed football. No offense to the other sports but they dont call me NFL Girl for nothing. I have become quite the fanatic over the years..but enough about me let's get on with the business…
The Detroit Lions…sigh. Wow..what can you say about them? Umm…well let's start with how they ended up in this tragic mess. In 2000 William Clay Ford Sr., the owner of the Lions, decided to hire Matt Millen as his CEO and general manager. Now what Bill Ford saw in Matt Millen no one to this day is quite sure. He had ZERO front office experience or player development knowledge. While he was a decent player and a pretty good commentator, the thought of him being able to make executive and even staffing decisions for a NFL franchise seemed unfathomable.
Fast forward to the next several drafts. Millen made extremely poor draft choices including drafting 4 receivers in 4 straight years which completely baffled most forecasters. The need for players on the defense (which was being scored on at will) or a good quality QB (which they had lacked for years) seemed more pressing. His choices were not only confusing but many were extremely overrated and under talented. The Lions began a downward spiral that only seemed to get progressively worse each season. Lions fans became increasingly angry and frustrated with Millen, begging for his removal. However, despite their pathetic record (31-97 by the end of his 8 years there), ownership stuck by him and even signed him to a contract extension in 2005. Now even I cant explain this..I mean seriously..when do you realize someone is dragging your team to the abyss? During his time there the Lions had a losing season every single year. Despite repeated head coaching changes and player changes, the team continued to lose. Finally at the beginning of the 2008/2009 season ownership had enough and fired Millen. Unfortunately because of the previous bad draft picks, poor trades and free agent losses, the team was a wreck. Millen had left a mess behind and the Lions would suffer greatly because of it.
2008 season…a train wreck for the Lions. The Lions became the only team in the modern era (70s and beyond) other than the 76 Bucaneers to lose every game in a single season and the only one since the NFL switched to a 16 game season. So far they have started this season 0-2 with a pretty tough schedule (they must face the AFC North & NFC West this season as well as their tough divison rivals the Packers, Bears & Vikings) ahead of them. Their 0-19 record going back to the 2007 season is tied for the 2nd worst all time behind the 76 Bucaneers (who went 0-26 in their first 2 seasons in the league).
Now on a bright note (if we can find one in the darkness that is the Lions), Lions have made some personnel shift that may help them to improve dramatically. First they hired Jim Schwartz (Titans former defensive coordinator) and brought him on as head coach. They hired Scott Linehan as their offensive coordinator and Gunther Cunningham as their defensive coordinator. While many of the Lions former draft picks have jumped ship or left the NFL, one good receiver, Calvin Johnson, remains. He is a tall, strong, fast receiver with amazing leaping and catching ability. With the addition of Matthew Stafford at quarterback, the hopes of the Lions rebuilding and becoming a competitive team again seems a little more likely. Despite not winning their 2nd game, they played competively and even jumped out to an early lead over the Vikings. Stafford and Johnson hooked up on several occasions making it clear that they will be a good combination. Will the Lions be able to build on these bright spots? Can they shift from a decade of losing to becoming a competive team again? This is the part that remains to be seen. At this point I think Lions fans would be happy just to get a win or 2. Can they do it and keep from tying or breaking the Bucaneers record of losses? We can always hold out hope.
← Michael Crabtree..What is wrong with this child?
Week 3 Predictions →
Copyright © 2022 She Knows Pro Football


text:
Louisiana	LA
Donate to Stand for Children Leadership Center
Support Early Childhood Education
Elect Education Champions
Education Leadership Institute
LEAD Fellowship
Resources & Relief during COVID-19
Financial & Family Resources
Health & Wellness Resources
Resources by Parish
Workshops On-Demand
Louisiana / About Us / Staff / Nikki Dangerfield
Louisiana Staff
Nikki Dangerfield
Regional Organizing Director
ndangerfield@stand.org
Before joining Stand in 2014, Nikki was a graphic designer looking for opportunities to bring systemic improvements to her community. That is when she started volunteering at Stand.
A product of the East Baton Rouge Parish School System, she knows what it is like to be a child who is overlooked and passed onto the next grade despite not being ready. When she started 9th grade, she could not read. It took moving to a new state, a different education system, and having a mother who advocated tirelessly for Nikki to be on track to graduate from high school on time. Now, in her role as Regional Organizing Director, Nikki is righting this wrong by working to close the achievement gap and ensure all students can read proficiently by the end of third grade.
During her time at Stand, Nikki has been instrumental in supporting parents as they become leaders in their children's schools and the East Baton Rouge Parish School System. She loves leading the Stand University for Parents, where she has seen parents go from having very limited interaction with their child's school to becoming the school's most outstanding volunteer. The highlight of her job is supporting parents as they transform into bold, outspoken advocates who testify in front of the school board, interview and endorse candidates during election season, and canvass and phone bank to ensure those education champions are elected.
Nikki has an Associate Degree in Graphic Design, a Bachelor of Arts and Master of Arts in Theology and Religious Studies, and is currently working toward her Doctoral Degree in Christian Counseling.
Nikki is the proud mother of four wonderful children, and currently lives in Baton Rouge with her two youngest sons. When she's not leading parents and fighting for high-quality public education, Nikki enjoys spending time with her children and grandchildren, being active in her church, and at any given time, working on a new self-development project.


text:
Knoxville Lost and Found
The Metamorphosis of Knoxville's Spaces
Requiem for old west Knoxville
I had heard about it, read about it in Property Scope, but I hadn't seen it myself until last night. One of the vestiges of a west Knoxville long forgotten except by those who grew up there from the 40's to the 60's (harder to find than you'd think), fell victim to the bulldozer. It's going to be a Chick-fil-a. The building was unloved, forgotten, and largely ignored by all of those BMW's and Escalades zipping by on the pike. It was the kind of place that polite society might want to pretend didn't exist next to the Starbucks and posh boutiques. It contained Opal's lounge, a sort of rowdy, blue collar place with impossibly cheap beer. There were rusting Oldsmobiles on jack stands and a tarped roof. You had to look pretty hard through the overgrown bush to see all of that, but it was there. I didn't think anyone else would notice, but I was wrong. Making my way through the impersonal, robotic, self-checkout lane at Kroger, I heard a woman of a certain age, who was wearing a fur coat and a fur, leopard print hat, exclaim that "they wouldn't be satisfied until they had paved over everything." This, of course, piqued my interest. She was talking about the Biltmore Court Motel and ranting about the trees. She couldn't believe that they had torn it down and then bulldozed all of the trees. I couldn't either and I couldn't believe that a person in Kroger, west of Sequoyah, shared my concerns. But she was right, the Biltmore, despite its recent history, had been a lovely place.
The bulldozer making its final passes over the former site of the Biltmore Court
Once the site of Bill's Drive-In. That is the original sign, note the neon star. It has survived all of these years and is likely headed to the landfill.
The Biltmore Court as it appeared a couple of years ago
That great neon-sign was removed in March 2011. I wonder what happened to it.
The Biltmore was a "motor court" built in the 1940's, some say 1949, during a time when Kingston Pike, US 11/70, was the main east/west thoroughfare in these parts. Kingston Pike was lined with these sort of places, places that ushered in the glory days of American motoring. There were service stations, restaurants, and a stretching line of motels. Most of them are now gone, some of them have been re-purposed. There was the Colonial Tourist Court, next door to the Biltmore, it's now a parking lot and a Starbucks. The Colony Tourist Court with its gas lamp inspired lighting, served for many years disguised as Colony Square, a shopping center/office building. It's now home to a shopping center that contains Vibe, @Home, and the former WokHay. Another old strip motel exists next to the 37919 post office. I haven't been able to determine what it was called. It houses offices and a paper shop. Further west, there was the Terrace View Motor Lodge. It looked like the kind of place a James Bond villain might have stayed with its super crisp, modern lines. It was bulldozed in the late 90's to become the Nature's Pantry and Well Nutrition (across from Calhoun's on Bearden Hill). The Mount Vernon, onward west, is now a Mattress store. Out near Gallaher View Rd, there is the Time Out Deli. It is located in the front portion of what was once Sharp's Motel and Grill.
Aside from the motels, there were roadhouses, eating establishments geared to the motoring public. One success story, against all odds, is the Highlands Grill. Heading west on Kingston Pike, just past Western Plaza, Old Kingston pike shoots off to the left at Bearden Beer Market (another successfully re-purposed building). Just behind the shopping center containing Long's Drug Store, the road shifts back to the right, and cuts over the railroad tracks to rejoin Kingston Pike. This was once the alignment of Kingston Pike and in that curve over the tracks, was located the Highlands, one of the first roadhouses. It operated from the 30's until the 60's but was then preserved as Andrew Morton's Gift Shop. It has recently been renovated and returned to restaurant service and it is an excellent experience if you haven't been there yet, The Grille at Highlands Row. Next to the Biltmore, was Bill's drive-in. It was a drive in restaurant that also had a dining room with a very western feel. Bill's was torn down years ago, but the platforms for the drive-in portion remained. They were bulldozed along with the Biltmore last week. Across from the Biltmore was the Dixieland. Some will remember it as Pero's Italian restaurant. Most younger folks will remember it as where McKay's bookstore used to be. It was bulldozed and is now a bank. There were many, many more.
Bill's Drive-In. There wasn't much left except for the sign and some foundation pads. I wonder if the "Save our signs" campaign has looked at saving this one. It might be there a few more days.
While all of these places were predecessors to what is now replacing them (Chick-fil-a's, Courtyard Hotels, Walgreens) they had something that none of these new places possess, individuality. These were Knoxville establishments, uniquely so. Sure, other towns had drive-in restaurants, but only Knoxville has the Pizza Palace. Every town has a Starbucks and each time a place like the Biltmore is bulldozed to become another chain restaurant or big box store, Knoxville loses another piece of its distinctiveness. The Homberg neighborhood, a unique part of Knoxville, now looks a little more like Cedar Bluff. It's a march toward becoming Anytown, USA. The woman in Kroger was right though, the Biltmore really was once a very lovely place.
The historical images on this post were borrowed from www.swankpad.org
Bill's Biltmore Court Kingston Pike Knoxville Knoxville History
Labels: Bill's Biltmore Court Kingston Pike Knoxville Knoxville History
Andrea said…
I wrote a blog about this the day it happened. It contains my brief, yet infuriating conversation with the Homburg Chik-fil-a on Facebook. You might be interested: click here
DRS said…
I cant believe they tore those buildings down. That community just lost some of it unique great structures with great historical presence. That is horrible.
And now a stinking $hit-fil-a sits there!
As a child/teen in the 1940s and 1950s the most important establishments along that part of Kingston Pike were the Dixieland Drive-in and the Pike Theater. The Pike Theater building still stands. I couldn't find the Dixieland. They made the best hamburgers.
There was a drive-in movie theater along there, too, across the Pike from the Long's Drug Store shopping center.
Alhambra Court was the one you couldn't locate/identify, there at the Bearden P.O. I remember it as where Olan Mills was located in a converted building, where we kids were dragged for photos!
John F. Weaver, Jr. said…
I don't know. The Alhambra was a collection of separate buildings, this place (now housing Archer's BBQ) is more of a row. I want to say it was called the Cherokee Motel, but I am not committing to that.
Swanky said…
https://www.swankpad.org/site/knoxville-then-and-now/
Several of these places documented a bit here.
322 S. Gay St. - The Terminal Building - The Gaps of Gay Street Part 1
If you have lived in Knoxville for any length of time, or if you've just eaten at the Downtown Grill and Brewery, then you have without a doubt heard of the "Million Dollar Fire of 1897." That fire destroyed much of the east side of the 300 and 400 blocks of Gay Street. Firefighters came from as far away as Chattanooga to battle the blaze, which threatened to burn down the entire city. With the ruins smoldering, city leaders declared it the greatest loss the city had ever suffered. However, times were optimistic and the business community vowed the next day to rebuild the structures better than before. Most of them were rebuilt, bigger and better, within five years.
From the ashes of the fire, rose many of the iconic structures we see today on the 300 and 400 blocks. Identifying them by their current businesses, the buildings that hold Sapphire, Downtown Grill and Brewery, the Art Market, the Phoenix (Clayton Bank), and Mast General Store were all built as replacements …
5709 Lyons View Pike - Westcliff
There has been a lot of discussion in the local property blogs about the proposal of a new shopping development located at the intersection of Cumberland Ave. and Alcoa Hwy. Anyone who has played or follows rugby in Knoxville knows this place very well. It's called Fulton bottoms and the reason it is called Fulton bottoms is that just across third creek was once the principal factory of the Fulton Company.
The Fulton Bellows factory as it appeared in the 1930's. This is looking from the Southeast. Note the train tracks which still exist and Cumberland Ave./Kingston Pk. looking very rural. Most of the background in this picture is taken up by the Alcoa Hwy/Kingston Pike interchange.
Roughly the same view today. The factory is gone. The foundation pads are all that remain.
The story of the Fulton Co. is an interesting but long one. It's probably a subject for another entry, however if you'd like to read the whole story you can find it here, as told by Jack Neely. In s…
The 500 Block of Gay Street, West Side - Krutch Park Extension - The Gaps of Gay Street Part 6
As we continue our tour south down Gay Street, we walk past the 400 block without stopping. The 400 block is one of the few (two) truly unbroken blocks on Knoxville's most important street.
So Bravo 400 Block, though you may look a little different you've weathered the years better than most. No surface parking lots here, so we're uninterested!!!
Let's cross Union Avenue and set foot on the 500 block, under the large porch of the Park National Bank Building (Conley Building, First American Bank Building, 507 S. Gay Tower, Embassy Suites, what have you...). This block has something in common with the 300 block in that it resembles a 7/10 split (for you non-bowlers that means it's missing its middle teeth). The 500 block is probably best known for its two giant bookends, the Park National Bank Building (1974) and the Holston Bank Building (1912). Between the two lies what we now know as "Krutch Park Extension," basically a grassy square with some fountains …
John F. Weaver, Jr.
Knoxville, Tennessee, United States
I am an 8th generation East Tennessean who is fascinated by this community. I aspire to share my knowledge and understanding of this place with newcomers and generational Knoxvillians alike.
An interesting take on urban decay.
417 W. Clinch Avenue
Aconda Court
Arcade Building
Bertha Roth
Bill's
Biltmore Court
Broyles
C.B. Atkin
C.M. McGhee
Cal Johnson
Charles McGhee
Clinch Avenue
Coolato
Downtown Grill and Brewery
Economy Drug
Farragut Hotel
Fogarty's
Fouche
Fouche Block
Fragile 15
Friedman's Jeweler
Gay Street
Hanover Shoes
Holston
Holston Hills
Holston National Bank
Holston River
Hope Brothers
Hotel Arnold
Hotel Atkin
Howard Taft
Jake Butcher
John Sevier Highway
Kimball's
Kingston Pike
Knox Heritage
Knoxville Brewing Company
Knoxville History
Knoxville Journal
Knoxville TVA Employees Credit Union
Krutch Park
Krutch Park Extension
Kuhlman's
Leola Manning
Lone Tree Saloon
Lyons View
Marble City Brewing Company
Max Friedman
McGhee
Moskin's
New Knoxville Brewing Company
Park National Bank
Queen Theatre
R. F. Graf
R. Z. Gill
Raylass
Rich's
Rick Terry Jewelry Designs
Ross Flats
S.H. George
Saw Works Brewing Company
Sherchi and Haun
Southern Railroad
Sprankle
St. James Sessions
Sterchi
T.V.A.
Tennessee Supreme Court
The Holston
United American Bank
Vasey's
VisitKnoxville
W.H. Obenour
W.T. Grant
Wall Avenue
Walnut Street
Walter Damrosch


text:
Lilla Hasselön är ett naturreservat i Forshälla socken i Uddevalla kommun i Bohuslän.

Reservatet består av en ö i Havstensfjorden samt kringliggande vatten sydväst om Uddevalla. Det omfattar 222 hektar och är skyddat sedan 1973. Större delen av öns areal omfattades redan 1965 och 1968 av strandskyddsförordnanden.

Öns högsta punkten ligger 85 meter över havet. Stränderna domineras av klippor, sten, block och branta stup.
Granskog dominerar vegetationen medan det finns lövinslag på östsidan. Där är även fuktigare vaför det växer vitmossor, blodrot, ekbräken, skogskovall, skogsviol och vårfryle. På ön finns även partier av ljunghed och enbuskmarker och hällmarksvegetation.

Som gäststuga fungerar det gamla båtsmanstorpet Fiskartorpet. Huvudbyggnaden är uppförd 1920 och runt denna finns en trädgård. Runt ön finns några sandstränder.

Naturreservatet förvaltas av Västkuststiftelsen.

Referenser

Källor
Lilla Hasselön, Länsstyrelsen i Västra Götalands län

Noter

Naturreservat i Uddevalla kommun
Naturskyddsområden bildade 1973
Sidor om naturreservat i Västra Götalands län som saknar länkar till Länsstyrelsen

redpajama_set_name: RedPajamaWikipedia


Hope - France in the United States / Embassy of France in Washington, D.C.
As part of its Winter film series "Films Across Borders: Stories of Migration", the Cultural Services of the French Embassy present the screening of the 2015 film Hope by Boris Lojkine.
Deep in the Sahara desert, as they try to get to Europe, Leonard, a young man from Cameroon, rescues Hope, a Nigerian woman. In a fiercely hostile world where safety requires staying with one's own people, these two try to find their way together, and to love each other.


Platform for Peace & Justice has released its latest report entitled "Cancellation of Turkish Passports and Prevention of the Freedom of Movement". The report which consists of 17 pages analyses the legal ground for passport cancellations according to domestic and international laws referring to Turkish Constitution and the European Convention on the Human Rights. Shedding light on the abusive use of the cancellation of passports by the current Turkish government, the report illustrates that the long-lasting State of Emergency regime is established deliberately to condemn dissidents to civil death not only by dismissing and arresting them but also destroying their hope and abilities to start new lives elsewhere.
The report also examines cases in which the Red Notice of INTERPOL is also abused by the Turkish government to harras dissidents abroad.
[OPINION] International Women's Day 2018 – How Does Turkey Fare up?


Peter Rotatori, III, firm owner, is a Stamford personal injury lawyer, arbitration and trial attorney with over 30 years of experience. He has represented clients in the following areas of law: civil personal injury law, automobile accident law, workers' compensation accidental injury law, workman's compensation repetitive trauma law,product liability law, product liability defective packaging law, medical malpractice, dental malpractice, nursing home malpractice, catastrophic injury law, real estate fraud, child injury law, dram shop liability, truck accident law, animal injury law, defective premises liability law and construction accident law.
Mr. Rotatori has employed years of dedication, high standards, integrity and excellence in the practice of tort law. His law office is located in picturesque Southbury, Connecticut. He practices in all Connecticut state courts.
Mr. Rotatori has assisted the following out-of-state law firms: Jones Day, Chicago, Illinois, Williams and Montgomery, Chicago, Illinois, Dougherty, Clements and Hofer, Charlotte, North Carolina and Roger N. Schumann, Esq. New York, NY.
Mr. Rotatori has served as a private personal injury arbitrator in civil personal injury cases. Mr. Rotatori can assist Connecticut Lawyers and their clients by way of private arbitration in the following types of personal injury negligence cases : automobile accidents, premises liability, medical malpractice, dental malpractice, wrongful death and uninsured/underinsured contract claims.
Member: The Golf Club at Oxford Greens in Oxford, CT.


text:
Q: Get unparsed element content I want to get the content of an element without it being parsed. In this case the results should be é however all methods I tried parse the content and return é. How do I get the actual content.

console.log('javascript textContent:'+document.getElementById('test').textContent);
console.log('javascript innerText:'+document.getElementById('test').innerText);
console.log('javascript innerHTML:'+document.getElementById('test').innerHTML);
console.log('jQuery text():'+$('#test').text());
console.log('jQuery html():'+$('#test').html());

é

A: The most simple approach would be to use a "backend" language to transform your given char since most of them (for example PHP and .net) provide a built-in function for that.
Unfortunately there is no existing vanilla function that implements this in javascript (at least not to my knowledge).
For example in php this would be:
string htmlentities(string $string....)

For javascript you could create your own solution.
Basically create a list of your needed html entities or take a pre-defined list like this (https://raw.githubusercontent.com/w3c/html/master/entities.json) and work from there on.
Iterate over each object and check if your searched character (é) is present in an object.
To speed up the process I'd save the JSON file to your webhost and maybe reduce its size by removing not needed entities.
It may not be the most beautiful solution but definetly does the job pretty well.

let element = document.getElementById('test').textContent;

fetch("https://raw.githubusercontent.com/w3c/html/master/entities.json")
  .then((resp) => resp.json()) // Transform the data into json
  .then(function(data) {
    Object.keys(data).forEach(function(key){
    if (data.hasOwnProperty(key)){
        if(data[key].characters === element) {
          console.log(key);
        }
    }
});
})

é

redpajama_set_name: RedPajamaStackExchange


Descripción : Our Products includes following ranges.
3, Organic fruit & vegetable powder.
4, Organic herbs straight powders & extracts.
Descripción : We offer BLACK MUSTARD certified with EU and NOP certificates.
Descripción : Sayvo offers Organic Black Mustard in a quantity of 420 tons certified both with EU and NOP certificates.
Descripción : Organic argan oil is offered to cosmetic labs and cosmetic private label formulators as well as importers as one of the most popular cosmetic ingredient for hair and skin care.
Descripción : Unigrà is in the business of transforming and selling oils and fats, margarine and semi-processed products to produce food, especially confectionery.
Founded in 1972 by Luciano Martini, over the years the company has developed its mission to produce top quality primary ingredients, semi-finished and finished products for all the channels in the sector: Industrial, Artisanal, Retail and Ho.Re.Ca.
We are proud to be the first Italian company to obtain certification with a sustainability scheme in the bioliquids sector and renewable energy sources.
Unigrà has been a member of the Roundtable on Sustainable Palm Oil (RSPO) since March 2007. The association was founded in 2004 and finances projects aimed at promoting and defining criteria both for reconverting the tropical forest into palm plantations and for safeguarding and preserving the identity of the local populations.
Care & Health Foods industries.
(pentaclethra macrophylla) and a long list of botanicals.
You are providing economic support to poor rural communities.
You are helping to conserve the biodiversity of Cameroon.
Every producer has been fairly treated and paid a fair price.
Every product has been sustainably harvested.
Every product has a rich African heritage.