text:
Variables and Data Types
------------------------

Unlike `Java <https://en.wikipedia.org/wiki/Java_(programming_language)>`_ or `C++ <https://en.wikipedia.org/wiki/C%2B%2B>`_,
which are `compiler-based <https://en.wikipedia.org/wiki/Compiler>`_ languages, `Python <https://www.python.org/>`_ is an `interpreter-based <https://en.wikipedia.org/wiki/Interpreter_(computing)>`_ language.
This means that each program is executed *line-by-line* with
no preprocessing for speeding up the execution time. As a consequence, the
developer does not have to specify the variable type before a given variable
name. `Python <https://www.python.org/>`_ follows the same rules for
naming variables as `Java <https://en.wikipedia.org/wiki/Java_(programming_language)>`_ or `C++ <https://en.wikipedia.org/wiki/C%2B%2B>`_,
so we will not repeat them here for brevity. The value of any variable can be
printed using the ``print`` keyword. Some examples of variable
assignments are given below: ::

    >>> myint = 7
    >>> myfloat = 7.0
    >>> mystring = "hello"

Strings
~~~~~~~

A string is simply a sequence of characters. All characters inside single or
double quotes constitute a string in `Python <https://www.python.org/>`_. This
gives flexibility in using both quotes and apostrophes within strings, as shown
below: ::

    >>> mystring = '"Come into my parlor", said the spider to the fly.'
    >>> print mystring
    "Come into my parlor", said the spider to the fly.

Two strings can be conveniently concatenated together using the ``+`` operator.
`Python <https://www.python.org/>`_ provides many built-in functions for string processing also, such as ``title``
which capitalizes the first letter of every word, ``upper`` which capitalizes
all letters, ``lower`` which converts all characters to lower case, or ``rstrip``
which deletes all whitespaces, just to name a few. Note that a number can also
be converted into string using the ``str`` keyword, as shown below: ::

    >>> mystring = "Index "+str(23)+" has value: "+str(1.5)
    >>> mystring
    'Index 23 has value: 1.5'

Since scientific computing
algorithms will primarily consider numeric values, we will not dive too deep into
string processing with `Python <https://www.python.org/>`_.

Integers
~~~~~~~~

Integers types are supported in `Python <https://www.python.org/>`_ with all the
usual addition (``+``), subtraction (``-``), multiplication (``*``),
division (``/``), and modulo (``%``) operators. Additionally, one can raise a number to a specified
power using the double-multiplication (``**``) operator. ::

    >>> a = 5
    >>> b = 3
    >>> a+b
    8
    >>> a-b
    2
    >>> a*b
    15
    >>> a/b
    1
    >>> a%b
    2
    >>> a**b
    125

Note that ``a/b`` gives us a value of ``1`` because both the arguments are
integers, so the ``/`` operator corresponds to *integer division*. If we wanted
a floating-point value, we can explicitly convert one argument to ``float``, as
shown below: ::

    >>> float(a)/b
    1.6666666666666667
    >>> a/float(b)
    1.6666666666666667

Floats
~~~~~~

We have already discussed floating-point numbers at length in the previous
chapter. Such numbers support all the usual arithmetic operators as integers.
The modulo (``%``) operator generalizes to *include* the fractional part in this case. A floating-point number can be explicitly
converted to an integer using the ``int`` keyword. This is also useful for
extracting the fractional part, as shown below: ::

    >>> a = 5.3
    >>> int(a)              # integer part
    5
    >>> a-int(a)            # fractional part
    0.2999999999999998
    >>> b = 2
    >>> a%b
    2.3

Comments can be specified by preceding the text with the ``#`` sign, as shown above.
Note how `Python <https://www.python.org/>`_ approximates the simple value of
``0.3`` with the more complex expression ``0.2999999999999998`` as shown above.
As explained in the previous chapter, this happens because of limited precision
available on the computer. In later chapters, we will discuss this issue at length and
specifically study the design of algorithms that do not produce wrong results
because of cancellations between approximate (limited precision)
representations.


text:
using namespace cv;

#define LOG_TAG "SNAPIT"

#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args)

#define OTSU 100
#define NIBLACK 200
#define SAUVOLA 300
#define WOLFJOLION 400

class BhThresholder
{
public :
    void doThreshold(InputArray src ,OutputArray dst,int method);
private:
};

#endif //_THRESHOLDER

redpajama_set_name: RedPajamaGithub


text:
package com.eagleoj.web.judger;

import com.eagleoj.web.entity.JudgerEntity;
import com.eagleoj.web.service.JudgerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author Smith
 **/
@Service
public class JudgerDispatcher {

    @Autowired
    private JudgerService judgerService;

    private List<JudgerEntity> judgerList;

    public void refresh() {
        judgerList = judgerService.listJudger();
    }

    public String getJudgerUrl() {
        if (judgerList == null || judgerList.size() == 0) {
            refresh();
        }

        if (judgerList == null || judgerList.size() == 0) {
            return null;
        }

        return generateUrl(randomJudger());
    }

    private JudgerEntity randomJudger() {
        Random random = new Random();
        int size = judgerList.size();
        int offset = random.nextInt(size);
        return judgerList.get(offset);
    }

    private String generateUrl(JudgerEntity entity) {
        return "http://"+entity.getUrl()+":"+entity.getPort();
    }
}


text:
if [ -e consul_ca.crt ]; then
  echo "Certs already exist, aborting creation."
  exit 0
fi

script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $script_dir

openssl genrsa -out consul.key 4096

openssl req -new -x509 -days 365 -key consul.key -subj '/C=US/ST=Somestate/L=sometown/O=somecompany/OU=someorg/CN=someguy' -out consul_ca.crt

openssl req -new -key consul.key -out consul.csr -subj '/C=US/ST=Somestate/L=sometown/O=somecompany/OU=someorg/CN=*'

openssl x509 -extfile openssl.conf -extensions ssl_client -req -days 365 -in consul.csr -CA consul_ca.crt -CAkey consul.key -out consul.crt -set_serial 01


text:
package com.zimbra.soap.base;

public interface ZimletIncludeCSS {
    public void setValue(String value);
    public String getValue();
}


text:
using UnityEngine;
using System.Collections;

public class CuadroDialogo : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mbean PUBLIC
   "-//JBoss//DTD JBOSS XMBEAN 1.1//EN"
   "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd">

<mbean>
   <description>Media Creation Mgt. SCU</description>

   <descriptors>
      <persistence persistPolicy="OnUpdate"/>
      <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager" />
   </descriptors>

   <class>org.dcm4chex.archive.dcm.mcmscu.MCMScuService</class>

   <constructor>
      <description>The default constructor</description>
      <name>MCMScuService</name>
   </constructor>

    <attribute access="read-write"
      getMethod="getCallingAET"
      setMethod="setCallingAET">
      <description>The calling AET.
      </description>
      <name>CallingAET</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="PACS_TIANI" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getRetrieveAET"
      setMethod="setRetrieveAET">
      <description>The retrieve AET (for move).
      </description>
      <name>RetrieveAET</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="PACS_TIANI" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getMoveDestinationAET"
      setMethod="setMoveDestinationAET">
      <description>The move destination AET.
      </description>
      <name>MoveDestinationAET</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="CDRECORD" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getMcmScpAET"
      setMethod="setMcmScpAET">
      <description>The Media Creation Managment SCP AET.
      </description>
      <name>McmScpAET</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="CDRECORD" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getFileSetIdPrefix"
      setMethod="setFileSetIdPrefix">
      <description>Prefix for FileSet ID.
      </description>
      <name>FileSetIdPrefix</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="DISK_" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getNrOfCopies"
      setMethod="setNrOfCopies">
      <description>Number of media to create (with same content; allowed: 1-99).
      </description>
      <name>NrOfCopies</name>
      <type>int</type>
      <descriptors>
         <value value="1" />
      </descriptors>
   </attribute>

    <attribute access="read-write"
      getMethod="getMaxMediaUsage"
      setMethod="setMaxMediaUsage">
      <description>Maximal media usage for DICOM files. This values is usually
      smaller than the real media size to keep space for index and optional html
      files. 1MB = 1000000 Byte, 1GB = 1000MB
      </description>
      <name>MaxMediaUsage</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="600MB" />
      </descriptors>
   </attribute>

    <attribute access="read-write"
      getMethod="getMinStudyAge"
      setMethod="setMinStudyAge">
      <description>The minimal duration before instances of studies are
      scheduled for offline storage. Increasing the delay for scheduling
      ensures that all instances of a study will be stored on a single media.
      Format: ##h (in hours), ##d (in days), ##w (in weeks).
      </description>
      <name>MinStudyAge</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="2d" />
      </descriptors>
   </attribute>

    <attribute access="read-write"
      getMethod="getMaxStudyAge"
      setMethod="setMaxStudyAge">
      <description>The maximal duration before studies are archived on
      media. Only effective, if media creation is triggered automatically
      by BurnMediaInterval != NEVER.
      Format: ##h (in hours), ##d (in days), ##w (in weeks).
      </description>
      <name>MaxStudyAge</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="4w" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getScheduleMediaInterval"
      setMethod="setScheduleMediaInterval">
      <description>Interval in which studies received former than configured
          Minimal Study Age are associated to media, scheduled for creation.
          Format: ##m (in minutes), ##h (in hours), ##d (in days).
          NEVER (= disable media scheduling).
      </description>
      <name>ScheduleMediaInterval</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="NEVER" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getUpdateMediaStatusInterval"
      setMethod="setUpdateMediaStatusInterval">
      <description>Interval in which Media Creation Server is quered for status
          of pending Media Creation Requests.
          Format: ##s (in seconds), ##m (in minutes), ##h (in hours).
          NEVER (= disable query of Media Creation Server).
      </description>
      <name>UpdateMediaStatusInterval</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="NEVER" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getBurnMediaInterval"
      setMethod="setBurnMediaInterval">
      <description>Interval in which creation of media with studies
          received former than configured Maximal Study Age is triggered
          automatically. Format: ##h (in hours), ##d (in days), ##w (in weeks).
          NEVER (= no automatical trigger of media creation).
      </description>
      <name>BurnMediaInterval</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="NEVER" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="isAutomaticMediaCreation"
      setMethod="setAutomaticMediaCreation">
      <description>Enables/disables automatic media creation.
      	If automatic media creation is disabled, a notification is send to the email list
      	defined in NotifyBurnMediaEmailTo.
      </description>
      <name>AutomaticMediaCreation</name>
      <type>boolean</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getNotifyBurnMediaEmailTo"
      setMethod="setNotifyBurnMediaEmailTo">
      <description>List of email address that should be notified seperated with ','
      	if one ore more media are ready to burn.
      </description>
      <name>NotifyBurnMediaEmailTo</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getNotifyBurnMediaEmailFrom"
      setMethod="setNotifyBurnMediaEmailFrom">
      <description>Email address that is used as from address in the notification mail.
      </description>
      <name>NotifyBurnMediaEmailFrom</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getAcTimeout"
      setMethod="setAcTimeout">
      <description>A-ASSOCIATE AC timeout in ms. 0 = no timeout.
      </description>
      <name>AcTimeout</name>
      <type>int</type>
      <descriptors>
         <value value="10000" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getDimseTimeout"
      setMethod="setDimseTimeout">
      <description>DIMSE message timeout in ms. 0 = no timeout.
      </description>
      <name>DimseTimeout</name>
      <type>int</type>
      <descriptors>
         <value value="60000" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getSoCloseDelay"
      setMethod="setSoCloseDelay">
      <description>Socket close delay in ms after A-RELEASE RSP.
      </description>
      <name>SoCloseDelay</name>
      <type>int</type>
      <descriptors>
         <value value="50" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getMaxPDUlen"
      setMethod="setMaxPDUlen">
      <description>Max. PDU size in bytes.
      </description>
      <name>MaxPDUlen</name>
      <type>int</type>
      <descriptors>
         <value value="16352" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getPriority"
      setMethod="setPriority">
      <description>Priority for move and media creation request. 0=medium, 1=high, 2=low.
      </description>
      <name>Priority</name>
      <type>int</type>
      <descriptors>
         <value value="0" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getIncludeNonDICOMObj"
      setMethod="setIncludeNonDICOMObj">
      <description>The type of none DICOM information/object that the SCP should include in the media.
      Use NO if no additional information/objects should be included.
      </description>
      <name>IncludeNonDicomObj</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="MD5_SUMS" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="isUseInstanceInfo"
      setMethod="setUseInstanceInfo">
      <description>Specifies whether or not to extract label information from the instances.
      </description>
      <name>UseInstanceInfo</name>
      <type>boolean</type>
      <descriptors>
         <value value="false" />
      </descriptors>
   </attribute>

   <attribute access="read-write"
      getMethod="getSendmailServiceName"
      setMethod="setSendmailServiceName">
      <description>Used internally - do NOT modify.
      </description>
      <name>SendmailServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=Sendmail" />
      </descriptors>
   </attribute>

   &defaultAttributes;

   <!-- Operations -->
   &defaultOperations;

   <operation impact="ACTION">
      <description>Check availability of Media Creation Managment SCP. Returns OK, MOVE_DEST_UNAVAIL or MCM_SCP_UNAVAIL.
      </description>
      <name>checkMcmScpAvail</name>
      <return-type>java.lang.String</return-type>
   </operation>

   <operation impact="ACTION">
      <description>Schedule media with studies received former than MinStudyAge</description>
      <name>scheduleMedia</name>
      <return-type>int</return-type>
   </operation>

   <operation impact="ACTION">
      <description>Update media status</description>
      <name>updateMediaStatus</name>
      <return-type>java.lang.String</return-type>
   </operation>

   <operation impact="ACTION">
      <description>Initiate creation of Media with studies received former than MaxStudyAge.
      </description>
      <name>burnMedia</name>
      <return-type>int</return-type>
   </operation>

    <operation impact="ACTION">
      <description>Delete Media.
      </description>
      <name>deleteMedia</name>
      <parameter>
        <description>Directory Path</description>
        <name>mediaPk</name>
        <type>java.lang.Integer</type>
      </parameter>
      <return-type>void</return-type>
   </operation>

