text:
"""
`Context` objects contain the information required for `DistArray`\s to
communicate with `LocalArray`\s.
"""

from __future__ import absolute_import

import atexit
import collections
import types
from abc import ABCMeta, abstractmethod

from functools import wraps

import numpy

from distarray.externals import six
from distarray import DISTARRAY_BASE_NAME
from distarray.globalapi import ipython_cleanup
from distarray.globalapi.distarray import DistArray
from distarray.globalapi.maps import Distribution, asdistribution

from distarray.globalapi.ipython_utils import IPythonClient
from distarray.utils import uid, nonce, has_exactly_one
from distarray.localapi.proxyize import Proxy

# mpi context
from distarray.mpionly_utils import (make_targets_comm,
                                     get_world_rank, initial_comm_setup,
                                     is_solo_mpi_process, get_comm_world,
                                     mpi, push_function)

@six.add_metaclass(ABCMeta)
class BaseContext(object):

    """
    Context objects manage the setup and communication of the worker processes
    for DistArray objects.  A DistArray object has a context, and contexts have
    an MPI intracommunicator that they use to communicate with worker
    processes.

    Typically there is just one context object that uses all processes,
    although it is possible to have more than one context with a different
    selection of engines.
    """

    _CLEANUP = None

    @abstractmethod
    def __init__(self):
        raise TypeError("The base context class is not meant to be "
                        "instantiated on its own.")

    @abstractmethod
    def cleanup(self):
        pass

    @abstractmethod
    def close(self):
        pass

    @abstractmethod
    def make_subcomm(self, new_targets):
        pass

    @abstractmethod
    def apply(self, func, args=None, kwargs=None, targets=None, autoproxyize=False):
        pass

    @abstractmethod
    def push_function(self, key, func):
        pass

    def _setup_context_key(self):
        """
        Create a dict on the engines which will hold everything from
        this context.
        """
        context_key = uid()
        cmd = ("import types, sys;"
               "%s = types.ModuleType('%s');")
        cmd %= (context_key, context_key)
        self._execute(cmd, self.all_targets)
        return context_key

    @staticmethod
    def _key_prefix():
        """ Get the base name for all keys. """
        return DISTARRAY_BASE_NAME

    def _generate_key(self):
        """ Generate a unique key name for this context. """
        key = "%s_%s" % (self.context_key, uid())
        return key

    def _key_and_push(self, *values, **kwargs):
        keys = [self._generate_key() for value in values]
        targets = kwargs.get('targets', self.targets)
        def _local_key_and_push(kvs):
            from distarray.localapi.proxyize import Proxy
            return [Proxy(key, val, '__main__') for key, val in kvs]
        result = self.apply(_local_key_and_push, (zip(keys, values), ), targets=targets)
        return tuple(result[0])

    def delete_key(self, key, targets=None):
        """ Delete the specific key from all the engines. """
        def _local_delete(obj):
            from distarray.localapi.proxyize import Proxy
            from importlib import import_module
            if isinstance(obj, Proxy):
                obj.cleanup()
            else:
                main = import_module('__main__')
                delattr(main, obj)
        targets = targets or self.targets
        with self.view.temp_flags(targets=targets):
            self.view.apply_sync(_local_delete, key)

    def _create_local(self, local_call, shape_or_dist, dtype):
        """Creates LocalArrays with the method named in `local_call`."""

        def create_local(local_call, ddpr, dtype, comm):
            from distarray.localapi.maps import Distribution
            if len(ddpr) == 0:
                dim_data = ()
            else:
                dim_data = ddpr[comm.Get_rank()]
            local_call = eval(local_call)
            distribution = Distribution(comm=comm, dim_data=dim_data)
            rval = local_call(distribution=distribution, dtype=dtype)
            return proxyize(rval)

        distribution = asdistribution(self, shape_or_dist)

        ddpr = distribution.get_dim_data_per_rank()
        args = [local_call, ddpr, dtype, distribution.comm]
        da_key = self.apply(create_local, args=args,
                            targets=distribution.targets)[0]
        return DistArray.from_localarrays(da_key, distribution=distribution,
                                          dtype=dtype)

    def empty(self, shape_or_dist, dtype=float):
        """Create an empty Distarray.

        Parameters
        ----------
        shape_or_dist : shape tuple or Distribution object
        dtype : NumPy dtype, optional (default float)

        Returns
        -------
        DistArray
            A DistArray distributed as specified, with uninitialized values.
        """
        return self._create_local(local_call='distarray.localapi.empty',
                                  shape_or_dist=shape_or_dist, dtype=dtype,)

    def zeros(self, shape_or_dist, dtype=float):
        """Create a Distarray filled with zeros.

        Parameters
        ----------
        shape_or_dist : shape tuple or Distribution object
        dtype : NumPy dtype, optional (default float)

        Returns
        -------
        DistArray
            A DistArray distributed as specified, filled with zeros.
        """
        return self._create_local(local_call='distarray.localapi.zeros',
                                  shape_or_dist=shape_or_dist, dtype=dtype,)

    def ones(self, shape_or_dist, dtype=float):
        """Create a Distarray filled with ones.

        Parameters
        ----------
        shape_or_dist : shape tuple or Distribution object
        dtype : NumPy dtype, optional (default float)

        Returns
        -------
        DistArray
            A DistArray distributed as specified, filled with ones.
        """
        return self._create_local(local_call='distarray.localapi.ones',
                                  shape_or_dist=shape_or_dist, dtype=dtype,)

    def allclose(self, a, b, rtol=1e-05, atol=1e-08):

        adist = a.distribution
        bdist = b.distribution

        if not adist.is_compatible(bdist):
            raise ValueError("%r and %r have incompatible distributions.")

        def local_allclose(la, lb, rtol, atol):
            from numpy import allclose
            return allclose(la.ndarray, lb.ndarray, rtol, atol)

        local_results = self.apply(local_allclose,
                                  (a.key, b.key, rtol, atol),
                                  targets=a.targets)
        return all(local_results)

    def save_dnpy(self, name, da):
        """
        Save a distributed array to files in the ``.dnpy`` format.

        The ``.dnpy`` file format is a binary format inspired by NumPy's
        ``.npy`` format.  The header of a particular ``.dnpy`` file contains
        information about which portion of a DistArray is saved in it (using
        the metadata outlined in the Distributed Array Protocol), and the data
        portion contains the output of NumPy's `save` function for the local
        array data.  See the module docstring for `distarray.localapi.format` for
        full details.

        Parameters
        ----------
        name : str or list of str
            If a str, this is used as the prefix for the filename used by each
            engine.  Each engine will save a file named ``<name>_<rank>.dnpy``.
            If a list of str, each engine will use the name at the index
            corresponding to its rank.  An exception is raised if the length of
            this list is not the same as the context's communicator's size.
        da : DistArray
            Array to save to files.

        Raises
        ------
        TypeError
            If `name` is an sequence whose length is different from the
            context's communicator's size.

        See Also
        --------
        load_dnpy : Loading files saved with save_dnpy.
        """

        def _local_save_dnpy(local_arr, fname_base):
            from distarray.localapi import save_dnpy
            fname = "%s_%s.dnpy" % (fname_base, local_arr.comm_rank)
            save_dnpy(fname, local_arr)

        def _local_save_dnpy_names(local_arr, fnames):
            from distarray.localapi import save_dnpy
            fname = fnames[local_arr.comm_rank]
            save_dnpy(fname, local_arr)

        if isinstance(name, six.string_types):
            func = _local_save_dnpy
        elif isinstance(name, collections.Sequence):
            if len(name) != len(self.targets):
                errmsg = "`name` must be the same length as `self.targets`."
                raise TypeError(errmsg)
            func = _local_save_dnpy_names
        else:
            errmsg = "`name` must be a string or a list."
            raise TypeError(errmsg)

        self.apply(func, (da.key, name), targets=da.targets)

    def load_dnpy(self, name):
        """
        Load a distributed array from ``.dnpy`` files.

        The ``.dnpy`` file format is a binary format inspired by NumPy's
        ``.npy`` format.  The header of a particular ``.dnpy`` file contains
        information about which portion of a DistArray is saved in it (using
        the metadata outlined in the Distributed Array Protocol), and the data
        portion contains the output of NumPy's `save` function for the local
        array data.  See the module docstring for `distarray.localapi.format` for
        full details.

        Parameters
        ----------
        name : str or list of str
            If a str, this is used as the prefix for the filename used by each
            engine.  Each engine will load a file named ``<name>_<rank>.dnpy``.
            If a list of str, each engine will use the name at the index
            corresponding to its rank.  An exception is raised if the length of
            this list is not the same as the context's communicator's size.

        Returns
        -------
        result : DistArray
            A DistArray encapsulating the file loaded on each engine.

        Raises
        ------
        TypeError
            If `name` is an iterable whose length is different from the
            context's communicator's size.

        See Also
        --------
        save_dnpy : Saving files to load with with load_dnpy.
        """

        def _local_load_dnpy(comm, fname_base):
            from distarray.localapi import load_dnpy
            fname = "%s_%s.dnpy" % (fname_base, comm.Get_rank())
            local_arr = load_dnpy(comm, fname)
            return proxyize(local_arr)

        def _local_load_dnpy_names(comm, fnames):
            from distarray.localapi import load_dnpy
            fname = fnames[comm.Get_rank()]
            local_arr = load_dnpy(comm, fname)
            return proxyize(local_arr)

        if isinstance(name, six.string_types):
            func = _local_load_dnpy
        elif isinstance(name, collections.Sequence):
            if len(name) != len(self.targets):
                errmsg = "`name` must be the same length as `self.targets`."
                raise TypeError(errmsg)
            func = _local_load_dnpy_names
        else:
            errmsg = "`name` must be a string or a list."
            raise TypeError(errmsg)

        da_key = self.apply(func, (self.comm, name), targets=self.targets)
        return DistArray.from_localarrays(da_key[0], context=self)

    def save_hdf5(self, filename, da, key='buffer', mode='a'):
        """
        Save a DistArray to a dataset in an ``.hdf5`` file.

        Parameters
        ----------
        filename : str
            Name of file to write to.
        da : DistArray
            Array to save to a file.
        key : str, optional
            The identifier for the group to save the DistArray to (the default
            is 'buffer').
        mode : optional, {'w', 'w-', 'a'}, default 'a'

            ``'w'``
                Create file, truncate if exists
            ``'w-'``
                Create file, fail if exists
            ``'a'``
                Read/write if exists, create otherwise (default)
        """
        try:
            # this is just an early check,
            # h5py isn't necessary until the local call on the engines
            import h5py
        except ImportError:
            errmsg = "An MPI-enabled h5py must be available to use save_hdf5."
            raise ImportError(errmsg)

        def _local_save_dnpy(filename, local_arr, key, mode):
            from distarray.localapi import save_hdf5
            save_hdf5(filename, local_arr, key, mode)

        self.apply(_local_save_dnpy, (filename, da.key, key, mode),
                   targets=da.targets)

    def load_npy(self, filename, distribution):
        """
        Load a DistArray from a dataset in a ``.npy`` file.

        Parameters
        ----------
        filename : str
            Filename to load.
        distribution: Distribution object

        Returns
        -------
        result : DistArray
            A DistArray encapsulating the file loaded.
        """

        def _local_load_npy(filename, ddpr, comm):
            from distarray.localapi import load_npy
            if len(ddpr):
                dim_data = ddpr[comm.Get_rank()]
            else:
                dim_data = ()
            return proxyize(load_npy(comm, filename, dim_data))

        ddpr = distribution.get_dim_data_per_rank()

        da_key = self.apply(_local_load_npy, (filename, ddpr, distribution.comm),
                            targets=distribution.targets)
        return DistArray.from_localarrays(da_key[0], distribution=distribution)

    def load_hdf5(self, filename, distribution, key='buffer'):
        """
        Load a DistArray from a dataset in an ``.hdf5`` file.

        Parameters
        ----------
        filename : str
            Filename to load.
        distribution: Distribution object
        key : str, optional
            The identifier for the group to load the DistArray from (the
            default is 'buffer').

        Returns
        -------
        result : DistArray
            A DistArray encapsulating the file loaded.
        """
        try:
            import h5py
        except ImportError:
            errmsg = "An MPI-enabled h5py must be available to use load_hdf5."
            raise ImportError(errmsg)

        def _local_load_hdf5(filename, ddpr, comm, key):
            from distarray.localapi import load_hdf5
            if len(ddpr):
                dim_data = ddpr[comm.Get_rank()]
            else:
                dim_data = ()
            return proxyize(load_hdf5(comm, filename, dim_data, key))

        ddpr = distribution.get_dim_data_per_rank()

        da_key = self.apply(_local_load_hdf5, (filename, ddpr, distribution.comm, key),
                   targets=distribution.targets)

        return DistArray.from_localarrays(da_key[0], distribution=distribution)

    def fromndarray(self, arr, distribution=None):
        """Create a DistArray from an ndarray.

        Parameters
        ----------
        distribution : Distribution object, optional
            If a Distribution object is not provided, one is created with
            `Distribution(arr.shape)`.

        Returns
        -------
        DistArray
            A DistArray distributed as specified, using the values and dtype
            from `arr`.
        """
        if distribution is None:
            distribution = Distribution(self, arr.shape)
        out = self.empty(distribution, dtype=arr.dtype)
        try:
            out[...] = arr
        except AttributeError:
            # no slicing for a given map type; do it the slow way
            for index, value in numpy.ndenumerate(arr):
                out[index] = value
        return out

    fromarray = fromndarray

    def fromfunction(self, function, shape, **kwargs):
        """Create a DistArray from a function over global indices.

        Unlike numpy's `fromfunction`, the result of distarray's
        `fromfunction` is restricted to the same Distribution as the
        index array generated from `shape`.

        See numpy.fromfunction for more details.
        """

        self.push_function(function.__name__, function, targets=self.targets)

        def _local_fromfunction(func_name, comm, ddpr, kwargs):
            from distarray.localapi import fromfunction
            from distarray.localapi.maps import Distribution
            from importlib import import_module

            main = import_module('__main__')

            if len(ddpr):
                dim_data = ddpr[comm.Get_rank()]
            else:
                dim_data = ()
            func = getattr(main, func_name)
            dist = Distribution(comm, dim_data=dim_data)
            local_arr = fromfunction(func, dist, **kwargs)
            return proxyize(local_arr)

        dist = kwargs.get('dist', None)
        grid_shape = kwargs.get('grid_shape', None)
        distribution = Distribution(context=self,
                                    shape=shape, dist=dist,
                                    grid_shape=grid_shape)
        ddpr = distribution.get_dim_data_per_rank()
        da_name = self.apply(_local_fromfunction,
                             (function.__name__, distribution.comm, ddpr, kwargs),
                             targets=distribution.targets)
        return DistArray.from_localarrays(da_name[0],
                                          distribution=distribution)

    def register(self, func):
        """Associate a function with this Context.  Allows access to the local
        process and local data associated with each DistArray.

        After registering a function with a context, the function can be called
        as ``context.func(...)``.  Doing so will call the function locally on
        target processes determined from the arguments passed in using
        ``Context.apply(...)``.  The function can take non-proxied Python
        objects, DistArrays, or other proxied objects as arguments.
        Non-proxied Python objects will be broadcasted to all local processes;
        proxied objects will be dereferenced before calling the function on the
        local process.
        """

        if func.__name__ in ("""__init__ cleanup close apply push_function
                             delete_key empty zeros ones save_dnpy load_dnpy
                             save_hdf5 load_npy load_hdf5 fromndarray
                             fromarray fromfunction register""".split()):
            msg = "Function name %s clashes with existing function."
            raise ValueError(msg % func.__name__)
        if func.__name__.startswith("_"):
            msg = "Function name %r starts with underscore."
            raise ValueError(msg % func.__name__)

        self.push_function(func.__name__, func, targets=self.targets)

        @wraps(func)
        def _wrapper(ctx, *args, **kwargs):
            dist = ctx._determine_distribution(list(args) +
                                               list(kwargs.values()))
            targets = dist.targets
            args = [a.key if isinstance(a, DistArray) else a
                    for a in args]
            kwargs = {k: (v.key if isinstance(v, DistArray) else v)
                      for k, v in kwargs.items()}
            results = ctx.apply(func, args=args,
                                kwargs=kwargs, targets=targets,
                                autoproxyize=True)
            return ctx._process_local_results(results, targets)

        setattr(self.__class__, _wrapper.__name__, _wrapper)

    def _determine_distribution(self, objs):
        dists = []
        for o in objs:
            if isinstance(o, DistArray):
                dists.append(o.distribution)
        for d in dists[1:]:
            if not dists[0].is_compatible(d):
                msg = "Distrbution %r is not compatible with %r"
                raise ValueError(msg % (dists[0], d))
        if not dists:
            raise TypeError("Cannot determine a Distribution.")
        return dists[0]

    def _process_local_results(self, results, targets):
        """Figure out what to return on the Client.

        Parameters
        ----------
        key : string
            Key corresponding to wrapped function's return value.

        Returns
        -------
        Varied
            A DistArray (if locally all values are LocalArray), a None (if
            locally all values are None), or else, pull the result back to the
            client and return it.  If all but one of the pulled values is None,
            return that non-None value only.
        """
        def is_NoneType(pxy):
            return pxy.type_str == str(type(None))

        def is_LocalArray(pxy):
            return (isinstance(pxy, Proxy) and
                    pxy.type_str == "<class 'distarray.localapi.localarray.LocalArray'>")

        if all(is_LocalArray(r) for r in results):
            result = DistArray.from_localarrays(results[0], context=self, targets=targets)
        elif all(r is None for r in results):
            result = None
        else:
            if has_exactly_one(results):
                result = next(x for x in results if x is not None)
            else:
                result = results

        return result

