text:
import json
import logging
from datetime import date

import cmor
import netCDF4
import numpy as np
import pandas as pd
from cdo import *

# for compressed files
import gzip
import shutil

from ece2cmor3 import cmor_utils, cmor_target, cmor_task

# from cmor.Test.test_python_open_close_cmor_multiple import path

# Logger object
log = logging.getLogger(__name__)

# Experiment name
exp_name_ = None

# Table root
table_root_ = None

# Reference date i.e. the start date given by user as a command line parameter
ref_date_ = None

# lpjg_path_ is the directory where the data files (LPJG .out-files) are located
lpjg_path_ = None

# ncpath_ is the tmp directory where the temporary netcdf files will be placed
ncpath_ = None
ncpath_created_ = False

target_grid_ = "T255"
gridfile_ = os.path.join(os.path.dirname(__file__), "resources/lpjg-grid-content", "ingrid_T255_unstructured.txt")

# list of requested entries for the land use axis
landuse_requested_ = []

# the cmor prefix (e.g. CMIP6) is currently needed to treat the possible requests for land use types, but  might be
# unnecessary in the future depending on how much of the request will be handled in already when writing the model
# output
cmor_prefix_ = None

_months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']

# various things extracted from Michael.Mischurow out2nc tool: ec_earth.py
grids = {
    80: [18, 25, 36, 40, 45, 54, 60, 64, 72, 72, 80, 90, 96, 100, 108, 120, 120, 128, 135, 144, 144, 150, 160, 160, 180,
         180, 180, 192, 192, 200, 200, 216, 216, 216, 225, 225, 240, 240, 240, 256, 256, 256, 256, 288, 288, 288, 288,
         288, 288, 288, 288, 288, 300, 300, 300, 300, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320,
         320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320],
    128: [18, 25, 36, 40, 45, 50, 60, 64, 72, 72, 80, 90, 90, 100, 108, 120, 120, 125, 128, 144, 144, 150, 160, 160,
          180, 180, 180, 192, 192, 200, 216, 216, 216, 225, 240, 240, 240, 250, 250, 256, 270, 270, 288, 288, 288, 300,
          300, 320, 320, 320, 320, 324, 360, 360, 360, 360, 360, 360, 360, 375, 375, 375, 375, 384, 384, 400, 400, 400,
          400, 405, 432, 432, 432, 432, 432, 432, 432, 450, 450, 450, 450, 450, 480, 480, 480, 480, 480, 480, 480, 480,
          480, 480, 486, 486, 486, 500, 500, 500, 500, 500, 500, 500, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512,
          512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512],
}
grids = {i: j + j[::-1] for i, j in grids.items()}

def rnd(x, digits=3):
    return round(x, digits)

def coords(df, root, meta):
    global gridfile_, target_grid_
    # deg is 128 in N128
    # common deg: 32, 48, 80, 128, 160, 200, 256, 320, 400, 512, 640
    # correspondence to spectral truncation:
    # t159 = n80; t255 = n128; t319 = n160; t639 = n320; t1279 = n640
    # i.e. t(2*X -1) = nX
    # number of longitudes in the regular grid: deg * 4
    # At deg >= 319 polar correction might have to be applied (see Courtier and Naughton, 1994)
    deg = 128
    grid_size = len(df)
    if grid_size == 10407:
        target_grid_ = "T159"
        deg = 80
        gridfile_ = os.path.join(os.path.dirname(__file__), "resources/lpjg-grid-content", "ingrid_T159_unstructured.txt")
    elif grid_size != 25799:
        log.error("Current grid with %i cells is not supported!", grid_size)
        exit(-1)

    lons = [lon for num in grids[deg] for lon in np.linspace(0, 360, num, False)]
    x, w = np.polynomial.legendre.leggauss(deg * 2)
    lats = np.arcsin(x) * 180 / -np.pi
    lats = [lats[i] for i, n in enumerate(grids[deg]) for _ in range(n)]

    if 'i' not in root.dimensions:
        root.createDimension('i', len(lons))
        root.createDimension('j', 1)

        latitude = root.createVariable('lat', 'f4', ('j', 'i'))
        latitude.standard_name = 'latitude'
        latitude.long_name = 'latitude coordinate'
        latitude.units = 'degrees_north'
        # latitude.bounds = 'lat_vertices'
        latitude[:] = lats

        longitude = root.createVariable('lon', 'f4', ('j', 'i'))
        longitude.standard_name = 'longitude'
        longitude.long_name = 'longitude coordinate'
        longitude.units = 'degrees_east'
        # longitude.bounds = 'lon_vertices'
        longitude[:] = lons

    run_lons = [rnd(i) for i in (df.index.levels[0].values + 360.0) % 360.0]
    run_lats = [rnd(i) for i in df.index.levels[1]]

    df.index.set_levels([run_lons, run_lats], inplace=True)
    df = df.reindex([(rnd(i), rnd(j)) for i, j in zip(lons, lats)], fill_value=meta['missing'])

    return df, ('j', 'i')

# TODO: if LPJG data that has been run on the regular grid is also used, the corresponding coords function
# from Michael Mischurow's regular.py should be added here (possibly with some modifications)

# Initialization before the processing of the LPJ-Guess tasks
def initialize(path, ncpath, expname, tabledir, prefix, refdate):
    global log, exp_name_, table_root_, ref_date_
    global lpjg_path_, ncpath_, ncpath_created_, landuse_requested_, cmor_prefix_
    exp_name_ = expname
    table_root_ = os.path.join(tabledir, prefix)
    lpjg_path_ = path
    ref_date_ = refdate
    cmor_prefix_ = prefix
    if not ncpath.startswith("/"):
        ncpath_ = os.path.join(lpjg_path_, ncpath)
    else:
        ncpath_ = ncpath
    if not os.path.exists(ncpath_) and not ncpath_created_:
        os.makedirs(ncpath_)
        ncpath_created_ = True
    cmor.load_table(table_root_ + "_grids.json")

    coordfile = os.path.join(tabledir, prefix + "_coordinate.json")
    if os.path.exists(coordfile):
        with open(coordfile) as f:
            data = json.loads(f.read())
        axis_entries = data.get("axis_entry", {})
        axis_entries = {k.lower(): v for k, v in axis_entries.iteritems()}
        if axis_entries['landuse']['requested']:
            landuse_requested_ = [entry.encode('ascii') for entry in axis_entries['landuse']['requested']]

    return True

# Executes the processing loop.
# used the nemo2cmor.py execute as template
def get_lpj_freq(frequency):
    if frequency == "yr" or frequency == "yrPt":
        return "yearly"
    if frequency == "mon":
        return "monthly"
    if frequency == "day":
        return "daily"
    return None

