text:
all : devel

#---------------------------------------------------------------------
# Declare the targets
#---------------------------------------------------------------------

# Targets for building GPDB with various options
# (development builds)
.PHONY : devel

# (release builds)
.PHONY : dist dist_prof

# Targets recognized by the PostgreSQL makefile (GNUmakefile)
.PHONY : all install installdirs uninstall distprep
.PHONY : clean distclean maintainer-clean

# The pvk target builds a subset of the GPDB package that includes just the
# tools used to verify the configuration of a set of GPDB servers.
.PHONY : pvk

# Targets for running autoconf and autoheader
.PHONY : autoconf

# Internal functions which are invoked by other rules within this makefile
.PHONY : mgmtcopy copylibs
.PHONY : RECONFIG HOMEDEP GPROOTDEP GPROOTDEP GPROOTFAIL
.PHONY : clients

#---------------------------------------------------------------------
# Make 3rd-party libraries and tools
#---------------------------------------------------------------------

# tell included makefiles where to find build-top-level resources
BLD_TOP:=$(shell sh -c pwd)
include Makefile.global
include Makefile.thirdparty

ifneq "$(BLD_BITS)" ""
export NO_M64=1
endif

#$(warning )
#$(warning PATH=$(PATH))
#$(warning LD_LIBRARY_PATH=$(LD_LIBRARY_PATH))
#$(warning )
#$(warning BLD_ARCH=$(BLD_ARCH))
#$(warning BLD_BITS=$(BLD_BITS))
#$(warning BLD_CFLAGS=$(BLD_CFLAGS))
#$(warning )

BLD_CXX_LIB_DIR=$($(BLD_ARCH)_CXX_LIB_DIR)

#---------------------------------------------------------------------
# Directory paths and file names
#---------------------------------------------------------------------

GPPGDIR=$(shell cd .. && pwd)
GPMGMT=../gpMgmt
BUILDDIR=$(GPPGDIR)

RELEASE=devel
GPDIR=greenplum-db-$(RELEASE)
PLRDIR=greenplum-plr-$(RELEASE)
CLIENTSDIR=greenplum-clients-$(RELEASE)

DISTPATH=$(GPROOT)/$(GPDIR)
CLIENTSDISTPATH=$(GPROOT)/$(CLIENTSDIR)

ifeq "$(DEVPATH)" ""
BLD_HOME=$(HOME)
DEVPATH=$(BLD_HOME)/$(GPDIR)
CLIENTSDEVPATH=$(BLD_HOME)/$(CLIENTSDIR)
else
# DEVPATH has been passed in as by the build scripts
GPROOT_DEV=$(dir $(DEVPATH))
CLIENTSDEVPATH=$(GPROOT_DEV)$(CLIENTSDIR)
endif

# files generated by 'configure'
ISCONFIG=$(GPPGDIR)/GNUmakefile

##
## On these platforms, we do the full build including the server. On other
## platforms, we do a client-only build.
##
SERVER_PLATFORMS=rhel7_x86_64 rhel6_x86_64 linux_x86_64

#---------------------------------------------------------------------
# Compiler options
#---------------------------------------------------------------------

OPTFLAGS="$(strip $(BLD_CFLAGS) -O3 -fargument-noalias-global -fno-omit-frame-pointer -g)"
PROFFLAGS="$(strip $(BLD_CFLAGS) -O3 -fargument-noalias-global -fno-omit-frame-pointer -g)"

ifeq (on, ${GPDBGOPT})
CFLAGS_OPT=-O1 -fno-omit-frame-pointer
else
CFLAGS_OPT=-O0
endif

ifeq (on, ${GPDBGCOV})
DEBUG_CFLAGS_OPT=
else
DEBUG_CFLAGS_OPT=-g3
endif

DEBUGFLAGS="$(strip $(BLD_CFLAGS) $(CFLAGS_OPT) $(DEBUG_CFLAGS_OPT))"
#---------------------------------------------------------------------
# configure
#---------------------------------------------------------------------

DEFPORT=5432

ORCA_CONFIG=--enable-orca

rhel6_x86_64_CONFIGFLAGS=--with-quicklz --with-gssapi --enable-mapreduce --enable-orafce --enable-ic-proxy ${ORCA_CONFIG} --enable-gpcloud --with-libxml --with-openssl --with-pam --with-ldap
rhel7_x86_64_CONFIGFLAGS=--with-quicklz --with-gssapi --enable-mapreduce --enable-orafce --enable-ic-proxy ${ORCA_CONFIG} --enable-gpcloud --with-libxml --with-openssl --with-pam --with-ldap
ubuntu18.04_x86_64_CONFIGFLAGS=--with-quicklz --with-gssapi --enable-mapreduce --enable-orafce --enable-ic-proxy ${ORCA_CONFIG} --enable-gpcloud --with-libxml --with-openssl --with-pam --with-ldap
sles12_x86_64_CONFIGFLAGS=--with-quicklz --with-gssapi --enable-mapreduce --enable-orafce --enable-ic-proxy ${ORCA_CONFIG} --enable-gpcloud --with-libxml --with-openssl --with-pam --with-ldap
BLD_CONFIGFLAGS=$($(BLD_ARCH)_CONFIGFLAGS)

CONFIGFLAGS=$(strip $(BLD_CONFIGFLAGS) --with-pgport=$(DEFPORT) $(BLD_DEPLOYMENT_SETTING))

ifdef CONFIGURE_FLAGS
CONFIGFLAGS+= $(CONFIGURE_FLAGS)
endif

ifneq (false, ${PG_LANG})
CONFIGFLAGS+= --with-perl --with-python PYTHON=python3
ifdef TCL_CFG
CONFIGFLAGS+= --with-tcl-config=${TCL_CFG}
endif
endif

# Configure in thirdparty libraries from the ext/ directory
CONFIG_INCLUDES=$(BLD_THIRDPARTY_INCLUDE_DIR) $(BLD_THIRDPARTY_INCLUDE_DIR)/libxml2
CONFIG_LIBRARIES=$(strip $(BLD_THIRDPARTY_LIB_DIR) $(BLD_CXX_LIB_DIR) $(BLD_PTHREADS_LIB_DIR))
CONFIGFLAGS+= --with-includes="$(CONFIG_INCLUDES)" --with-libraries="$(CONFIG_LIBRARIES)"

CONFIGFLAGS+= --disable-rpath
CONFIGFLAGS+= LDFLAGS='-Wl,--enable-new-dtags -Wl,-rpath,\$$$$ORIGIN/../lib'

RECONFIG :
	rm -f Debug/GNUmakefile
	rm -f Release/GNUmakefile
	rm -f $(GPPGDIR)/GNUmakefile

$(GPPGDIR)/GNUmakefile : $(GPPGDIR)/configure  env.sh
	rm -rf $(INSTLOC)
	mkdir -p $(GPPGDIR)
	echo "Running ./configure with CONFIGFLAGS=$(CONFIGFLAGS)\n"
	cd $(GPPGDIR) && \
                     CFLAGS=$(INSTCFLAGS) 					  \
                     ./configure $(CONFIGFLAGS)               \
                         --prefix=$(INSTLOC)                  \
                         --mandir=$(INSTLOC)/man

Debug/GNUmakefile : $(GPPGDIR)/configure  env.sh
	rm -rf $(INSTLOC)
	mkdir -p Debug
	echo "Running ./configure with CONFIGFLAGS=$(CONFIGFLAGS)\n"
	cd Debug && \
                CFLAGS=$(INSTCFLAGS) 						 \
                ./configure $(CONFIGFLAGS)                   \
                    --prefix=$(INSTLOC)                      \
                    --mandir=$(INSTLOC)/man

Release/GNUmakefile : $(GPPGDIR)/configure  env.sh
	rm -rf $(INSTLOC)
	mkdir -p Release
	echo "Running ./configure with CONFIGFLAGS=$(CONFIGFLAGS)\n"
	cd Release && \
                  CFLAGS=$(INSTCFLAGS) 					    \
                  ./configure $(CONFIGFLAGS)                \
                      --prefix=$(INSTLOC)                   \
                      --mandir=$(INSTLOC)/man

#---------------------------------------------------------------------
# autoconf
#---------------------------------------------------------------------
# Whenever there is a change to the configure.in file, autoconf and
# autoheader should be run to regenerate the files configure and
# src/include/pg_config.h.in.  Note that autoconf and autoheader
# don't update the timestamps of their output files unless there is an
# actual change in the contents; thus 'make' rules don't work well for
# rebuilding those files automatically.  Developers should rebuild them
# manually when needed, which can be done by invoking 'make autoconf'.

autoconf : RECONFIG
	cd $(GPPGDIR) && autoconf && autoheader

#---------------------------------------------------------------------
# standardized build rules
#---------------------------------------------------------------------

BLD_LD_LIBRARY_PATH:=$($(BLD_ARCH)_LD_LIBRARY_PATH):$($(BLD_WHERE_THE_LIBRARY_THINGS_ARE))
export $(BLD_WHERE_THE_LIBRARY_THINGS_ARE)=$(BLD_LD_LIBRARY_PATH)

perl_archlibexp:=$(shell perl -MConfig -e 'print $$Config{archlibexp}')

# set default build steps
define BUILD_STEPS
	@$(MAKE) -C $(BUILDDIR)/src/backend generated-headers
	cd $(BUILDDIR) && PYGRESQL_LDFLAGS='-Wl,-rpath,\$$$$ORIGIN/../../../lib -Wl,--enable-new-dtags' QUICKLZ_LDFLAGS='-Wl,-rpath,\$$$$ORIGIN/../../lib -Wl,--enable-new-dtags' $(MAKE) $(PARALLEL_MAKE_OPTS) install
	cd $(BUILDDIR)/src/pl/plpython && $(MAKE) clean && echo 'LDFLAGS += -Wl,-rpath,\$$$$ORIGIN/../../ext/python/lib/ -Wl,--enable-new-dtags' >> Makefile && $(MAKE) $(PARALLEL_MAKE_OPTS) install && cd $(BUILDDIR)
	cd $(BUILDDIR)/src/pl/plperl && $(MAKE) clean && echo "LDFLAGS += -Wl,-rpath,$(perl_archlibexp)/CORE -Wl,--enable-new-dtags" >> GNUmakefile && echo "LDFLAGS_SL += -Wl,-rpath,$(perl_archlibexp)/CORE -Wl,--enable-new-dtags" >> GNUmakefile && $(MAKE) $(PARALLEL_MAKE_OPTS) install && cd $(BUILDDIR)
	#@$(MAKE) greenplum_path INSTLOC=$(INSTLOC)
	#@$(MAKE) mgmtcopy INSTLOC=$(INSTLOC)
	@$(MAKE) copylibs INSTLOC=$(INSTLOC)
	@$(MAKE) clients INSTLOC=$(INSTLOC) CLIENTSINSTLOC=$(CLIENTSINSTLOC)
	@$(MAKE) set_scripts_version INSTLOC=$(CLIENTSINSTLOC)
	@$(MAKE) copylicense INSTLOC=$(INSTLOC) \
                         CLIENTSINSTLOC=$(CLIENTSINSTLOC)
endef

ifeq "$(BLD_GPDB_BUILDSET)" "partial"
define BUILD_STEPS
	rm -rf $(INSTLOC)
	cd $(BUILDDIR)/gpMgmt/ && $(MAKE) generate_greenplum_path_file
	cd $(BUILDDIR)/src/backend/ && $(MAKE) ../../src/include/parser/gram.h
	cd $(BUILDDIR)/src/backend/ && $(MAKE) ../../src/include/utils/errcodes.h
	cd $(BUILDDIR)/src/backend/ && $(MAKE) ../../src/include/utils/fmgroids.h
	cd $(BUILDDIR)/src/port/ && $(MAKE) install
	cd $(BUILDDIR)/src/bin/scripts/ && $(MAKE) install
	cd $(BUILDDIR)/src/bin/psql/ && $(MAKE) install
	cd $(BUILDDIR)/src/bin/pg_config/ && $(MAKE) install
	cd $(BUILDDIR)/src/bin/pg_dump/ && $(MAKE) pg_dump
	cp -p $(BUILDDIR)/src/bin/pg_dump/pg_dump $(INSTLOC)/bin/
	cd $(BUILDDIR)/src/bin/pg_dump/ && $(MAKE) pg_dumpall
	cp -p $(BUILDDIR)/src/bin/pg_dump/pg_dumpall $(INSTLOC)/bin/
	cd $(BUILDDIR)/src/bin/pg_dump/ && $(MAKE) pg_restore
	cp -p $(BUILDDIR)/src/bin/pg_dump/pg_restore $(INSTLOC)/bin/
	cd $(BUILDDIR)/src/interfaces/ecpg/ && $(MAKE) install
	cd $(BUILDDIR)/src/include/ && $(MAKE) install
	cd $(BUILDDIR)/src/interfaces/libpq/ && $(MAKE) install
	cd $(BUILDDIR)/src/bin/gpfdist && $(MAKE) install
	cp -p $(GPMGMT)/bin/gpload $(INSTLOC)/bin/gpload
	cp -p $(GPMGMT)/bin/gpload.py $(INSTLOC)/bin/gpload.py
	$(MAKE) copylibs INSTLOC=$(INSTLOC)
	cd $(GPMGMT)/bin && $(MAKE) pygresql INSTLOC=$(INSTLOC)
	$(MAKE) clients INSTLOC=$(INSTLOC) CLIENTSINSTLOC=$(CLIENTSINSTLOC)