class IPythonContext(BaseContext):

    """
    Context class that uses IPython.parallel.

    See the docstring for  `BaseContext` for more information about Contexts.

    See also
    --------
    BaseContext
    """

    def __init__(self, client=None, targets=None):

        if client is None:
            self.client = IPythonClient()
            self.owns_client = True
        else:
            self.client = client
            self.owns_client = False

        self.view = self.client[:]
        self.nengines = len(self.view)

        self.all_targets = sorted(self.view.targets)
        if targets is None:
            self.targets = self.all_targets
        else:
            self.targets = []
            for target in targets:
                if target not in self.all_targets:
                    raise ValueError("Target %r not registered" % target)
                else:
                    self.targets.append(target)
        self.targets = sorted(self.targets)

        # local imports
        self.view.execute("from functools import reduce; "
                          "from importlib import import_module; "
                          "import distarray.localapi; "
                          "import distarray.localapi.mpiutils; "
                          "import distarray.utils; "
                          "import distarray.localapi.proxyize as proxyize; "
                          "from distarray.localapi.proxyize import Proxy; "
                          "import numpy")

        self.context_key = self._setup_context_key()

        # setup proxyize which is used by context.apply in the rest of the
        # setup.
        cmd = "proxyize = proxyize.Proxyize()"
        self.view.execute(cmd)

        self._base_comm = self._make_base_comm()
        self._comm_from_targets = {tuple(sorted(self.view.targets)): self._base_comm}
        self.comm = self.make_subcomm(self.targets)

        if not BaseContext._CLEANUP:
            BaseContext._CLEANUP = (atexit.register(ipython_cleanup.clear_all),
                                    atexit.register(ipython_cleanup.cleanup_all,
                                                    '__main__',
                                                    DISTARRAY_BASE_NAME))

    def make_subcomm(self, new_targets):

        if new_targets != sorted(new_targets):
            raise ValueError("targets must be in sorted order.")

        try:
            return self._comm_from_targets[tuple(new_targets)]
        except KeyError:
            pass

        def _make_new_comm(rank_list, base_comm):
            import distarray.localapi.mpiutils as mpiutils
            res = mpiutils.create_comm_with_list(rank_list, base_comm)
            return proxyize(res)  # noqa

        new_comm = self.apply(_make_new_comm, (new_targets, self._base_comm),
                              targets=self.view.targets)[0]

        self._comm_from_targets[tuple(new_targets)] = new_comm
        return new_comm

    def _make_base_comm(self):
        """
        Returns a proxy for an MPI communicator that encompasses all targets in
        self.view.targets (not self.targets, which can be a subset).
        """

        def get_rank():
            from distarray.localapi.mpiutils import get_comm_private
            return get_comm_private().Get_rank()

        # self.view's engines must encompass all ranks in the MPI communicator,
        # i.e., everything in rank_map.values().
        def get_size():
            from distarray.localapi.mpiutils import get_comm_private
            return get_comm_private().Get_size()

        # get a mapping of IPython engine ID to MPI rank
        rank_from_target = self.view.apply_async(get_rank).get_dict()
        ranks = [ rank_from_target[target] for target in self.view.targets ]

        comm_size = self.view.apply_async(get_size).get()[0]
        if set(rank_from_target.values()) != set(range(comm_size)):
            raise ValueError('Engines in view must encompass all MPI ranks.')

        # create a new communicator with the subset of ranks. Note that
        # create_comm_with_list() must be called on all engines, not just those
        # involved in the new communicator.  This is because
        # create_comm_with_list() issues a collective MPI operation.
        def _make_new_comm(rank_list):
            import distarray.localapi.mpiutils as mpiutils
            new_comm = mpiutils.create_comm_with_list(rank_list)
            if not mpiutils.get_base_comm():
                mpiutils.set_base_comm(new_comm)
            return proxyize(new_comm)  # noqa

        return self.apply(_make_new_comm, args=(ranks,),
                          targets=self.view.targets)[0]

    # Key management routines:
    def cleanup(self):
        """ Delete keys that this context created from all the engines. """
        # TODO: FIXME: cleanup needs updating to work with proxy objects.
        ipython_cleanup.cleanup(view=self.view, module_name='__main__',
                                prefix=self.context_key)

    def close(self):
        self.cleanup()
        def free_subcomm(subcomm):
            subcomm.Free()
        for targets, subcomm in self._comm_from_targets.items():
            self.apply(free_subcomm, (subcomm,), targets=targets)
        if self.owns_client:
            self.client.close()
        self.comm = None

    # End of key management routines.

    def _execute(self, lines, targets):
        return self.view.execute(lines, targets=targets, block=True)

    def _push(self, d, targets):
        return self.view.push(d, targets=targets, block=True)

    def apply(self, func, args=None, kwargs=None, targets=None, autoproxyize=False):
        """
        Analogous to IPython.parallel.view.apply_sync

        Parameters
        ----------
        func : function
        args : tuple
            positional arguments to func
        kwargs : dict
            key word arguments to func
        targets : sequence of integers
            engines func is to be run on.
        autoproxyize: bool, default False
            If True, implicitly return a Proxy object from the function.

        Returns
        -------
            return a list of the results on the each engine.
        """

        def func_wrapper(func, apply_nonce, context_key, args, kwargs, autoproxyize):
            """
            Function which calls the applied function after grabbing all the
            arguments on the engines that are passed in as names of the form
            `__distarray__<some uuid>`.
            """
            from importlib import import_module
            import types
            from distarray.metadata_utils import arg_kwarg_proxy_converter
            from distarray.localapi import LocalArray

            main = import_module('__main__')
            main.proxyize.set_state(apply_nonce)

            # Modify func to change the namespace it executes in.
            # but builtins don't have __code__, __globals__, etc.
            if not isinstance(func, types.BuiltinFunctionType):
                # get func's building  blocks first
                func_code = func.__code__
                func_name = func.__name__
                func_defaults = func.__defaults__
                func_closure = func.__closure__

                # build the func's new execution environment
                main.__dict__.update({'context_key': context_key})
                new_func_globals = main.__dict__
                # create the new func
                func = types.FunctionType(func_code, new_func_globals,
                                          func_name, func_defaults,
                                          func_closure)

            args, kwargs = arg_kwarg_proxy_converter(args, kwargs)
            result = func(*args, **kwargs)

            if autoproxyize and isinstance(result, LocalArray):
                return main.proxyize(result)
            else:
                return result

        # default arguments
        args = () if args is None else args
        kwargs = {} if kwargs is None else kwargs

        args = tuple(a.key if isinstance(a, DistArray) else a for a in args)
        kwargs = {k: (v.key if isinstance(v, DistArray) else v) for k, v in kwargs.items()}

        apply_nonce = nonce()
        wrapped_args = (func, apply_nonce, self.context_key, args, kwargs, autoproxyize)

        targets = self.targets if targets is None else targets

        with self.view.temp_flags(targets=targets):
            return self.view.apply_sync(func_wrapper, *wrapped_args)

    def push_function(self, key, func, targets=None):
        targets = targets or self.targets
        self._push({key: func}, targets=targets)

