text:
"""
This object is a small tool to allow user to quickly
determine the variance in q  from the
instrumental parameters.
"""
from instrument import Sample
from instrument import Detector
from instrument import TOF as Neutron
from instrument import Aperture
# import math stuffs
from math import pi
from math import sqrt
import math
import numpy as np
import sys
import logging

logger = logging.getLogger(__name__)

#Plank's constant in cgs unit
_PLANK_H = 6.62606896E-27
#Gravitational acc. in cgs unit
_GRAVITY = 981.0

class ResolutionCalculator(object):
    """
    compute resolution in 2D
    """
    def __init__(self):

        # wavelength
        self.wave = Neutron()
        # sample
        self.sample = Sample()
        # aperture
        self.aperture = Aperture()
        # detector
        self.detector = Detector()
        # 2d image of the resolution
        self.image = []
        self.image_lam = []
        # resolutions
        # lamda in r-direction
        self.sigma_lamd = 0
        # x-dir (no lamda)
        self.sigma_1 = 0
        #y-dir (no lamda)
        self.sigma_2 = 0
        # 1D total
        self.sigma_1d = 0
        self.gravity_phi = None
        # q min and max
        self.qx_min = -0.3
        self.qx_max = 0.3
        self.qy_min = -0.3
        self.qy_max = 0.3
        # q min and max of the detector
        self.detector_qx_min = -0.3
        self.detector_qx_max = 0.3
        self.detector_qy_min = -0.3
        self.detector_qy_max = 0.3
        # possible max qrange
        self.qxmin_limit = 0
        self.qxmax_limit = 0
        self.qymin_limit = 0
        self.qymax_limit = 0

        # plots
        self.plot = None
        # instrumental params defaults
        self.mass = 0
        self.intensity = 0
        self.wavelength = 0
        self.wavelength_spread = 0
        self.source_aperture_size = []
        self.source2sample_distance = []
        self.sample2sample_distance = []
        self.sample_aperture_size = []
        self.sample2detector_distance = []
        self.detector_pix_size = []
        self.detector_size = []
        self.get_all_instrument_params()
        # max q range for all lambdas
        self.qxrange = []
        self.qyrange = []

    def compute_and_plot(self, qx_value, qy_value, qx_min, qx_max,
                         qy_min, qy_max, coord='cartesian'):
        """
        Compute the resolution
        : qx_value: x component of q
        : qy_value: y component of q
        """
        # make sure to update all the variables need.
        # except lambda, dlambda, and intensity
        self.get_all_instrument_params()
        # wavelength etc.
        lamda_list, dlamb_list = self.get_wave_list()
        intens_list = []
        sig1_list = []
        sig2_list = []
        sigr_list = []
        sigma1d_list = []
        num_lamda = len(lamda_list)
        for num in range(num_lamda):
            lam = lamda_list[num]
            # wavelength spread
            dlam = dlamb_list[num]
            intens = self.setup_tof(lam, dlam)
            intens_list.append(intens)
            # cehck if tof
            if num_lamda > 1:
                tof = True
            else:
                tof = False
            # compute 2d resolution
            _, _, sigma_1, sigma_2, sigma_r, sigma1d = \
                        self.compute(lam, dlam, qx_value, qy_value, coord, tof)
            # make image
            image = self.get_image(qx_value, qy_value, sigma_1, sigma_2,
                                   sigma_r, qx_min, qx_max, qy_min, qy_max,
                                   coord, False)
            if qx_min > self.qx_min:
                qx_min = self.qx_min
            if qx_max < self.qx_max:
                qx_max = self.qx_max
            if qy_min > self.qy_min:
                qy_min = self.qy_min
            if qy_max < self.qy_max:
                qy_max = self.qy_max

            # set max qranges
            self.qxrange = [qx_min, qx_max]
            self.qyrange = [qy_min, qy_max]
            sig1_list.append(sigma_1)
            sig2_list.append(sigma_2)
            sigr_list.append(sigma_r)
            sigma1d_list.append(sigma1d)
        # redraw image in global 2d q-space.
        self.image_lam = []
        total_intensity = 0
        sigma_1 = 0
        sigma_r = 0
        sigma_2 = 0
        sigma1d = 0
        for ind in range(num_lamda):
            lam = lamda_list[ind]
            dlam = dlamb_list[ind]
            intens = self.setup_tof(lam, dlam)
            out = self.get_image(qx_value, qy_value, sig1_list[ind],
                                 sig2_list[ind], sigr_list[ind],
                                 qx_min, qx_max, qy_min, qy_max, coord)
            # this is the case of q being outside the detector
            #if numpy.all(out==0.0):
            #    continue
            image = out
            # set variance as sigmas
            sigma_1 += sig1_list[ind] * sig1_list[ind] * self.intensity
            sigma_r += sigr_list[ind] * sigr_list[ind] * self.intensity
            sigma_2 += sig2_list[ind] * sig2_list[ind] * self.intensity
            sigma1d += sigma1d_list[ind] * sigma1d_list[ind] * self.intensity
            total_intensity += self.intensity

        if total_intensity != 0:
            # average variance
            image_out = image / total_intensity
            sigma_1 = sigma_1 / total_intensity
            sigma_r = sigma_r / total_intensity
            sigma_2 = sigma_2 / total_intensity
            sigma1d = sigma1d / total_intensity
            # set sigmas
            self.sigma_1 = sqrt(sigma_1)
            self.sigma_lamd = sqrt(sigma_r)
            self.sigma_2 = sqrt(sigma_2)
            self.sigma_1d = sqrt(sigma1d)
            # rescale
            max_im_val = 1
            if max_im_val > 0:
                image_out /= max_im_val
        else:
            image_out = image * 0.0
            # Don't calculate sigmas nor set self.sigmas!
            sigma_1 = 0
            sigma_r = 0
            sigma_2 = 0
            sigma1d = 0
        if len(self.image) > 0:
            self.image += image_out
        else:
            self.image = image_out

        # plot image
        return self.plot_image(self.image)

    def setup_tof(self, wavelength, wavelength_spread):
        """
        Setup all parameters in instrument

        : param ind: index of lambda, etc
        """

        # set wave.wavelength
        self.set_wavelength(wavelength)
        self.set_wavelength_spread(wavelength_spread)
        self.intensity = self.wave.get_intensity()

        if wavelength == 0:
            msg = "Can't compute the resolution: the wavelength is zero..."
            raise RuntimeError, msg
        return self.intensity

    def compute(self, wavelength, wavelength_spread, qx_value, qy_value,
                coord='cartesian', tof=False):
        """
        Compute the Q resoltuion in || and + direction of 2D
        : qx_value: x component of q
        : qy_value: y component of q
        """
        coord = 'cartesian'
        lamb = wavelength
        lamb_spread = wavelength_spread
        # the shape of wavelength distribution

        if tof:
            # rectangular
            tof_factor = 2
        else:
            # triangular
            tof_factor = 1
        # Find polar values
        qr_value, phi = self._get_polar_value(qx_value, qy_value)
        # vacuum wave transfer
        knot = 2*pi/lamb
        # scattering angle theta; always true for plane detector
        # aligned vertically to the ko direction
        if qr_value > knot:
            theta = pi/2
        else:
            theta = math.asin(qr_value/knot)
        # source aperture size
        rone = self.source_aperture_size
        # sample aperture size
        rtwo = self.sample_aperture_size
        # detector pixel size
        rthree = self.detector_pix_size
        # source to sample(aperture) distance
        l_ssa = self.source2sample_distance[0]
        # sample(aperture) to detector distance
        l_sad = self.sample2detector_distance[0]
        # sample (aperture) to sample distance
        l_sas = self.sample2sample_distance[0]
        # source to sample distance
        l_one = l_ssa + l_sas
        # sample to detector distance
        l_two = l_sad - l_sas

        # Sample offset correction for l_one and Lp on variance calculation
        l1_cor = (l_ssa * l_two) / (l_sas + l_two)
        lp_cor = (l_ssa * l_two) / (l_one + l_two)
        # the radial distance to the pixel from the center of the detector
        radius = math.tan(theta) * l_two
        #Lp = l_one*l_two/(l_one+l_two)
        # default polar coordinate
        comp1 = 'radial'
        comp2 = 'phi'
        # in the case of the cartesian coordinate
        if coord == 'cartesian':
            comp1 = 'x'
            comp2 = 'y'

        # sigma in the radial/x direction
        # for source aperture
        sigma_1 = self.get_variance(rone, l1_cor, phi, comp1)
        # for sample apperture
        sigma_1 += self.get_variance(rtwo, lp_cor, phi, comp1)
        # for detector pix
        sigma_1 += self.get_variance(rthree, l_two, phi, comp1)
        # for gravity term for 1d
        sigma_1grav1d = self.get_variance_gravity(l_ssa, l_sad, lamb,
                                                  lamb_spread, phi, comp1, 'on') / tof_factor
        # for wavelength spread
        # reserve for 1d calculation
        A_value = self._cal_A_value(lamb, l_ssa, l_sad)
        sigma_wave_1, sigma_wave_1_1d = self.get_variance_wave(A_value,
                                                               radius, l_two, lamb_spread,
                                                               phi, 'radial', 'on')
        sigma_wave_1 /= tof_factor
        sigma_wave_1_1d /= tof_factor
        # for 1d
        variance_1d_1 = (sigma_1 + sigma_1grav1d) / 2 + sigma_wave_1_1d
        # normalize
        variance_1d_1 = knot * knot * variance_1d_1 / 12

        # for 2d
        #sigma_1 += sigma_wave_1
        # normalize
        sigma_1 = knot * sqrt(sigma_1 / 12)
        sigma_r = knot * sqrt(sigma_wave_1 / (tof_factor *12))
        # sigma in the phi/y direction
        # for source apperture
        sigma_2 = self.get_variance(rone, l1_cor, phi, comp2)

        # for sample apperture
        sigma_2 += self.get_variance(rtwo, lp_cor, phi, comp2)

        # for detector pix
        sigma_2 += self.get_variance(rthree, l_two, phi, comp2)

        # for gravity term for 1d
        sigma_2grav1d = self.get_variance_gravity(l_ssa, l_sad, lamb,
                                                  lamb_spread, phi, comp2, 'on') / tof_factor

        # for wavelength spread
        # reserve for 1d calculation
        sigma_wave_2, sigma_wave_2_1d = self.get_variance_wave(A_value,
                                                               radius, l_two, lamb_spread,
                                                               phi, 'phi', 'on')
        sigma_wave_2 /= tof_factor
        sigma_wave_2_1d /= tof_factor
        # for 1d
        variance_1d_2 = (sigma_2 + sigma_2grav1d) / 2 + sigma_wave_2_1d
        # normalize
        variance_1d_2 = knot * knot * variance_1d_2 / 12

        # for 2d
        #sigma_2 =  knot*sqrt(sigma_2/12)
        #sigma_2 += sigma_wave_2
        # normalize
        sigma_2 = knot * sqrt(sigma_2 / 12)
        sigma1d = sqrt(variance_1d_1 + variance_1d_2)
        # set sigmas
        self.sigma_1 = sigma_1
        self.sigma_lamd = sigma_r
        self.sigma_2 = sigma_2
        self.sigma_1d = sigma1d
        return qr_value, phi, sigma_1, sigma_2, sigma_r, sigma1d

    def _within_detector_range(self, qx_value, qy_value):
        """
        check if qvalues are within detector range
        """
        # detector range
        detector_qx_min = self.detector_qx_min
        detector_qx_max = self.detector_qx_max
        detector_qy_min = self.detector_qy_min
        detector_qy_max = self.detector_qy_max
        if self.qxmin_limit > detector_qx_min:
            self.qxmin_limit = detector_qx_min
        if self.qxmax_limit < detector_qx_max:
            self.qxmax_limit = detector_qx_max
        if self.qymin_limit > detector_qy_min:
            self.qymin_limit = detector_qy_min
        if self.qymax_limit < detector_qy_max:
            self.qymax_limit = detector_qy_max
        if qx_value < detector_qx_min or qx_value > detector_qx_max:
            return False
        if qy_value < detector_qy_min or qy_value > detector_qy_max:
            return False
        return True

    def get_image(self, qx_value, qy_value, sigma_1, sigma_2, sigma_r,
                  qx_min, qx_max, qy_min, qy_max,
                  coord='cartesian', full_cal=True):
        """
        Get the resolution in polar coordinate ready to plot
        : qx_value: qx_value value
        : qy_value: qy_value value
        : sigma_1: variance in r direction
        : sigma_2: variance in phi direction
        : coord: coordinate system of image, 'polar' or 'cartesian'
        """
        # Get  qx_max and qy_max...
        self._get_detector_qxqy_pixels()

        qr_value, phi = self._get_polar_value(qx_value, qy_value)

        # Check whether the q value is within the detector range
        if qx_min < self.qx_min:
            self.qx_min = qx_min
            #raise ValueError, msg
        if qx_max > self.qx_max:
            self.qx_max = qx_max
            #raise ValueError, msg
        if qy_min < self.qy_min:
            self.qy_min = qy_min
            #raise ValueError, msg
        if qy_max > self.qy_max:
            self.qy_max = qy_max
            #raise ValueError, msg
        if not full_cal:
            return None

        # Make an empty graph in the detector scale
        dx_size = (self.qx_max - self.qx_min) / (1000 - 1)
        dy_size = (self.qy_max - self.qy_min) / (1000 - 1)
        x_val = np.arange(self.qx_min, self.qx_max, dx_size)
        y_val = np.arange(self.qy_max, self.qy_min, -dy_size)
        q_1, q_2 = np.meshgrid(x_val, y_val)
        #q_phi = numpy.arctan(q_1,q_2)
        # check whether polar or cartesian
        if coord == 'polar':
            # Find polar values
            qr_value, phi = self._get_polar_value(qx_value, qy_value)
            q_1, q_2 = self._rotate_z(q_1, q_2, phi)
            qc_1 = qr_value
            qc_2 = 0.0
            # Calculate the 2D Gaussian distribution image
            image = self._gaussian2d_polar(q_1, q_2, qc_1, qc_2,
                                           sigma_1, sigma_2, sigma_r)
        else:
            # catesian coordinate
            # qx_center
            qc_1 = qx_value
            # qy_center
            qc_2 = qy_value

            # Calculate the 2D Gaussian distribution image
            image = self._gaussian2d(q_1, q_2, qc_1, qc_2,
                                     sigma_1, sigma_2, sigma_r)
        # out side of detector
        if not self._within_detector_range(qx_value, qy_value):
            image *= 0.0
            self.intensity = 0.0
            #return self.image

        # Add it if there are more than one inputs.
        if len(self.image_lam) > 0:
            self.image_lam += image * self.intensity
        else:
            self.image_lam = image * self.intensity

        return self.image_lam

    def plot_image(self, image):
        """
        Plot image using pyplot
        : image: 2d resolution image

        : return plt: pylab object
        """
        import matplotlib.pyplot as plt

        self.plot = plt
        plt.xlabel('$\\rm{Q}_{x} [A^{-1}]$')
        plt.ylabel('$\\rm{Q}_{y} [A^{-1}]$')
        # Max value of the image
        # max = numpy.max(image)
        qx_min, qx_max, qy_min, qy_max = self.get_detector_qrange()

        # Image
        im = plt.imshow(image,
                        extent=[qx_min, qx_max, qy_min, qy_max])

        # bilinear interpolation to make it smoother
        im.set_interpolation('bilinear')

        return plt

    def reset_image(self):
        """
        Reset image to default (=[])
        """
        self.image = []

    def get_variance(self, size=[], distance=0, phi=0, comp='radial'):
        """
        Get the variance when the slit/pinhole size is given
        : size: list that can be one(diameter for circular) or two components(lengths for rectangular)
        : distance: [z, x] where z along the incident beam, x // qx_value
        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'

        : return variance: sigma^2
        """
        # check the length of size (list)
        len_size = len(size)

        # define sigma component direction
        if comp == 'radial':
            phi_x = math.cos(phi)
            phi_y = math.sin(phi)
        elif comp == 'phi':
            phi_x = math.sin(phi)
            phi_y = math.cos(phi)
        elif comp == 'x':
            phi_x = 1
            phi_y = 0
        elif comp == 'y':
            phi_x = 0
            phi_y = 1
        else:
            phi_x = 0
            phi_y = 0
        # calculate each component
        # for pinhole w/ radius = size[0]/2
        if len_size == 1:
            x_comp = (0.5 * size[0]) * sqrt(3)
            y_comp = 0
        # for rectangular slit
        elif len_size == 2:
            x_comp = size[0] * phi_x
            y_comp = size[1] * phi_y
        # otherwise
        else:
            raise ValueError, " Improper input..."
        # get them squared
        sigma = x_comp * x_comp
        sigma += y_comp * y_comp
        # normalize by distance
        sigma /= (distance * distance)

        return sigma

    def get_variance_wave(self, A_value, radius, distance, spread, phi,
                          comp='radial', switch='on'):
        """
        Get the variance when the wavelength spread is given

        : radius: the radial distance from the beam center to the pix of q
        : distance: sample to detector distance
        : spread: wavelength spread (ratio)
        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'

        : return variance: sigma^2 for 2d, sigma^2 for 1d [tuple]
        """
        if switch.lower() == 'off':
            return 0, 0
        # check the singular point
        if distance == 0 or comp == 'phi':
            return 0, 0
        else:
            # calculate sigma^2 for 1d
            sigma1d = 2 * math.pow(radius/distance*spread, 2)
            if comp == 'x':
                sigma1d *= (math.cos(phi)*math.cos(phi))
            elif comp == 'y':
                sigma1d *= (math.sin(phi)*math.sin(phi))
            else:
                sigma1d *= 1
            # sigma^2 for 2d
            # shift the coordinate due to the gravitational shift
            rad_x = radius * math.cos(phi)
            rad_y = A_value - radius * math.sin(phi)
            radius = math.sqrt(rad_x * rad_x + rad_y * rad_y)
            # new phi
            phi = math.atan2(-rad_y, rad_x)
            self.gravity_phi = phi
            # calculate sigma^2
            sigma = 2 * math.pow(radius/distance*spread, 2)
            if comp == 'x':
                sigma *= (math.cos(phi)*math.cos(phi))
            elif comp == 'y':
                sigma *= (math.sin(phi)*math.sin(phi))
            else:
                sigma *= 1

            return sigma, sigma1d

    def get_variance_gravity(self, s_distance, d_distance, wavelength, spread,
                             phi, comp='radial', switch='on'):
        """
        Get the variance from gravity when the wavelength spread is given

        : s_distance: source to sample distance
        : d_distance: sample to detector distance
        : wavelength: wavelength
        : spread: wavelength spread (ratio)
        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'

        : return variance: sigma^2
        """
        if switch.lower() == 'off':
            return 0
        if self.mass == 0.0:
            return 0
        # check the singular point
        if d_distance == 0 or comp == 'x':
            return 0
        else:
            a_value = self._cal_A_value(None, s_distance, d_distance)
            # calculate sigma^2
            sigma = math.pow(a_value / d_distance, 2)
            sigma *= math.pow(wavelength, 4)
            sigma *= math.pow(spread, 2)
            sigma *= 8
            return sigma

    def _cal_A_value(self, lamda, s_distance, d_distance):
        """
        Calculate A value for gravity

        : s_distance: source to sample distance
        : d_distance: sample to detector distance
        """
        # neutron mass in cgs unit
        self.mass = self.get_neutron_mass()
        # plank constant in cgs unit
        h_constant = _PLANK_H
        # gravity in cgs unit
        gravy = _GRAVITY
        # m/h
        m_over_h = self.mass / h_constant
        # A value
        a_value = d_distance * (s_distance + d_distance)
        a_value *= math.pow(m_over_h / 2, 2)
        a_value *= gravy
        # unit correction (1/cm to 1/A) for A and d_distance below
        a_value *= 1.0E-16
        # if lamda is give (broad meanning of A)  return 2* lamda^2 * A
        if lamda is not None:
            a_value *= (4 * lamda * lamda)
        return a_value

    def get_intensity(self):
        """
        Get intensity
        """
        return self.wave.intensity

    def get_wavelength(self):
        """
        Get wavelength
        """
        return self.wave.wavelength

    def get_default_spectrum(self):
        """
        Get default_spectrum
        """
        return self.wave.get_default_spectrum()

    def get_spectrum(self):
        """
        Get _spectrum
        """
        return self.wave.get_spectrum()

    def get_wavelength_spread(self):
        """
        Get wavelength spread
        """
        return self.wave.wavelength_spread

    def get_neutron_mass(self):
        """
        Get Neutron mass
        """
        return self.wave.mass

    def get_source_aperture_size(self):
        """
        Get source aperture size
        """
        return self.aperture.source_size

    def get_sample_aperture_size(self):
        """
        Get sample aperture size
        """
        return self.aperture.sample_size

    def get_detector_pix_size(self):
        """
        Get detector pixel size
        """
        return self.detector.pix_size

    def get_detector_size(self):
        """
        Get detector size
        """
        return self.detector.size

    def get_source2sample_distance(self):
        """
        Get detector source2sample_distance
        """
        return self.aperture.sample_distance

    def get_sample2sample_distance(self):
        """
        Get detector sampleslitsample_distance
        """
        return self.sample.distance

    def get_sample2detector_distance(self):
        """
        Get detector sample2detector_distance
        """
        return self.detector.distance

    def set_intensity(self, intensity):
        """
        Set intensity
        """
        self.wave.set_intensity(intensity)

    def set_wave(self, wavelength):
        """
        Set wavelength list or wavelength
        """
        if wavelength.__class__.__name__ == 'list':
            self.wave.set_wave_list(wavelength)
        elif wavelength.__class__.__name__ == 'float':
            self.wave.set_wave_list([wavelength])
            #self.set_wavelength(wavelength)
        else:
            raise

    def set_wave_spread(self, wavelength_spread):
        """
        Set wavelength spread  or wavelength spread
        """
        if wavelength_spread.__class__.__name__ == 'list':
            self.wave.set_wave_spread_list(wavelength_spread)
        elif wavelength_spread.__class__.__name__ == 'float':
            self.wave.set_wave_spread_list([wavelength_spread])
        else:
            raise

    def set_wavelength(self, wavelength):
        """
        Set wavelength
        """
        self.wavelength = wavelength
        self.wave.set_wavelength(wavelength)

    def set_spectrum(self, spectrum):
        """
        Set spectrum
        """
        self.spectrum = spectrum
        self.wave.set_spectrum(spectrum)

    def set_wavelength_spread(self, wavelength_spread):
        """
        Set wavelength spread
        """
        self.wavelength_spread = wavelength_spread
        self.wave.set_wavelength_spread(wavelength_spread)

    def set_wave_list(self, wavelength_list, wavelengthspread_list):
        """
        Set wavelength and its spread list
        """
        self.wave.set_wave_list(wavelength_list)
        self.wave.set_wave_spread_list(wavelengthspread_list)

    def get_wave_list(self):
        """
        Set wavelength spread
        """
        return self.wave.get_wave_list()

    def get_intensity_list(self):
        """
        Set wavelength spread
        """
        return self.wave.get_intensity_list()

    def set_source_aperture_size(self, size):
        """
        Set source aperture size

        : param size: [dia_value] or [x_value, y_value]
        """
        if len(size) < 1 or len(size) > 2:
            raise RuntimeError, "The length of the size must be one or two."
        self.aperture.set_source_size(size)

    def set_neutron_mass(self, mass):
        """
        Set Neutron mass
        """
        self.wave.set_mass(mass)
        self.mass = mass

    def set_sample_aperture_size(self, size):
        """
        Set sample aperture size

        : param size: [dia_value] or [xheight_value, yheight_value]
        """
        if len(size) < 1 or len(size) > 2:
            raise RuntimeError, "The length of the size must be one or two."
        self.aperture.set_sample_size(size)

    def set_detector_pix_size(self, size):
        """
        Set detector pixel size
        """
        self.detector.set_pix_size(size)

    def set_detector_size(self, size):
        """
        Set detector size in number of pixels
        : param size: [pixel_nums] or [x_pix_num, yx_pix_num]
        """
        self.detector.set_size(size)

    def set_source2sample_distance(self, distance):
        """
        Set detector source2sample_distance

        : param distance: [distance, x_offset]
        """
        if len(distance) < 1 or len(distance) > 2:
            raise RuntimeError, "The length of the size must be one or two."
        self.aperture.set_sample_distance(distance)

    def set_sample2sample_distance(self, distance):
        """
        Set detector sample_slit2sample_distance

        : param distance: [distance, x_offset]
        """
        if len(distance) < 1 or len(distance) > 2:
            raise RuntimeError, "The length of the size must be one or two."
        self.sample.set_distance(distance)

    def set_sample2detector_distance(self, distance):
        """
        Set detector sample2detector_distance

        : param distance: [distance, x_offset]
        """
        if len(distance) < 1 or len(distance) > 2:
            raise RuntimeError, "The length of the size must be one or two."
        self.detector.set_distance(distance)

    def get_all_instrument_params(self):
        """
        Get all instrumental parameters
        """
        self.mass = self.get_neutron_mass()
        self.spectrum = self.get_spectrum()
        self.source_aperture_size = self.get_source_aperture_size()
        self.sample_aperture_size = self.get_sample_aperture_size()
        self.detector_pix_size = self.get_detector_pix_size()
        self.detector_size = self.get_detector_size()
        self.source2sample_distance = self.get_source2sample_distance()
        self.sample2sample_distance = self.get_sample2sample_distance()
        self.sample2detector_distance = self.get_sample2detector_distance()

    def get_detector_qrange(self):
        """
        get max detector q ranges

        : return: qx_min, qx_max, qy_min, qy_max tuple
        """
        if len(self.qxrange) != 2 or len(self.qyrange) != 2:
            return None
        qx_min = self.qxrange[0]
        qx_max = self.qxrange[1]
        qy_min = self.qyrange[0]
        qy_max = self.qyrange[1]

        return qx_min, qx_max, qy_min, qy_max

    def _rotate_z(self, x_value, y_value, theta=0.0):
        """
        Rotate x-y cordinate around z-axis by theta
        : x_value: numpy array of x values
        : y_value: numpy array of y values
        : theta: angle to rotate by in rad

        :return: x_prime, y-prime
        """
        # rotate by theta
        x_prime = x_value * math.cos(theta) + y_value * math.sin(theta)
        y_prime = -x_value * math.sin(theta) + y_value * math.cos(theta)

        return x_prime, y_prime

    def _gaussian2d(self, x_val, y_val, x0_val, y0_val,
                    sigma_x, sigma_y, sigma_r):
        """
        Calculate 2D Gaussian distribution
        : x_val: x value
        : y_val: y value
        : x0_val: mean value in x-axis
        : y0_val: mean value in y-axis
        : sigma_x: variance in x-direction
        : sigma_y: variance in y-direction

        : return: gaussian (value)
        """
        # phi values at each points (not at the center)
        x_value = x_val - x0_val
        y_value = y_val - y0_val
        phi_i = np.arctan2(y_val, x_val)

        # phi correction due to the gravity shift (in phi)
        phi_0 = math.atan2(y0_val, x0_val)
        phi_i = phi_i - phi_0 + self.gravity_phi

        sin_phi = np.sin(self.gravity_phi)
        cos_phi = np.cos(self.gravity_phi)

        x_p = x_value * cos_phi + y_value * sin_phi
        y_p = -x_value * sin_phi + y_value * cos_phi

        new_sig_x = sqrt(sigma_r * sigma_r / (sigma_x * sigma_x) + 1)
        new_sig_y = sqrt(sigma_r * sigma_r / (sigma_y * sigma_y) + 1)
        new_x = x_p * cos_phi / new_sig_x - y_p * sin_phi
        new_x /= sigma_x
        new_y = x_p * sin_phi / new_sig_y + y_p * cos_phi
        new_y /= sigma_y

        nu_value = -0.5 * (new_x * new_x + new_y * new_y)

        gaussian = np.exp(nu_value)
        # normalizing factor correction
        gaussian /= gaussian.sum()

        return gaussian

    def _gaussian2d_polar(self, x_val, y_val, x0_val, y0_val,
                          sigma_x, sigma_y, sigma_r):
        """
        Calculate 2D Gaussian distribution for polar coodinate
        : x_val: x value
        : y_val: y value
        : x0_val: mean value in x-axis
        : y0_val: mean value in y-axis
        : sigma_x: variance in r-direction
        : sigma_y: variance in phi-direction
        : sigma_r: wavelength variance in r-direction

        : return: gaussian (value)
        """
        sigma_x = sqrt(sigma_x * sigma_x + sigma_r * sigma_r)
        # call gaussian1d
        gaussian = self._gaussian1d(x_val, x0_val, sigma_x)
        gaussian *= self._gaussian1d(y_val, y0_val, sigma_y)

        # normalizing factor correction
        if sigma_x != 0 and sigma_y != 0:
            gaussian *= sqrt(2 * pi)
        return gaussian

    def _gaussian1d(self, value, mean, sigma):
        """
        Calculate 1D Gaussian distribution
        : value: value
        : mean: mean value
        : sigma: variance

        : return: gaussian (value)
        """
        # default
        gaussian = 1.0
        if sigma != 0:
            # get exponent
            nu_value = (value - mean) / sigma
            nu_value *= nu_value
            nu_value *= -0.5
            gaussian *= np.exp(nu_value)
            gaussian /= sigma
            # normalize
            gaussian /= sqrt(2 * pi)

        return gaussian

    def _atan_phi(self, qy_value, qx_value):
        """
        Find the angle phi of q on the detector plane for qx_value, qy_value given
        : qx_value: x component of q
        : qy_value: y component of q

        : return phi: the azimuthal angle of q on x-y plane
        """
        phi = math.atan2(qy_value, qx_value)
        return phi

    def _get_detector_qxqy_pixels(self):
        """
        Get the pixel positions of the detector in the qx_value-qy_value space
        """

        # update all param values
        self.get_all_instrument_params()

        # wavelength
        wavelength = self.wave.wavelength
        # Gavity correction
        delta_y = self._get_beamcenter_drop()  # in cm

        # detector_pix size
        detector_pix_size = self.detector_pix_size
        # Square or circular pixel
        if len(detector_pix_size) == 1:
            pix_x_size = detector_pix_size[0]
            pix_y_size = detector_pix_size[0]
        # rectangular pixel pixel
        elif len(detector_pix_size) == 2:
            pix_x_size = detector_pix_size[0]
            pix_y_size = detector_pix_size[1]
        else:
            raise ValueError, " Input value format error..."
        # Sample to detector distance = sample slit to detector
        # minus sample offset
        sample2detector_distance = self.sample2detector_distance[0] - \
                                    self.sample2sample_distance[0]
        # detector offset in x-direction
        detector_offset = 0
        try:
            detector_offset = self.sample2detector_distance[1]
        except:
            logger.error(sys.exc_value)

        # detector size in [no of pix_x,no of pix_y]
        detector_pix_nums_x = self.detector_size[0]

        # get pix_y if it exists, otherwse take it from [0]
        try:
            detector_pix_nums_y = self.detector_size[1]
        except:
            detector_pix_nums_y = self.detector_size[0]

        # detector offset in pix number
        offset_x = detector_offset / pix_x_size
        offset_y = delta_y / pix_y_size

        # beam center position in pix number (start from 0)
        center_x, center_y = self._get_beamcenter_position(detector_pix_nums_x,
                                                           detector_pix_nums_y,
                                                           offset_x, offset_y)
        # distance [cm] from the beam center on detector plane
        detector_ind_x = np.arange(detector_pix_nums_x)
        detector_ind_y = np.arange(detector_pix_nums_y)

        # shif 0.5 pixel so that pix position is at the center of the pixel
        detector_ind_x = detector_ind_x + 0.5
        detector_ind_y = detector_ind_y + 0.5

        # the relative postion from the beam center
        detector_ind_x = detector_ind_x - center_x
        detector_ind_y = detector_ind_y - center_y

        # unit correction in cm
        detector_ind_x = detector_ind_x * pix_x_size
        detector_ind_y = detector_ind_y * pix_y_size

        qx_value = np.zeros(len(detector_ind_x))
        qy_value = np.zeros(len(detector_ind_y))
        i = 0

        for indx in detector_ind_x:
            qx_value[i] = self._get_qx(indx, sample2detector_distance, wavelength)
            i += 1
        i = 0
        for indy in detector_ind_y:
            qy_value[i] = self._get_qx(indy, sample2detector_distance, wavelength)
            i += 1

        # qx_value and qy_value values in array
        qx_value = qx_value.repeat(detector_pix_nums_y)
        qx_value = qx_value.reshape(detector_pix_nums_x, detector_pix_nums_y)
        qy_value = qy_value.repeat(detector_pix_nums_x)
        qy_value = qy_value.reshape(detector_pix_nums_y, detector_pix_nums_x)
        qy_value = qy_value.transpose()

        # p min and max values among the center of pixels
        self.qx_min = np.min(qx_value)
        self.qx_max = np.max(qx_value)
        self.qy_min = np.min(qy_value)
        self.qy_max = np.max(qy_value)

        # Appr. min and max values of the detector display limits
        # i.e., edges of the last pixels.
        self.qy_min += self._get_qx(-0.5 * pix_y_size,
                                    sample2detector_distance, wavelength)
        self.qy_max += self._get_qx(0.5 * pix_y_size,
                                    sample2detector_distance, wavelength)
        #if self.qx_min == self.qx_max:
        self.qx_min += self._get_qx(-0.5 * pix_x_size,
                                    sample2detector_distance, wavelength)
        self.qx_max += self._get_qx(0.5 * pix_x_size,
                                    sample2detector_distance, wavelength)

        # min and max values of detecter
        self.detector_qx_min = self.qx_min
        self.detector_qx_max = self.qx_max
        self.detector_qy_min = self.qy_min
        self.detector_qy_max = self.qy_max

        # try to set it as a Data2D otherwise pass (not required for now)
        try:
            from sas.sascalc.dataloader.data_info import Data2D
            output = Data2D()
            inten = np.zeros_like(qx_value)
            output.data = inten
            output.qx_data = qx_value
            output.qy_data = qy_value
        except:
            logger.error(sys.exc_value)

        return output

    def _get_qx(self, dx_size, det_dist, wavelength):
        """
        :param dx_size: x-distance from beam center [cm]
        :param det_dist: sample to detector distance [cm]

        :return: q-value at the given position
        """
        # Distance from beam center in the plane of detector
        plane_dist = dx_size
        # full scattering angle on the x-axis
        theta = np.arctan(plane_dist / det_dist)
        qx_value = (2.0 * pi / wavelength) * np.sin(theta)
        return qx_value

    def _get_polar_value(self, qx_value, qy_value):
        """
        Find qr_value and phi from qx_value and qy_value values

        : return qr_value, phi
        """
        # find |q| on detector plane
        qr_value = sqrt(qx_value*qx_value + qy_value*qy_value)
        # find angle phi
        phi = self._atan_phi(qy_value, qx_value)

        return qr_value, phi

    def _get_beamcenter_position(self, num_x, num_y, offset_x, offset_y):
        """
        :param num_x: number of pixel in x-direction
        :param num_y: number of pixel in y-direction
        :param offset: detector offset in x-direction in pix number

        :return: pix number; pos_x, pos_y in pix index
        """
        # beam center position
        pos_x = num_x / 2
        pos_y = num_y / 2

        # correction for offset
        pos_x += offset_x
        # correction for gravity that is always negative
        pos_y -= offset_y

        return pos_x, pos_y

    def _get_beamcenter_drop(self):
        """
        Get the beam center drop (delta y) in y diection due to gravity

        :return delta y: the beam center drop in cm
        """
        # Check if mass == 0 (X-ray).
        if self.mass == 0:
            return 0
        # Covert unit from A to cm
        unit_cm = 1e-08
        # Velocity of neutron in horizontal direction (~ actual velocity)
        velocity = _PLANK_H / (self.mass * self.wave.wavelength * unit_cm)
        # Compute delta y
        delta_y = 0.5
        delta_y *= _GRAVITY
        sampletodetector = self.sample2detector_distance[0] - \
                                    self.sample2sample_distance[0]
        delta_y *= sampletodetector
        delta_y *= (self.source2sample_distance[0] + self.sample2detector_distance[0])
        delta_y /= (velocity * velocity)

        return delta_y


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class FaChain extends React.Component<IconBaseProps> { }
export = FaChain;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.kylin.engine.streaming;

