text:
class Product < ActiveRecord::Base
  belongs_to :category

  has_attached_file :photo, :styles => { :small => "150x150>" },
                    :url  => "/assets/products/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/assets/products/:id/:style/:basename.:extension"

  validates_attachment_presence :photo
  validates_attachment_size :photo, :less_than => 5.megabytes
  validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']
end


text:
title:  Jwenn Repo Nan Fanmi An
date:  31/07/2021
---

### Lekti pou etid semenn sa a
Jenèz 34 ; Ebre 11.17-22 ; Detewonòm 4.29 ; 1 Jan 3.1, 2 ; Jenèz 39 ; Efezyen 6.1-13.

>
Pasaj pou n memorize a

> "Se poutèt sa, frè mwen renmen anpil yo, koulye a nou tou avèti. Pran prekosyon nou pou nou pa kite mechan sa yo trennen nou ale ak manti yo, pou nou pa pèdi pozisyon kote nou kanpe fèm lan. Okontrè, se pou nou grandi nan favè ak konesans Jezikri, Seyè nou ak Sovè nou. Se pou li tout lwanj la, koulye a ak pou tout tan. Amèn" (2 Pyè 3.17, 18, HCV).

Sa fè plizyè jou yon jenn gason sa te kanpe l ap fikse yon sèl kote, finalman l resi wè frè l yo l t ap chache depi kèk jou. Li pwoche yo epi l fè yo yon siy ak men l, li konstate figi yo pati. Yo akeyi l tankou yon enkoni. Frè l sa yo te gen lide pou touye l. Si se pa t Ribenn, petèt li te kapab pa vivan ankò. Ribenn rive konvenk lòt frè l yo pou yo sèlman bay Jozèf kèk pataswèl epi lage l nan yon pui ki pa gen dlo.

Sa se ekzanp yon fanmi tèt anba !

Nou gen posiblite pou n chwazi anpil bagay nan lavi, men, nou pa chwazi fanmi n. Pa gen moun ki pafè, e okenn nan nou pa gen relasyon ki pafè ak fanmi l. Kèk nan nou gen privilèj pou n gen manman ak papa, frè ak sè, ak lòt manm fanmi ki aksepte lanmou Bondye. Men, se pa sa l ye pou anpil moun. Relasyon nan fanmi yo souvan konplike epi konn bay dlo nan je, yon bagay ki fè lapenn e ki mande reflechi. Se konsa, nou gen yon ray anndan n, epi n al pase l sou lòt moun.

Kijan n kapab jwenn vrè repo a nan Bondye nan domèn sa a nan lavi n ? Semèn sa a, n ap etidye istwa Jozèf, yon fason pou n wè Bondye k ap aji, ki pote gerizon ak repo pou nanm nou, malgre relasyon tèt anba nan fanmi yo.

_*Etidye leson semèn sa a pou saba 7 dawou._

redpajama_set_name: RedPajamaGithub