def execute(tasks):
    global log, table_root_
    global lpjg_path_, ncpath_
    log.info("Executing %d lpjg tasks..." % len(tasks))
    log.info("Cmorizing lpjg tasks...")
    taskdict = cmor_utils.group(tasks, lambda t: t.target.table)
    for table, tasklist in taskdict.iteritems():
        try:
            tab_id = cmor.load_table("_".join([table_root_, table]) + ".json")
            cmor.set_table(tab_id)
        except Exception as e:
            log.error("CMOR failed to load table %s, skipping variables %s. Reason: %s"
                      % (table, ','.join([tsk.target.variable for tsk in tasklist]), e.message))
            continue

        lon_id = None
        lat_id = None
        for task in tasklist:
            freq = task.target.frequency.encode()
            freqstr = get_lpj_freq(task.target.frequency)
            if freqstr is None:
                log.error("The frequency %s for variable %s in table %s is not supported by lpj2cmor" %
                          (task.target.frequency, task.target.variable, task.target.table))
                task.set_failed()
                continue

            # if compressed file .out.gz file exists, uncompress it to temporary .out file
            gzfile = os.path.join(lpjg_path_, task.source.variable() + "_" + freqstr + ".out.gz")
            if os.path.exists(gzfile):
                lpjgfile = os.path.join(ncpath_, task.source.variable() + "_" + freqstr + ".out")
                log.info("Uncompressing file "+gzfile+" to temporary file "+lpjgfile)
                with gzip.open(gzfile, 'rb') as f_in, open(lpjgfile, 'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
            else:
                lpjgfile = os.path.join(lpjg_path_, task.source.variable() + "_" + freqstr + ".out")

            if not os.path.exists(lpjgfile):
                log.error("The file %s does not exist. Skipping CMORization of variable %s."
                          % (lpjgfile, task.source.variable()))
                task.set_failed()
                continue
            if not check_time_resolution(lpjgfile, freq):
                log.error("The data in the file %s did not match the expected frequency (time resolution). "
                          "Skipping CMORization of variable %s." % (lpjgfile, task.source.variable()))
                task.set_failed()
                continue
            log.info("Processing file "+lpjgfile)
            setattr(task, cmor_task.output_path_key, task.source.variable() + ".out")
            outname = task.target.out_name
            outdims = task.target.dimensions

            # find first and last year in the .out-file
            firstyear, lastyear = find_timespan(lpjgfile)
            # check if user given reference year is after the first year in data file: this is not allowed
            if int(ref_date_.year) > firstyear:
                log.error("The reference date given is after the first year in the data (%s) for variable %s "
                          "in file %s. Skipping CMORization." % (firstyear, task.source.variable(), lpjgfile))
                task.set_failed()
                continue

            # divide the data in the .out-file by year to temporary files
            yearly_files = divide_years(lpjgfile, firstyear, lastyear, outname)

            for yearfile in yearly_files:

                # Read data from the .out-file and generate the netCDF file including remapping
                ncfile = create_lpjg_netcdf(freq, yearfile, outname, outdims)

                if ncfile is None:
                    if "landUse" in outdims.split():
                        log.error("Land use columns in file %s do not contain all of the requested land use types. "
                                  "Skipping CMORization of variable %s" % (
                                      getattr(task, cmor_task.output_path_key), task.source.variable()))
                    else:
                        log.error(
                            "Unexpected subtype in file %s: either no type axis has been requested for variable %s "
                            "or explicit treatment for the axis has not yet been implemented. Skipping CMORization."
                            % (getattr(task, cmor_task.output_path_key), task.source.variable()))
                    break

                # special treatment of fco2nat=fco2nat_lpjg+fgco2_nemo
                if outname=="fco2nat" and freq=="mon" and table=="Amon" and (cmor.get_cur_dataset_attribute("source_id") == "EC-Earth3-CC"):
                    if not add_nemo_variable(task, ncfile, "fgco2", "1m"):
                        log.error("There was a problem adding nemo variable %s to %s in table %s... "
                                  "exiting ece2cmor3" % ("fgco2", task.target.variable, task.target.table))
                        exit(-1)

                dataset = netCDF4.Dataset(ncfile, 'r')
                # Create the grid, need to do only once as all LPJG variables will be on same grid
                # Currently create_grid just creates latitude and longitude axis since that should be all that is needed
                if lon_id is None and lat_id is None:
                    lon_id, lat_id = create_grid(dataset, task)
                setattr(task, "longitude_axis", lon_id)
                setattr(task, "latitude_axis", lat_id)

                # Create cmor time axis for current variable
                create_time_axis(dataset, task)

                # if this is a land use variable create cmor land use axis
                if "landUse" in outdims.split():
                    create_landuse_axis(task, lpjgfile, freq)

                # if this is a pft variable (e.g. landCoverFrac) create cmor vegtype axis
                if "vegtype" in outdims.split():
                    create_vegtype_axis(task, lpjgfile, freq)

                # if this variable has the soil depth dimension sdepth
                # (NB! not sdepth1 or sdepth10) create cmor sdepth axis
                if "sdepth" in outdims.split():
                    create_sdepth_axis(task, lpjgfile, freq)

                # if this variable has one or more "singleton axes" (i.e. axes
                # of length 1) which can be those dimensions
                # named "type*", these will be created here
                for lpjgcol in outdims.split():
                    if lpjgcol.startswith("type"):
                        # THIS SHOULD BE LINKED TO CIP6_coordinate.json!
                        if lpjgcol == "typenwd":
                            singleton_value = "herbaceous_vegetation"
                        elif lpjgcol == "typepasture":
                            singleton_value = "pastures"
                        else:
                            continue
                        create_singleton_axis(task, lpjgfile, str(lpjgcol), singleton_value)

                # cmorize the current task (variable)
                execute_single_task(dataset, task)
                dataset.close()

                # remove the regular (non-cmorized) netCDF file and the temporary .out file for current year
                os.remove(ncfile)
                os.remove(yearfile)

            # end yearfile loop

            # if compressed file .out.gz file exists, remove temporary .out file
            if os.path.exists(gzfile):
                os.remove(lpjgfile)

    return

# checks that the time resolution in the .out data file matches the requested frequency
def check_time_resolution(lpjgfile, freq):
    with open(lpjgfile) as f:
        header = next(f).lower().split()
    if freq == "mon":
        return 'mth' in header or header[-12:] == _months
    elif freq == "day":
        return 'day' in header
    elif freq.startswith("yr"):
        # to find out if it is yearly data have to check that it is neither monthly nor daily
        if 'mth' in header or header[-12:] == _months or 'day' in header:
            return False
        else:
            return True
    else:
        return False  # LPJ-Guess only supports yearly, monthly or daily time resolutions

# Returns first and last year present in the .out data file
def find_timespan(lpjgfile):
    df = pd.read_csv(lpjgfile, delim_whitespace=True, usecols=['Year'], dtype=np.int32)

    firstyr = df['Year'].min()
    lastyr = df['Year'].max()

    return firstyr, lastyr

# Divides the .out file by year to a set of temporary files This approach was chosen to avoid problems with trying to
#  keep huge amounts of data in the memory as the original .out-files can have even >100 years worth of daily data
def divide_years(lpjgfile, firstyr, lastyr, outname):
    files = {}
    filenames = []
    with open(lpjgfile) as f:
        header = next(f)
        # create the yearly files and write header to each
        for yr in range(firstyr, lastyr + 1):
            fname = os.path.join(ncpath_, outname + "_" + str(yr) + ".out")
            filenames.append(fname)
            files[yr] = open(fname, 'w')
            files[yr].write(header)

        # assign the data lines in the .out-file to correct yearly file
        for line in f:
            yr = int(line.split()[2])
            if yr < firstyr:
                continue
            files[yr].write(line)

    for yr in files:
        files[yr].close()

    return filenames

# this function builds upon a combination of _get and save_nc functions from the out2nc.py tool originally by Michael
#  Mischurow
def create_lpjg_netcdf(freq, inputfile, outname, outdims):
    global ncpath_, gridfile_

    # checks for additional dimensions besides lon,lat&time (for those dimensions where the dimension actually exists
    #  in lpjg data)
    is_land_use = "landUse" in outdims.split()
    is_veg_type = "vegtype" in outdims.split()
    is_sdepth = "sdepth" in outdims.split()

    # assigns a flag to handle two different possible monthly LPJ-Guess formats
    months_as_cols = False
    if freq == "mon":
        with open(inputfile) as f:
            header = next(f).lower().split()
            months_as_cols = header[-12:] == _months

    if freq == "mon" and not months_as_cols:
        idx_col = [0, 1, 2, 3]
    elif freq == "day":
        idx_col = [0, 1]
    else:
        idx_col = [0, 1, 2]

    df = pd.read_csv(inputfile, delim_whitespace=True, index_col=idx_col, dtype=np.float64, compression='infer')
    df.rename(columns=lambda x: x.lower(), inplace=True)

    if is_land_use:
        # NOTE: The following treatment of landuse types is likely to change depending on how the lut data requests
        # will be treated when creating the .out-files
        if not landuse_requested_:  # no specific request for land use types, pick all types present in the .out-file
            landuse_types = list(df.columns.values)
        elif cmor_prefix_ == "CMIP6":
            # NOTE: the land use files in the .out-files should match the CMIP6 requested ones (in content if not in
            # name) for future CMIP6 runs this is just a temporary placeholder solution for testing purposes!
            landuse_types = ['psl', 'pst', 'crp', 'urb']
        else:
            # for now skip the variable entirely if there is not exact matches in the .out-file for all the requested
            #  landuse types (except for CMIP6-case of course)
            colnames = list(df.columns.values)
            for lut in landuse_requested_:
                if lut not in colnames:
                    return None
            landuse_types = landuse_requested_

        df_list = []
        for lut in range(len(landuse_types)):
            colname = landuse_types[lut]
            df_list.append(get_lpjg_datacolumn(df, freq, colname, months_as_cols))

    elif is_veg_type:
        pfts = list(df.columns.values)
        df_list = []
        for p in range(len(pfts)):
            df_list.append(get_lpjg_datacolumn(df, freq, pfts[p], months_as_cols))

    elif is_sdepth:
        depths = list(df.columns.values)
        if "year" in depths:
            if freq == "mon" or freq == "day":
                depths = list(depths[2:])
            else:
                depths = list(depths[1:])
        df_list = []
        for sd in range(len(depths)):
            df_list.append(get_lpjg_datacolumn(df, freq, depths[sd], months_as_cols))

    else:  # regular variable
        colname = ""
        if not months_as_cols:
            if "total" not in list(df.columns.values):
                return None
            else:
                colname = "total"
        df = get_lpjg_datacolumn(df, freq, colname, months_as_cols)
        df_list = [df]

    if freq.startswith("yr"):
        str_year=str(int(df_list[0].columns[0]))
    else:
        str_year=str(int(df_list[0].columns[0][1]))

    log.info( "Creating lpjg netcdf file for variable " + outname + " for year " + str_year )

    ncfile = os.path.join(ncpath_, outname + "_" + freq + "_" + str_year + ".nc")
    # Note that ncfile could be named anything, it will be deleted later and the cmorization takes care of proper
    # naming conventions for the final file

    # temporary netcdf file name (will be removed after remapping is done)
    temp_ncfile = os.path.join(ncpath_, 'LPJGtemp.nc')
    root = netCDF4.Dataset(temp_ncfile, 'w')  # now format is NETCDF4

    root.createDimension('time', None)
    timev = root.createVariable('time', 'f4', ('time',))
    refyear = int(ref_date_.year)
    if freq == "mon":
        curyear, tres = int(df_list[0].columns[0][1]), 'month'
        t_since_fyear = (curyear - refyear) * 12
    elif freq == "day":
        curyear, tres = int(df_list[0].columns[0][1]), 'day'
        t_since_fyear = (date(curyear, 1, 1) - date(refyear, 1, 1)).days
    else:
        curyear, tres = int(df_list[0].columns[0]), 'year'
        t_since_fyear = curyear - refyear
    timev[:] = np.arange(t_since_fyear, t_since_fyear + df_list[0].shape[1])
    timev.units = '{}s since {}-01-01'.format(tres, refyear)
    timev.calendar = "proleptic_gregorian"

    meta = {"missing": 1.e+20}  # the missing/fill value could/should be taken from the target header info if available
    # and does not need to be in a meta dict since coords only needs the fillvalue anyway, but do it like this (i.e.
    # out2nc-style) for now

    N_dfs = len(df_list)
    df_normalised = []
    dimensions = []

    for l in range(N_dfs):
        # TODO: if different LPJG grids possible you need an if-check here to choose which function is called
        df_out, dimensions = coords(df_list[l], root, meta)
        df_normalised.append(df_out)

    if N_dfs == 1:
        dimensions = 'time', dimensions[0], dimensions[1]

        variable = root.createVariable(outname, 'f4', dimensions, zlib=True,
                                       shuffle=False, complevel=5, fill_value=meta['missing'])
        if outname == "tsl":
            variable[:] = df_normalised[0].values.T  # TODO: see out2nc for what to do here if you have the LPJG regular grid
        else:
            dumvar = df_normalised[0].values.T
            variable[:] = np.where(dumvar < 1.e+20, dumvar, 0.)   # TODO: see out2nc for what to do here if you have the LPJG regular grid

    else:
        root.createDimension('fourthdim', N_dfs)

        dimensions = 'time', 'fourthdim', dimensions[0], dimensions[1]
        variable = root.createVariable(outname, 'f4', dimensions, zlib=True,
                                       shuffle=False, complevel=5, fill_value=meta['missing'])
        for l in range(N_dfs):
            if outname == "tsl":
                variable[:, l, :, :] = df_normalised[l].values.T  # TODO: see out2nc for what to do here if you have the LPJG regular grid
            else:
                dumvar = df_normalised[l].values.T
                variable[:, l, :, :] = np.where(dumvar < 1.e+20, dumvar, 0.)   # TODO: see out2nc for what to do here if you have the LPJG regular grid

    root.sync()
    root.close()

    # do the remapping
    cdo = Cdo()

    if target_grid_ == "T159":
        cdo.remapycon('n80', input="-setgrid," + gridfile_ + " " + temp_ncfile,
                      output=ncfile)
    else:
        cdo.remapycon('n128',input="-setgrid," + gridfile_ + " " + temp_ncfile,
                      output=ncfile)  # TODO: add remapping for possible other grids

    os.remove(temp_ncfile)

    return ncfile

# finds the nemo output containing varname at nemo_freq
# this uses code in nemo2cmor.py, which could be moved to cmor_utils
def find_nemo_file(varname, nemo_freq):
    # find the nemo output folder for this leg (assumes it is in the runtime/output/nemo/??? folder)
    path_output_lpjg, leg_no = os.path.split(lpjg_path_)
    path_output = os.path.split(path_output_lpjg)
    nemo_path = os.path.join(path_output[0],'nemo',leg_no)
    # get the file which contains fgco2
    try:
        nemo_files = cmor_utils.find_nemo_output(nemo_path, exp_name_)
    except OSError:
        log.error("Cannot find any nemo output files in %s"
                  % (nemo_path))
        return ""
    print(str(nemo_files))
    file_candidates = [f for f in nemo_files if cmor_utils.get_nemo_frequency(f, exp_name_) == nemo_freq]
    results = []
    for ncfile in file_candidates:
        ds = netCDF4.Dataset(ncfile)
        if varname in ds.variables:
            results.append(ncfile)
        ds.close()
    # simplified error reporting
    if len(results) !=1:
        log.error("Cannot find any suitable nemo output files in %s"
                  % (nemo_path))
        return ""
    return results[0]

# this function builds upon a combination of _get and save_nc functions from the out2nc.py tool originally by Michael
#  Mischurow
def add_nemo_variable(task, ncfile, nemo_var_name, nemo_var_freq):
    # find nemo raw output file
    nemo_ifile = find_nemo_file(nemo_var_name, nemo_var_freq)
    if nemo_ifile == "":
        log.error("NEMO variable %s needed for target %s in table %s was not found in nemo output... "
                  % (nemo_var_name, task.target.variable, task.target.table))
        return False

    # define auxiliary and temp. files
    nemo_maskfile = os.path.join(os.path.dirname(__file__), "resources", "nemo-mask-ece.nc")
    nemo_ofile = os.path.join(ncpath_, "tmp_nemo.nc")
    interm_file = os.path.join(ncpath_, "intermediate.nc")
    if os.path.exists(nemo_ofile):
        os.remove(nemo_ofile)
    if os.path.exists(interm_file):
        os.remove(interm_file)

    # make sure the mask and input file have same dimensions
    ds_maskfile = netCDF4.Dataset(nemo_maskfile, 'r')
    ds_ifile = netCDF4.Dataset(nemo_ifile, 'r')
    dims_maskfile = ds_maskfile.dimensions
    dims_ofile = ds_ifile.dimensions
    if dims_maskfile['x'].size != dims_ofile['x'].size or dims_maskfile['y'].size != dims_ofile['y'].size:
            log.error("NEMO mask and output file, required for NEMO variable %s needed for target %s in table %s do not have same dimensions... "
                      % (nemo_var_name, task.target.variable, task.target.table))
            return False
    ds_maskfile.close()
    ds_ifile.close()

    # perform the conservative remapping using cdo
    #cdo -L selvar,${varname} ${ifile} tmp1.nc
    #CDO_REMAP_NORM=destarea cdo -L invertlat -setmisstoc,0 -remapycon,n128 -selindexbox,2,361,2,292 -mul tmp1.nc $mask $ofile
    log.info("Using the following cdo version for conservative remapping")
    os.system("cdo -V")
    os.system("cdo -L selvar,"+nemo_var_name+" "+nemo_ifile+" "+interm_file)
    if target_grid_ == "T159":
        remap_grid='n80'
    elif target_grid_ == "T255":
        remap_grid='n128'
    else:
        log.error("WRONG GRID %s in function add_nemo_variable in lpjg2cmor.py!" % target_grid_)
        exit(-1)
    os.system("CDO_REMAP_NORM=destarea cdo -L invertlat -setmisstoc,0 -remapycon,"+remap_grid+" -selindexbox,2,361,2,292 -mul "+interm_file+" "+nemo_maskfile+" "+nemo_ofile)

    if not os.path.exists(nemo_ofile):
        log.error("There was a problem remapping %s variable in nemo output file %s needed for %s in table %s... "
                  % (nemo_var_name, nemo_ifile, task.target.variable, task.target.table))
        return False

    # add the nemo output to the lpjg output
    if os.path.exists(interm_file):
        os.remove(interm_file)
    os.system("cdo -L add -selvar,"+task.target.variable+" "+ncfile+" "+nemo_ofile+" "+interm_file)
    if not os.path.exists(interm_file):
        log.error("There was a problem adding remapped %s variable from nemo output file %s to %s in table %s... "
                  % (nemo_var_name, nemo_ifile, task.target.variable, task.target.table))
        return False

    # overwrite final ncfile and cleanup
    os.remove(nemo_ofile)
    shutil.move(interm_file, ncfile)

    return True

# Extracts single column from the .out-file
def get_lpjg_datacolumn(df, freq, colname, months_as_cols):
    if freq == "day":
        # create a single time column so that extra days won't be added to
        # the time axis (if there are both leap and non-leap years)
        # Time axis needs to be modified on first call
        if "year" in list(df.columns.values):
            df['timecolumn'] = df['year'] + 0.001 * df['day']
            df.drop(columns=['year', 'day'], inplace=True)
            df.set_index('timecolumn', append=True, inplace=True)
        df = df[[colname]]
        df = df.unstack()

    elif freq.startswith("yr"):
        df = df.pop(colname)
        df = df.unstack()
    elif freq == "mon":
        if months_as_cols:
            df = df.unstack()
            df = df.reindex(sorted(df.columns, key=(lambda x: (x[1], _months.index(x[0])))),
                            axis=1, copy=False)
        else:
            df = df.pop(colname)
            df = df.unstack().unstack()
            df = df.reindex(sorted(df.columns, key=(lambda x: (x[1], x[0]))),
                            axis=1, copy=False)
    return df

# Performs CMORization of a single task/year
def execute_single_task(dataset, task):
    global log
    task.status = cmor_task.status_cmorizing
    lon_axis = [] if not hasattr(task, "longitude_axis") else [getattr(task, "longitude_axis")]
    lat_axis = [] if not hasattr(task, "latitude_axis") else [getattr(task, "latitude_axis")]
    t_axis = [] if not hasattr(task, "time_axis") else [getattr(task, "time_axis")]
    lu_axis = [] if not hasattr(task, "landUse_axis") else [getattr(task, "landUse_axis")]
    veg_axis = [] if not hasattr(task, "vegtype_axis") else [getattr(task, "vegtype_axis")]
    sdep_axis = [] if not hasattr(task, "sdepth_axis") else [getattr(task, "sdepth_axis")]

    # loop over potential singleton axes
    singleton_axis = []
    for ax in dir(task):
        if ax.startswith("singleton_"):
            singleton_axis += [getattr(task, ax)]

    axes = lon_axis + lat_axis + lu_axis + veg_axis + sdep_axis + t_axis + singleton_axis
    varid = create_cmor_variable(task, dataset, axes)

    ncvar = dataset.variables[task.target.out_name]
    missval = getattr(ncvar, "missing_value", getattr(ncvar, "fill_value", np.nan))

    factor = get_conversion_factor(getattr(task, cmor_task.conversion_key, None))
    log.info("CMORizing variable %s in table %s form %s in "
             "file %s..." % (task.target.out_name, task.target.table, task.source.variable(),
                             getattr(task, cmor_task.output_path_key)))
    cmor_utils.netcdf2cmor(varid, ncvar, 0, factor, missval=getattr(task.target, cmor_target.missval_key, missval),
                           swaplatlon=True)
    closed_file = cmor.close(varid, file_name=True)
    log.info("CMOR closed file %s" % closed_file)
    task.status = cmor_task.status_cmorized

# Creates cmor time axis for the variable
# The axis is created separately for each variable and each year
def create_time_axis(ds, task):
    # finding the time dimension name: adapted from nemo2cmor, presumably there is always only one time dimension and
    #  the length of the time_dim list will be 1
    tgtdims = getattr(task.target, cmor_target.dims_key)
    time_dim = [d for d in list(set(tgtdims.split())) if d.startswith("time")]

    timevals = ds.variables["time"][:]  # time variable in the netcdf-file from create_lpjg_netcdf is "time"
    # time requires bounds as well, the following should simply set them to be from start to end of each
    # year/month/day (as appropriate for current data)
    f = np.vectorize(lambda x: x + 1)
    time_bnd = np.stack((timevals, f(timevals)), axis=-1)

    tid = cmor.axis(table_entry=str(time_dim[0]), units=getattr(ds.variables["time"], "units"),
                    coord_vals=timevals, cell_bounds=time_bnd)
    setattr(task, "time_axis", tid)

    return

# Creates longitude and latitude cmor-axes for LPJ-Guess variables Seems this is enough for cmor according to the
# cmor documentation, and there is indeed no problem at least when passing the data through the CMORization functions
def create_grid(ds, task):
    lons = ds.variables["lon"][:]
    lats = ds.variables["lat"][:]

    # create the cell bounds since they are required: we have a 512x256 grid with longitude from 0 to 360 and
    # latitude from -90 to 90, i.e. resolution ~0.7 longitude values start from 0 so the cell lower bounds are the
    # same as lons (have to be: cmor requires monotonically increasing values so 359.X to 0.X is not allowed)
    lon_half_dists = np.insert(0.5 * (lons[1:] - lons[:-1]), 0, [0.5 * (lons[1] - lons[0])])
    lon_bnd = np.stack((lons[:] - lon_half_dists, lons[:] + lon_half_dists), axis=-1)

    # creating latitude bounds so that latitude values are the (approximate) mid-points of the cell lower and upper
    # bounds
    if target_grid_ == "T159":
        lat_bnd_lower = np.array([-90.0, -88.47338107])
        nsteps = 159
        step_length = 1.11991622
    elif target_grid_ == "T255":
        lat_bnd_lower = np.array([-90.0, -89.12264116])
        nsteps = 255
        step_length = 0.70175308
    for i in range(1, nsteps):
        lat_bnd_lower = np.append(lat_bnd_lower, lat_bnd_lower[i] + step_length)
    lat_bnd_upper = np.append(lat_bnd_lower[1:], 90.0)
    lat_bnd = np.stack((lat_bnd_lower, lat_bnd_upper), axis=-1)

    lon_id = cmor.axis(table_entry="longitude", units=getattr(ds.variables["lon"], "units"),
                       coord_vals=lons, cell_bounds=lon_bnd)
    lat_id = cmor.axis(table_entry="latitude", units=getattr(ds.variables["lat"], "units"),
                       coord_vals=lats, cell_bounds=lat_bnd)

    return lon_id, lat_id

# Unit conversion utility method (not really needed but carried over from nemo2cmor anyway)
def get_conversion_factor(conversion):
    global log
    if not conversion:
        return 1.0
    #   if conversion == "tossqfix":
    #       return 1.0
    if conversion == "frac2percent":
        return 100.0
    if conversion == "percent2frac":
        return 0.01
    log.error("Unknown explicit unit conversion %s will be ignored" % conversion)
    return 1.0

# Creates a variable in the cmor package
def create_cmor_variable(task, dataset, axes):
    srcvar = task.source.variable()
    unit = getattr(task.target, "units")
    if hasattr(task.target, "positive") and len(task.target.positive) != 0:
        return cmor.variable(table_entry=str(task.target.out_name), units=str(unit), axis_ids=axes,
                             original_name=str(srcvar), positive=task.target.positive)
    else:
        return cmor.variable(table_entry=str(task.target.out_name), units=str(unit), axis_ids=axes,
                             original_name=str(srcvar))

# Creates a cmor landUse axis
def create_landuse_axis(task, lpjgfile, freq):
    if landuse_requested_:
        landusevals = landuse_requested_
    else:
        with open(lpjgfile) as f:
            header = next(f).split()
            if freq.startswith("yr"):
                landusevals = header[3:]
            else:
                landusevals = header[4:]

    LU_id = cmor.axis(table_entry="landUse", units='none', coord_vals=landusevals)

    setattr(task, "landUse_axis", LU_id)
    return

# Creates a cmor vegtype axis
def create_vegtype_axis(task, lpjgfile, freq):
    with open(lpjgfile) as f:
        header = next(f).split()
        if freq.startswith("yr"):
            pfts = header[3:]
        else:
            pfts = header[4:]
    vegtypevals = pfts

    veg_id = cmor.axis(table_entry="vegtype", units='none', coord_vals=vegtypevals)

    setattr(task, "vegtype_axis", veg_id)
    return

# Creates a cmor sdepth axis
def create_sdepth_axis(task, lpjgfile, freq):
    log.info("Creating depth axis using file %s..." % lpjgfile)
    with open(lpjgfile) as f:
        header = next(f).split()
        if freq.startswith("yr"):
            depths = header[3:]
        else:
            depths = header[4:]
    sdepthvals = np.array([float(d) for d in depths])

    sdepth_bnd_lower = np.append(0, sdepthvals[:-1])
    sdepth_bnd = np.stack((sdepth_bnd_lower, sdepthvals), axis=-1)

    sdep_id = cmor.axis(table_entry="sdepth", units='m', coord_vals=sdepthvals,
                        cell_bounds=sdepth_bnd)

    setattr(task, "sdepth_axis", sdep_id)
    return

# Creates a cmor singleton depth axis
def create_singleton_axis(task, lpjgfile, lpjgcol, singleton_value):
    log.info("Creating singleton axis for %s using file %s..." % (lpjgcol,lpjgfile))

    axis_name = "singleton_"+lpjgcol+"_axis"
    single_id = cmor.axis(table_entry=lpjgcol, units='none', coord_vals=[singleton_value])

    setattr(task, axis_name, single_id)
    return


text:
IBEW 22 Referral System
Login Register Job Calls Out of Work List How it Works Mobile Apps Support
Home Job Calls Out of Work List How it Works Mobile Apps Support Login Register
This Privacy Policy covers the collection of information you provide while using the IBEW Local 22 Smartphone App (the App) and web site job call services (Website).
IBEW Local 22 collects non-personally-identifying information in connection with the use, download and installation of the App and Website, such as operating system, location analytics, and the number of downloads of the App. IBEW Local 22 may share this non-personally-identifying information for the purpose of reviewing, assessing and publishing information regarding the use of the App and Website.
Should the user elect to use the account features of the App and Website, which is not required, IBEW Local 22 collects personally-identifying information, including information related to creating an account or logging into an account such as full name, email address, username, telephone number (for calling and texts), qualifications, referral/dispatch information and IP address of login.
IBEW Local 22 does not require any user of the App and Website to provide personally-identifying information. A user may decline to provide such information, but such declination limits the features available through the App and Website. IBEW Local 22 does not request any sensitive permissions (camera, microphone, accounts, contacts, or phone) through the App; however, the user of the App and Website may elect to receive notifications via text message (message and data rates may apply) and/or push notifications through the App and Website.
By using the App and Website and taking advantage of its referral/dispatch features, you agree and acknowledge that the information collected may be shared with employers for purposes of referral/dispatch. By using the App and Website and taking advantage of its referral/dispatch features, you agree and acknowledge that your full name, dispatch number, book number, and home local will be collected and/or shared with IBEW Local 22 and all other applicants on the out of work list for purposes of referral/dispatch, including other authenticated users of the App and Website.
Except as stated herein and unless required by law, IBEW Local 22 will not disclose your personally-identifiable information. The App and Website may contain links to websites that are not managed by IBEW Local 22. IBEW Local 22 bears no responsibility for such websites.
Copyright 2020 IBEW Local 22. All rights reserved. Powered by Union Worx

redpajama_set_name: RedPajamaCommonCrawl


text:
Harvey Weinstein sentenced to 23 years in prison for sex crimes
On Behalf of Dusek Law | Mar 19, 2020 | Sex Crimes
Minnesota readers might be interested to learn that Harvey Weinstein was sentenced to 23 years in prison on March 11 in a New York City courtroom. In February, the former Hollywood film producer was convicted of committing a criminal sexual act and rape in the third degree.
The case against Weinstein kicked into high gear after two exposés about his alleged criminal conduct were published in October 2017, prompting dozens of women to come forward with accusations that he sexually assaulted them and then intimidated them into remaining silent. The allegations against him were instrumental in launching the #MeToo movement that rocked the film and television industries in 2018 and 2019.
A total of six women testified against Weinstein during the trial, which lasted several weeks. Their testimonies helped prosecutors paint a picture of a serial sexual predator who assaulted and harassed young women in Hollywood dating back to the 1970s. If he had been convicted of all charges, he could have faced up to life in prison. However, the jury acquitted him of the most serious charges. Even so, his defense attorneys argued that the 23-year sentence handed down by the judge was a "de facto life sentence" and "obscene."
As this case demonstrates, defendants accused of sex crimes can face severe consequences if they are convicted by a judge or jury. As a result, some criminal defense attorneys might suggest negotiating a plea deal that lets the defendant plead guilty to lesser charges. This strategy would allow the defendant to avoid the stress and added risk of a trial, and it might help him or her obtain a lighter sentence.


Assigns the census tract code, based on the population, street-name and number, to the handled postal addresses, based on the information from the National Statistics Institute census.
Assigns the census section code, based on the population, street-name and number, to the handled postal addresses, based on the information from the National Statistics Institute census.
This is useful for micro marketing actions, such as the census tract, which guarantee the uniform distribution of population in 2,500 inhabitants segments, as well as allowing for the obtaining of reliable population statistics from public sources.


Data management is the key to improved business efficiency. Every organization needs a proper data management system that enables it to perform at optimum speed and compete with its business rivals. Informatica PowerCenter is a software application that provides a central place to store data and PowerCenter trainingenables users to master its functions.
However, a data migration of such magnitude requires proper training and strategizing. There are certain training firms like ExistBI that can easily equip the employees with the required skills to undertake such a critical task. We can help you unlock the nuances of the PowerCenter training in an easy and yet comprehensive manner. Call us on our US number +1 800 280 4376 or our UK number +44 (0)207 554 8568.


I recently presented onstage at the Enterprise Mobility: BYOD event here in London with a couple of respected peers in the industry from Airwatch and Swivel as well as a VMware colleague. After taking questions from the audience around security for BYOD, my main takeaway from the event and in particular this session is that there is still a lot of confusion around mobility in general. In fact, mobility is becoming a catch-all phrase for end-user computing (EUC) transformation.
It's amazing how quickly the line between BYOD and enterprise mobility (EM) became blurred. A number of people in the audience had deployed some form of BYOD (most for smartphones) to enable employees to get access to email and calendar. But others, typically with a higher level of risk associated with externalising email, were struggling with the business case.
But BYOD is only one aspect of mobility. The main benefit from enabling users to become more mobile is realised when you mobilise the business workflow that they are part of. This started off as email for executives—with their exec toys such as tablets or the latest smartphone—an obvious use case. But when a business is looking holistically at mobility, there are many other opportunities such as enabling field engineers or the sales force to be more productive. So, the important message that I stressed to my audience wasn't about technology or security, but rather to ensure they establish the business justification for doing this work before jumping in with both feet.
It's paramount to gather the business requirements first, by engaging the business stakeholders to understand their needs. I recently helped an IT director of a large multinational company interpret the corporate strategy to collaborate with industry partners. I took the IT team and line-of-business stakeholders through a defined process of the steps required to build out a highly agile externalisation platform. Now they have users accessing the platform from any device and any location—24/7—and they manage everything from the centre since the devices are unknown to them. It's like BYOD to an extent, but tied to a major business initiative and nothing to do with smartphones.
As with this example, the most successful IT projects are those linked to business outcomes. The EUC space has long been at the unfortunate end of the IT spectrum in that it provides the general tools and services that employees expect to use on a day-to-day basis, yet the solutions do not appear to deliver direct value to the business.
Set a clear and simple mission statement with your business stakeholders.
Kick off with a discovery workshop with the key stakeholders from IT and the business.
Use the MoSCoW model or similar to help set priorities.
Review your findings regularly with key stakeholders.
Once this series of steps is complete, I find that my clients are in a good place to communicate internally to key stakeholders as well as externally to potential vendors of technology solutions—communication that paves the way to move forward to build out the business case and functional and technical designs for the solution.
RELATED: To learn more about the trends in mobile adoption and how IT is adapting, read the Mobile Rebels research report. This VMware-commissioned study provides insight to the pressures European businesses are facing and reveals just how dependent employees have become on their mobile devices.
This entry was posted in IT Analysis, IT Best Practices, IT Transformation and tagged BYOD, end-user computing, enterprise mobility, EUC, IT transformation, mobility, VMware Accelerate, VMware Accelerate Advisory Services on November 29, 2013 by Heidi Pate.
How does the intersection of two huge opportunities—cloud computing and big data—impact data strategies, and how does the IT organization take advantage of them to create business value?
As an Accelerate strategist, I define actionable strategies within organizations aimed at accelerating the maturity and business impact of virtualization and cloud initiatives. Many of the executives I work with are finding themselves at the intersection of two mega opportunities facing their organizations—cloud computing and big data.
To ensure common vernacular, "cloud computing" refers to an IT approach that allows the abstraction of computing workloads, so that they can be run across multiple environments based on organizational requirements (private, hybrid, or public clouds). This is made possible by decoupling the data and software from the servers and storage systems running them, which enables IT resources to be dynamically allocated and delivered as services (as in infrastructure-as-a-service, platform-as-a-service, storage-as-a-service solutions, and so forth).
In the realm of data, cloud computing allows organizations to think outside the traditional data center constructs, which limit capabilities based upon finite capacity. Cloud computing provides the elasticity and flexibility to spin up or down compute capacity based upon the needs of the business. Now it's possible to build applications that exceed the limits of existing compute power without worrying about significant CapEx investments to meet the demands of future applications.
But what about big data? Forrester Research defines big data as techniques and technologies that make capturing value from data at an extreme scale economical and estimates that we will exceed 2.7 zettabytes (equivalent of 27 million terrabytes) of global digital data this year. The key difference between big data and our traditional analytics strategy is that the investments required to support the variety, volume, and velocity of today's data available was previously prohibitive.
Big data strategies provide us with the means to collect and analyze this data in a way that is flexible and cost-effective. While many hear "big data" and think of the challenges of managing it, I prefer to focus on the opportunity to turn this growing data stream into business value.
The technologies—including applications and data platform—to leverage this new paradigm are still being created, but it's inevitable that they will depend on integration with cloud computing.
Build your application with tomorrow in mind – Big data offers significant benefits but is dependent on building applications that can leverage the key tenants of cloud computing.
Strive to retain flexibility – Cloud and big data strategies need to be examined in concert with significant attention focused on maximizing elasticity and portability of workloads.
All data is in scope – Big data is about extracting insight from the full body of organizational data versus the typical 10 percent that resides within your relational database management system (RDBMS).
Staff for success – Be aggressive in building data scientist capabilities, as this will be a critical requirement in driving your big data strategy.
Don't be afraid to start small – Leverage the expertise of early leaders such as Pivotal that can provide your efforts a jump-start by exposing you to the art of the possible.
Derek Lacks is a strategist with VMware Accelerate Advisory Services based in Massachusetts.
 Forbes.com: Big Data Meets Cloud, Holger Kisker, Ph.D.
This entry was posted in IT Analysis, IT Best Practices and tagged big data, Pivotal, VMware Accelerate, VMware Accelerate Advisory Services on November 22, 2013 by Heidi Pate.
Companies need to deploy a modern workplace and innovative infrastructure in order to digitize business processes, and that often calls for organizational and financial shifts in both the IT and marketing departments. Can a software-defined data center (SDDC)—which at first glance may appear to be purely a technology strategy—help CIOs and CMOs work together to deliver competitive business innovation while reducing budgets? I believe so.
A standard definition of digital services is difficult to nail down, but I found this one helpful: A digital service is one that has been entirely automated and which is controlled by the customer of the service. This describes a wide swath of new applications, personalized services, social interaction, and data analysis that might also include digital marketing initiatives. In this context, CIOs are now expected to show the business results of technology investments, and CMOs are also increasingly open to spending budgets outside traditional marketing in order to reach new users.
In general, CMOs know about product placement, go to market, and new customer demands; they also have to protect the business from surprises like new competitors and disruptive business models. Increasingly, time is a precious commodity, as emphasis shifts to short product lifecycles to test new markets and services.
CIOs typically have a great understanding of corporate business processes, information security, and available resources. They are skilled at scouting new technology and solutions with a focus on expenditures and new areas of savings. It seems obvious that enabling greater coordination between these two worlds will lead to a more competitive, robust, and agile organization. But how?
Despite the best intentions to collaborate for mutual advantage and company-wide success, challenges quickly surface when we lay out each department's specific objectives in an organizational matrix, especially when it comes to personal MBOs.
How can a software-defined data center help?
Having the ability to exploit a unified data center platform that provides new standards for automation, flexibility, and efficiency can bridge the different perspectives. In an SDDC, the compute, storage, networking, security, and availability services are pooled, aggregated, and delivered as intelligent, policy-driven software. Other key components include self-service, financial visibility, and policy-based provisioning for infrastructure and application. This provides business users with faster deployment and more reliable access to differentiating technology tools.
When CIO and CMO strategies are joined, it's important to highlight the impacts an SDDC will have on efficiency (cost control), agility (revenue contribution), and reliability (quality of service and risk mitigation). The impacts of an SDDC adoption, together the priorities associated with the opportunities CMOs and CIOs are striving to take advantage of, will help to define and exploit personalized roadmaps.
Abstraction of applications from the underlying infrastructure enables true self- and automated provisioning of services, overcoming manual steps and the wait time that exists when multiple siloed IT groups need to communicate.
The policy-based automation of pre-configured applications can simplify the processes related to the rework, which are often required to change configurations, or distribution of systems geographically.
Governance and brokerage of public cloud services from IaaS to SaaS, which can also provide agility-related benefits such as lower costs and time to market, but must be evaluated and in many cases integrated within existing processes.
Over the past two years, I have helped many customers gain visibility and insights into their current level of maturity using a software-defined reference framework. Capturing meaningful KPIs helps to build an executable roadmap that aligns with user demand and provides the ability to measure improvement over time.
Using their results to determine action plans needed to improve these metrics, CMOs and CIOs can decide which capability to address first and which marketing/IT joint investments will lead to the most beneficial business outcomes within the shortest amount of time.
Enrico Boverino is senior business solution strategist for VMware Accelerate Advisory Services based in Italy. You can follow him on Twitter at @eboverino.
This entry was posted in IT Best Practices, IT Transformation and tagged digital services, policy-based automation, SDDC, self-service catalog, Service Broker, service catalog, shadow IT, Software-defined Data Center, VMware Accelerate Advisory Services on November 15, 2013 by Heidi Pate.
I have made bold observations in my recent blogs about the need for a cultural shift to that of a service-driven culture. This is a culture with a strong focus on customer needs, customer services, and meeting deadlines. This type of culture also allows the IT organization to scale and adapt to changing business needs rather than rigidly following old strategies. Although a cultural shift like this might seem an insurmountable task, I've seen it occur—and faster than you might think.
Strategic vision: IT must have a strong strategic vision that is anchored to the broader business goals. Short-, near- and long-term success criteria should be clearly defined and routinely reviewed by the full spectrum of stakeholders.
Vision translation: The executive and director-level managers still need to disseminate the strategic vision to IT staff but should work hand-in-hand with service owners. Together they present a far more efficient method for evangelizing the strategic vision and leading a service lifecycle management process that keeps functional groups focused on internal deliverables as well as the interdependent needs of other groups.
Strategic framework: The service owner is a key role, but he is like an orchestra conductor—he needs to have the sheet music from which to direct the many individual musicians. The strategic framework is that sheet music. This framework should outline the operational readiness of IT and prioritize the work streams necessary to deliver on the IT strategy and services. This is also an opportunity to establish a roadmap to the desired service capability maturity level.
Risk: IT organizations tend to mitigate most risk within their sphere of control. They are uneasy asking other business groups to mitigate risks, even though these groups may be better positioned to do so. It is a wasted opportunity to have a great service-driven strategy if the business areas that IT depends on can't catch up. This is where a strategic vision that is tied to a business-wide strategy can help, by clarifying which business functions are best suited to assess specific risks and giving them an outline for doing so.
Of course, no single plan will cover every IT organization's needs, but this will present a good place to start a conversation. When I'm called in to help an organization with establishing a service-driven strategy, I start by establishing the end-state vision with the executive representatives for the organization, and then assess the operational capabilities of the business to deliver on that vision. The assessment then allows the IT organization to create a strategic framework by which the areas of improvement can be prioritized and remediation can be executed. This process has proven to expedite the journey of organizations in reaching service-driven capabilities.
This entry was posted in IT Analysis, IT Best Practices, IT Transformation and tagged alex salicrup, IT Service Provider, IT strategy, Service Broker, strategic consulting, VMware Accelerate, VMware Accelerate Advisory Services on November 10, 2013 by Heidi Pate.


text:
Q: The functions .prev() and .closest() not working as expected This is my .cshtml code :

        <input asp-for="FileName" type="hidden" class="hdnFileName" />
        <input type="file" asp-for="UploadFile" accept=".csv" />
        <button id="btnUpload" class="btn btn-tertiary btnFileSelect" type="button">Browse</button>

I need the id of the FileName on click of the upload button.
Script :
$(".btnFileSelect").each(function () {
    var btnId = $(this).attr("id");
    //The below code is not working and throwing an undefined value.
    //Tried .closest() which is not working either.
    var fileName = $(this).prev('.hdnFileName').attr('id');
})

Variable fileName is showing undefined.
What do I change? Is it being a hidden field the issue?

A: prev doesn't scan, it will only ever return a jQuery object for the previous element (if the selector matches) or an empty one (if it doesn't). From the documentation:

Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