/**
 */
public class BootstrapConfig {

    private String cubeName;
    private long start = 0L;
    private long end = 0L;

    private boolean fillGap;

    public long getStart() {
        return start;
    }

    public void setStart(long start) {
        this.start = start;
    }

    public long getEnd() {
        return end;
    }

    public void setEnd(long end) {
        this.end = end;
    }

    public String getCubeName() {
        return cubeName;
    }

    public void setCubeName(String cubeName) {
        this.cubeName = cubeName;
    }

    public boolean isFillGap() {
        return fillGap;
    }

    public void setFillGap(boolean fillGap) {
        this.fillGap = fillGap;
    }
}


text:
package org.emberjs.codeInsight.tags;

import com.intellij.html.impl.RelaxedHtmlFromSchemaElementDescriptor;
import com.intellij.lang.javascript.index.JSNamedElementProxy;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.xml.XmlDocumentImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlElementsGroup;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.schema.AnyXmlAttributeDescriptor;
import org.emberjs.codeInsight.ComponentUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

/**
 * @author Dennis.Ushakov
 */
public class EmberJSTagDescriptor implements XmlElementDescriptor {
    protected final String myName;
    private final JSNamedElementProxy myDeclaration;

    public EmberJSTagDescriptor(String name, JSNamedElementProxy declaration) {
        myName = name;
        myDeclaration = declaration;
    }