endef
endif

#---------------------------------------------------------------------
# environment for later builds inside the source tree
#
# run this to create an environment-loading script, source it,
# and be able to build inside the source tree with the same
# results as building from here at the top
#---------------------------------------------------------------------

env.sh:
	echo "export BLD_ARCH=$(BLD_ARCH)" > env.sh
	echo "export NO_M64=$(NO_M64)" >> env.sh
	echo "export PATH=$(PATH)" >> env.sh
	echo "export $(BLD_WHERE_THE_LIBRARY_THINGS_ARE)=$($(BLD_WHERE_THE_LIBRARY_THINGS_ARE))" >> env.sh
ifneq "$(PERL_DIR)" ""
	echo "export PERL5LIB=$(PERL_DIR)/lib/site_perl/5.12.4/x86_64-linux:$(PERL_DIR)/lib/site_perl/5.12.4:$(PERL_DIR)/lib/5.12.4/x86_64-linux:$(PERL_DIR)/lib/5.12.4" >> env.sh
endif

#---------------------------------------------------------------------
# Development builds
#---------------------------------------------------------------------

devel : INSTCFLAGS=$(DEBUGFLAGS)
devel : INSTLOC=$(DEVPATH)
devel : CLIENTSINSTLOC=$(CLIENTSDEVPATH)
devel : CONFIGFLAGS+= --enable-cassert --enable-debug --enable-depend
ifdef ENABLE_VPATH_BUILD
devel : BUILDDIR=Debug
devel : ISCONFIG=$(BUILDDIR)/GNUmakefile
devel : HOMEDEP Debug/GNUmakefile
else
devel : HOMEDEP $(ISCONFIG)
endif
	$(BUILD_STEPS)

#---------------------------------------------------------------------
# Release builds
#---------------------------------------------------------------------

dist : INSTCFLAGS=$(OPTFLAGS)
dist : INSTLOC=$(DISTPATH)
dist : CLIENTSINSTLOC=$(CLIENTSDISTPATH)
ifdef ENABLE_VPATH_BUILD
dist : BUILDDIR=Release
dist : ISCONFIG=$(BUILDDIR)/GNUmakefile
dist : GPROOTDEP RECONFIG Release/GNUmakefile
else
dist : GPROOTDEP RECONFIG $(ISCONFIG)
endif
	$(BUILD_STEPS)

dist_prof : INSTCFLAGS=$(PROFFLAGS)
dist_prof : INSTLOC=$(DISTPATH)
dist_prof : CLIENTSINSTLOC=$(CLIENTSDISTPATH)
ifdef ENABLE_VPATH_BUILD
dist_prof : BUILDDIR=Release
dist_prof : ISCONFIG=$(BUILDDIR)/GNUmakefile
dist_prof : GPROOTDEP RECONFIG $(ISCONFIG)
else
dist_prof : ISCONFIG=../GNUmakefile
dist_prof : GPROOTDEP RECONFIG $(ISCONFIG)
endif
	$(BUILD_STEPS)

dist_faultinj : CLIENTSINSTLOC=$(CLIENTSDISTPATH)
ifdef ENABLE_VPATH_BUILD
dist_faultinj : BUILDDIR=Release
dist_faultinj : ISCONFIG=$(BUILDDIR)/GNUmakefile
dist_faultinj : GPROOTDEP RECONFIG Release/GNUmakefile
else
dist_faultinj : ISCONFIG=../GNUmakefile
dist_faultinj : GPROOTDEP RECONFIG $(ISCONFIG)
endif
	$(BUILD_STEPS)

#---------------------------------------------------------------------
# clientTools
#---------------------------------------------------------------------
#
# The clients target builds GPDB [f]or a subset of files needed for client
# platforms.  It also builds clientTools-specific items like the ODBC drivers.
#

ifneq "$(GPROOT)" ""
CLIENTS_HOME_DIR=$(GPROOT)
else
CLIENTS_HOME_DIR=$(BLD_HOME)
endif
CLIENTSINSTLOC=$(CLIENTS_HOME_DIR)/greenplum-clients
CLIENTSINSTLOC_BIN=$(CLIENTSINSTLOC)/bin
CLIENTSINSTLOC_BINEXT=$(CLIENTSINSTLOC)/bin/ext/
CLIENTSINSTLOC_EXT=$(CLIENTSINSTLOC)/ext
CLIENTSINSTLOC_LIB=$(CLIENTSINSTLOC)/lib
CLIENTSINSTLOC_LIB_PWARE=$(CLIENTSINSTLOC)/lib/pware
CLIENTSINSTLOC_DOCS=$(CLIENTSINSTLOC)/docs
CLIENTSINSTLOC_OPENSOURCE=$(CLIENTSINSTLOC)/thirdparty

DOC_TYPE=Unix
SCRIPT=.sh

define tmpCLIENTS_FILESET_BIN
	gpfdist
	gpload
	gpload.py
	pg_dump
	pg_dumpall
	psql
	createdb
	dropdb
	createuser
	dropuser
endef
CLIENTS_FILESET_BIN = $(strip $(tmpCLIENTS_FILESET_BIN))

# pg.py, pgdb.py, _pg.so are from pygresql which does not install into a single module
define tmpCLIENTS_FILESET_BINEXT
	pg.py
	pgdb.py
	_pg*.so
	yaml
endef
CLIENTS_FILESET_BINEXT = $(strip $(tmpCLIENTS_FILESET_BINEXT))

BLD_PYTHON_FILESET=.

BLD_OS:=$(shell uname -s)
Darwin_CLIENTS_LIBS=libcrypto.*.dylib libssl.*.dylib libpq.*.dylib* libkrb5.*.dylib libcom_err.*.dylib libldap_r-*.dylib libk5crypto.*.dylib libkrb5support.*.dylib liblber-*.dylib libyaml*.dylib
Linux_CLIENTS_LIBS=libpq.so*
define tmpCLIENTS_FILESET_LIB
	$($(BLD_OS)_CLIENTS_LIBS)
endef
CLIENTS_FILESET_LIB = $(strip $(tmpCLIENTS_FILESET_LIB))

ifeq "$(MPP_ARCH)" ""
rhel6_x86_64_MPP_ARCH=RHEL6-x86_64
rhel7_x86_64_MPP_ARCH=RHEL7-x86_64
ifneq "$($(BLD_ARCH)_MPP_ARCH)" ""
export MPP_ARCH=$($(BLD_ARCH)_MPP_ARCH)
else
export MPP_ARCH=$(BLD_ARCH)
endif
endif

ifeq "$(INSTLOC)" ""
INSTLOC=$(GPDIR)
endif

VERSION:=$(shell [ -f ../VERSION ] && perl -pe 's, ,-,g' ../VERSION)
VERSION_SHORT:=$(shell [ -f ../VERSION ] && perl -pe 's, .*,,g' ../VERSION)

clients :
	if [ ! -z "$(CLIENTSINSTLOC)" ] && [ "$(CLIENTSINSTLOC)" != "/" ]; then rm -rf $(CLIENTSINSTLOC); fi
ifeq "$(findstring clients,$(BLD_TARGETS))" ""
	# ---- build and packaging of the clients package is currently disabled;
	# ---- set BLD_TARGETS="clients" to enable them.
else
	# ---- copy GPDB fileset ----
	mkdir -p $(CLIENTSINSTLOC_BIN)
	(cd $(INSTLOC)/bin/ && $(TAR) cf - $(CLIENTS_FILESET_BIN)) | (cd $(CLIENTSINSTLOC_BIN)/ && $(TAR) xpf -)$(check_pipe_for_errors)
	mkdir -p $(CLIENTSINSTLOC_BINEXT)
	(cd $(GPMGMT)/bin/ext/ && $(TAR) cf - $(CLIENTS_FILESET_BINEXT)) | (cd $(CLIENTSINSTLOC_BINEXT)/ && $(TAR) xpf -)$(check_pipe_for_errors)
ifneq "$(PYTHONHOME)" ""
	mkdir -p $(CLIENTSINSTLOC_EXT)/python
	(cd $(PYTHONHOME) && $(TAR) cf - $(BLD_PYTHON_FILESET)) | (cd $(CLIENTSINSTLOC_EXT)/python/ && $(TAR) xpf -)$(check_pipe_for_errors)
endif
	mkdir -p $(CLIENTSINSTLOC_LIB)
 ifneq "$(CLIENTS_FILESET_LIB)" ""
	 (cd $(INSTLOC)/lib/ && $(TAR) cf - $(CLIENTS_FILESET_LIB)) | (cd $(CLIENTSINSTLOC_LIB)/ && $(TAR) xpf -)$(check_pipe_for_errors)
 endif
	# ---- copy scripts fileset ----
	mkdir -p $(CLIENTSINSTLOC)
	cp -f client/scripts/greenplum_$@_path$(SCRIPT) $(CLIENTSINSTLOC)/

	# ---- updating the version in required packages ----
	@$(MAKE) set_scripts_version INSTLOC=$(CLIENTSINSTLOC)
endif

#---------------------------------------------------------------------
# Platform Verification Kit (PVK)
#   formerly checkTools
#
# The pvk target builds a subset of the GPDB package that includes
# just the tools used to verify the configuration of a set of GPDB servers.
#---------------------------------------------------------------------

PVK_SCRIPTS = \
	bin/gpscp			\
	bin/gpssh			\
	bin/gpcheckperf			\
	$(NULL)

PVK_FILESET = \
	$(CHECKTOOLS_SCRIPTS)	\
	bin/lib/gplib.py	\
	bin/lib/pxssh.py	\
	bin/lib/pexpect.py	\
	bin/lib/multidd		\
	bin/lib/stream		\
	$(NULL)

pvk : INSTCFLAGS=$(OPTFLAGS)
pvk : INSTLOC=$(DISTPATH)
pvk : version GPROOTDEP
	cd $(GPMGMT)/bin && $(MAKE) stream
	mkdir -p $(INSTLOC)/bin/lib
	@for file in $(PVK_FILESET); do \
	    echo "cp -p $(GPMGMT)/$${file} $(INSTLOC)/$${file}"; \
	    cp -p $(GPMGMT)/$${file} $(INSTLOC)/$${file}; \
	done
	perl putversion $(foreach script,$(PVK_SCRIPTS),$(INSTLOC)/$(script))

#---------------------------------------------------------------------
# Set Version
#---------------------------------------------------------------------

SET_VERSION_SCRIPTS = \
	bin/gpactivatestandby \
	bin/gpaddmirrors \
	bin/gpcheckperf \
	bin/gpdeletesystem \
	bin/gpexpand \
	bin/gpfilespace \
	bin/gpinitstandby \
	bin/gpinitsystem \
	bin/gpload.py \
	bin/gplogfilter \
	bin/gpmovemirrors \
	bin/gprecoverseg \
	bin/gpreload \
	bin/gpscp \
	bin/gpssh \
	bin/gpssh-exkeys \
	bin/gpstart \
	bin/gpstate \
	bin/gpstop \
	bin/lib/gpcheckcat \
	sbin/gpconfig_helper.py \
	sbin/gpcleansegmentdir.py \
	sbin/gpgetstatususingtransition.py \
	sbin/gpsegstart.py \
	sbin/gpsegstop.py \
	sbin/gpupgrademirror.py \
	lib/python/gppylib/programs/clsAddMirrors.py \
	lib/python/gppylib/programs/clsHostCacheLookup.py \
	lib/python/gppylib/programs/clsRecoverSegment.py \
	lib/python/gppylib/programs/clsSystemState.py \
	lib/python/gppylib/programs/gppkg.py \
	lib/python/gppylib/programs/kill.py \
	lib/python/gppylib/mainUtils.py \
	$(NULL)

set_scripts_version :
	@for file in $(SET_VERSION_SCRIPTS); do \
	    if [ -f $(INSTLOC)/$${file} ]; then \
	        perl $(BLD_TOP)/../putversion $(INSTLOC)/$${file} ; \
	    fi ; \
	done