(jQuery's set-based nature makes that slightly less clear than it could be, but basically you'll get the immediately-previous element if it matches, or none if it doesn't.)
If you want to scan, use .prevAll().eq(0). Or in this case, I'd probably use siblings:
var fileName = $(this).siblings('.hdnFileName').attr('id');

(I'm assuming something at some point adds an id to that element, since it doesn't have one in the markup you've shown.)

redpajama_set_name: RedPajamaStackExchange


OneSky Community Resources has a broad range of services and programs to offer in the South Okanagan. We are often posting positions that have to be filled on a permanent, casual or temporary basis. We post these positions internally and externally.
OneSky Community Resources is an equity employer and encourages applications from men, women, persons with disabilitie, members of visible minorities, First Nations, Inuit, and Metis people, people of all sexual orientation and genders and others who may contribute our further diversification.
We wish to thank all applicants for their interest, however, only those selected for an interview will be contacted.


Anything that can be photographed.
You have the option to buy prints of all sizes, a large selection of gifts, calendars and greeting cards.
If the size photo you desire does not crop well, contact me via email or phone and I will make the necessary adjustments to the original file.
Any special photo effects that you see in any of my albums can be applied to any photo by contacting me via email or phone.
Also feel free to contact me if you would like an event covered in the Alpharetta, Georgia area.
A wide variety of photographic subjects from the Michael Owen Klenetsky collection.
Butterflies, Zoo animals, Thoroughbreds, Dogs, Insects Etc.
Wills Park Horse Show Any special effect you see here can be applied to any photo. Just send me an email or call me with your request.
Broward County H.S. Girl's Softball All-Star Game May 17, 2010 played at Plantation H.S. - North vs. South.
Slide show of the wonderful wedding created by Marsha and enjoyed by all.
Horseshow Ventures at Wills Park Any special effect you see here can be applied to any photo. Just send me an email or call me with your request.
Horseshow Ventures at Wills Park Sept. 18, 2016 Any special effect you see here can be applied to any photo. Just send me an email or call me with your request.
The Jump Ahead Benefit Show Held at Wills Park Aug 21, 2016 Any special effect you see here can be applied to any photo. Just send me an email or call me with your request.
The Jump Ahead Benefit Show at Wills Park Any special effect you see here can be applied to any photo. Just send me an email or call me with your request.
Equestrian Competition at Wills Park Any special effects shown can be done to any photo upon request.
Wills Park Alpharetta, GA Any special effect can be applied to any photo. Just send me an email with your request.
July 23rd and 24th 2016 Any special effects shown can be done to any photo upon request.


The ACT Aspire assessment was introduced for the first time during the 2015-2016 school year and is now administered annually to all students in third through eighth grades.
In fall, winter and early spring of each school year three Aspire interim assessments are administered in preparation for the summative test in April. All students in grades three through eight use Chromebooks to complete online assessment tests in the core subjects of English, math, reading and science. The interim assessment results are for internal use, to establish a baseline and provide important progress indicators as we move toward the Aspire summative assessment in April, which is completed with pencil and paper bubble sheets.
Our summative assessment results from April of 2017 and 2016 can be viewed here.
Aspire is the first step in a vertical assessment system designed to connect student performance with readiness benchmarks as they progress chronologically from third grade through high school. Anchored by the ACT–the leading college assessment exam–Aspire maps learner progress using comprehensive academic guideposts to provide actionable information and insight to prepare students for higher education. This parent overview on ACT's web site provides more information about the Aspire asssessments.
Our school historically administered TerraNova tests to students in third, fifth and seventh grades every year; the final year of TerraNova testing was in 2015. Our test results demonstrate that our students achieved scores above the national average for all test categories. Millions of students across the country take the TerraNova tests; by comparing their scores a national norm is established which indicates students' performance at different grade levels. This national norm is set at 50. Scores above 50 indicate that students are performing above the norm; scores below 50, that they are performing below.
NP of Mean NCE is the national percentile rank of the average score of the group of students tested. For example, a grade 7 Math NP of MNCE score of 92 means the average student in 7th grade is ranked higher than 92% of the nation in Math.
Saint Juliana is committed to serving all students and families with Christian care and compassion. We welcome all students, including students with diverse learning needs, and give all applicants the same consideration for admission.


text:
Q: Cartesian Product of multiple array I think it is basically an easy problem, but I'm stuck. My brain is blocked by this problem, so I hope you can help me.
I have 2 to N arrays of integers, like
{1,2,3,4,5}
{1,2,3,4,5,6}
{1,3,5}
.....

Now i want to have a list containing arrays of int[N] with every posibillity like
{1,1,1}
{1,1,3}
{1,1,5}
{1,2,1}
....
{1,3,1}
....
{2,1,1}
{2,1,3}
....
{5,6,5}

so there are 6*5*3 (90) elements in it.
Is there a simple algorithm to do it? I think the language didn't matter but I prefer Java.

A: Thx for the help!
I add a valid answer with the implementation in java for the next guy, who has the same problem. I also do it generic so u can have any CartesianProduct on any Object, not just ints:
public class Product {

    @SuppressWarnings("unchecked")
    public static <T> List<T[]> getCartesianProduct(T[]... objects){
        List<T[]> ret = null;
        if (objects != null){
            //saves length from first dimension. its the size of T[] of the returned list
            int len = objects.length;
            //saves all lengthes from second dimension
            int[] lenghtes = new int[len];
            // arrayIndex
            int array = 0;
            // saves the sum of returned T[]'s
            int lenSum = 1;
            for (T[] t: objects){
                lenSum *= t.length;
                lenghtes[array++] = t.length;
            }
            //initalize the List with the correct lenght to avoid internal array-copies
            ret = new ArrayList<T[]>(lenSum);
            //reusable class for instatiation of T[]
            Class<T> clazz = (Class<T>) objects[0][0].getClass();
            T[] tArray;
            //values stores arrayIndexes to get correct values from objects
            int[] values = new int[len];

            for (int i = 0; i < lenSum; i++){
                tArray = (T[])Array.newInstance(clazz, len);
                for (int j = 0; j < len; j++){
                    tArray[j] = objects[j][values[j]];
                }
                ret.add(tArray);
                //value counting:
                //increment first value
                values[0]++;
                for (int v = 0; v < len; v++){
                    //check if values[v] doesn't exceed array length
                    if (values[v] == lenghtes[v]){
                        //set it to null and increment the next one, if not the last
                        values[v] = 0;
                        if (v+1 < len){
                            values[v+1]++;
                        }
                    }
                }

            }
        }
        return ret;
    }
}

A: As i understand what you want, you need to get all permutations.
Use recursive algorithm, detailed here.

A: As I see this should work fine:
concatMap (λa -> concatMap (λb -> concatMap (λc -> (a,b,c)) L3) L2) L1
where concatMap(called SelectMany in C#) is defined as
concatMap f l = concat (map f l).
and map maps a function over a list
and concat(sometimes called flatten) takes a List of List and turns it into a flat List


text:
SNP and Greens warned oil and gas rhetoric has 'shaken investor confidence' and risks jobs
admin0 December 19, 2021, 8:16 pm December 19, 2021 0 340
SNP and Greens ministers have been warned by business leaders that their hostility to the oil and gas sector is putting thousands of jobs on the line.
Oil and Gas UK (OGUK) has backed the calls for politicians and pressure groups to work collaboratively to cut emissions and ensure the sector can thrive in a net zero world.
Leading Scottish and UK business and industrial chiefs have warned that some politicians are risking causing damage to the North Sea oil and gas sector with their opposition.
It comes after Nicola Sturgeon changed her track and called for the Cambo oil field to be halted and Greens co-leader Patrick Harvie appeared to celebrate Shell pulling out of the project.
The letter, signed by a host of organisations including the British Chambers of Commence and Scottish Chambers of Commerce, warns that "statements calling for an end to new exploration and production have shaken investor confidence".
It adds: "A cliff-edge end to oil and gas production threatens tens of thousands of jobs and our ability to deliver a home-grown energy transition. We must avoid a repeat of what happened to our mining communities in the 1980s.
"We urge politicians to reflect carefully on their public statements on oil and gas … Statements calling for an end to new exploration and production have shaken investor confidence and placed tens of thousands of jobs – together with the economic wellbeing of whole communities across the UK – at risk.
"We must now pause and allow for a reasoned debate about our energy future to take place."
Deirdre Michie, chief executive of OGUK, said: "Businesses are joining the public in supporting our calls for a planned and fair transition towards our climate goals.
"Right now, we need oil and gas for 73 per cent of our total energy, and so the transition to carbon neutrality will be a huge and complex task.
"We will only be able to achieve it with careful planning by policy-makers who think long-term to develop clear government policies that are then supported by all politicians working together in the national interest.
"Those policies need to help the UK develop a range of technologies such as offshore wind, solar power, CO2 capture and storage and industrial-scale hydrogen production.
"But they must also ensure that, during the transition, the nation keeps getting the energy it needs. For years to come that will mean oil and gas will need to be part of the energy mix."It will be far better for the nation and the environment if we source these fuels from around our shores rather than relying on even more imports."
The Scottish Government said its focus "must now be on achieving the fastest possible just transition for the oil and gas sector — one that delivers jobs and economic benefit, and also ensures our energy security and meets our climate obligations".
Previous ArticleMartinelli's the man and coronavirus confusion – Premier League talking pointsNext ArticleLateral flow tests 'shortage' amid second day of UK Government website issues


First attempt for micro-project implementation.
1.Chapatti Diagram - The specific objective is to promote awareness and motivation in the community about the establishments relevant to their lives in and out of the village, relative important regarding their practical and emotional proximity. The general objective is to help the community to understand the relationship with such establishments and discuss about how they can improve it. The result of this chapatti diagrams exercise enabled the villagers to understand their relative relationship with the establishments.
2.Village mapping. - Through village drawing the community should understand and engage in an enriching discussion about the relative importance of the elements and features of their village. This will help A&D to find the common places where they can implement some micro-projects. This helped them to find out the problematic places. The result of the village drawing exercise fulfilled the wider concept of understanding about their village location (includes houses, water taps, roads, temples, drainage etc). This transect analysis accomplished the focused target.
4.Resource flow - To define the outgoing and incoming resources in the village; the main aim is to discuss and plan strategies (such as building their capacities) to balance such flows in favour of the community and help them improve where they lack. The result of the resource flow exercise was easier to forecast their real strengths and weaknesses, where they have to enhance and what they have to do. Similar to resource mapping. Resource flow also achieved the specific aim to find the outgoing and incoming resources in the village.
5.History of the village - To share and discuss about the history of the village, by an elderly person, within the village and to learn about the roots and origin of their culture. The result from this exercise had given few interesting information about the previous incidents that have had happened in the village.
From this PRA, A&D and PRAXIS found few important needs that should be solved as soon as possible. From those needs, the people prioritized drainage problem as an immediate need. A&D and PRAXIS have started working to solve this problem.


In: Halofsky, Jessica E.; Creutzburg, Megan K.; Hemstrom, Miles A., eds. 2014. Integrating social, economic, and ecological values across large landscapes. Gen.Tech. Rep. PNW-GTR-896. Portland, OR: U.S. Department of Agriculture, Forest Service, Pacific Northwest Research Station: 111-128.
In: Kerns, Becky K.; Shlisky, Ayn J.; Daniel, Colin J., tech. eds. Proceedings of the First Landscape State-and-Transition Simulation Modeling Conference, June 14–16, 2011, Portland, Oregon. Gen. Tech. Rep. PNW-GTR-869. Portland, OR: U.S. Department of Agriculture, Forest Service, Pacific Northwest Research Station: 57-72.
Gen. Tech. Rep. PNW-GTR-941. Portland, OR: U.S. Department of Agriculture, Forest Service, Pacific Northwest Research Station. 51 p.
Gen. Tech. Rep. RMRS-GTR-76. Ogden, UT: U.S. Department of Agriculture, Forest Service, Rocky Mountain Research Station. 14 p.
In: Halofsky, Jessica E.; Creutzburg, Megan K.; Hemstrom, Miles A., eds. 2014. Integrating social, economic, and ecological values across large landscapes. Gen.Tech. Rep. PNW-GTR-896. Portland, OR: U.S. Department of Agriculture, Forest Service, Pacific Northwest Research Station: 1-14.
In: Gobster, Paul H.; Smardon, Richard C., eds. 2018. Visual resource stewardship conference proceedings: landscape and seascape management in a time of change. Gen. Tech. Rep. NRS-P-183. Newtown Square, PA: U.S. Department of Agriculture, Forest Service, Northern Research Station: 73-85.
In: Gobster, Paul H.; Smardon, Richard C., eds. Visual resource stewardship conference proceedings: landscape and seascape management in a time of change. Gen. Tech. Rep. NRS-P-183. Newtown Square, PA: U.S. Department of Agriculture, Forest Service, Northern Research Station: 127-135.
Forest Ecology and Management. 259: 487-495.


Yodel were the courier used by Morrisons Cellar to deliver to me a case of wine, after using Yodels tracking service I was amazed to find that according to Yodel my wine had been delivered the previous day. I phoned Yodel tell them this was not so but they simply referred me to Morrisons yet 2 days later the actual delivery driver called me and insisted he had left the goods with one of my next door neighbours and had left a card through my door, I had already checked with my neighbours of 20 plus years and so knew this to be untrue and there had been no card placed through my letterbox. Morrisons spent 2 weeks " investigating " with Yodel who claimed the same, then that it had been left with someone 12 doors from my house and lastly that they had re delivered the goods which of course they had not.
At this point when I grew exasperated with the incompetence of Yodel and threatened to escalate the issue within Morrisons I was offered a re order but refused on the grounds that I would never knowingly order anything that involved a delivery from Yodel, I was then offered a full refund, I took the opportunity to advise Morrisons that they should find a more proficient courier to deliver their produce or they were likely to lose customers like they have lost me!


text:
Inle Lake and the east Travel Guide
ROUGHGUIDES.COM /ASIA / MYANMAR-BURMA / INLE-LAKE-EAST
With Kayah and Kayin states mostly off-limits to tourists, it's the large Shan State (a good deal of which is itself closed) that epitomizes the appeal of the hilly east of the country. A day-trip on Inle Lake, visiting stilt villages and colourful markets, is top of the list, although for many travellers the trekking opportunities around Kalaw are equally appealing. Fewer visitors make it to Kengtung, but it has its own isolated charm and offers the chance to trek to villages where traditional animist beliefs still hold sway.
Continue reading to find out more about...
Kengtung
Pindaya
Related tailor-made travel itineraries for Myanmar (Burma)
4 days from 890 USD
Mrauk U: Myanmar's Best-Kept Secret
8 days from 1390 USD
The Flavours of Myanmar: A Culinary Journey
Love Yangon
Classical Myanmar
view all itineraries ⤍
When it got too hot in the lowlands for the British during the colonial era, they retreated to hill stations like KALAW. Today the climate is still part of the appeal, even if it can get a bit chilly at night in winter, and the town is a base for some excellent treks to ethnic minority villages.
Other than the market, which is open every day but spills out into the streets when it's Kalaw's turn to host the rotating market, there isn't a lot to do in the town itself besides visit its pagodas. These include the mirrored Aung Chan Tha Zedi in the centre and small Thein Taung Paya, uphill from the Union Highway and notable mainly for the views back towards the town.
Shan State markets
A number of markets in this region operate on a five-day cycle, with three or four markets taking place on each day of that cycle. With the possible exception of the very touristy Ywama "floating market", they're fascinating places – particularly early in the morning – where people from remote villages sell their produce or livestock and buy essential goods. Tour operators, guides and hotel staff should know the schedule; and it's common to visit the relevant market during a boat tour.
There are many options for one- or two-day treks around Kalaw, following trails through the hills to villages inhabited by Palaung, Danu, Pa-O, Taung Yoe and other ethnic groups. Don't expect untarnished nature – there has been significant deforestation in the area, and the routes mostly run past fields and plantations – but nonetheless, these hikes are a great way to get a glimpse of rural life.
The most popular longer trek is to Inle Lake, which normally takes three days, although it's possible to shorten it to two (skipping some of the route by car) or lengthen it to four. There are many different routes and finishing points on the western side of the lake, including Khaung Dine and Indein. Usually one night is spent in a village home and another in a monastery.
The trails can get very muddy during the rainy season (June to October), while in peak season the overnight stops on the Kalaw-to-Inle trek can become pretty busy.
Its prominent position within the Golden Triangle – the opium-growing zone covering parts of Myanmar, Vietnam, Laos and Thailand – meant that for many years Kengtung (pronounced Cheng-tung, and also known as Kyaing Tong) was off-limits to tourists. These days, however, the main rebel groups have signed ceasefires with the government and visitors are allowed in with some restrictions: the only way to get to Kengtung from within Myanmar is by flying, although you can visit overland from Thailand. This tends to mean that travellers on tight budgets leave it out of their itineraries.
It's certainly worth the visit if you can afford it; Kengtung itself is one of the most appealing cities in the country, with a definite Thai feel: monks wear saffron robes, Thai baht are accepted in some hotels and you may hear yourself being called falang instead of "foreigner". Most people, though, visit for the excellent hiking possible in the surrounding area.
Set across hills and with a lake close to its heart, Kengtung is a pleasurable place simply to wander around. The Thai influence is clear in both the architecture and the names of temples such as Wat Jong Kam and Wat In, both of which have clusters of Buddha statues in their main pagodas.
There's also a long history of Christian missionary activity in the area; a large complex in the west of town includes the Cathedral of the Immaculate Heart of Mary and St Louis' Seminary. The giant Buddha nearby, known as Ya Taw Mu, has his back turned away from it.
While there are a few decent mid-range places in town, the pickings are pretty slim for travellers on a tight budget.
Foreign visitors are not allowed to stay over in the villages around Kengtung, and most of the day-hikes are at least an hour's drive from town, which makes hiking here relatively expensive. Trips can be arranged direct with freelance guides or through accommodation; one of the cheaper options is with Harry's Trekking House. The guide fee – typically $20 per day – is supposed to go straight to the guide, although many hotels and guesthouses quietly take a cut.
The most popular destination is the Pin Tauk area (transport from K35,000), as the three-hour walk passes through the villages of several different ethnic groups (Akha, Eng and Khun Shan, plus Silver Palaung if there's time). Hikers may be dismayed to find, however, that most of their interaction with locals involves being offered handicrafts.
Other hikes are likely to be more rewarding, including to the Akha villages of Hokyin Hill (transport from K35,000), the former British hill station of Loimwe (transport from K50,000), and – furthest afield, near the Chinese border – the villages of Wan Nyet and Wan Saen (transport from K60,000), where Loi people live in longhouses.
The small town of PINDAYA is located in the heart of one of the most important agricultural regions in the country. The drive itself is a good reason to make the trip, as the patchwork of red soil, green crops and variously-hued flowers is simply stunning. It's also oddly reminiscent of southern Europe, at least until you see a small Danu child riding on the back of a water buffalo. You'll have to pay a $2 entry fee for the area as you get close to Pindaya.
Shwe Oo Min
The main attraction in the town is Shwe Oo Min, an atmospheric series of caves crammed full of Buddha statues – some date back centuries, but the collection is still expanding. The first section of the cave is packed with a vast number of almost identical golden images of the Buddha, while the further chambers – which are less cramped – exhibit more variety in materials and styles but still with the same subject.
It's possible to continue north from here along the hillside via other shrines and a monastery.
Discover more places related to Myanmar (Burma)
Around Mandalay
Bagan and the central plains
Mandalay and around
Northern Myanmar
Nyaungshwe
Pyin Oo Lwin
Southeastern Myanmar
The delta region and western Myanmar
The Rough Guide to Myanmar (Burma) and related travel guides
In-depth, easy-to-use travel guides filled with expert advice.
BUY $2.99
Find even more inspiration for Myanmar (Burma) here
Myanmar: is it time for tourists to return?
14 essential Burmese experiences
9 tips for backpacking Myanmar (Burma)
Living with the locals in rural Myanmar
Things not to miss
Off the tourist trail in Southeast Asia: 5 underrated cities
The untouched coast of southern Myanmar (Burma)
18 places to go back in time
Planning on your own? Prepare for your trip
Use Rough Guides' trusted partners for great rates
Andy Turner
The Rough Guide to Myanmar (Burma)
Your travel guide to Myanmar (Burma)
Myanmar (Burma)?


text:
Q: Magento keeps auto-checking "Use default value" box in category description field after save I have a problem with Magento community edition 1.4.0.1. When I go to edit store categories, not the global one but for specific store for some categories (not all of them) Magento keeps auto-checking the "Use Default Value" box for selected fields like "Desctipion" or "Meta Description". This is a problem because the next time you go to that category to edit "Name" for example you have to manually uncheck those boxes to preserve data in them after next save.
To explain in more details please check the screenshot attached.

A: Do you remove the content of the description field? We fixed a bug on the bugathon on the last weekend. There is a displaying bug, the check whether the field should be used from the default is isset() against an array which value is NULL.
https://github.com/magento/bugathon_march_2013/pull/217
And it should be this commit, my internet is buggy at the moment, so I can't check:
https://github.com/magento/bugathon_march_2013/commit/b9b344085c7d14bfdd1babb75677c931f2785209


text:
Q: AirflowException: The conn_id `http_default` isn't defined error trying to run an HTTP operator in Airflow I have an Airflow DAG that, as the last task, needs to send an HTTP request to trigger a Google Cloud Function. I am testing it out but the HTTP task fails.
Task definition:
send_standby_signal = ho.SimpleHttpOperator(
        task_id = 'send-k8s-cluster-standby-signal',
        endpoint = 'https://path-to-function-endpoint',
        method = 'POST',
        data = '',
        trigger_rule = trigger_rule.TriggerRule.ALL_DONE
)

Error:
[2019-10-02 13:57:29,088] {http_operator.py:87} INFO - Calling HTTP method
[2019-10-02 13:57:29,122] {__init__.py:1580} ERROR - The conn_id `http_default` isn't defined
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/models/__init__.py", line 1441, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/usr/local/lib/python3.7/site-packages/airflow/operators/http_operator.py", line 92, in execute
    self.extra_options)
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/http_hook.py", line 101, in run
    session = self.get_conn(headers)
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/http_hook.py", line 60, in get_conn
    conn = self.get_connection(self.http_conn_id)
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/base_hook.py", line 80, in get_connection
    conn = random.choice(cls.get_connections(conn_id))
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/base_hook.py", line 75, in get_connections
    conns = cls._get_connections_from_db(conn_id)
  File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 73, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/base_hook.py", line 58, in _get_connections_from_db
    "The conn_id `{0}` isn't defined".format(conn_id))
airflow.exceptions.AirflowException: The conn_id `http_default` isn't defined

A: Simple answer, really. I didn't have http_default defined in Airflow Connections. How embarrassing.


text:
Desolate (2013)
Not Rated | 1h 17min | Drama, Sci-Fi, Thriller
Shot over a 3 year period during free weekends and in between his 2nd feature 'Mon Ami' with NO crew and NO script, Desolate is an example of experimental film-making using resources that ... See full summary »
Rob Grant
Jez Bonham, Justin Stone, Teagan Vincze
Low budget Sci-fi
Sci-Fi / Drama
Search for "Desolate" on Amazon.com
Title: Desolate (2013)
Alive I (2018)
Horror | Thriller
A severely injured man and woman awake in an abandoned sanitarium only to discover that a sadistic caretaker holds the keys to their freedom and the horrific answers as to their real identity.
Director: Rob Grant
Stars: Thomas Cocquerel, Camille Stopps, Angus Macfadyen
Fake Blood (2017)
Documentary | Horror | Thriller
Rob Grant and Mike Kovac receive a disturbing fan video inspired by their previous horror movie Mon Ami, motivating them to investigate the responsibility of filmmakers in portraying ... See full summary »
Stars: Chelsey Reist, Camden Filtness, Mike Kovac
Yesterday I (2009)
Action | Comedy | Drama
Six complete strangers are forced to band together and flee the city when a zombie outbreak occurs. But after making camp in the middle of the wilderness, the group realise it's each other they should fear.
Stars: Graham Wardle, P. Lynn Johnson, Bill Murdoch
Mon Ami (2012)
Comedy | Crime
Two friends try executing their 'get-rich-quick' plan by kidnapping their boss's daughter, but when the plan falls apart, they must scramble to fix the situation and repair their friendship.
Stars: Mike Kovac, Graham Wardle, Scott Wallis
Harpoon (2019)
Rivalries, dark secrets, and sexual tension emerge when three best friends find themselves stranded on a yacht in the middle of the ocean under suspicious circumstances.
Stars: Munro Chambers, Emily Tyra, Christopher Gray
Desolate V (2016)
Action | Crime | Drama
Director: David Nzinga
Stars: David Nzinga, Ester Uddén, Erik Bolin
Echoes of Fear (2018)
After inheriting her grandfather's house, a young woman must confront the mystery of his sudden death and the evil that hides inside.
Directors: Brian Avenet-Bradley, Laurence Avenet-Bradley
Stars: Trista Robinson, Hannah Race, Paul Chirico
Desolate I (2018)
While trying to survive the worst drought in history, a family of farmers force their youngest brother down a path of destruction; betrayed and left for dead in an unfamiliar land, he must survive, endure and seek the revenge he deserves.
Director: Frederick Cipoletti
Stars: Will Brittain, Callan Mulvey, Tyson Ritter
Desolate Land (TV Series 2017)
A cowboy awakens to find himself in an abandoned, unfamiliar land. He goes out in search of life.
Stars: Beau Yotty, Dan Weisgerber, Nathan Yotty
My Soul to Keep (2019)
Eli believes that there's a monster living in his basement, and it's trying to steal his soul.
Director: Ajmal Zaheer Ahmad
Stars: Parker Smerek, Remington Gielniak, Arielle Olkhovsky
Desolate IV
Matthew struggles to be freed from the judgment and criticisms from within. Tonight, he abducted the man behind all his problems, announcing that everything will end on this night.
Director: Willan Leung
Stars: Kat Ruston, Wolfgang Klassen, Mike Li
She Came from the Woods (2017)
Short | Horror
A campfire story comes to life for a group of counselors on the last day of summer at Camp Briarbrook.
Directors: Carson Bloomquist, Erik Bloomquist
Stars: Ehad Berisha, Justin Andrew Davis, Peyton Michelle Edwards
Jez Bonham ... Chad
Justin Stone ... Devon (as Justin Sproule)
Teagan Vincze ... Annie
Shot over a 3 year period during free weekends and in between his 2nd feature 'Mon Ami' with NO crew and NO script, Desolate is an example of experimental film-making using resources that are available to anyone that can afford a camera. The film follows a young man who hits rock bottom after suspecting his best friend may be responsible for his failed relationship. But when a mysterious incident rocks the downtown core, they are forced to put differences aside in order to survive the night... Written by Anonymous
Drama | Sci-Fi | Thriller
Official Facebook | Official site
CAD 3,600 (estimated)
With no extra people on set Jez Bonham had to play the monsters that were stocking him. See more »
Gripping lo-budget SF
27 April 2014 | by davidkhardman – See all my reviews
Desolate is a 77 minute film made on a shoestring budget by director Rob Grant, using a single DSLR camera and some borrowed sound equipment. It is also surprisingly good, though needless to say you shouldn't hold your breath waiting for it to appear at your nearest multiplex. I saw this film at the Sci-Fi-London Film Festival, and I daresay the festival circuit may well be your best chance to catch up with it if you are a sci-fi fan.
The story concerns Chad, who has recently broken up with his girlfriend Annie. Consequently, he has hit the bottle, believing that Annie is having an affair with his best friend, Devon. Whilst Chad and Devon are arguing about this up in the hills, there is a huge explosion in the town below. Chad returns to his apartment where the rolling news coverage reveals that the devastation may have been a UFO crashing, and that witnesses have reported seeing "creatures". Creatures there turn out to be, and they don't want to make friends.
Given the lack of budget, director Grant cleverly relies on the viewer's own imagination to create an atmosphere of fear. It's a horror movie technique as old as the hills to use the sight of a door to make us afraid of what might be on the other side, but it works with great effect here. I was genuinely gripped throughout. Of course, given the limitations that Grant is working within, there are lots of shaky camera shots deployed, with people and objects going in and out of focus. Although these techniques are fairly obvious to the viewer, Grant at least does not attempt to pad the film out, and I thought the film was just about the right length. It kept my attention until the rather Shakespearean ending.
Perhaps the weakest aspect was that the central character of Chad was not especially likable. He starts out as rather self-pitying and selfish, and I can't say that he seemed much different at the end. On the other hand, he isn't a bad character, so I was still able to root for him against the monsters – I don't know if all viewers would be as tolerant as me in this regard!


Need a logo designed for a t-shirt. (Event is tomorrow!) Roughly this concept: "2 Out Rally" is main wording. Want to combine Baseball and Road Rally imagery. Will be printing on a white t-shirt with red sleeves.