    @Override
    public String getQualifiedName() {
        return myName;
    }

    @Override
    public String getDefaultName() {
        return myName;
    }

    @Override
    public XmlElementDescriptor[] getElementsDescriptors(XmlTag context) {
        XmlDocumentImpl xmlDocument = PsiTreeUtil.getParentOfType(context, XmlDocumentImpl.class);
        if (xmlDocument == null) return EMPTY_ARRAY;
        return xmlDocument.getRootTagNSDescriptor().getRootElementsDescriptors(xmlDocument);
    }

    @Override
    public XmlElementDescriptor getElementDescriptor(XmlTag childTag, XmlTag contextTag) {
        XmlTag parent = contextTag.getParentTag();
        if (parent == null) return null;
        final XmlNSDescriptor descriptor = parent.getNSDescriptor(childTag.getNamespace(), true);
        return descriptor == null ? null : descriptor.getElementDescriptor(childTag);
    }

    @Override
    public XmlAttributeDescriptor[] getAttributesDescriptors(@Nullable XmlTag context) {
        final String string = getDeclaration().getIndexItem().getTypeString();
        final String attributes = string.split(";", -1)[3];
        final String[] split = attributes.split(",");
        final XmlAttributeDescriptor[] result;
        if (split.length == 1 && split[0].isEmpty()) {
            result = XmlAttributeDescriptor.EMPTY;
        } else {
            result = new XmlAttributeDescriptor[split.length];
            for (int i = 0; i < split.length; i++) {
                result[i] = new AnyXmlAttributeDescriptor(ComponentUtil.getAttributeName(split[i]));
            }
        }
        final XmlAttributeDescriptor[] commonAttributes = {
                RelaxedHtmlFromSchemaElementDescriptor.getAttributeDescriptorFromFacelets(string, context)
        };
        return RelaxedHtmlFromSchemaElementDescriptor.addAttrDescriptorsForFacelets(context, ArrayUtil.mergeArrays(result, commonAttributes));
    }