text:
module Mixlib
  class Install
    class Util
      class << self
        # @return [String] a pretty/helpful representation of a Chef Omnibus
        #   package version
        # @api private
        def pretty_version(version)
          case version
          when "true" then "install only if missing"
          when "latest" then "always install latest version"
          else version
          end
        end

        # Builds a complete command given a variables String preamble and a file
        # containing shell code.
        #
        # @param vars [String] shell variables, as a String
        # @param file [String] file basename (without extension) containing
        #   shell code
        # @param powershell [Boolean] for powershell
        # @return [String] command
        # @api private
        def shell_code_from_file(vars, file, powershell, opts = {})
          src_file = file + (powershell ? ".ps1" : ".sh")

          Util.wrap_shell([vars, "", IO.read(src_file)].join("\n"),
                          powershell, opts)
        end

        # Wraps a body of shell code with common context appropriate for the type
        # of shell.
        #
        # @param code [String] the shell code to be wrapped
        # @param opts [Hash] options
        # @param opts[:http_proxy] [String] http proxy url
        # @param opts[:https_proxy] [String] https proxy url
        # @return [String] wrapped shell code
        # @api private
        def wrap_shell(code, powershell = false, opts = {})
          env = []
          if opts[:http_proxy]
            env << Util.shell_env_var("http_proxy", opts[:http_proxy], powershell)
            env << Util.shell_env_var("HTTP_PROXY", opts[:http_proxy], powershell)
          end
          if opts[:https_proxy]
            env << Util.shell_env_var("https_proxy", opts[:https_proxy], powershell)
            env << Util.shell_env_var("HTTPS_PROXY", opts[:https_proxy], powershell)
          end
          unless env.empty?
            code = env.join("\n").concat("\n").concat(code)
          end
          if powershell
            "\n" + code
          else
            Util.wrap_command(code)
          end
        end

        # Builds a shell environment variable assignment string for the
        # required shell type.
        #
        # @param name [String] variable name
        # @param value [String] variable value
        # @return [String] shell variable assignment
        # @api private
        def shell_env_var(name, value, powershell = false)
          if powershell
            shell_var("env:#{name}", value, true)
          else
            "#{shell_var(name, value)}; export #{name}"
          end
        end

        # Builds a shell variable assignment string for the required shell type.
        #
        # @param name [String] variable name
        # @param value [String] variable value
        # @param powershell [Boolean] for powershell
        # @return [String] shell variable assignment
        def shell_var(name, value, powershell = false)
          if powershell
            %{$#{name} = "#{value}"}
          else
            %{#{name}="#{value}"}
          end
        end

        # Generates a command (or series of commands) wrapped so that it can be
        # invoked on a remote instance or locally.
        #
        # This method uses the Bourne shell (/bin/sh) to maximize the chance of
        # cross platform portability on Unix-like systems.
        #
        # @param [String] the command
        # @return [String] a wrapped command string
        def wrap_command(cmd)
          cmd = "false" if cmd.nil?
          cmd = "true" if cmd.to_s.empty?
          cmd = cmd.sub(/\n\Z/, "") if cmd =~ /\n\Z/

          "sh -c '\n#{cmd}\n'"
        end

        # Build the user-agent string
        #
        # @param name [Array] headers
        # @return [String] generated user-agent string
        def user_agent_string(headers)
          require_relative "version"
          user_agents = %W{mixlib-install/#{Mixlib::Install::VERSION}}
          user_agents << headers
          # Ensure that if the default user agent is already set it doesn't get duplicated
          user_agents.flatten.compact.uniq.join(" ")
        end

        def map_windows_version(version)
          # This logic does not try to compare and determine proper versions based on conditions or ranges.
          # These are here to improve UX for desktop versions.
          case version
          when /^10/
            "2016"
          when /^6.3/, /^8.1/, /2016nano/
            "2012r2"
          when /^6.2/, /^8/
            "2012"
          when /^6.1/, /^7/
            "2008r2"
          when /^6/
            "2008"
          else
            version
          end
        end

        #
        # Normalizes architecture information
        #
        # @param [String] architecture
        #
        # @return String [architecture]
        def normalize_architecture(architecture)
          case architecture
          when "amd64"
            "x86_64"
          when "arm64"
            "aarch64"
          when "i86pc", "i686"
            "i386"
          when "sun4u", "sun4v"
            "sparc"
          else
            architecture
          end
        end
      end
    end
  end
end


text:
<template name="accessDenied">

You can't get here! Please log in.

</template>


text:
Enabling drivers and hardware types
===================================

Introduction
------------

The Bare Metal service delegates actual hardware management to **drivers**.
*Drivers*, also called *hardware types*, consist of *hardware interfaces*:
sets of functionality dealing with some aspect of bare metal provisioning
in a vendor-specific way. There are generic **hardware types** (eg.
``redfish`` and ``ipmi``), and vendor-specific ones (eg. ``ilo`` and
``irmc``).

.. note::
   Starting with the Rocky release, the terminologies *driver*,
   *dynamic driver*, and *hardware type* have the same meaning
   in the scope of Bare Metal service.

.. _enable-hardware-types:

Enabling hardware types
-----------------------

Hardware types are enabled in the configuration file of the
**ironic-conductor** service by setting the ``enabled_hardware_types``
configuration option, for example:

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = ipmi,redfish

Due to the driver's dynamic nature, they also require configuring enabled
hardware interfaces.

.. note::
   All available hardware types and interfaces are listed in setup.cfg_ file
   in the source code tree.

.. _enable-hardware-interfaces:

Enabling hardware interfaces
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are several types of hardware interfaces:

bios
    manages configuration of the BIOS settings of a bare metal node.
    This interface is vendor-specific and can be enabled via the
    ``enabled_bios_interfaces`` option:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = <hardware_type_name>
        enabled_bios_interfaces = <bios_interface_name>

    See :doc:`/admin/bios` for details.
boot
    manages booting of both the deploy ramdisk and the user instances on the
    bare metal node. See :doc:`/admin/interfaces/boot` for details.

    Boot interface implementations are often vendor specific,
    and can be enabled via the ``enabled_boot_interfaces`` option:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,ilo
        enabled_boot_interfaces = pxe,ilo-virtual-media

    Boot interfaces with ``pxe`` in their name require :doc:`configure-pxe`.
    There are also a few hardware-specific boot interfaces - see
    :doc:`/admin/drivers` for their required configuration.
console
    manages access to the serial console of a bare metal node.
    See :doc:`/admin/console` for details.
deploy
    defines how the image gets transferred to the target disk. See
    :doc:`/admin/interfaces/deploy` for an explanation of the difference
    between supported deploy interfaces.

    The deploy interfaces can be enabled as follows:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,redfish
        enabled_deploy_interfaces = direct,ramdisk

    .. note::
      The ``direct`` deploy interface requires the Object Storage service
      or an HTTP service
inspect
    implements fetching hardware information from nodes. Can be implemented
    out-of-band (via contacting the node's BMC) or in-band (via booting
    a ramdisk on a node). The latter implementation is called ``inspector``
    and uses a separate service called
    :ironic-inspector-doc:`ironic-inspector <>`. Example:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,ilo,irmc
        enabled_inspect_interfaces = ilo,irmc,inspector

    See :doc:`/admin/inspection` for more details.
management
    provides additional hardware management actions, like getting or setting
    boot devices. This interface is usually vendor-specific, and its name
    often matches the name of the hardware type (with ``ipmitool`` being
    a notable exception). For example:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,redfish,ilo,irmc
        enabled_management_interfaces = ipmitool,redfish,ilo,irmc

    Using ``ipmitool`` requires :doc:`configure-ipmi`. See
    :doc:`/admin/drivers` for the required configuration of each driver.
network
    connects/disconnects bare metal nodes to/from virtual networks.
    See :doc:`configure-tenant-networks` for more details.
power
    runs power actions on nodes. Similar to the management interface, it is
    usually vendor-specific, and its name often matches the name of the
    hardware type (with ``ipmitool`` being again an exception). For example:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,redfish,ilo,irmc
        enabled_power_interfaces = ipmitool,redfish,ilo,irmc

    Using ``ipmitool`` requires :doc:`configure-ipmi`. See
    :doc:`/admin/drivers` for the required configuration of each driver.
raid
    manages building and tearing down RAID on nodes. Similar to inspection,
    it can be implemented either out-of-band or in-band (via ``agent``
    implementation). See :doc:`/admin/raid` for details. For example:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,redfish,ilo,irmc
        enabled_raid_interfaces = agent,no-raid
storage
    manages the interaction with a remote storage subsystem, such as the
    Block Storage service, and helps facilitate booting from a remote
    volume. This interface ensures that volume target and connector
    information is updated during the lifetime of a deployed instance.
    See :doc:`/admin/boot-from-volume` for more details.

    This interface defaults to a ``noop`` driver as it is considered
    an "opt-in" interface which requires additional configuration
    by the operator to be usable.

    For example:

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,irmc
        enabled_storage_interfaces = cinder,noop

vendor
    is a place for vendor extensions to be exposed in API. See
    :doc:`/contributor/vendor-passthru` for details.

    .. code-block:: ini

        [DEFAULT]
        enabled_hardware_types = ipmi,redfish,ilo,irmc
        enabled_vendor_interfaces = ipmitool,no-vendor

Here is a complete configuration example, enabling two generic protocols,
IPMI and Redfish, with a few additional features:

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = ipmi,redfish
    enabled_boot_interfaces = pxe
    enabled_console_interfaces = ipmitool-socat,no-console
    enabled_deploy_interfaces = direct
    enabled_inspect_interfaces = inspector
    enabled_management_interfaces = ipmitool,redfish
    enabled_network_interfaces = flat,neutron
    enabled_power_interfaces = ipmitool,redfish
    enabled_raid_interfaces = agent
    enabled_storage_interfaces = cinder,noop
    enabled_vendor_interfaces = ipmitool,no-vendor

Note that some interfaces have implementations named ``no-<TYPE>`` where
``<TYPE>`` is the interface type. These implementations do nothing and return
errors when used from API.

Hardware interfaces in multi-conductor environments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When enabling hardware types and their interfaces, make sure that for
every enabled hardware type, the whole set of enabled interfaces matches for
all conductors. However, different conductors can have different hardware
types enabled.

For example, you can have two conductors with the following configuration
respectively:

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = ipmi
    enabled_deploy_interfaces = direct
    enabled_power_interfaces = ipmitool
    enabled_management_interfaces = ipmitool

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = redfish
    enabled_deploy_interfaces = ansible
    enabled_power_interfaces = redfish
    enabled_management_interfaces = redfish

But you cannot have two conductors with the following configuration
respectively:

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = ipmi,redfish
    enabled_deploy_interfaces = direct
    enabled_power_interfaces = ipmitool,redfish
    enabled_management_interfaces = ipmitool,redfish

.. code-block:: ini

    [DEFAULT]
    enabled_hardware_types = redfish
    enabled_deploy_interfaces = ansible
    enabled_power_interfaces = redfish
    enabled_management_interfaces = redfish

This is because the ``redfish`` hardware type will have different enabled
*deploy* interfaces on these conductors. It would have been fine, if the second
conductor had ``enabled_deploy_interfaces = direct`` instead of ``ansible``.

This situation is not detected by the Bare Metal service, but it can cause
inconsistent behavior in the API, when node functionality will depend on
which conductor it gets assigned to.

.. note::
   We don't treat this as an error, because such *temporary* inconsistency is
   inevitable during a rolling upgrade or a configuration update.

Configuring interface defaults
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When an operator does not provide an explicit value for one of the interfaces
(when creating a node or updating its driver), the default value is calculated
as described in :ref:`hardware_interfaces_defaults`. It is also possible
to override the defaults for any interfaces by setting one of the options named
``default_<IFACE>_interface``, where ``<IFACE>`` is the interface name.
For example:

.. code-block:: ini

    [DEFAULT]
    default_deploy_interface = direct
    default_network_interface = neutron

This configuration forces the default *deploy* interface to be ``direct`` and
the default *network* interface to be ``neutron`` for all hardware types.

The defaults are calculated and set on a node when creating it or updating
its hardware type. Thus, changing these configuration options has no effect on
existing nodes.

.. warning::
   The default interface implementation must be configured the same way
   across all conductors in the cloud, except maybe for a short period of time
   during an upgrade or configuration update. Otherwise the default
   implementation will depend on which conductor handles which node, and this
   mapping is not predictable or even persistent.

.. warning::
   These options should be used with care. If a hardware type does not
   support the provided default implementation, its users will have to always
   provide an explicit value for this interface when creating a node.

.. _setup.cfg: https://opendev.org/openstack/ironic/src/branch/master/setup.cfg


text:
from math import *
import numpy as np
import scipy.interpolate as spip
from scipy.integrate import ode,odeint
import copy
import warnings

G=6.67384e-11
crash_alt=-5000 #no collision detection, so just end the simulation if >5km below ground

def unit_vector(vector):
    """ Returns the unit vector of the vector.
    Code stolen from StackOverflow:
    http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python  """
    if np.linalg.norm(vector)==0.0:
        return np.zeros(np.shape(vector))
    else:
        return vector / np.linalg.norm(vector)

def angle_between(v1, v2):
    """ Returns the angle in radians between vectors 'v1' and 'v2'::

            >>> angle_between((1, 0, 0), (0, 1, 0))
            1.5707963267948966
            >>> angle_between((1, 0, 0), (1, 0, 0))
            0.0
            >>> angle_between((1, 0, 0), (-1, 0, 0))
            3.141592653589793

    Code stolen from StackOverflow:
    http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python
    """
    v1_u = unit_vector(v1)
    v2_u = unit_vector(v2)
    angle = np.arccos(np.dot(v1_u, v2_u))
    if np.isnan(angle):
        if (v1_u == v2_u).all():
            return 0.0
        else:
            return np.pi
    return angle

class Atmosphere(object):
    """Currently "type" does nothing; eventually it'll allow switching between
    scale-height and International Standard Atmosphere"""
    def __init__(self,type, rho_SL, scale_height_constant, mean_temp):
        self.type=0
        self.rho_SL=rho_SL
        self.scaleHeight=scale_height_constant*mean_temp

    def get_rho(self,mode,altitude):
        """returns either -1 if below ground level or density at altitude if
        above. Again, mode does nothing, but will eventually allow choice
        between scale-height model and ISA."""
        if altitude<0:
            return 0
        else:
            return self.rho_SL*exp(-altitude/self.scaleHeight)

class Planet(object):
    """A spherical planet with a mass, radius, atmosphere, and rotation period.
    Note on coördinate system: +z is north."""
    def __init__(self,mass, radius, period, atmosphere):
        self.mass=mass
        self.radius=radius
        self.period=period
        self.atmosphere=atmosphere

    def altitude(self,coordinates):
        return np.linalg.norm(coordinates)-self.radius

    def get_atm_rho(self,coordinates):
        return self.atmosphere.get_rho(0,self.altitude(coordinates))

    def gravity(self,coordinates):
        return -(coordinates/np.linalg.norm(coordinates))*(G*self.mass)/(coordinates.dot(coordinates))

    def absoluteWind(self,coordinates):
        """Returns velocity vector of air as it rotates. Assume that the planet
        is rotating about the z-axis. Atmosphere is assumed to be rotating as a
        solid body at the same rate as the rest of the planet up to 1000km, and
        is then assumed to be stationary. """
        if self.altitude(coordinates)>1e6:
            return np.array([0.,0.,0.])
        else:
            r=sqrt(coordinates[0]**2+coordinates[1]**2)
            velocity = np.array([-coordinates[1],coordinates[0],0.])*((2*pi)/self.period)
            return velocity

    def fiveKeplerianElements(self,position,velocity):
        """Returns an array: eccentricity, semimajor axis, inclination,
        longitude of ascending node, argument of periapsis."""

        r=np.linalg.norm(position)
        v=np.linalg.norm(velocity)

        I=np.array([1.,0.,0.])
        K=np.array([0.,0.,1.])

        h_vec=np.cross(position,velocity)
        h_sca=np.linalg.norm(h_vec)
        mu=G*self.mass

        n=np.cross(K,h_vec)

        a=(-mu/2)*1/(v**2/2-mu/r)
        ecc_vec=(1/mu)*(v*v*position - (position.dot(velocity))*velocity)-position/r
        ecc=np.linalg.norm(ecc_vec)

        inclination=angle_between(h_vec,K)
        longAscendingNode=angle_between(n,I)
        argPeriapsis=np.arccos((n.dot(ecc_vec))/(ecc*np.linalg.norm(n)))

        return [ecc,a,inclination,longAscendingNode,argPeriapsis]

    def isBelowSurface(self,position):
        r=np.linalg.norm(position)
        if r-self.radius<crash_alt:
            return True
        else:
            return False

class Stage(object):
    """A rocket stage.
    TODO (HIGH): more realistic I_sp vs altitude
    TODO (MEDIUM): support for C_D vs AoA and Mach rather than constant C_D
    TODO (LOW): support for nonzero L/D ratios
    """
    def __init__(self,M,M_R,vac_Isp,SL_Isp,additional_C_D,additional_frontal_area,max_throttle,min_throttle,throttle_schedule,prop_margin,tvc_schedule):
        self.drymass=M/M_R;
        self.propmass=M-self.drymass
        self.residualProp=self.propmass*prop_margin
        self.vac_Isp=vac_Isp
        self.SL_Isp=SL_Isp
        self.C_D_additional=additional_C_D
        self.additionalFrontalArea=additional_frontal_area
        self.maxThrottle=max_throttle
        self.minThrottle=min_throttle

        """A weird halfway thing: integrate actual propellant flow values (as
        opposed to relative values in throttle_schedule) over unit time. This
        essentially gives us the mean throttle value."""
        meanThrottle=min_throttle

        for j in range(len(throttle_schedule[0])-1):
            meanThrottle+=(max_throttle-min_throttle)*0.5*(throttle_schedule[1][j+1]+throttle_schedule[1][j])*(throttle_schedule[0][j+1]-throttle_schedule[0][j])

        if meanThrottle>0:
            self.burnoutTime=(self.propmass*(1-prop_margin))/meanThrottle
        else:
            self.burnoutTime=3e7

        self.ignitionTime=0.0
        self.sepTime=self.burnoutTime

        self.throttleSchedule=np.copy(throttle_schedule)
        self.tvcSchedule=np.copy(tvc_schedule)

        self.throttleSchedule[0][0:len(self.throttleSchedule[0])]*=self.burnoutTime
        self.throttleSchedule[1][0:len(self.throttleSchedule[1])]*=(max_throttle-min_throttle)
        self.throttleSchedule[1][0:len(self.throttleSchedule[1])]+=min_throttle

        self.tvcSchedule[0][0:len(self.tvcSchedule[1])]*=self.burnoutTime

        self.mdotInterpolated=spip.interp1d(self.throttleSchedule[0],self.throttleSchedule[1],kind='linear')
        self.TVCsInterpolated=spip.interp1d(self.tvcSchedule[0],self.tvcSchedule[1:3,:],kind='cubic')

    def mass(self,time):
        if time>=self.burnoutTime:
            if time>=self.sepTime:
                return 0.
            else:
                return self.drymass+self.residualProp
        elif time<self.ignitionTime:
            return self.drymass+self.propmass
        else:
            lastControlPointIndex=0

            for j in range(len(self.throttleSchedule[0])-1):
                if (time>=self.throttleSchedule[0][j]) and (time<self.throttleSchedule[0][j+1]):
                    lastControlPointIndex=j

            propburned=0.0

            for j in range(lastControlPointIndex):
                propburned+=0.5*(self.throttleSchedule[1][j+1]+self.throttleSchedule[1][j])*(self.throttleSchedule[0][j+1]-self.throttleSchedule[0][j])

            propburned+=0.5*(self.mdotInterpolated(time)+self.throttleSchedule[1][lastControlPointIndex])*(time-self.throttleSchedule[0][lastControlPointIndex])

            return self.drymass+self.propmass-propburned

    def thrust(self,t,x,planet):
        """I_sp variation with altitude needs fixing."""
        if t>=self.burnoutTime or t<self.ignitionTime:
            return np.zeros(3)
        else:
            rho_SL=planet.atmosphere.rho_SL
            sl_v_e=self.SL_Isp*9.81
            vc_v_e=self.vac_Isp*9.81
            thrustMag=self.mdotInterpolated(t)*(sl_v_e+(vc_v_e-sl_v_e)*((rho_SL-planet.get_atm_rho(x))/rho_SL))

            thphi=self.TVCsInterpolated(t);
            unitThrustVector=np.array([sin(thphi[0])*cos(thphi[1]), sin(thphi[0])*sin(thphi[1]),cos(thphi[0])])

            return thrustMag*unitThrustVector

    def dragCoefficientContribution(self,t):
        if t<self.sepTime:
            return self.C_D_additional
        else:
            return 0

    def frontalAreaContribution(self,t):
        if t<self.sepTime:
            return self.additionalFrontalArea
        else:
            return 0

    def shiftTimesBy(self,preIgnitionCoastTime,postBurnoutCoastTime):
        self.ignitionTime+=preIgnitionCoastTime
        self.burnoutTime+=preIgnitionCoastTime
        self.sepTime+=preIgnitionCoastTime+postBurnoutCoastTime

        self.tvcSchedule[0][0:len(self.tvcSchedule[0])]+=preIgnitionCoastTime
        self.throttleSchedule[0][0:len(self.throttleSchedule[0])]+=preIgnitionCoastTime

        self.mdotInterpolated=spip.interp1d(self.throttleSchedule[0],self.throttleSchedule[1],kind='linear')
        self.TVCsInterpolated=spip.interp1d(self.tvcSchedule[0],self.tvcSchedule[1:3,:],kind='cubic')

class InertStage(Stage):
    """Unpropelled stages, e.g payloads and fairings"""
    def __init__(self,M,additional_C_D,additional_frontal_area,septime):
        self.drymass=M;
        self.C_D_additional=additional_C_D
        self.additionalFrontalArea=additional_frontal_area
        self.sepTime=septime
        self.ignitionTime=3e7
        self.burnoutTime=3e7

    def mass(self,t):
        if t<self.sepTime:
            return self.drymass
        else:
            return 0.0

    def thrust(self,t,x,planet):
        return 0.0

    def dragCoefficientContribution(self,t):
        if t<self.sepTime:
            return self.C_D_additional
        else:
            return 0.0

    def frontalAreaContribution(self,t):
        if t<self.sepTime:
            return self.additionalFrontalArea
        else:
            return 0.0

    def shiftTimesBy(self,preIgnitionCoastTime,postBurnoutCoastTime):
        self.sepTime+=preIgnitionCoastTime+postBurnoutCoastTime

class Rocket(object):
    """A rocket with an arbitrary number of stages, each of which has its own
    mass ratio, total mass, vacuum Isp, sea-level Isp, independent coefficient
    of drag, coefficient of drag when attached to upper stages,...
    Also, a propellant usage schedule, staging times, and a thrust vectoring
    schedule.
        """

    def __init__(self,payload):
    #TODO (HIGH): implement fairings.
    #TODO (MEDIUM): implement parallel staging & propellant cross-feed
    #TODO (LOW): make the rocket a rocket rather than a point mass, and include rotational inertia (so tvc schedule is actual tvc schedule rather than magically pointing thrust vector elsewhere).
        self.stages=[]
        self.flightlog=[]
        self.stages.append(copy.copy(payload))

    def addSerialStage(self,stageToAdd,preignitionCoastTime,postBurnoutCoastTime):
        stageCopy=copy.copy(stageToAdd)

        stageCopy.shiftTimesBy(preignitionCoastTime,postBurnoutCoastTime)

        for stage in self.stages:
            stage.shiftTimesBy(stageCopy.sepTime,0.0)

        self.stages.append(stageCopy)

    def addStage(self,stageToAdd,separationPropLevel,ignitionTime):
        """Stage is added to "bottom" of rocket - build the rocket
        from top down"""
        self.stages.append(copy.copy(stageToAdd))
        self.separationPropLevels.append(separationPropLevel)
        self.ignitionTimes.append(ignitionTime)
        print("deprecated!")

    def separateStage(self):
        self.ignitionTimes.remove(-1)
        self.separationPropLevels.remove(-1)
        print("deprecated!")
        return self.stages.pop()

    def totalMass(self):
        m=self.totalPropMass()
        for S in self.stages:
            m+=S.drymass
        return m
        print("deprecated!")

    def totalPropMass(self):
        m=0
        for S in self.stages:
            m+=S.fuelmass
        return m
        print("deprecated!")

    def dmdt(self,mdot,fuelmass,engineRunning):
        print("deprecated!")
        if fuelmass>0 and engineRunning:
            return min(self.stages[-1].maxThrottle,max(mdot,self.stages[-1].minThrottle))
        else:
            return 0

    def dvdt(self,x,v,m,thePlanet,thrust):
        """note that x,v,m may not actually be the same as those stored in self,
        because of RK4!
        returns an array of 3-arrays: a from thrust, a from gravity, a from drag
        """
        a_g=thePlanet.gravity(x)

        v_air=v-thePlanet.absoluteWind(x)

        airspeed=np.linalg.norm(v_air)
        a_d=-v_air*(1.0/m)*(0.5*thePlanet.get_atm_rho(x)*airspeed*self.stages[-1].C_D_below*self.stages[-1].frontalArea)

        a_t=thrust/m

        return [a_t, a_d, a_g]

    def v_e_atAltitude(self,x,planet):
        """This needs to be fixed later. Currently it's just about as wrong as
        it's possible for it to be."""
        rho_SL=planet.atmosphere.rho_SL
        sl_v_e=self.stages[-1].SL_Isp*9.81
        vc_v_e=self.stages[-1].vac_Isp*9.81
        return sl_v_e+(vc_v_e-sl_v_e)*((rho_SL-planet.get_atm_rho(x))/rho_SL)

    def sDot(self,t,s,planet,targetSMA):
        """s is the rocket's state vector, consisting of: x_{1,2,3},v_{1,2,3},m.
        Note that a and m are purely a function of t."""

        x=s[0:3]
        v=s[3:6]

        kepEls=planet.fiveKeplerianElements(x,v)

        sdot=np.zeros(7)

        if kepEls[1]>=targetSMA:
            sdot[6]=0
            #print(s)
            #print(str(kepEls[1])+">="+str(targetSMA))
            return sdot
        else:
            sdot[0:3]=v

            F_t=self.thrust(t,x,planet)
            a_t=F_t/self.mass(t)

            v_air=v-planet.absoluteWind(x)
            airspeed=np.linalg.norm(v_air)
            a_d=-v_air*(0.5*planet.get_atm_rho(x)*airspeed*self.dragCoefficient(t)*self.frontalArea(t))/self.mass(t)

            a_g=planet.gravity(x)

            sdot[3:6]=a_t+a_d+a_g

            sdot[6]=1

            flightstatus=np.zeros(5)
            flightstatus[0]=t
            flightstatus[1]=self.mass(t)
            flightstatus[2]=np.linalg.norm(a_t)
            flightstatus[3]=np.linalg.norm(a_d)
            flightstatus[4]=np.linalg.norm(a_g)

            self.flightlog.append(flightstatus)

            return sdot

    def thrust(self,t,x,planet):
        """Sum thrusts of all stages at t. This allows for future features like parallel staging."""
        thrust=np.zeros(3)
        for stage in self.stages:
            thrust+=stage.thrust(t,x,planet)
        return thrust

    def mass(self,t):
        mass=0.
        for stage in self.stages:
            mass+=stage.mass(t)
        return mass

    def dragCoefficient(self,t):
        drag_coefficient=0.
        for stage in self.stages:
            drag_coefficient+=stage.dragCoefficientContribution(t)
        return drag_coefficient

    def frontalArea(self,t):
        frontal_area=0.
        for stage in self.stages:
            frontal_area+=stage.frontalAreaContribution(t)
        return frontal_area

    def integrateFlight(self,initialCoords,initialVel,planet,t0,maxSimTime, stopOnSuccess, desiredSemiMajor):
        #TODO: add support for stopOnSuccess
        backend='dopri5'

        s0=np.zeros(7)
        s0[0:3]=initialCoords
        s0[3:6]=initialVel
        s0[6]=1

        #solver = odeint(self.sDot).set_integrator(backend)
        #solver.set_initial_value(s0, t0)
        #solver.set_f_params(planet,desiredSemiMajor)

        return odeint(self.sDot,s0,t0,args=(planet,desiredSemiMajor),full_output=True)

    def rk4Flight(self,initialCoords,initialVel,planet,t0,simTime,stopOnSuccess,desiredSemiMajor,h_base):

        singularitytimes=[]
        for s in self.stages:
            singularitytimes.append(s.ignitionTime)
            singularitytimes.append(s.burnoutTime)
            singularitytimes.append(s.sepTime)

        h_min=1e-12

        terminalGuidanceThreshold=200000*h_base
        singularityThreshold=3*h_base
        terminalGuidanceActive=False

        self.flightlog=[]

        s=np.zeros(7)
        s[0:3]=initialCoords
        s[3:6]=initialVel
        s[6]=1

        t=t0

        traj=[]

        keepSimulating=1

        #print(self.stages[1].burnoutTime)

        while t<simTime and keepSimulating>0 and t<self.stages[1].burnoutTime:
            #if t>454:
            #    print('---')
            distanceToNextSingularity=3e7

            for time in singularitytimes:
                if t<time and time-t<distanceToNextSingularity:
                    distanceToNextSingularity=time-t

            traj.append(np.copy(s))
            k1=self.sDot(t,s,planet,desiredSemiMajor)

            kepEls=planet.fiveKeplerianElements(s[0:3],s[3:6])

            h_cand=[]

            #if t>454:
            #    print("dist="+str(distanceToNextSingularity))
            #    print("sma error="+str(desiredSemiMajor-kepEls[1]))

            if (desiredSemiMajor-kepEls[1])<terminalGuidanceThreshold:
                h_cand.append(max(h_min, h_base*(desiredSemiMajor-kepEls[1])/terminalGuidanceThreshold))
                if not terminalGuidanceActive:
                    terminalGuidanceActive=True
                    #print("Terminal guidance active!")
            if distanceToNextSingularity<singularityThreshold:
                h_cand.append(max(h_min, h_base*distanceToNextSingularity/singularityThreshold))
                #if t>454:
                #    print("Singularity approaching! t="+str(t)+", h="+str(h))

            h_cand.append(h_base)

            h=min(h_cand)

            #if t>454:
            #    print("h="+str(h))

            k2=self.sDot(t+0.5*h,s+(0.5*h)*k1,planet,desiredSemiMajor)
            k3=self.sDot(t+0.5*h,s+(0.5*h)*k2,planet,desiredSemiMajor)
            k4=self.sDot(t+h,s+h*k3,planet,desiredSemiMajor)

            s+=h*(k1+2*k2+2*k3+k4)/6
            t+=h

            if(stopOnSuccess==True):
                keepSimulating=k4[6]

        return traj

    def simulateFlight(self,initialCoords,initialVel, planet, maxSimTime, timeStep, stopAtLastMeco, desiredSemiMajor):
        """Simulate the rocket's flight. Assumes all stages have been added and
        that the propellant and TVC schedules have been defined. Also assumes
        that initialVel is initial velocity relative to ground/atmosphere.
            stopAtLastMeco: terminate simulation at final stage MECO.
        Returns a list of arrays containing the following rows:
            time
            position (three)
            velocity (three)
            acceleration from thrust (three)
            acceleration from drag (three)
            acceleration from gravity (three)
            Q
            remaining propellant"""

        x=np.copy(initialCoords)
        v=np.copy(initialVel)
        v+=planet.absoluteWind(x)

        interpPropSchedule=spip.interp1d(self.propellantUsageSchedule[0],self.propellantUsageSchedule[1],kind='linear')
        interpTVCSchedule=spip.interp1d(self.tvcSchedule[0],self.tvcSchedule[1:3,:],kind='linear')

        t=0.0
        eventTimer=0.0
        nextEventType=0 #0 is engine ignition, 1 is ECO and stage sep

        enginesRunning=True
        stopSimulation=False

        allStates=[]
        thphi=interpTVCSchedule(t);
        unitThrustVector=np.array([sin(thphi[0])*cos(thphi[1]), sin(thphi[0])*sin(thphi[1]),cos(thphi[0])])
        thrust=self.v_e_atAltitude(initialCoords,planet)*interpPropSchedule(t)*unitThrustVector
        startAcceleration=self.dvdt(x,v,self.totalMass(),planet,thrust)

        """drawn out this way for improved execution speed. I'm sure there's a
        better way to do this..."""
        vehState=np.zeros(19)
        vehState[0]=t
        vehState[1:4]=np.copy(x)
        vehState[4:7]=np.copy(v)
        vehState[7:10]=startAcceleration[0]  #a_thrust
        vehState[10:13]=startAcceleration[1] #a_drag
        vehState[13:16]=startAcceleration[2] #a_gravity
        vehState[16]=0.0
        vehState[17]=self.totalPropMass()
        vehState[18]=self.totalMass()

        allStates.append(vehState)

        while t<maxSimTime and stopSimulation==False:
            #print("---DEBUG: X AND V---")
            #print(x)
            #print(v)

            #Engine and staging logic
            if nextEventType==0 and eventTimer>=self.ignitionTimes[-1]:
                self.ignitionTimes.pop()
                enginesRunning=True
                nextEventType=1
                eventTimer=0.0
                print("ignition, ", end="")

            if nextEventType==1 and self.stages[-1].fuelmass<=self.separationPropLevels[-1] and len(self.stages)>1:
                self.separationPropLevels.pop()
                discardedStage=self.stages.pop()
                enginesRunning=False
                nextEventType=0
                eventTimer=0.0
                print("MECO & stage sep (t="+str(t)+", alt="+str(planet.altitude(x))+") ", end="")

            if len(self.stages)==1 and self.stages[-1].fuelmass<=self.separationPropLevels[-1]:
                enginesRunning=False
                print("upper stage burnout! t="+str(t)+", alt="+str(planet.altitude(x)))
                if stopAtLastMeco:
                    stopSimulation=True

            #decide on dt
            thphi=interpTVCSchedule(t);
            unitThrustVector=np.array([sin(thphi[0])*cos(thphi[1]), sin(thphi[0])*sin(thphi[1]),cos(thphi[0])])
            thrust=self.v_e_atAltitude(initialCoords,planet)*interpPropSchedule(t)*unitThrustVector
            a_guess=self.dvdt(x,v,self.totalMass(),planet,thrust)
            a_mag_guess=np.linalg.norm(a_guess[0])+np.linalg.norm(a_guess[1])+np.linalg.norm(a_guess[2])

            dt=timeStep/a_mag_guess

            #RK4, using for-loop this time.
            km=np.zeros(4)
            kv=np.zeros([4,3])
            kx=np.zeros([4,3])

            #print("---START RK---")
            for j in range(4):
                """It's nice that Python lets you use -1 as an index. Makes this
                bit a lot cleaner."""
                substep=0.5*floor((j+1)/2)

                km[j]=self.dmdt(interpPropSchedule(t+substep*dt),self.stages[-1].fuelmass-dt*substep*km[j-1],enginesRunning)

                thphi=interpTVCSchedule(t+substep*dt);
                unitThrustVector=np.array([sin(thphi[0])*cos(thphi[1]), sin(thphi[0])*sin(thphi[1]),cos(thphi[0])])
                thrust=self.v_e_atAltitude(x,planet)*km[j]*unitThrustVector
                a=self.dvdt(x+substep*dt*kx[j-1,:], v+substep*dt*kv[j-1,:], self.totalMass()-substep*dt*km[j-1],planet,thrust)

                #print(a)

                kv[j,:]=a[0]+a[1]+a[2]

                kx[j,:]=v+substep*dt*kv[j-1]

            #print("---RK KONSTANTS---")

            #print(km)
            #print(kv)
            #print(kx)

            #print(dt)

            x+=dt*(kx[0]+2*kx[1]+2*kx[2]+kx[3])/6
            v+=dt*(kv[0]+2*kv[1]+2*kv[2]+kv[3])/6

            self.stages[-1].burnFuel(dt*(km[0]+2*km[1]+2*km[2]+km[3])/6)

            #stop if we've crashed
            if planet.isBelowSurface(x):
                stopSimulation=True
                print('crashed!')

            #stop if we have enough orbital energy
            semiMajor=planet.fiveKeplerianElements(x,v)[1]
            if semiMajor>=desiredSemiMajor and enginesRunning:
                enginesRunning=False
                print("Enough energy! t="+str(t)+", alt="+str(planet.altitude(x)))
                if stopAtLastMeco:
                    stopSimulation=True

            t+=dt
            eventTimer+=dt

            #Do appending and stuff
            vehState=np.zeros(19)
            vehState[0]=t
            vehState[1:4]=x
            vehState[4:7]=v
            vehState[7:10]=a[0]
            vehState[10:13]=a[1]
            vehState[13:16]=a[2]
            vehState[16]=0.5*(np.linalg.norm(v-planet.absoluteWind(x))**2)*planet.get_atm_rho(x)
            vehState[17]=self.totalPropMass()
            vehState[18]=self.totalMass()

            allStates.append(vehState)

        return allStates

class Simulator(object):
    def __init__(self,planet,rocket,propellantSchedule,tvcSchedule):
        self.tvcSchedule=tvcSchedule
        self.propellantSchedule=propellantSchedule
        self.rocket=rocket
        self.planet=planet

    def plfitness(self,initialCoords,initialVel,maxSimTime, timeStep, stopAtLastMeco, desiredSemiMajor,desiredEccentricity):
        flightStats=self.rocket.simulateFlight(initialCoords,initialVel, self.planet, maxSimTime, timeStep, stopAtLastMeco, desiredSemiMajor);
        arrayFlightStats=np.asarray(flightStats).T

        eccTol=0.002
        smaTol=15000

        smaWeight=0.001
        eccWeight=20
        propResidualWeight=-0.1

        kepEls=self.planet.fiveKeplerianElements(arrayFlightStats[1:4,-1],arrayFlightStats[4:7,-1])
        propResidual=arrayFlightStats[17, -1]-self.rocket.separationPropLevels[-1]

        fitness=0.;
        componentstr=""

        if abs(desiredSemiMajor-kepEls[1])>smaTol:
            fitness+=(abs(desiredSemiMajor-kepEls[1])-smaTol)*smaWeight
            componentstr+="a was "+str(kepEls[1])+", "

        if abs(kepEls[0]-desiredEccentricity)>eccTol:
            fitness+=(abs(kepEls[0]-desiredEccentricity)-eccTol)*eccWeight
            componentstr+="e was "+str(kepEls[0])
        else:
            fitness+=propResidual*propResidualWeight
            componentstr+="e good and "+str(propResidualWeight)+"kg residual."

        print("error="+str(fitness)+" ("+componentstr+")")
        return fitness;


text:
from kivy.config import Config

#Config.read("~/.kivy/config.ini")
Config.set('kivy', 'keyboard_mode', 'systemanddock')

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.graphics import BorderImage
from kivy.logger import Logger

from kivy.properties import ObjectProperty, DictProperty, NumericProperty
from piikki_utilities import  ItemHandler, Settings
from customer import CustomerHandler, Customer
from popups import *
import os
import re

#Builder.load_file('piikki.kv')

button_color = (0.26, 0.43, 0.56,1)
button_font_color = (0, 0, 0, 1)
button_font_size = 26

'''MenuScreen is the landing screen of the app'''
class MenuScreen(Screen):

    def exit_app(self):
        App.get_running_app().stop()

'''LoginScreen is used for login'''
class LoginScreen(Screen):

    def __init__(self, **kv):
        super(LoginScreen, self).__init__(**kv)
        self.main_app = kv['main_app']
        self.selected_account = None

        self.test_button = Button(text="press")

        filter_chars = "abcdefghijklmnopqrstuwxyzo"
        self.init_filter_buttons(filter_chars)

    #implements a method for kivy screen
    def on_pre_enter(self):
        self.ids.info_label.font_size=button_font_size-5
        if self.main_app.customer_handler.customers:
            for cust in self.main_app.customer_handler.customers:
                self.make_account_button(cust)

    def on_leave(self):
        self.ids.account_list.clear_widgets()
        self.reset_fields()
        self.ids.filter_input_label.text = ""

    def make_account_button(self,customer):
    	button = AccountButton(customer, text = customer.account_name)
    	button.bind(on_release=self.select_account)
    	self.ids.account_list.add_widget(button)

    def select_account(self, button):
        self.selected_account=button.account
        #self.ids.account_label.text = button.account.account_name
        #self.ids.tab_value_label.text = str(button.account.tab_value)
        #self.ids.customer_name_label.text = button.account.customer_name
        #self.ids.info_label.text = "Selected account:"
        #self.ids.info_label.font_size=button_font_size
        self.login()

    def reset_fields(self):
        self.selected_account = None
        #self.ids.account_label.text = ""
        #self.ids.tab_value_label.text = ""
        #self.ids.customer_name_label.text = ""
        self.ids.info_label.text = "Please select your account from the list"

    def login(self):
        warning_label = self.ids.warning_label

        if self.selected_account == None:
            warning_label.text = "Please select an account"
        else:
            self.main_app.current_customer = self.selected_account
            self.manager.transition.direction = "left"
            self.manager.current = "osto"

        def empty_warning():
            warning_label.text = ""
        Clock.schedule_once(lambda dt: empty_warning(), 7)

    #filter visible account based on the text on filter_input_label
    def filter_account_buttons(self):
        filter_text = self.ids.filter_input_label.text
        self.ids.account_list.clear_widgets()
    	for cust in self.main_app.customer_handler.customers:
    	    if filter_text in cust.account_name:
    		self.make_account_button(cust)

    #initializes filter buttons for names
    def init_filter_buttons(self, char_list):
    	for char in char_list:
    	    butt = Button(text=char, font_size=button_font_size,
    			    background_normal='', color= button_font_color,
                                background_color = button_color )
    	    butt.bind(on_release=self.on_filter_button_press)
    	    self.ids.filter_button_container.add_widget(butt)

    def on_filter_button_press(self, button):
    	self.ids.filter_input_label.text += button.text
    	self.filter_account_buttons()

    def on_remove_filter_text(self):
    	self.ids.filter_input_label.text = self.ids.filter_input_label.text[0:-1]
    	self.filter_account_buttons()

'''AccountScreen is used for creating a new accouont'''
class AccountScreen(Screen):

    def __init__(self, **kv):
        Screen.__init__(self, **kv)
        self.main_app = kv['main_app']
        self.acc_name_input =self.main_app.add_input(self.ids.acc_name_container)
        self.given_name_input = self.main_app.add_input(self.ids.given_name_container)
        self.family_name_input = self.main_app.add_input(self.ids.family_name_container)
        #self.password1 = self.main_app.add_input(self.ids.password1_container, True)
        #self.password2 = self.main_app.add_input(self.ids.password2_container, True)
        self.acc_name_input.bind(on_text_validate=self.on_enter_press)
        self.given_name_input.bind(on_text_validate=self.on_enter_press)
        self.family_name_input.bind(on_text_validate=self.on_enter_press)

    #function for handling enter presses when writing
    def on_enter_press(self,instance):
	self.create_account()

    #function called when new account is created. Validates text inputs and creates customer through in customer_handler
    def create_account(self):
        acc_name = self.acc_name_input.text
        given_name = self.given_name_input.text
        family_name = self.family_name_input.text
        #password1 = self.password1.text
        #password2 = self.password2.text

        warning_label = self.ids.warning_label

        if acc_name == "" or given_name == "" or family_name == "":
            warning_label.text = "Please fill in all the information"
        else:
            '''making the names have format John Doe'''
            customer_name = given_name + " " + family_name
            if len(given_name) > 1 and len(family_name) > 1:
                customer_name = given_name[0].upper() + given_name[1:].lower() + " " + family_name[0].upper() + family_name[1:].lower()

            self.main_app.customer_handler.create_new_account(acc_name, customer_name, encode=True)
            warning_label.text = "Account created"

            if self.main_app.customer_handler.account_row(customer_name) > 1:
                warning_label.text = ("account with same name exists, make sure to have different nicks")

        def empty_warning():
            warning_label.text = ""
        Clock.schedule_once(lambda dt: empty_warning(), 7)

    def clear_fields(self):
        self.acc_name_input.text = ""
        self.given_name_input.text = ""
        self.family_name_input.text = ""

'''BuyScreen displays the items in sale and handles buy transactions'''
class BuyScreen(Screen):

    def __init__(self, **kv):
        super(BuyScreen, self).__init__( **kv)
        self.main_app = kv['main_app']

        #item initialization
        self.selected_items = {}

        self.item_list = self.main_app.item_handler.get_items()
        self.show_all_items()
        self.init_filter_buttons("abcdefghijklmnopqrstuwxyz")

    def on_pre_enter(self):
        self.ids.account_label.text = self.main_app.current_customer.account_name
        self.ids.tab_value_label.text = str(self.main_app.current_customer.tab_value)
        self.ids.tab_value_label.color = self.tab_color()
        self.update_item_list()
        self.show_all_items()
        self.selected_items = {}
        self.update_selected_items_table()

    def on_leave(self):
        self.selected_items = {}

    def update_item_list(self):
        self.item_list = self.main_app.item_handler.update_item_list()

    '''Updates the customer account name and the tab value when entering the screen and when needed'''
    def update_screen(self):
        self.ids.account_label.text = self.main_app.current_customer.account_name
        self.ids.tab_value_label.text = str(self.main_app.current_customer.tab_value)
        self.ids.tab_value_label.color = self.tab_color()
        self.update_selected_items_table()

    '''Changes the current customer of the app to None, unselects the items, and swithces screens to login screen'''
    def to_login_and_logout(self):
        self.main_app.current_customer = None
        self.manager.transition.direction="right"
        self.manager.current = "login"

    #goes to the customer screen
    def go_to_customer_screen(self):
        self.manager.transition.direction = "left"
        self.manager.current = "customer"

    #shows all the items on the container 'buy_item_list' with classes and separators between classes
    def show_all_items(self):
        self.ids.product_filter_label.text = ''
        if len(self.item_list) == 0: pass
        else:
            candy_list = filter(lambda x: x.item_class == "Candy", self.item_list)
            drink_list = filter(lambda x: x.item_class == "Soft drink", self.item_list)
            food_list = filter(lambda x: x.item_class == "Food", self.item_list)
            sorted_items = candy_list + drink_list + food_list
            container = self.ids.buy_item_list
            container.clear_widgets()
            for item in candy_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)
            container.add_widget(MySeparator())
            for item in drink_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)
            container.add_widget(MySeparator())
            for item in food_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)

    def show_candy(self):
        self.ids.product_filter_label.text = ''
        if self.item_list == None: pass
        else:
            candy_list = filter(lambda x: x.item_class == "Candy", self.item_list)
            container = self.ids.buy_item_list
            container.clear_widgets()
            for item in candy_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)

    def show_soft_drinks(self):
        self.ids.product_filter_label.text = ''
        if self.item_list == None: pass
        else:
            drink_list = filter(lambda x: x.item_class == "Soft drink", self.item_list)
            container = self.ids.buy_item_list
            container.clear_widgets()
            for item in drink_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)

    def show_food(self):
        self.ids.product_filter_label.text = ''
        if self.item_list == None: pass
        else:
            food_list = filter(lambda x: x.item_class == "Food", self.item_list)
            container = self.ids.buy_item_list
            container.clear_widgets()
            for item in food_list:
                item_layout = BuyItemLayout(item, container)
                container.add_widget(item_layout)

    def show_most_bought(self):
        #check if there are items or for some reasen a customer has not been selected (alwasy should be)
        if len(self.item_list) == 0 or self.main_app.current_customer == None: pass
        else:
            most_bought = self.main_app.customer_handler.most_bought(self.main_app.current_customer)
            if most_bought:
                most_bought_list = [x[0] for x in most_bought]
                most_bought_list = filter(lambda x: self.item_exists_update_price(x), most_bought_list)
                most_bought_list = most_bought_list[:3]
                container = self.ids.buy_item_list
                container.clear_widgets()
                for item in most_bought_list:
                    item_layout = BuyItemLayout(item, container)
                    container.add_widget(item_layout)

    #filter visible products based on the text on product_filter_label
    def filter_products(self):
	filter_text = self.ids.product_filter_label.text
	if self.item_list == None: pass
        else:
            container = self.ids.buy_item_list
            container.clear_widgets()
            for item in self.item_list:
		if filter_text in item.name:
		    item_layout = BuyItemLayout(item, container)
                    container.add_widget(item_layout)

    #updates the selected items screen
    def update_selected_items_table(self):
        container = self.ids.selected_item_container
        container.clear_widgets()
        for key in sorted(self.selected_items.keys(), key=lambda item: self.selected_items[item][1] , reverse=True):
            container.add_widget(SelectedItemLayout(self.selected_items[key][0], self.selected_items[key][1], container))

    #initializes filter buttons for names
    def init_filter_buttons(self, char_list):
	for char in char_list:
	    butt = Button(text=char, font_size=button_font_size,
			    background_normal='',
                            background_color=button_color, color=button_font_color)
	    butt.bind(on_release=self.on_filter_button_press)

	    self.ids.product_filter_button_container.add_widget(butt)

    #determines what happens, when buttons with letters for filtering are pressed
    def on_filter_button_press(self, button):
	self.ids.product_filter_label.text += button.text
	self.filter_products()

    #determines what happens when backspace is used
    def on_remove_filter_text(self):
	self.ids.product_filter_label.text = self.ids.product_filter_label.text[0:-1]
	self.filter_products()

    def select_item(self,item):
        if item.name in self.selected_items:
            self.selected_items[item.name] = (item, self.selected_items[item.name][1]+ 1)
        else:
            self.selected_items[item.name] = (item, 1)

        self.update_selected_items_table()

    def unselect_item(self, item):
        #decrease the count of selected items
        if item.name in self.selected_items:
            nmbr_selected = self.selected_items[item.name][1]
            if nmbr_selected < 2:
                del self.selected_items[item.name]
            else:
                self.selected_items[item.name] = (item, self.selected_items[item.name][1] - 1)
            self.update_selected_items_table()

    def buy_item(self):
        if len(self.selected_items.keys()) == 0: pass
        else:
            amount = 0
            for key in self.selected_items:
                amount += self.selected_items[key][0].price * self.selected_items[key][1]
                #add all the bought items to database
                for ii in range(self.selected_items[key][1]):
                    self.main_app.customer_handler.save_buy(self.main_app.current_customer, self.selected_items[key][0])
            #save the buy to database
            self.main_app.customer_handler.pay_from_tab(self.main_app.current_customer, amount)
            self.selected_items = {}
            self.update_screen()

    def buy_and_exit(self):
        if len(self.selected_items.keys()) == 0: pass
        else:
            amount = 0
            for key in self.selected_items:
                amount += self.selected_items[key][0].price * self.selected_items[key][1]
                #add all the bought items to database
                for ii in range(self.selected_items[key][1]):
                    self.main_app.customer_handler.save_buy(self.main_app.current_customer, self.selected_items[key][0])
            #save the buy to database
            self.main_app.customer_handler.pay_from_tab(self.main_app.current_customer, amount)
            self.selected_items = {}
            self.update_screen()
            self.to_login_and_logout()

    #in most bought this is used to check whether item exists and if it does, update price
    def item_exists_update_price(self,item):
        for it in self.item_list:
            if it.name == item.name:
                item.price = it.price
                return True
        return False

    def tab_color(self):
        tab = self.main_app.current_customer.tab_value
        if tab >= 5.0:
            return (0,1,0,1)
        elif tab < 5.0 and tab >=0:
            return (1,1,0,1)
        else:
            return (1,0,0,1)