def _shutdown(mpi, intercomm, targets):
    msg = ('kill',)
    for t in targets:
        intercomm.send(msg, dest=t)
    intercomm.Free()
    mpi.Finalize()

class MPIContext(BaseContext):

    """
    Context class that uses MPI only (no IPython.parallel).

    See the docstring for  `BaseContext` for more information about Contexts.

    See also
    --------
    BaseContext
    """

    INTERCOMM = None

    def delete_key(self, key, targets=None):
        msg = ('delete', key)
        targets = targets or self.targets
        if MPIContext.INTERCOMM:
            self._send_msg(msg, targets=targets)

    def __init__(self, targets=None):

        if MPIContext.INTERCOMM is None:
            MPIContext.INTERCOMM = initial_comm_setup()
            assert get_world_rank() == 0

        self.nengines = MPIContext.INTERCOMM.remote_size
        self.all_targets = list(range(self.nengines))
        self.targets = self.all_targets if targets is None else sorted(targets)

        # make/get comms
        # this is the object we want to use with push, pull, etc'
        self._comm_from_targets = {}
        self.comm = self.make_subcomm(self.targets)

        if BaseContext._CLEANUP is None:
            BaseContext._CLEANUP = atexit.register(_shutdown,
                                               mpi,
                                               MPIContext.INTERCOMM,
                                               tuple(self.all_targets))

        # local imports
        self._execute("from functools import reduce; "
                          "from importlib import import_module; "
                          "import distarray.localapi; "
                          "import distarray.localapi.mpiutils; "
                          "import distarray.utils; "
                          "from distarray.localapi.proxyize import Proxyize, Proxy; "
                          "import numpy")

        self.context_key = self._setup_context_key()

        # setup proxyize which is used by context.apply in the rest of the
        # setup.
        cmd = "proxyize = Proxyize()"
        self._execute(cmd)

    # Key management routines:

    def cleanup(self):
        """ Delete keys that this context created from all the engines. """
        # TODO: implement cleanup.
        pass

    def close(self):
        for targets, subcomm in self._comm_from_targets.items():
            if subcomm is MPIContext.INTERCOMM:
                continue
            self._send_msg(('free_comm', subcomm), targets=targets)

    # End of key management routines.

    def _send_msg(self, msg, targets=None):
        targets = self.targets if targets is None else targets
        for t in targets:
            MPIContext.INTERCOMM.send(msg, dest=t)

    def _recv_msg(self, targets=None):
        res = []
        targets = self.targets if targets is None else targets
        for t in targets:
            res.append(MPIContext.INTERCOMM.recv(source=t))
        return res

    def make_subcomm(self, targets):
        if len(targets) > self.nengines:
            msg = ("The number of engines (%s) is less than the number of "
                   "targets you want (%s)." % (self.nengines, len(targets)))
            raise ValueError(msg)

        if targets != sorted(targets):
            raise ValueError("targets must be in sorted order.")

        try:
            return self._comm_from_targets[tuple(targets)]
        except KeyError:
            pass

        msg = ('make_targets_comm', targets)
        self._send_msg(msg, targets=self.all_targets)
        new_comm = make_targets_comm(targets)
        self._comm_from_targets[tuple(targets)] = new_comm
        return new_comm

    def _execute(self, lines, targets=None):
        msg = ('execute', lines)
        return self._send_msg(msg, targets=targets)

    def _push(self, d, targets=None):
        msg = ('push', d)
        return self._send_msg(msg, targets=targets)

    def apply(self, func, args=None, kwargs=None, targets=None, autoproxyize=False):
        """
        Analogous to IPython.parallel.view.apply_sync

        Parameters
        ----------
        func : function
        args : tuple
            positional arguments to func
        kwargs : dict
            keyword arguments to func
        targets : sequence of integers
            engines func is to be run on.
        autoproxyize: bool, default False
            If True, implicitly return a Proxy object from the function.

        Returns
        -------
        list
            result from each engine.
        """
        # default arguments
        args = () if args is None else args
        kwargs = {} if kwargs is None else kwargs

        args = tuple(a.key if isinstance(a, DistArray) else a for a in args)
        kwargs = {k: (v.key if isinstance(v, DistArray) else v) for k, v in kwargs.items()}

        targets = self.targets if targets is None else targets

        apply_nonce = nonce()
        apply_metadata = (apply_nonce, self.context_key)

        if not isinstance(func, types.BuiltinFunctionType):
            # break up the function
            func_code = func.__code__
            func_name = func.__name__
            func_defaults = func.__defaults__
            func_closure = func.__closure__

            func_data = (func_code, func_name, func_defaults, func_closure)

            msg = ('func_call', func_data, args, kwargs, apply_metadata, autoproxyize)

        else:
            msg = ('builtin_call', func, args, kwargs, autoproxyize)

        self._send_msg(msg, targets=targets)
        return self._recv_msg(targets=targets)

    def push_function(self, key, func, targets=None):
        push_function(self, key, func, targets=targets)

class ContextCreationError(RuntimeError):
    pass

def _fire_off_engines(rank):
    if rank:
        from distarray.mpi_engine import Engine
        Engine()

def Context(*args, **kwargs):

    kind = kwargs.pop('kind', '')

    if not kind:
        kind = 'ipython' if is_solo_mpi_process() else 'mpi'

    if kind.lower().startswith('mpi'):

        CW = get_comm_world()
        myrank = CW.rank
        if myrank:
            _fire_off_engines(myrank)
            import sys
            sys.exit()
        else:
            return MPIContext(*args, **kwargs)

    elif kind.lower().startswith('ipython'):
        return IPythonContext(*args, **kwargs)

    else:
        raise ContextCreationError("%s is not a valid Context selector string." % kind)

redpajama_set_name: RedPajamaGithub