    @Nullable
    @Override
    public XmlAttributeDescriptor getAttributeDescriptor(XmlAttribute attribute) {
        return getAttributeDescriptor(attribute.getName(), attribute.getParent());
    }

    @Nullable
    @Override
    public XmlAttributeDescriptor getAttributeDescriptor(@NonNls final String attributeName, @Nullable XmlTag context) {
        return ContainerUtil.find(getAttributesDescriptors(context), new Condition<XmlAttributeDescriptor>() {
            @Override
            public boolean value(XmlAttributeDescriptor descriptor) {
                return attributeName.equals(descriptor.getName());
            }
        });
    }

    @Override
    public XmlNSDescriptor getNSDescriptor() {
        return null;
    }

    @Nullable
    @Override
    public XmlElementsGroup getTopGroup() {
        return null;
    }

    @Override
    public int getContentType() {
        return CONTENT_TYPE_ANY;
    }

    @Nullable
    @Override
    public String getDefaultValue() {
        return null;
    }

    @Override
    public JSNamedElementProxy getDeclaration() {
        return myDeclaration;
    }

    @Override
    public String getName(PsiElement context) {
        return getName();
    }

    @Override
    public String getName() {
        return myName;
    }

    @Override
    public void init(PsiElement element) {
    }

    @Override
    public Object[] getDependences() {
        return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }
}


text:
<reddot:cms>
    <if>
        <query valuea="Context:CurrentIndex.Id" operator="==" valueb="Context:FirstIndex.Id">
            <htmltext>Index<navigation:nextlevel></htmltext>
        </query>
        <query type="else">
            <if>
                <query valuea="Context:CurrentIndex.Id" operator="==" valueb="Context:LastIndex.Id">
                    <htmltext>/<%!! Context:CurrentIndex.Headline !!%></htmltext>
                </query>
                <query type="else">
                    <htmltext>/<%!! Context:CurrentIndex.Headline !!%><navigation:nextlevel></htmltext>
                </query>
            </if>
        </query>
    </if>
</reddot:cms>


text:
""" CLI for the deliver subcommand
"""
import click
import logging

from taca.utils.misc import send_mail
from taca.utils.config import load_yaml_config
from taca_ngi_pipeline.deliver import deliver as _deliver
from taca_ngi_pipeline.deliver import deliver_grus as _deliver_grus
from taca_ngi_pipeline.deliver import deliver_dds as _deliver_dds

logger = logging.getLogger(__name__)

#######################################
# deliver
#######################################

@click.group()
@click.pass_context
@click.option('--deliverypath', type=click.STRING, help="Deliver to this destination folder")
@click.option('--stagingpath', type=click.STRING, help="Stage the delivery under this path")
@click.option('--uppnexid', type=click.STRING, help="Use this UppnexID instead of fetching from database")
@click.option('--operator', type=click.STRING, default=None, multiple=True,
              help="Email address to notify operator at. Multiple operators can be specified")
@click.option('--stage_only', is_flag=True, default=False,
              help="Only stage the delivery but do not transfer any files")
@click.option('--ignore-analysis-status', is_flag=True, default=False,
              help="Do not check analysis status upon delivery. To be used only when delivering projects without BP (e.g., WHG)")
@click.option('--force', is_flag=True, default=False,
              help="Force delivery, even if e.g. analysis has not finished or sample has already been delivered")
@click.option('--cluster', type=click.Choice(['grus', 'dds']), # Can be expanded to include future clusters
              help="Specify to which cluster one wants to deliver")