</mbean>


text:
package softuni.store.models.bindingModels.game;

import java.io.Serializable;

public class BoughtGame implements Serializable{
    private Long id;

    public BoughtGame() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="@string/pref_header_about">

        <com.hjwylde.rivers.ui.activities.settings.VersionPreference
            android:title="@string/pref_title_version"/>

        <Preference
            android:title="@string/pref_title_licenses">
            <intent android:action=".ui.activities.LicensesActivity"/>
        </Preference>
    </PreferenceCategory>
</PreferenceScreen>


text:
const express = require('express')
const moment = require('moment')
const router = express.Router()

// Local dependencies
const countries = require('../../../data/location-autocomplete')

/**
 * Prototype index
 */
router.all('/', (req, res) => {
    req.session.data = {}
    res.render(`${__dirname}/views/index`, { isStart: true })
})

router.all('/accessibility', (req, res) => {
    res.render(`${__dirname}/views/accessibility`)
});

/**
 * Redirects to first question
 */
router.all('/claimant/questions', (req, res) => {
    return res.redirect('./questions/british-passport')
})

/**
 * Question: British passport?
 */
router.all('/:type/questions/british-passport', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // UK national
    if (submitted.ukNational === 'yes') {
        return res.redirect('./british-passport-today')
    }

    // Non-UK national
    if (submitted.ukNational === 'no') {
        return res.redirect('./refugee')
    }

    res.render(`${__dirname}/views/questions/british-passport`)
})

/**
 * Question: Brought passport today?
 */
router.all('/:type/questions/british-passport-today', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Brought their passport
    if (submitted.passportToday === 'yes') {
        return res.redirect('./british-passport-nationality')
    }

    // Not brought their passport
    if (submitted.passportToday === 'no') {
        return res.redirect('./british-passport-fei')
    }

    res.render(`${__dirname}/views/questions/british-passport-today`)
})

/**
 * Question: Can they bring their passport to another appionyment?
 */
router.all('/:type/questions/british-passport-fei', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Yes
    if (submitted.passportFei === 'yes') {
        return res.redirect('../../outcome/END016')
    }

    // No
    if (submitted.passportFei === 'no') {
        return res.redirect('../../outcome/END300')
    }

    res.render(`${__dirname}/views/questions/british-passport-fei`)
})

/**
 * Question: Is passport nationality British?
 */
router.all('/:type/questions/british-passport-nationality', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // British citizen
    if (submitted.britishCitizen === 'yes') {
        saved.nationality = 'country:GB'
        return res.redirect('./out-of-country')
    }

    // Not British citizen
    if (submitted.britishCitizen === 'no') {
        return res.redirect('../../outcome/END300')
    }

    res.render(`${__dirname}/views/questions/british-passport-nationality`)
})

/**
 * Question: Out of the UK for more than 4 weeks?
 */
router.all('/:type/questions/out-of-country', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Out of country?
    if (submitted.outOfCountryFourWeeks === 'yes') {
        return res.redirect(saved.britishCitizen === 'yes' ?
            './out-of-country-return-date' : './out-of-country-return-period')
    }

    // Not out of country
    if (submitted.outOfCountryFourWeeks === 'no') {

        if (saved.noPublicFunds === 'no') {
            return res.redirect('../../outcome/END103')
        }

        return res.redirect(saved.britishCitizen === 'yes' ?
            '../../outcome/END015' : '../../outcome/END102')
    }

    res.render(`${__dirname}/views/questions/out-of-country`)
})

/**
 * Question: Out of the UK since the card was issued?
 */
router.all('/:type/questions/out-of-country-since-date', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Date components
    saved.brpIssueDate = formatDate(saved.brpIssueDate)
    const { day, month, year, date } = saved.brpIssueDate

    // Out of country since card was issued?
    if (submitted.outOfCountryYesNo === 'yes' && day && month && year) {
        const twoYearsAgo = moment.utc().startOf('day').subtract(2, 'years')

        // Is the date valid but less than 2 years ago
        if (date.isValid() && date.isSameOrBefore(twoYearsAgo)) {
            return res.redirect('./out-of-country-settlement')
        }

        return res.redirect('./out-of-country-since-date')
    }

    // Not out of country since card was issued?
    if (submitted.outOfCountryYesNo === 'no') {
        return res.redirect('../../outcome/END102')
    }

    res.render(`${__dirname}/views/questions/out-of-country-since-date`)
})

/**
 * Question: Since date, what is the longest period out of the UK?
 */
router.all('/:type/questions/out-of-country-settlement', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Date components
    saved.brpIssueDate = formatDate(saved.brpIssueDate)
    const { date } = saved.brpIssueDate

    // Out of country more than 2 years?
    if (submitted.outOfCountry === 'over-two-years') {
        return res.redirect('../../outcome/END306')
    }

    // Out of country more than 4 weeks?
    if (submitted.outOfCountry === 'up-to-two-years') {
        const today = moment.utc().startOf('day')
        const oneMonthAgo = moment(today).subtract(1, 'month')

        // Permit issued on or less than one month ago? Skip return date check
        if (date.isValid() && date.isAfter(oneMonthAgo)) {
            saved.outOfUkReturnPeriod = 'up-to-one-month'
            return res.redirect('../../outcome/END006')
        }

        return res.redirect('./out-of-country')
    }

    // Out of country less than 4 weeks
    if (submitted.outOfCountry === 'up-to-four-weeks') {
        return res.redirect('../../outcome/END100')
    }

    res.render(`${__dirname}/views/questions/out-of-country-settlement`)
})

/**
 * Question: What is the longest period out of the UK?
 */