#---------------------------------------------------------------------
# Internal functions
#---------------------------------------------------------------------

mgmtcopy :
	#Copy the management utilities
	mkdir -p $(INSTLOC)/bin
	mkdir -p $(INSTLOC)/lib
	mkdir -p $(INSTLOC)/lib/python
	mkdir -p $(INSTLOC)/sbin
	#Setup /lib/python contents
	cp -rp $(GPMGMT)/bin/gppylib $(INSTLOC)/lib/python
	cp -rp $(GPMGMT)/bin/ext/* $(INSTLOC)/lib/python
	cp -rp $(GPMGMT)/bin $(INSTLOC)
	cp -rp $(GPMGMT)/sbin/* $(INSTLOC)/sbin/.
	if [ ! -d ${INSTLOC}/docs ] ; then mkdir ${INSTLOC}/docs ; fi
	if [ -d $(GPMGMT)/doc ]; then cp -rp $(GPMGMT)/doc $(INSTLOC)/docs/cli_help; fi
	if [ -d $(GPMGMT)/demo/gpfdist_transform ]; then \
	  mkdir -p $(INSTLOC)/demo; \
	  $(TAR) -C $(GPMGMT)/demo -czf $(INSTLOC)/demo/gpfdist_transform.tar.gz gpfdist_transform; \
	fi
	$(MAKE) set_scripts_version INSTLOC=$(INSTLOC)
	# Remove unwanted files.
	rm -rf $(INSTLOC)/bin/ext
	rm -rf $(INSTLOC)/bin/pythonSrc
	rm -rf $(INSTLOC)/bin/Makefile
	rm -rf $(INSTLOC)/bin/src
	rm -rf $(INSTLOC)/bin/gppylib
	find $(INSTLOC)/lib/python/gppylib -name test -type d | xargs rm -rf

libcopy=(cd $(1) && $(TAR) cf - $(2)) | (cd $(3) && $(TAR) xvf -)$(check_pipe_for_errors)

copylibs : thirdparty-dist
	mkdir -p $(INSTLOC)/etc
	mkdir -p $(INSTLOC)/include

copylicense:
	for proddir in $(INSTLOC) $(CLIENTSINSTLOC); do \
	   if [ -d $${proddir} ]; then \
	      echo cp -v ${BLD_TOP}/LICENSE $${proddir}; \
	      echo cp -v ${BLD_TOP}/NOTICE  $${proddir}; \
	   fi; \
	done

HOMEDEP :
	@ #If the HOME variable isn't set, then execute the usage() path
	@if [ x"$(HOME)" = x ]; then $(MAKE) HOMEFAIL; fi

GPROOTDEP :
	@ #If the GPROOT variable isn't set, then execute the usage() path
	@if [ x"$(GPROOT)" = x ]; then $(MAKE) GPROOTFAIL; fi

GPROOTFAIL :
	@echo
	@echo "	The GPROOT path variable is not set."
	@echo
	@echo "	You must decide where you will install to, and set GPROOT to that location, prior to"
	@echo "	installing the GP module with this Makefile."
	@echo
	@exit 1

HOMEFAIL :
	@echo
	@echo "	The HOME environment variable is not set. Please set it to continue."
	@echo
	@exit 1

#---------------------------------------------------------------------
# Cleanup
#---------------------------------------------------------------------

clean :
#	@if [ ! -f $(ISCONFIG) ]; then echo "GPDB root not configured, no need to clean it"; fi
	@if [ -d Debug -a -f Debug/GNUmakefile ]; then cd Debug; $(MAKE) clean; fi
	@if [ -d Release -a -f Release/GNUmakefile ]; then cd Release; $(MAKE) clean; fi
	@if [ -d $(GPPGDIR) -a -f $(GPPGDIR)/GNUmakefile ]; then cd $(GPPGDIR); $(MAKE) clean; fi
	@if [ -d $(GPMGMT)/bin ]; then cd $(GPMGMT)/bin; $(MAKE) clean; fi

distclean :
#	@if [ ! -f $(ISCONFIG) ]; then echo "GPDB root not configured, no need to clean it"; fi
	@if [ -d Debug -a -f Debug/GNUmakefile ]; then cd Debug; $(MAKE) distclean; fi
	@if [ -d Release -a -f Release/GNUmakefile ]; then cd Release; $(MAKE) distclean; fi
	@if [ -d $(GPPGDIR) -a -f $(GPPGDIR)/GNUmakefile ]; then cd $(GPPGDIR); $(MAKE) distclean; fi
	@if [ -d $(GPMGMT)/bin ]; then cd $(GPMGMT)/bin; $(MAKE) distclean; fi
	@rm -f VERSION
	@rm -f env.sh

distprep : $(ISCONFIG)
	@cd $(BUILDDIR) && $(MAKE) distprep


text:
<!DOCTYPE html>

    <link type="text/css" rel="stylesheet" href="../css/materialize.css"  media="screen,projection"/>
    <link rel='shortcut icon' href='../favicon.ico' type='image/x-icon'/ >

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Aaron Jacobson </title>

        Aaron Jacobson

Home

Resume

Photography

Portfolio

Code

Contact

Home

Resume

Portfolio

Photography

Code

Contact

Portraits

            Coleman

            Kelsey

            Kelsey and her code

            LinkedIn profile shot

            Doing that work

      Aaron Jacobson © 2015
      Made with Materialize

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/ico" href="{{ STATIC_URL }}images/favicon.ico"/>
    <title>EIC: Africa</title>

    <!-- Le styles -->
    <link href="{{ STATIC_URL }}css/foundation.css" rel="stylesheet" type="text/css">

    <!-- Le scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="{{ STATIC_URL }}src/form.js"></script>
    <script>
        $(document).ready(
            function () {
                bind_all();
            }
        );
    </script>
</head>
<body>

</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Spelman STEM Scholars (S3) Program</AwardTitle>
    <AwardEffectiveDate>01/15/2009</AwardEffectiveDate>
    <AwardExpirationDate>12/31/2013</AwardExpirationDate>
    <AwardAmount>599490</AwardAmount>
    <AwardInstrument>
      <Value>Continuing grant</Value>
    </AwardInstrument>
    <Organization>
      11040000
      <Directorate>
        <LongName>Direct For Education and Human Resources</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Undergraduate Education</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Paul Tymann</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>Interdisciplinary (99)<br/><br/>The Spelman STEM Scholars (S3) program is providing competitive scholarships and academic/career-building support to academically-talented, economically disadvantaged African American females who pursue a STEM degree. Special emphasis is being placed on building a critical mass of prospective engineering graduates in Spelman's dual-degree engineering program with Georgia Institute of Technology and its Black Graduate Student Association. Spelman's esteemed group of faculty, "The Vanguard Faculty," will support and guide the first-year students. In addition to the scholarship support, Spelman is developing three new support initiatives: 1) introduction to engineering seminar series, 2) a graduate student mentoring program, and 3) scholarship/graduate school writing workshop.</AbstractNarration>
    <MinAmdLetterDate>01/09/2009</MinAmdLetterDate>
    <MaxAmdLetterDate>04/15/2010</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0850069</AwardID>
    <Investigator>
      <FirstName>Dekimberlin</FirstName>
      <LastName>Neely</LastName>
      <EmailAddress>dneely@spelman.edu</EmailAddress>
      <StartDate>04/15/2010</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Monica</FirstName>
      <LastName>Stephens</LastName>
      <EmailAddress>mstephens@spelman.edu</EmailAddress>
      <StartDate>01/09/2009</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Carmen</FirstName>
      <LastName>Sidbury</LastName>
      <EmailAddress>csidbury@spelman.edu</EmailAddress>
      <StartDate>01/09/2009</StartDate>
      <EndDate>08/06/2009</EndDate>
      <RoleCode>Former Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Spelman College</Name>
      <CityName>Atlanta</CityName>
      <ZipCode>303144399</ZipCode>
      <PhoneNumber>4042705897</PhoneNumber>
      <StreetAddress>350 Spelman Lane SW</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Georgia</StateName>
      <StateCode>GA</StateCode>
    </Institution>
    <ProgramElement>
      1536
      <Text>S-STEM:SCHLR SCI TECH ENG&MATH</Text>
    </ProgramElement>
    <ProgramReference>
      9178
      <Text>UNDERGRADUATE EDUCATION</Text>
    </ProgramReference>
    <ProgramReference>
      SMET
      <Text>SCIENCE, MATH, ENG & TECH EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
local ADDON_NAME, ADDON = ...

function DJBagsSettingsColumnsLoad(self)
	function self:Update()
		self.name:SetText(ADDON.locale.COLUMNS:format(self:GetParent().bag.settings.maxColumns))
	end
	self.up.process = function()
		local currentCount = self:GetParent().bag.settings.maxColumns
		if (currentCount < 20) then
			self:GetParent().bag.settings.maxColumns = currentCount + 1

			self:Update()
			self:GetParent().bag:Refresh()
		end
	end
	self.down.process = function()
		local currentCount = self:GetParent().bag.settings.maxColumns
		if (currentCount > 1) then
			self:GetParent().bag.settings.maxColumns = currentCount - 1

			self:Update()
			self:GetParent().bag:Refresh()
		end
	end
end

function DJBagsSettingsScaleLoad(self)
	function self:Update()
		self.name:SetText(ADDON.locale.SCALE:format(self:GetParent().bag.settings.scale))
	end
	self.up.process = function()
		local currentCount = self:GetParent().bag.settings.scale or 1
		if (currentCount < 1.7) then
			self:GetParent().bag.settings.scale = currentCount + 0.02

			self:Update()
			self:GetParent().bag:SetScale(self:GetParent().bag.settings.scale)
		end
	end
	self.down.process = function()
		local currentCount = self:GetParent().bag.settings.scale or 1
		if (currentCount > 0.2) then
			self:GetParent().bag.settings.scale = currentCount - 0.02

			self:Update()
			self:GetParent().bag:SetScale(self:GetParent().bag.settings.scale)
		end
	end
end


text:
@implementation Product

@end


text:
package org.telegram.tl;

/**
 * Packed type of tl-bool true value
 *
 * @author Ruben Bermudez
 */
public class TLBoolTrue extends TLBool {

    public static final int CLASS_ID = 0x997275b5;

    @Override
    public int getClassId() {
        return CLASS_ID;
    }

    @Override
    public String toString() {
        return "boolTrue#997275b5";
    }
}


text:
package net.vz.mongodb.jackson;

import com.mongodb.BasicDBObject;
import org.junit.Before;
import org.junit.Test;
import net.vz.mongodb.jackson.mock.MockObject;

import java.util.List;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

/**
 * Test the Json DB Cursor
 */
public class TestDBCursor extends MongoDBTestBase {
    private JacksonDBCollection<MockObject, String> coll;

    @Before
    public void setup() throws Exception {
        coll = getCollection(MockObject.class, String.class);
    }

    @Test
    public void testIterator() {
        MockObject o1 = new MockObject("id1", "blah1", 10);
        MockObject o2 = new MockObject("id2", "blah2", 20);
        MockObject o3 = new MockObject("id3", "blah3", 30);
        coll.insert(o1, o2, o3);
        DBCursor<MockObject> cursor = coll.find().sort(new BasicDBObject("integer", 1));
        assertThat(cursor.hasNext(), equalTo(true));
        assertThat(cursor.next(), equalTo(o1));
        assertThat(cursor.curr(), equalTo(o1));
        assertThat(cursor.hasNext(), equalTo(true));
        assertThat(cursor.next(), equalTo(o2));
        assertThat(cursor.curr(), equalTo(o2));
        assertThat(cursor.hasNext(), equalTo(true));
        assertThat(cursor.next(), equalTo(o3));
        assertThat(cursor.curr(), equalTo(o3));
        assertThat(cursor.hasNext(), equalTo(false));
    }

    @Test
    public void testArray() {
        MockObject o1 = new MockObject("id1", "blah1", 10);
        MockObject o2 = new MockObject("id2", "blah2", 20);
        MockObject o3 = new MockObject("id3", "blah3", 30);
        coll.insert(o1, o2, o3);
        List<MockObject> results = coll.find().sort(new BasicDBObject("integer", 1)).toArray();
        assertThat(results, contains(o1, o2, o3));
        assertThat(results, hasSize(3));
    }
}


text:
// Copyright (C) 2009 The Android Open Source Project
//
// 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.

package com.google.gwtexpui.user.client;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * Hosts a single {@link View}.
 *
 *
View instances are attached inside of an invisible DOM node, permitting their {@code onLoad()}
 * method to be invoked and to update the DOM prior to the elements being made visible in the UI.
 *
 *