@click.option('--generate_xml_and_manifest_files_only', is_flag=True,  default=False,
              help="Explicitly generate xml amd manifest files for ENA submission on a staged project")

def deliver(ctx, deliverypath, stagingpath,
            uppnexid, operator, stage_only,
            force, cluster, ignore_analysis_status,
            generate_xml_and_manifest_files_only):
    """ Deliver methods entry point
    """
    if deliverypath is None:
        del ctx.params['deliverypath']
    if stagingpath is None:
        del ctx.params['stagingpath']
    if uppnexid is None:
        del ctx.params['uppnexid']
    if operator is None or len(operator) == 0:
        del ctx.params['operator']

# deliver subcommands
# project delivery
@deliver.command()
@click.pass_context
@click.argument('projectid', type=click.STRING, nargs=-1)
@click.option('--snic-api-credentials',
            default=None,
            envvar='SNIC_API_STOCKHOLM',
            type=click.File('r'),
            help='Path to SNIC-API credentials to create delivery projects')
@click.option('--statusdb-config',
            default=None,
            envvar='STATUS_DB_CONFIG',
            type=click.File('r'),
            help='Path to statusdb-configuration')
@click.option('--order-portal',
            default=None,
            envvar='ORDER_PORTAL',
            type=click.File('r'),
            help='Path to order portal credantials to retrive PI email')
@click.option('--pi-email',
            default=None,
            type=click.STRING,
            help='pi-email, to be specified if PI-email stored in statusdb does not correspond SUPR PI-email')
@click.option('--sensitive/--no-sensitive',
            default=True,
            help='flag to specify if data contained in the project is sensitive or not')
@click.option('--hard-stage-only',
            is_flag=True,
            default=False,
            help='Perform all the delivery actions but does not run to_mover (to be used for semi-manual deliveries)')
@click.option('--add-user',
            multiple=True,
            type=click.STRING,
            help='User email address to add in GRUS delivery project. Multiple user can be given by calling parameter multiple times')
@click.option('--fc-delivery',
              type=click.STRING,
              help='Flowcell id for delivering whole Illumnina run folder')
@click.option('--project-desc',
            default=None,
            type=click.STRING,
            help='Project description, to be specified if project not in order portal (DDS only)')
@click.option('--ignore-orderportal-members',
            is_flag=True,
            default=False,
            help='Do not fetch member information from the order portal')

def project(ctx, projectid,
            snic_api_credentials=None, statusdb_config=None,
            order_portal=None, pi_email=None,
            sensitive=True, hard_stage_only=False,
            add_user=None, fc_delivery=False,
            project_desc=None, ignore_orderportal_members=False):
    """ Deliver the specified projects to the specified destination
    """
    for pid in projectid:
        if ctx.parent.params['cluster']:
            if statusdb_config == None:
                logger.error("--statusdb-config or env variable $STATUS_DB_CONFIG"
                             " need to be set to perform {} delivery".format(ctx.parent.params['cluster']))
                return 1
            load_yaml_config(statusdb_config.name)
            if order_portal == None:
                logger.error("--order-portal or env variable $ORDER_PORTAL"
                             " need to be set to perform {} delivery".format(ctx.parent.params['cluster']))
                return 1
            load_yaml_config(order_portal.name)
        if not ctx.parent.params['cluster']: # Soft stage case
            d = _deliver.ProjectDeliverer(
                pid,
                **ctx.parent.params)
        elif ctx.parent.params['cluster'] == 'grus': # Hard stage and deliver to GRUS
            if snic_api_credentials == None:
                logger.error("--snic-api-credentials or env variable $SNIC_API_STOCKHOLM need to be set to perform GRUS delivery")
                return 1
            load_yaml_config(snic_api_credentials.name)
            d = _deliver_grus.GrusProjectDeliverer(
                projectid=pid,
                pi_email=pi_email,
                sensitive=sensitive,
                hard_stage_only=hard_stage_only,
                add_user=list(set(add_user)),
                fcid=fc_delivery,
                **ctx.parent.params)
        elif ctx.parent.params['cluster'] == 'dds': # Hard stage and deliver using DDS
            d = _deliver_dds.DDSProjectDeliverer(
                projectid=pid,
                pi_email=pi_email,
                sensitive=sensitive,
                add_user=list(set(add_user)),
                fcid=fc_delivery,
                do_release=False,
                project_description=project_desc,
                ignore_orderportal_members=ignore_orderportal_members,
                **ctx.parent.params)

        if fc_delivery:
            _exec_fn(d, d.deliver_run_folder)
        else:
            _exec_fn(d, d.deliver_project)

# sample delivery
#TODO: not used? remove?
@deliver.command()
@click.pass_context
@click.argument('projectid', type=click.STRING, nargs=1)
@click.argument('sampleid', type=click.STRING, nargs=-1)
def sample(ctx, projectid, sampleid):
    """ Deliver the specified sample to the specified destination
    """
    for sid in sampleid:
        if not ctx.parent.params['cluster']: # Soft stage case
            d = _deliver.SampleDeliverer(
                projectid,
                sid,
                **ctx.parent.params)
        elif ctx.parent.params['cluster'] == 'grus':
            logger.error("When delivering to grus only project can be specified, not sample")
            return 1
        elif ctx.parent.params['cluster'] == 'dds':
            logger.error("When delivering with DDS only project can be specified, not sample")
            return 1
        _exec_fn(d, d.deliver_sample)

# helper function to handle error reporting
def _exec_fn(obj, fn):
    try:
        if fn():
            logger.info(
                "{} processed successfully".format(str(obj)))
        else:
            logger.info(
                "{} processed with some errors, check log".format(
                    str(obj)))
    except Exception as e:
        logger.exception(e)
        try:
            send_mail(
                subject="[ERROR] processing failed: {}".format(str(obj)),
                content="Project: {}\nSample: {}\nCommand: {}\n\nAdditional information:{}\n".format(
                    obj.projectid, obj.sampleid, str(fn), str(e)),
                receiver=obj.config.get('operator'))
        except Exception as me:
            logger.error(
                "processing {} failed - reason: {}, but operator {} could not be notified - reason: {}".format(
                    str(obj), e, obj.config.get('operator'), me))
        else:
            logger.error("processing {} failed - reason: {}, operator {} has been notified".format(
                str(obj), str(e), obj.config.get('operator')))

# check status of ongoing GRUS delivery
@deliver.command()
@click.pass_context
@click.argument('projectid', type=click.STRING, nargs=-1)
@click.option('--snic-api-credentials',
			  default=None,
			  envvar='SNIC_API_STOCKHOLM',
			  type=click.File('r'),
			  help='Path to SNIC-API credentials to create delivery projects')
@click.option('--statusdb-config',
			  default=None,
			  envvar='STATUS_DB_CONFIG',
			  type=click.File('r'),
			  help='Path to statusdb-configuration')

def check_status(ctx, projectid, snic_api_credentials=None, statusdb_config=None):
    """In grus delivery mode checks the status of an onggoing delivery
    """
    for pid in projectid:
        if statusdb_config == None:
            logger.error("--statusdb-config or env variable $STATUS_DB_CONFIG need to be set to perform GRUS delivery")
            return 1
        load_yaml_config(statusdb_config.name)
        if snic_api_credentials == None:
            logger.error("--snic-api-credentials or env variable $SNIC_API_STOCKHOLM need to be set to perform GRUS delivery")
            return 1
        load_yaml_config(snic_api_credentials.name)

        d = _deliver_grus.GrusProjectDeliverer(
                pid,
                **ctx.parent.params)
        d.check_mover_delivery_status()

@deliver.command()
@click.pass_context
@click.argument('projectid', type=click.STRING)
@click.option('--dds_project',
              default=None,
              type=click.STRING,
              help='DDS project ID to release')
@click.option('--dds_deadline',
              default=45,
              type=click.IntRange(1, 90),
              help='Deadline for DDS project in days [min 1; max 90; default 45]')
@click.option('--no-dds-mail',
            is_flag=True,
            default=False,
            help='Do not send DDS e-mail notifications regarding project updates')

def release_dds_project(ctx, projectid, dds_project, dds_deadline, no_dds_mail):
    """Updates DDS delivery status in Charon and releases DDS project to user.
    """
    if not dds_project:
        logger.error('Please specify the DDS project ID to release with --dds_project')
        return 1
    d = _deliver_dds.DDSProjectDeliverer(
        projectid,
        do_release=True,
        **ctx.parent.params)
    d.release_DDS_delivery_project(dds_project, no_dds_mail, dds_deadline)


text:
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tt.android.directorypicker"
    android:versionCode="1"
    android:versionName="0.0.1" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name" >

    </application>

</manifest>


text:
package generated.zcsclient.mail;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for getTagResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="getTagResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="tag" type="{urn:zimbraMail}tagInfo" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getTagResponse", propOrder = {
    "tag"
})
public class testGetTagResponse {

    protected List<testTagInfo> tag;

    /**
     * Gets the value of the tag property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the tag property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getTag().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link testTagInfo }
     *
     *
     */
    public List<testTagInfo> getTag() {
        if (tag == null) {
            tag = new ArrayList<testTagInfo>();
        }
        return this.tag;
    }

}


text:
Problema
--------

Arrastar e soltar um elemento na página web

Solução
-------

Brython implementa uma API baseada na especificação de arrastar e
soltar de HTML5. Na forma básica apresentada neste exemplo, ela
consiste em definir funções de resposta para 3 eventos:

- _dragstart_ no elemento arrastável (quando o usuário começa a
  arrastá-lo)

- _dragover_ na zona de destino (quando o elemento arrastável é movido
  sobre ele)

- _drop_ na zona de destino (quando o usuário libera o botão do mouse)

Para vincular a função de resposta _callback_ a um evento _event_ em
um elemento _element_, usamos o método
_element_.bind(_event,callback_)

As funções de resposta recebem um único argumento, uma instância de
`DOMEvent`. Para comunicar informação durante a operação de arrastar e
soltar, o evento tem um atributo _data_ que recebe um valor na função
de resposta associada a _dragstart_; este valor é usado na função de
resposta associada com _drop_ para identificar o elemento que esta
sendo solto.

No exemplo, quando o objeto arrastável tiver sido solto, ele não pode
mais ser arrastado; para isso, removemos os vínculos a um evento
_event_ neste objeto usando o método
_element_.unbind(_event_)

destination zone