router.all('/:type/questions/out-of-country-longest-period', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.outOfCountry === 'up-to-two-years') {
        return res.redirect('../../outcome/END014')
    }

    if (submitted.outOfCountry === 'over-two-years') {
        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/out-of-country-longest-period`)
})

/**
 * Question: What date did they return?
 */
router.all('/:type/questions/out-of-country-return-date', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Date components
    saved.outOfUkReturn = formatDate(saved.outOfUkReturn)
    const { day, month, year, date } = saved.outOfUkReturn

    // All three date fields provided
    if (submitted.outOfUkReturn && day && month && year) {
        const today = moment.utc().startOf('day')

        // Is the date valid and in the past?
        if (date.isValid() && date.isBefore(today)) {
            // More than six months ago
            if (date.isBefore(moment(today).subtract(6, 'months'))) {
                return res.redirect('../../outcome/END101')
            }

            // More than one month ago
            if (date.isBefore(moment(today).subtract(1, 'month'))) {
                return res.redirect('./is-currently-employed')
            }

            // Less than or one month ago
            return res.redirect('../../outcome/END001')
        }
    }

    res.render(`${__dirname}/views/questions/out-of-country-return-date`)
})

/**
 * Question: How long have they been back?
 */
router.all('/:type/questions/out-of-country-return-period', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Less than 1 month
    if (submitted.outOfUkReturnPeriod === 'up-to-one-month') {
        return res.redirect('../../outcome/END006')
    }

    // Between 1 and 6 months
    if (submitted.outOfUkReturnPeriod === 'up-to-six-months') {
        return res.redirect('./is-currently-employed')
    }

    // Over six months
    if (submitted.outOfUkReturnPeriod === 'over-six-months') {
        if (saved.brpType === 'leave to remain' || saved.brpType === 'leave to enter' && saved.noPublicFunds === 'no') {
            return res.redirect('../../outcome/END103')
        }
        return res.redirect('../../outcome/END100')
    }

    res.render(`${__dirname}/views/questions/out-of-country-return-period`)
})

/**
 * Question: Is this person a refugee?
 */
router.all('/:type/questions/refugee', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Refugee?
    if (submitted.refugee === 'yes') {
        return res.redirect('./residence-permit-refugee')
    }

    // Not a refugee
    if (submitted.refugee === 'no') {
        return res.redirect('./nationality')
    }

    res.render(`${__dirname}/views/questions/refugee`)
})

/**
 * Question: Pre-settled status?
 */
router.all('/:type/questions/residence-pre-settled-status', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant;

    if (submitted.preSettledStatus === 'yes') {
        if (claimant.isEEA) {
            return res.redirect('./residence-sticker-blue')
        } else {
            return res.redirect('./residence-permit');
        }
    }

    if (submitted.preSettledStatus === 'no') {
        return res.redirect('./uk-december-2020-claimant')
    }

    res.render(`${__dirname}/views/questions/residence-pre-settled-status`)
})

/**
 * Question: claimant in UK December 2020?
 */
router.all('/:type/questions/uk-december-2020-claimant', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant;
    // UK national
    if (submitted.claimantUkDecember2020) {
        req.session.data.claimant.ukDecember2020 = submitted.claimantUkDecember2020;

        if (submitted.claimantUkDecember2020 === 'yes') {

            if (claimant.isEEA) {
                return res.redirect('./residence-sticker-blue')
            } else {
                return res.redirect('./family-permit')
            }
        }

        if (submitted.claimantUkDecember2020 === 'no') {
            if (claimant.isEEA) {
                return res.redirect('./family-permit')
            } else {

                return res.redirect('./family-permit')
            }
        }
    }
    res.render(`${__dirname}/views/questions/uk-december-2020-claimant`)
})

/**
 * Question: Does this person have a family permit?
 */
router.all('/:type/questions/family-permit', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant;
    // UK national
    if (submitted.claimantFamilyPermit === 'yes') {
        if (claimant.isEEA) {
            return res.redirect('../../outcome/END030')
        } else {
            if (claimant.ukDecember2020 === 'yes') {
                return res.redirect('../../outcome/END030')
            } else {
                return res.redirect('../../outcome/END032')
            }
        }
    }

    if (submitted.claimantFamilyPermit === 'no') {
        return res.redirect('./uk-december-2020-partner')
    }

    res.render(`${__dirname}/views/questions/family-permit`)
})

/**
 * Question: claimant partner in UK December 2020?
 */
router.all('/:type/questions/uk-december-2020-partner', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.partnerUkDecember2020 === 'yes') {
        return res.redirect('./nationality-partner')
    }

    if (submitted.partnerUkDecember2020 === 'no') {
        return res.redirect('./uk-december-2020-family-member')
    }

    res.render(`${__dirname}/views/questions/uk-december-2020-partner`)
})

/**
 * Question: claimant family member in UK December 2020?
 */
router.all('/:type/questions/uk-december-2020-family-member', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant;

    if (submitted.familyMemberUkDecember2020 === 'yes') {
        return res.redirect('./nationality-family-member')
    }

    if (submitted.familyMemberUkDecember2020 === 'no') {
        if (claimant.isEEA) {
            return res.redirect('../../outcome/END029')
        } else {
            if (claimant.ukDecember2020 === 'yes') {
                return res.redirect('./residence-permit')
            } else {
                return res.redirect('../../outcome/END033')
            }
        }
    }

    res.render(`${__dirname}/views/questions/uk-december-2020-family-member`)
})

/**
 * Question: Nationality?
 */
router.all('/:type/questions/nationality', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    // Claimant submitted answers
    if (type === 'claimant' && submitted.nationality) {
        saved.britishCitizen = 'no'

        if (claimant.nationality === 'country:GB') {
            return res.redirect('./british-passport-today')
        }

        if (claimant.nationality === 'country:IE') {
            return res.redirect('../../outcome/END001')
        }

        if (claimant.nationality === 'country:CH') {
            return res.redirect('./residence-sticker-pink')
        }

        if (claimant.nationality === 'country:BG') {
            return res.redirect('./residence-sticker-yellow')
        }

        if (claimant.nationality === 'country:HR' || claimant.nationality === 'country:RO') {
            return res.redirect('./residence-sticker-purple-or-yellow')
        }

        if (claimant.isCESC || claimant.isECSMA) {
            return res.redirect('../../outcome/END307')
        }

        if (claimant.isEEA || !claimant.isEEA) {
            return res.redirect('./residence-pre-settled-status')
        }
    }

    // Partner submitted answers
    if (type === 'partner' && submitted.nationality) {

        if (claimant.isEEA && claimant.dontWorkReason === 'other' && !partner.isEEA) {
            return res.redirect('../../outcome/END306')
        }
        if (claimant.isEEA && claimant.dontWorkReason === 'illness' && !partner.isEEA) {
            return res.redirect('../../outcome/END306')
        }

        if (!claimant.isEEA && partner.nationality === 'country:GB') {
            return res.redirect('../../outcome/END304')
        }

        if (!claimant.isEEA && partner.nationality === 'territory:IM') {
            return res.redirect('../../outcome/END304')
        }

        if (!claimant.isEEA && partner.nationality === 'country:IE') {
            return res.redirect('./employment-status')

        }

        if (!claimant.isEEA && !partner.isEEA) {
            return res.redirect('../../outcome/END304')
        }

        if (claimant.isEEA && !partner.isEEA) {
            return res.redirect('../../outcome/END304')
        }

        // Claimant and partner from Isle of Man
        if (claimant.nationality === 'territory:IM' && partner.nationality === 'territory:IM') {
            return res.redirect('../../outcome/END012')
        }

        // Claimant is ill
        if (claimant.dontWorkReason === 'illness') {
            if (partner.nationality === 'country:GB') {
                return res.redirect('../../outcome/END012')
            }
        }

        // Claimant is unemployed
        if (claimant.dontWorkReason === 'other') {

            if (['country:IE', 'territory:IM'].includes(claimant.nationality)) {
                return res.redirect('../../outcome/END303')
            }
        }

        // Partner from UK, Ireland or Isle of Man
        if (['country:GB', 'country:IE', 'territory:IM'].includes(partner.nationality)) {
            return res.redirect('../../outcome/END303')
        }

        if (partner.isEEA) {

            return res.redirect('./partnership-household')
        }

        return res.redirect('../../outcome/END306')
    }

    res.render(`${__dirname}/views/questions/nationality`, {
        items: countries.list(saved.nationality)
    })
})

/**
 * Question: Partner nationality?
 */
router.all('/:type/questions/nationality-partner', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant
    if (submitted.nationalityPartner) {
        const isEEA = countries.isEEA(submitted.nationalityPartner);
        if (submitted.nationalityPartner === 'country:GB') {
            if (claimant.isEEA) {
                return res.redirect('../../outcome/END303');
            } else {
                return res.redirect('../../outcome/END304');
            }
        } else if (isEEA) {
            return res.redirect('../../outcome/END030')
        } else if (!isEEA) {
            if (claimant.isEEA) {
                return res.redirect('../../outcome/END029')
            } else {
                if(claimant.ukDecember2020 === 'yes') {
                return res.redirect('./residence-permit')
                } else {
                    return res.redirect('../../outcome/END033')
                }
            }
        }

    }
    res.render(`${__dirname}/views/questions/nationality-partner`, {
        items: countries.list(submitted.nationalityPartner || "")
    })
})

/**
 * Question: Family member nationality?
 */
router.all('/:type/questions/nationality-family-member', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const claimant = req.session.data.claimant

    if (submitted.nationalityFamilyMember) {
        const isEEA = countries.isEEA(submitted.nationalityFamilyMember);
        if (submitted.nationalityFamilyMember === 'country:GB') {
            if (claimant.isEEA) {
                return res.redirect('../../outcome/END303');
            } else {
                return res.redirect('../../outcome/END303')
            }
        } else if (isEEA) {
            return res.redirect('../../outcome/END030')
        }
        if (claimant.isEEA) {
            return res.redirect('../../outcome/END029')
        } else {
            if (claimant.ukDecember2020 === 'yes') {
                return res.redirect('./residence-permit')
            } else {
                return res.redirect('../../outcome/END033')
            }
        }
    }

    res.render(`${__dirname}/views/questions/nationality-family-member`, {
        items: countries.list(submitted.nationality || "")
    })
})

/**
 * Question: Have they brought their residence document today?
 */
router.all('/:type/questions/residence-document-check-blue', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerConfirmation === 'yes') {
        return res.redirect('../../outcome/END022')
    }

    if (submitted.residenceStickerConfirmation === 'no') {
        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/residence-document-check-blue`)
})

/**
 * Question: Have they brought their residence document today?
 */
router.all('/:type/questions/residence-document-check-pink', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerConfirmationPink === 'yes') {
        return res.redirect('../../outcome/END022')
    }

    if (submitted.residenceStickerConfirmationPink === 'no') {
        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/residence-document-check-pink`)
})

/**
 * Question: Have they brought their residence document today?
 */
router.all('/:type/questions/residence-document-check-yellow', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerConfirmationYellow === 'yes') {
        return res.redirect('../../outcome/END022')
    }

    if (submitted.residenceStickerConfirmationYellow === 'no') {
        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/residence-document-check-yellow`)
})

/**
 * Question: Have they brought their residence document today?
 */
router.all('/:type/questions/residence-document-check-purple', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerConfirmationPurple === 'yes') {
        return res.redirect('../../outcome/END022')
    }

    if (submitted.residenceStickerConfirmationPurple === 'no') {
        return res.redirect('./employment-status')
    }
    res.render(`${__dirname}/views/questions/residence-document-check-purple`)
})