'''CustomerScreen allows customers to add value to the tab and see their balance history'''
class CustomerScreen(Screen):

    def __init__(self, **kv):
        super(CustomerScreen, self).__init__(**kv)
        self.main_app = kv['main_app']
        self.add_tab_input = FloatInput(write_tab=False, multiline=False)
        self.ids.add_tab_input_container.add_widget(self.add_tab_input)

    def add_to_tab(self):
        tab_input = self.add_tab_input
        try:
            if tab_input.text == "" or float(tab_input.text) >150.0:
                self.ids.warning_label.text = "Please enter a proper amount"
            else:
                self.main_app.customer_handler.pay_to_tab(self.main_app.current_customer, float(tab_input.text))
                self.update_screen()
                self.ids.warning_label.text = "Added {} succesfully to your tab".format(float(tab_input.text))
                tab_input.text= ""
        except ValueError:
            self.ids.warning_label.text = "Please enter a proper amount"

        def empty_warning():
            self.ids.warning_label.text = ""
        Clock.schedule_once(lambda dt: empty_warning(), 7)

    def on_pre_enter(self):
        self.update_screen()

    def on_leave_screen(self):
        self.ids.account_label.text = ""
        self.ids.tab_value_label.text = ""

    def update_screen(self):
        if self.main_app.current_customer:
            self.ids.account_label.text = self.main_app.current_customer.account_name
            self.ids.tab_value_label.text = str(self.main_app.current_customer.tab_value)
            self.ids.tab_value_label.color = self.tab_color()

    def tab_color(self):
        tab = self.main_app.current_customer.tab_value
        if tab >= 5.0:
            return (0,1,0,1)
        elif tab < 5.0 and tab >=0:
            return (1,1,0,1)
        else:
            return (1,0,0,1)