draggable object

    from browser import doc

    panel = doc["panel"] # zona amarela

    source = doc["source"] # zona vermelha
    # posicionar em (10,10) a partir do canto superior esquerdo de panel
    source.style.top = "%spx" %(10+panel.top)
    source.style.left = "%spx" %(10+panel.left)
    # tornar a zona vermelha arrastável
    source.draggable = True

    dest = doc["dest"] # zona verde
    # posicionar em (10,150) a partir do canto superior esquerdo de panel
    dest.style.top = "%spx" %(10+panel.top)
    dest.style.left = "%spx" %(150+panel.left)

    # quando o mouse estiver sobre o elemento arrastável, mudar o cursor
    def mouse_over(ev):
        print('mouse over ! ')
        ev.target.style.cursor = "pointer"

    # deslocamento do mouse relativamente ao objeto arrastado quando o arrastamento começa
    m0 = [None,None]

    # função chamada quando o usuário começa a arrastar o objeto
    def drag_start(ev):
        global m0
        # calcular o deslocamento do mouse
        # ev.x e ev.y são as coordenadas do mouse quando o evnto é ativado
        # ev.target é o elemento arrastado. Seus atributos "left" e "top" são
        # inteiros, a distância das bordas esquerda e superior do documento
        m0 = [ev.x-ev.target.left,ev.y-ev.target.top]
        # associar dados ao processo de arrasto
        ev.data['text']=ev.target.id
        # permitir que o objeto arrastado seja movido
        ev.data.effectAllowed = 'move'

    # função chamada quando o objeto arrastável está sobre a zona de destino
    def drag_over(ev):
        ev.data.dropEffect = 'move'
        # aqui devemos prevenir o comportamento padrão para este tipo de evento
        ev.preventDefault()

    # função vinculada à zona de destino
    # descreve o que acontece quando o objeto é solto, p.ex. quando o mouse é
    # liberado enquanto o objeto está sobre a zona
    def drop(ev):
        # retomar dados armazenados em drag_start (o id do elemento arrastável)
        src_id = ev.data['text']
        elt = doc[src_id]
        # ajustar as novas coordenadas do objeto arrastado
        elt.style.left = "%spx" %(ev.x-m0[0])
        elt.style.top = "%spx" %(ev.y-m0[1])
        # não arrastar mais o objeto
        elt.draggable = False
        # remover a função de resposta
        elt.unbind('mouseover')
        elt.style.cursor = "auto"
        ev.preventDefault()

    # vincular eventos aos objetos arrastáveis
    source.bind('mouseover',mouse_over)
    source.bind('dragstart',drag_start)

    # vincular eventos à zona de destino
    dest.bind('dragover',drag_over)
    dest.bind('drop',drop)


text:
require 'rails_helper'

RSpec.describe Timeline::Source, type: :model do
  it 'should be invalid when name not present' do
    expect(
      FactoryBot.build(:timeline_source, name: nil)
    ).to have(1).errors_on(:name)
  end
end


text:
layout: tagpage
title: "Tag: lists"
tag: lists
robots: noindex
---


text:
package com.burning.iplay.utils;

import android.support.design.widget.Snackbar;
import android.view.View;

/**
 * @author Kiven
 * @time 2017-2-15  19:36
 * Email f842728368@163.com
 * @desc Toast工具类
 */
public class ToastUtil {
    private ToastUtil() {
    }

    public static void showToast(View view, String msg) {
        if (view != null && msg != null) {
            Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).show();
        }
    }
}


text:
<?php

namespace VGMdb\Component\Console;

use VGMdb\Component\Console\Command\ExitCommand;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Shell as BaseShell;

/**
 * Shell.
 *
 * @author Gigablah <gigablah@vgmdb.net>
 */
class Shell extends BaseShell
{
    public function __construct(BaseApplication $application)
    {
        $application->add(new ExitCommand());

        parent::__construct($application);
    }

    protected function getHeader()
    {
        $header = parent::getHeader();

        return str_replace('<comment>^D</comment>', '<comment>exit</comment> or <comment>quit</comment>', $header);
    }
}


text: Visualizando todos los mensajes


text:
@implementation SpectacleWindowPositionCalculator

+ (SpectacleCalculationResult *)calculateWindowRect: (CGRect)windowRect visibleFrameOfScreen: (CGRect)visibleFrameOfScreen action: (SpectacleWindowAction)action {
    CGRect calculatedWindowRect = windowRect;

    if ((action >= SpectacleWindowActionRightHalf) && (action <= SpectacleWindowActionLowerRight)) {
        calculatedWindowRect.origin.x = visibleFrameOfScreen.origin.x + floor(visibleFrameOfScreen.size.width / 2.0f);
    } else if (MovingToCenterRegionOfDisplay(action)) {
        calculatedWindowRect.origin.x = floor(visibleFrameOfScreen.size.width / 2.0f) - floor(calculatedWindowRect.size.width / 2.0f) + visibleFrameOfScreen.origin.x;
    } else if (!MovingToThirdOfDisplay(action)) {
        calculatedWindowRect.origin.x = visibleFrameOfScreen.origin.x;
    }

    if (MovingToTopRegionOfDisplay(action)) {
        calculatedWindowRect.origin.y = visibleFrameOfScreen.origin.y + floor(visibleFrameOfScreen.size.height / 2.0f) + remainder(visibleFrameOfScreen.size.height, 2.0f);
    } else if (MovingToCenterRegionOfDisplay(action)) {
        calculatedWindowRect.origin.y = floor(visibleFrameOfScreen.size.height / 2.0f) - floor(calculatedWindowRect.size.height / 2.0f) + visibleFrameOfScreen.origin.y;
    } else if (!MovingToThirdOfDisplay(action)) {
        calculatedWindowRect.origin.y = visibleFrameOfScreen.origin.y;
    }

    if ((action == SpectacleWindowActionLeftHalf) || (action == SpectacleWindowActionRightHalf)) {
        return [SpectacleWindowPositionCalculator calculateLeftOrRightHalfRect:windowRect visibleFrameOfScreen: visibleFrameOfScreen withAction: action];
    } else if ((action == SpectacleWindowActionTopHalf) || (action == SpectacleWindowActionBottomHalf)) {
        return [SpectacleWindowPositionCalculator calculateTopOrBottomHalfRect:windowRect visibleFrameOfScreen: visibleFrameOfScreen withAction: action];
    } else if (MovingToUpperOrLowerLeftOfDisplay(action) || MovingToUpperOrLowerRightDisplay(action)) {
        calculatedWindowRect.size.width = floor(visibleFrameOfScreen.size.width / 2.0f);
        calculatedWindowRect.size.height = floor(visibleFrameOfScreen.size.height / 2.0f);
    } else if (!MovingToCenterRegionOfDisplay(action) && !MovingToThirdOfDisplay(action)) {
        calculatedWindowRect.size.width = visibleFrameOfScreen.size.width;
        calculatedWindowRect.size.height = visibleFrameOfScreen.size.height;
    }

    if (MovingToThirdOfDisplay(action)) {
        calculatedWindowRect = [SpectacleWindowPositionCalculator findThirdForWindowRect: calculatedWindowRect visibleFrameOfScreen: visibleFrameOfScreen withAction: action];
    }

    return [SpectacleCalculationResult resultWithAction: action windowRect: calculatedWindowRect];
}

+ (SpectacleCalculationResult *)calculateResizedWindowRect: (CGRect)windowRect visibleFrameOfScreen: (CGRect)visibleFrameOfScreen sizeOffset: (CGFloat)sizeOffset action: (SpectacleWindowAction)action {
    CGRect calculatedWindowRect = windowRect;

    calculatedWindowRect.size.width = calculatedWindowRect.size.width + sizeOffset;
    calculatedWindowRect.origin.x = calculatedWindowRect.origin.x - floor(sizeOffset / 2.0f);

    if (AgainstTheRightEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
        calculatedWindowRect.origin.x = CGRectGetMaxX(visibleFrameOfScreen) - calculatedWindowRect.size.width;

        if (AgainstTheLeftEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
            calculatedWindowRect.size.width = visibleFrameOfScreen.size.width;
        }
    }

    if (AgainstTheLeftEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
        calculatedWindowRect.origin.x = visibleFrameOfScreen.origin.x;
    }

    if (calculatedWindowRect.size.width >= visibleFrameOfScreen.size.width) {
        calculatedWindowRect.size.width = visibleFrameOfScreen.size.width;
    }

    calculatedWindowRect.size.height = calculatedWindowRect.size.height + sizeOffset;
    calculatedWindowRect.origin.y = calculatedWindowRect.origin.y - floor(sizeOffset / 2.0f);

    if (AgainstTheTopEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
        calculatedWindowRect.origin.y = CGRectGetMaxY(visibleFrameOfScreen) - calculatedWindowRect.size.height;

        if (AgainstTheBottomEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
            calculatedWindowRect.size.height = visibleFrameOfScreen.size.height;
        }
    }

    if (AgainstTheBottomEdgeOfScreen(windowRect, visibleFrameOfScreen)) {
        calculatedWindowRect.origin.y = visibleFrameOfScreen.origin.y;
    }

    if (calculatedWindowRect.size.height >= visibleFrameOfScreen.size.height) {
        calculatedWindowRect.size.height = visibleFrameOfScreen.size.height;
        calculatedWindowRect.origin.y = windowRect.origin.y;
    }

    if (CGRectEqualToRect(windowRect, visibleFrameOfScreen) && (sizeOffset < 0)) {
        calculatedWindowRect.size.width = windowRect.size.width + sizeOffset;
        calculatedWindowRect.origin.x = windowRect.origin.x - floor(sizeOffset / 2.0f);

        calculatedWindowRect.size.height = windowRect.size.height + sizeOffset;
        calculatedWindowRect.origin.y = windowRect.origin.y - floor(sizeOffset / 2.0f);
    }

    if ([SpectacleWindowPositionCalculator isWindowRect: calculatedWindowRect tooSmallRelativeToVisibleFrameOfScreen: visibleFrameOfScreen]) {
        calculatedWindowRect = windowRect;
    }

    return [SpectacleCalculationResult resultWithAction: action windowRect: calculatedWindowRect];
}

#pragma mark -

+ (NSArray *)thirdsFromVisibleFrameOfScreen: (CGRect)visibleFrameOfScreen {
    NSMutableArray *result = [NSMutableArray new];
    NSInteger i = 0;

    for (i = 0; i < 3; i++) {
        CGRect thirdOfScreen = visibleFrameOfScreen;

        thirdOfScreen.origin.x = visibleFrameOfScreen.origin.x + (floor(visibleFrameOfScreen.size.width / 3.0f) * i);
        thirdOfScreen.size.width = floor(visibleFrameOfScreen.size.width / 3.0f);

        [result addObject: [SpectacleHistoryItem historyItemFromAccessibilityElement: nil windowRect: thirdOfScreen]];
    }

    for (i = 0; i < 3; i++) {
        CGRect thirdOfScreen = visibleFrameOfScreen;

        thirdOfScreen.origin.y = visibleFrameOfScreen.origin.y + visibleFrameOfScreen.size.height - (floor(visibleFrameOfScreen.size.height / 3.0f) * (i + 1));
        thirdOfScreen.size.height = floor(visibleFrameOfScreen.size.height / 3.0f);

        [result addObject: [SpectacleHistoryItem historyItemFromAccessibilityElement: nil windowRect: thirdOfScreen]];
    }

    return result;
}