text:
2 Corinthians 8;2 Kings 20;2 Kings 21;Nahum 2
2 Corinthians 8; 2 Kings 20; 2 Kings 21; Nahum 2
Viewing Multiple Passages
1 We want you to know, brothers, about the grace of God granted to the churches of Macedonia:
2 during a severe testing by affliction, their abundance of joy and their deep poverty overflowed into the wealth of their generosity.
3 I testify that, on their own, according to their ability and beyond their ability,
4 they begged us insistently for the privilege of sharing in the ministry to the saints,
5 and not just as we had hoped. Instead, they gave themselves especially to the Lord, then to us by God's will.
6 So we urged Titus that, just as he had begun, so he should also complete this grace to you.
7 Now as you excel in everything-in faith, in speech, in knowledge, in all diligence, and in your love for us-excel also in this grace.
8 I am not saying this as a command. Rather, by means of the diligence of others, I am testing the genuineness of your love.
9 For you know the grace of our Lord Jesus Christ: although He was rich, for your sake He became poor, so that by His poverty you might become rich.
10 Now I am giving an opinion on this because it is profitable for you, who a year ago began not only to do something but also to desire it.
11 But now finish the task as well, that just as there was eagerness to desire it, so there may also be a completion from what you have.
12 For if the eagerness is there, it is acceptable according to what one has, not according to what he does not have.
13 It is not that there may be relief for others and hardship for you, but it is a question of equality-
14 at the present time your surplus is [available] for their need, so that their abundance may also become [available] for your need, that there may be equality.
15 As it has been written: The person who gathered much did not have too much, and the person who gathered little did not have too little.
16 Thanks be to God who put the same diligence for you into the heart of Titus.
17 For he accepted our urging and, being very diligent, went out to you by his own choice.
18 With him we have sent the brother who is praised throughout the churches for his gospel ministry.
19 And not only that, but he was also appointed by the churches to accompany us with this gift that is being administered by us for the glory of the Lord Himself and to show our eagerness [to help].
20 We are taking this precaution so no one can find fault with us concerning this large sum administered by us.
21 For we are making provision for what is honorable, not only before the Lord but also before men.
22 We have also sent with them our brother whom we have often tested, in many circumstances, and found diligent-and now even more diligent because of his great confidence in you.
23 As for Titus, he is my partner and co-worker serving you; as for our brothers, they are the messengers of the churches, the glory of Christ.
24 Therefore, before the churches, show them the proof of your love and of our boasting about you.
1 In those days Hezekiah became terminally ill. The prophet Isaiah son of Amoz came and said to him, "This is what the Lord says: 'Put your affairs in order, for you are about to die; you will not recover.' "
2 Then Hezekiah turned his face to the wall and prayed to the Lord,
3 "Please Lord, remember how I have walked before You faithfully and wholeheartedly and have done what is good in Your sight." And Hezekiah wept bitterly.
4 Isaiah had not yet gone out of the inner courtyard when the word of the Lord came to him:
5 "Go back and tell Hezekiah, the leader of My people, 'This is what the Lord God of your ancestor David says: I have heard your prayer; I have seen your tears. Look, I will heal you. On the third day [from now] you will go up to the Lord's temple.
6 I will add 15 years to your life. I will deliver you and this city from the hand of the king of Assyria. I will defend this city for My sake and for the sake of My servant David.' "
7 Then Isaiah said, "Bring a lump of pressed figs." So they brought it and applied it to his infected skin, and he recovered.
8 Hezekiah had asked Isaiah, "What is the sign that the Lord will heal me and that I will go up to the Lord's temple on the third day?"
9 Isaiah said, "This is the sign to you from the Lord that He will do what He has promised: Should the shadow go ahead 10 steps or go back 10 steps?"
10 Then Hezekiah answered, "It's easy for the shadow to lengthen 10 steps. No, let the shadow go back 10 steps."
11 So Isaiah the prophet called out to the Lord, and He brought the shadow back the 10 steps it had descended on Ahaz's stairway.
12 At that time Merodach-baladan son of Baladan, king of Babylon, sent letters and a gift to Hezekiah since he heard that Hezekiah had been sick.
13 Hezekiah gave them a hearing and showed them his whole treasure house-the silver, the gold, the spices, and the precious oil-and his armory, and everything that was found in his treasuries. There was nothing in his palace and in all his realm that Hezekiah did not show them.
14 Then the prophet Isaiah came to King Hezekiah and asked him, "What did these men say, and where did they come to you from?" Hezekiah replied, "They came from a distant country, from Babylon."
15 Isaiah asked, "What have they seen in your palace?" Hezekiah answered, "They have seen everything in my palace. There isn't anything in my treasuries that I didn't show them."
16 Then Isaiah said to Hezekiah, "Hear the word of the Lord:
17 'The time will certainly come when everything in your palace and all that your fathers have stored up until this day will be carried off to Babylon; nothing will be left,' says the Lord.
18 'Some of your descendants who come from you will be taken away, and they will become eunuchs in the palace of the king of Babylon.' "
19 Then Hezekiah said to Isaiah, "The word of the Lord that you have spoken is good," for he thought: Why not, if there will be peace and security during my lifetime?
20 The rest of the events of Hezekiah's [reign], along with all his might and how he made the pool and the tunnel and brought water into the city, are written about in the Historical Record of Judah's Kings.
21 Hezekiah rested with his fathers, and his son Manasseh became king in his place.
1 Manasseh was 12 years old when he became king; he reigned 55 years in Jerusalem. His mother's name was Hephzibah.
2 He did what was evil in the Lord's sight, imitating the abominations of the nations that the Lord had dispossessed before the Israelites.
3 He rebuilt the high places that his father Hezekiah had destroyed and reestablished the altars for Baal. He made an Asherah, as King Ahab of Israel had done; he also worshiped the whole heavenly host and served them.
4 He would build altars in the Lord's temple, where the Lord had said, "Jerusalem is where I will put My name."
5 He built altars to the whole heavenly host in both courtyards of the Lord's temple.
6 He made his son pass through the fire, practiced witchcraft and divination, and consulted mediums and spiritists. He did a great amount of evil in the Lord's sight, provoking [Him].
7 Manasseh set up the carved image of Asherah he made in the temple that the Lord had spoken about to David and his son Solomon, "I will establish My name forever in this temple and in Jerusalem, which I have chosen out of all the tribes of Israel.
8 I will never again cause the feet of the Israelites to wander from the land I gave to their ancestors if only they will be careful to do all I have commanded them-the whole law that My servant Moses commanded them."
9 But they did not listen; Manasseh caused them to stray so that they did greater evil than the nations the Lord had destroyed before the Israelites.
10 The Lord spoke through His servants the prophets, saying,
11 "Since Manasseh king of Judah has committed all these abominations-greater evil than the Amorites who preceded him had done-and by means of his idols has also caused Judah to sin,
12 this is what the Lord God of Israel says: 'I am about to bring such disaster on Jerusalem and Judah that everyone who hears about it will shudder.
13 I will stretch over Jerusalem the measuring line [used on] Samaria and the mason's level [used on] the house of Ahab, and I will wipe Jerusalem clean as one wipes a bowl-wiping it and turning it upside down.
14 I will abandon the remnant of My inheritance and hand them over to their enemies. They will become plunder and spoil to all their enemies,
15 because they have done what is evil in My sight and have provoked Me from the day their ancestors came out of Egypt until today.' "
16 Manasseh also shed so much innocent blood that he filled Jerusalem with it from one end to another. This was in addition to his sin he caused Judah to commit so that they did what was evil in the Lord's sight.
17 The rest of the events of Manasseh's [reign], along with all his accomplishments and the sin that he committed, are written about in the Historical Record of Judah's Kings.
18 Manasseh rested with his fathers and was buried in the garden of his own house, the garden of Uzza. His son Amon became king in his place.
19 Amon was 22 years old when he became king; he reigned two years in Jerusalem. His mother's name was Meshullemeth daughter of Haruz; [she was] from Jotbah.
20 He did what was evil in the Lord's sight as his father Manasseh had done.
21 He walked in all the ways his father had walked; he served the idols his father had served, and he worshiped them.
22 He abandoned the Lord God of his ancestors and did not walk in the way of the Lord.
23 Amon's servants conspired against the king and killed him in his own house.
24 Then the common people executed all those who had conspired against King Amon and made his son Josiah king in his place.
25 The rest of the events of Amon's [reign], along with his accomplishments, are written about in the Historical Record of Judah's Kings.
26 He was buried in his tomb in the garden of Uzza, and his son Josiah became king in his place.
1 One who scatters is coming up against you. Man the fortifications! Watch the road! Brace yourself! Summon all your strength!
2 For the Lord will restore the majesty of Jacob, yes, the majesty of Israel, though ravagers have ravaged them and ruined their vine branches.
3 The shields of his warriors are dyed red; the valiant men are dressed in scarlet. The fittings of the chariot flash like fire on the day of its [battle] preparations, and the spears are brandished.
4 The chariots dash madly through the streets; they rush around in the plazas. They look like torches; they dart back and forth like lightning.
5 He gives orders to his officers; they stumble as they advance. They race to its wall; the protective shield is set in place.
6 The river gates are opened, and the palace erodes away.
7 Beauty is stripped, she is carried away; her ladies-in-waiting moan like the sound of doves, and beat their breasts.
8 Nineveh has been like a pool of water from her [first] days, but they are fleeing. "Stop! Stop!" [they cry,] but no one turns back.
9 "Plunder the silver! Plunder the gold!" There is no end to the treasure, an abundance of every precious thing.
10 Desolation, decimation, devastation! Hearts melt, knees tremble, loins shake, every face grows pale!
11 Where is the lions' lair, or the feeding ground of the young lions, where the lion and lioness prowled, and the lion's cub, with nothing to frighten them away?
12 The lion mauled whatever its cubs needed and strangled [prey] for its lionesses. It filled up its dens with the kill, and its lairs with mauled prey.
13 Beware, I am against you- the declaration of the Lord of Hosts. I will make your chariots go up in smoke and the sword will devour your young lions. I will cut off your prey from the earth, and the sound of your messengers will never be heard again.

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: (PHP) Using the username of a logged in user to add it into another database So for my assignment, I need to use the username of a logged in user, and put that into another table in the same database, when the said user uploads an image, and whenever I try to upload, the database comes up with only the id, the rest is empty.
Processing Script:
<?php
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['title'])) $title = $_POST['title'];
if(isset($_POST['category'])) $category = $_POST['category'];
if(isset($_POST['description'])) $description = $_POST['description'];
if(isset($_POST['tags'])) $tags = $_POST['tags'];

$filename = $_FILES['image']['name'];
$location = $_FILES['image']['tmp_name'];

move_uploaded_file($location, "uploads/$filename");

