text:
/*
 * 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
 *
 * http://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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.civicinfo.model;

/**
 * Model definition for VoterInfoSegmentResult.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Civic Information API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VoterInfoSegmentResult extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long generatedMillis;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private PostalAddress postalAddress;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private VoterInfoRequest request;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private VoterInfoResponse response;

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Long getGeneratedMillis() {
    return generatedMillis;
  }

  /**
   * @param generatedMillis generatedMillis or {@code null} for none
   */
  public VoterInfoSegmentResult setGeneratedMillis(java.lang.Long generatedMillis) {
    this.generatedMillis = generatedMillis;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public PostalAddress getPostalAddress() {
    return postalAddress;
  }

  /**
   * @param postalAddress postalAddress or {@code null} for none
   */
  public VoterInfoSegmentResult setPostalAddress(PostalAddress postalAddress) {
    this.postalAddress = postalAddress;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public VoterInfoRequest getRequest() {
    return request;
  }

  /**
   * @param request request or {@code null} for none
   */
  public VoterInfoSegmentResult setRequest(VoterInfoRequest request) {
    this.request = request;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public VoterInfoResponse getResponse() {
    return response;
  }

  /**
   * @param response response or {@code null} for none
   */
  public VoterInfoSegmentResult setResponse(VoterInfoResponse response) {
    this.response = response;
    return this;
  }

  @Override
  public VoterInfoSegmentResult set(String fieldName, Object value) {
    return (VoterInfoSegmentResult) super.set(fieldName, value);
  }

  @Override
  public VoterInfoSegmentResult clone() {
    return (VoterInfoSegmentResult) super.clone();
  }

}


text:
class RenameTextToContent < ActiveRecord::Migration
  def self.up
    rename_column :paragraphs, :text, :content
  end

  def self.down
    rename_column :paragraphs, :content, :text
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.mitre.mrald.taglib;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;

import org.mitre.mrald.formbuilder.CrossLinkElement;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.DBMetaData;
import org.mitre.mrald.util.MraldError;
import org.mitre.mrald.util.MraldOutFile;

/**
 *  A formbuilder that applies to elements that need to span
 *  multiple databases. e.g. The crossLink that specifies how to connect
 *  across two disparagate databases
 *
 *@author     ghamilton
 *@created    August 29, 2007
 */
public class MultiDbFormBuilderTag extends FormBuilderTag
{

    /**
     *  Constructor for the FormBuilderTag object
     */
    public MultiDbFormBuilderTag()
    {
        super();
    }

    /**
     *  Standard entry for the Tag - kinda like main() for stand alone apps
     *
     *@return                   Always 0.
     *@exception  JspException  Standard exception - ones not caught will fall
     *      through to the ErrorPage.jsp
     */

    @SuppressWarnings("unchecked")
    public int doEndTag()
        throws JspException
    {
    	MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "MultiDbFormBuilder: doEndTag start" );
    	//The main difference between FormBuilder and MultiDbFormBuilder
    	//ArrayList<DBMetaData> mds = ( ArrayList<DBMetaData> ) pageContext.getAttribute( "MultiDBMetaData" );
    	HashMap<String, DBMetaData> mds = (HashMap<String,DBMetaData>)pageContext.getRequest().getAttribute("MultiDBMetaData");
    	MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "MultiDbFormBuilder: doEndTag: mds " + mds.size());

    	StringBuffer ret = new StringBuffer();
		 /*
	     *  add the HTML
	     */
	     CrossLinkElement thisElement;
	     try
	     {
	         thisElement = (CrossLinkElement)castElement();
	     }
	     catch ( ServletException e )
	     {
	         throw new MraldError( e );
	     }
	     setNumber();

	     ArrayList<DBMetaData> rearrangeDBs = new ArrayList<DBMetaData>();
	     for (DBMetaData md: mds.values())
	     {
	    	 rearrangeDBs.add(md);
	     }

	     for ( int i = 0; i < number; i++ )
	        {
	            ret.append( thisElement.getFBHtml( rearrangeDBs, i , thread) );
	            if ( i < number - 1 )
	            {
	                ret.append( "<hr width=\"90%\">\n" );
	            }
	        }
	          ret.append(  SECTION_CLOSE );

	     try
	     {
	        pageContext.getOut().print( ret.toString() );
	     }
	     catch ( java.io.IOException e )
	     {
	        throw new JspException( e.getMessage() );
	     }

        return 0;
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p476;

import org.gradle.test.performance.mediummonolithicjavaproject.p475.Production9517;

public class Production9526 {

    private Production9517 property0;

    public Production9517 getProperty0() {
        return property0;
    }

    public void setProperty0(Production9517 value) {
        property0 = value;
    }

    private Production9521 property1;

    public Production9521 getProperty1() {
        return property1;
    }

    public void setProperty1(Production9521 value) {
        property1 = value;
    }

    private Production9525 property2;

    public Production9525 getProperty2() {
        return property2;
    }

    public void setProperty2(Production9525 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
if [ ! -n "$BASH" ]
then
echo GDP and Yocto in general only works with bash as the interactive shell.
echo Please retry with bash
return
fi

# Parse target board & eula agreement from args

choice=$1

if [[ $2 == "accept-eula" ]] ; then
   eula=true
fi

echo "You selected target $choice"

declare -a targets=("qemux86-64" "porter" "raspberrypi2" "raspberrypi3" "minnowboard" "silk" "dragonboard-410c")
declare -a supported=("qemux86-64" "porter" "minnowboard" "raspberrypi2" "raspberrypi3" "dragonboard-410c" "silk")
declare -a variables=("choice" "eula" "machine" "modules" "bsp" "bsparr" "supported" "targets" "variables")

for i in ${targets[@]}; do
   if [[ ${i} == $choice ]] ; then
      machine=$choice
      echo "$machine is a valid target"
      break
   fi
done

if test -z "$machine" ; then
   echo "An invalid target name was given of $choice, available targets are:"
   printf '%s\n' "${targets[@]}"
   unset "${variables[@]}"
   echo "Usage: source init.sh target [accept-eula] [-f]"
   return
else
   if [[ ! ${supported[@]} =~ "$machine" ]] && [[ ${!#} != "-f" ]]; then
      echo "However currently, only the following targets are officially supported:"
      printf '%s\n' "${supported[@]}"
      echo "You can either "
      echo "re-run with a supported target (or override this check with -f)"
      echo "or get the gdp-11 branch:"
      echo "   git checkout origin/gdp-11 and then re-run"
      echo "   source init.sh $machine"
      unset "${variables[@]}"
      return
   fi
fi

if [[ "$machine" == "dragonboard-410c" ]] && test -z "$eula" ; then
   echo "Building GDP for DragonBoard 410c requires Qualcomm EULA acceptance."
   echo "See http://git.yoctoproject.org/cgit/cgit.cgi/meta-qcom/tree/conf/EULA for details."
   echo "Please re-run init.sh with additional 'accept-eula' argument"
   unset "${variables[@]}"
   return
fi

echo "Generating bitbake configuration files for $machine"

cp gdp-src-build/conf/templates/${machine}.local.conf gdp-src-build/conf/local.conf
cp gdp-src-build/conf/templates/${machine}.bblayers.conf gdp-src-build/conf/bblayers.conf

# Accept EULA in local.conf
if [[ $machine == "dragonboard-410c" ]] ; then
   echo "ACCEPT_EULA_dragonboard-410c = "'"1"'"" >> gdp-src-build/conf/local.conf
fi

echo "Local & bblayers conf set for $machine"

# init really makes sense only the first time
# and after that is redundant, only require target
# bsp submodule layer
declare -A bsparr

bsparr+=( ["minnowboard"]="meta-intel" ["raspberrypi2"]="meta-raspberrypi" ["raspberrypi3"]="meta-raspberrypi" ["porter"]="meta-renesas" ["silk"]="meta-renesas" ["dragonboard-410c"]="meta-qcom" )

modules=($(git submodule | awk '{ print $2 }'))
for i in ${bsparr[@]}; do
   if [[ "$machine" == "qemux86-64" ]] || [[ $i != ${bsparr[${machine}]} ]] ; then
      modules=(${modules[@]//*$i*})
   fi
done

git submodule init "${modules[@]}"

# git submodule sync helpfully rewrites your remotes (typically "origin")
# inside the submodules :) I bet this helpfulness will drive some power
# users mad, but for most users this will reduce instead of add confusion
git submodule sync "${modules[@]}"

# update here could help ensure people get the right checked out version
# after they have switched branches. However learning how submodules work
# is better (because they are not that user friendly otherwise...))
git submodule update "${modules[@]}"

unset "${variables[@]}"

source poky/oe-init-build-env gdp-src-build

echo
echo "Now run:  bitbake genivi-dev-platform"


text:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sched.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include "BBBiolib.h"
#include "BBBiolib_McSPI.h"
//-----------------------------------------------------------------------------------------------
/* Argument define */

/* McSPI module have 4channel , but only pinout2 */
#define MCSPI_ARG_MODULE_COUNT	2
#define MCSPI_ARG_CHANNEL_COUNT	2

/* Device register mamory map */
#define MCSPI0_MMAP_ADDR	0x48030000
#define MCSPI1_MMAP_ADDR	0x481A0000
#define MCSPI_MMAP_LEN	0x1000

/* Device register offset */
#define MCSPI_SYSCONFIG	0x110
#define MCSPI_IRQENABLE	0x11c
#define MCSPI_IRQSTATUS	0x118
#define MCSPI_SYSSTATUS	0x114
#define MCSPI_SYST	0x124
#define MCSPI_MODULCTRL	0x128
#define MCSPI_CH0CONF	0x12C
#define MCSPI_CH0STAT	0x130
#define MCSPI_CH0CTRL	0x134
#define MCSPI_TX0	0x138
#define MCSPI_RX0	0x13C
#define MCSPI_XFERLEVEL	0x17C
#define MCSPI_DAFTX	0x180
#define MCSPI_DAFRX	0x1A0

/* offset between MCSPI_CH0CONF, MCSPI_CH1CONF, MCSPI_CH2CONF, MCSPI_CH3CONF */
#define MCSPI_CH_REG_OFFSET	0x14

#define CM_PER_SPI1_CLKCTRL_IDLEST_MASK	(0x3 <<16)
#define MCSPI_GET_CHSTAT_EOT(a)	((a&0x04)>>2)
#define MCSPI_GET_CHSTAT_TXS(a)	((a&0x02)>>1)
#define MCSPI_GET_CHSTAT_RXS(a)	(a&0x01)

#define MCSPI_GET_SYSSTATUS_RESETDONE(a)	(a&0x01)
//-----------------------------------------------------------------------------------------------
/* struct definition */

#define McSPI_TxRx_Tx		0x01
#define McSPI_TxRx_Rx		0x02

struct BBBIO_McSPI_TxRx_struct
{
	unsigned int Tx ;
	unsigned int Rx ;
	unsigned int flag ;
};

// Channel struct
#define McSPI_CH_ENABLE		0x01
#define McSPI_CH_DISABLE	0x02

/* McSPI channel strcut */
struct BBBIO_McSPI_CH_struct
{
	int status ;
	struct BBBIO_McSPI_TxRx_struct TxRx ;
};

/* McSPI module struct */
struct BBBIO_McSPI_struct
{
	int CM_PER_enable ;
	struct BBBIO_McSPI_CH_struct CH[MCSPI_ARG_CHANNEL_COUNT];
};
//-----------------------------------------------------------------------------------------------
/* Global Variable */
extern int memh;
extern volatile unsigned int *cm_per_addr ;

const unsigned int McSPI_AddressOffset[]={MCSPI0_MMAP_ADDR, MCSPI1_MMAP_ADDR};
volatile unsigned int *mcspi_ptr[MCSPI_ARG_CHANNEL_COUNT] ={NULL};

struct BBBIO_McSPI_struct McSPI_Module[MCSPI_ARG_MODULE_COUNT] ={0} ;
/* ----------------------------------------------------------------------------------------------- */
inline void write_reg(volatile void *reg_base ,unsigned int offset ,unsigned int data)
{
	*((volatile unsigned int* )(reg_base+offset)) = data;
}
/* ----------------------------------------------------------------------------------------------- */
inline unsigned int read_reg(volatile void *reg_base ,unsigned int offset)
{
	return *((volatile unsigned int* )(reg_base+offset));
}
/* ----------------------------------------------------------------------------------------------- */
/* McSPI init
 * iolib_init() will run this function automatically
 */
int BBBIO_McSPI_Init()
{
	int i ;
	if (memh == 0) {
#ifdef BBBIO_LIB_DBG
		printf("BBBIO_PWM_Init: memory not mapped?\n");
#endif
		return 0;
    	}

	for (i=0; i<2; i++) {
		mcspi_ptr[i] = mmap(0, MCSPI_MMAP_LEN, PROT_READ | PROT_WRITE, MAP_SHARED, memh, McSPI_AddressOffset[i]);
		if(mcspi_ptr[i] == MAP_FAILED) {
#ifdef BBBIO_LIB_DBG
			printf("BBBIO_McSPI_Init: McSPI %d mmap failure!\n",i);
#endif
	                return 0;
		}
	}
    return 1;
}
/* ----------------------------------------------------------------------------------------------- */
/* Set Transmit data */
void BBBIO_McSPI_Tx(unsigned int McSPI_ID ,unsigned int channel ,unsigned int data)
{
	McSPI_Module[McSPI_ID].CH[channel].TxRx.Tx =data;
}
/* ----------------------------------------------------------------------------------------------- */
/* Receive data */
unsigned int BBBIO_McSPI_Rx(unsigned int McSPI_ID ,unsigned int channel )
{
	return McSPI_Module[McSPI_ID].CH[channel].TxRx.Rx ;
}
/* ----------------------------------------------------------------------------------------------- */
/* McSPI module work */
int BBBIO_McSPI_work(unsigned int McSPI_ID)
{
	unsigned int chn =0;
	unsigned int chn_offset =0;
	unsigned int reg_value ;

	/* check CM_PER enable status, or it may caue "Bus error" signal message. */
	if(McSPI_Module[McSPI_ID].CM_PER_enable) {
		struct BBBIO_McSPI_CH_struct *CH_ptr = &McSPI_Module[McSPI_ID].CH[0] ;

		for(chn =0 ; chn < MCSPI_ARG_CHANNEL_COUNT ; chn ++) {
			if(McSPI_Module[McSPI_ID].CH[chn].status &McSPI_CH_ENABLE) {
				chn_offset = chn * MCSPI_CH_REG_OFFSET ;

				/* channel enable */
				write_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0CTRL + chn_offset, 1);

				/* set transform data */
				if(McSPI_Module[McSPI_ID].CH[chn].TxRx.flag & McSPI_TxRx_Tx) {
					write_reg(mcspi_ptr[McSPI_ID], MCSPI_TX0 +chn_offset, McSPI_Module[McSPI_ID].CH[chn].TxRx.Tx );
				}
				else {	/* must set a dummy data in Tx reigster of receive only mode .*/
					write_reg(mcspi_ptr[McSPI_ID], MCSPI_TX0 +chn_offset, 0);
				}

				/* waiting for EOT ,not support interrupt yet , using polling waiting for the moment*/
				reg_value =0;
				while(!MCSPI_GET_CHSTAT_EOT(reg_value)) {
					reg_value = read_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0STAT + chn_offset);
					sched_yield();
				}
                                while(!MCSPI_GET_CHSTAT_RXS(reg_value)) {
					reg_value = read_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0STAT + chn_offset);
					sched_yield();
				}

				/* copy receive data */
				if(McSPI_Module[McSPI_ID].CH[chn].TxRx.flag & McSPI_TxRx_Rx) {
					McSPI_Module[McSPI_ID].CH[chn].TxRx.Rx = read_reg(mcspi_ptr[McSPI_ID], MCSPI_RX0 + chn_offset);
				}

				/* channel disable */
				write_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0CTRL + chn_offset, 0);
			}
		}
	}
	else {
#ifdef BBBIO_LIB_DBG
		printf("BBBIO_McSPI_work: McSPI %d CM_PER Clock Gating!\n",McSPI_ID);
#endif
		return 0 ;
	}
	return 1 ;
}
/* ----------------------------------------------------------------------------------------------- */
int BBBIO_McSPI_Setting(unsigned int McSPI_ID ,
			unsigned int channel,
			unsigned int MS, 		/* MS 			,maset or slave */
			unsigned int TRM ,		/* TRM 			,Tx only / Rx only , TxRx */
			unsigned int CLK_div ,		/* clock divider	, default clock : 48M Hz */
			unsigned int CLKmode ,		/* POL/PHA ,		,clock polarity */
			unsigned int EPOL ,
			unsigned int DataDir ,		/* IS/DPE1/DPE0		,data0 Output data1 Input ,or data0 Input data1 Output */
			unsigned int WL)		/* WL 			,word length */
{
	volatile unsigned int* reg;
	unsigned int reg_value ;
	unsigned int chn_offset =channel *0x14;

	/* check CM_PER enable status, or it may caue "Bus error" signal message. */
        if(McSPI_Module[McSPI_ID].CM_PER_enable) {
		/* disable channel */
		write_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0CTRL + chn_offset, 0);
		write_reg(mcspi_ptr[McSPI_ID], MCSPI_MODULCTRL, MS << 2);
 		write_reg(mcspi_ptr[McSPI_ID], MCSPI_CH0CONF + chn_offset, (DataDir << 16 | TRM << 12 | (WL - 1) << 7 | EPOL << 6 | CLK_div << 2 | CLKmode));

		if(TRM != BBBIO_McSPI_Tx_Only)
			McSPI_Module[McSPI_ID].CH[channel].TxRx.flag |= McSPI_TxRx_Rx ;
	        if(TRM != BBBIO_McSPI_Rx_Only) {
        	        McSPI_Module[McSPI_ID].CH[channel].TxRx.flag |= McSPI_TxRx_Tx ;
			McSPI_Module[McSPI_ID].CH[channel].TxRx.Tx =0;
		}
		McSPI_Module[McSPI_ID].CH[channel].status |=McSPI_CH_ENABLE;
	}
        else {
#ifdef BBBIO_LIB_DBG
		printf("BBBIO_McSPI_work: McSPI %d CM_PER Clock Gating!\n",McSPI_ID);
#endif
                return 0 ;
        }
	return 1 ;
}
/* ----------------------------------------------------------------------------------------------- */
/* Beaglebone Black , SPI Expansion Header Mode Check */
int BBBIO_McSPI_EP_check(unsigned int McSPI_ID)
{
	unsigned int ret = 1;

	if(McSPI_ID ==1) {
		/*SPI 1 cs 0~1*/
		if(!BBBIO_sys_pinmux_check(9, 19, BBBIO_PINMUX_MODE_4) &&
			!BBBIO_sys_pinmux_check(9, 20, BBBIO_PINMUX_MODE_4) &&
			!BBBIO_sys_pinmux_check(9, 28, BBBIO_PINMUX_MODE_3) &&
			!BBBIO_sys_pinmux_check(9, 42, BBBIO_PINMUX_MODE_2) ) {
			ret = 0;
		}

		/* SPI 1 Da0~1 , clk */
		if(!BBBIO_sys_pinmux_check(9, 29, BBBIO_PINMUX_MODE_3) &&
			!BBBIO_sys_pinmux_check(9, 30, BBBIO_PINMUX_MODE_3) &&
			!BBBIO_sys_pinmux_check(9, 31, BBBIO_PINMUX_MODE_3) &&
			!BBBIO_sys_pinmux_check(9, 42, BBBIO_PINMUX_MODE_4)) {
			ret =0;
		}
	}
	else {
		/* SPI 0 cs 0 */
		if(!BBBIO_sys_pinmux_check(9, 17, BBBIO_PINMUX_MODE_0)) {
                        ret = 0;
                }

                /* SPI 1 Da0~1 , clk */
                if(!BBBIO_sys_pinmux_check(9, 18, BBBIO_PINMUX_MODE_0) &&
                        !BBBIO_sys_pinmux_check(9, 21, BBBIO_PINMUX_MODE_0) &&
                        !BBBIO_sys_pinmux_check(9, 22, BBBIO_PINMUX_MODE_0)) {
                        ret =0;
                }
	}
	return ret ;
}
/* ----------------------------------------------------------------------------------------------- */
//#define BBBIO_McSPI_Enable(a) BBBIO_McSPI_CLK_set(a,1,0)
//#define BBBIO_McSPI_Disable(a) BBBIO_McSPI_CLK_set(a,0,0)

int BBBIO_McSPI_CLK_set(unsigned int McSPI_ID ,int enable , int idle)
{
	volatile unsigned int* reg = NULL;
	const unsigned int CM_PER_McSPI[] = {BBBIO_CM_PER_SPI0_CLKCTRL, BBBIO_CM_PER_SPI1_CLKCTRL};

	if(McSPI_ID > 1 || McSPI_ID < 0) {
#ifdef BBBIO_LIB_DBG
		printf("BBBIO_McSPI_CLK_set: Unknow McSPI module ID : %d\n", McSPI_ID);
#endif
		return 0 ;
	}

	/* pin mux check */
	if(!BBBIO_McSPI_EP_check(McSPI_ID)) {
#ifdef BBBIO_LIB_DBG
		printf("BBBIO_McSPI_CLK_set: No effect pin mux Detected of SPI-%d ,Please use EP_STATUS toolkit to check Pin mux mode\n", McSPI_ID);
#endif
		return 0;
	}

	if(enable) {
		write_reg(cm_per_addr, CM_PER_McSPI[McSPI_ID], 0x3 << 16 | 0x2);
		McSPI_Module[McSPI_ID].CM_PER_enable = 1;
	}
	else {
		write_reg(cm_per_addr, CM_PER_McSPI[McSPI_ID], 0);
		McSPI_Module[McSPI_ID].CM_PER_enable = 0;
	}

	return 1 ;
}
/* ----------------------------------------------------------------------------------------------- */
void BBBIO_McSPI_Reset(unsigned int McSPI_ID)
{
	unsigned int reg_value ;

	/* reset */
	write_reg(mcspi_ptr[McSPI_ID], MCSPI_SYSCONFIG, 0x2 << 3 | 0x2);

	/* waiting reset finish */
	reg_value =0;
	while(!MCSPI_GET_SYSSTATUS_RESETDONE(reg_value)) {
		reg_value = read_reg(mcspi_ptr[McSPI_ID] ,MCSPI_SYSSTATUS);
		sched_yield();
	}
#ifdef BBBIO_LIB_DBG
	printf("Reset Finish\n");
#endif
}


text:
from __future__ import annotations

import functools
import typing as t

import click

def task_id_arg(f: t.Callable | None = None, *, required=True):
    """
    By default, the task ID is made required; pass `required=False` to the
    decorator arguments to make it optional.
    """
    if f is None:
        return functools.partial(task_id_arg, required=required)
    return click.argument("TASK_ID", required=required)(f)


text:
<?php

// autoload_real.php @generated by Composer

class ComposerAutoloaderInit3e34b7ec688032ab1bc0f044395208d8
{
    private static $loader;

    public static function loadClassLoader($class)
    {
        if ('Composer\Autoload\ClassLoader' === $class) {
            require __DIR__ . '/ClassLoader.php';
        }
    }

    public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

        spl_autoload_register(array('ComposerAutoloaderInit3e34b7ec688032ab1bc0f044395208d8', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array('ComposerAutoloaderInit3e34b7ec688032ab1bc0f044395208d8', 'loadClassLoader'));

        $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
        if ($useStaticLoader) {
            require_once __DIR__ . '/autoload_static.php';

            call_user_func(\Composer\Autoload\ComposerStaticInit3e34b7ec688032ab1bc0f044395208d8::getInitializer($loader));
        } else {
            $map = require __DIR__ . '/autoload_namespaces.php';
            foreach ($map as $namespace => $path) {
                $loader->set($namespace, $path);
            }

            $map = require __DIR__ . '/autoload_psr4.php';
            foreach ($map as $namespace => $path) {
                $loader->setPsr4($namespace, $path);
            }

            $classMap = require __DIR__ . '/autoload_classmap.php';
            if ($classMap) {
                $loader->addClassMap($classMap);
            }
        }

        $loader->register(true);

        if ($useStaticLoader) {
            $includeFiles = Composer\Autoload\ComposerStaticInit3e34b7ec688032ab1bc0f044395208d8::$files;
        } else {
            $includeFiles = require __DIR__ . '/autoload_files.php';
        }
        foreach ($includeFiles as $fileIdentifier => $file) {
            composerRequire3e34b7ec688032ab1bc0f044395208d8($fileIdentifier, $file);
        }

        return $loader;
    }
}

function composerRequire3e34b7ec688032ab1bc0f044395208d8($fileIdentifier, $file)
{
    if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
        require $file;

        $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
    }
}


text:
<component name="libraryTable">
  <library name="AndroidProfileTwitter">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/AndroidProfileTwitter.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
import RPi.GPIO as GPIO
import time
pin_number = 22
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin_number, GPIO.OUT)
while True:
    GPIO.output(pin_number, True)
    time.sleep(1)
    GPIO.output(pin_number, False)
    time.sleep(1)


text:
<?php

namespace TractorCow\Fluent\Tests\Extension\FluentAdminTraitTest;

use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\Form;
use TractorCow\Fluent\Extension\Traits\FluentAdminTrait;

/**
 * Dummy admin handler to hold trait
 */
class AdminHandler implements TestOnly
{
    use FluentAdminTrait;
    use Injectable;

    /**
     * @param Form   $form
     * @param string $message
     * @return string
     */
    public function actionComplete($form, $message)
    {
        $record = $form->getRecord();
        $record->flushCache(true); // Note: Flushes caches E.g. FluentVersionedExtension
        return $message;
    }
}


text:
#ifndef NDHIST_DETAIL_BIN_ITER_VALUE_TYPE_TRAITS_HPP_INCLUDED
#define NDHIST_DETAIL_BIN_ITER_VALUE_TYPE_TRAITS_HPP_INCLUDED 1

#include <vector>

#include <boost/python.hpp>

#include <boost/numpy.hpp>
#include <boost/numpy/iterators/value_type_traits.hpp>

#include <ndhist/detail/bin_value.hpp>

namespace bp = boost::python;
namespace bn = boost::numpy;

namespace ndhist {
namespace detail {

template <typename WeightValueType>
struct bin_iter_value_type_traits
  : bn::iterators::value_type_traits
{
    typedef bin_iter_value_type_traits<WeightValueType>
            type_t;

    typedef bin_value<WeightValueType>
            value_type;

    typedef value_type &
            value_ref_type;

    typedef value_type const &
            value_cref_type;

    typedef value_type *
            value_ptr_type;

    bin_iter_value_type_traits()
    {}

    bin_iter_value_type_traits(bn::ndarray const & arr)
      : fields_byte_offsets_(arr.get_dtype().get_fields_byte_offsets())
    {}

    std::vector<intptr_t> fields_byte_offsets_;
    value_type bin_value_;

    static
    void
    set_value(
        bn::iterators::value_type_traits & vtt_base
      , char * data_ptr
      , value_cref_type newbin
    )
    {
        value_ref_type bin = type_t::dereference(vtt_base, data_ptr);

        *bin.noe_  = *newbin.noe_;
        *bin.sow_  = *newbin.sow_;
        *bin.sows_ = *newbin.sows_;
    }

    static
    value_ref_type
    dereference(
        bn::iterators::value_type_traits & vtt_base
      , char * data_ptr
    )
    {
        type_t & vtt = *static_cast<type_t *>(&vtt_base);

        vtt.bin_value_.noe_  = reinterpret_cast<uintptr_t *>(data_ptr);
        vtt.bin_value_.sow_  = reinterpret_cast<WeightValueType *>(data_ptr + vtt.fields_byte_offsets_[1]);
        vtt.bin_value_.sows_ = reinterpret_cast<WeightValueType *>(data_ptr + vtt.fields_byte_offsets_[2]);

        return vtt.bin_value_;
    }
};

template <>
struct bin_iter_value_type_traits<bp::object>
  : bn::iterators::value_type_traits
{
    typedef bin_iter_value_type_traits<bp::object>
            type_t;

    typedef bin_value<bp::object>
            value_type;

    typedef value_type &
            value_ref_type;

    typedef value_type const &
            value_cref_type;

    typedef value_type *
            value_ptr_type;

    bin_iter_value_type_traits()
    {}

    bin_iter_value_type_traits(bn::ndarray const & arr)
      : fields_byte_offsets_(arr.get_dtype().get_fields_byte_offsets())
    {}

    std::vector<intptr_t> fields_byte_offsets_;
    value_type bin_value_;

    static
    void
    set_value(
        bn::iterators::value_type_traits & vtt_base
      , char * data_ptr
      , value_cref_type newbin
    )
    {
        value_ref_type bin = type_t::dereference(vtt_base, data_ptr);

        *bin.noe_          = *newbin.noe_;
        *bin.sow_obj_ptr_  = reinterpret_cast<uintptr_t>(bp::incref<PyObject>(newbin.sow_obj_.ptr()));
        *bin.sows_obj_ptr_ = reinterpret_cast<uintptr_t>(bp::incref<PyObject>(newbin.sows_obj_.ptr()));
    }

    static
    value_ref_type
    dereference(
        bn::iterators::value_type_traits & vtt_base
      , char * data_ptr
    )
    {
        type_t & vtt = *static_cast<type_t *>(&vtt_base);

        vtt.bin_value_.noe_ = reinterpret_cast<uintptr_t*>(data_ptr);

        vtt.bin_value_.sow_obj_ptr_ = reinterpret_cast<uintptr_t*>(data_ptr + vtt.fields_byte_offsets_[1]);
        if(*(vtt.bin_value_.sow_obj_ptr_) == 0) {
            vtt.bin_value_.sow_obj_ = bp::object();
        }
        else {
            vtt.bin_value_.sow_obj_ = bp::object(bp::detail::borrowed_reference(reinterpret_cast<PyObject*>(*vtt.bin_value_.sow_obj_ptr_)));
        }
        vtt.bin_value_.sow_ = &vtt.bin_value_.sow_obj_;

        vtt.bin_value_.sows_obj_ptr_ = reinterpret_cast<uintptr_t*>(data_ptr + vtt.fields_byte_offsets_[2]);
        if(*(vtt.bin_value_.sows_obj_ptr_) == 0) {
            vtt.bin_value_.sows_obj_ = bp::object();
        }
        else {
            vtt.bin_value_.sows_obj_ = bp::object(bp::detail::borrowed_reference(reinterpret_cast<PyObject*>(*vtt.bin_value_.sows_obj_ptr_)));
        }
        vtt.bin_value_.sows_ = &vtt.bin_value_.sows_obj_;

        return vtt.bin_value_;
    }
};

}//namespace detail
}//namespace ndhist

#endif // !NDHIST_DETAIL_BIN_ITER_VALUE_TYPE_TRAITS_HPP_INCLUDED


text:
#include <aws/lightsail/model/GetOperationsForResourceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Lightsail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetOperationsForResourceRequest::GetOperationsForResourceRequest() :
    m_resourceNameHasBeenSet(false),
    m_pageTokenHasBeenSet(false)
{
}

Aws::String GetOperationsForResourceRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_resourceNameHasBeenSet)
  {
   payload.WithString("resourceName", m_resourceName);

  }

  if(m_pageTokenHasBeenSet)
  {
   payload.WithString("pageToken", m_pageToken);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection GetOperationsForResourceRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Lightsail_20161128.GetOperationsForResource"));
  return headers;

}


text:
package tunnel

import (
	"net"
	"os"
	"path/filepath"
	"unsafe"

	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/defaults"

	"github.com/sirupsen/logrus"
)

const (
	MapName = "cilium_tunnel_map"

	// Cilium versions < 1.0 used this tunnel map name, we remove it when
	// we open the new tunnel map. In a future release, we should remove
	// this downgrade handling code
	oldMapName = "tunnel_endpoint_map"

	// MaxEntries is the maximum entries in the tunnel endpoint map
	MaxEntries = 65536
)

var (
	// TunnelMap represents the BPF map for tunnels
	TunnelMap = &Map{Map: bpf.NewMap(MapName,
		bpf.MapTypeHash,
		int(unsafe.Sizeof(tunnelEndpoint{})),
		int(unsafe.Sizeof(tunnelEndpoint{})),
		MaxEntries,
		0, 0,
		func(key []byte, value []byte) (bpf.MapKey, bpf.MapValue, error) {
			k, v := tunnelEndpoint{}, tunnelEndpoint{}

			if err := bpf.ConvertKeyValue(key, value, &k, &v); err != nil {
				return nil, nil, err
			}

			return &k, &v, nil
		}).WithCache(),
	}
)

// Map implements tunnel connectivity configuration in the BPF datapath.
type Map struct {
	*bpf.Map
}

func init() {
	TunnelMap.NonPersistent = true
	bpf.OpenAfterMount(TunnelMap.Map)

	// Remove old map and ignore errors; this is the "normal" case.
	// BPFFS map root in older versions of Cilium wasn't dynamic, so the
	// path of this old map will be always
	// /sys/fs/bpf/tc/globals/tunnel_endpoint_map
	os.Remove(filepath.Join(defaults.DefaultMapRoot, defaults.DefaultMapPrefix, oldMapName))
}

type tunnelEndpoint struct {
	bpf.EndpointKey
}

func newTunnelEndpoint(ip net.IP) *tunnelEndpoint {
	return &tunnelEndpoint{
		EndpointKey: bpf.NewEndpointKey(ip),
	}
}

func (v tunnelEndpoint) NewValue() bpf.MapValue { return &tunnelEndpoint{} }

// SetTunnelEndpoint adds/replaces a prefix => tunnel-endpoint mapping
func (m *Map) SetTunnelEndpoint(prefix net.IP, endpoint net.IP) error {
	key, val := newTunnelEndpoint(prefix), newTunnelEndpoint(endpoint)

	log.WithFields(logrus.Fields{
		fieldPrefix:   prefix,
		fieldEndpoint: endpoint,
	}).Debug("Updating tunnel map entry")

	return TunnelMap.Update(key, val)
}

// DeleteTunnelEndpoint removes a prefix => tunnel-endpoint mapping
func (m *Map) DeleteTunnelEndpoint(prefix net.IP) error {
	log.WithField(fieldPrefix, prefix).Debug("Deleting tunnel map entry")
	return TunnelMap.Delete(newTunnelEndpoint(prefix))
}


text:
package de.gishmo.gwt.example.module0402.server;

import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.google.web.bindery.autobean.shared.AutoBeanUtils;
import com.google.web.bindery.autobean.vm.AutoBeanFactorySource;
import de.gishmo.gwt.example.module0402.shared.dto.Address;
import de.gishmo.gwt.example.module0402.shared.dto.Person;
import de.gishmo.gwt.example.module0402.shared.dto.PersonList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@SuppressWarnings("serial")
public class JsonPersonService
  extends HttpServlet {

  private static Map<Long, Person> persons;
  private MyBeanFactory myBeanFactory = AutoBeanFactorySource.create(MyBeanFactory.class);

  @Override
  protected void doGet(HttpServletRequest req,
                       HttpServletResponse resp)
    throws ServletException, IOException {

    String fc = req.getParameter("fc");
    if (fc != null) {
      if (persons == null) {
        persons = new HashMap<Long, Person>();
        initList();
      }
      if (fc.equals("01")) {
        handleFc01(req,
                   resp);
      } else if (fc.equals("02")) {
        handleFc02(resp);
      } else {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  private void initList() {
    Address address01 = this.createAddress();
    address01.setId(1);
    address01.setStreet("Evergreen Terrace");
    address01.setZip("7 42");
    address01.setCity("Springfield");

    Address address02 = this.createAddress();
    address01.setId(2);
    address01.setStreet("Blumenweg Nr. 13");
    address01.setZip("");
    address01.setCity("Entenhausen");

    Address address03 = this.createAddress();
    address01.setId(3);
    address01.setStreet("Am Goldberg Nr. 1");
    address01.setZip("");
    address01.setCity("Entenhausen");

    Person person01 = this.createPerson();
    person01.setId(1);
    person01.setFirstName("Homer");
    person01.setName("Simpson");
    person01.setAdress(address01);

    Person person02 = this.createPerson();
    person02.setId(2);
    person02.setFirstName("Marge");
    person02.setName("Simpson");
    person02.setAdress(address01);

    Person person03 = this.createPerson();
    person03.setId(3);
    person03.setFirstName("Bart");
    person03.setName("Simpson");
    person03.setAdress(address01);

    Person person04 = this.createPerson();
    person04.setId(4);
    person04.setFirstName("Lisa");
    person04.setName("Simpson");
    person04.setAdress(address01);

    Person person05 = this.createPerson();
    person05.setId(5);
    person05.setFirstName("Maggie");
    person05.setName("Simpson");
    person05.setAdress(address01);

    Person person06 = this.createPerson();
    person06.setId(6);
    person06.setFirstName("Donald");
    person06.setName("Duck");
    person06.setAdress(address02);

    Person person07 = this.createPerson();
    person07.setId(7);
    person07.setFirstName("Trick");
    person07.setName("Duck");
    person07.setAdress(address02);

    Person person08 = this.createPerson();
    person08.setId(8);
    person08.setFirstName("Tick");
    person08.setName("Duck");
    person08.setAdress(address02);

    Person person09 = this.createPerson();
    person09.setId(9);
    person09.setFirstName("Tack");
    person09.setName("Duck");
    person09.setAdress(address02);

    Person person10 = this.createPerson();
    person10.setId(10);
    person10.setFirstName("Dagobert");
    person10.setName("Duck");
    person10.setAdress(address03);

    persons.put(new Long(1),
                person01);
    persons.put(new Long(2),
                person02);
    persons.put(new Long(3),
                person03);
    persons.put(new Long(4),
                person04);
    persons.put(new Long(5),
                person05);
    persons.put(new Long(6),
                person06);
    persons.put(new Long(7),
                person07);
    persons.put(new Long(8),
                person08);
    persons.put(new Long(9),
                person09);
    persons.put(new Long(10),
                person10);
  }

  private void handleFc01(HttpServletRequest request,
                          HttpServletResponse response)
    throws IOException {
    String id = request.getParameter("id");
    if (id != null) {
      try {
        if (persons.containsKey(new Long(id))) {
          PrintWriter out = response.getWriter();
          out.print(this.serializePersonToJSON(persons.get(new Long(id))));
          out.flush();
        }
      } catch (NumberFormatException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  private void handleFc02(HttpServletResponse response)
    throws IOException {
    PrintWriter out = response.getWriter();
    out.print(this.serializePersonListToJSON());
    out.flush();
  }

  private Address createAddress() {
    AutoBean<Address> person = myBeanFactory.address();
    return person.as();
  }

  private Person createPerson() {
    AutoBean<Person> person = myBeanFactory.person();
    return person.as();
  }

  private String serializePersonToJSON(Person person) {
    AutoBean<Person> bean = AutoBeanUtils.getAutoBean(person);
    return AutoBeanCodex.encode(bean)
                        .getPayload();
  }

  private String serializePersonListToJSON() {
    List<Person> list = new ArrayList<Person>();
    Iterator<Long> iterator = persons.keySet()
                                     .iterator();
    while (iterator.hasNext()) {
      list.add(persons.get(iterator.next()));
    }
    PersonList personList = createPersonList();
    personList.setPersons(list);
    return serializePersonListToJSON(personList);
  }

  private PersonList createPersonList() {
    AutoBean<PersonList> personList = myBeanFactory.personList();
    return personList.as();
  }

  private String serializePersonListToJSON(PersonList personList) {
    AutoBean<PersonList> bean = AutoBeanUtils.getAutoBean(personList);
    return AutoBeanCodex.encode(bean)
                        .getPayload();
  }

  interface MyBeanFactory
    extends AutoBeanFactory {
    AutoBean<Address> address();

    AutoBean<Person> person();

    AutoBean<PersonList> personList();
  }
}


text:
<?php namespace ShekarSiri\BaseRepo;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //dd('REPO');
    }
}


text:
/*
 * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.OpsWorks.Model
{
    /// <summary>
    /// Contains the data needed by RDP clients such as the Microsoft Remote Desktop Connection
    /// to log in to the instance.
    /// </summary>
    public partial class TemporaryCredential
    {
        private string _instanceId;
        private string _password;
        private string _username;
        private int? _validForInMinutes;

        /// <summary>
        /// Gets and sets the property InstanceId.
        /// <para>
        /// The instance's AWS OpsWorks ID.
        /// </para>
        /// </summary>
        public string InstanceId
        {
            get { return this._instanceId; }
            set { this._instanceId = value; }
        }

        // Check to see if InstanceId property is set
        internal bool IsSetInstanceId()
        {
            return this._instanceId != null;
        }

        /// <summary>
        /// Gets and sets the property Password.
        /// <para>
        /// The password.
        /// </para>
        /// </summary>
        public string Password
        {
            get { return this._password; }
            set { this._password = value; }
        }

        // Check to see if Password property is set
        internal bool IsSetPassword()
        {
            return this._password != null;
        }

        /// <summary>
        /// Gets and sets the property Username.
        /// <para>
        /// The user name.
        /// </para>
        /// </summary>
        public string Username
        {
            get { return this._username; }
            set { this._username = value; }
        }

        // Check to see if Username property is set
        internal bool IsSetUsername()
        {
            return this._username != null;
        }

        /// <summary>
        /// Gets and sets the property ValidForInMinutes.
        /// <para>
        /// The length of time (in minutes) that the grant is valid. When the grant expires, at
        /// the end of this period, the user will no longer be able to use the credentials to
        /// log in. If they are logged in at the time, they will be automatically logged out.
        /// </para>
        /// </summary>
        public int ValidForInMinutes
        {
            get { return this._validForInMinutes.GetValueOrDefault(); }
            set { this._validForInMinutes = value; }
        }

        // Check to see if ValidForInMinutes property is set
        internal bool IsSetValidForInMinutes()
        {
            return this._validForInMinutes.HasValue;
        }

    }
}


text:
<?php

/* TwigBundle:Exception:error.json.twig */
class __TwigTemplate_a5e12d1f7a5438d848638d410409d4f225d149d48344866d3eb419e484011748 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo twig_jsonencode_filter(array("error" => array("code" => (isset($context["status_code"]) ? $context["status_code"] : null), "message" => (isset($context["status_text"]) ? $context["status_text"] : null))));
        echo "
";
    }

    public function getTemplateName()
    {
        return "TwigBundle:Exception:error.json.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }
}


text:
package quiz.blackjack;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by bollsal on 2016. 12. 19..
 */
public class BlackJack {

    public static final int BLACK_JACK_VALUE = 21;

    interface STATE {
        String BLACK_JACK_FIRST_TURN = "Black jack first turn";

        String USER_BLACK_JACK = "user Black jack";
        String DEALER_BLACK_JACK = "dealer Black jack";

        String USER_BURST = "user Burst";
        String DEALER_BURST = "dealer Burst";

        String USER_WIN = "user win";
        String DEALER_WIN = "dealer win";
        String DRAW = "draw";
    }

    private List<Integer> cards = new ArrayList<>();

    private List<Integer> userCards = new ArrayList<>();
    private List<Integer> dealerCards = new ArrayList<>();

    private int turnCount = 0;

    public BlackJack() {
        initCards();
    }

    public void initCards() {
        for (int i = 2; i < 11; i++) {
            cards.add(i);
        }
        cards.add(10);  // J
        cards.add(10);  // Q
        cards.add(10);  // K
        cards.add(11);  // A
    }

    public int getTurnCount() {
        return turnCount;
    }

    public void firstHit() {
        hit(false);
        hit(false);

        turnCount++;
    }

    public void hit() {
        hit(false);
    }

    public void hit(boolean addTurnCount) {
        addUserCard();
        addDealerCard();

        if (addTurnCount)
            turnCount++;
    }

    public void stand() {
        // TODO : ??
        turnCount++;
    }

    private void addUserCard() {
        userCards.add(getCard());
    }

    private void addDealerCard() {
        dealerCards.add(getCard());
    }

    private int getCard() {
        Collections.shuffle(cards);
        return cards.get(0);
    }

    public List<Integer> getUserCards() {
        return userCards;
    }

    public List<Integer> getDealerCards() {
        return dealerCards;
    }

    public int getUserCardCount() {
        return userCards.size();
    }

    public int getDealerCardCount() {
        return dealerCards.size();
    }

    private int getUserValue() {
        int user = 0;
        for (int userCard : userCards) {
            user += userCard;
        }
        return user;
    }

    private int getDealerValue() {
        int dealer = 0;
        for (int dealerCard : dealerCards) {
            dealer += dealerCard;
        }
        return dealer;
    }

    public String checkState() {
        int user = getUserValue();
        int dealer = getDealerValue();

        if (turnCount == 1) {
            if (user == BLACK_JACK_VALUE || dealer == BLACK_JACK_VALUE) {
                return STATE.BLACK_JACK_FIRST_TURN;
            }
        } else {
            if (user == BLACK_JACK_VALUE) {
                return STATE.USER_BLACK_JACK;
            } else if (dealer == BLACK_JACK_VALUE) {
                return STATE.DEALER_BLACK_JACK;
            } else if (user > BLACK_JACK_VALUE) {
                return STATE.USER_BURST;
            } else if (dealer > BLACK_JACK_VALUE) {
                return STATE.DEALER_BURST;
            } else if (user > dealer) {
                return STATE.USER_WIN;
            } else if (user < dealer) {
                return STATE.DEALER_WIN;
            } else {
                return STATE.DRAW;
            }
        }

        return null;
    }
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-56.js
 * @description Object.create - 'enumerable' property of one property in 'Properties' is own accessor property without a get function (8.10.5 step 3.a)
 */

function testcase() {

        var accessed = false;
        var descObj = {};
        Object.defineProperty(descObj, "enumerable", {
            set: function () { }
        });

        var newObj = Object.create({}, {
            prop: descObj
        });
        for (var property in newObj) {
            if (property === "prop") {
                accessed = true;
            }
        }
        return !accessed;
    }
runTestCase(testcase);


text:
namespace CGAL {

namespace Polyline_simplification_2
{
/// \ingroup PkgPolylineSimplification2Classes

/// This class is a cost function which calculates the cost as the square of the distance between the original and simplified polylines,
/// possibly scaled based on a factor.
///
/// \cgalModels `PolylineSimplificationCostFunction`.
template<class FT>
class Hybrid_squared_distance_cost
{

public:

  /// Initializes the cost function with the specified `ratio`
  Hybrid_squared_distance_cost( FT ratio ) : mSquaredRatio(ratio*ratio) {}

  /// Compute the hybrid squared distance cost.
  ///
  /// Given a vertex in constraint iterator `vicq` computes `vicp=std::prev(vicq)` and `vicr=std::next(vicq)`,
  /// returns the maximal square distance between each point along the original subpolyline,
  /// between `vicp` and `vicr`,
  /// and the straight line segment from `*vicp->point() to *vicr->point()` divided by the smallest of
  /// - the square of the ratio given to the constructor of the cost function,
  /// - and the shortest squared distance between that segment and each of the vertices adjacent to `vicq`.
  ///
  /// \tparam CDT  must be `CGAL::Constrained_Delaunay_triangulation_2` with a vertex type that
  /// is model of  `PolylineSimplificationVertexBase_2`.
 template<class CDT>
 boost::optional<typename CDT::Geom_traits::FT>
    operator()(  const Constrained_triangulation_plus_2<CDT>& pct
                 , typename Constrained_triangulation_plus_2<CDT>::Vertices_in_constraint_iterator vicq) const
  {
    typedef typename Constrained_triangulation_plus_2<CDT>::Points_in_constraint_iterator Points_in_constraint_iterator;
    typedef typename Constrained_triangulation_plus_2<CDT>::Vertex_circulator Vertex_circulator;
    typedef typename Constrained_triangulation_plus_2<CDT>::Geom_traits Geom_traits ;
    typedef typename Geom_traits::Compute_squared_distance_2 Compute_squared_distance;
    typedef typename Geom_traits::Construct_segment_2        Construct_segment;
    typedef typename Geom_traits::Segment_2                  Segment;
    typedef typename Geom_traits::Point_2                    Point;

    Compute_squared_distance compute_squared_distance = pct.geom_traits().compute_squared_distance_2_object() ;
    Construct_segment        construct_segment        = pct.geom_traits().construct_segment_2_object() ;
    typedef typename Constrained_triangulation_plus_2<CDT>::Vertices_in_constraint_iterator Vertices_in_constraint_iterator;

    Vertices_in_constraint_iterator vicp = boost::prior(vicq);
    Vertices_in_constraint_iterator vicr = boost::next(vicq);

    Point const& lP = (*vicp)->point();
    Point const& lR = (*vicr)->point();

    Segment lP_R = construct_segment(lP, lR) ;

    FT d1(0);
    Points_in_constraint_iterator pp(vicp), rr(vicr);
    ++pp;

    for ( ;pp != rr; ++pp )
      d1 = (std::max)(d1, compute_squared_distance( lP_R, *pp ) ) ;

    FT d2 = mSquaredRatio;

    Vertex_circulator vc = pct.incident_vertices(*vicq), done(vc);
    do {
      if((vc != pct.infinite_vertex()) && (vc != *vicp) && (vc != *vicr)){
	d2 = (std::min)(d2, compute_squared_distance(vc->point(), (*vicq)->point()));
      }
      ++vc;
    }while(vc != done);

    return d1 / d2;
  }

private:

  FT mSquaredRatio ;

};

} // namespace Polyline_simplification_2

} //namespace CGAL

#endif // CGAL_POLYLINE_SIMPLIFICATION_2_HYBRID_SQUARED_DISTANCE_COST_H


text:
#ifndef _BEAMPARTICLE_H_
#define _BEAMPARTICLE_H_
#include "Particle.h"
#include "../utils/CLHEP/Vector/Vector/LorentzVector.h"
#include "PDF.h"
#include <vector>

using namespace std;

namespace VINHAC {

class BeamParticle;
class Particle;
}

namespace VINHAC {

//!  Class representing beam particle in BeamHandler
/*!
 * @see BeamHandler
*/
class BeamParticle: public Particle {
private:
	PDF *pdf; //!< Parton density function of the beam particle;
public:
	/**
	* \brief Constructor of BeamParticle
	*/
	BeamParticle();

	/**
	* \brief Destructor of BeamParticle
	*/
	~BeamParticle();

	/**
	* \brief Constructor of BeamParticle
	*
	* @see PDF
	* @param PDGid PDG id of particle
	* @param pdf pointer to PDF object for this particle
	*/
	BeamParticle(int PDGid, PDF* pdf);

	/**
	* \brief Constructor of BeamParticle
	*
	* @see PDF
	* @see CLHEP::HepLorentzVector
	* @param PDGid PDG id of particle
	* @param momentum momentum of particle
	* @param pdf pointer to PDF object for this particle
	*/
	BeamParticle(int PDGid, CLHEP::HepLorentzVector momentum, PDF* pdf);

	/**
	* \brief sets PDF object for this particle
	*
	* @see PDF
	* @param pdf pointer to PDF object for this particle
	*/
	inline void setPDF(PDF* pdf) {
		this->pdf = pdf;
	}

	/**
	* \brief returns PDF object for this particle
	*
	* @see PDF
	* @return pdf pointer to PDF object for this particle
	*/
	inline PDF* getPDF() {
		return pdf;
	}

};
}
#endif /* BEAMPARTICLE_H_ */


text:
@class TLPeer;
@class TLPeerNotifySettings;

@interface TLDialog : NSObject <TLObject>

@property (nonatomic, retain) TLPeer *peer;
@property (nonatomic) int32_t top_message;
@property (nonatomic) int32_t unread_count;
@property (nonatomic, retain) TLPeerNotifySettings *notify_settings;

@end

@interface TLDialog$dialog : TLDialog

@end


text:
#region License

#endregion

using System;

namespace VulkaNetGenerator.Attributes
{
    public class AsTypeAttribute : Attribute
    {
        public string TypeStr { get; }

        public AsTypeAttribute(string typeStr) { TypeStr = typeStr; }
    }
}


text:
<?php
use Zend\Config\Factory;

return Factory::fromFiles(
    glob(__DIR__ . '/autoload/{,*.}{global,local}.php', GLOB_BRACE)
);


text:
<?php

namespace Classes;

class Git {

    protected $repo_path = null;
    protected static $bin = '/usr/bin/git';

    public static function &create_new($repo_path, $source = null) {
        if (is_dir($repo_path) && file_exists($repo_path."/.git") && is_dir($repo_path."/.git")) {
            throw new \Exception('"'.$repo_path.'" is already a git repository');
        } else {
            $repo = new self($repo_path, true, false);
            if (is_string($source)) {
                $repo->clone_from($source);
            } else {
                $repo->run('init');
            }
            return $repo;
        }
    }

    public function __construct($repo_path = null, $create_new = false, $_init = true) {
        if (is_string($repo_path)) {
            $this->set_repo_path($repo_path, $create_new, $_init);
        }
    }

    public function set_repo_path($repo_path, $create_new = false, $_init = true) {
        if (is_string($repo_path)) {
            if ($new_path = realpath($repo_path)) {
                $repo_path = $new_path;
                if (is_dir($repo_path)) {
                    if (file_exists($repo_path."/.git") && is_dir($repo_path."/.git")) {
                        $this->repo_path = $repo_path;
                    } else {
                        if ($create_new) {
                            $this->repo_path = $repo_path;
                            if ($_init) {
                                $this->run('init');
                            }
                        } else {
                            throw new \Exception('"'.$repo_path.'" is not a git repository');
                        }
                    }
                } else {
                    throw new \Exception('"'.$repo_path.'" is not a directory');
                }
            } else {
                if ($create_new) {
                    if ($parent = realpath(dirname($repo_path))) {
                        mkdir($repo_path);
                        $this->repo_path = $repo_path;
                        if ($_init) $this->run('init');
                    } else {
                        throw new \Exception('cannot create repository in non-existent directory');
                    }
                } else {
                    throw new \Exception('"'.$repo_path.'" does not exist');
                }
            }
        }
    }

    public function test_git() {
        $descriptorspec = array(
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w'),
        );
        $pipes = array();
        $resource = proc_open(Git::get_bin(), $descriptorspec, $pipes);

        $stdout = stream_get_contents($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        foreach ($pipes as $pipe) {
            fclose($pipe);
        }

        $status = trim(proc_close($resource));
        return ($status != 127);
    }

    protected function run_command($command) {
        $descriptorspec = array(
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w'),
        );
        $pipes = array();
        $resource = proc_open($command, $descriptorspec, $pipes, $this->repo_path);

        $stdout = stream_get_contents($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        foreach ($pipes as $pipe) {
            fclose($pipe);
        }

        $status = trim(proc_close($resource));
        if ($status) throw new \Exception($stderr);

        return $stdout;
    }

    public function run($command) {
        return $this->run_command(Git::get_bin()." ".$command);
    }

    public function add($files = "*") {
        if (is_array($files)) {
            $files = '"'.implode('" "', $files).'"';
        }
        return $this->run("add $files -v");
    }

    public function commit($message = "") {
        return $this->run("commit -av -m ".escapeshellarg($message));
    }

    public function clone_to($target) {
        return $this->run("clone --local ".$this->repo_path." $target");
    }

    public function clone_from($source) {
        return $this->run("clone --local $source ".$this->repo_path);
    }

    public function clone_remote($source) {
        return $this->run("clone $source ".$this->repo_path);
    }

    public function clean($dirs = false) {
        return $this->run("clean".(($dirs) ? " -d" : ""));
    }

    public function create_branch($branch) {
        return $this->run("branch $branch");
    }

    public function delete_branch($branch, $force = false) {
        return $this->run("branch ".(($force) ? '-D' : '-d')." $branch");
    }

    public function list_branches($keep_asterisk = false) {
        $branchArray = explode("\n", $this->run("branch"));
        foreach($branchArray as $i => &$branch) {
            $branch = trim($branch);
            if (! $keep_asterisk) {
                $branch = str_replace("* ", "", $branch);
            }
            if ($branch == "") {
                unset($branchArray[$i]);
            }
        }
        return $branchArray;
    }

    public function active_branch($keep_asterisk = false) {
        $branchArray = $this->list_branches(true);
        $active_branch = preg_grep("/^\*/", $branchArray);
        reset($active_branch);
        if ($keep_asterisk) {
            return current($active_branch);
        } else {
            return str_replace("* ", "", current($active_branch));
        }
    }

    public function checkout($branch) {
        return $this->run("checkout $branch");
    }

    public function merge($branch) {
        return $this->run("merge $branch --no-ff");
    }

    public function fetch() {
        return $this->run("fetch");
    }

    public function add_tag($tag, $message = null) {
        if ($message === null) {
            $message = $tag;
        }
        return $this->run("tag -a $tag -m $message");
    }

    public function push($remote, $branch) {
        return $this->run("push --tags $remote $branch");
    }

    public function pull($remote, $branch) {
        return $this->run("pull $remote $branch");
    }

    public function set_description($new) {
        file_put_contents($this->repo_path."/.git/description", $new);
    }

    public function get_description() {
        return file_get_contents($this->repo_path."/.git/description");
    }

    public static function set_bin($path) {
        self::$bin = $path;
    }

    public static function get_bin() {
        return self::$bin;
    }

    public static function open($repo_path) {
        return new self($repo_path);
    }

    public static function is_repo($var) {
        return (get_class($var) == 'GitRepo');
    }
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/activeandroid/activeandroid.iml" filepath="$PROJECT_DIR$/activeandroid/activeandroid.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/framework/framework.iml" filepath="$PROJECT_DIR$/framework/framework.iml" />
      <module fileurl="file://$PROJECT_DIR$/greendao/greendao.iml" filepath="$PROJECT_DIR$/greendao/greendao.iml" />
      <module fileurl="file://$PROJECT_DIR$/ormlite/ormlite.iml" filepath="$PROJECT_DIR$/ormlite/ormlite.iml" />
      <module fileurl="file://$PROJECT_DIR$/sugarorm/sugarorm.iml" filepath="$PROJECT_DIR$/sugarorm/sugarorm.iml" />
      <module fileurl="file://$PROJECT_DIR$/tcc.iml" filepath="$PROJECT_DIR$/tcc.iml" />
    </modules>
  </component>
</project>


text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

namespace OpenIddict.Validation;

/// <summary>
/// Represents the type of an OpenIddict validation handler.
/// </summary>
public enum OpenIddictValidationHandlerType
{
    /// <summary>
    /// The handler is of an unspecified type.
    /// </summary>
    Unknown = 0,

    /// <summary>
    /// The handler is a built-in handler, provided as part of the official OpenIddict packages.
    /// </summary>
    BuiltIn = 1,

    /// <summary>
    /// The handler is a custom handler, registered by the end user or a third-party package.
    /// </summary>
    Custom = 2
}


text:
@interface EntityOneToOne2 : NSManagedObject

@property (nonatomic, retain) NSNumber * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSManagedObject *parentEntity;

@end


text:
package nxt.http;

import nxt.Account;
import nxt.Attachment;
import nxt.DigitalGoodsStore;
import nxt.NxtException;
import org.json.simple.JSONStreamAware;

import javax.servlet.http.HttpServletRequest;

import static nxt.http.JSONResponses.GOODS_NOT_DELIVERED;
import static nxt.http.JSONResponses.INCORRECT_PURCHASE;

public final class DGSFeedback extends CreateTransaction {

    static final DGSFeedback instance = new DGSFeedback();

    private DGSFeedback() {
        super(new APITag[] {APITag.DGS, APITag.CREATE_TRANSACTION},
                "purchase");
    }

    @Override
    JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

        DigitalGoodsStore.Purchase purchase = ParameterParser.getPurchase(req);

        Account buyerAccount = ParameterParser.getSenderAccount(req);
        if (! buyerAccount.getId().equals(purchase.getBuyerId())) {
            return INCORRECT_PURCHASE;
        }
        if (purchase.getEncryptedGoods() == null) {
            return GOODS_NOT_DELIVERED;
        }

        Account sellerAccount = Account.getAccount(purchase.getSellerId());
        Attachment attachment = new Attachment.DigitalGoodsFeedback(purchase.getId());
        return createTransaction(req, buyerAccount, sellerAccount.getId(), 0, attachment);
    }

}


text:
describe 'VolumeSettingController' do
  tests VolumeSettingScreen
  alias :screen :controller

  describe '初期化' do

    it 'should not be nil' do
      screen.should.not.be.nil
    end

    it 'テストプレーヤーを持つ' do
      screen.test_player.tap do |player|
        player.should.not.be.nil
        player.should.be.kind_of(AVAudioPlayer)
      end
    end

  end

  it 'should not rotate' do
    screen.should_autorotate.should.be.false
  end
end


text:
import { Coordinate } from '@odopod/odo-helpers';
import { Direction, Axis } from './settings';

function isXAxis(axis) {
  return axis === Axis.X;
}

function isYAxis(axis) {
  return axis === Axis.Y;
}

function isBothAxis(axis) {
  return axis === Axis.BOTH;
}

function hasDirection(direction) {
  return direction !== Direction.NONE;
}

function finiteOrZero(velocity) {
  return Number.isFinite(velocity) ? velocity : 0;
}

/**
 * Calculate the velocity between two points.
 *
 * @param {number} deltaTime Change in time.
 * @param {number} deltaX Change in x.
 * @param {number} deltaY Change in y.
 * @return {Coordinate} Velocity of the drag.
 */

function getVelocity(deltaTime, deltaX, deltaY) {
  return new Coordinate(
    finiteOrZero(deltaX / deltaTime),
    finiteOrZero(deltaY / deltaTime),
  );
}

function getTheDirection(value1, value2, isGreater, isLess, isEqual) {
  if (value1 - value2 > 0) {
    return isGreater;
  } else if (value1 - value2 < 0) {
    return isLess;
  }

  return isEqual;
}

/**
 * angle to direction define.
 * @param {Coordinate} coord1 The starting coordinate.
 * @param {Coordinate} coord2 The ending coordinate.
 * @return {string} Direction constant.
 */
function getDirection(coord1, coord2) {
  if (Math.abs(coord1.x - coord2.x) >= Math.abs(coord1.y - coord2.y)) {
    return getTheDirection(
      coord1.x, coord2.x, Direction.LEFT,
      Direction.RIGHT, Direction.NONE,
    );
  }

  return getTheDirection(
    coord1.y, coord2.y, Direction.UP,
    Direction.DOWN, Direction.NONE,
  );
}

function isOnAxis(axis, direction) {
  const isXAndLeftOrRight = isXAxis(axis) && (
    direction === Direction.LEFT ||
    direction === Direction.RIGHT);

  const isYAndUpOrDown = isYAxis(axis) && (
    direction === Direction.UP ||
    direction === Direction.DOWN);

  const isBothAndNotNone = isBothAxis(axis) && hasDirection(direction);

  return isXAndLeftOrRight || isYAndUpOrDown || isBothAndNotNone;
}

function didMoveOnAxis(axis, direction, deltaX, deltaY) {
  // X axis and deltaX > 0
  return (isXAxis(axis) && Math.abs(deltaX) > 0) ||

  // Y axis and deltaY > 0
  (isYAxis(axis) && Math.abs(deltaY) > 0) ||

  // Both axis, as long as it actually moved.
  (isBothAxis(axis) && hasDirection(direction));
}

function getAxisDirection(axis, start, end) {
  const _start = Object.assign({}, start);
  const _end = Object.assign({}, end);

  if (isXAxis(axis)) {
    _start.y = 0;
    _end.y = 0;
  } else if (isYAxis(axis)) {
    _start.x = 0;
    _end.x = 0;
  }

  return getDirection(_start, _end);
}

class PointerEvent {
  /**
   * Object representing a drag event.
   * @param {Object} options Options object.
   * @param {string} options.type Event type.
   * @param {Element} options.target Element the event is happening on.
   * @param {Coordinate} options.delta Total movement of the pointer (with friction
   *     already applied to it).
   * @param {Coordinate} options.currentVelocity Calculated velocity since the last interval.
   * @constructor
   */
  constructor(options) {
    this.type = options.type;

    /**
     * @type {Element}
     */
    this.target = options.target;

    /**
     * @type {Element}
     */
    this.currentTarget = options.currentTarget;

    /**
     * Starting location of the pointer.
     * @type {Coordinate}
     */
    this.start = options.start;

    /**
     * Ending location of the pointer.
     * @type {Coordinate}
     */
    this.end = options.end;

    /**
     * Change in position since the start of the drag.
     * @type {Coordinate}
     */
    this.delta = options.delta;

    /**
     * Time elapsed from mouse/touch down to mouse/touch up.
     * @type {number}
     */
    this.deltaTime = options.deltaTime;

    /**
     * Velocity of the whole drag.
     * @type {Coordinate}
     */
    this.velocity = getVelocity(this.deltaTime, this.delta.x, this.delta.y);

    /**
     * The velocity in the last 100 milliseconds.
     * @type {Coordinate}
     */
    this.currentVelocity = options.currentVelocity;

    /**
     * Distance dragged.
     * @type {number}
     */
    this.distance = Coordinate.distance(options.start, options.end);

    /**
     * Direction of drag.
     * @type {Direction}
     */
    this.direction = getDirection(options.start, options.end);

    /**
     * Whether the drag direction is on the axis of the draggable element.
     * @type {boolean}
     */
    this.isDirectionOnAxis = isOnAxis(options.axis, this.direction);

    /**
     * Whether the draggable element moved along the dragging axis at all.
     * @type {boolean}
     */
    this.didMoveOnAxis = didMoveOnAxis(
      options.axis, this.direction,
      this.delta.x, this.delta.y,
    );

    /**
     * Direction of drag which excludes directions not on its axis.
     * @type {Direction}
     */
    this.axisDirection = getAxisDirection(options.axis, options.start, options.end);

    /** @type {{pixel: Coordinate, percent: Coordinate}} */
    this.position = options.position;

    /** @type {boolean} Whether `preventDefault` has been called. */
    this.defaultPrevented = false;
  }

  preventDefault() {
    this.defaultPrevented = true;
  }
}

export default PointerEvent;


text:
**Please follow these basic steps to simplify pull request reviews - if you don't you'll probably just be asked to anyway.**

* Please rebase your branch against the current master
* Run ```npm install``` to make sure your development dependencies are up-to-date
* If you've added new functionality, **please** include tests which validate its behaviour
* Make reference to possible [issues](https://github.com/rodzzlessa24/vue-webgulp/issues) on PR comment

## Submitting bug reports

* Please detail the affected browser(s) and operating system(s)
* Please be sure to state which version of node **and** npm you're using


text:
package com.haulmont.cuba.core.sys.remoting.discovery;

import java.util.List;
import java.util.function.Consumer;

/**
 * Strategy class for work with {@link StaticServerSelector}.
 * Does not sorts the list of servers - this is a legacy behavior for platform version < 6.5.
 */
public class NoopServerSorter implements Consumer<List<String>> {

    @Override
    public void accept(List<String> strings) {
        // no sorting
    }
}


text:
package org.osgi.util.pushstream;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * {@link PushbackPolicyOption} provides a standard set of simple
 * {@link PushbackPolicy} implementations.
 *
 * @see PushbackPolicy
 */
public enum PushbackPolicyOption {

	/**
	 * Returns a fixed amount of back pressure, independent of how full the
	 * buffer is
	 */
	FIXED {
		@Override
		public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) {
			return q -> value;
		}
	},
	/**
	 * Returns zero back pressure until the buffer is full, then it returns a
	 * fixed value
	 */
	ON_FULL_FIXED {
		@Override
		public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) {
			return q -> q.remainingCapacity() == 0 ? value : 0;
		}
	},
	/**
	 * Returns zero back pressure until the buffer is full, then it returns an
	 * exponentially increasing amount, starting with the supplied value and
	 * doubling it each time. Once the buffer is no longer full the back
	 * pressure returns to zero.
	 */
	ON_FULL_EXPONENTIAL {
		@Override
		public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) {
			AtomicInteger backoffCount = new AtomicInteger(0);
			return q -> {
				if (q.remainingCapacity() == 0) {
					return value << backoffCount.getAndIncrement();
				}
				backoffCount.set(0);
				return 0;
			};

		}
	},
	/**
	 * Returns zero back pressure when the buffer is empty, then it returns a
	 * linearly increasing amount of back pressure based on how full the buffer
	 * is. The maximum value will be returned when the buffer is full.
	 */
	LINEAR {
		@Override
		public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) {
			return q -> {
				long remainingCapacity = q.remainingCapacity();
				long used = q.size();
				return (value * used) / (used + remainingCapacity);
			};
		}
	};

	/**
	 * Create a {@link PushbackPolicy} instance configured with a base back
	 * pressure time in nanoseconds
	 *
	 * The actual backpressure returned will vary based on the selected
	 * implementation, the base value, and the state of the buffer.
	 *
	 * @param value
	 * @return A {@link PushbackPolicy} to use
	 */
	public abstract <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value);

}


text:
using namespace llvm;

namespace rubinius {

namespace jit {

  void MethodBuilder::setup() {
    std::vector<Type*> ftypes;
    ftypes.push_back(ctx_->ptr_type("State"));
    ftypes.push_back(ctx_->ptr_type("CallFrame"));
    ftypes.push_back(ctx_->ptr_type("Executable"));
    ftypes.push_back(ctx_->ptr_type("Module"));
    ftypes.push_back(ctx_->ptr_type("Arguments"));

    FunctionType* ft = FunctionType::get(ctx_->ptr_type("Object"), ftypes, false);

    std::ostringstream ss;
    ss << std::string("_X_")
       << ctx_->llvm_state()->enclosure_name(info_.method())
       << "#"
       << ctx_->llvm_state()->symbol_debug_str(info_.method()->name())
       << "k@" << ++ctx_->llvm_state()->vm()->metrics().m.jit_metrics.methods_compiled;

    llvm::Function* func = Function::Create(ft, GlobalValue::ExternalLinkage,
                            ss.str(), ctx_->module());

    Function::arg_iterator ai = func->arg_begin();
    llvm::Value* state = ai++; state->setName("state");
    llvm::Value* prev = ai++; prev->setName("previous");
    exec = ai++; exec->setName("exec");
    module = ai++; module->setName("mod");
    llvm::Value* args = ai++; args->setName("args");

    BasicBlock* block = BasicBlock::Create(ctx_->llvm_context(), "entry", func);
    b().SetInsertPoint(block);

    ctx_->set_function(func);

    info_.set_state(state);
    info_.set_args(args);
    info_.set_previous(prev);
    info_.set_entry(block);

    alloc_frame("method_body");

    check_arity();

    initialize_frame(machine_code_->stack_size);

    nil_stack(machine_code_->stack_size, constant(cNil, obj_type));

    setup_scope();

    import_args();

    import_args_ = b().GetInsertBlock();

    b().CreateBr(body_);
    b().SetInsertPoint(body_);
  }

  void MethodBuilder::check_arity() {
    Value* total_offset = b().CreateConstGEP2_32(info_.args(), 0,
        offset::Arguments::total, "total_pos");
    Value* N = b().CreateLoad(total_offset, "arg.total");

    // For others to use.
    arg_total = N;

    BasicBlock* check_arity = info_.new_block("check_arity");
    BasicBlock* arg_error = info_.new_block("arg_error");
    BasicBlock* cont = info_.new_block("import_args");

    const native_int T = machine_code_->total_args;
    const native_int M = machine_code_->required_args;
    const native_int RI = machine_code_->splat_position;
    const bool RP = (RI >= 0);

    if(T == 0) {
      if(!RP) {
        Value* cmp = b().CreateICmpNE(N, cint(0), "arg_cmp");
        b().CreateCondBr(cmp, arg_error, cont);
      } else {
        b().CreateBr(cont);
      }
    } else {
      b().CreateBr(check_arity);
    }

    b().SetInsertPoint(check_arity);

    BasicBlock* n_gt_t = info_.new_block("not_rp_and_n_gt_t");

    // N < M
    Value* cmp = b().CreateICmpSLT(N, cint(M), "arg_cmp");
    b().CreateCondBr(cmp, arg_error, n_gt_t);

    b().SetInsertPoint(n_gt_t);

    BasicBlock* kw_check = info_.new_block("kw_check");

    // !RP && N > T
    if(!RP) {
      Value* cmp = b().CreateICmpSGT(N, cint(T), "arg_cmp");
      b().CreateCondBr(cmp, arg_error, kw_check);
    } else {
      b().CreateBr(kw_check);
    }

    b().SetInsertPoint(kw_check);

    if(machine_code_->keywords) {
      BasicBlock* kw_check = info_.new_block("kw_check_object");

      b().CreateCondBr(
          b().CreateICmpSGT(N, cint(M)),
          kw_check, cont);

      b().SetInsertPoint(kw_check);

      Value* arg_ary = b().CreateLoad(
          b().CreateConstGEP2_32(info_.args(), 0,
            offset::Arguments::arguments, "arg_ary_pos"),
          "arg_ary");

      Value* kw_arg = b().CreateLoad(
            b().CreateGEP(arg_ary,
              b().CreateSub(N, cint(1))));

      Signature sig(ctx_, "Object");
      sig << "State";
      sig << "CallFrame";
      sig << "Object";

      Value* call_args[] = {
        info_.state(),
        info_.previous(),
        kw_arg
      };

      Value* keyword_val = sig.call("rbx_check_keyword",
          call_args, 3, "keyword_val", b());

      b().CreateStore(keyword_val, keyword_object_);
    }

    b().CreateBr(cont);

    b().SetInsertPoint(arg_error);

    // Call our arg_error helper
    Signature sig(ctx_, "Object");

    sig << "State";
    sig << "CallFrame";
    sig << "Arguments";
    sig << ctx_->Int32Ty;

    Value* call_args[] = {
      info_.state(),
      info_.previous(),
      info_.args(),
      cint(machine_code_->total_args)
    };

    Value* val = sig.call("rbx_arg_error", call_args, 4, "ret", b());
    return_value(val);

    // Switch to using continuation
    b().SetInsertPoint(cont);
  }

  void MethodBuilder::assign_fixed_args(Value* arg_ary, int start, int end) {
    for(int i = start; i < end; i++) {
      Value* int_pos = cint(i);

      Value* arg_val_offset = b().CreateConstGEP1_32(arg_ary, i, "arg_val_offset");

      Value* arg_val = b().CreateLoad(arg_val_offset, "arg_val");

      Value* idx[] = {
        cint(0),
        cint(offset::StackVariables::locals),
        int_pos
      };

      Value* pos = b().CreateGEP(vars, idx, "var_pos");

      b().CreateStore(arg_val, pos);
    }
  }

  void MethodBuilder::import_args() {
    Value* N = arg_total;

    const native_int T = machine_code_->total_args;
    const native_int M = machine_code_->required_args;
    const native_int P = machine_code_->post_args;
    const native_int H = M - P;
    const native_int RI = machine_code_->splat_position;
    const bool RP = (RI >= 0);

    Value* arg_ary = b().CreateLoad(
                       b().CreateConstGEP2_32(info_.args(), 0,
                         offset::Arguments::arguments, "arg_ary_pos"),
                       "arg_ary");

    BasicBlock* after_args = info_.new_block("after_args");
    BasicBlock* setup_bounds = info_.new_block("setup_bounds");

    if(!RP && M == T) {
      if(H > 0) assign_fixed_args(arg_ary, 0, H);
      if(P > 0) assign_fixed_args(arg_ary, H, H + P);

      b().CreateBr(after_args);
    } else {
      b().CreateBr(setup_bounds);
    }

    b().SetInsertPoint(setup_bounds);

    Value* null = Constant::getNullValue(obj_type);

    // K = (keyword_object && N > M) ? 1 : 0;
    Value* K = b().CreateSelect(
        b().CreateAnd(
          b().CreateICmpNE(b().CreateLoad(keyword_object_), null),
          b().CreateICmpSGT(N, cint(M))),
        cint(1), cint(0));

    // O = T - M - (mcode->keywords ? 1 : 0);
    Value* O = cint(T - M - (machine_code_->keywords ? 1 : 0));

    // E = N - M - K;
    Value* N_M_K = b().CreateSub(N, b().CreateAdd(cint(M), K));
    Value* E = b().CreateSelect(b().CreateICmpSGE(N_M_K, cint(0)), N_M_K, cint(0));

    // ON = (X = MIN(O, E)) > 0 ? X : 0;
    Value* X = b().CreateSelect(b().CreateICmpSLE(O, E), O, E);
    Value* ON = b().CreateSelect(b().CreateICmpSGT(X, cint(0)), X, cint(0));

    // head arguments
    if(H > 0) {
      assign_fixed_args(arg_ary, 0, H);
    }

    // arg limit = H + ON
    Value* H_ON = b().CreateAdd(cint(H), ON);

    BasicBlock* pre_opts = info_.new_block("pre_optional_args");
    BasicBlock* post_opts = info_.new_block("post_optional_args");

    b().CreateCondBr(
        b().CreateICmpSGT(O, cint(0)),
        pre_opts, post_opts);

    // optional arguments
    // for(l = a = H; l < H + O && a < H + ON; l++, a++)

    b().SetInsertPoint(pre_opts);

    // local limit = H + O
    Value* H_O = b().CreateAdd(cint(H), O);

    {
      BasicBlock* top = info_.new_block("opt_arg_loop_top");
      BasicBlock* body = info_.new_block("opt_arg_loop_body");
      BasicBlock* after = info_.new_block("opt_arg_loop_cont");

      // local_index_ = arg_index_ = H
      b().CreateStore(cint(H), local_index_);
      b().CreateStore(cint(H), arg_index_);

      b().CreateBr(top);
      b().SetInsertPoint(top);

      Value* local_i = b().CreateLoad(local_index_, "local_index");
      Value* arg_i = b().CreateLoad(arg_index_, "arg_index");

      // local_index_ < H + O && arg_index_ < H + ON
      Value* loop_test = b().CreateAnd(
          b().CreateICmpSLT(local_i, H_O),
          b().CreateICmpSLT(arg_i, H_ON));

      b().CreateCondBr(loop_test, body, after);

      b().SetInsertPoint(body);

      Value* idx[] = {
        cint(0),
        cint(offset::StackVariables::locals),
        local_i
      };

      // locals[local_index_] = args[local_index_]
      b().CreateStore(
          b().CreateLoad(
            b().CreateGEP(arg_ary, arg_i)),
          b().CreateGEP(vars, idx));

      // local_index_++
      b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index_);

      // arg_index++
      b().CreateStore(b().CreateAdd(arg_i, cint(1)), arg_index_);

      b().CreateBr(top);

      b().SetInsertPoint(after);
    }

    // if ON < O : more optional parameters than arguments available
    {
      BasicBlock* pre = info_.new_block("missing_opt_arg_loop_pre");
      BasicBlock* top = info_.new_block("missing_opt_arg_loop_top");
      BasicBlock* body = info_.new_block("missing_opt_arg_loop_body");
      BasicBlock* after = info_.new_block("missing_opt_arg_loop_cont");

      b().CreateCondBr(
          b().CreateICmpSLT(ON, O),
          pre, post_opts);

      b().SetInsertPoint(pre);

      b().CreateStore(H_ON, local_index_);

      Type* undef_type = llvm::PointerType::getUnqual(obj_type);
      Object** addr = ctx_->llvm_state()->shared().globals.undefined.object_address();
      Value* undef = b().CreateLoad(constant(addr, undef_type));

      b().CreateBr(top);
      b().SetInsertPoint(top);

      Value* local_i = b().CreateLoad(local_index_, "local_index");

      b().CreateCondBr(
          b().CreateICmpSLT(local_i, H_O),
          body, after);

      b().SetInsertPoint(body);

      Value* idx[] = {
        cint(0),
        cint(offset::StackVariables::locals),
        local_i
      };

      // locals[local_index_] = undefined
      b().CreateStore(
          undef,
          b().CreateGEP(vars, idx));

      // local_index_++
      b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index_);

      b().CreateBr(top);

      b().SetInsertPoint(after);
      b().CreateBr(post_opts);
    }

    b().SetInsertPoint(post_opts);

    BasicBlock* post_args = info_.new_block("post_args");

    // rest arguments
    if(RP) {
      // RN = (RP && (X = E - ON) > 0) ? X : 0;
      X = b().CreateSub(E, ON);
      Value* RN = b().CreateSelect(
          b().CreateICmpSGT(X, cint(0)), X, cint(0));

      Signature sig(ctx_, "Object");
      sig << "State";
      sig << "Arguments";
      sig << ctx_->Int32Ty;
      sig << ctx_->Int32Ty;

      Value* call_args[] = {
        info_.state(),
        info_.args(),
        H_ON,
        RN
      };

      Function* func = sig.function("rbx_construct_splat");
      func->setOnlyReadsMemory();
      func->setDoesNotThrow();

      CallInst* splat_val = sig.call("rbx_construct_splat",
          call_args, 4, "splat_val", b());

      splat_val->setOnlyReadsMemory();
      splat_val->setDoesNotThrow();

      Value* idx[] = {
        cint(0),
        cint(offset::StackVariables::locals),
        cint(RI)
      };

      Value* pos = b().CreateGEP(vars, idx, "splat_pos");
      b().CreateStore(splat_val, pos);
    }

    b().CreateBr(post_args);
    b().SetInsertPoint(post_args);

    BasicBlock* kw_args = info_.new_block("kw_args");

    if(P > 0) {
      // post arguments
      // PI = H + O + (RP ? 1 : 0)
      Value* PI = b().CreateAdd(cint(H), RP ? b().CreateAdd(O, cint(1)) : O);

      // l = PI; l < PI + P && a < N - K
      Value* PI_P = b().CreateAdd(PI, cint(P));
      Value* N_K = b().CreateSub(N, K);

      // local_index_ = PI
      b().CreateStore(PI, local_index_);

      // arg_index_ = N - P - K
      b().CreateStore(
          b().CreateSub(
            b().CreateSub(N, cint(P)), K),
          arg_index_);

      {
        BasicBlock* top = info_.new_block("post_arg_loop_top");
        BasicBlock* body = info_.new_block("post_arg_loop_body");
        BasicBlock* after = info_.new_block("post_arg_loop_cont");

        b().CreateBr(top);
        b().SetInsertPoint(top);

        Value* local_i = b().CreateLoad(local_index_, "local_index");
        Value* arg_i = b().CreateLoad(arg_index_, "arg_index");

        // l < PI + P && a < N - K
        Value* loop_test = b().CreateAnd(
            b().CreateICmpSLT(local_i, PI_P),
            b().CreateICmpSLT(arg_i, N_K));

        b().CreateCondBr(loop_test, body, after);

        b().SetInsertPoint(body);

        Value* idx[] = {
          cint(0),
          cint(offset::StackVariables::locals),
          local_i
        };

        // locals[local_index_] = args[local_index_]
        b().CreateStore(
            b().CreateLoad(
              b().CreateGEP(arg_ary, arg_i)),
            b().CreateGEP(vars, idx));

        // local_index_++
        b().CreateStore(b().CreateAdd(local_i, cint(1)), local_index_);

        // arg_index++
        b().CreateStore(b().CreateAdd(arg_i, cint(1)), arg_index_);

        b().CreateBr(top);

        b().SetInsertPoint(after);
      }
    }

    b().CreateBr(kw_args);
    b().SetInsertPoint(kw_args);

    // keywords
    {
      BasicBlock* before_kw = info_.new_block("before_keywords");
      BasicBlock* after_kw = info_.new_block("after_keywords");

      Value* null = Constant::getNullValue(obj_type);
      Value* kw_val = b().CreateLoad(keyword_object_, "kw_val");

      b().CreateCondBr(
          b().CreateICmpNE(kw_val, null),
          before_kw, after_kw);

      b().SetInsertPoint(before_kw);

      Value* idx[] = {
        cint(0),
        cint(offset::StackVariables::locals),
        RP ? cint(T) : cint(T - 1)
      };

      b().CreateStore(
          b().CreateLoad(keyword_object_),
          b().CreateGEP(vars, idx));

      b().CreateBr(after_kw);

      b().SetInsertPoint(after_kw);
    }

    b().CreateBr(after_args);
    b().SetInsertPoint(after_args);
  }

  void MethodBuilder::return_value(Value* ret, BasicBlock* cont) {
    if(ctx_->llvm_state()->include_profiling()) {
      BasicBlock* end_profiling = info_.new_block("end_profiling");
      if(!cont) {
        cont = info_.new_block("continue");
      }

      ctx_->profiling(b(), end_profiling, cont);

      Signature sig(ctx_, ctx_->VoidTy);
      sig << llvm::PointerType::getUnqual(ctx_->Int8Ty);

      Value* call_args[] = {
        method_entry_
      };

      sig.call("rbx_end_profiling", call_args, 1, "", b());

      b().CreateBr(cont);

      b().SetInsertPoint(cont);
    }

    info_.add_return_value(ret, b().GetInsertBlock());
    b().CreateBr(info_.return_pad());
  }

  void MethodBuilder::setup_scope() {
    llvm::Value* args = info_.args();

    Value* heap_null = ConstantExpr::getNullValue(llvm::PointerType::getUnqual(vars_type));
    Value* heap_pos = get_field(vars, offset::StackVariables::on_heap);

    b().CreateStore(heap_null, heap_pos);

    Value* self = b().CreateLoad(get_field(args, offset::Arguments::recv),
        "args.recv");

    if(Class* klass = info_.self_class()) {
      if(!klass->nil_p()) {
        type::KnownType kt = type::KnownType::unknown();
        if(kind_of<SingletonClass>(klass)) {
          kt = type::KnownType::singleton_instance(klass->class_id());
        } else {
          kt = type::KnownType::instance(klass->class_id());
        }
        kt.associate(ctx_, self);
      }
    }

    b().CreateStore(self, get_field(vars, offset::StackVariables::self));
    Value* mod = module;
    b().CreateStore(mod, get_field(vars, offset::StackVariables::module));

    Value* blk = b().CreateLoad(get_field(args, offset::Arguments::block),
        "args.block");
    b().CreateStore(blk, get_field(vars, offset::StackVariables::block));

    b().CreateStore(Constant::getNullValue(ctx_->ptr_type("VariableScope")),
        get_field(vars, offset::StackVariables::parent));

    b().CreateStore(constant(cNil, obj_type), get_field(vars, offset::StackVariables::last_match));

    nil_locals();
  }

  void MethodBuilder::initialize_frame(int stack_size) {
    Value* code_gep = get_field(call_frame, offset::CallFrame::compiled_code);
    method = b().CreateBitCast(
        exec, cast<llvm::PointerType>(code_gep->getType())->getElementType(), "compiled_code");

    // previous
    b().CreateStore(info_.previous(), get_field(call_frame, offset::CallFrame::previous));

    // arguments
    b().CreateStore(info_.args(), get_field(call_frame, offset::CallFrame::arguments));

    // msg
    b().CreateStore(
        ConstantInt::getNullValue(ctx_->Int8PtrTy),
        get_field(call_frame, offset::CallFrame::dispatch_data));

    // compiled_code
    b().CreateStore(method, code_gep);

    // constant_scope
    Value* constant_scope = b().CreateLoad(
        b().CreateConstGEP2_32(method, 0, offset::CompiledCode::scope, "constant_scope_pos"),
        "constant_scope");

    Value* constant_scope_gep = get_field(call_frame, offset::CallFrame::constant_scope);
    b().CreateStore(constant_scope, constant_scope_gep);

    // flags
    int flags = CallFrame::cJITed;
    if(!use_full_scope_) flags |= CallFrame::cClosedScope;

    b().CreateStore(
        cint(flags),
        get_field(call_frame, offset::CallFrame::flags));

    // ip
    b().CreateStore(
        cint(0),
        get_field(call_frame, offset::CallFrame::ip));

    // scope
    b().CreateStore(vars, get_field(call_frame, offset::CallFrame::scope));

    // jit_data
    b().CreateStore(
        constant(ctx_->runtime_data_holder(), ctx_->Int8PtrTy),
        get_field(call_frame, offset::CallFrame::jit_data));

    if(ctx_->llvm_state()->include_profiling()) {
      BasicBlock* setup_profiling = info_.new_block("setup_profiling");
      BasicBlock* cont = info_.new_block("continue");

      ctx_->profiling(b(), setup_profiling, cont);

      Signature sig(ctx_, ctx_->VoidTy);
      sig << "State";
      sig << llvm::PointerType::getUnqual(ctx_->Int8Ty);
      sig << "Executable";
      sig << "Module";
      sig << "Arguments";
      sig << "CompiledCode";

      Value* call_args[] = {
        info_.state(),
        method_entry_,
        exec,
        module,
        info_.args(),
        method
      };

      sig.call("rbx_begin_profiling", call_args, 6, "", b());

      b().CreateBr(cont);

      b().SetInsertPoint(cont);
    }
  }
}
}

#endif


text:
package com.bt.nia.koala.robustness.parsers;

import java.util.Iterator;
import java.util.List;

import com.bt.nia.koala.robustness.commands.UnexpectedOutputException;

public class KoalaPortalOutputParser extends OutputParserBase {
	private static final String KOALA_PORTAL_TITLE_REGEX = "^.*?<title>BT Cloud</title>.*?$";

	@Override
	protected int getMinNumLines() {
		throw new RuntimeException("Not used");
	}

	@Override
	protected int getMaxNumLines() {
		throw new RuntimeException("Not used");
	}

	@Override
	public String[] parse(List<String> lines) throws UnexpectedOutputException {
		Iterator<String> iter = lines.iterator();
		StringBuilder output = new StringBuilder();
		while (iter.hasNext()) {
			String line = iter.next();
			if (line.matches(KOALA_PORTAL_TITLE_REGEX))
				return null;
			else if (line.contains("HTML><HEAD><TITLE>Directory:"))
				throw new UnexpectedOutputException("Directory listing found on home page");
			else
				output.append(line + "\n");
		}

		throw new UnexpectedOutputException(String.format("No title in koala portal output:\n%s", output.toString()));
	}

	@Override
	protected String parseLine(int lineNumber, String line) {
		throw new RuntimeException("Not used");
	}
}


text:
<?php
declare(strict_types = 1);

namespace Database\Tables;

use Data\UserId;
use Database\AbstractTable;
use Database\Filters\AbstractFilter;
use Database\Filters\Types\ProjectFilter;
use Database\Objects\ProjectInfo;
use Database\Objects\ProjectVisibilityInfo;
use Database\Objects\RoleInfo;
use Database\Objects\UserProfile;
use Exception;
use PDOException;
use Session\Permissions\ProjectPermissions;
use Session\Permissions\SystemPermissions;

final class ProjectTable extends AbstractTable{
  /**
   * @param string $name
   * @param string $url
   * @param bool $hidden
   * @param UserProfile $owner
   * @throws Exception
   */
  public function addProject(string $name, string $url, bool $hidden, UserProfile $owner): void{
    $this->db->beginTransaction();

    try{
      $this->execute('INSERT INTO projects (name, url, description, hidden, owner_id) VALUES (?, ?, \'\', ?, ?)',
                     'SSBS', [$name, $url, $hidden, $owner->getId()]);

      $id = $this->getLastInsertId();

      if ($id === null){
        $this->db->rollBack();
        throw new Exception('Could not retrieve project ID.');
      }

      $project = new ProjectInfo($id, $name, $url, $owner->getId());
      $roles = new ProjectRoleTable($this->db, $project);
      $perms = new ProjectRolePermTable($this->db, $project);
      $members = new ProjectMemberTable($this->db, $project);

      $perms_reporter = [
          ProjectPermissions::CREATE_ISSUE,
      ];

      $perms_developer = array_merge($perms_reporter, [
          ProjectPermissions::MODIFY_ALL_ISSUE_FIELDS,
          ProjectPermissions::EDIT_ALL_ISSUES,
          ProjectPermissions::MANAGE_MILESTONES,
          ProjectPermissions::LIST_MEMBERS,
      ]);

      $perms_moderator = array_merge($perms_developer, [
          ProjectPermissions::DELETE_ALL_ISSUES,
          ProjectPermissions::MANAGE_MEMBERS,
          ProjectPermissions::VIEW_SETTINGS,
      ]);

      $perms_admin = array_merge($perms_moderator, [
          ProjectPermissions::MANAGE_SETTINGS_GENERAL,
          ProjectPermissions::MANAGE_SETTINGS_DESCRIPTION,
          ProjectPermissions::MANAGE_SETTINGS_ROLES,
      ]);

      $owner_role_id = $roles->addRole('Owner', RoleInfo::PROJECT_OWNER);
      $administrator_role_id = $roles->addRole('Administrator');
      $moderator_role_id = $roles->addRole('Moderator');
      $developer_role_id = $roles->addRole('Developer');
      $reporter_role_id = $roles->addRole('Reporter');

      $perms->addRolePermissions($administrator_role_id, $perms_admin);
      $perms->addRolePermissions($moderator_role_id, $perms_moderator);
      $perms->addRolePermissions($developer_role_id, $perms_developer);
      $perms->addRolePermissions($reporter_role_id, $perms_reporter);

      $members->addMember($owner->getId(), $owner_role_id);

      $this->db->commit();
    }catch(PDOException $e){
      $this->db->rollBack();
      throw $e;
    }
  }

  public function changeSettings(int $id, string $name, bool $hidden): void{
    $this->execute('UPDATE projects SET name = ?, hidden = ? WHERE id = ?',
                   'SBI', [$name, $hidden, $id]);
  }

  public function countProjects(?ProjectFilter $filter = null): ?int{
    $filter ??= ProjectFilter::empty();

    $stmt = $filter->prepare($this->db, 'SELECT COUNT(*) FROM projects', AbstractFilter::STMT_COUNT);
    $stmt->execute();
    return $this->fetchOneInt($stmt);
  }

  /**
   * @param ProjectFilter|null $filter
   * @return ProjectInfo[]
   */
  public function listProjects(?ProjectFilter $filter = null): array{
    $filter ??= ProjectFilter::empty();

    $stmt = $filter->prepare($this->db, 'SELECT id, name, url, owner_id FROM projects');
    $stmt->execute();
    return $this->fetchMap($stmt, fn($v): ProjectInfo => new ProjectInfo($v['id'], $v['name'], $v['url'], UserId::fromRaw($v['owner_id'])));
  }

  /**
   * @param UserId $user_id
   * @return ProjectInfo[]
   */
  public function listProjectsOwnedBy(UserId $user_id): array{
    $stmt = $this->db->prepare('SELECT id, name, url FROM projects WHERE owner_id = ?');
    $stmt->execute([$user_id]);
    return $this->fetchMap($stmt, fn($v): ProjectInfo => new ProjectInfo($v['id'], $v['name'], $v['url'], $user_id));
  }

  public function getInfoFromUrl(string $url, ?UserId $logon_user_id, SystemPermissions $perms): ?ProjectVisibilityInfo{
    $user_visibility_clause = $logon_user_id === null ? '' : ProjectFilter::getUserVisibilityClause();
    $stmt = $this->db->prepare('SELECT id, name, owner_id, (hidden = FALSE'.$user_visibility_clause.') AS visible FROM projects WHERE url = :url');
    $stmt->bindValue('url', $url);

    if ($logon_user_id !== null){
      ProjectFilter::bindUserVisibility($stmt, $logon_user_id);
    }

    $stmt->execute();
    $res = $this->fetchOneRaw($stmt);

    if ($res === false){
      return null;
    }

    $project = new ProjectInfo($res['id'], $res['name'], $url, UserId::fromRaw($res['owner_id']));
    $visible = (bool)$res['visible'] || $perms->check(SystemPermissions::LIST_ALL_PROJECTS);

    return new ProjectVisibilityInfo($project, $visible);
  }

  public function setDescription(int $id, string $description): void{
    $this->execute('UPDATE projects SET description = ? WHERE id = ?',
                   'SI', [$description, $id]);
  }

  public function getDescription(int $id): ?string{
    $stmt = $this->execute('SELECT description FROM projects WHERE id = ?',
                           'I', [$id]);

    return $this->fetchOneColumn($stmt);
  }

  public function checkUrlExists(string $url): bool{
    $stmt = $this->execute('SELECT 1 FROM projects WHERE url = ?',
                           'S', [$url]);

    return (bool)$this->fetchOneColumn($stmt);
  }

  public function isHidden(int $id): bool{
    $stmt = $this->execute('SELECT hidden FROM projects WHERE id = ?',
                           'I', [$id]);

    return (bool)$this->fetchOneColumn($stmt);
  }

  public function deleteById(int $id): void{
    $this->execute('DELETE FROM projects WHERE id = ?',
                   'I', [$id]);
  }
}

?>