/**
 * Question: Have they brought a pink card with a residence sticker in it?
 */
router.all('/:type/questions/residence-sticker-pink', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerPink === 'yes') {
        return res.redirect('./residence-sticker-issued')
    }

    if (submitted.residenceStickerPink === 'no') {
        return res.redirect('./residence-document-check-pink')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-pink`)
})

/**
 * Question: Have they brought a yellow card with a residence sticker in it?
 */
router.all('/:type/questions/residence-sticker-yellow', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerYellow === 'yes') {
        return res.redirect('./residence-sticker-issued')
    }

    if (submitted.residenceStickerYellow === 'no') {
        return res.redirect('./residence-document-check-yellow')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-yellow`)
})

/**
 * Question: Have they brought a purple or yellow card with a residence sticker in it?
 */
router.all('/:type/questions/residence-sticker-purple-or-yellow', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerPurpleYellow === 'yes') {
        return res.redirect('./residence-sticker-issued')
    }

    if (submitted.residenceStickerPurpleYellow === 'no') {
        return res.redirect('./residence-document-check-purple')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-purple-or-yellow`)
})

/**
 * Question: Have they brought a blue card with a residence sticker in it?
 */
router.all('/:type/questions/residence-sticker-blue', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerBlue === 'yes') {
        return res.redirect('./residence-sticker-issued')
    }

    if (submitted.residenceStickerBlue === 'no') {
        return res.redirect('./residence-document-check-blue')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-blue`)
})

/**
 * Question: Where was the document issued?
 */
router.all('/:type/questions/residence-sticker-issued', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerIssued) {
        if (submitted.residenceStickerIssued === 'none') {
            return res.redirect('./employment-status')
        }

        return res.redirect('./residence-sticker-type')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-issued`)
})

/**
 * Question: What's under 'type of document'?
 */
router.all('/:type/questions/residence-sticker-type', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerType) {
        if (submitted.residenceStickerType === 'none') {
            return res.redirect('./residence-sticker-type-more')
        }

        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-type`)
})

/**
 * Question: Do either of these appear under 'type of document'?
 */
router.all('/:type/questions/residence-sticker-type-more', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residenceStickerTypeMore) {
        if (['certDoc', 'permanent'].includes(submitted.residenceStickerTypeMore)) {
            return res.redirect('./out-of-country-longest-period')
        }

        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/residence-sticker-type-more`)
})

/**
 * Question: Have they been living in the UK for the last 5 years?
 */
router.all('/:type/questions/in-country-five-years', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.inCountry) {
        return res.redirect('./employment-status')
    }

    res.render(`${__dirname}/views/questions/in-country-five-years`)
})

/**
 * Question: Have they brought a residence permit?
 */
router.all('/:type/questions/residence-permit', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Refugee with/without permit
    if (saved.refugee === 'yes') {
        if (submitted.brp === 'yes') {
            return res.redirect('./residence-permit-type-refugee')
        }

        if (submitted.brp === 'no') {
            return res.redirect('../../outcome/END008')
        }
    }

    // Anyone else with/without permit
    if (saved.refugee === 'no') {
        if (submitted.brp === 'yes') {
            return res.redirect('./residence-permit-expired')
        }

        if (submitted.brp === 'no') {
            return res.redirect('./residence-permit-fei')
        }
    }

    res.render(`${__dirname}/views/questions/residence-permit`)
})

/**
 * Question: Can they bring a Biometric Residence Permit (BRP) or Residence Card to another appointment?
 */
router.all('/:type/questions/residence-permit-fei', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.residencePermitFei === 'yes') {
        return res.redirect('../../outcome/END027')
    }

    if (submitted.residencePermitFei === 'no') {
        return res.redirect('./no-public-funds')
    }

    res.render(`${__dirname}/views/questions/residence-permit-fei`)
})

/**
 * Question: Which of the following words are shown?
 */
router.all('/:type/questions/residence-permit-type', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    // Leave to remain/enter
    if (submitted.brpType === 'leave to remain' || submitted.brpType === 'leave to enter') {
        return res.redirect('./no-public-funds-residence-permit')
    }

    // Check for leave time for settlement
    if (submitted.brpType === 'settlement') {
        return res.redirect('./residence-permit-issue-date')
    }

    // Residence or EU Scheme pre-settlement
    if (submitted.brpType === 'residence' || submitted.brpType === 'eu scheme pre-settlement') {
        return res.redirect('./residence-permit-sub-type')
    }

    // EU Scheme settlement
    if (submitted.brpType === 'eu scheme settlement') {
        return res.redirect('./residence-out-of-uk')
    }

    res.render(`${__dirname}/views/questions/residence-permit-type`)
})

/**
 * Question: In the last 2 years, have they been out of the UK for 4 weeks or more in a single trip?
 */
router.all('/:type/questions/residence-out-of-uk', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    console.log(submitted)
    if (submitted.outOfUk === 'yes') {
        return res.redirect('./residence-return-to-uk')
    }

    if (submitted.outOfUk === 'no') {
        return res.redirect('../../outcome/END105')
    }

    res.render(`${__dirname}/views/questions/residence-out-of-uk`);
});

/**
 * Question: When did they return to the UK from their most recent trip of 4 weeks or more?
 */
router.all('/:type/questions/residence-return-to-uk', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.returnToUk === 'less than one month ago') {
        return res.redirect('../../outcome/END028')
    }

    if (submitted.returnToUk === 'between 1 and 6 months ago') {
        return res.redirect('./residence-currently-working')
    }

    if (submitted.returnToUk === '6 months ago or more') {
        return res.redirect('../../outcome/END105')
    }

    res.render(`${__dirname}/views/questions/residence-return-to-uk`);
});

/**
 * Question: Are they currently working?
 */
router.all('/:type/questions/residence-currently-working', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.currentlyWorking === 'yes') {
        return res.redirect('../../outcome/END105')
    }

    if (submitted.currentlyWorking === 'no') {
        return res.redirect('../../outcome/END028')
    }

    res.render(`${__dirname}/views/questions/residence-currently-working`);
});

/**
 * Question: What's the permit issue date?
 */
router.all('/:type/questions/residence-permit-issue-date', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Date components
    saved.brpIssueDate = formatDate(saved.brpIssueDate)
    const { day, month, year, date } = saved.brpIssueDate

    // All three date fields provided
    if (submitted.brpIssueDate && day && month && year) {
        const today = moment.utc().startOf('day')
        const fourWeeksAgo = moment(today).subtract(4, 'weeks')
        const twoYearsAgo = moment(today).subtract(2, 'years')

        // Is the date valid but less than 4 weeks ago?
        if (date.isValid() && date.isSameOrAfter(fourWeeksAgo)) {
            return res.redirect('../../outcome/END100')
        }

        // Is the date valid and two or more years ago
        if (date.isValid() && date.isSameOrBefore(twoYearsAgo)) {
            return res.redirect('./out-of-country-since-date')
        }

        // Is the date valid and in the past?
        if (date.isValid() && date.isBefore(today)) {
            return res.redirect('./out-of-country')
        }
    }

    res.render(`${__dirname}/views/questions/residence-permit-issue-date`)
})

/**
 * Question: Which other words are shown?
 */
router.all('/:type/questions/residence-permit-sub-type', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.brpSubType) {
        // Full HRT required for permanent residents
        if (submitted.brpSubType === 'residence-permanent') {
            return res.redirect('../../outcome/END306')
        }

        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/residence-permit-sub-type`)
})

/**
 * Question: Does the permit type state REFUGEE?
 */
router.all('/:type/questions/residence-permit-type-refugee', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Permit says refugee?
    if (submitted.permitTypeRefugee === 'yes') {
        return res.redirect('./residence-permit-expired-refugee')
    }

    // Permit doesn't say refugee
    if (submitted.permitTypeRefugee === 'no') {
        return res.redirect('./no-public-funds')
    }

    res.render(`${__dirname}/views/questions/residence-permit-type-refugee`)
})

/**
 * Question: Have they got a Biometric Residence Permit (BRP)?
 */
router.all('/:type/questions/residence-permit-refugee', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Refugee with a BRP
    if (submitted.brp === 'yes') {
        return res.redirect('./residence-permit-type-refugee')
    }

    // Refugee without a BRP
    if (submitted.brp === 'no') {
        return res.redirect('residence-permit-refugee-check')
    }

    res.render(`${__dirname}/views/questions/residence-permit-refugee`)
})

/**
 * Question: Have they brought their Biometric Residence Permit (BRP) today?
 */
router.all('/:type/questions/residence-permit-refugee-check', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Permit says refugee?
    if (submitted.permitTypeRefugeeCheck === 'yes') {
        return res.redirect('../../outcome/END020')
    }

    // Permit doesn't say refugee
    if (submitted.permitTypeRefugeeCheck === 'no') {
        return res.redirect('../../outcome/END008')
    }

    res.render(`${__dirname}/views/questions/residence-permit-refugee-check`)
})

/**
 * Question: Has the card expired?
 */
router.all('/:type/questions/residence-permit-expired', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Card expired?
    if (submitted.permitExpired === 'yes') {
        return res.redirect('../../outcome/END306')
    }

    // Card hasn't expired
    if (submitted.permitExpired === 'no') {
        // Refugee with permit
        if (saved.refugee === 'yes') {
            return res.redirect('../../outcome/END018')
        }

        return res.redirect('./residence-permit-type')
    }

    res.render(`${__dirname}/views/questions/residence-permit-expired`)
})

/**
 * Question: Has the permit expired?
 */
router.all('/:type/questions/residence-permit-expired-refugee', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Card expired?
    if (submitted.permitExpiredRefugee === 'yes') {
        return res.redirect('../../outcome/END301')
    }

    // Card hasn't expired
    if (submitted.permitExpiredRefugee === 'no') {
        // Refugee with permit
        if (saved.refugee === 'yes') {
            return res.redirect('../../outcome/END018')
        }

        return res.redirect('./residence-permit-type')
    }

    res.render(`${__dirname}/views/questions/residence-permit-expired-refugee`)
})

/**
 * Question: Visa says no public funds?
 */