'''Screen used for admin stuff, such as adding new items, viewing tabs and changing item prices
    Actually settings'''
class AdminScreen(Screen):

    def __init__(self,  **kv):
        Screen.__init__(self,  **kv)
        self.main_app = kv['main_app']

'''AccManageScreen is used by admin to monitor and change accounts balances and
to remove accounts'''
class AccManageScreen(Screen):

    def __init__(self, **kv):
        super(AccManageScreen, self).__init__(**kv)
        self.main_app = kv['main_app']

    def on_pre_enter(self):
        for cust in self.main_app.customer_handler.customers:
            layout = CustomerLayout(cust, self.ids.customer_container)
            self.ids.customer_container.add_widget(layout)

    def on_leave(self):
        self.ids.customer_container.clear_widgets()

    def confirm_replace_cust_db(self):
        p = ConfirmationPopup(self.main_app.customer_handler.replace_customer_db,
                              "Are you sure you wish to replace the current customers?")
        p.open()

    def confirm_backup_customers(self):
        p = ConfirmationPopup(self.main_app.customer_handler.backup_customers,
                              "Do you wish to backup your customer db? (by uploading to drive)")
        p.open()

'''FileManageScreen is used by admin to add, delete and update items'''
class ItemManageScreen(Screen):

    def __init__(self, **kv):
        super(ItemManageScreen, self).__init__( **kv)
        self.main_app = kv['main_app']

        for item in self.main_app.item_handler.item_list:
            layout = ManageItemLayout(item, self.ids.item_manage_container)
            self.ids.item_manage_container.add_widget(layout)

        self.ids.item_manage_container.add_widget(AddItemLayout(self.ids.item_manage_container))

    def add_one_item(self, item):
        last_widget = self.ids.item_manage_container.children[0] #might not work always
        Logger.info('ItemManageScreen: OBS last widget to be removed {}'.format(last_widget))
        self.ids.item_manage_container.remove_widget(last_widget)
        self.ids.item_manage_container.add_widget(ManageItemLayout(item,self.ids.item_manage_container))
        self.ids.item_manage_container.add_widget(AddItemLayout(self.ids.item_manage_container))

    def add_item(self):
        p = AddItemPopup(self)
        p.open()