+ (CGRect)findThirdForWindowRect: (CGRect)windowRect visibleFrameOfScreen: (CGRect)visibleFrameOfScreen withAction: (SpectacleWindowAction)action {
    NSArray *thirds = [SpectacleWindowPositionCalculator thirdsFromVisibleFrameOfScreen: visibleFrameOfScreen];
    CGRect result = [thirds[0] windowRect];
    NSInteger i = 0;

    for (i = 0; i < thirds.count; i++) {
        CGRect currentWindowRect = [thirds[i] windowRect];

        if (RectCenteredWithinRect(currentWindowRect, windowRect)) {
            NSInteger j = i;

            if (action == SpectacleWindowActionNextThird) {
                if (++j >= thirds.count) {
                    j = 0;
                }
            } else if (action == SpectacleWindowActionPreviousThird) {
                if (--j < 0) {
                    j = thirds.count - 1;
                }
            }

            result = [thirds[j] windowRect];

            break;
        }
    }

    return result;
}

#pragma mark -

+ (BOOL)isWindowRect: (CGRect)windowRect tooSmallRelativeToVisibleFrameOfScreen: (CGRect)visibleFrameOfScreen {
    CGFloat minimumWindowRectWidth = floor(visibleFrameOfScreen.size.width / SpectacleMinimumWindowSizeRatio);
    CGFloat minimumWindowRectHeight = floor(visibleFrameOfScreen.size.height / SpectacleMinimumWindowSizeRatio);

    return (windowRect.size.width <= minimumWindowRectWidth) || (windowRect.size.height <= minimumWindowRectHeight);
}

#pragma mark -

+ (SpectacleCalculationResult *)calculateLeftOrRightHalfRect: (CGRect)windowRect visibleFrameOfScreen: (CGRect)visibleFrameOfScreen withAction: (SpectacleWindowAction)action {
    CGRect oneHalfRect = visibleFrameOfScreen;

    oneHalfRect.size.width = floor(oneHalfRect.size.width / 2.0f);

    if (action == SpectacleWindowActionRightHalf) {
        oneHalfRect.origin.x += oneHalfRect.size.width;
    }

    if (fabs(CGRectGetMidY(windowRect) - CGRectGetMidY(oneHalfRect)) <= 1.0f) {
        CGRect oneThirdsRect = oneHalfRect;

        oneThirdsRect.size.width = floor(visibleFrameOfScreen.size.width / 3.0f);

        if (action == SpectacleWindowActionRightHalf) {
            oneThirdsRect.origin.x = visibleFrameOfScreen.origin.x + visibleFrameOfScreen.size.width - oneThirdsRect.size.width;
        }

        if (RectCenteredWithinRect(oneHalfRect, windowRect)) {
            return [SpectacleCalculationResult resultWithAction: SpectacleWindowActionNextThird windowRect: oneThirdsRect];
        }

        if (RectCenteredWithinRect(oneThirdsRect, windowRect)) {
            CGRect twoThirdRect = oneHalfRect;

            twoThirdRect.size.width = floor(visibleFrameOfScreen.size.width * 2 / 3.0f);

            if (action == SpectacleWindowActionRightHalf) {
                twoThirdRect.origin.x = visibleFrameOfScreen.origin.x + visibleFrameOfScreen.size.width - twoThirdRect.size.width;
            }

            return [SpectacleCalculationResult resultWithAction: SpectacleWindowActionNextThird windowRect: twoThirdRect];
        }
    }

    return [SpectacleCalculationResult resultWithAction: action windowRect: oneHalfRect];
}

#pragma mark -

+ (SpectacleCalculationResult *)calculateTopOrBottomHalfRect: (CGRect)windowRect visibleFrameOfScreen: (CGRect)visibleFrameOfScreen withAction: (SpectacleWindowAction)action {
    CGRect oneHalfRect = visibleFrameOfScreen;

    oneHalfRect.size.height = floor(oneHalfRect.size.height / 2.0f);

    if (action == SpectacleWindowActionTopHalf) {
        oneHalfRect.origin.y += oneHalfRect.size.height + remainder(visibleFrameOfScreen.size.height, 2.0f);
    }

    if (fabs(CGRectGetMidX(windowRect) - CGRectGetMidX(oneHalfRect)) <= 1.0f) {
        CGRect oneThirdRect = oneHalfRect;

        oneThirdRect.size.height = floor(visibleFrameOfScreen.size.height / 3.0f);

        if (action == SpectacleWindowActionTopHalf) {
            oneThirdRect.origin.y = visibleFrameOfScreen.origin.y + visibleFrameOfScreen.size.height - oneThirdRect.size.height;
        }

        if (RectCenteredWithinRect(oneHalfRect, windowRect)) {
            return [SpectacleCalculationResult resultWithAction: SpectacleWindowActionNextThird windowRect: oneThirdRect];
        }

        if (RectCenteredWithinRect(oneThirdRect, windowRect)) {
            CGRect twoThirdsRect = oneHalfRect;

            twoThirdsRect.size.height = floor(visibleFrameOfScreen.size.height * 2 / 3.0f);

            if (action == SpectacleWindowActionTopHalf) {
                twoThirdsRect.origin.y = visibleFrameOfScreen.origin.y + visibleFrameOfScreen.size.height - twoThirdsRect.size.height;
            }

            return [SpectacleCalculationResult resultWithAction: SpectacleWindowActionNextThird windowRect: twoThirdsRect];
        }
    }

    return [SpectacleCalculationResult resultWithAction: action windowRect: oneHalfRect];
}

@end


text:
package warehouse;

/**
 * This class represents a warehouse Product.
 *
 * @author Ishaan Ivaturi
 */
public class Product {
    /**
     * product identification
     */
    private int id;

    /**
     * product name
     */
    private String name;

    /**
     * number of items in stock
     */
    private int stock;

    /**
     * the number of days since the store opening that the item was last purchased
     */
    private int lastPurchaseDay;

    /**
     * Initial demand is obtained from a survey prior to product release
     */
    private int demand;

    /**
     * Initial Demand + Total Amount Purchased + Date of Last Purchase
     */
    private int popularity;

    public Product(int i, String n, int s, int l, int d) {
        id = i;
        name = n;
        stock = s;
        lastPurchaseDay = l;
        demand = d;
        popularity = l + d;
    }

    public Product(int i, String n, int s, int l) {
        this(i, n, s, l, 0);
    }