router.all('/:type/questions/no-public-funds(-residence-permit)?', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Visa says "no public funds"
    if (submitted.noPublicFunds === 'yes') {
        return res.redirect(saved.brp === 'no' ?
            '../../outcome/END005' : '../../outcome/END004')
    }

    // Visa doesn't say "no public funds"
    if (submitted.noPublicFunds === 'no') {
        if (saved.brpType === 'leave to remain' || saved.brpType === 'leave to enter') {
            return res.redirect('./out-of-country')
        }

        return res.redirect('./family-member')
    }

    let view = `${__dirname}/views/questions/no-public-funds`

    // Change to BRP copy variant
    if (req.originalUrl.includes('-residence-permit')) {
        view = `${__dirname}/views/questions/no-public-funds-residence-permit`
    }

    res.render(view)
})

/**
 * Question: Have they been employed for 3 months or more?
 */
router.all('/:type/questions/eea-worker-employed-three-months-or-more', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employedThreeMonths === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.employedThreeMonths === 'no') {
        return res.redirect('./eea-worker-with-permanent-employment-contract')
    }

    res.render(`${__dirname}/views/questions/eea-worker-employed-three-months-or-more`)
})

/**
 * Question: Were they employed for 3 months or more before they stopped working?
 */
router.all('/:type/questions/previously-employed-for-3-months-or-more', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.threeMonthsStopped === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.threeMonthsStopped === 'no') {
        return res.redirect('./eea-worker-with-permanent-employment-contract')
    }

    res.render(`${__dirname}/views/questions/previously-employed-for-3-months-or-more`)
})

/**
 * Question: Have they got a permanent employment contract?
 */
router.all('/:type/questions/eea-worker-with-permanent-employment-contract', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.permanentContract === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.permanentContract === 'no') {
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/eea-worker-with-permanent-employment-contract`)
})

/**
 * Question: Does this person have a job?
 */
router.all('/:type/questions/employment-status', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    // Not working
    if ((submitted.employmentStatus || []).includes('dontWork')) {
        if (type === 'partner' && partner.nationality === 'country:IE' && !claimant.isEEA) {
            return res.redirect('./employment-status-not-working-partner')
        }

        return res.redirect('./employment-status-not-working')
    }

    // Self employed
    if ((submitted.employmentStatus || []).includes('selfEmployed')) {

        if (type === 'partner' && partner.isEEA && claimant.refugee === 'yes' && claimant.permitTypeRefugee === 'no') {
            return res.redirect('../../outcome/END301')
        }

        if (type === 'partner' && partner.isEEA && claimant.isEEA) {
            return res.redirect('../../outcome/END303')
        }
        if (type === 'partner' && partner.nationality === 'country:IE' && !claimant.isEEA) {
            return res.redirect('../../outcome/END304')
        }

        return res.redirect('../../outcome/END302')
    }

    // Employed or self-employed
    if ((submitted.employmentStatus || []).includes('employed') && (submitted.employmentStatus || []).includes('selfEmployed')) {

        if (type === 'partner' && partner.nationality === 'country:IE' && !claimant.isEEA) {
            return res.redirect('../../outcome/END304')
        }
    }
    // Employed and self-employed
    if ((submitted.employmentStatus || []).includes('employedAndSelfEmployed')) {

        if (type === 'partner' && partner.nationality === 'country:IE' && !claimant.isEEA) {
            return res.redirect('../../outcome/END304')
        }

        return res.redirect('../../outcome/END302')

    }

    // Employed
    if ((submitted.employmentStatus || []).includes('employed')) {

        if (type === 'partner' && partner.isEEA && claimant.refugee === 'yes' && claimant.permitTypeRefugee === 'no') {
            return res.redirect('../../outcome/END301')
        }

        if (type === 'partner' && claimant.isEEA) {
            return res.redirect('../../outcome/END012')
        }

        if (type === 'partner' && !claimant.isEEA) {
            return res.redirect('../../outcome/END013')
        }

        return res.redirect('./employment-payslips-confirm')
    }

    res.render(`${__dirname}/views/questions/employment-status`)
})

/**
 * Question: Have they brought payslips or bank statements covering the last 3 months?
 */
router.all('/:type/questions/employment-payslips-confirm', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentPayslipsConfirm === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.employmentPayslipsConfirm === 'no') {
        return res.redirect('./employment-payslips-evidence')
    }

    res.render(`${__dirname}/views/questions/employment-payslips-confirm`)
})

/**
 * Question: Have they brought payslips or bank statements covering the last month, and a permanent contract?
 */
router.all('/:type/questions/employment-payslips-evidence', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentPayslipsEvidence === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.employmentPayslipsEvidence === 'no') {
        return res.redirect('./employment-evidence-fei')
    }

    res.render(`${__dirname}/views/questions/employment-payslips-evidence`)
})

/**
 * Question: Can they provide the following?
 */
router.all('/:type/questions/employment-status(-not-working)?-evidence', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    if (['most-recent', 'three-months'].includes(submitted.employmentStatusEvidence)) {
        if (saved.dontWorkReason === 'redundant') {
            return res.redirect('../../outcome/END010')
        }

        if (saved.dontWorkReason === 'illness') {
            return res.redirect('../../outcome/END011')
        }

        return res.redirect('./employment-status-confirm')
    }

    if (submitted.employmentStatusEvidence === 'none') {
        return res.redirect('./employment-evidence-fei')
    }

    let view = `${__dirname}/views/questions/employment-status-evidence`

    // Change to not working copy variant
    if (req.originalUrl.includes('-not-working')) {
        view = `${__dirname}/views/questions/employment-status-not-working-evidence`
    }

    res.render(view)
})

/**
* Question: Can they bring their fit notes to another appointment?
*/
router.all('/:type/questions/employment-status-fit-note-confirm', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentStatusFitNoteConfirm === 'yes') {
        return res.redirect('./employment-status-fei')
    }

    if (submitted.employmentStatusFitNoteConfirm === 'no') {
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/employment-status-fit-note-confirm`)
})

/**
* Question: Does this person have a letter stating that they have been made redundant from their most recent job?
*/
router.all('/:type/questions/redundancy-letter', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.redundancyLetter === 'yes') {
        return res.redirect('./type-of-redundancy')
    }

    if (submitted.redundancyLetter === 'no') {
        return res.redirect('../../outcome/END305')
    }

    res.render(`${__dirname}/views/questions/redundancy-letter`)
})

/**
 * Question: Does this person have a letter stating that they have been made redundant from their most recent job?
 */
router.all('/:type/questions/redundancy-a-month', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.redundancyAMonth === 'yes') {
        return res.redirect('./employment-status-not-working-evidence')
    }

    if (submitted.redundancyAMonth === 'no') {
        return res.redirect('../../outcome/END305')
    }

    res.render(`${__dirname}/views/questions/redundancy-a-month`)
})

/**
* Question: What type of redundancy did this person take?
*/
router.all('/:type/questions/type-of-redundancy', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.typeOfRedundancy === 'compulsory') {
        return res.redirect('./redundancy-a-month')
    }

    if (submitted.typeOfRedundancy === 'voluntary') {
        return res.redirect('../../outcome/END305')
    }

    if (submitted.typeOfRedundancy === 'no') {
        return res.redirect('../../outcome/END305')
    }

    res.render(`${__dirname}/views/questions/type-of-redundancy`)
})

/**
* Question: Can they bring their employment evidence to another appointment?
*/
router.all('/:type/questions/employment-status-fei', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentStatusFEI === 'three-months') {
        return res.redirect('../../outcome/END025')
    }

    if (submitted.employmentStatusFEI === 'most-recent') {
        return res.redirect('../../outcome/END025')
    }

    if (submitted.employmentStatusFEI === 'none') {
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/employment-status-fei`)
})

/**
 * Question: Have they brought this evidence today?
 */
router.all('/:type/questions/employment-status-confirm', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentStatusConfirm === 'yes') {
        return res.redirect('../../outcome/END002')
    }

    if (submitted.employmentStatusConfirm === 'no') {
        return res.redirect('../../outcome/END021')
    }

    res.render(`${__dirname}/views/questions/employment-status-confirm`)
})

/**
 * Question: Are they currently working?
 */
router.all('/:type/questions/is-currently-employed', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    let outcomeDecisionBritish = '../../outcome/END101'
    let outcomeDecisionOther = '../../outcome/END100'
    let outcomeBritish = '../../outcome/END001'
    let outcomeOther = '../../outcome/END006'

    // BRP provided
    if (saved.brp === 'no') {
        outcomeOther = '../../outcome/END007'
    }

    // Working
    if ((submitted.employmentStatus || []).includes('employed')) {

        if (saved.brpType === 'leave to remain' || saved.brpType === 'leave to enter' && saved.outOfUkReturnPeriod === 'up-to-six-months') {
            return res.redirect('../../outcome/END103')
        }

        return res.redirect(saved.britishCitizen === 'yes' ?
            outcomeDecisionBritish : outcomeDecisionOther)
    }

    // Not working
    if ((submitted.employmentStatus || []).includes('dontWork')) {
        return res.redirect(saved.britishCitizen === 'yes' ?
            outcomeBritish : outcomeOther)
    }

    res.render(`${__dirname}/views/questions/is-currently-employed`)
})

/**
 * Question: Why aren't they working?
 */
router.all('/:type/questions/employment-status-not-working', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    // Not working because redundant + partner
    if (submitted.dontWorkReason === 'redundant') {

        if (type === 'partner' && partner.isEEA && claimant.isEEA) {
            return res.redirect('../../outcome/END303')
        }
        if (type === 'partner' && claimant.isEEA) {
            return res.redirect('../../outcome/END012')
        }

        if (type === 'partner' && !claimant.isEEA) {
            return res.redirect('../../outcome/END013')
        }

        // Not working because redundant
        return res.redirect('./previously-employed-for-3-months-or-more')
    }

    if (submitted.dontWorkReason === 'corona') {
        return res.redirect('./previously-employed-for-3-months-or-more')
    }

    // Not working because ill
    if (submitted.dontWorkReason === 'illness') {
        return res.redirect('./previously-employed-for-3-months-or-more')
    }

    // Not working because of other reason + partner
    if (submitted.dontWorkReason === 'other') {
        if (type === 'partner') {

            if (partner.isEEA && claimant.refugee === 'yes' && claimant.permitTypeRefugee === 'no') {
                return res.redirect('../../outcome/END301')
            }

            if (partner.isEEA && claimant.isEEA) {
                return res.redirect('../../outcome/END303')
            }

            return res.redirect('../../outcome/END303')
        }

        // Not working because of other reason
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/employment-status-not-working`)
})