$db = mysqli_connect("localhost", "root","", "artworks") or die(mysqli_error($db));
$q = "insert into artwork values(null, '$username', '$title', '$category', '$description', '$tags', '$filename')";
mysqli_query($db, $q) or die(mysqli_error($db));

header("Location:index.php");
exit(0); ?>

Login Script:
    <?php
    if(isset($_POST['username'])) $username = $_POST['username'];
    if(isset($_POST['password'])) $password = $_POST['password'];

    $db = mysqli_connect("localhost", "root","", "artworks")  or die(mysqli_error($db));
    $q = "select * from member where username='$username' and password=SHA('$password')";
    $results = mysqli_query($db, $q) or die(mysqli_error($db));

    if(mysqli_num_rows($results) > 0)
    {
        session_start();
        $_SESSION['username'] = $username;
        header("Location:index.php");
        exit(0);
    }

    header("Location:register.php");?>

Upload Script
<?php
session_start();

    if(!isset($_SESSION['username']))
    {
        header("Location:login.php");
        exit(0);
    }
?>

<?php include("header.inc");
        include("nav.inc"); ?>

<form role = "form-horizontal" method = "post" action = "add_ps.php" enctype="multipart/form-data">

            Title
            <input type = "text" class = "form-control" id = "title" placeholder = "Title of Image">

            Category
            <input type = "text" class = "form-control" id = "category" placeholder = "Category of Image">

            Description
            <textarea class="form-control" rows="5" id="description" placeholder = "Description of Image"></textarea>

            Tags (Seperate with comma)
            <input type = "text" class = "form-control" id = "tag" placeholder = "Tag of Image">

            File input
            <input type = "file" id = "uploads">

Upload image here

                <button type = "submit" class = "btn btn-primary">Submit</button>

</form>

<?php include("footer.inc"); ?>

Hope this help, I feel like I am missing out on some tiny detail

A: When you have your fields in the form, your fields will be submitted with the name= value of the field which you don't have...
    <input type="text" class="form-control" id="title" placeholder="Title of Image" name="title">

Repeat this for all of your fields.  I've also removed the spaces between the value and the attribute label.
Also when you submit the form, you check if a value is set and then set the variable you use, but you don't check if they aren't set and stop the form being submitted.  This means that if the field isn't set, the code will just continue with an empty value (as you've found)  it will also have some form of message(if you added reporting) to say the field doesn't exist...
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['title'])) $title = $_POST['title'];
if(isset($_POST['category'])) $category = $_POST['category'];
if(isset($_POST['description'])) $description = $_POST['description'];
if(isset($_POST['tags'])) $tags = $_POST['tags'];

Would be better written to say if all the fields are set...
if (isset($_POST['username']) && isset($_POST['title']) ... ) { // Add rest of fields.
    $username = $_POST['username'];
    $title = $_POST['title'];
    // Add rest of fields.

    // Process insert
}

A: Just add name="image" You are missing it
 <input type = "file" id = "uploads" name="image">

redpajama_set_name: RedPajamaStackExchange


text:
COVID-19 Resources & Information Read On...
Town Centre Park
1299 Pinetree Way
Coquitlam, BC V3B 7S4
Sports Field & Outdoor Court Status and Availability - the current status and availability of sports fields in Coquitlam can be found on the Sports Field Status page.
Sport and User Group Parking Map (PDF)
Sport Facility Hosting Guide (PDF)
Town Centre Park Amenities Map (PDF)
Town Centre Park Map (PDF)
Walking and Jogging Map (PDF)
Other Link Town Centre Park Master Plan
Playing Field
Sport Field
Named, "Best Public Space" by the Canadian Institute of Planners in 2017, Coquitlam's Town Centre Park is a destination city-wide park that serves the local community, providing exceptional sport, recreation and cultural amenities and experiences.
TD Community Plaza
The TD Community Plaza is a one of the premier outdoor performance and event venues in the City and the region. With seating for up to 1,300, scenic lake views and easy access, the design combines landscaping, hardscape and freeform architectural elements, along with inscriptions and artistic motifs that reference milestones from the City's 125 plus years and the area's natural history.
Coquitlam's largest inventory of sport facilities, which includes:
Percy Perry track and field stadium
3 ball diamonds
5 lit synthetic turf playing fields and a grass playing field
6 sand volleyball courts
8 lit tennis courts
Basketball cour
Roller hockey court
View the Sport Facility Hosting Guide for more information about Town Centre Park amenities.
Town Centre Park is accessed by transit from Lafarge Lake-Douglas SkyTrain station and has ample free parking.
Active Play Amenities
Other amenities for active play include:
Playground with accessible features
Skateboard bowl
Lafarge Lake
Lafarge Lake, loop trail and lawn meadows invite strolling, picnicking, or fishing from the pier – the Lake is regularly stocked with rainbow trout between March and November by the Fraser Valley Trout Hatchery. Enjoy the forest walk and mountain views and visit in the evening to experience the fountain colours and seasonal light displays.
Inspiration Garden
Inspiration Garden, located in the southeast corner of the Park, supports and inspires gardeners with a focus on sharing knowledge about sustainable growing practices. Discover beautiful horticultural displays and many opportunities for learning at the Inspiration Garden.
Concessions are available during the summer, open daily 10:30 a.m. to 7:30 p.m. including weekends.
Thirty years ago, the Park was the site of a gravel plant and pit. What visitors now enjoy as picturesque Lafarge Lake was a man-made excavated lake donated to the City by the LaFarge company in the mid 1980s. Mel Earl was the Lafarge Canada plant manager and the park commissioner who persuaded his company to donate the Lafarge Gravel Pit land to the citizens of Coquitlam. He passed away on July 29, 1992 and a monument to honour him is located on the west side of the tennis courts.
To help the City realize a vision of hosting the 1991 Summer Games, the surrounding land was given by the Province and developed into a state-of-the-art sport and recreation facility. Town Centre Park officially opened in May 1989, and the BC Summer Games, held two years later, were a huge success.
Town Centre Park Plaza opened on the eastern shore of Lafarge Lake during the July 1, 2016 Canada Day celebration as a legacy project or the Coquitlam's 125th Anniversary. It was renamed TD Community Plaza in 2018. Within the hundred acres of Town Centre Park, the legacy of sport, recreation and celebration continues.
Artificial turf and natural grass
Base distance 50 feet
Pitching distance 70 feet
Field Hockey and Lacrosse, Full Size
Football Canadian/American dimensions
Soccer 230 by 328 feet
Lit Fields
Sports Fields Status
Sports Field Status Updates
Eight Courts (Tennis Court Use Times (PDF))
Has Lighting
Subfacilities
► ▼ TD Community Plaza
View Subfacility
► ▼ Town Centre Spray Park
View current
Follow City Council
Pay bills,
applications & licences
& report a problem
Contribute your ideas
and feedback
Stay informed on
3000 Guildford Way
Coquitlam, BC Canada V3B 7N2
Hours: Mon to Fri, 8 a.m.-5 p.m.
Reception: 604-927-3000
Property Inquiry System
Taxes and Utilities
Business Licence Renewal
Bylaws and Legal