    public Product(int i, String n) {
        this(i, n, 0, 0);
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getStock() {
        return stock;
    }

    public int getLastPurchaseDay() {
        return lastPurchaseDay;
    }

    public int getDemand() {
        return demand;
    }

    public int getPopularity() {
        return popularity;
    }

    public void setId(int i) {
        id = i;
    }

    public void setName(String n) {
        name = n;
    }

    public void updateStock(int s) {
        stock += s;
    }

    public void setStock(int s) {
        stock = s;
    }

    public void setLastPurchaseDay(int l) {
        lastPurchaseDay = l;
        popularity = lastPurchaseDay + demand;
    }

    public void updateDemand(int d) {
        demand += d;
        popularity = lastPurchaseDay + demand;
    }

    public void setDemand(int d) {
        demand = d;
        popularity = lastPurchaseDay + demand;
    }

    /**
     * Returns true if this object equals other
     */
    public boolean equals(Object other) {
        if (!(other instanceof Product)) {
            return false;
        }
        Product o = (Product) other;
        return this.getId() == o.getId();
    }

    public String toString() {
        return String.format("(%s: %d, %d)", name, stock, popularity);
    }
}


text:
Util Extension
==============
Activate util extension:

```yml
sk_twig_extensions:
    extensions:
        string_extension: true
```

## Filter
### Filter ucfirst
#### Description
```
{{ string value | ucfirst }}
```
Make a string's first character uppercase.

This is a simple wrapper for the php [ucfirst](http://php.net/manual/en/function.ucfirst.php) function.

#### Parameters
##### value
A string or an object implementing __toString magic method

#### Example
```twig
<span>{{ "hello World" | ucfirst }}</span>
```
##### Output:

```html
<span>Hello World</span>
```

### Filter lcfirst
#### Description
```
{{ string value | lcfirst }}
```
Make a string's first character lowercase.

This is a simple wrapper for the php [lcfirst](http://php.net/manual/en/function.lcfirst.php) function.

#### Parameters
##### value
A string or an object implementing __toString magic method

#### Example
```twig
<span>{{ "Hello World" | lcfirst }}</span>
```
##### Output:

```html
<span>hello World</span>
```

## Functions
### Function ucfirst
#### Description
```
{{ ucfirst( string value ) }}
```
Make a string's first character uppercase.

This is a simple wrapper for the php [ucfirst](http://php.net/manual/en/function.ucfirst.php) function.

#### Parameters
##### value
A string or an object implementing __toString magic method

#### Example
```twig
<span>{{ ucfirst( "hello World" ) }}</span>
```
##### Output:

```html
<span>Hello World</span>
```

### Function lcfirst
#### Description
```
{{ lcfirst( string value ) }}
```
Make a string's first character lowercase.

This is a simple wrapper for the php [lcfirst](http://php.net/manual/en/function.lcfirst.php) function.

#### Parameters
##### value
A string or an object implementing __toString magic method

#### Example
```twig
<span>{{ lcfirst( "Hello World" ) }}</span>
```
##### Output:

```html
<span>hello World</span>
```


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vdslib;

import com.yahoo.vespa.objects.BufferSerializer;
import com.yahoo.vespa.objects.Deserializer;

import java.nio.ByteOrder;
import java.io.UnsupportedEncodingException;

public class DocumentSummary {

    private final Summary[] summaries;

    public DocumentSummary(Deserializer buf) {
        BufferSerializer bser = (BufferSerializer) buf; // This is a trick. This should be done in a different way.
        bser.order(ByteOrder.BIG_ENDIAN);
        buf.getInt(null); // legacy - ignored
        int numSummaries = buf.getInt(null);
        summaries = new Summary[numSummaries];
        if (numSummaries > 0) {
            int summaryBufferSize = buf.getInt(null);

            byte[] cArr = bser.getBuf().array();
            int start = bser.getBuf().arrayOffset() + bser.position();
            bser.position(bser.position() + summaryBufferSize);
            for(int i=0; i < numSummaries; i++) {
                int summarySize = buf.getInt(null);
                int end = start;
                while (cArr[end++] != 0);
                try {
                    byte [] sb = new byte [summarySize];
                    System.arraycopy(cArr, end, sb, 0, summarySize);
                    summaries[i] = new Summary(new String(cArr, start, end-start-1, "utf-8"), sb);
                    start = end + summarySize;
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("UTF-8 apparently not supported");
                }
            }
        }
    }

    /** Constructs a new message from a byte buffer. */
    public DocumentSummary(byte[] buffer) {
        this(BufferSerializer.wrap(buffer));
    }

    final public int getSummaryCount()         { return summaries.length; }
    final public Summary getSummary(int hitNo) { return summaries[hitNo]; }

    public static class Summary implements Comparable<Summary> {

        private final String  docId;
        private byte[] summary;

        private Summary(String docId) {
            this.docId = docId;
        }

        public Summary(String docId, byte [] summary) {
            this(docId);
            this.summary = summary;
        }

        final public String getDocId()           { return docId; }
        final public byte [] getSummary()        { return summary; }
        final public void setSummary(byte [] summary) { this.summary = summary; }

        public int compareTo(Summary s) {
            return getDocId().compareTo(s.getDocId());
        }

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>main.java.onDisk Class Hierarchy</title>
<meta name="date" content="2015-02-21">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package main.java.onDisk

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

main.java.onDisk.BinMerger

main.java.onDisk.Corpus

main.java.onDisk.DiskFrequencyWrapper

main.java.onDisk.DiskPosting

main.java.onDisk.Dump

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
using System;
using Umbraco.Cms.Core.Models.Entities;

namespace Umbraco.Cms.Core.Models
{
    public class TwoFactorLogin : EntityBase, ITwoFactorLogin
    {
        public string ProviderName { get; set; }
        public string Secret { get; set; }
        public Guid UserOrMemberKey { get; set; }
        public bool Confirmed { get; set; }
    }
}


text:
package org.apache.jackrabbit.oak.plugins.document;

import java.util.List;

import com.google.common.collect.Lists;

import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDockerRule;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.jetbrains.annotations.Nullable;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import static org.junit.Assume.assumeNotNull;

public class MongoConnectionFactory extends ExternalResource {

    private final MongoDockerRule mongo = new MongoDockerRule();

    private final List<MongoConnection> connections = Lists.newArrayList();

    @Override
    public Statement apply(Statement base, Description description) {
        Statement s = super.apply(base, description);
        if (MongoDockerRule.isDockerAvailable()) {
            s = mongo.apply(s, description);
        }
        return s;
    }

    @Nullable
    public MongoConnection getConnection() {
        return getConnection(MongoUtils.DB);
    }

    @Nullable
    public MongoConnection getConnection(String dbName) {
        // first try MongoDB running on configured host and port
        MongoConnection c = MongoUtils.getConnection(dbName);
        if (c == null && MongoDockerRule.isDockerAvailable()) {
            // fall back to docker if available
            c = new MongoConnection("localhost", mongo.getPort(), dbName);
        }
        assumeNotNull(c);
        if (c != null) {
            connections.add(c);
        }
        return c;
    }

    @Override
    protected void after() {
        for (MongoConnection c : connections) {
            try {
                c.close();
            } catch (IllegalStateException e) {
                // may happen when connection is already closed (OAK-7447)
            }
        }
    }
}


text:
package templates

import chisel3._
import chisel3.util._
import chisel3.core.IntParam

// This wrapper is needed because we need to wire reset as an input,
// and reset is accessible only from within Modules in Chisel
class RetimeWrapper(val width: Int, val delay: Int) extends Module {
  val io = IO(new Bundle {
    val flow = Input(Bool())
    val in = Input(UInt(width.W))
    val out = Output(UInt(width.W))
  })

    val sr = Module(new RetimeShiftRegister(width, delay))
    sr.io.clock := clock
    sr.io.reset := reset.toBool
    sr.io.flow := io.flow
    sr.io.in := io.in
    io.out := sr.io.out
}

class RetimeWrapperWithReset(val width: Int, val delay: Int) extends Module {
  val io = IO(new Bundle {
    val flow = Input(Bool())
    val rst = Input(Bool())
    val in = Input(UInt(width.W))
    val out = Output(UInt(width.W))
  })

    if (delay > 0) {
      val sr = Module(new RetimeShiftRegister(width, delay))
      sr.io.clock := clock
      sr.io.reset := reset.toBool | io.rst
      sr.io.flow := io.flow
      sr.io.in := io.in
      io.out := sr.io.out
    } else {
      io.out := io.in
    }
}

class RetimeShiftRegister(val width: Int, val delay: Int) extends BlackBox(
  Map(
    "WIDTH" -> IntParam(width),
    "STAGES" -> IntParam(delay)
    )
) {
  val io = IO(new Bundle {
    val clock = Input(Clock())
    val reset = Input(Bool())
    val flow = Input(Bool())
    val in = Input(UInt(width.W))
    val out = Output(UInt(width.W))
  })
}


text:
package com.evolved.automata.parser;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;

class ConjunctionMatcher extends Matcher
{

	public ConjunctionMatcher(String grammarComponent, CFGParser.GlobalState global, Matcher[] subStates)
	{
		super(global);
		this.subStates = subStates;
		maxSubMatches = subStates.length-1;
		matchIndex = 0;
		this.grammarComponent=grammarComponent;
	}

	public Matcher clone()
	{
		ConjunctionMatcher n = new ConjunctionMatcher(grammarComponent, global, subStates);
		return n;
	}

	public LinkedList<Matcher> match()
	{
		LinkedList<Matcher> grammarList = new LinkedList<Matcher>();
		Matcher firstState = null;
		firstState = subStates[0].clone();
		int processType;
		processType=firstState.setExecutionParameters(global, 0, startIndex, inputString, capturedMaps, captureGroupNames, this, nonDeterministicAncestor, parsedComponents);
		if (processType!=CFGParser.GlobalState.STARTED)
		{
			updateFailureCache(nonDeterministicAncestor);
			return updateFromParseFailure(this, -1);
		}

		grammarList.add(firstState);
		return grammarList;
	}

	protected LinkedList<Matcher> updateFromParseSuccess(Matcher subChild, int nextIndex, Hashtable<String, LinkedList<String>> nextCapturedMap, Matcher nonDeterministicPrior )
	{
		endIndex = subChild.getEndIndex();
		LinkedList<Matcher> grammarList = new LinkedList<Matcher>();
		matchIndex=nextIndex;

		if (matchIndex>maxSubMatches)
		{
			finalize();
			if (parent!=null)
			{
				grammarList = parent.updateFromParseSuccess(this, indexInParent+1, nextCapturedMap, nonDeterministicPrior);
				return grammarList;
			}
			else
			{
				subChild.finalize();
				grammarList.add(subChild);
				subChild.capturedMaps = nextCapturedMap;
				return grammarList;
			}
		}
		else
		{
			Matcher nextState = subStates[matchIndex].clone();
			int processType;
			processType=nextState.setExecutionParameters(global, matchIndex, endIndex, inputString, nextCapturedMap, captureGroupNames, this, nonDeterministicPrior, parsedComponents);
			if (processType!=CFGParser.GlobalState.STARTED)
			{
				if (nonDeterministicPrior==nonDeterministicAncestor)
				{
					updateFailureCache(nonDeterministicPrior);
				}
				return nonDeterministicPrior.updateFromParseFailure(this, -1);
			}

			grammarList.add(nextState);
			return grammarList;
		}

	}
}


text:
package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.TransliterationOptions;
import com.basistech.rosette.apimodel.TransliterationResponse;
import com.basistech.util.LanguageCode;

import java.io.IOException;

import static com.basistech.rosette.api.common.AbstractRosetteAPI.TRANSLITERATION_SERVICE_PATH;

/**
 * Example which demonstrates the transliteration API.
 */
public class TransliterationExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new TransliterationExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String transliterationData = "ana r2ye7 el gam3a el sa3a 3 el 3asr";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        // The API object creates an HTTP client, but to provide your own:
        // HttpRosetteAPI.Builder#httpClient(CloseableHttpClient)
        DocumentRequest<TransliterationOptions> request = DocumentRequest.<TransliterationOptions>builder()
                .content(transliterationData)
                .language(LanguageCode.ARABIC)
                .build();
        TransliterationResponse response = rosetteApi.perform(TRANSLITERATION_SERVICE_PATH, request, TransliterationResponse.class);
        System.out.println(responseToJson(response));
    }
}


text:
package magicgate

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"

	"golang.org/x/net/context"

	"google.golang.org/appengine"
	"google.golang.org/appengine/log"
	"google.golang.org/appengine/urlfetch"
)

func init() {
	http.HandleFunc("/", handler)
}

const (
	welcomeMsg = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello Gopher, how are you?</Say>
	<Record timeout="5"/>
</Response>`
	comeInMsg = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Welcome home!</Say>
    <Play digits="9"></Play>
</Response>`
	goAwayMsg = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Go away, you evil person</Say>
</Response>`
)

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/xml")

	rec := r.FormValue("RecordingUrl")
	if rec == "" {
		fmt.Fprint(w, welcomeMsg)
		return
	}
	ctx := appengine.NewContext(r)
	text, err := transcribe(ctx, rec)
	if err != nil {
		http.Error(w, "could not transcribe", http.StatusInternalServerError)
		log.Errorf(ctx, "could not transcribe: %v", err)
		return
	}

	log.Infof(ctx, "transcription: %s", text)
	if text == "hello gopher" {
		fmt.Fprint(w, comeInMsg)
	} else {
		fmt.Fprint(w, goAwayMsg)
	}
}

func transcribe(c context.Context, url string) (string, error) {
	b, err := fetchAudio(c, url)
	if err != nil {
		return "", err
	}

	return fetchTranscription(c, b)
}

func fetchAudio(c context.Context, url string) ([]byte, error) {
	res, err := urlfetch.Client(c).Get(url)
	if err != nil {
		return nil, fmt.Errorf("could not fetch %v: %v", url, err)
	}
	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("fetch with status %s", res.Status)
	}
	defer res.Body.Close()
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("could not read response: %v", err)
	}
	return b, nil
}

var speechURL = "https://speech.googleapis.com/v1/speech:recognize?key=" +
	os.Getenv("SPEECH_API_KEY")

func fetchTranscription(ctx context.Context, audio []byte) (string, error) {
	req := map[string]interface{}{
		"config": map[string]interface{}{
			"encoding":        "LINEAR16",
			"sampleRateHertz": 8000,
			"languageCode":    "en-US",
		},
		"audio": map[string]interface{}{
			"content": base64.StdEncoding.EncodeToString(audio),
		},
	}

	payload, err := json.Marshal(req)
	if err != nil {
		return "", fmt.Errorf("could not encode speech request: %v", err)
	}
	res, err := urlfetch.Client(ctx).Post(speechURL, "application/json", bytes.NewReader(payload))
	if err != nil {
		return "", fmt.Errorf("could not transcribe: %v", err)
	}

	var data struct {
		Error struct {
			Code    int
			Message string
			Status  string
		}
		Results []struct {
			Alternatives []struct {
				Transcript string
				Confidence float64
			}
		}
	}
	defer res.Body.Close()
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		return "", fmt.Errorf("could not decode speech response: %v", err)
	}
	if data.Error.Code != 0 {
		return "", fmt.Errorf("speech API error: %d %s %s",
			data.Error.Code, data.Error.Status, data.Error.Message)
	}
	if len(data.Results) == 0 || len(data.Results[0].Alternatives) == 0 {
		return "", fmt.Errorf("no transcriptions found")
	}
	return data.Results[0].Alternatives[0].Transcript, nil
}