Complaint View instances must invoke {@link View#display()} once the DOM is ready for
 * presentation.
 */
public class ViewSite<V extends View> extends Composite {
  private final FlowPanel main;
  private SimplePanel current;
  private SimplePanel next;

  public ViewSite() {
    main = new FlowPanel();
    initWidget(main);
  }

  /** Get the current view; null if there is no view being displayed. */
  @SuppressWarnings("unchecked")
  public V getView() {
    return current != null ? (V) current.getWidget() : null;
  }

  /**
   * Set the next view to display.
   *
   *
The view will be attached to the DOM tree within a hidden container, permitting its {@code
   * onLoad()} method to execute and update the DOM without the user seeing the result.
   *
   * @param view the next view to display.
   */
  public void setView(V view) {
    if (next != null) {
      main.remove(next);
    }
    view.site = this;
    next = new SimplePanel();
    next.setVisible(false);
    main.add(next);
    next.add(view);
  }

  /**
   * Invoked after the view becomes the current view and has been made visible.
   *
   * @param view the view being displayed.
   */
  protected void onShowView(V view) {}

  @SuppressWarnings("unchecked")
  final void swap(View v) {
    if (next != null && next.getWidget() == v) {
      if (current != null) {
        main.remove(current);
      }
      current = next;
      next = null;
      current.setVisible(true);
      onShowView((V) v);
    }
  }
}


text:
package be.degreyt.mmdoc.datamodel.impl;

import be.degreyt.mmdoc.datamodel.*;

import java.net.URL;
import java.util.Set;

/**
 * Created by WDH on 09/03/14.
 */
public class EventImpl extends AbstractCard implements Event {
    public EventImpl(String identification, Faction faction, String name, Rarity rarity, String description, URL smallImageUrl, URL largeImageUrl, Set<ExpansionInfo> expansionInfos) {
        super(identification, faction, name, rarity, description, expansionInfos);
    }

    @Override
    public CardType getCardType() {
        return CardType.EVENT;
    }

}


text:
import pytest
from django.conf import global_settings
from django.test import Client, TestCase, override_settings
from django.urls import reverse

pytestmark = pytest.mark.django_db

@override_settings(STATICFILES_STORAGE=global_settings.STATICFILES_STORAGE)
class SmokeTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test__home_url__GET(self):
        # SETUP

        # TEST
        response = self.client.get(reverse("home"), follow=True)

        # CHECK
        self.assertEqual(response.status_code, 200)

@pytest.mark.parametrize(
    "test_in, result",
    [
        ("t", True),
        ("f", False),
        ("true", True),
        ("false", False),
        ("1", "1"),
        ("foo", "foo"),
    ],
)
def test_settingspy_env_var(monkeypatch, test_in, result):
    monkeypatch.setenv("TEST_VAR", test_in)
    from chipy_org import settings  # pylint: disable=import-outside-toplevel

    assert settings.env_var("TEST_VAR") == result

@pytest.mark.parametrize(
    "test_in, result",
    [
        ("", []),
        ("f@e.com", ["f@e.com"]),
        ("f@e.com,b@e.com", ["f@e.com", "b@e.com"]),
    ],
)
def test_settingspy_env_list(monkeypatch, test_in, result):
    monkeypatch.setenv("TEST_VAR", test_in)
    from chipy_org import settings  # pylint: disable=import-outside-toplevel

    assert settings.env_list("TEST_VAR") == result

@override_settings(STATICFILES_STORAGE=global_settings.STATICFILES_STORAGE)
def test_logout_redirects_to_home(client):
    response = client.post("/logout/", follow=True)
    assert response.status_code == 200
    assert response.request["PATH_INFO"] == "/"


text:
import * as React from 'react';
import Todo from './todo';

export default class Todos extends React.Component<{ source: string }, { items: string[] }> {

    constructor(props: { source: string }) {
        super(props);
        this.state = { items: ['Apple', 'Banana', 'Cranberry', 'Apple1', 'Banana2', 'Cranberry3'] };
    }

    handleClick = (index) => {
        let items = this.state.items.filter((item, i) => {
            return index !== i;
        });
        this.setState({ items: items }, () => {
            if (items.length === 1) {
                let item = this.refs["item0"] as Todo;
                item.animate();
            }
        });
    }

    render() {
        return (
            <div>
                {this.state.items.map((item, i) => {
                    let boundClick = this.handleClick.bind(this, i);
                    return (
                        <Todo onClick={() => this.handleClick(i) } key={i} title={item} ref={'item' + i} />
                    );
                }, this) }
            </div>
        );
    }
}


text:
> Style guide for [Git][git].

## Commits

All commits should follow the [seven rules][git-seven-rules] of a [Git][git] commit message:

1.  Use the [imperative mood][imperative-mood] in the [Git][git] commit subject line.

    ```text
    # Do not...
    Fixed Markdown lint errors
    ```

    ```text
    # Do...
    Fix Markdown lint errors
    ```

2.  Capitalize the first word of the subject line.

    ```text
    # Do not...
    fix Markdown lint errors
    ```

    ```text
    # Do...
    Fix Markdown lint errors
    ```

3.  Do **not** end the subject line with a period.

    ```text
    # Do not...
    Fix Markdown lint errors.
    ```

    ```text
    # Do...
    Fix Markdown lint errors
    ```

4.  Separate the subject line from the body with a blank line.

    ```text
    # Do not...
    This is the subject line
    This is the body body body body body body body body body body body body
    body body body body body body body body body body body body body body
    ```

    ```text
    # Do...
    This is the subject line

    This is the body body body body body body body body body body body body
    body body body body body body body body body body body body body body
    ```

5.  Try to limit the subject line to `50` characters.

    ```text
    # Do not...
    This is the subject line line line line line line line line line line line line line line
    ```

    ```text
    # Do...
    This is the subject line
    ```

6.  Use the body to explain the _what_ and _why_, and not the _how_.

    ```text
    # Do not...
    Change Markdown heading style

    Update various Markdown files to stop lint errors. Change the heading
    style from `===` to `#`.
    ```

    ```text
    # Do...
    Change Markdown heading style

    Change the heading style to ensure consistency with `remark` output.
    This ensures that all Markdown files are all of the same style, thus
    reducing the number of edge cases Markdown parsers need to consider.
    ```

7.  Try to wrap the body at `72` characters.

    ```text
    # Do not...
    This is the subject line

    This is the body body body body body body body body body body body body body body body body body body body body body body body body body body
    ```

    ```text
    # Do...
    This is the subject line

    This is the body body body body body body body body body body body body
    body body body body body body body body body body body body body body
    ```

* * *

## Branching

This project follows the branching model articulated in ["A successful Git branching model"][git-flow].

### Master

-   The `master` branch is **protected**.

-   The `master` branch should **only** include source code which is stable, tested, and peer reviewed. In short, the source code should **always** reflect a "production-ready" state.

-   Each commit on the `master` branch should have an associated tag.

    ```bash
    $ git tag -a 2.0.0
    $ git push origin --tags
    ```

### Develop

-   The `develop` branch is **protected**.
-   The `develop` branch should **only** include code which is tested, peer reviewed, and passes continuous integration tests.
-   The source code should **always** reflect the latest development changes for the **next** release.

### Features

-   A feature branch should use the naming convention: `feature/<name>`.

-   A feature branch should branch from the `develop` branch.

    ```bash
    $ git checkout -b feature/<name> develop
    ```

-   Once a feature is complete, [squash][git-squash] commits into a single commit.

-   In order to merge a feature branch into the `develop` branch, submit a pull request against the `develop` branch.

-   Before merging a feature branch into the `develop` branch, the source code **must** be peer reviewed and pass continuous integration tests.

### Releases

-   A release branch should use the naming convention: `release-<major>.<minor>.<patch>`.

-   The release number should follow [semantic versioning][semver].

-   A release branch should branch from the `develop` branch.

    ```bash
    $ git checkout -b release-2.0.0 develop
    ```

-   Active development should **not** occur on a release branch. A release branch is a preparation branch (vetting, testing, updating meta data, et cetera) before merging into the `master` branch.

-   Once a release branch is complete, submit a pull request against the `master` branch.

-   Before merging the release branch into the `master` branch, the changes **must** be peer reviewed and pass continuous integration tests.

-   Once merged into `master`, submit a pull request against the `develop` branch to retain the changes made in the release branch.

### Hotfixes

-   A hotfix branch should use the naming convention: `hotfix/<name>`.

-   The purpose of a hotfix branch is to immediately patch a bug on the `master` branch. Accordingly, a hotfix branch should branch from the `master` branch.

    ```bash
    $ git checkout -b hotfix/<name> master
    ```

-   The hotfix branch should increment the ["patch"][semver] version number.

-   Once a hotfix is complete, [squash][git-squash] commits into a single commit.

-   Submit a pull request against the `master` branch.

-   Before merging a hotfix branch into the `master` branch, the changes **must** be peer reviewed and pass continuous integration tests.

-   Once merged into `master`, if a release branch currently exists, submit a pull request against the `release` branch. Otherwise, submit a pull request against the `develop` branch. By merging a hotfix into a release branch, the hotfix changes should be propagated to the `develop` branch upon merging the release branch into the `develop` branch.

* * *

## Pull Requests

-   All feature pull requests should be [rebased][git-rebase] against the latest `develop` branch.
-   All feature pull requests should be submitted against the `develop` branch.

* * *

## License

This document may be reused under a [Creative Commons Attribution-ShareAlike License][license].

<section class="links">

[git]: https://git-scm.com/

[git-rebase]: https://git-scm.com/docs/git-rebase

[git-squash]: https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Squashing-Commits

[git-seven-rules]: http://chris.beams.io/posts/git-commit/

[imperative-mood]: https://en.wikipedia.org/wiki/Imperative_mood

[git-flow]: http://nvie.com/posts/a-successful-git-branching-model/

[semver]: http://semver.org/

[license]: https://creativecommons.org/licenses/by-sa/4.0/

</section>

<!-- /.links -->


text:
namespace ppapi {
namespace proxy {

PpapiCommandBufferProxy::PpapiCommandBufferProxy(
    const ppapi::HostResource& resource,
    ProxyChannel* channel)
    : resource_(resource),
      channel_(channel) {
}

PpapiCommandBufferProxy::~PpapiCommandBufferProxy() {
  // gpu::Buffers are no longer referenced, allowing shared memory objects to be
  // deleted, closing the handle in this process.
}

bool PpapiCommandBufferProxy::Initialize() {
  return true;
}

gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() {
  ppapi::ProxyLock::AssertAcquiredDebugOnly();
  return last_state_;
}

int32 PpapiCommandBufferProxy::GetLastToken() {
  ppapi::ProxyLock::AssertAcquiredDebugOnly();
  return last_state_.token;
}

void PpapiCommandBufferProxy::Flush(int32 put_offset) {
  if (last_state_.error != gpu::error::kNoError)
    return;

  IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush(
      ppapi::API_ID_PPB_GRAPHICS_3D, resource_, put_offset);

  // Do not let a synchronous flush hold up this message. If this handler is
  // deferred until after the synchronous flush completes, it will overwrite the
  // cached last_state_ with out-of-date data.
  message->set_unblock(true);
  Send(message);
}

void PpapiCommandBufferProxy::WaitForTokenInRange(int32 start, int32 end) {
  if (last_state_.error != gpu::error::kNoError)
    return;

  bool success = false;
  gpu::CommandBuffer::State state;
  if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForTokenInRange(
          ppapi::API_ID_PPB_GRAPHICS_3D,
          resource_,
          start,
          end,
          &state,
          &success)))
    UpdateState(state, success);
}

void PpapiCommandBufferProxy::WaitForGetOffsetInRange(int32 start, int32 end) {
  if (last_state_.error != gpu::error::kNoError)
    return;

  bool success = false;
  gpu::CommandBuffer::State state;
  if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForGetOffsetInRange(
          ppapi::API_ID_PPB_GRAPHICS_3D,
          resource_,
          start,
          end,
          &state,
          &success)))
    UpdateState(state, success);
}

void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) {
  if (last_state_.error == gpu::error::kNoError) {
    Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer(
         ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id));
  }
}

scoped_refptr<gpu::Buffer> PpapiCommandBufferProxy::CreateTransferBuffer(
    size_t size,
    int32* id) {
  *id = -1;

  if (last_state_.error != gpu::error::kNoError)
    return NULL;

  // Assuming we are in the renderer process, the service is responsible for
  // duplicating the handle. This might not be true for NaCl.
  ppapi::proxy::SerializedHandle handle(
      ppapi::proxy::SerializedHandle::SHARED_MEMORY);
  if (!Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer(
            ppapi::API_ID_PPB_GRAPHICS_3D, resource_, size, id, &handle))) {
    return NULL;
  }

  if (*id <= 0 || !handle.is_shmem())
    return NULL;

  scoped_ptr<base::SharedMemory> shared_memory(
      new base::SharedMemory(handle.shmem(), false));

  // Map the shared memory on demand.
  if (!shared_memory->memory()) {
    if (!shared_memory->Map(handle.size())) {
      *id = -1;
      return NULL;
    }
  }

  return gpu::MakeBufferFromSharedMemory(shared_memory.Pass(), handle.size());
}

void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) {
  if (last_state_.error != gpu::error::kNoError)
    return;

  Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer(
      ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id));
}

void PpapiCommandBufferProxy::Echo(const base::Closure& callback) {
  NOTREACHED();
}

uint32 PpapiCommandBufferProxy::CreateStreamTexture(uint32 texture_id) {
  NOTREACHED();
  return 0;
}

uint32 PpapiCommandBufferProxy::InsertSyncPoint() {
  uint32 sync_point = 0;
  if (last_state_.error == gpu::error::kNoError) {
    Send(new PpapiHostMsg_PPBGraphics3D_InsertSyncPoint(
         ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point));
  }
  return sync_point;
}

uint32 PpapiCommandBufferProxy::InsertFutureSyncPoint() {
  uint32 sync_point = 0;
  if (last_state_.error == gpu::error::kNoError) {
    Send(new PpapiHostMsg_PPBGraphics3D_InsertFutureSyncPoint(
        ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point));
  }
  return sync_point;
}

void PpapiCommandBufferProxy::RetireSyncPoint(uint32 sync_point) {
  if (last_state_.error == gpu::error::kNoError) {
    Send(new PpapiHostMsg_PPBGraphics3D_RetireSyncPoint(
        ppapi::API_ID_PPB_GRAPHICS_3D, resource_, sync_point));
  }
}

void PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point,
                                              const base::Closure& callback) {
  NOTREACHED();
}

void PpapiCommandBufferProxy::SignalQuery(uint32 query,
                                          const base::Closure& callback) {
  NOTREACHED();
}

void PpapiCommandBufferProxy::SetSurfaceVisible(bool visible) {
  NOTREACHED();
}

gpu::Capabilities PpapiCommandBufferProxy::GetCapabilities() {
  // TODO(boliu): Need to implement this to use cc in Pepper. Tracked in
  // crbug.com/325391.
  return gpu::Capabilities();
}

gfx::GpuMemoryBuffer* PpapiCommandBufferProxy::CreateGpuMemoryBuffer(
    size_t width,
    size_t height,
    unsigned internalformat,
    unsigned usage,
    int32* id) {
  NOTREACHED();
  return NULL;
}

void PpapiCommandBufferProxy::DestroyGpuMemoryBuffer(int32 id) {
  NOTREACHED();
}

bool PpapiCommandBufferProxy::Send(IPC::Message* msg) {
  DCHECK(last_state_.error == gpu::error::kNoError);

  if (channel_->Send(msg))
    return true;

  last_state_.error = gpu::error::kLostContext;
  return false;
}

void PpapiCommandBufferProxy::UpdateState(
    const gpu::CommandBuffer::State& state,
    bool success) {
  // Handle wraparound. It works as long as we don't have more than 2B state
  // updates in flight across which reordering occurs.
  if (success) {
    if (state.generation - last_state_.generation < 0x80000000U) {
      last_state_ = state;
    }
  } else {
    last_state_.error = gpu::error::kLostContext;
    ++last_state_.generation;
  }
}

}  // namespace proxy
}  // namespace ppapi


text:
layout: post
title: How to Convert a PDF file to text in Java
subtitle: Using the WhatsMate PDF-to-Text REST API
published: true
last_modified_at: 2022-05-03T00:00:00+08:00
---

This article shows you how to extract text from an online PDF document in `Java`.

Here's how:

1. Copy the following source code to a Java file named `SyncPdfTextExtractor.java`.
2. Specify the URL of your online PDF document on line 20.
3. Replace the Client ID and Secret on lines 10 and 11 if you have your own credentials.
4. Compile the Java file: `javac SyncPdfTextExtractor.java`
5. Execute the class to see the extracted text: `java SyncPdfTextExtractor`

If your PDF file is larger than 1 MB, you will need to call the asynchronous API instead. See an example in Java.

The trial account only allows you to call the PDF-to-Text API up to 20 times for learning purpose. [Upgrade to a Premium plan](https://www.whatsmate.net/pdf-api-subscribe.html) to use the API seriously.

Want to extract PDF text in another programming language? Check out the [PDF-to-Text API](https://www.whatsmate.net/pdf-to-text-api.html) page.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Intercom.Clients;
using Intercom.Converters.ClassConverters;
using Intercom.Core;
using Intercom.Data;
using Intercom.Exceptions;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
using RestSharp;
using RestSharp.Authenticators;

namespace Intercom.Test
{
    [TestFixture()]
    public class UserCountJsonConverterTest : TestBase
    {
        private UserCountJsonConverter userCountJsonConverter;

        public UserCountJsonConverterTest()
        {
            this.userCountJsonConverter = new UserCountJsonConverter();
        }

        [Test()]
        public void ReadJson_ForUserSegment_ReturnsValidCount()
        {
            String input = "{\"type\":\"count\",\"user\":{\"segment\":[{\"Active\":2},{\"New\":0},{\"P1 Test\":0},{\"Slipping Away\":0}]}}";
            StringReader stringReader = new StringReader(input);
            JsonReader reader = new JsonTextReader(stringReader);
            UserSegmentCount userSegmentCount =
                userCountJsonConverter.ReadJson(reader, typeof(UserSegmentCount), null, null) as UserSegmentCount;

            Assert.IsNotNull(userSegmentCount);
            Assert.AreEqual( 4, userSegmentCount.segments.Count);
            Assert.AreEqual(2, userSegmentCount.segments["Active"]);
        }

        [Test()]
        public void ReadJson_ForUserTag_ReturnsValidCount()
        {
            String input = "{\"type\":\"count\",\"user\":{\"tag\":[{\"automated-tag\":0},{\"has_device_token\":1001},{\"Tag 1\":1},{\"test_user_tagged\":2}]}}";
            StringReader stringReader = new StringReader(input);
            JsonReader reader = new JsonTextReader(stringReader);
            UserTagCount userTagCount =
                userCountJsonConverter.ReadJson(reader, typeof(UserTagCount), null, null) as UserTagCount;

            Assert.IsNotNull(userTagCount);
            Assert.AreEqual(4, userTagCount.tags.Count);
            Assert.IsTrue(userTagCount.tags.Any(c => c.Key == "has_device_token" && c.Value == 1001));
        }

        [Test()]
        public void ReadJson_InvalidJson_ThrowsException()
        {
            String input = "{\"type\":\"count\",\"usted-tag\":0},{\"has_device_token\":1001},{\"Tag 1\":1},{\"test_user_tagged\":2}]}}";
            StringReader stringReader = new StringReader(input);
            JsonReader reader = new JsonTextReader(stringReader);

            Assert.Throws<JsonConverterException>(() =>
            {
                userCountJsonConverter.ReadJson(reader, typeof(UserTagCount), null, null);
            });
        }
    }
}


text:
namespace Mata.Test
{
    using System;

    public class TestModel
    {
        public string StringProperty { get; set; }

        public bool BoolProperty { get; set; }

        public byte ByteProperty { get; set; }

        public short ShortProperty { get; set; }

        public int IntProperty { get; set; }

        public long LongProperty { get; set; }

        public char CharProperty { get; set; }

        public DateTime DateTimeProperty { get; set; }

        public decimal DecimalProperty { get; set; }

        public float FloatProperty { get; set; }

        public double DoubleProperty { get; set; }

        public Guid GuidProperty { get; set; }

        public bool? NullableBoolProperty { get; set; }

        public byte? NullableByteProperty { get; set; }

        public short? NullableShortProperty { get; set; }

        public int? NullableIntProperty { get; set; }

        public long? NullableLongProperty { get; set; }

        public char? NullableCharProperty { get; set; }

        public DateTime? NullableDateTimeProperty { get; set; }

        public decimal? NullableDecimalProperty { get; set; }

        public float? NullableFloatProperty { get; set; }

        public double? NullableDoubleProperty { get; set; }

        public Guid? NullableGuidProperty { get; set; }

        public DateTimeOffset DateTimeOffsetProperty { get; set; }

        public DateTimeOffset? NullableDateTimeOffsetProperty { get; set; }
    }
}


text:
/*************************************************************************/
/*  camera_2d.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "camera_2d.h"
#include "core/math/math_funcs.h"
#include "scene/scene_string_names.h"
#include "servers/visual_server.h"
#include <editor/editor_node.h>

void Camera2D::_update_scroll() {

	if (!is_inside_tree())
		return;

	if (get_tree()->is_editor_hint()) {
		update(); //will just be drawn
		return;
	}

	if (current) {

		ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));

		Transform2D xform = get_camera_transform();

		if (viewport) {
			viewport->set_canvas_transform(xform);
		}
		get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_camera_moved", xform);
	};
}

void Camera2D::set_zoom(const Vector2 &p_zoom) {

	zoom = p_zoom;
	Point2 old_smoothed_camera_pos = smoothed_camera_pos;
	_update_scroll();
	smoothed_camera_pos = old_smoothed_camera_pos;
};

Vector2 Camera2D::get_zoom() const {

	return zoom;
};

Transform2D Camera2D::get_camera_transform() {

	if (!get_tree())
		return Transform2D();

	ERR_FAIL_COND_V(custom_viewport && !ObjectDB::get_instance(custom_viewport_id), Transform2D());

	Size2 screen_size = viewport->get_visible_rect().size;

	Point2 new_camera_pos = get_global_transform().get_origin();
	Point2 ret_camera_pos;

	if (!first) {

		if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) {

			if (h_drag_enabled && !get_tree()->is_editor_hint()) {
				camera_pos.x = MIN(camera_pos.x, (new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT]));
				camera_pos.x = MAX(camera_pos.x, (new_camera_pos.x - screen_size.x * 0.5 * drag_margin[MARGIN_LEFT]));
			} else {

				if (h_ofs < 0) {
					camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs;
				} else {
					camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs;
				}
			}

			if (v_drag_enabled && !get_tree()->is_editor_hint()) {

				camera_pos.y = MIN(camera_pos.y, (new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM]));
				camera_pos.y = MAX(camera_pos.y, (new_camera_pos.y - screen_size.y * 0.5 * drag_margin[MARGIN_TOP]));

			} else {

				if (v_ofs < 0) {
					camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs;
				} else {
					camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs;
				}
			}

		} else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) {

			camera_pos = new_camera_pos;
		}

		Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());
		Rect2 screen_rect(-screen_offset + camera_pos, screen_size * zoom);

		if (offset != Vector2())
			screen_rect.position += offset;

		if (limit_smoothing_enabled) {
			if (screen_rect.position.x < limit[MARGIN_LEFT])
				camera_pos.x -= screen_rect.position.x - limit[MARGIN_LEFT];

			if (screen_rect.position.x + screen_rect.size.x > limit[MARGIN_RIGHT])
				camera_pos.x -= screen_rect.position.x + screen_rect.size.x - limit[MARGIN_RIGHT];

			if (screen_rect.position.y + screen_rect.size.y > limit[MARGIN_BOTTOM])
				camera_pos.y -= screen_rect.position.y + screen_rect.size.y - limit[MARGIN_BOTTOM];

			if (screen_rect.position.y < limit[MARGIN_TOP])
				camera_pos.y -= screen_rect.position.y - limit[MARGIN_TOP];
		}

		if (smoothing_enabled && !get_tree()->is_editor_hint()) {

			float c = smoothing * get_fixed_process_delta_time();
			smoothed_camera_pos = ((camera_pos - smoothed_camera_pos) * c) + smoothed_camera_pos;
			ret_camera_pos = smoothed_camera_pos;
			//camera_pos=camera_pos*(1.0-smoothing)+new_camera_pos*smoothing;
		} else {

			ret_camera_pos = smoothed_camera_pos = camera_pos;
		}

	} else {
		ret_camera_pos = smoothed_camera_pos = camera_pos = new_camera_pos;
		first = false;
	}

	Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());

	float angle = get_global_transform().get_rotation();
	if (rotating) {
		screen_offset = screen_offset.rotated(angle);
	}

	Rect2 screen_rect(-screen_offset + ret_camera_pos, screen_size * zoom);
	if (screen_rect.position.x < limit[MARGIN_LEFT])
		screen_rect.position.x = limit[MARGIN_LEFT];

	if (screen_rect.position.x + screen_rect.size.x > limit[MARGIN_RIGHT])
		screen_rect.position.x = limit[MARGIN_RIGHT] - screen_rect.size.x;

	if (screen_rect.position.y + screen_rect.size.y > limit[MARGIN_BOTTOM])
		screen_rect.position.y = limit[MARGIN_BOTTOM] - screen_rect.size.y;

	if (screen_rect.position.y < limit[MARGIN_TOP])
		screen_rect.position.y = limit[MARGIN_TOP];

	if (offset != Vector2()) {

		screen_rect.position += offset;
		if (screen_rect.position.x + screen_rect.size.x > limit[MARGIN_RIGHT])
			screen_rect.position.x = limit[MARGIN_RIGHT] - screen_rect.size.x;

		if (screen_rect.position.y + screen_rect.size.y > limit[MARGIN_BOTTOM])
			screen_rect.position.y = limit[MARGIN_BOTTOM] - screen_rect.size.y;

		if (screen_rect.position.x < limit[MARGIN_LEFT])
			screen_rect.position.x = limit[MARGIN_LEFT];

		if (screen_rect.position.y < limit[MARGIN_TOP])
			screen_rect.position.y = limit[MARGIN_TOP];
	}

	camera_screen_center = screen_rect.position + screen_rect.size * 0.5;

	Transform2D xform;
	if (rotating) {
		xform.set_rotation(angle);
	}
	xform.scale_basis(zoom);
	xform.set_origin(screen_rect.position /*.floor()*/);

	/*
	if (0) {

		xform = get_global_transform() * xform;
	} else {

		xform.elements[2]+=get_global_transform().get_origin();
	}
*/

	return (xform).affine_inverse();
}

void Camera2D::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_FIXED_PROCESS: {

			_update_scroll();

		} break;
		case NOTIFICATION_TRANSFORM_CHANGED: {

			if (!is_fixed_processing())
				_update_scroll();

		} break;
		case NOTIFICATION_ENTER_TREE: {

			if (custom_viewport && ObjectDB::get_instance(custom_viewport_id)) {
				viewport = custom_viewport;
			} else {
				viewport = get_viewport();
			}

			canvas = get_canvas();

			RID vp = viewport->get_viewport_rid();

			group_name = "__cameras_" + itos(vp.get_id());
			canvas_group_name = "__cameras_c" + itos(canvas.get_id());
			add_to_group(group_name);
			add_to_group(canvas_group_name);

			if (get_tree()->is_editor_hint()) {
				set_fixed_process(false);
			}

			_update_scroll();
			first = true;

		} break;
		case NOTIFICATION_EXIT_TREE: {

			if (is_current()) {
				if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) {
					viewport->set_canvas_transform(Transform2D());
				}
			}
			remove_from_group(group_name);
			remove_from_group(canvas_group_name);
			viewport = NULL;

		} break;
		case NOTIFICATION_DRAW: {

			if (!is_inside_tree() || !get_tree()->is_editor_hint())
				break;

			Color area_axis_color(0.5, 0.42, 0.87, 0.63);
			float area_axis_width = 1;
			if (current)
				area_axis_width = 3;

			Transform2D inv_camera_transform = get_camera_transform().affine_inverse();
			Size2 screen_size = get_viewport_rect().size;

			Vector2 screen_endpoints[4] = {
				inv_camera_transform.xform(Vector2(0, 0)),
				inv_camera_transform.xform(Vector2(screen_size.width, 0)),
				inv_camera_transform.xform(Vector2(screen_size.width, screen_size.height)),
				inv_camera_transform.xform(Vector2(0, screen_size.height))
			};

			Transform2D inv_transform = get_global_transform().affine_inverse(); // undo global space

			for (int i = 0; i < 4; i++) {
				draw_line(inv_transform.xform(screen_endpoints[i]), inv_transform.xform(screen_endpoints[(i + 1) % 4]), area_axis_color, area_axis_width);
			}

		} break;
	}
}

void Camera2D::set_offset(const Vector2 &p_offset) {

	offset = p_offset;
	_update_scroll();
}

Vector2 Camera2D::get_offset() const {

	return offset;
}

void Camera2D::set_anchor_mode(AnchorMode p_anchor_mode) {

	anchor_mode = p_anchor_mode;
	_update_scroll();
}

Camera2D::AnchorMode Camera2D::get_anchor_mode() const {

	return anchor_mode;
}

void Camera2D::set_rotating(bool p_rotating) {

	rotating = p_rotating;
	_update_scroll();
}

bool Camera2D::is_rotating() const {

	return rotating;
}

void Camera2D::_make_current(Object *p_which) {

	if (p_which == this) {

		current = true;
		_update_scroll();
	} else {
		current = false;
	}
}

void Camera2D::_set_current(bool p_current) {

	if (p_current)
		make_current();

	current = p_current;
}

bool Camera2D::is_current() const {

	return current;
}

void Camera2D::make_current() {

	if (!is_inside_tree()) {
		current = true;
	} else {
		get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", this);
	}
}

void Camera2D::clear_current() {

	current = false;
	if (is_inside_tree()) {
		get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", (Object *)(NULL));
	}
}

void Camera2D::set_limit(Margin p_margin, int p_limit) {

	ERR_FAIL_INDEX(p_margin, 4);
	limit[p_margin] = p_limit;
}

int Camera2D::get_limit(Margin p_margin) const {

	ERR_FAIL_INDEX_V(p_margin, 4, 0);
	return limit[p_margin];
}

void Camera2D::set_limit_smoothing_enabled(bool enable) {

	limit_smoothing_enabled = enable;
	_update_scroll();
}

bool Camera2D::is_limit_smoothing_enabled() const {

	return limit_smoothing_enabled;
}

void Camera2D::set_drag_margin(Margin p_margin, float p_drag_margin) {

	ERR_FAIL_INDEX(p_margin, 4);
	drag_margin[p_margin] = p_drag_margin;
}

float Camera2D::get_drag_margin(Margin p_margin) const {

	ERR_FAIL_INDEX_V(p_margin, 4, 0);
	return drag_margin[p_margin];
}

Vector2 Camera2D::get_camera_pos() const {

	return camera_pos;
}

void Camera2D::force_update_scroll() {

	_update_scroll();
}

void Camera2D::reset_smoothing() {

	smoothed_camera_pos = camera_pos;
	_update_scroll();
}

void Camera2D::align() {

	ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));

	Size2 screen_size = viewport->get_visible_rect().size;

	Point2 current_camera_pos = get_global_transform().get_origin();
	if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) {
		if (h_ofs < 0) {
			camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs;
		} else {
			camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs;
		}
		if (v_ofs < 0) {
			camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs;
		} else {
			camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs;
		}
	} else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) {

		camera_pos = current_camera_pos;
	}

	_update_scroll();
}

void Camera2D::set_follow_smoothing(float p_speed) {

	smoothing = p_speed;
	if (smoothing > 0 && !(is_inside_tree() && get_tree()->is_editor_hint()))
		set_fixed_process(true);
	else
		set_fixed_process(false);
}

float Camera2D::get_follow_smoothing() const {

	return smoothing;
}

Point2 Camera2D::get_camera_screen_center() const {

	return camera_screen_center;
}

void Camera2D::set_h_drag_enabled(bool p_enabled) {

	h_drag_enabled = p_enabled;
}

bool Camera2D::is_h_drag_enabled() const {

	return h_drag_enabled;
}

void Camera2D::set_v_drag_enabled(bool p_enabled) {

	v_drag_enabled = p_enabled;
}

bool Camera2D::is_v_drag_enabled() const {

	return v_drag_enabled;
}

void Camera2D::set_v_offset(float p_offset) {

	v_ofs = p_offset;
}

float Camera2D::get_v_offset() const {

	return v_ofs;
}

void Camera2D::set_h_offset(float p_offset) {

	h_ofs = p_offset;
}
float Camera2D::get_h_offset() const {

	return h_ofs;
}

void Camera2D::_set_old_smoothing(float p_val) {
	//compatibility
	if (p_val > 0) {
		smoothing_enabled = true;
		set_follow_smoothing(p_val);
	}
}

void Camera2D::set_enable_follow_smoothing(bool p_enabled) {

	smoothing_enabled = p_enabled;
}

bool Camera2D::is_follow_smoothing_enabled() const {

	return smoothing_enabled;
}

void Camera2D::set_custom_viewport(Node *p_viewport) {
	ERR_FAIL_NULL(p_viewport);
	if (is_inside_tree()) {
		remove_from_group(group_name);
		remove_from_group(canvas_group_name);
	}

	custom_viewport = p_viewport->cast_to<Viewport>();

	if (custom_viewport) {
		custom_viewport_id = custom_viewport->get_instance_ID();
	} else {
		custom_viewport_id = 0;
	}

	if (is_inside_tree()) {

		if (custom_viewport)
			viewport = custom_viewport;
		else
			viewport = get_viewport();

		RID vp = viewport->get_viewport_rid();
		group_name = "__cameras_" + itos(vp.get_id());
		canvas_group_name = "__cameras_c" + itos(canvas.get_id());
		add_to_group(group_name);
		add_to_group(canvas_group_name);
	}
}

Node *Camera2D::get_custom_viewport() const {

	return custom_viewport;
}

void Camera2D::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Camera2D::set_offset);
	ClassDB::bind_method(D_METHOD("get_offset"), &Camera2D::get_offset);

	ClassDB::bind_method(D_METHOD("set_anchor_mode", "anchor_mode"), &Camera2D::set_anchor_mode);
	ClassDB::bind_method(D_METHOD("get_anchor_mode"), &Camera2D::get_anchor_mode);

	ClassDB::bind_method(D_METHOD("set_rotating", "rotating"), &Camera2D::set_rotating);
	ClassDB::bind_method(D_METHOD("is_rotating"), &Camera2D::is_rotating);

	ClassDB::bind_method(D_METHOD("make_current"), &Camera2D::make_current);
	ClassDB::bind_method(D_METHOD("clear_current"), &Camera2D::clear_current);
	ClassDB::bind_method(D_METHOD("_make_current"), &Camera2D::_make_current);

	ClassDB::bind_method(D_METHOD("_update_scroll"), &Camera2D::_update_scroll);

	ClassDB::bind_method(D_METHOD("_set_current", "current"), &Camera2D::_set_current);
	ClassDB::bind_method(D_METHOD("is_current"), &Camera2D::is_current);

	ClassDB::bind_method(D_METHOD("set_limit", "margin", "limit"), &Camera2D::set_limit);
	ClassDB::bind_method(D_METHOD("get_limit", "margin"), &Camera2D::get_limit);

	ClassDB::bind_method(D_METHOD("set_limit_smoothing_enabled", "limit_smoothing_enabled"), &Camera2D::set_limit_smoothing_enabled);
	ClassDB::bind_method(D_METHOD("is_limit_smoothing_enabled"), &Camera2D::is_limit_smoothing_enabled);

	ClassDB::bind_method(D_METHOD("set_v_drag_enabled", "enabled"), &Camera2D::set_v_drag_enabled);
	ClassDB::bind_method(D_METHOD("is_v_drag_enabled"), &Camera2D::is_v_drag_enabled);

	ClassDB::bind_method(D_METHOD("set_h_drag_enabled", "enabled"), &Camera2D::set_h_drag_enabled);
	ClassDB::bind_method(D_METHOD("is_h_drag_enabled"), &Camera2D::is_h_drag_enabled);

	ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera2D::set_v_offset);
	ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera2D::get_v_offset);

	ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera2D::set_h_offset);
	ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera2D::get_h_offset);

	ClassDB::bind_method(D_METHOD("set_drag_margin", "margin", "drag_margin"), &Camera2D::set_drag_margin);
	ClassDB::bind_method(D_METHOD("get_drag_margin", "margin"), &Camera2D::get_drag_margin);

	ClassDB::bind_method(D_METHOD("get_camera_pos"), &Camera2D::get_camera_pos);
	ClassDB::bind_method(D_METHOD("get_camera_screen_center"), &Camera2D::get_camera_screen_center);

	ClassDB::bind_method(D_METHOD("set_zoom", "zoom"), &Camera2D::set_zoom);
	ClassDB::bind_method(D_METHOD("get_zoom"), &Camera2D::get_zoom);

	ClassDB::bind_method(D_METHOD("set_custom_viewport", "viewport:Viewport"), &Camera2D::set_custom_viewport);
	ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"), &Camera2D::get_custom_viewport);

	ClassDB::bind_method(D_METHOD("set_follow_smoothing", "follow_smoothing"), &Camera2D::set_follow_smoothing);
	ClassDB::bind_method(D_METHOD("get_follow_smoothing"), &Camera2D::get_follow_smoothing);

	ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing", "follow_smoothing"), &Camera2D::set_enable_follow_smoothing);
	ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"), &Camera2D::is_follow_smoothing_enabled);

	ClassDB::bind_method(D_METHOD("force_update_scroll"), &Camera2D::force_update_scroll);
	ClassDB::bind_method(D_METHOD("reset_smoothing"), &Camera2D::reset_smoothing);
	ClassDB::bind_method(D_METHOD("align"), &Camera2D::align);

	ClassDB::bind_method(D_METHOD("_set_old_smoothing", "follow_smoothing"), &Camera2D::_set_old_smoothing);

	ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "anchor_mode", PROPERTY_HINT_ENUM, "Fixed TopLeft,Drag Center"), "set_anchor_mode", "get_anchor_mode");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rotating"), "set_rotating", "is_rotating");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "_set_current", "is_current");
	ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "zoom"), "set_zoom", "get_zoom");

	ADD_GROUP("Limit", "limit_");
	ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_left"), "set_limit", "get_limit", MARGIN_LEFT);
	ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_top"), "set_limit", "get_limit", MARGIN_TOP);
	ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_right"), "set_limit", "get_limit", MARGIN_RIGHT);
	ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_bottom"), "set_limit", "get_limit", MARGIN_BOTTOM);
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "limit_smoothed"), "set_limit_smoothing_enabled", "is_limit_smoothing_enabled");

	ADD_GROUP("Draw Margin", "draw_margin_");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_h_enabled"), "set_h_drag_enabled", "is_h_drag_enabled");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_v_enabled"), "set_v_drag_enabled", "is_v_drag_enabled");

	ADD_GROUP("Smoothing", "smoothing_");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smoothing_enabled"), "set_enable_follow_smoothing", "is_follow_smoothing_enabled");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "smoothing_speed"), "set_follow_smoothing", "get_follow_smoothing");

	ADD_GROUP("Drag Margin", "drag_margin_");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_left", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_LEFT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_top", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_TOP);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_right", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_RIGHT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_bottom", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_BOTTOM);

	BIND_CONSTANT(ANCHOR_MODE_DRAG_CENTER);
	BIND_CONSTANT(ANCHOR_MODE_FIXED_TOP_LEFT);
}

Camera2D::Camera2D() {

	anchor_mode = ANCHOR_MODE_DRAG_CENTER;
	rotating = false;
	current = false;
	limit[MARGIN_LEFT] = -10000000;
	limit[MARGIN_TOP] = -10000000;
	limit[MARGIN_RIGHT] = 10000000;
	limit[MARGIN_BOTTOM] = 10000000;

	drag_margin[MARGIN_LEFT] = 0.2;
	drag_margin[MARGIN_TOP] = 0.2;
	drag_margin[MARGIN_RIGHT] = 0.2;
	drag_margin[MARGIN_BOTTOM] = 0.2;
	camera_pos = Vector2();
	first = true;
	smoothing_enabled = false;
	limit_smoothing_enabled = false;
	custom_viewport = NULL;
	custom_viewport_id = 0;

	smoothing = 5.0;
	zoom = Vector2(1, 1);

	h_drag_enabled = true;
	v_drag_enabled = true;
	h_ofs = 0;
	v_ofs = 0;
	set_notify_transform(true);
}


text:
<template>

</template>


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
V. L. Komarov, Fl. URSS 2:640. 1934

#### Original name
null

### Remarks
null


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**current_value** | **str** | currentValue is the current value of the metric (as a quantity). |
**metric_name** | **str** | metricName is the name of the metric in question. |
**target** | [**V2beta1CrossVersionObjectReference**](V2beta1CrossVersionObjectReference.md) | target is the described Kubernetes object. |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
$(document).ready(function () {
  $('.tweet-text').each(function() {
    var tweetHtml = $(this).html();
    var newTweetHtml = tweetHtml.replace('#ilovemercurial', '#ilovemercurial')
    $(this).html(newTweetHtml);
  });
});


text:
class Browser;
class Profile;

namespace base {
class CommandLine;
class FilePath;
}  // namespace base

namespace web_app {
namespace startup {

// Various ways web apps can open on Chrome launch.
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class OpenMode {
  // Launched app by any method other than through the command-line or from a
  // platform shortcut.
  kInWindowOther = 0,
  kInTab = 1,            // Launched as an installed web app in a browser tab.
  kUnknown = 2,          // The requested web app was not installed.
  kInWindowByUrl = 3,    // Launched the app by url with --app switch.
  kInWindowByAppId = 4,  // Launched app by id with --app-id switch.
  kMaxValue = kInWindowByAppId,
};

// Handles a launch for a `command_line` that includes --app-id. If the app id
// is invalid, it will fall back to launching a normal browser window. Will
// return true if the --app-id flag was found, otherwise false.
bool MaybeHandleWebAppLaunch(const base::CommandLine& command_line,
                             const base::FilePath& cur_dir,
                             Profile* profile,
                             chrome::startup::IsFirstRun is_first_run);

// Final handling after a web app has been launched.
void FinalizeWebAppLaunch(absl::optional<OpenMode> app_open_mode,
                          const base::CommandLine& command_line,
                          chrome::startup::IsFirstRun is_first_run,
                          Browser* browser,
                          apps::LaunchContainer container);

// `callback` will be run after the next `MaybeHandleWebAppLaunch()` invocation
// finishes executing.
void SetStartupDoneCallbackForTesting(base::OnceClosure callback);

}  // namespace startup
}  // namespace web_app

#endif  //  CHROME_BROWSER_UI_STARTUP_WEB_APP_STARTUP_UTILS_H_


text:
/**
 *
 */

/*
var app = app || {};

var AdminRouter = Backbone.Router.extend({
	initialize: function () {
		this.institucionCollection = new InstitucionEducativaCollection;
		this.cargoCollection = new CargoCollection;
		this.periodoAcademicoCollection = new PeriodoAcademicoCollection;
		this.nivelCollection = new NivelCollection;
		this.gradoCollection = new GradoCollection;
		this.seccionCollection = new SeccionCollection;
	},
	routes: {
		'institucioneducativa': 'institucioneducativa',
		'institucioneducativa/edit(/:id)': 'editinstitucioneducativa',
		'cargo': 'cargoIndex',
		'cargo/edit(/:id)': 'editcargo',
		'periodoacademico(/)': 'periodoacademicoIndex',
		'periodoacademico/edit(/:id)': 'editperiodoacademico',
		'estructuraie(/)': 'estructuraieIndex',
		'admin/planadocente(/)': 'planaDocente'
	},
	institucioneducativa: function () {
		var view = new InstitucionEducativaListView ({
			collection: this.institucionCollection,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.$el);
		//$('#workspace').empty().append(view.$el);
		view.collection.fetch({
			silent: true,
			success: function () {
				view.collection.trigger('add');
			}
		});
	},
	editinstitucioneducativa: function (id) {
		// try to get cached model
		var model = this.institucionCollection.get(id);
		if (id == null) model = new InstitucionEducativaModel ();
		if (typeof model == 'undefined') { // not cached
			model = new InstitucionEducativaModel ({
				idInstitucion: id
			});
		}
		var view = new InstitucionEducativaFormView ({
			model: model,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.render().$el);
		//$('#workspace').empty().append(view.render().$el);
		if (id != null) view.model.fetch();
	},
	cargoIndex: function () {
		var view = new CargoListView({
			collection: this.cargoCollection,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.$el);
		view.collection.fetch({
			silent: true,
			success: function () {
				view.collection.trigger('add');
			}
		});
	},
	editcargo: function (id) {
		// try to get cached model
		var model = this.cargoCollection.get(id);
		if (id == null) model = new CargoModel ();
		if (typeof model == 'undefined') { // not cached
			model = new CargoModel ({
				idCargo: id
			});
			this.cargoCollection.add(model);
		}
		var view = new CargoFormView({
			model: model,
			collection: this.cargoCollection,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.render().$el);
		if (id != null) view.model.fetch();
	},
	periodoacademicoIndex: function () {
		var view = new PeriodoAcademicoListView({
			collection: this.periodoAcademicoCollection,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.$el);
		view.collection.fetch({
			silent: true,
			success: function () {
				view.collection.trigger('add');
			}
		});
	},
	editperiodoacademico: function (id) {
		// try to get cached model
		var model = this.periodoAcademicoCollection.get(id);
		if (id == null) model = new PeriodoAcademicoModel ();
		if (typeof model == 'undefined') { // not cached
			model = new PeriodoAcademicoModel ({
				idCargo: id
			});
			this.periodoAcademicoCollection.add(model);
		}
		var view = new PeriodoAcademicoFormView({
			model: model,
			collection: this.periodoAcademicoCollection,
			router: this
		});
		app.workspace.getWorkspaceArea().empty().append(view.render().$el);
		if (id != null) view.model.fetch();
	},
	estructuraieIndex: function () {
		console.log(this.gradoCollection);
		var view = new EstructuraInstitucionEducativaView({
			collection: this.nivelCollection,
			router: this,
			institucionCollection: this.institucionCollection,
			gradoCollection: this.gradoCollection,
			seccionCollection: this.seccionCollection
		});
		app.workspace.getWorkspaceArea().empty().append(view.$el);
		view.collection.fetch({
			silent: true,
			success: function () {
				view.collection.trigger('add');
			}
		});
		view.options.institucionCollection.fetch({
			silent: true,
			success: function () {
				view.options.institucionCollection.trigger('add');
			}
		});
	},
	planaDocente: function () {
		//
	}
});

*/

define(['backbone', 'AdminApplication'], function (Backbone, app) {
	var AdminRouter;

	AdminRouter = Backbone.Router.extend({
		routes: {
			'cargo': 'showCargo',
			'institucioneducativa': 'showInstitucionEducativa',
			'periodoacademico': 'showPeriodoAcademico',
			'estructuraie': 'showEstructuraie',
			'admin/planadocente': 'showPlanadocente'
		},
		showCargo: function () {
			app.showCargoListView();
		},
		showInstitucionEducativa: function () {
			app.showInstitucionEducativaListView();
		},
		showPeriodoAcademico: function () {
			app.showPeriodoAcademico();
		},
		showEstructuraie: function () {
			app.showEstructuraie();
		},
		showPlanadocente: function () {
			app.showPlanadocente();
		}
	});

	return AdminRouter;
});


text:
@interface RxSampleSequenceSink<O : id<RxObserverType>> : RxSink<O> <RxObserverType, RxLockOwnerType, RxSynchronizedOnType>
@property (nullable) id element;
@property BOOL atEnd;
@property (nonnull) RxSample *parent;
@end

@interface RxSamplerSink : NSObject <RxObserverType, RxLockOwnerType, RxSynchronizedOnType>
@end

@implementation RxSamplerSink {
    RxSampleSequenceSink *__nonnull _parent;
}

- (nonnull instancetype)initWithParent:(nonnull RxSampleSequenceSink *)parent {
    self = [super init];
    if (self) {
        _parent = parent;
    }
    return self;
}

- (void)rx_lock {
    [[self getRxLock] lock];
}

- (void)rx_unlock {
    [[self getRxLock] unlock];
}

- (nonnull RxSpinLock *)getRxLock {
    return _parent->_lock;
}

- (void)on:(nonnull RxEvent *)event {
    rx_synchronizedOn(self, event);
}

- (void)_synchronized_on:(nonnull RxEvent *)event {
    switch (event.type) {
        case RxEventTypeNext: {
            id element = _parent.element;
            if (element) {
                if (_parent.parent->_onlyNew) {
                    _parent.element = nil;
                }

                [_parent forwardOn:[RxEvent next:element]];
            }

            if (_parent.atEnd) {
                [_parent forwardOn:[RxEvent completed]];
                [_parent dispose];
            }
            break;
        }
        case RxEventTypeError: {
            [_parent forwardOn:[RxEvent error:event.error]];
            [_parent dispose];
            break;
        }
        case RxEventTypeCompleted: {
            id element = _parent.element;
            if (element) {
                _parent.element = nil;
                [_parent forwardOn:[RxEvent next:element]];
            }
            if (_parent.atEnd) {
                [_parent forwardOn:[RxEvent completed]];
                [_parent dispose];
            }
            break;
        }
    }
}

@end

@implementation RxSampleSequenceSink {
    RxSingleAssignmentDisposable *__nonnull _sourceSubscription;
}

- (nonnull instancetype)initWithParent:(nonnull RxSample *)parent observer:(nonnull id <RxObserverType>)observer {
    self = [super initWithObserver:observer];
    if (self) {
        _element = nil;
        _atEnd = NO;
        _sourceSubscription = [[RxSingleAssignmentDisposable alloc] init];
        _parent = parent;
    }
    return self;
}

- (nonnull id <RxDisposable>)run {
    _sourceSubscription.disposable = [_parent->_source subscribe:self];
    id <RxDisposable> samplerSubscription = [_parent->_sampler subscribe:[[RxSamplerSink alloc] initWithParent:self]];

    return [RxStableCompositeDisposable createDisposable1:_sourceSubscription disposable2:samplerSubscription];
}

- (void)rx_lock {
    [[self getRxLock] lock];
}

- (void)rx_unlock {
    [[self getRxLock] unlock];
}

- (nonnull RxSpinLock *)getRxLock {
    return _lock;
}

- (void)on:(nonnull RxEvent *)event {
    rx_synchronizedOn(self, event);
}

- (void)_synchronized_on:(nonnull RxEvent *)event {
    switch (event.type) {
        case RxEventTypeNext: {
            _element = event.element;
            break;
        }
        case RxEventTypeError: {
            [self forwardOn:event];
            [self dispose];
            break;
        }
        case RxEventTypeCompleted: {
            _atEnd = YES;
            [_sourceSubscription dispose];
            break;
        }
    }
}

@end

@implementation RxSample

- (nonnull instancetype)initWithSource:(nonnull RxObservable<id> *)source sampler:(nonnull RxObservable<id> *)sampler onlyNew:(BOOL)onlyNew {
    self = [super init];
    if (self) {
        _source = source;
        _sampler = sampler;
        _onlyNew = onlyNew;
    }
    return self;
}

- (nonnull id <RxDisposable>)run:(nonnull id <RxObserverType>)observer {
    RxSampleSequenceSink *sink = [[RxSampleSequenceSink alloc] initWithParent:self observer:observer];
    sink.disposable = [sink run];
    return sink;
}

@end


text:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;

public class BullEye extends JPanel
{
  public void paintComponent ( Graphics g )
  {
    super.paintComponent( g );

    Random randomNumberOne = new Random();
    Color firstColor = new Color( randomNumberOne.nextInt(255), randomNumberOne.nextInt(255), randomNumberOne.nextInt(255));

    Random randomNumberTwo = new Random();
    Color secondColor = new Color( randomNumberTwo.nextInt(255), randomNumberTwo.nextInt(255), randomNumberTwo.nextInt(255));

    //draw the first circle
    g.setColor( firstColor );
    g.fillOval( 10, 10, 200, 200 );

    // draw the second circle
    g.setColor( secondColor );
    g.fillOval( 30, 30, 160, 160 );

    // draw the third circle
    g.setColor( firstColor );
    g.fillOval( 50, 50, 120, 120 );

    // draw the fourth circle
    g.setColor( secondColor );
    g.fillOval( 65, 65, 90, 90 );

    // draw the fifth circle
    g.setColor( firstColor );
    g.fillOval( 80, 80, 60, 60 );
  }
}


text:
class CreateContributions < ActiveRecord::Migration
  def self.up
    create_table :contributions do |t|
      t.integer :user_id
      t.integer :repository_id
      t.timestamps
    end
  end

  def self.down
    drop_table :contributions
  end
end


text:
#region License

#endregion

using System;
using Newtonsoft.Json;

namespace CSharp.Geeklist.Api.Models
{
	/// <summary>
	/// Represents a Geeklist micros response.
	/// </summary>
	/// <author>Scott Smith</author>
	[Serializable]
	public class MicrosResponse
	{
		[JsonProperty("status")]
		public string Status { get; set; }

		[JsonProperty("data")]
		public MicrosDetails MicrosDetails { get; set; }

		[JsonIgnore]
		public string RawJson { get; set; }
	}
}


text:
<?php

namespace CatLab\Charon\Laravel\JsonApi\Models\Routing;

/**
 * Class RouteCollection
 * @package CatLab\Charon\Laravel\JsonApi\Models\Routing
 */
class RouteCollection extends \CatLab\Charon\Collections\RouteCollection
{
    /**
     * @param $method
     * @param $path
     * @param $action
     * @param $options
     * @return Route
     */
    protected function createRoute($method, $path, $action, $options)
    {
        return new Route($this, $method, $path, $action, $options);
    }
}


text:
global pulseguess
global Uwantin

%Reset the params structure
params = [];

%Location of the nuclei file (full path name)
params.nucleifile = 'molecule_sample2.def';

%Number of timesteps
params.plength = 400;

%Length of each time step
params.timestep = 10e-6;

%Initial stepsize (this is reasonably important - run some tries
%and choose a value which is close to what the program is choosing
%after 50 or so iterations)
params.stepsize = 2e-2;

%Desired unitary
%H90
params.Uwant = expm(-i*(pi/2)*(full(mkstate('+1XII',0))));

params.subsystem{1} = [1 2 3];

params.subsys_weight = [1];

%Desired fidelity for the unitary (this is the trace squared fidelity F = abs(Ugoal^dagger*Usim)^2/N^2)
params.fidelity = 0.9995;

%RF distribution to optimize over (will slow down search and convergence dramatically)
%Two dimensional array first column is percentage of sample; second
%column is percentage of rf strength it sees.
%params.rfdist = [0.3 0.97;.4 1.00;0.3 1.03];

params.rfdist = [1 1];

%Hamiltonian distribution to optimize over
%params.Hamdist = (1/8)*ones(1,8);

params.Hamdist = [1];

%Matrices for robustness to Hamiltonian distributions.  These will be
%multiplied by 2PI and added to the natural Hamiltonian.
params.Hammatts{1} = 0;

%Spins in nuclei file to ignore in search
params.spins_ignore = {'C1','C3','C4','C5','C6','C7','C8'};

%RF control fields (3D array of control Hamiltonians - as many as you like)
X = [0 1;1 0]; Y = [0 -i;i 0]; I = eye(2);
n=3;
tmpRFmat = zeros(2^n,2^n);
for nucct = [1 2 3]
    tmpmat = 1;
    for nucctbis = 1:1:n
        if(nucctbis == nucct)
            tmpmat = kron(tmpmat,X);
        else
            tmpmat = kron(tmpmat,I);
        end
    end
    tmpRFmat = tmpRFmat + tmpmat;
end
params.RFmatts(:,:,1) = tmpRFmat;

tmpRFmat = zeros(2^n,2^n);
for nucct = [1 2 3]
    tmpmat = 1;
    for nucctbis = 1:1:n
        if(nucctbis == nucct)
            tmpmat = kron(tmpmat,Y);
        else
            tmpmat = kron(tmpmat,I);
        end
    end
    tmpRFmat = tmpRFmat + tmpmat;
end
params.RFmatts(:,:,1) = 0.5*tmpRFmat;

%The maximum rf power for each rf field in rad/s
params.rfmax = 2*pi*[25e3 25e3 16.7e3 16.7e3 15e3 15e3];

%Some parameters for the random guess
%Scale of the random guess for each RFmatt (between 0 and 1)
params.randscale = [0.05 0.05 0.05 0.05 0.05 0.05];

%Choose every randevery points at random (rest will be fit to cubic spline)
params.randevery = 25;

%Tolerance for improving i.e. if over 20 tries we are not improving by an average of at least this,
%we will try a new random starting point
params.improvechk = 1e-7;

%Minimum stepsize (if we're not moving anywhere we should stop searching)
params.minstepsize = 1e-7;

%Number of random guesses to try before giving up
params.numtry = 5;

%A vector of the pulsing frequency for each spin (this is defined
%with respect to the same frequency your nuclei file is)
params.pulsefreq = [-4000 -4000 -4000];

%Soft pulse buffering delay (delays required before and after soft pulses.
%  (Since our time periods are usually greater than 350ns we could probably
    %try to use fast shapes)
params.softpulsebuffer = 10e-6;

%If there is a starting guess for the pulse load it in here (should
%be a structure
params.pulseguess = [pulseguess];

%The type of pulse we are searching for (1 for unitary, 2 for state
%to state)
params.searchtype = 1;

%Flag for whether you want to allow the time steps to vary
params.tstepflag = 0;

%Maximum length of pulse (rather soft boundary)
params.tpulsemax = 10e-3;

%Input and goal states for state to state
params.rhoin = mkstate('+1XII',1);
params.rhogoal = mkstate('+1YII',1);

%Allow Zfreedom or not
params.Zfreedomflag = 1;

%Parameter to force the beginnings and end of the pulse to zero
%with a penalty function
params.onofframps = 0;
params.onoff_numpts = 10;
params.onoff_param1 = 1e-3;
params.onoff_param2 = 0.25;

%Display every x seconds irrespective of how things are improved
params.dispevery = 60;


text:
package consulo.javascript.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.lang.javascript.JSElementTypes;
import com.intellij.lang.javascript.psi.*;
import com.intellij.lang.javascript.psi.impl.JSExpressionImpl;
import com.intellij.lang.javascript.psi.resolve.JSResolveUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import consulo.annotation.access.RequiredWriteAction;
import consulo.javascript.lang.psi.JavaScriptType;
import consulo.javascript.lang.psi.JavaScriptTypeElement;
import consulo.javascript.psi.JavaScriptLambdaExpression;
import org.jetbrains.annotations.NonNls;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author VISTALL
 * @since 03.03.2016
 */
public class JavaScriptLambdaExpressionImpl extends JSExpressionImpl implements JavaScriptLambdaExpression
{
	public JavaScriptLambdaExpressionImpl(ASTNode node)
	{
		super(node);
	}

	@Override
	@RequiredReadAction
	public boolean processDeclarations(@Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, PsiElement lastParent, @Nonnull PsiElement place)
	{
		if(lastParent != null && lastParent.getParent() == this)
		{
			final JSParameter[] params = getParameterList().getParameters();
			for(JSParameter param : params)
			{
				if(!processor.execute(param, state))
				{
					return false;
				}
			}

			boolean b = JSResolveUtil.processDeclarationsInScope(this, processor, state, lastParent, place);
			if(b)
			{
				processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this);
			}
			return b;
		}

		return processor.execute(this, state);
	}

	@Override
	protected void accept(@Nonnull JSElementVisitor visitor)
	{
		visitor.visitLambdaExpression(this);
	}

	@RequiredReadAction
	@Nonnull
	@Override
	public JSParameterList getParameterList()
	{
		return findNotNullChildByClass(JSParameterList.class);
	}

	@Override
	public JSSourceElement[] getBody()
	{
		final ASTNode[] children = getNode().getChildren(JSElementTypes.SOURCE_ELEMENTS);
		if(children.length == 0)
		{
			return JSSourceElement.EMPTY_ARRAY;
		}
		JSSourceElement[] result = new JSSourceElement[children.length];
		for(int i = 0; i < children.length; i++)
		{
			result[i] = (JSSourceElement) children[i].getPsi();
		}
		return result;
	}

	@Nonnull
	@Override
	public JavaScriptType getReturnType()
	{
		return JavaScriptType.UNKNOWN;
	}

	@Override
	public String getReturnTypeString()
	{
		return null;
	}

	@Nullable
	@Override
	public JavaScriptTypeElement getReturnTypeElement()
	{
		return null;
	}

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

	@Nullable
	@Override
	public JSAttributeList getAttributeList()
	{
		return null;
	}

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

	@RequiredReadAction
	@Nullable
	@Override
	public PsiElement getNameIdentifier()
	{
		return null;
	}

	@RequiredWriteAction
	@Override
	public PsiElement setName(@Nonnull @NonNls String name) throws IncorrectOperationException
	{
		return null;
	}
}


text:
from urlparse import urlparse

import requests

from . import app
from . import log

class Banned(requests.ConnectionError):

    def __init__(self):
        super(Banned, self).__init__('The connection was refused.')

class Session(requests.Session):

    def __init__(self, *args, **kwargs):
        super(Session, self).__init__(*args, **kwargs)
        self.headers['User-Agent'] = app.config['USER_AGENT']

    def request(self, method, url, **kwargs):
        log.debug('HTTP: %s %s', method.upper(), urlparse(url).netloc)
        try:
            # set default timeout
            kwargs.setdefault('timeout', app.config['HTTP_TIMEOUT'])

            # by default we don't verify certificates
            kwargs.setdefault('verify', False)
            resp = super(Session, self).request(method, url, **kwargs)

            # implicit exception raising on HTTP errors, can be turned
            # off ad-hoc by extra raise_for_status=False keyword argument
            if kwargs.get('raise_for_status', True):
                resp.raise_for_status()
            return resp

        except requests.exceptions.ConnectionError as e:
            if 'Connection refused' in unicode(e):
                raise Banned
            raise

from requests.exceptions import *  # NOQA


text:
extern zend_class_entry *test_router_exception_ce;

ZEPHIR_INIT_CLASS(Test_Router_Exception);