On this week's episode of The Real Housewives of Orange County, Shannon Beador had a breakthrough about her rocky marriage to her husband David. Beador told her best friend Tamra Judge that she wasn't going to let her problems with David affect how she feels about herself anymore.
Viewers know all about Shannon's marital issues, because she has revealed that David has become distant since her weight-gain, which started reminding her of the last time he pulled away from her and had an affair.
Shannon explained how her weight-gain has put a strain on her marriage.
Tamra showed support and concern for her friend.
Judge also said that when she was married to her ex-husband, Simon Barney, she would lash out at others because she was unhappy. She said she sees the same pattern happening with Shannon.
The ladies are getting ready to go on a trip to Iceland (it's going to be crazy) and this seemed to improve Shannon's outlook on things.
"I talk to you every single day, and I swear you cry once a day. Maybe you need a little time away from David right now," Tamra added.
What did you think of this week's episode of RHOC? Let's talk about it.


ORLANDO, Fla. -- A longtime Orlando company is preparing to weather a big storm: retaliatory tariffs from the E.U., Canada and Mexico, now in place.
"These tariffs are a big deal," said Duane Kuck. "It's going to get back to the U.S. and its employment."
For the last fifty years, Kuck's family has owned and operated Regal Marine Industries. The boating company, which started with six employees, has grown exponentially. It now employs 750 people between its Jetport Drive location by Orlando International Airport and another factory in Valdosta, GA.
They build around 2,000 boats a year, sending them around the globe.
Kuck said that it's not a hobby; it's his passion, and one shared by many others.
"Boating is one of those things that really brings the family together … we find a lot of enthusiasm and energy around the idea of helping families get closer and building special memories," he explained.
But, Regal's president and CEO is worried that retaliatory E.U. tariffs will mean a big loss: around $13 million dollars each year.
"Most of our business going to the tariff regions, Canada, E.U. and Mexico, have just been put on hold or orders cancelled," he said, explaining that to get ahead of the tariff, they sent ten newly-constructed boats to Canada, almost wiping our their showroom stock.
According to the National Marine Manufacturers Association, with export tariffs to the E.U., Mexico and Canada of 20, 15 and 10 percent respectively, boat exports to those regions represent 69 percent of all U.S. made boats. And the business has essentially "frozen up."
"We'd like to see this trade war ended as soon as possible. We acknowledge and agree China has not been playing fair … But, we don't believe tariffs are the answer. We believe the answer is to get President Trump to the negotiating table with the president of China to negotiate a bilateral trade agreement," said the association's president, Thom Dammrich, on the phone today.
After all, the industry is large in the U.S., employing about 470,000 people; of that number, 55,000 are direct jobs in Florida.
There are also 5,500 related businesses in Florida, according to the association.
Dammrich shared that the economic impact of recreational boating in the sunshine state -- the number one boating state in the country -- is roughly $10.3 billion a year. Florida tops the U.S. in terms of total number registered boats and spending annually, plus measures high on the list of boat production.
"The industry welcomed the tax cuts earlier in the year, but believe the trade war will completely offset any gains from the tax cuts," added Dammrich.
"It's a huge disadvantage for the U.S. marine industry," said Kuck.
While they, too, benefited from the tax reform -- investing in new products and bonuses for the team -- and want trade to be fair, right now the industry is up against a rising tide of problems.
The business owner said that he doesn't want to have to lay any workers off. And the additional hires they were planning on making are on hold. They're now hoping to boost their business in the states as they pivot from the tariffed regions.


text:
This New Feature Makes Google Pixel 2 Better Than Samsung Galaxy S8
By Mark Aserit ( [email protected] ) Jun 28, 2017 10:00 AM EDT Comment
The Google Pixel 2 comes in October 2017 CNET
Details around Google's Pixel 2 continue to spread on the Internet. The newest leaked data claims the upcoming Pixel smartphone will have better camera and body design than Samsung Galaxy S8. Also, the update to the critically acclaimed Pixel may come in two variants.
The Pixel's elegant design is very appealing for most of the mobile phone users. Now that the Galaxy S8 and LG G6 have thin bezels, Google will reportedly go bezel-less for the next Pixel smartphone. Tech experts say Pixel 2 may look old if Google does not upgrade its design. Therefore, the bezel-less design will push the handset into today's new sleek tech aesthetic.
Aside from the new look, Google Pixel will have improved low-light camera sensor for photography enthusiasts. The primary camera of the first Pixel has only 12 megapixels, and Google is set to upgrade that feature for the Pixel 2. The main snapper of the second Pixel might offer 18-megapixel sensor.
The camera of iPhone is popular for its low-light and steady video recording. To keep up with the upcoming iPhone 8, expect Pixel 2 to have smooth and light sensitive video recording capabilities.
Fox News reported that the new Pixel might also offer longer battery life. The current Pixel and Pixel XL only have 13 hours of battery life. That's a very good time for a premium smartphone. However, if the next Pixel has the same 13-hour battery capacity, it might not stay competitive in the smartphone market. The Galaxy S8 and S8 Plus can last for up to 16 hours. So, we might see the next Pixel with 16-hour battery life.
Interestingly, folks from XDA Developers obtained interesting information on the upcoming Google Pixel 2 line. The publication said the data came from a developer who worked on the first version of the handset, suggesting the info is true. The developer revealed Google would release two variants of Pixel 2 this year, contrary to the rumored three versions.
The low-end version of Pixel 2 is codenamed "Walleye." It will reportedly have a 4.97-inch screen, a Snapdragon 835 processor and 4GB of RAM. Surprisingly, this smaller Pixel 2 may have similar features with iPhone 7. In a nod to Apple's revolutionary design, Google's plans to remove Walleye's headphone jack to make room for stereo speakers.
For the larger variant, "Taimen" will boast a 5.99-inch OLED display with 1440p resolution. Compare to Walleye, Taiman will have a headphone jack. Inside, it will be powered by Qualcomm's Snapdragon 835 processor, 128GB of storage and 4GB of RAM.
Google Pixel 2 release date is scheduled for October 2017. The handset is expected to become available in all major mobile carriers like Verizon, Sprint, and AT&T.
Tags : Google Pixel 2 release date, Google Pixel 2 specs, Google, Samsung Galaxy S8


You must love the Lord your God with all your heart and with all your soul and with all your might.
Even the biblical force of creation - the creator itself asks for one thing - love.
"The dance between darkness and light will always remain— the stars and the moon will always need the darkness to be seen, the darkness will just not be worth having without the moon and the stars." C. JoyBell C.
"I am my beloved's, and my beloved is mine." The Song of Songs.


text:
/**
 * This class is the bridge between the ngReactGrid class and React
 * @param ngReactGrid
 * @constructor
 */
var NgReactGridReactManager = function (ngReactGrid) {
    /**
     * Reference to the ngReactGrid main class
     */
    this.ngReactGrid = ngReactGrid;

    /**
     * How many records we are currently showing with filters, search, pageSize and pagination applied
     * @type {number}
     */
    this.showingRecords = 0;

    /**
     * The starting index by which we are filtering the local data
     * @type {number}
     */
    this.startIndex = 0;

    /**
     * The end index by which we are filtering local data
     * @type {number}
     */
    this.endIndex = 0;

    /**
     * This is a copy of the data given to ngReactGrid (local data only)
     * @type {Array}
     */
    this.originalData = [];

    /**
     * This is a copy of the data given to ngReactGrid whenever it is filtered (local data only)
     * @type {Array}
     */
    this.filteredData = [];

    /**
     * Values of all filter fields
     * @type {Object}
     */
    this.filterValues = {};

    /**
     * This is a copy of the pagination-independent viewable data in table that
     *     can be affected by filter and sort
     * @type {Array}
     */
    this.filteredAndSortedData = [];

    /**
     * Loading indicator
     * @type {boolean}
     */
    this.loading = false;

    /**
     * Instance pointer to a static function
     * @type {Function}
     */
    this.getObjectPropertyByString = NgReactGridReactManager.getObjectPropertyByString;
};

/**
 * This function is used to add API to the grid object created by the user.
 * @param gridObject
 */
NgReactGridReactManager.prototype.mixinAPI = function(gridObject) {
    var self = this;

    /**
     * Get filtered and sorted data
     */
    gridObject.getFilteredAndSortedData = function() {
        return self.getFilteredAndSortedData.call(self);
    };
};

/**
 * Get table data wrapper
 */
NgReactGridReactManager.prototype.getFilteredAndSortedData = function() {
    return this.filteredAndSortedData;
};

/**
 * Page size setter, this is called for the NgReactGridComponent (React class)
 * @param pageSize
 */
NgReactGridReactManager.prototype.setPageSize = function (pageSize) {

    var update = {
        pageSize: pageSize,
        currentPage: 1
    };

    /*
     * Is there a search in place
     */
    if (this.ngReactGrid.isSearching()) {
        update.data = this.filteredData;
    }

    /**
     * Send the update event to the main class
     */
    this.ngReactGrid.update(this.ngReactGrid.events.PAGESIZE, update);

    /**
     * If we are in server mode, call getData
     */
    if (this.ngReactGrid.isServerMode()) {
        this.ngReactGrid.getData();
    }
};

/**
 * Sorting callback, this is called from the NgReactGridComponent whenever a header cell is clicked (and is sortable)
 * @param field
 */
NgReactGridReactManager.prototype.setSortField = function (field) {

    /**
     * The initial update to the grid
     * @type {{sortInfo: {field: string, dir: string}}}
     */
    var update = {
        sortInfo: {
            field: field,
            dir: ""
        }
    };

    /**
     * Are we sorting on a new field
     */
    if (this.ngReactGrid.sortInfo.field !== field) {
        update.sortInfo.dir = "asc";
    } else {
        /**
         * Switch the sorting direction
         */
        if (this.ngReactGrid.sortInfo.dir === "asc") {
            update.sortInfo.dir = "desc";
        } else {
            update.sortInfo.dir = "asc";
        }

    }

    /**
     * Call getData for Server Mode or perform a local sort
     */
    if (this.ngReactGrid.isServerMode()) {
        this.ngReactGrid.update(this.ngReactGrid.events.SORTING, update);
        this.ngReactGrid.getData();
    } else {
        this.performLocalSort(update);
    }
};

/**
 * Simple asc -> desc, desc -> asc sorting, used for local data, resets the current page to 1
 * @param update
 */
NgReactGridReactManager.prototype.performLocalSort = function (update) {
    var copy;

    if (this.ngReactGrid.isSearching()) {
        copy = this.filteredData;
    } else {
        copy = this.originalData.slice(0);
    }

    var isAsc = update.sortInfo.dir === "asc";

    copy.sort(function (a, b) {
        var aField = this.getObjectPropertyByString(a, update.sortInfo.field);
        var bField = this.getObjectPropertyByString(b, update.sortInfo.field);

        if (isAsc) {
            return aField <= bField ? -1 : 1;
        } else {
            return aField >= bField ? -1 : 1;
        }
    }.bind(this));

    update.data = copy;
    update.currentPage = 1;

    this.ngReactGrid.update(this.ngReactGrid.events.SORTING, update);
};

/**
 * This is a recursive search function that will transverse an object searching for an index of a string
 * @param obj
 * @param search
 * @param (Optional) column
 * @returns {boolean}
 */
NgReactGridReactManager.prototype.deepSearch = function(obj, search, column) {
    var found = false;

    if (obj) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {

                var prop = obj[i];

                if (typeof prop === "object") {
                    found = this.deepSearch(prop, search, column);
                    if (found === true) break;
                } else {
                    if (column && column !== '_global') {
                      if (i !== column.split('.').pop()) continue;
                    }
                    if (String(obj[i]).toLowerCase().indexOf(search.toLowerCase()) !== -1) {
                        found = true;
                        break;
                    }
                }

            }
        }
    }

    return found;
};

/**
 * Search callback for everytime the user updates the search box.
 *   Supports local mode and server mode; local mode only for column search.
 * @param search
 * @param (Optional) column
 */
NgReactGridReactManager.prototype.setSearch = function (search, column) {
    var column = column ? column : '_global';
    this.filterValues[column] = search;

    var update = {
        search: search
    };

    if (this.ngReactGrid.isLocalMode()) {
        this.filteredData = this.originalData.slice(0);
        for (var column in this.filterValues) {
            if (this.filterValues.hasOwnProperty(column)) {
                this.filteredData = this.filteredData.filter(function (obj) {
                    var found = false;
                    found = this.deepSearch(obj, this.filterValues[column], column);
                    return found;
                }.bind(this));
            }
        }

        update.data = this.filteredData;
        update.currentPage = 1;

        this.ngReactGrid.update(this.ngReactGrid.events.SEARCH, update);
    } else {
        this.ngReactGrid.search = search;
        this.ngReactGrid.getData();
    }
};

/**
 * Pagination call back, called every time a pagination change is made
 * @param page
 */
NgReactGridReactManager.prototype.goToPage = function (page) {

    var update = {
        currentPage: page
    };

    this.ngReactGrid.update(this.ngReactGrid.events.PAGINATION, update);

    if (this.ngReactGrid.isServerMode()) {
        this.ngReactGrid.getData();
    }
};

/**
 * Row click callback
 * @param row
 */
NgReactGridReactManager.prototype.rowClick = function(row) {
    this.ngReactGrid.rowClick(row);
};

/**
 * This function is called from React to make sure that any callbacks being passed into react cell components, update the
 * angular scope
 * @param cell
 * @returns {*}
 */
NgReactGridReactManager.prototype.wrapFunctionsInAngular = function (cell) {
    for (var key in cell.props) {
        if (cell.props.hasOwnProperty(key)) {
            if (key === "children" && cell.props[key]) {
                this.wrapFunctionsInAngular(cell.props[key]);
            } else if (typeof cell.props[key] === 'function') {
                cell.props[key] = this.wrapWithRootScope(cell.props[key]);
            }
        }

    }
    return cell;
};