/**
* Question: Why aren't they working? (Partner)
*/
router.all('/:type/questions/employment-status-not-working-partner', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    // Not working because redundant + partner
    if (submitted.dontWorkReason === 'redundant') {

        if (type === 'partner' && partner.isEEA && claimant.isEEA) {
            return res.redirect('../../outcome/END303')
        }
        if (type === 'partner' && claimant.isEEA) {
            return res.redirect('../../outcome/END012')
        }

        if (type === 'partner' && !claimant.isEEA) {
            return res.redirect('../../outcome/END013')
        }

        // Not working because redundant
        return res.redirect('./previously-employed-for-3-months-or-more')
    }

    // Not working because ill
    if (submitted.dontWorkReason === 'illness') {
        return res.redirect('./employment-status-fit-note')
    }

    // Not working because of other reason + partner
    if (submitted.dontWorkReason === 'other') {
        if (type === 'partner') {

            if (partner.isEEA && claimant.refugee === 'yes' && claimant.permitTypeRefugee === 'no') {
                return res.redirect('../../outcome/END301')
            }

            if (partner.isEEA && claimant.isEEA) {
                return res.redirect('../../outcome/END303')
            }

            return res.redirect('../../outcome/END303')
        }

        // Not working because of other reason
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/employment-status-not-working-partner`)
})

/**
 * Question: Have they had constant fit notes?
 */
router.all('/:type/questions/employment-status-fit-note', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    if (submitted.fitNote === 'yes') {
        if (type === 'partner' && claimant.isEEA) {
            return res.redirect('../../outcome/END012')
        }

        if (type === 'partner' && !claimant.isEEA) {
            return res.redirect('../../outcome/END013')
        }

        return res.redirect('./employment-status-not-working-evidence')
    }

    if (submitted.fitNote === 'no' || submitted.fitNote === 'dontKnow') {

        if (type === 'partner' && partner.isEEA && claimant.refugee === 'yes' && claimant.permitTypeRefugee === 'no') {
            return res.redirect('../../outcome/END301')
        }

        if (type === 'partner' && partner.isEEA && claimant.isEEA) {
            return res.redirect('../../outcome/END303')
        }

        if (type === 'partner') {
            return res.redirect('../../outcome/END303')
        }

        return res.redirect('./employment-status-fit-note-confirm')
    }

    res.render(`${__dirname}/views/questions/employment-status-fit-note`)
})

/**
 * Question: What evidence can they bring to another appointment?
 */
router.all('/:type/questions/employment-evidence-fei', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.employmentEvidenceFei === 'three-months') {
        return res.redirect('../../outcome/END021')
    }

    if (submitted.employmentEvidenceFei === 'most-recent') {
        return res.redirect('../../outcome/END104')
    }

    if (submitted.employmentEvidenceFei === 'none') {
        return res.redirect('./married-or-civil-partner')
    }

    res.render(`${__dirname}/views/questions/employment-evidence-fei`)
})

/**
 * Question: Is this person living in the same household as their partner?
 */
router.all('/:type/questions/partnership-household', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]

    if (submitted.partnershipHousehold === 'yes') {
        return res.redirect('./employment-status')
    }

    if (submitted.partnershipHousehold === 'no') {
        return res.redirect('../../outcome/END303')
    }

    res.render(`${__dirname}/views/questions/partnership-household`)
})

/**
 * Question: Visa says family member?
 */
router.all('/:type/questions/family-member', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Visa says "family member"
    if (submitted.familyMember === 'yes') {
        if (type === 'partner') {
            return res.redirect('../../outcome/END303')
        }

        return res.redirect('./married-or-civil-partner')
    }

    // Visa doesn't say "family member"
    if (submitted.familyMember === 'no') {
        return res.redirect(saved.brp === 'no' ?
            '../../outcome/END007' : '../../outcome/END006')
    }

    res.render(`${__dirname}/views/questions/family-member`)
})

/**
 * Question: Married or civil partner?
 */
router.all('/:type/questions/married-or-civil-partner', (req, res) => {
    const type = req.params.type
    const submitted = req.body[type]
    const saved = req.session.data[type]

    // Saved data by type
    const claimant = req.session.data.claimant
    const partner = req.session.data.partner

    // Married or civil partner?
    if (submitted.partner === 'yes') {
        return res.redirect('../../partner/questions/nationality')
    }

    // No partner
    if (submitted.partner === 'no') {
        if (saved.brpType === 'leave to remain' || saved.brpType === 'leave to enter') {
            return res.redirect('../../outcome/END006')
        }

        if (saved.refugee === 'yes' && saved.permitTypeRefugee === 'no') {
            return res.redirect('../../outcome/END301')
        }

        if (claimant.isEEA && claimant.dontWorkReason === 'redundant') {
            return res.redirect('../../outcome/END305')
        }

        if (claimant.isEEA && claimant.dontWorkReason === 'illness') {
            return res.redirect('../../outcome/END305')
        }

        if (claimant.isEEA && claimant.dontWorkReason === 'other') {
            return res.redirect('../../outcome/END305')
        }

        if (!claimant.isEEA && saved.brpSubType === 'residence-derivative') {
            return res.redirect('../../outcome/END306')
        }

        if (!claimant.isEEA && saved.brpSubType === 'residence-family-member-eu') {
            return res.redirect('../../outcome/END306')
        }

        return res.redirect('../../outcome/END302')
    }

    res.render(`${__dirname}/views/questions/married-or-civil-partner`)
})

/**
 * Outcome
 */
router.all('/outcome/:outcome', (req, res) => {
    res.render(`${__dirname}/views/outcomes/${req.params.outcome}`)
})

/**
 * Format date for display
 */
function formatDate({ day, month, year } = {}) {
    day = day ? day.padStart(2, '0') : ''
    month = month ? month.padStart(2, '0') : ''
    year = year || ''

    // Apply formatting
    const date = moment.utc(`${year}-${month}-${day}`, 'YYYY-MM-DD', true)
    const formatted = date.isValid() ? date.format('D MMM YYYY') : ''

    return {
        day,
        month,
        year,
        date,
        formatted
    }
}

module.exports = router


text:
require 'spec_helper'

describe Projects::MergeRequestsController do
  let(:project) { create(:project) }
  let(:user)    { create(:user) }
  let(:merge_request) { create(:merge_request_with_diffs, target_project: project, source_project: project) }

  before do
    sign_in(user)
    project.team << [user, :master]
  end

  describe "#show" do
    shared_examples "export merge as" do |format|
      it "should generally work" do
        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response).to be_success
      end

      it "should generate it" do
        MergeRequest.any_instance.should_receive(:"to_#{format}")

        get :show, project_id: project.to_param, id: merge_request.iid, format: format
      end

      it "should render it" do
        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response.body).to eq((merge_request.send(:"to_#{format}",user)).to_s)
      end

      it "should not escape Html" do
        MergeRequest.any_instance.stub(:"to_#{format}").and_return('HTML entities &<>" ')

        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response.body).to_not include('&')
        expect(response.body).to_not include('>')
        expect(response.body).to_not include('<')
        expect(response.body).to_not include('"')
      end
    end

    describe "as diff" do
      include_examples "export merge as", :diff
      let(:format) { :diff }

      it "should really only be a git diff" do
        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response.body).to start_with("diff --git")
      end
    end

    describe "as patch" do
      include_examples "export merge as", :patch
      let(:format) { :patch }

      it "should really be a git email patch with commit" do
        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response.body[0..100]).to start_with("From #{merge_request.commits.last.id}")
      end

      it "should contain git diffs" do
        get :show, project_id: project.to_param, id: merge_request.iid, format: format

        expect(response.body).to match(/^diff --git/)
      end
    end
  end
end


text:
"""
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

""" reassign endpoints """
from fastapi import APIRouter, Response, status, HTTPException
from typing import List, Dict
from common.models import Document
from common.db_client import bq_client
from common.utils.format_data_for_bq import format_data_for_bq
from common.utils.stream_to_bq import stream_document_to_bigquery
# from common.utils.copy_gcs_documents import copy_blob
from common.utils.logging_handler import Logger
from common.config import BUCKET_NAME
from common.config import STATUS_IN_PROGRESS, STATUS_SUCCESS, STATUS_ERROR
from common.config import PROCESS_TASK_API_PATH
from google.cloud import storage
# disabling for linting to pass
# pylint: disable = broad-except
import re
import datetime
import requests
from models.reassign import Reassign
import fireo
import traceback

router = APIRouter()

@router.post("/reassign_case_id")
async def reassign_case_id(reassign: Reassign, response: Response):
  """
  Reassigns case_id of given document
    Args:
    old_case_id (str): Case id of the supporting
    document which need to be reassigned ,
    uid (str) : unique Id of the supportingdocument
    new_case_id :existing application form case_id
    user : username of person who is reassigning the document
    comment : comment put by user
    Returns:
      200 : Successfully reassigned the document
      404 :document to be reassigne is not found
      404 : new_case_id application not found
      400 : If old case_id and new_case_id is same
      406 : if given document with old case_id is
      application and cannot be reassigned
      500 :  Some unexpected error occured
    """
  try:
    reassign_dict = reassign.dict()
    uid = reassign_dict.get("uid")
    old_case_id = reassign_dict.get("old_case_id")
    new_case_id = reassign_dict.get("new_case_id")
    user = reassign_dict.get("user")
    comment = reassign_dict.get("comment")

    #Check if the old case_id and new_case_id is same
    #send bad request error
    # if old_case_id == new_case_id:
    #   response.status_code = status.HTTP_400_BAD_REQUEST
    #   response.body = f"The  existing case_id {old_case_id}and new " \
    #               f"case_id {new_case_id} is" \
    #               f" same enter different case_id"
    #   return {"message": response.body}

    document = Document.find_by_uid(uid)
    #If document with given uid does not exist send 404
    # not found error
    if document is None:
      Logger.error(f"document to be reassigned with case_id {old_case_id}"
                   f" and uid {uid} does not exist in database")
      response.status_code = status.HTTP_404_NOT_FOUND
      response.body = f"document to be reassigned with case_id {old_case_id} " \
                      f"and uid {uid} does not exist in database"
      return {"message": response.body}

    #if given document with old case_id is application and cannot be
    # reassigned send user response that this file is not acceptable
    if document.document_type == "application_form":
      Logger.error(
          f"document to be reassigned with case_id {old_case_id}"
          f" and uid {uid} is application form and cannot be reassigned")
      response.status_code = status.HTTP_406_NOT_ACCEPTABLE
      response.body =f"document to be reassigned with case_id {old_case_id}" \
                  f" and uid {uid} is application form and cannot be reassigned"
      return {"message": response.body}
    new_case_id_document  = Document.collection.filter(case_id=new_case_id).\
      filter(document_type ="application_form").get()
    print("After new case_id check")
    print(f"new_case_id_document: {new_case_id_document}")
    #application with new case case_id does not exist in db
    #send 404 not found error
    if not new_case_id_document:
      Logger.error(
          f"Document with case_id {new_case_id} not found for reassign")
      response.status_code = status.HTTP_404_NOT_FOUND
      response.body = f"Application with case_id {new_case_id}" \
      f" does not exist in database to reassigne supporting doc " \
      f"{old_case_id} and uid {uid}"
      return {"message": response.body}

    client = bq_client()
    gcs_source_url = document.url
    document_class = document.document_class
    document_type = document.document_type
    entities = document.entities
    context = document.context
    extraction_score = document.extraction_score

    #remove the prefix of bucket name from gcs_url to get blob name
    prefix_name = f"gs://{BUCKET_NAME}/"
    source_blob_name = re.sub(prefix_name, "", gcs_source_url, 1)
    print(f"source_blob_name: {source_blob_name}")

    #remove the prefix of old_case_id and give new case_id for
    # destination folder in gcs
    destination_blob_name = re.sub(old_case_id, new_case_id, source_blob_name,
                                   1)
    print(f"destination_blob_name: {destination_blob_name}")

    if source_blob_name == destination_blob_name:
      return {"status": STATUS_SUCCESS, "url": document.url}

    status_copy_blob = copy_blob(BUCKET_NAME, source_blob_name,
                                 destination_blob_name)

    # check if moving file in gcs is sucess
    if status_copy_blob != STATUS_SUCCESS:
      response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
      response.body = f"Error in copying files in " \
     f"gcs bucket from source folder {old_case_id},destination" \
          f" {new_case_id} "
      return {"message": response.body}

    print("----------Updating firestore-----------")
    #Update Firestore databse
    document.case_id = new_case_id
    updated_url = prefix_name + destination_blob_name
    document.url = updated_url
    # Update HITL audit trail for reassigned action
    hitl_audit_trail = {
        "status": "reassigned",
        "timestamp": datetime.datetime.utcnow(),
        "user": user,
        "comment": comment,
        "old_case_id": old_case_id,
        "new_case_id": new_case_id,
        "action": f"reassigned from {old_case_id} to {new_case_id}"
    }
    document.hitl_status = fireo.ListUnion([hitl_audit_trail])
    document.update()
    #Update Bigquery database
    entities_for_bq = format_data_for_bq(entities)
    update_bq = stream_document_to_bigquery(client, new_case_id, uid,
                                            document_class, document_type,
                                            entities_for_bq)
    print("--------firestore db ----------------")
    # status_process_task =
    response_process_task = call_process_task(new_case_id, uid, document_class,
                                              document_type, updated_url,
                                              context, extraction_score,
                                              entities)
    if update_bq == [] and response_process_task.status_code == 202:

      Logger.info(
          f"ressign case_id from {old_case_id} to {new_case_id} is successfull")
      return {"status": STATUS_SUCCESS, "url": document.url}
    else:
      print("inside else")
      response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
      response.body = "Error in updating bigquery database"

  except Exception as e:
    err = traceback.format_exc().replace("\n", " ")
    Logger.error(err)
    raise HTTPException(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) from e

# disabling for linting to pass for blob_copy variable
# pylint: disable = unused-variable
def copy_blob(bucket_name, source_blob_name, destination_blob_name):
  print(f"copy_blob: bucket_name = {bucket_name}")
  print(f"copy_blob: source_blob_name = {source_blob_name}")
  print(f"copy_blob: destination_blob_name = {destination_blob_name}")

  storage_client = storage.Client()
  source_bucket = storage_client.bucket(bucket_name)
  source_blob = source_bucket.blob(source_blob_name)
  destination_bucket = storage_client.bucket(bucket_name)
  source_bucket.copy_blob(source_blob, destination_bucket,
                          destination_blob_name)
  source_bucket.delete_blob(source_blob_name)
  return STATUS_SUCCESS

def call_process_task(case_id: str, uid: str, document_class: str,
                      document_type: str, gcs_uri: str, context: str,
                      extraction_score: float, entities: List[Dict]):
  """
    Starts the process task API after reassign
  """

  data = {
      "case_id": case_id,
      "uid": uid,
      "context": context,
      "gcs_url": gcs_uri,
      "document_class": document_class,
      "document_type": document_type,
      "extraction_score": extraction_score,
      "extraction_entities": entities
  }
  payload = {"configs": [data]}
  base_url = f"http://upload-service/{PROCESS_TASK_API_PATH}?is_reassign=true"
  Logger.info(f"Params for process task {payload}")
  response = requests.post(base_url, json=payload)
  return response


text:
<resources>
    <string name="app_name">AppBase</string>
</resources>


text:
/**
 *
 */
package org.caleydo.core.io;

import javax.xml.bind.annotation.XmlType;

import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.EDataType;

/**
 * A parsing specification for a single column containing the number of the column, the {@link EDataClass} and the
 * {@link EDataType}.
 *
 * @author Alexander Lex
 *
 */
@XmlType
public class ColumnDescription {

	/** The number of the column to be parsed, starting with 0 */
	private int column;

	/** The meta-data of the column. Can be either different for every column or the same for all columns in a table */
	private DataDescription dataDescription;

	/**
	 * Default Constructor used for columns that are part of homogeneous datasets.
	 */
	public ColumnDescription() {
	}

	/**
	 * Constructor for columns that are part of homogeneous datasets.
	 *
	 * @param column
	 *            sets {@link #column}.
	 */
	public ColumnDescription(int column) {
		this.column = column;
	}

	/**
	 * Constructor for inhomogeneous tables.
	 *
	 * @param dataClass
	 *            sets {@link #dataDescription}
	 */
	public ColumnDescription(DataDescription dataDescription) {
		this.dataDescription = dataDescription;

	}

	/**
	 * Constructor fully initializing the object, for inhomogeneous tables.
	 *
	 * @param column
	 *            sets {@link #column}
	 * @param dataClass
	 *            sets {@link #dataDescription}
	 */
	public ColumnDescription(int column, DataDescription dataDescription) {
		this.column = column;
		this.dataDescription = dataDescription;
	}

	/**
	 * @param column
	 *            setter, see {@link #column}
	 */
	public void setColumn(int column) {
		this.column = column;
	}

	/**
	 * @return the column, see {@link #column}
	 */
	public int getColumn() {
		return column;
	}

	/**
	 * @param dataDescription
	 *            setter, see {@link dataDescription}
	 */
	public void setDataDescription(DataDescription dataDescription) {
		this.dataDescription = dataDescription;
	}

	/**
	 * @return the dataDescription, see {@link #dataDescription}
	 */
	public DataDescription getDataDescription() {
		return dataDescription;
	}

	@Override
	public String toString() {
		return "[" + column + ", " + dataDescription + "]";
	}
}


text:
using namespace Ast;
using namespace Codegen;

Result_t ArraySlice::codegen(CodegenInstance* cgi, fir::Type* extratype, fir::Value* target)
{
	return Operators::OperatorMap::get().call(ArithmeticOp::Slice, cgi, this, { this->arr, this->start, this->end });
}

fir::Type* ArraySlice::getType(CodegenInstance* cgi, fir::Type* extratype, bool allowFail)
{
	fir::Type* t = this->arr->getType(cgi);
	if(t->isDynamicArrayType())
	{
		return fir::ArraySliceType::get(t->toDynamicArrayType()->getElementType());
	}
	else if(t->isArraySliceType())
	{
		return t;
	}
	else if(t->isArrayType())
	{
		return fir::ArraySliceType::get(t->toArrayType()->getElementType());
	}
	else if(t->isStringType())
	{
		// special case (as usual), slicing strings returns strings.
		return fir::Type::getStringType();
	}
	else
	{
		error(this, "Slicing operator on custom types ('%s') is not supported yet", t->str().c_str());

		// // todo: multiple subscripts
		// fir::Function* getter = Operators::getOperatorSubscriptGetter(cgi, this, t, { this, this->index });
		// if(!getter)
		// {
		// 	error(this, "Invalid subscript on type '%s', with index type '%s'", t->str().c_str(),
		// 		this->index->getType(cgi)->str().c_str());
		// }

		// return getter->getReturnType();
	}
}

namespace Operators
{
	static void _complainAboutSliceIndices(CodegenInstance* cgi, std::string fmt, fir::Value* complaintValue, Parser::Pin pos)
	{
		fir::Function* fprintfn = cgi->module->getOrCreateFunction(Identifier("fprintf", IdKind::Name),
			fir::FunctionType::getCVariadicFunc({ fir::Type::getVoidPtr(), fir::Type::getInt8Ptr() },
			fir::Type::getInt32()), fir::LinkageType::External);

		fir::Function* fdopenf = cgi->module->getOrCreateFunction(Identifier("fdopen", IdKind::Name),
			fir::FunctionType::get({ fir::Type::getInt32(), fir::Type::getInt8Ptr() }, fir::Type::getVoidPtr(), false),
			fir::LinkageType::External);

		// basically:
		// void* stderr = fdopen(2, "w")
		// fprintf(stderr, "", bla bla)

		fir::ConstantValue* tmpstr = cgi->module->createGlobalString("w");
		fir::ConstantValue* fmtstr = cgi->module->createGlobalString(fmt);

		iceAssert(fmtstr);

		auto loc = fir::ConstantString::get(Parser::pinToString(pos));
		fir::Value* posstr = cgi->irb.CreateGetStringData(loc);
		fir::Value* err = cgi->irb.CreateCall2(fdopenf, fir::ConstantInt::getInt32(2), tmpstr);

		cgi->irb.CreateCall(fprintfn, { err, fmtstr, posstr, complaintValue });

		cgi->irb.CreateCall0(cgi->getOrDeclareLibCFunc("abort"));
		cgi->irb.CreateUnreachable();
	}

	static void checkSliceOperation(CodegenInstance* cgi, fir::Value* maxlen, fir::Value* beginIndex, fir::Value* endIndex,
		std::vector<Expr*> args)
	{
		Parser::Pin apos = (args[1] ? args[1]->pin : args[0]->pin);
		Parser::Pin bpos = (args[2] ? args[2]->pin : args[0]->pin);

		if(!beginIndex->getType()->isIntegerType())
			error(args[1], "Expected integer type for array slice; got '%s'", beginIndex->getType()->str().c_str());

		if(!endIndex->getType()->isIntegerType())
			error(args[2], "Expected integer type for array slice; got '%s'", endIndex->getType()->str().c_str());

		fir::Value* length = cgi->irb.CreateSub(endIndex, beginIndex);

		// do a check
		auto neg_begin = cgi->irb.addNewBlockInFunction("neg_begin", cgi->irb.getCurrentFunction());
		auto neg_end = cgi->irb.addNewBlockInFunction("neg_end", cgi->irb.getCurrentFunction());
		auto neg_len = cgi->irb.addNewBlockInFunction("neg_len", cgi->irb.getCurrentFunction());
		auto check1 = cgi->irb.addNewBlockInFunction("check1", cgi->irb.getCurrentFunction());
		auto check2 = cgi->irb.addNewBlockInFunction("check2", cgi->irb.getCurrentFunction());
		auto merge = cgi->irb.addNewBlockInFunction("merge", cgi->irb.getCurrentFunction());

		{
			fir::Value* neg = cgi->irb.CreateICmpLT(beginIndex, fir::ConstantInt::getInt64(0));
			cgi->irb.CreateCondBranch(neg, neg_begin, check1);
		}

		cgi->irb.setCurrentBlock(check1);
		{
			fir::Value* neg = cgi->irb.CreateICmpLT(endIndex, fir::ConstantInt::getInt64(0));
			cgi->irb.CreateCondBranch(neg, neg_end, check2);
		}

		cgi->irb.setCurrentBlock(check2);
		{
			fir::Value* neg = cgi->irb.CreateICmpLT(length, fir::ConstantInt::getInt64(0));
			cgi->irb.CreateCondBranch(neg, neg_len, merge);
		}

		cgi->irb.setCurrentBlock(neg_begin);
		_complainAboutSliceIndices(cgi, "%s: Start index for array slice was negative (%zd)\n", beginIndex, apos);

		cgi->irb.setCurrentBlock(neg_end);
		_complainAboutSliceIndices(cgi, "%s: Ending index for array slice was negative (%zd)\n", endIndex, bpos);

		cgi->irb.setCurrentBlock(neg_len);
		_complainAboutSliceIndices(cgi, "%s: Length for array slice was negative (%zd)\n", length, bpos);

		cgi->irb.setCurrentBlock(merge);

		// bounds check.
		{
			// endindex is non-inclusive, so do the len vs len check
			fir::Function* checkf = RuntimeFuncs::Array::getBoundsCheckFunction(cgi, true);
			iceAssert(checkf);

			cgi->irb.CreateCall3(checkf, maxlen, endIndex, fir::ConstantString::get(Parser::pinToString(apos)));
		}
	}

	static Result_t performSliceOperation(CodegenInstance* cgi, fir::Type* elmType, fir::Value* data, fir::Value* maxlen,
		fir::Value* beginIndex, fir::Value* endIndex, std::vector<Expr*> args)
	{
		checkSliceOperation(cgi, maxlen, beginIndex, endIndex, args);

		// ok, make the slice
		fir::Type* slct = fir::ArraySliceType::get(elmType);
		fir::Value* ai = cgi->irb.CreateStackAlloc(slct);

		// FINALLY.
		// increment ptr
		fir::Value* newptr = cgi->irb.CreatePointerAdd(data, beginIndex);
		fir::Value* newlen = cgi->irb.CreateSub(endIndex, beginIndex);

		cgi->irb.CreateSetArraySliceData(ai, newptr);
		cgi->irb.CreateSetArraySliceLength(ai, newlen);

		if(cgi->isRefCountedType(elmType))
		{
			// increment the refcounts for the strings
			fir::Function* incrfn = RuntimeFuncs::Array::getIncrementArrayRefCountFunction(cgi, elmType);
			iceAssert(incrfn);

			cgi->irb.CreateCall2(incrfn, newptr, newlen);
		}

		// slices are rvalues
		return Result_t(cgi->irb.CreateLoad(ai), ai, ValueKind::RValue);
	}

	Result_t operatorSlice(CodegenInstance* cgi, ArithmeticOp op, Expr* usr, std::vector<Expr*> args)
	{
		// slice that motherfucker up
		iceAssert(args.size() == 3);
		iceAssert(op == ArithmeticOp::Slice);

		// ok.
		fir::Value* lhs = 0; fir::Value* lhsptr = 0;
		std::tie(lhs, lhsptr) = args[0]->codegen(cgi);

		iceAssert(lhs);
		if(!lhsptr) lhsptr = cgi->irb.CreateImmutStackAlloc(lhs->getType(), lhs);

		// ok then
		fir::Type* lt = lhs->getType();

		if(lt->isDynamicArrayType())
		{
			// make that shit happen
			fir::Value* beginIndex = 0;
			fir::Value* endIndex = 0;

			if(args[1])	beginIndex = args[1]->codegen(cgi).value;
			else		beginIndex = fir::ConstantInt::getInt64(0);

			if(args[2])	endIndex = args[2]->codegen(cgi).value;
			else		endIndex = cgi->irb.CreateGetDynamicArrayLength(lhsptr);

			beginIndex = cgi->autoCastType(fir::Type::getInt64(), beginIndex);
			endIndex = cgi->autoCastType(fir::Type::getInt64(), endIndex);

			return performSliceOperation(cgi, lt->toDynamicArrayType()->getElementType(), cgi->irb.CreateGetDynamicArrayData(lhsptr),
				cgi->irb.CreateGetDynamicArrayLength(lhsptr), beginIndex, endIndex, args);
		}
		else if(lt->isArrayType())
		{
			// make that shit happen
			fir::Value* beginIndex = 0;
			fir::Value* endIndex = 0;

			if(args[1])	beginIndex = args[1]->codegen(cgi).value;
			else		beginIndex = fir::ConstantInt::getInt64(0);

			if(args[2])	endIndex = args[2]->codegen(cgi).value;
			else		endIndex = fir::ConstantInt::getInt64(lt->toArrayType()->getArraySize());

			beginIndex = cgi->autoCastType(fir::Type::getInt64(), beginIndex);
			endIndex = cgi->autoCastType(fir::Type::getInt64(), endIndex);

			fir::Value* data = cgi->irb.CreateConstGEP2(lhsptr, 0, 0);

			return performSliceOperation(cgi, lt->toArrayType()->getElementType(), data,
				fir::ConstantInt::getInt64(lt->toArrayType()->getArraySize()), beginIndex, endIndex, args);
		}
		else if(lt->isArraySliceType())
		{
			// make that shit happen
			fir::Value* beginIndex = 0;
			fir::Value* endIndex = 0;

			if(args[1])	beginIndex = args[1]->codegen(cgi).value;
			else		beginIndex = fir::ConstantInt::getInt64(0);

			if(args[2])	endIndex = args[2]->codegen(cgi).value;
			else		endIndex = cgi->irb.CreateGetArraySliceLength(lhsptr);

			beginIndex = cgi->autoCastType(fir::Type::getInt64(), beginIndex);
			endIndex = cgi->autoCastType(fir::Type::getInt64(), endIndex);

			return performSliceOperation(cgi, lt->toArraySliceType()->getElementType(), cgi->irb.CreateGetArraySliceData(lhsptr),
				cgi->irb.CreateGetArraySliceLength(lhsptr), beginIndex, endIndex, args);
		}
		else if(lt->isStringType())
		{
			// make that shit happen
			fir::Value* beginIndex = 0;
			fir::Value* endIndex = 0;

			if(args[1])	beginIndex = args[1]->codegen(cgi).value;
			else		beginIndex = fir::ConstantInt::getInt64(0);

			if(args[2])	endIndex = args[2]->codegen(cgi).value;
			else		endIndex = cgi->irb.CreateGetStringLength(lhs);

			beginIndex = cgi->autoCastType(fir::Type::getInt64(), beginIndex);
			endIndex = cgi->autoCastType(fir::Type::getInt64(), endIndex);

			// do it manually, since we want to get a string instead of char[]
			// and also we don't want to be stupid, so slices make copies!!
			// todo: might want to change
			checkSliceOperation(cgi, cgi->irb.CreateGetStringLength(lhs), beginIndex, endIndex, args);

			// ok
			fir::Value* srcptr = cgi->irb.CreatePointerAdd(cgi->irb.CreateGetStringData(lhs), beginIndex);
			fir::Value* length = cgi->irb.CreateSub(endIndex, beginIndex);

			fir::Value* data = 0;
			{
				// space for null + refcount
				size_t i64Size = 8;
				fir::Value* malloclen = cgi->irb.CreateAdd(length, fir::ConstantInt::getInt64(1 + i64Size));

				// now malloc.
				fir::Function* mallocf = cgi->getOrDeclareLibCFunc(ALLOCATE_MEMORY_FUNC);
				iceAssert(mallocf);

				fir::Value* buf = cgi->irb.CreateCall1(mallocf, malloclen);

				// move it forward (skip the refcount)
				data = cgi->irb.CreatePointerAdd(buf, fir::ConstantInt::getInt64(i64Size));

				fir::Function* memcpyf = cgi->module->getIntrinsicFunction("memmove");
				cgi->irb.CreateCall(memcpyf, { data, srcptr, cgi->irb.CreateIntSizeCast(length, fir::Type::getInt64()),
					fir::ConstantInt::getInt32(0), fir::ConstantInt::getBool(0) });

				// null terminator
				cgi->irb.CreateStore(fir::ConstantInt::getInt8(0), cgi->irb.CreatePointerAdd(data, length));
			}

			// ok, now fix it
			fir::Value* str = cgi->irb.CreateValue(fir::Type::getStringType());
			str = cgi->irb.CreateSetStringData(str, data);
			str = cgi->irb.CreateSetStringLength(str, length);

			cgi->irb.CreateSetStringRefCount(str, fir::ConstantInt::getInt64(1));

			// make a new fake
			fir::Value* aa = cgi->irb.CreateImmutStackAlloc(fir::Type::getStringType(), str);
			cgi->addRefCountedValue(aa);

			return Result_t(str, aa, ValueKind::RValue);
		}
		else
		{
			error("enotsup slice on custom type");
		}
	}
}