'''FileScreen is used to select item paths from the device'''
class FileScreen(Screen):
    pass

class TestScreen(Screen):

    def __init__(self, **kv):
        super(TestScreen, self).__init__(**kv)
        self.app = App.get_running_app()

class CustomerLayout(BoxLayout):
    customer = ObjectProperty(None)

    def __init__(self, customer, container, **kv):
        self.customer = customer
        self.container = container
        super(CustomerLayout, self).__init__(**kv)

        #for child in self.children[int(len(self.children)/2):int(len(self.children))]:
        #    self.remove_widget(child)

    def update_tab_value(self):
        p = UpdateCustomerTabPopup(self, self.customer)
        p.open()

    def confirm_delete_customer(self):
        title = 'Do you wish to remove account for {} ?'.format(self.customer.customer_name)
        p = ConfirmationPopup(self.delete_customer, title)
        p.open()

    def delete_customer(self):
        App.get_running_app().man.customer_handler.delete_customer(self.customer)
        self.container.remove_widget(self)

class ManageItemLayout(BoxLayout):

    item = ObjectProperty(None)
    container = ObjectProperty(None)

    def __init__(self, item, container, **kv):
        self.item = item
        self.container = container
        BoxLayout.__init__(self, **kv)

        #for some reason all objects in kivy file are added twice, remove duplicates
        #for child in self.children[4:9]:
        #    self.remove_widget(child)

    def confirm_delete_item(self):
        title = 'Do you wish to delete {}?'.format(self.item.name)
        p = ConfirmationPopup(self.delete_item, title)
        p.open()

    def delete_item(self):
        App.get_running_app().man.item_handler.delete_item(self.item)
        self.container.remove_widget(self)

    def update_item_price(self):
        p = UpdateItemPopup(self,self.item)
        p.open()