/**
 * This is the wrapping function on all callbacks passed into the React cell components for ngReactGrid
 * @param func
 * @returns {Function}
 */
NgReactGridReactManager.prototype.wrapWithRootScope = function (func) {
    var self = this;
    return function () {
        var args = arguments;
        var phase = self.ngReactGrid.rootScope.$$phase;

        if (phase == '$apply' || phase == '$digest') {
            func.apply(null, args);
        } else {
            self.ngReactGrid.rootScope.$apply(function () {
                func.apply(null, args);
            });
        }
    };
};

/**
 * This function allows you to get a property from any object, no matter how many levels deep it is
 * MOVE THIS FUNCTION INTO ITS OWN CLASS
 * @param object
 * @param str
 * @static
 * @returns {*}
 */
NgReactGridReactManager.getObjectPropertyByString = function (object, str) {

    /**
     * Convert indexes to properties
     */
    str = str.replace(/\[(\w+)\]/g, '.$1');

    /**
     * Strip a leading dot
     */
    str = str.replace(/^\./, '');
    var a = str.split('.');
    while (a.length) {
        var n = a.shift();
        if (object != null && n in object) {
            object = object[n];
        } else {
            return;
        }
    }
    return object;
};

/**
 * Updates an object property given a specified path, it will create the object if it doesn't exist
 * @static
 * @param obj
 * @param path
 * @param value
 */
NgReactGridReactManager.updateObjectPropertyByString = function(obj, path, value) {
    var a = path.split('.');
    var o = obj;
    for (var i = 0; i < a.length - 1; i++) {
        var n = a[i];
        if (n in o) {
            o = o[n];
        } else {
            o[n] = {};
            o = o[n];
        }
    }
    o[a[a.length - 1]] = value;
};

module.exports = NgReactGridReactManager;


text:
Sovereign Debt: A Modern Greek Tragedy - Audience Q&A, Part 2
Christopher Waller of the St. Louis Fed is joined by economists Fernando Martin and Christopher Neely to take questions from the audience. In this second part of the Q&A, participants asked about the situation in Spain, why Canada avoided the crises that hit the U.S. and Europe, and at what level of debt the U.S. could experience a sovereign debt crisis of its own.
Part 1: Welcoming Remarks, Julie Stackhouse (5:44)
Part 2: The Ability vs. the Willingness To Repay Debt (14:45)
Part 3: Why Is Europe Having a Sovereign Debt Crisis Now? (8:19)
Part 4: Waking Up to the Great Shocks (6:20)
Part 5: Insuring Against Default and Higher Rollover Risk (4:54)
Part 6: Austerity Measures and the Real Default Threats (8:55)
Part 7: The Moral of the Tragedy (8:29)
Part 8: Q&A Part 1 (14:25)
Q: Can you talk about the Spanish problem? I understand they have the highest unemployment rate in the EU for people under 24, they've got a collapsing banking system, they've got problems in the property market. So what do you see as their long-term future, and do they have willingness?
Christopher Waller: I should have some of my Spanish staff members answer that question. They're sitting in the back somewhere.
Q: It's such a big part of the EU. It's one of the bigger economies, so I think what happens there is very important.
Christopher Waller: You want to take a whack at this one?
Fernando Martin: I can take a shot. You're absolutely right. I mean, both Spain and Portugal share this similar feature which is unemployment has been going up quite a lot. I mean, Portugal for a longer time, Spain more recently. Now, as to the willingness to fix those problems, that's a question for the politicians there and for the public that elects them. But all these countries share the same feature which is, you know, besides their more structural problem, expenditure has been going up since 2007 and only now has been coming down. And that's what's generating the political conflict which is on top of the labor market problem. So now you have a battle being fought on many fronts, and the point is that that's a political conflict. So as economists we can only say so much.
Christopher Waller: Yeah, just an observation—Carlos, you're in the back there somewhere. But Spanish unemployment was at 20 percent for a long time—decades. And then it came way down. Now it's back up to 25. So I've heard the argument that the temporary drop in Spanish unemployment was an outlier.
Q: Was that through the property market inflation that they had?
Christopher Waller: Spain had a huge property bubble. And maybe a large part of their employment gains was all in construction which is now effectively gone.
Q: To what extent has the American investment banking industry contributed to the sovereign debt crisis?
Christopher Waller: Boy, it's fun to let those guys have it, isn't it?
Christopher Neely: I can't image that we can—I mean, I'd like to blame Goldman-Sachs as much as anybody, but I can't imagine we can blame—I mean, there was the deal with Greece where they capitalized part of Greece's future income in, what, 2000 or 2001...
Christopher Waller: It was to help them with these...
Christopher Neely: ...but, you know, we're talking about a tiny, tiny deal.
Christopher Waller: Yeah.
Q: How did Canada avoid the financial crisis that's infected the U.S. and Europe? And are there any lessons that can be learned from their performance?
Christopher Waller: That's a great question for my Canadian colleague over here.
[Laughter and over-talking]
Fernando Martin: So, I mean, what you say is correct. Canada has not been having any financial crisis, and the reason is they're less dynamic. Their banking sector is basically eight big banks and then lots of very small banks, and these banks are very conservative. They work very closely with the Bank of Canada. They don't do crazy stuff, let's put it that way. Which is good when a crisis hits because you're not exposed to new problems. But on the other hand, it means that you don't get to explore self-progress. Right? I mean, they don't even do as much as American banks. So you don't get the good stuff but you also don't get the bad stuff. It all depends on what you prefer. Do you prefer something like this? Or do you prefer something like that? And like I said before, I mean, countries solve these problems in different ways.
Q: One of the propositions you talked about early on was that wars many times drive the debt that countries incur. A couple of questions. One, it's safe to say that the cost of fighting a war is not what's behind the European crisis. And then projecting that out, at what point will the U.S. funding multiple wars get to a point where it in fact is having a negative impact on Europe?
Christopher Neely: Where the U.S. is having a negative impact on Europe?
Q: Well, when our debt limit gets to a point and continues to grow by the funding that we have to do to support the various wars, where at some point is that projection that we can't take care of ourselves but we're having a bigger impact on Europe than it's having on itself?
Christopher Neely: Well, I think currently the U.S. spending on forces in Afghanistan might be a little bit over 1 percent of GDP, which is not trivial. I mean, it's not a very small amount but it's certainly not what's driving the U.S. debt situation in the long run. What's driving the U.S. debt situation in the long run is almost entirely Medicare. And I'm a lot more worried about the effect of U.S. debt on the U.S. than I am about what it's going to do to people in Portugal or Greece or Denmark.
Christopher Waller: And in the back?
Q: One of the very first slides that you had today showed the current crisis is due to federal deficit. And the crisis is in part probably due to the crisis that you had listed immediately prior to that which is households unable to pay their mortgages. What do you see as the cause for that to happen since most of the mortgage and the debt rates for individual households have always been fairly high, maybe a little bit higher than normal, but nothing to have us fall off the cliff? What was it that caused that?
Christopher Waller: Well, I would say the following. We did see a pretty substantial increase in leverage of households in the form of the amount of equity they had in their house. So the less equity you have in your house, the smaller the price drop has to be to wipe you out. So that's just the first thing of—And we did see a pretty dramatic—I don't know the numbers off the top of my head. My colleague Bill Emmons here at the bank knows much more about this than I do. But the key thing in the U.S. was nobody ever believed that housing prices could fall. It was just a misbelief that prices for the nation as a whole could not go down. So if you build all your expectations, your financing, your borrowing around that and then it happens, you're in trouble.
Q: Do you believe that commodity price increases immediately preceding that—oil going to close to $150 a barrel, food prices increasing, so on and so forth—do you think that was one of the factors that may have led to it as well?
Christopher Neely: I think that that was a trigger. I think that that well could have been a trigger but not a fundamental cause.
Julie Stackhouse: Yeah, if I might jump in? The first session we did last fall—which, again, I'll put a little plug on the St. Louis Fed website—actually went through the factors leading up to the financial crisis, the issues in the mortgage market, the leverage in the market, the spur in housing prices, then, of course, all the construction and land development that followed the housing boom, and then ultimately the collapse. And many more factors than that have contributed as well. So I might just direct you to that. It will give you a good primer on the original financial crisis that we all went through a few years ago.
Q: We talked about how economies can get out of debt, basically raising taxes, cut spending, et cetera. Spain obviously is a worrisome country. Recently, I would say a couple of weeks ago, I was hearing on NPR news about this person getting interviewed, and it seems like in Spain they have a mastery for tax evasion. And the person was talking about, well, I work part time, and the other part time I get paid under the table. So it's a big issue to deal with. And what do you see were some of the measures I guess than can be taken to remedy this?
Christopher Neely: I think this is a question for the Argentinian.
Christopher Waller: He probably knows more about it than us.
Fernando Martin: I mean, we were discussing this before. Right? So the point is that these are deep structure problems that have been going on for a long time. They are not particular to this crisis. There are issues that are more longer term. I mean, the U.S. also has an informal sector. Many countries have it. What this tells you is, suppose, I mean, the connection to this particular crisis I would say would be now people realize how burdensome these informal sectors are. Because basically all government expenditure is financing everyone. Right? If you have public works, public education, et cetera, everyone benefits. But only the people in the formal sector pay taxes. So the point is that you can understand how this may revolt against people not paying taxes. So I would say that we've increased the political conflict because these guys in the formal sector are still voting. Right? They don't want to be sucked into the formal sector and have to pay the tab.
Q: Right now we have 43 percent of our budget is made up of Medicare, Social Security and Medicaid. We have two political parties in this country that seem at odds and not wanting to do anything about this problem. How long can we go theoretically before we have a huge problem here? How high can that number go up before something triggers a collapse?
Christopher Waller: Well, I'll just take a minute and plug our second Dialogue with the Fed series last fall which was Bill Emmons gave a very nice presentation on fiscal sustainability in the U.S. and addressed exactly a lot of these questions. I'm assuming that's also available on our website, so you may want to take a look at that. I mean, again, this question about sustainability. If your debt-to-GDP ratio is projected to go to a million percent, that's not going to work. But we've seen Japan go to 200 percent without some problems. Other countries get to 110, 120 and then these things go. That's the danger in this. We don't know what the magic number is that this thing finally triggers. But clearly if you go to the Congressional Budget Office and look at projections, these numbers can't be true. Something will have to happen. Either there will be cuts, there will be taxes, or the debt suddenly will be looking like Italy and Greece at some point. So the current policies are unsustainable in any way, shape or form out so many years. So something is going to have to be done.
Julie Stackhouse: I'm going to jump in here, Chris, if I might?
Christopher Waller: Okay.
Julie Stackhouse: Because we are at the end of our time, I'd like to invite those that still have questions, if at the end you want to come up and catch these guys quickly, I'm sure that they would be happy to do that. We have gotten into some issues here that are very, very important, and I would like to echo the session on the fiscal deficit. It looked at the Congressional Budget Office projections, and it was telling to see how these lines begin to grow. And while you can't say it's going to be this particular year that the U.S. will have a problem, you can say the U.S. will have a problem if there isn't some action that's taken. And importantly I think, as you've heard Federal Reserve Chairman Bernanke speak—usually the Federal Reserve is very non-political on these matters—he's made it very clear that the federal budget deficit will affect the U.S. economy eventually, and it must be addressed either through an increase in taxes, increase in revenues, a cost in spending or some combination, but it will affect the U.S. economy if it's left unaddressed. So a very important lesson and I think one for all of us to think about as we look at what might lie ahead.
I'd like to take just a moment I guess to summarize some of the things that I've heard you guys say tonight to be sure that I got it right. We did talk a lot about how did Greece get there, the fact that it was a country with leverage. And countries in Europe, countries in the U.S. all had a spike in leverage as we worked through issues associated with the financial crisis. You know, a very interesting saga of how that financial crisis may have started in the United States with our housing market, but we exported the cost of that crisis to other countries around the world as well. And so it was truly something that affected more than just us. Greece, a very small economy, has been helped. There's been a lot of financial support for Greece. There was a deal reached on how Greece would manage its budget going forward in the austerity measures. That led to a default on the part of the Greek debt. It looked like Greece was under control in terms of the ability to manage its budget. And now, more uncertainty. And I think one of the things that's interesting, if I understand it correctly, that Greece is scheduled to cut $15 billion from its budget in June of this year. And if it does not, as I understand it, then that will factor in to whether it receives additional fiscal assistance from other European Union members, which would be scheduled to occur sometimes towards the end of the summer. So very interesting. We'll see this saga unfold over the summer and see how markets think or believe Greece will respond.
So why do we care? Greece is a small economy, as Chris said. But, of course, Greece is an economy for which we will begin to see whether or not countries can operate with austerity measures, can work towards alleviating debt. And, of course, the question is, if Greece can't do it and shows that it can't, much less the chaos that could occur if there is an exit from the European Union, is the question of can Spain, can Italy manage its debt with austerity measures? So there are all the uncertainties that surround us. And, of course, in the United States we're connected with Europe in many different ways. To some degree, our financial institutions, our corporations have investments in those countries, hold debt of those countries, do business in those countries, so it's certainly not something where we can isolate ourselves from that crisis and have to be mindful that in the case of a very, very severe event, that certainly there would be some repercussions to the U.S.
Beyond that, though, is this matter of saying, what are the lessons learned in Greece? And is it a tragedy that we in the United States can first foresee it could happen and second are willing to address in our own country before it becomes a tragedy here? So I think I've got the main points. Does that sound about right?
Christopher Waller: Yep.
Julie Stackhouse: I'd like to do a couple of quick poll questions before we go tonight. So if you're ready, grab your clickers one more time. All right. Next fall we'll be offering more "Dialogue with the Fed" series. I'd love today to announce to you what they are. But as much as Europe was a session that made sense now, for a number of reasons in the fall I'm not sure what's going to make sense. So we will just say there will be something. And the question is: Do you plan to attend? Or is it a program that you'd like to attend in the fall? So we'd like your thoughts on that. Please go ahead and tell us what you think. Okay, great, thank you, 86 percent. That gives us a lot of motivation to bring this back to you. In fact, it kind of makes us do it, doesn't it? We've given you that choice.
Okay, now, this one you get to choose topics. And I'm not sure if it's going to let you choose more than one. You can try. But for sure choose the topic that you think is something that's most intriguing to you so we have a sense of what would be most valuable. Okay, it looks like we're probably close enough. That's an interesting mix. It's kind of nice to see housing go down. You know, for some of us, we've talked about housing for so many years, it's like, ah, we've had enough of housing, let's talk about something else. So great, thanks for that. Dodd-Frank, that's interesting. And that actually is a topic we talk a lot with about bankers—or bankers talk a lot with about us. But you're seeing it more in the news, so that, in fact, may be a timely topic to bring back and talk about, what does it mean for me and for my business and for some of the costs that are out there?
So with that, I'd like to thank you all for being here tonight. It's been great having you. Please come back.
Subscribe to Dialogue with the Fed
This popular lecture series addresses key issues and provides the opportunity to ask questions of Fed experts. Views expressed are not necessarily those of the St. Louis Fed or Federal Reserve System.
Ellen Amato | 314‑202‑9909


text:
Q: Cannot create a new model via MassAssignment, causes QueryException Duplicate Entry I'm learning Laravel and when I tried inserting a user via artisan tinker with code below
$user = App\User::create([
    'username'=>'johnd',
    'first_name'=>'john',
    'last_name'=>'doe',
    'email'=>'john@doe.com',
    'password'=>'thisShouldBeRandom',
    'shool_id'=>1,'type'=>'TEACHER'
]);

It throws this error:
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'username' (SQL: insert into `users` (`first_name`, `last_name`, `type`, `updated_at`, `created_at`) values (john, doe, TEACHER, 2015-12-22 07:12:49, 2015-12-22 07:12:49))'

My model is:
namespace App;

use App\School;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use League\Flysystem\Exception;
use URL;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['school_id', 'type'];

    /**
     * The attributes that are NOT mass assignable.
     *
     * @var array
     */
    protected $guarded = ['email', 'password', 'username'];
}

Also I noticed in the error it's only trying to insert the following columns into first_name, last_name, type, updated_at, created_at when I also included username in the array. Anything I'm missing?
EDIT
Looks like I have to add in username, email and the rest of the fields in the fillable property, however I'm thinking this might make it unsecure as it's fillable from a request. I think this is more appropriate with public data such as articles, posts, comments, etc. I'm thinking I'll go with a different approach for sensitive data, I could be wrong though. Again thanks for all the help!
P.S. When testing with artisan tinker make sure you close the instance and launch anew when you modify the code because it keeps the old compiled instance and doesn't see you changes. Took me a while to realise and caused a lot of headache.

A: You need to remove 'username' from $guarded and put it in $fillable.
With 'username' in $guarded you are preventing the field to be set. So the database tries to create/update the field 'username' with empy default value, and it happens that you already have a row with empty username (because of the same error).
Actually, remove all column names you need to specify from $guarded and put them in $fillable, because I think you'll want to have 'email' and 'password' created/updated.


Hybrid simulations of molecular systems combining all-atom (AA) with coarse grain (CG) representations are a valuable alternative to get atomistic details on relevant regions, while treating a bigger part of the system at the CG level.
We developed a reduced set of parameters, which allows to easily link the AMBER force field of DNA with the CG representation developed by our group.
No modification is needed for any of the existing residues (neither AA, nor CG). Only a reduced set of bonding interactions at the AA/CG interface is enough to produce a smooth transition of electrostatic, mechanic and dynamic features in different AA/CG systems using Generalized Born model for implicit solvent.
All the interactions are computed within the same classical Hamiltonian. Therefore, it is straightforwardly usable in any popular simulation packages.
This opens the possibility to an immediate extension multiscale quantum/ classical/CG simulation schemes.


text:
Q: Convert NAD_1983_Mississippi_TM to Decimal Degrees in Excel Spreadsheet I have an excel file with coordinates in NAD_1983_Mississippi_TM that I need to have converted into Lat-Long decimal degrees.
I need a new or updated spreadsheet with NAD_1983_Mississippi_TM coordinates converted to decimal degrees.
Is there a way I can do this in ArcGIS Desktop 10.7.1 or in Excel without having to go back to each point one-by-one?


text:
La provincia dello Schleswig-Holstein (in tedesco: Provinz Schleswig-Holstein) fu una provincia del Regno di Prussia e dello Stato libero di Prussia dal 1868 al 1946.

Storia
Fu creata a partire dai ducati di Schleswig e Holstein, che erano stati conquistati dalla Prussia e dall'Impero austriaco strappandoli alla Danimarca nella guerra dello Schleswig del 1864. Dopo la guerra austro-prussiana del 1866, che finì con la sconfitta austriaca, Schleswig e Holstein furono annessi dalla Prussia. La provincia fu creata nel 1868 e includeva anche il Ducato di Lauenburg.

Dopo la sconfitta dell'Impero tedesco nella prima guerra mondiale, gli Alleati organizzarono due plebisciti nello Schleswig settentrionale e centrale il 10 febbraio e il 14 marzo 1920 per decidere o meno su un'eventuale unione con la Danimarca. Nello Schleswig settentrionale il 75% votò per la riunificazione con la Danimarca, mentre lo Schleswig centrale votò all'80% per restare con la Germania. Nella parte meridionale della regione non si tenne alcuna votazione.

Il 15 giugno 1920 lo Schleswig settentrionale fu ufficialmente riunito alla Danimarca, divenendo la Contea dello Jutland meridionale. La parte rimanente dello Schleswig-Holstein rimase provincia dello Stato libero di Prussia.

Con la legge della Grande Amburgo del 1937, la Città libera di Lubecca fu incorporata nella provincia, mentre le città di Altona e Wandsbek divennero distretti di Amburgo.

Dopo la seconda guerra mondiale, lo Schleswig-Holstein divenne parte della zona di occupazione britannica, anche se una piccola parte ad est di Ratzeburg fu riassegnata al Meclemburgo nella zona di occupazione sovietica.

Nel 1946, per decreto dell'occupante britannico, la provincia dello Schleswig-Holstein fu disciolta e il suo territorio, distaccato dalla Prussia, formò il nuovo Land dello Schleswig-Holstein.

Note

Voci correlate
Schleswig-Holstein
Pace di Praga (1866)

Collegamenti esterni

Province della Prussia
Schleswig-Holstein

redpajama_set_name: RedPajamaWikipedia