class AddItemLayout(BoxLayout):

    container = ObjectProperty(None)

    def __init__(self,container, **kv):
        self.container = container
        super(AddItemLayout, self).__init__(**kv)

        #stupid bug again
        #for child in self.children[int(len(self.children)/2):int(len(self.children))]:
        #    self.remove_widget(child)

''' the layout for items presented in buyscreen, each should have know its own item'''
class BuyItemLayout(BoxLayout):

    def __init__(self,item, container, **kv):
        self.item = item
        self.container = container
        super(BuyItemLayout,self).__init__(**kv)

    def increase_item(self):
        App.get_running_app().man.get_screen('osto').select_item(self.item)

    def decrease_item(self):
        App.get_running_app().man.get_screen('osto').unselect_item(self.item)

''' the layout for items presented in buyscreen, each should have know its own item'''
class SelectedItemLayout(BoxLayout):

    def __init__(self,item, amount_of_selected, container, **kv):
        self.item = item
        self.amount_of_selected = amount_of_selected
        self.container = container
        super(SelectedItemLayout,self).__init__(**kv)

class MyInputListener(Widget):

    def __init__(self, parent_screen, **kv):
	super(MyInputListener,self).__init__(**kv)
	#self.orientation = "vertical"
	#self.data_label = Label(text="saaas")
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text')
        if self._keyboard.widget:
	    print(self._keyboard.widget)
        #self._keyboard.bind(on_key_down=self._on_keyboard_down)
        #self.add_widget(self.data_label)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
	pass
        #self.data_label.text = self.data_label.text

'''ItemButton is used in the BuyScreen to portray the items'''
class ItemButton(Button):

    def __init__(self, item, **kv):
        super(ItemButton, self).__init__(**kv)
        self.item = item

class MySeparator(Label):

    pass

'''AccountButton is used in the loginScreen account selection'''
class AccountButton(Button):

    def __init__(self,account, **kv):
        Button.__init__(self, **kv)
        self.account = account

class CustomDropDown(DropDown):
    pass

class FloatInput(TextInput):

    pat = re.compile('[^0-9]')
    def insert_text(self, substring, from_undo=False):
        pat = self.pat
        if '.' in self.text:
            s = re.sub(pat, '', substring)
        else:
            s = '.'.join([re.sub(pat, '', s) for s in substring.split('.', 1)])
        return super(FloatInput, self).insert_text(s, from_undo=from_undo)

'''PiikkiManager is the parent class of every screen and
    contains data that should be available to all the screens'''
class PiikkiManager(ScreenManager):

    def __init__(self, **kv):
        ScreenManager.__init__(self, **kv)
        self.app = kv['piikki_app']

        from kivy.utils import platform
        if platform == 'android':
            path = self.app.user_data_dir
        else:
            path = os.path.dirname(os.path.realpath(__file__))

        self.current_customer = None
        self.customer_handler = CustomerHandler(path)
        self.item_handler = ItemHandler(path)

        self.add_widget(MenuScreen(name="menu", main_app = self))
        self.add_widget(TestScreen(name="test", main_app=self))
        self.add_widget(LoginScreen(name="login", main_app = self))
        self.add_widget(AccountScreen(name="account", main_app = self))
        self.add_widget(CustomerScreen(name="customer", main_app = self))
        self.add_widget(BuyScreen(name="osto", main_app = self))
        self.add_widget(AdminScreen(name="admin", main_app = self))
        self.add_widget(AccManageScreen(name='acc_manage', main_app = self))
        self.add_widget(ItemManageScreen(name='item_manage', main_app = self))
        self.add_widget(FileScreen(name="select", main_app = self))

    #add a text input to a given container, used by multiple screens
    def add_input(self, container, passw=False):
        text_input = TextInput(password=passw)
	text_input.write_tab = False
	text_input.multiline = False
        container.add_widget(text_input)
        return text_input

'''Finally the main app class used by kivy'''
class PiikkiApp(App):

    def check_back_up(self):
        if self.settings.time_to_backup():
            self.man.customer_handler.backup_customers()

    def build(self):
        self.man = PiikkiManager(piikki_app = self)
        self.settings = Settings(os.path.dirname(os.path.realpath(__file__)))
        self.check_back_up()
        Clock.schedule_interval(lambda dt: self.check_back_up(), 40000)

        return self.man

if __name__ == '__main__':
    PiikkiApp().run()


text:
package org.joda.beans.sample;

import java.util.List;
import java.util.Map;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.DerivedProperty;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBean;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

/**
 * Mock JavaBean, used for testing.
 *
 * @author Stephen Colebourne
 */
@BeanDefinition
public abstract class AbstractResult<T extends Address> extends DirectBean {

    /** The docs. */
    @PropertyDefinition
    private List<T> docs;

    @DerivedProperty
    public abstract String getResultType();

    //------------------------- AUTOGENERATED START -------------------------
    /**
     * The meta-bean for {@code AbstractResult}.
     * @return the meta-bean, not null
     */
    @SuppressWarnings("rawtypes")
    public static AbstractResult.Meta meta() {
        return AbstractResult.Meta.INSTANCE;
    }

    /**
     * The meta-bean for {@code AbstractResult}.
     * @param <R>  the bean's generic type
     * @param cls  the bean's generic type
     * @return the meta-bean, not null
     */
    @SuppressWarnings("unchecked")
    public static <R extends Address> AbstractResult.Meta<R> metaAbstractResult(Class<R> cls) {
        return AbstractResult.Meta.INSTANCE;
    }

    static {
        MetaBean.register(AbstractResult.Meta.INSTANCE);
    }

    @SuppressWarnings("unchecked")
    @Override
    public AbstractResult.Meta<T> metaBean() {
        return AbstractResult.Meta.INSTANCE;
    }

    //-----------------------------------------------------------------------
    /**
     * Gets the docs.
     * @return the value of the property
     */
    public List<T> getDocs() {
        return docs;
    }

    /**
     * Sets the docs.
     * @param docs  the new value of the property
     */
    public void setDocs(List<T> docs) {
        this.docs = docs;
    }

    /**
     * Gets the the {@code docs} property.
     * @return the property, not null
     */
    public final Property<List<T>> docs() {
        return metaBean().docs().createProperty(this);
    }

    //-----------------------------------------------------------------------
    /**
     * Gets the the {@code resultType} property.
     * @return the property, not null
     */
    public final Property<String> resultType() {
        return metaBean().resultType().createProperty(this);
    }

    //-----------------------------------------------------------------------
    @Override
    public AbstractResult<T> clone() {
        return JodaBeanUtils.cloneAlways(this);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj != null && obj.getClass() == this.getClass()) {
            AbstractResult<?> other = (AbstractResult<?>) obj;
            return JodaBeanUtils.equal(getDocs(), other.getDocs());
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hash = getClass().hashCode();
        hash = hash * 31 + JodaBeanUtils.hashCode(getDocs());
        return hash;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder(96);
        buf.append("AbstractResult{");
        int len = buf.length();
        toString(buf);
        if (buf.length() > len) {
            buf.setLength(buf.length() - 2);
        }
        buf.append('}');
        return buf.toString();
    }

    protected void toString(StringBuilder buf) {
        buf.append("docs").append('=').append(JodaBeanUtils.toString(getDocs())).append(',').append(' ');
        buf.append("resultType").append('=').append(JodaBeanUtils.toString(getResultType())).append(',').append(' ');
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-bean for {@code AbstractResult}.
     * @param <T>  the type
     */
    public static class Meta<T extends Address> extends DirectMetaBean {
        /**
         * The singleton instance of the meta-bean.
         */
        @SuppressWarnings("rawtypes")
        static final Meta INSTANCE = new Meta();

        /**
         * The meta-property for the {@code docs} property.
         */
        @SuppressWarnings({"unchecked", "rawtypes" })
        private final MetaProperty<List<T>> docs = DirectMetaProperty.ofReadWrite(
                this, "docs", AbstractResult.class, (Class) List.class);
        /**
         * The meta-property for the {@code resultType} property.
         */
        private final MetaProperty<String> resultType = DirectMetaProperty.ofDerived(
                this, "resultType", AbstractResult.class, String.class);
        /**
         * The meta-properties.
         */
        private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
                this, null,
                "docs",
                "resultType");

        /**
         * Restricted constructor.
         */
        protected Meta() {
        }

        @Override
        protected MetaProperty<?> metaPropertyGet(String propertyName) {
            switch (propertyName.hashCode()) {
                case 3088955:  // docs
                    return docs;
                case -571837193:  // resultType
                    return resultType;
            }
            return super.metaPropertyGet(propertyName);
        }

        @Override
        public boolean isBuildable() {
            return false;
        }

        @Override
        public BeanBuilder<? extends AbstractResult<T>> builder() {
            throw new UnsupportedOperationException("AbstractResult is an abstract class");
        }

        @SuppressWarnings({"unchecked", "rawtypes" })
        @Override
        public Class<? extends AbstractResult<T>> beanType() {
            return (Class) AbstractResult.class;
        }

        @Override
        public Map<String, MetaProperty<?>> metaPropertyMap() {
            return metaPropertyMap$;
        }

        //-----------------------------------------------------------------------
        /**
         * The meta-property for the {@code docs} property.
         * @return the meta-property, not null
         */
        public final MetaProperty<List<T>> docs() {
            return docs;
        }

        /**
         * The meta-property for the {@code resultType} property.
         * @return the meta-property, not null
         */
        public final MetaProperty<String> resultType() {
            return resultType;
        }

        //-----------------------------------------------------------------------
        @Override
        protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
            switch (propertyName.hashCode()) {
                case 3088955:  // docs
                    return ((AbstractResult<?>) bean).getDocs();
                case -571837193:  // resultType
                    return ((AbstractResult<?>) bean).getResultType();
            }
            return super.propertyGet(bean, propertyName, quiet);
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
            switch (propertyName.hashCode()) {
                case 3088955:  // docs
                    ((AbstractResult<T>) bean).setDocs((List<T>) newValue);
                    return;
                case -571837193:  // resultType
                    if (quiet) {
                        return;
                    }
                    throw new UnsupportedOperationException("Property cannot be written: resultType");
            }
            super.propertySet(bean, propertyName, newValue, quiet);
        }

    }

    //-------------------------- AUTOGENERATED END --------------------------
}


text:
package com.lin.web.interceptor;

import java.util.Map;
import java.util.logging.Logger;

import com.lin.web.dto.SessionObjectDTO;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AdminSessionCheckInterceptor implements Interceptor {

	private static final long serialVersionUID = 1L;
	private String status;
	private SessionObjectDTO sessionDTO;
	private static final Logger log = Logger.getLogger(AdminSessionCheckInterceptor.class.getName());

	public void destroy() {
		log.warning(" AdminSessionCheckInterceptor destroy() is called...");
	}

	public void init() {
		log.warning(" AdminSessionCheckInterceptor init() is called...");
	}

	public String intercept(ActionInvocation actionInvocation) throws Exception {
		ActionContext context = actionInvocation.getInvocationContext();
		Map<String, Object> sessionMap = context.getSession();
		sessionDTO=(SessionObjectDTO) sessionMap.get("sessionDTO");
		if(sessionMap != null && !sessionMap.isEmpty() && (sessionDTO!=null && sessionDTO.getEmailId()!=null && (sessionDTO.isAdminUser() || sessionDTO.isSuperAdmin()))) {
			log.warning("User is either a SuperAdmin or a Administrator");

		}else{
			log.warning("Neither a SuperAdmin nor an Administrator");
			//setStatus("You do not have the required permission.");
			return "unAuthorisedAccess";
		}

		String actionResult = actionInvocation.invoke();
		return actionResult;
		}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getStatus() {
		return status;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BE.Core.Algorithms
{
    public class StoreChoiseAlgorithmInput
    {
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSRace</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>


text:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import sangria.execution.{ErrorWithResolver, Executor, QueryAnalysisError}
import sangria.marshalling.sprayJson._
import sangria.parser.QueryParser
import sangria.renderer.SchemaRenderer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
import spray.json._

object Server extends App {
  implicit val system = ActorSystem("sangria-server")
  implicit val materializer = ActorMaterializer()
  val repository = new Repository

  val route: Route =
    pathSingleSlash {
      getFromResource("root.html")
    } ~
    pathPrefix("ubeer") {
      getFromDirectory("ubeer-client")
    } ~
    pathPrefix("graphiql") {
      getFromDirectory("graphiql")
    } ~
    (post & path("graphql")) {
      entity(as[JsValue]) { requestJson => {
        val JsObject(fields) = requestJson
        val JsString(query) = fields("query")
        val operation = fields.get("operationName") collect {
          case JsString(op) => op
        }

        val vars = fields.get("variables") match {
          case Some(obj: JsObject) => obj
          case _ => JsObject.empty
        }

        QueryParser.parse(query) match {
          // Query parsed successfully, time to execute it!
          case Success(queryAst) => complete(
            Executor.execute(
              ProjectSchema.schema,
              queryAst,
              repository,
              variables = vars,
              operationName = operation
            ).map(OK -> _)
            .recover {
              case error: QueryAnalysisError => BadRequest -> error.resolveError
              case error: ErrorWithResolver => InternalServerError -> error.resolveError
            }
          )

          // Cannot parse GraphQL query, return error
          case Failure(error) =>
            complete(BadRequest, JsObject("error" -> JsString(error.getMessage)))
        }
      }}
    }

  // Prints a human-readable representation of the schema upon server startup
  println(SchemaRenderer.renderSchema(ProjectSchema.schema))

  Http().bindAndHandle(route, "0.0.0.0", 8080)
}


text:
from __future__ import unicode_literals

import os.path

from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(name='django-cache-magic',
      version='0.1.0',
      description='Django Cache Magic',
      author='Nathaniel Tucker',
      author_email='me@ntucker.me',
      url='https://github.com/ntucker/django-cache-magic',
      packages=find_packages(),
      include_package_data=True,
      install_requires=['django>=1.3', ],
      long_description=read('README.rst'),
      license="BSD",
      classifiers=[
          'Development Status :: 4 - Beta',
          'Environment :: Web Environment',
          'Framework :: Django',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: BSD License',
          'Operating System :: OS Independent',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
      ],
      )


text:
namespace paddle {
namespace framework {
namespace ir {

void SetOp(ProgramDesc* prog, const std::string& type, const std::string& name,
           const std::vector<std::string>& inputs,
           const std::vector<std::string>& outputs, bool use_mkldnn,
           float scale = 0) {
  auto* op = prog->MutableBlock(0)->AppendOp();
  op->SetType(type);
  op->SetAttr("use_mkldnn", use_mkldnn);
  op->SetAttr("name", name);
  if (type == "conv2d") {
    op->SetAttr("Scale_out", scale);
    op->SetInput("Input", {inputs[0]});
    if (inputs.size() > 1) op->SetInput("Filter", {inputs[1]});
    if (inputs.size() > 2) op->SetInput("Bias", {inputs[2]});
    op->SetOutput("Output", {outputs[0]});
  } else if (type == "quantize") {
    op->SetInput("Input", {inputs[0]});
    op->SetOutput("Output", {outputs[0]});
    op->SetAttr("Scale", scale);
  } else if (type == "dequantize") {
    op->SetInput("Input", {inputs[0]});
    op->SetOutput("Output", {outputs[0]});
    op->SetAttr("Scale", scale);
  } else if (type == "requantize") {
    op->SetInput("Input", {inputs[0]});
    op->SetOutput("Output", {outputs[0]});
    op->SetAttr("Scale_out", scale);
  } else if (type == "concat") {
    op->SetInput("X", inputs);
    op->SetOutput("Out", outputs);
  }
}

// (a,w1,b1)->Conv1->d
// d->Dequant(scale1)->e
// e->Quant(scale2)->f
// (f,w2,b2)->Conv2->i
ProgramDesc BuildConvRequantProgramDesc(bool use_mkldnn, float scale_out,
                                        float scale1, float scale2) {
  ProgramDesc prog;
  for (auto& v : std::initializer_list<std::string>(
           {"a", "w1", "b1", "d", "e", "f", "w2", "b2", "i"})) {
    auto* var = prog.MutableBlock(0)->Var(v);
    if (v.find("w") == 0 || v.find("b") == 0) {
      var->SetPersistable(true);
    }
  }

  SetOp(&prog, "conv2d", "Conv1", {"a", "w1", "b1"}, {"d"}, use_mkldnn,
        scale_out);
  SetOp(&prog, "dequantize", "Dequant", {"d"}, {"e"}, use_mkldnn, scale1);
  SetOp(&prog, "quantize", "Quant", {"e"}, {"f"}, use_mkldnn, scale2);
  SetOp(&prog, "conv2d", "Conv2", {"f", "w2", "b2"}, {"i"}, use_mkldnn,
        scale_out);
  return prog;
}

static const std::initializer_list<std::string> variable_names{
    "a", "b", "c", "d", "e", "f", "g", "h"};

// a->Conv1->b
// b->Dequant(scale1)->c
// c->Quant1(scale2)->d and d->Conv2->e
// c->Conv3->f
// c->Quant2(scale3)->g and g->Conv4->h
ProgramDesc BuildConvMultiOutputProgramDesc(bool use_mkldnn, float scale_out,
                                            float scale1, float scale2,
                                            float scale3) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }

  SetOp(&prog, "conv2d", "Conv1", {"a"}, {"b"}, use_mkldnn, scale_out);
  SetOp(&prog, "dequantize", "Dequant", {"b"}, {"c"}, use_mkldnn, scale1);

  SetOp(&prog, "quantize", "Quant1", {"c"}, {"d"}, use_mkldnn, scale2);
  SetOp(&prog, "conv2d", "Conv2", {"d"}, {"e"}, use_mkldnn, scale_out);

  SetOp(&prog, "conv2d", "Conv3", {"c"}, {"f"}, use_mkldnn, scale_out);

  SetOp(&prog, "quantize", "Quant2", {"c"}, {"g"}, use_mkldnn, scale3);
  SetOp(&prog, "conv2d", "Conv4", {"g"}, {"h"}, use_mkldnn, scale_out);

  return prog;
}

//  a->Conv1->b->Requant(scale1)->c
//  d->Conv2->e->Requant(scale2)->f
//  {c,f}->Concat
ProgramDesc BuildConvsRequantConcatProgramDesc(bool use_mkldnn, float scale_out,
                                               float scale1, float scale2) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }

  SetOp(&prog, "conv2d", "Conv1", {"a"}, {"b"}, use_mkldnn, scale_out);
  SetOp(&prog, "requantize", "Requant1", {"b"}, {"c"}, use_mkldnn, scale1);

  SetOp(&prog, "conv2d", "Conv2", {"d"}, {"e"}, use_mkldnn, scale_out);
  SetOp(&prog, "requantize", "Requant2", {"e"}, {"f"}, use_mkldnn, scale2);

  SetOp(&prog, "concat", "Concat", {"c"}, {"f"}, use_mkldnn);

  return prog;
}

// a->Concat->b
// b->Dequant(scale1)->c
// c->Quant(scale2)->d
// d->Conv->e
ProgramDesc BuildConcatDequantQuantProgramDesc(bool use_mkldnn, float scale_out,
                                               float scale1, float scale2) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }

  SetOp(&prog, "concat", "Concat", {"a"}, {"b"}, use_mkldnn);
  SetOp(&prog, "dequantize", "Dequant", {"b"}, {"c"}, use_mkldnn, scale1);
  SetOp(&prog, "quantize", "Quant", {"c"}, {"d"}, use_mkldnn, scale2);
  SetOp(&prog, "conv2d", "Conv2", {"d"}, {"e"}, use_mkldnn, scale_out);
  return prog;
}

// a->Conv1->b
// b->Requant1(Scale1)->c
// b->Requant2(Scale2)->d
ProgramDesc BuildConvMultiRequantProgramDesc(bool use_mkldnn, float scale_out,
                                             float scale1, float scale2) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "conv2d", "Conv1", {"a"}, {"b"}, use_mkldnn, scale_out);
  SetOp(&prog, "requantize", "Requant1", {"b"}, {"c"}, use_mkldnn, scale1);
  SetOp(&prog, "requantize", "Requant2", {"b"}, {"d"}, use_mkldnn, scale2);
  return prog;
}

// a->Conv1->b
// b->Dequant1(Scale1)->c
// c->Concat
ProgramDesc BuildConvDequantConcatProgramDesc(bool use_mkldnn, float scale_out,
                                              float scale) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "conv2d", "Conv1", {"a"}, {"b"}, use_mkldnn, scale_out);
  SetOp(&prog, "dequantize", "Dequant1", {"b"}, {"c"}, use_mkldnn, scale);
  SetOp(&prog, "concat", "Concat1", {"c"}, {"d"}, use_mkldnn);
  return prog;
}

// a->Conv1->b
// b->Dequant1(Scale1)->c
// b->Conv2->d
ProgramDesc BuildConvDequantConvProgramDesc(bool use_mkldnn, float scale_out,
                                            float scale) {
  ProgramDesc prog;
  for (auto& v : variable_names) {
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "conv2d", "Conv1", {"a"}, {"b"}, use_mkldnn, scale_out);
  SetOp(&prog, "dequantize", "Dequant1", {"b"}, {"c"}, use_mkldnn, scale);
  SetOp(&prog, "conv2d", "Conv2", {"b"}, {"d"}, use_mkldnn);
  return prog;
}

void InitTensorHolder(Scope* scope, const paddle::platform::Place& place,
                      const char* var_name) {
  auto x = scope->Var(var_name);
  auto tensor = x->GetMutable<LoDTensor>();
  tensor->mutable_data(place, proto::VarType::FP32, 1);
}

void PrepareGraph(std::unique_ptr<ir::Graph>* graph, const ProgramDesc& prog) {
  auto place = paddle::platform::CPUPlace();
  NaiveExecutor exe{place};
  Scope scope;
  exe.CreateVariables(prog, 0, true, &scope);

  for (auto& v : variable_names) {
    InitTensorHolder(&scope, place, v.c_str());
  }
  (*graph)->SetNotOwned(kParamScopeAttr, &scope);
}

void RegisterPass(std::unique_ptr<ir::Graph>* graph) {
  auto pass = PassRegistry::Instance().Get("cpu_quantize_squash_pass");
  graph->reset(pass->Apply(graph->release()));
}

// check number of nodes
void CountNodeTest(const ProgramDesc& prog, int removed_nodes_num) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  PrepareGraph(&graph, prog);

  int original_nodes_num = graph->Nodes().size();
  RegisterPass(&graph);
  int current_nodes_num = graph->Nodes().size();

  EXPECT_EQ(original_nodes_num - removed_nodes_num, current_nodes_num);
}

// check op->scale_out
void EqualScaleOutTest(const ProgramDesc& prog, const std::string& name,
                       float scale) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  PrepareGraph(&graph, prog);
  RegisterPass(&graph);

  for (auto* node : graph->Nodes()) {
    if (node->IsOp() &&
        boost::get<std::string>(node->Op()->GetAttr("name")) == name) {
      float scale_out = boost::get<float>(node->Op()->GetAttr("Scale_out"));
      EXPECT_EQ(scale_out, scale);
    }
  }
}

// check requant_op scales
void CheckRequantScalesTest(const ProgramDesc& prog, float scale_in,
                            float scale_out) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));

  PrepareGraph(&graph, prog);
  RegisterPass(&graph);

  for (auto* node : graph->Nodes()) {
    if (node->IsOp() && node->Op()->Type() == "requantize") {
      float op_scale_in = boost::get<float>(node->Op()->GetAttr("Scale_in"));
      EXPECT_EQ(op_scale_in, scale_in);
      float op_scale_out = boost::get<float>(node->Op()->GetAttr("Scale_out"));
      EXPECT_EQ(op_scale_out, scale_out);
    }
  }
}

// From Conv1->d->Dequant->e->Quant->f->Conv2
// To Conv1->d->Conv2
TEST(CpuQuantizeSquashPass, equal_scales) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto use_mkldnn = true;
  // Remove 4 nodes: Dequant, Quant, e, f
  auto remove_nodes = 4;

  CountNodeTest(
      BuildConvRequantProgramDesc(use_mkldnn, scale_out, scale, scale),
      remove_nodes);
}

// From Conv1->d->Dequant->e->Quant->f->Conv2
// First change to Conv1->d->Requant->f->Conv2
// Then Conv1->f->Conv2
TEST(CpuQuantizeSquashPass, unequal_scales) {
  auto scale_out = 1.0f;
  auto scale1 = 1.2345f;
  auto scale2 = 21.0f;
  auto use_mkldnn = true;
  // Remove 4 nodes: Dequant, Quant, e, d
  auto remove_nodes = 4;

  CountNodeTest(
      BuildConvRequantProgramDesc(use_mkldnn, scale_out, scale1, scale2),
      remove_nodes);

  EqualScaleOutTest(
      BuildConvRequantProgramDesc(use_mkldnn, scale_out, scale1, scale2),
      "Conv1", scale2);
}

// from
// a->Conv1->b->Dequant(Scale1)->c
// c->Quant1(Scale1)->d and d->Conv2->e
// c->Quant2(Scale2)->g and g->Conv4->h
// c->Conv3->f
// to
// a->Conv1->b
// b->Conv2->e
// b->Requant(Scale_in = Scale1; Scale_out = Scale2)->g->Conv4->h
// b->Dequant(Scale1)->c->Conv3->f
TEST(CpuQuantizeSquashPass, branch_to_equal_unequal_and_fp32) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto scale2 = 21.0f;
  auto use_mkldnn = true;
  // Remove 3 nodes: Quant1, c, Quant2,
  // Insert 1 node: Requant
  auto remove_nodes = 2;

  CountNodeTest(BuildConvMultiOutputProgramDesc(use_mkldnn, scale_out, scale,
                                                scale, scale2),
                remove_nodes);
  CheckRequantScalesTest(BuildConvMultiOutputProgramDesc(use_mkldnn, scale_out,
                                                         scale, scale, scale2),
                         scale, scale2);
}

//  a->Conv1->b->Requant->c
//  d->Conv2->e->Requant->f
//  {c,f}->Concat
TEST(CpuQuantizeSquashPass, equal_scales_squash_requantize) {
  // Delete both requantize op
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto use_mkldnn = true;
  // Remove 4 nodes: b, Requant1, e, Requant2
  auto remove_nodes = 4;
  CountNodeTest(
      BuildConvsRequantConcatProgramDesc(use_mkldnn, scale_out, scale, scale),
      remove_nodes);

  // check equal scale conv->scale_out and requant->scale_out
  EqualScaleOutTest(
      BuildConvsRequantConcatProgramDesc(use_mkldnn, scale_out, scale, scale),
      "Conv1", scale);
  EqualScaleOutTest(
      BuildConvsRequantConcatProgramDesc(use_mkldnn, scale_out, scale, scale),
      "Conv2", scale);
}

// a->Concat->b->Dequant->c->Quant->d->Conv->e
// to a->Concat->b->Requant->d->Conv->e
TEST(CpuQuantizeSquashPass,
     unequal_scales_squash_dequantize_quantize_into_requantize) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto scale2 = 21.0f;
  auto use_mkldnn = true;
  // Remove 3 nodes: Dequant1, c, Quant
  // Insert 1 node: Requant
  auto remove_nodes = 2;

  CountNodeTest(
      BuildConcatDequantQuantProgramDesc(use_mkldnn, scale_out, scale, scale2),
      remove_nodes);
  CheckRequantScalesTest(
      BuildConcatDequantQuantProgramDesc(use_mkldnn, scale_out, scale, scale2),
      scale, scale2);
}

// a->Conv1->b
// b->Requant1(Scale1)->c
// b->Requant2(Scale2)->d
TEST(CpuQuantizeSquashPass, more_than_one_conv_out_outputs) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto scale2 = 21.0f;
  auto use_mkldnn = true;
  // nothing change
  auto remove_nodes = 0;
  CountNodeTest(
      BuildConvMultiRequantProgramDesc(use_mkldnn, scale_out, scale, scale2),
      remove_nodes);
}

// a->Conv1->c->Concat
TEST(CpuQuantizeSquashPass, conv_dequant_only_one_output) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto use_mkldnn = true;
  // remove 2 nodes: Dequant1, c
  auto remove_nodes = 2;
  CountNodeTest(BuildConvDequantConcatProgramDesc(use_mkldnn, scale_out, scale),
                remove_nodes);
}

TEST(CpuQuantizeSquashPass, conv_dequant_more_than_one_op_after_conv) {
  auto scale_out = 1.0f;
  auto scale = 1.2345f;
  auto use_mkldnn = true;
  // nothing change
  auto remove_nodes = 0;
  CountNodeTest(BuildConvDequantConvProgramDesc(use_mkldnn, scale_out, scale),
                remove_nodes);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

USE_PASS(cpu_quantize_squash_pass);


text:
package skripteditor.addons.skript.cls;

import skripteditor.clazz.DyeColor;
import skripteditor.clazz.SkClass;

public class ClsColor extends SkClass<DyeColor> {

	@Override
	public String getClassPattern() {
		return "colo[u]r[s]";
	}

	@Override
	public SkClassParse<DyeColor> parse(String text) {
		SkClassParse<DyeColor> result = new SkClassParse<DyeColor>();
		result.parsedObject = DyeColor.getByName(text);
		if (result.parsedObject == null) {
			result.error = "That is not a valid Boolean! valid Booleans: true/yes/on or false/no/off";
			result.parsedObject = null;
		}else{
			result.valid = true;
		}
		return result;
	}

	@Override
	public String[] getExamples() {
		return new String[] {
				"color of the sheep is red or black", "set the colour of the block to green",
				"message \"You're holding a <%color of tool%>%color of tool%<reset> wool block\""
		};
	}

	@Override
	public String getName() {
		return "Color";
	}

}