text:
CREATE TABLE `RHY_PERSONAS`
(
  `PER_CODIGO` Varchar(30) NOT NULL,
  `PER_NOMBRE` Varchar(30) NOT NULL,
  `PER_P_APELLIDO` Varchar(30) NOT NULL,
  `PER_S_APELLIDO` Varchar(20) NOT NULL,
  `PER_F_NACIMIENTO` Date,
  `PER_GENERO` Varchar(1) NOT NULL,
  `PAI_CODIGO` Int
)
;

CREATE INDEX `IX_Relationship62` ON `RHY_PERSONAS` (`PAI_CODIGO`)
;

ALTER TABLE `RHY_PERSONAS` ADD  PRIMARY KEY (`PER_CODIGO`)
;

-- Table RHY_PADECIMIENTOS

CREATE TABLE `RHY_PADECIMIENTOS`
(
  `PAD_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `PAD_NOMBRE` Varchar(30) NOT NULL,
  `PAD_DESCRIPCION` Varchar(140),
  PRIMARY KEY (`PAD_CODIGO`)
)
;

-- Table RHY_HISTORIAL_MEDICO

CREATE TABLE `RHY_HISTORIAL_MEDICO`
(
  `HIS_PAD_CODIGO` Int NOT NULL,
  `HIS_COMENTARIO` Varchar(100),
  `PER_CODIGO` Varchar(30) NOT NULL
)
;

ALTER TABLE `RHY_HISTORIAL_MEDICO` ADD  PRIMARY KEY (`HIS_PAD_CODIGO`,`PER_CODIGO`)
;

-- Table RHY_USUARIO

CREATE TABLE `RHY_USUARIO`
(
  `USU_USUARIO` Varchar(30) NOT NULL,
  `USU_CONTRASENA` Varchar(30) NOT NULL,
  `USU_ULTIMA_CONEXION` Date,
  `PER_CODIGO` Varchar(30) NOT NULL
)
;

ALTER TABLE `RHY_USUARIO` ADD  PRIMARY KEY (`PER_CODIGO`)
;

-- Table RHY_ROLES

CREATE TABLE `RHY_ROLES`
(
  `ROL_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `ROL_NOMBRE` Varchar(30) NOT NULL,
  `ROL_DESCRIPCION` Varchar(100),
  `ROL_DEFAULT` Varchar(1) NOT NULL,
  PRIMARY KEY (`ROL_CODIGO`)
)
;

-- Table RHY_ROL_USUARIOS

CREATE TABLE `RHY_ROL_USUARIOS`
(
  `USU_PER_CODIGO` Varchar(30) NOT NULL,
  `ROL_CODIGO` Int NOT NULL
)
;

ALTER TABLE `RHY_ROL_USUARIOS` ADD  PRIMARY KEY (`USU_PER_CODIGO`,`ROL_CODIGO`)
;

-- Table RHY_PERMISOS

CREATE TABLE `RHY_PERMISOS`
(
  `PER_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `PER_NOMBRE` Varchar(30) NOT NULL,
  `PER_DESCRIPCION` Varchar(100),
  `PER_MODULO` Varchar(4) NOT NULL,
  PRIMARY KEY (`PER_CODIGO`)
)
;

-- Table RHY_PERMISOS_ROLES

CREATE TABLE `RHY_PERMISOS_ROLES`
(
  `ROL_CODIGO` Int NOT NULL,
  `PER_CODIGO` Int NOT NULL,
  `PER_TIPOPER` Varchar(2) NOT NULL
)
;

ALTER TABLE `RHY_PERMISOS_ROLES` ADD  PRIMARY KEY (`ROL_CODIGO`,`PER_CODIGO`)
;

-- Table RHY_CURSOS

CREATE TABLE `RHY_CURSOS`
(
  `CUR_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `CUR_NOMBRE` Varchar(30) NOT NULL,
  `CUR_COSTOPUBLICO` Int NOT NULL,
  `CUR_FECHA_APERTURA` Date NOT NULL,
  `CUR_FECHA_CLAUSURA` Date,
  `ACA_CODIGO` Int NOT NULL,
  `CUR_DESCIPCION` Varchar(200),
  `CUR_ESTADO` Varchar(1) NOT NULL,
  `CUR_PRIVACIDAD` Varchar(1) NOT NULL,
  `TIP_CODIGO` Int,
  PRIMARY KEY (`CUR_CODIGO`)
)
;

CREATE INDEX `IX_Relationship77` ON `RHY_CURSOS` (`ACA_CODIGO`)
;

CREATE INDEX `IX_Relationship1` ON `RHY_CURSOS` (`TIP_CODIGO`)
;

-- Table RHY_MATRICULA

CREATE TABLE `RHY_MATRICULA`
(
  `MAT_FECHA` Date,
  `MAT_CUR_COD` Int NOT NULL,
  `EST_CODIGO` Varchar(30) NOT NULL,
  `MAT_ESTADO` Varchar(1) NOT NULL,
  `EST_ACA_COD` Int NOT NULL
)
;

ALTER TABLE `RHY_MATRICULA` ADD  PRIMARY KEY (`MAT_CUR_COD`,`EST_CODIGO`,`EST_ACA_COD`)
;

-- Table RHY_PAGOS

CREATE TABLE `RHY_PAGOS`
(
  `PAG_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `PAG_FECHA` Date NOT NULL,
  `PAG_ESTADO` Varchar(1) NOT NULL,
  `PAG_MONTO` Int NOT NULL,
  `FAC_CODIGO` Int NOT NULL,
  `PAG_TIPOCODIGO` Int,
 UNIQUE `PAG_CODIGO` (`PAG_CODIGO`)
)
;

CREATE INDEX `IX_Relationship81` ON `RHY_PAGOS` (`FAC_CODIGO`)
;

CREATE INDEX `IX_Relationship1` ON `RHY_PAGOS` (`PAG_TIPOCODIGO`)
;

-- Table RHY_ESPACIOS

CREATE TABLE `RHY_ESPACIOS`
(
  `ESP_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `ESP_NOMBRE` Varchar(30) NOT NULL,
  `ESP_DIRECCION` Varchar(200),
  `ACA_CODIGO` Int NOT NULL,
  PRIMARY KEY (`ESP_CODIGO`)
)
;

CREATE INDEX `IX_Relationship73` ON `RHY_ESPACIOS` (`ACA_CODIGO`)
;

-- Table RHY_AGENDA_CURSO

CREATE TABLE `RHY_AGENDA_CURSO`
(
  `AGE_CURSOCODIGO` Int NOT NULL,
  `AGE_ESPACIOCODIGO` Int,
  `AGE_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `AGE_FECHAPRIMERA` Date NOT NULL,
  `AGE_RECURRENCIA` Varchar(1) NOT NULL,
  `AGE_INSCODIGO` Varchar(30) NOT NULL,
  `AGE_HORAINIC` Int NOT NULL DEFAULT 4,
  `ACA_CODIGO` Int,
  PRIMARY KEY (`AGE_CODIGO`)
)
;

CREATE INDEX `IX_Relationship26` ON `RHY_AGENDA_CURSO` (`AGE_CURSOCODIGO`)
;

CREATE INDEX `IX_Relationship28` ON `RHY_AGENDA_CURSO` (`AGE_ESPACIOCODIGO`)
;

CREATE INDEX `IX_Relationship52` ON `RHY_AGENDA_CURSO` (`AGE_INSCODIGO`,`ACA_CODIGO`)
;

-- Table RHY_EVENTOS

CREATE TABLE `RHY_EVENTOS`
(
  `EVE_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `EVE_NOMBRE` Varchar(30) NOT NULL,
  `EVE_PRIVACIDAD` Varchar(1) NOT NULL,
  `ACA_CODIGO` Int NOT NULL,
  `EVE_ESTADO` Varchar(1) NOT NULL,
  PRIMARY KEY (`EVE_CODIGO`)
)
;

CREATE INDEX `IX_Relationship74` ON `RHY_EVENTOS` (`ACA_CODIGO`)
;

-- Table RHY_AGENDA_EVENTO

CREATE TABLE `RHY_AGENDA_EVENTO`
(
  `AGE_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `AGE_FECHA_INICIO` Date NOT NULL,
  `AGE_FECHA_FIN` Date NOT NULL,
  `AGE_RECURRENCIA` Varchar(1),
  `AGE_ESPACIO_CODIGO` Int NOT NULL,
  `AGE_EVENTO_CODIGO` Int NOT NULL,
  `AGE_INSECARGADO` Varchar(30) NOT NULL,
  `ACA_CODIGO` Int,
  PRIMARY KEY (`AGE_CODIGO`)
)
;

CREATE INDEX `IX_Relationship30` ON `RHY_AGENDA_EVENTO` (`AGE_ESPACIO_CODIGO`)
;

CREATE INDEX `IX_Relationship31` ON `RHY_AGENDA_EVENTO` (`AGE_EVENTO_CODIGO`)
;

CREATE INDEX `IX_Relationship51` ON `RHY_AGENDA_EVENTO` (`AGE_INSECARGADO`,`ACA_CODIGO`)
;

-- Table RHY_BITACORA

CREATE TABLE `RHY_BITACORA`
(
  `SES_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `SES_FECHA` Date NOT NULL,
  `SES_ACCION` Varchar(60),
  `SES_USUARIO_CODIGO` Varchar(30) NOT NULL,
  PRIMARY KEY (`SES_CODIGO`)
)
;

CREATE INDEX `IX_Relationship32` ON `RHY_BITACORA` (`SES_USUARIO_CODIGO`)
;

-- Table RHY_IMAGENES

CREATE TABLE `RHY_IMAGENES`
(
  `IMG_RUTA` Varchar(150) NOT NULL,
  `IMG_DESCRIPCION` Varchar(100),
  `IMG_FECHA` Date NOT NULL,
  `IMG_LUGAR` Varchar(100),
  `IMG_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `IMG_SUBIDOPOR` Varchar(30) NOT NULL,
  `IMG_PRIVACIDAD` Varchar(1) NOT NULL,
  PRIMARY KEY (`IMG_CODIGO`)
)
;

CREATE INDEX `IX_Relationship33` ON `RHY_IMAGENES` (`IMG_SUBIDOPOR`)
;

-- Table RHY_FACTURACION

CREATE TABLE `RHY_FACTURACION`
(
  `FAC_DESCRIPCION` Varchar(150),
  `FAC_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `FAC_FECHA` Date NOT NULL,
  `FAC_CLI_DESCR` Varchar(150),
  `FAC_USU_ENC` Varchar(30) NOT NULL,
  `FAC_CLI_COD` Varchar(30),
  `ACA_CODIGO` Int,
  PRIMARY KEY (`FAC_CODIGO`)
)
;

CREATE INDEX `IX_Relationship36` ON `RHY_FACTURACION` (`FAC_USU_ENC`)
;

CREATE INDEX `IX_Relationship37` ON `RHY_FACTURACION` (`FAC_CLI_COD`)
;

CREATE INDEX `IX_Relationship4` ON `RHY_FACTURACION` (`ACA_CODIGO`)
;

-- Table RHY_ASISTENCIA

CREATE TABLE `RHY_ASISTENCIA`
(
  `ASI_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `ASI_FECHA` Date,
  PRIMARY KEY (`ASI_CODIGO`)
)
;

-- Table RHY_TIPOCONTACTO

CREATE TABLE `RHY_TIPOCONTACTO`
(
  `TIP_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `TIP_DESCRIPCION` Varchar(30),
  `TIP_NOMBRE` Varchar(20) NOT NULL,
  PRIMARY KEY (`TIP_CODIGO`)
)
;

-- Table RHY_CONTACTOPER

CREATE TABLE `RHY_CONTACTOPER`
(
  `CON_TIPCODIGO` Int NOT NULL,
  `CON_PERCODIGO` Varchar(30) NOT NULL,
  `CON_DATO` Varchar(50) NOT NULL
)
;

ALTER TABLE `RHY_CONTACTOPER` ADD  PRIMARY KEY (`CON_TIPCODIGO`,`CON_PERCODIGO`)
;

-- Table RHY_ESTUDIANTES

CREATE TABLE `RHY_ESTUDIANTES`
(
  `EST_PER_COD` Varchar(30) NOT NULL,
  `EST_FECHINGRESO` Date NOT NULL,
  `EST_ACA_COD` Int NOT NULL
)
;

ALTER TABLE `RHY_ESTUDIANTES` ADD  PRIMARY KEY (`EST_PER_COD`,`EST_ACA_COD`)
;

-- Table RHY_INSTRUCTOR

CREATE TABLE `RHY_INSTRUCTOR`
(
  `PER_CODIGO` Varchar(30) NOT NULL,
  `INS_FECHAINGRESO` Date NOT NULL,
  `INS_ESTADO` Varchar(1) NOT NULL,
  `ACA_CODIGO` Int NOT NULL
)
;

ALTER TABLE `RHY_INSTRUCTOR` ADD  PRIMARY KEY (`PER_CODIGO`,`ACA_CODIGO`)
;

-- Table RHY_CLASES

CREATE TABLE `RHY_CLASES`
(
  `CLA_ID` Int NOT NULL AUTO_INCREMENT,
  `CLA_FECHA` Date NOT NULL,
  `CLA_COMENTARIO` Varchar(50),
  `AGE_CODIGO` Int NOT NULL,
  `CLA_HORAINICIO` Int DEFAULT 4,
  `CLA_ESTADO` Varchar(1) NOT NULL,
  PRIMARY KEY (`CLA_ID`)
)
;

CREATE INDEX `IX_Relationship53` ON `RHY_CLASES` (`AGE_CODIGO`)
;

-- Table RHY_ASISTENCIAS

CREATE TABLE `RHY_ASISTENCIAS`
(
  `CLA_ID` Int NOT NULL,
  `EST_CODIGO` Varchar(30) NOT NULL,
  `EST_ACA_COD` Int NOT NULL
)
;

ALTER TABLE `RHY_ASISTENCIAS` ADD  PRIMARY KEY (`CLA_ID`,`EST_CODIGO`,`EST_ACA_COD`)
;

-- Table RHY_ACADEMIAS

CREATE TABLE `RHY_ACADEMIAS`
(
  `ACA_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `ACA_NOMBRE` Varchar(100),
  `ACA_DIR_COD` Int,
  PRIMARY KEY (`ACA_CODIGO`)
)
;

CREATE INDEX `IX_Relationship64` ON `RHY_ACADEMIAS` (`ACA_DIR_COD`)
;

-- Table RHY_PAISES

CREATE TABLE `RHY_PAISES`
(
  `PAI_NOMBRE` Varchar(120) NOT NULL,
  `PAI_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `PAI_ISO3166` Varchar(3),
  PRIMARY KEY (`PAI_CODIGO`)
)
;

-- Table RHY_PROVINCIAS

CREATE TABLE `RHY_PROVINCIAS`
(
  `PRO_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `PRO_NOMBRE` Varchar(120) NOT NULL,
  `PAI_CODIGO` Int,
  PRIMARY KEY (`PRO_CODIGO`)
)
;

CREATE INDEX `IX_Relationship57` ON `RHY_PROVINCIAS` (`PAI_CODIGO`)
;

-- Table RHY_CANTONES

CREATE TABLE `RHY_CANTONES`
(
  `CAN_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `CAN_NOMBRE` Varchar(120) NOT NULL,
  `PRO_CODIGO` Int,
  PRIMARY KEY (`CAN_CODIGO`)
)
;

CREATE INDEX `IX_Relationship58` ON `RHY_CANTONES` (`PRO_CODIGO`)
;

-- Table RHY_BARRIOS

CREATE TABLE `RHY_BARRIOS`
(
  `BAR_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `BAR_NOMBRE` Varchar(120) NOT NULL,
  `DIS_CODIGO` Int,
  PRIMARY KEY (`BAR_CODIGO`)
)
;

CREATE INDEX `IX_Relationship60` ON `RHY_BARRIOS` (`DIS_CODIGO`)
;

-- Table RHY_DISTRITOS

CREATE TABLE `RHY_DISTRITOS`
(
  `DIS_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `DIS_NOMBRE` Varchar(120) NOT NULL,
  `CAN_CODIGO` Int,
  PRIMARY KEY (`DIS_CODIGO`)
)
;

CREATE INDEX `IX_Relationship59` ON `RHY_DISTRITOS` (`CAN_CODIGO`)
;

-- Table RHY_DIRECION

CREATE TABLE `RHY_DIRECION`
(
  `DIR_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `DIR_DESCRIPCION` Varchar(250),
  `BAR_CODIGO` Int,
  `DIR_NOMBRE` Varchar(60),
  PRIMARY KEY (`DIR_CODIGO`)
)
;

CREATE INDEX `IX_Relationship61` ON `RHY_DIRECION` (`BAR_CODIGO`)
;

-- Table RHY_DIRECCPERSONAL

CREATE TABLE `RHY_DIRECCPERSONAL`
(
  `PER_CODIGO` Varchar(30) NOT NULL,
  `DIR_CODIGO` Int NOT NULL,
  `DIR_DESCRIPCION` Varchar(120)
)
;

ALTER TABLE `RHY_DIRECCPERSONAL` ADD  PRIMARY KEY (`PER_CODIGO`,`DIR_CODIGO`)
;

-- Table RHY_RESIDENCIAS

CREATE TABLE `RHY_RESIDENCIAS`
(
  `PAI_CODIGO` Int NOT NULL,
  `PER_CODIGO` Varchar(30) NOT NULL,
  `RES_DESCRIPCION` Varchar(120),
  `RES_OTORGADO` Date NOT NULL
)
;

ALTER TABLE `RHY_RESIDENCIAS` ADD  PRIMARY KEY (`PAI_CODIGO`,`PER_CODIGO`)
;

-- Table RHY_CONTAC_ACA

CREATE TABLE `RHY_CONTAC_ACA`
(
  `CON_TIP_COD` Int NOT NULL,
  `CON_ACA_COD` Int NOT NULL,
  `CON_DATO` Varchar(200)
)
;

ALTER TABLE `RHY_CONTAC_ACA` ADD  PRIMARY KEY (`CON_TIP_COD`,`CON_ACA_COD`)
;

-- Table RHY_SERVICIOS

CREATE TABLE `RHY_SERVICIOS`
(
  `SER_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `SER_COSTO` Int NOT NULL,
  `SER_TIPOCODIGO` Int NOT NULL,
  `SER_NOMBRE` Varchar(50) NOT NULL,
  `SER_DESCRIPCION` Varchar(150),
  PRIMARY KEY (`SER_CODIGO`)
)
;

CREATE INDEX `IX_Relationship82` ON `RHY_SERVICIOS` (`SER_TIPOCODIGO`)
;

-- Table RHY_SERVICIOSTIPO

CREATE TABLE `RHY_SERVICIOSTIPO`
(
  `SER_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `SER_NOMBRE` Varchar(50) NOT NULL,
  `SER_DESCRIPCION` Varchar(150),
  PRIMARY KEY (`SER_CODIGO`)
)
;

-- Table RHY_PAGOSTIPOS

CREATE TABLE `RHY_PAGOSTIPOS`
(
  `PAG_TIPOCODIGO` Int NOT NULL AUTO_INCREMENT,
  `PAG_NOMBRE` Varchar(50) NOT NULL,
  `PAG_DESCRIPCION` Varchar(150),
  PRIMARY KEY (`PAG_TIPOCODIGO`)
)
;

-- Table RHY_CURSOSERVICIO

CREATE TABLE `RHY_CURSOSERVICIO`
(
  `CUR_CODIGO` Int NOT NULL,
  `SER_CODIGO` Int NOT NULL
)
;

ALTER TABLE `RHY_CURSOSERVICIO` ADD  PRIMARY KEY (`CUR_CODIGO`,`SER_CODIGO`)
;

-- Table RHY_SERVICIOSCOBRADOS

CREATE TABLE `RHY_SERVICIOSCOBRADOS`
(
  `FAC_CODIGO` Int NOT NULL,
  `SER_CODIGO` Int NOT NULL,
  `SER_MON_COBRADO` Int NOT NULL,
  `SER_DES_APLICADO` Int
)
;

ALTER TABLE `RHY_SERVICIOSCOBRADOS` ADD  PRIMARY KEY (`FAC_CODIGO`,`SER_CODIGO`)
;

-- Table RHY_CONTROLPAGOS

CREATE TABLE `RHY_CONTROLPAGOS`
(
  `FAC_CODIGO` Int NOT NULL,
  `SER_CODIGO` Int NOT NULL,
  `CUR_CODIGO` Int NOT NULL,
  `EST_CODIGO` Varchar(30) NOT NULL,
  `EST_ACA_COD` Int NOT NULL
)
;

ALTER TABLE `RHY_CONTROLPAGOS` ADD  PRIMARY KEY (`FAC_CODIGO`,`SER_CODIGO`,`CUR_CODIGO`,`EST_CODIGO`,`EST_ACA_COD`)
;

-- Table RHY_IMAGENCURSO

CREATE TABLE `RHY_IMAGENCURSO`
(
  `IMG_CODIGO` Int NOT NULL,
  `CUR_CODIGO` Int NOT NULL
)
;

ALTER TABLE `RHY_IMAGENCURSO` ADD  PRIMARY KEY (`IMG_CODIGO`,`CUR_CODIGO`)
;

-- Table RHY_CONFIGWEB

CREATE TABLE `RHY_CONFIGWEB`
(
  `CON_NOMBRE` Varchar(50),
  `CON_FECHACREACION` Date NOT NULL,
  `CON_HORA` Int DEFAULT 4,
  `CON_DESCRIPCION` Varchar(150),
  `CON_PER_COD` Varchar(30) NOT NULL,
  `CON_ACA_COD` Int NOT NULL,
  `CON_MISION` Varchar(400),
  `CON_VISION` Varchar(400),
  `CON_ACADINFO` Varchar(400),
  `CON_CORREOTIPCOD` Int NOT NULL,
  `CON_TELTIPCOD` Int NOT NULL
)
;

CREATE INDEX `IX_Relationship94` ON `RHY_CONFIGWEB` (`CON_PER_COD`)
;

CREATE INDEX `IX_Relationship99` ON `RHY_CONFIGWEB` (`CON_CORREOTIPCOD`)
;

CREATE INDEX `IX_Relationship101` ON `RHY_CONFIGWEB` (`CON_TELTIPCOD`)
;

ALTER TABLE `RHY_CONFIGWEB` ADD  PRIMARY KEY (`CON_ACA_COD`)
;

-- Table RHY_WEBCASILLERO

CREATE TABLE `RHY_WEBCASILLERO`
(
  `WEB_NOMBRE` Varchar(150),
  `WEB_CORREO` Varchar(150),
  `WEB_TEMA` Varchar(100),
  `WEB_MENSAJE` Varchar(300),
  `WEB_CODIGO` Int NOT NULL AUTO_INCREMENT,
  `ACA_CODIGO` Int,
  PRIMARY KEY (`WEB_CODIGO`)
)
;

CREATE INDEX `IX_Relationship96` ON `RHY_WEBCASILLERO` (`ACA_CODIGO`)
;

-- Table RHY_USUACADEMIA

CREATE TABLE `RHY_USUACADEMIA`
(
  `ACA_CODIGO` Int NOT NULL,
  `PER_CODIGO` Varchar(30) NOT NULL
)
;

ALTER TABLE `RHY_USUACADEMIA` ADD  PRIMARY KEY (`ACA_CODIGO`,`PER_CODIGO`)
;

-- Table RHY_ACCESOIMGWEB

CREATE TABLE `RHY_ACCESOIMGWEB`
(
  `IMG_CODIGO` Int NOT NULL,
  `ACA_CODIGO` Int NOT NULL,
  `ACC_ID` Varchar(10) NOT NULL,
  `ACC_DESCRIPCION` Varchar(150)
)
;

ALTER TABLE `RHY_ACCESOIMGWEB` ADD  PRIMARY KEY (`IMG_CODIGO`,`ACA_CODIGO`)
;

ALTER TABLE `RHY_ACCESOIMGWEB` ADD UNIQUE `ACC_ID` (`ACC_ID`)
;

-- Table RHY_TIPO_CURSOS

CREATE TABLE `RHY_TIPO_CURSOS`
(
  `TIP_CODIGO` Int NOT NULL,
  `TIP_TIPO_CURSO` Varchar(100) NOT NULL
)
;

ALTER TABLE `RHY_TIPO_CURSOS` ADD  PRIMARY KEY (`TIP_CODIGO`)
;

-- Create relationships section -------------------------------------------------

ALTER TABLE `RHY_HISTORIAL_MEDICO` ADD CONSTRAINT `FPK_PADECIMIENT1` FOREIGN KEY (`HIS_PAD_CODIGO`) REFERENCES `RHY_PADECIMIENTOS` (`PAD_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_USUARIO` ADD CONSTRAINT `FPK_PERSONA3` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ROL_USUARIOS` ADD CONSTRAINT `FPK_USUARIO5` FOREIGN KEY (`USU_PER_CODIGO`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ROL_USUARIOS` ADD CONSTRAINT `FPK_ROL1` FOREIGN KEY (`ROL_CODIGO`) REFERENCES `RHY_ROLES` (`ROL_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PERMISOS_ROLES` ADD CONSTRAINT `FPK_ROL2` FOREIGN KEY (`ROL_CODIGO`) REFERENCES `RHY_ROLES` (`ROL_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PERMISOS_ROLES` ADD CONSTRAINT `FPK_PERMIS1` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERMISOS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_MATRICULA` ADD CONSTRAINT `FPK_CURSO2` FOREIGN KEY (`MAT_CUR_COD`) REFERENCES `RHY_CURSOS` (`CUR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_CURSO` ADD CONSTRAINT `FK_CURSO1` FOREIGN KEY (`AGE_CURSOCODIGO`) REFERENCES `RHY_CURSOS` (`CUR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_CURSO` ADD CONSTRAINT `FK_ESPACIO2` FOREIGN KEY (`AGE_ESPACIOCODIGO`) REFERENCES `RHY_ESPACIOS` (`ESP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_EVENTO` ADD CONSTRAINT `FK_ESPACIO1` FOREIGN KEY (`AGE_ESPACIO_CODIGO`) REFERENCES `RHY_ESPACIOS` (`ESP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_EVENTO` ADD CONSTRAINT `FK_EVENTO1` FOREIGN KEY (`AGE_EVENTO_CODIGO`) REFERENCES `RHY_EVENTOS` (`EVE_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_BITACORA` ADD CONSTRAINT `FK_USUARIO4` FOREIGN KEY (`SES_USUARIO_CODIGO`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_IMAGENES` ADD CONSTRAINT `FK_USUARIO6` FOREIGN KEY (`IMG_SUBIDOPOR`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_FACTURACION` ADD CONSTRAINT `FK_USUARIO3` FOREIGN KEY (`FAC_USU_ENC`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_FACTURACION` ADD CONSTRAINT `FK_PERSONA7` FOREIGN KEY (`FAC_CLI_COD`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTACTOPER` ADD CONSTRAINT `FPK_TIPOCONT3` FOREIGN KEY (`CON_TIPCODIGO`) REFERENCES `RHY_TIPOCONTACTO` (`TIP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTACTOPER` ADD CONSTRAINT `FPK_PERSONA4` FOREIGN KEY (`CON_PERCODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ESTUDIANTES` ADD CONSTRAINT `FPK_PERSONA6` FOREIGN KEY (`EST_PER_COD`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_MATRICULA` ADD CONSTRAINT `FPK_ESTUDIANTE2` FOREIGN KEY (`EST_CODIGO`, `EST_ACA_COD`) REFERENCES `RHY_ESTUDIANTES` (`EST_PER_COD`, `EST_ACA_COD`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_INSTRUCTOR` ADD CONSTRAINT `FPK_PERSONA5` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_EVENTO` ADD CONSTRAINT `FK_INSTRUC1` FOREIGN KEY (`AGE_INSECARGADO`, `ACA_CODIGO`) REFERENCES `RHY_INSTRUCTOR` (`PER_CODIGO`, `ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_AGENDA_CURSO` ADD CONSTRAINT `FK_INSTRUC2` FOREIGN KEY (`AGE_INSCODIGO`, `ACA_CODIGO`) REFERENCES `RHY_INSTRUCTOR` (`PER_CODIGO`, `ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CLASES` ADD CONSTRAINT `FK_AGENDACUR1` FOREIGN KEY (`AGE_CODIGO`) REFERENCES `RHY_AGENDA_CURSO` (`AGE_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ASISTENCIAS` ADD CONSTRAINT `FPK_CLASES1` FOREIGN KEY (`CLA_ID`) REFERENCES `RHY_CLASES` (`CLA_ID`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ASISTENCIAS` ADD CONSTRAINT `FPK_ESTUDIANTE3` FOREIGN KEY (`EST_CODIGO`, `EST_ACA_COD`) REFERENCES `RHY_ESTUDIANTES` (`EST_PER_COD`, `EST_ACA_COD`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PROVINCIAS` ADD CONSTRAINT `FK_PAIS3` FOREIGN KEY (`PAI_CODIGO`) REFERENCES `RHY_PAISES` (`PAI_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CANTONES` ADD CONSTRAINT `FK_PROVINCIA1` FOREIGN KEY (`PRO_CODIGO`) REFERENCES `RHY_PROVINCIAS` (`PRO_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_DISTRITOS` ADD CONSTRAINT `FK_CANTON1` FOREIGN KEY (`CAN_CODIGO`) REFERENCES `RHY_CANTONES` (`CAN_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_BARRIOS` ADD CONSTRAINT `FK_DISTRITO1` FOREIGN KEY (`DIS_CODIGO`) REFERENCES `RHY_DISTRITOS` (`DIS_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_DIRECION` ADD CONSTRAINT `FK_BARRIO1` FOREIGN KEY (`BAR_CODIGO`) REFERENCES `RHY_BARRIOS` (`BAR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PERSONAS` ADD CONSTRAINT `FK_PAIS2` FOREIGN KEY (`PAI_CODIGO`) REFERENCES `RHY_PAISES` (`PAI_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ACADEMIAS` ADD CONSTRAINT `FK_DIRECCIO1` FOREIGN KEY (`ACA_DIR_COD`) REFERENCES `RHY_DIRECION` (`DIR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_DIRECCPERSONAL` ADD CONSTRAINT `FPK_PERSONA2` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_DIRECCPERSONAL` ADD CONSTRAINT `FPK_DIRECCIO2` FOREIGN KEY (`DIR_CODIGO`) REFERENCES `RHY_DIRECION` (`DIR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_RESIDENCIAS` ADD CONSTRAINT `FPK_PAIS1` FOREIGN KEY (`PAI_CODIGO`) REFERENCES `RHY_PAISES` (`PAI_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_RESIDENCIAS` ADD CONSTRAINT `FPK_PERSONA1` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTAC_ACA` ADD CONSTRAINT `FPK_TIPOCONT4` FOREIGN KEY (`CON_TIP_COD`) REFERENCES `RHY_TIPOCONTACTO` (`TIP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTAC_ACA` ADD CONSTRAINT `FPK_ACADEMI3` FOREIGN KEY (`CON_ACA_COD`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_INSTRUCTOR` ADD CONSTRAINT `FK_ACADEMI9` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ESTUDIANTES` ADD CONSTRAINT `FK_ACADEMI10` FOREIGN KEY (`EST_ACA_COD`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ESPACIOS` ADD CONSTRAINT `FK_ACADEMI6` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_EVENTOS` ADD CONSTRAINT `FK_ACADEMI7` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CURSOS` ADD CONSTRAINT `FK_ACADEMI4` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PAGOS` ADD CONSTRAINT `FK_FACTURA1` FOREIGN KEY (`FAC_CODIGO`) REFERENCES `RHY_FACTURACION` (`FAC_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_SERVICIOS` ADD CONSTRAINT `FK_SERVICTIP1` FOREIGN KEY (`SER_TIPOCODIGO`) REFERENCES `RHY_SERVICIOSTIPO` (`SER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CURSOSERVICIO` ADD CONSTRAINT `FPK_CURSO3` FOREIGN KEY (`CUR_CODIGO`) REFERENCES `RHY_CURSOS` (`CUR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CURSOSERVICIO` ADD CONSTRAINT `FPK_SERVIC1` FOREIGN KEY (`SER_CODIGO`) REFERENCES `RHY_SERVICIOS` (`SER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_SERVICIOSCOBRADOS` ADD CONSTRAINT `PFK_FACTURA2` FOREIGN KEY (`FAC_CODIGO`) REFERENCES `RHY_FACTURACION` (`FAC_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_SERVICIOSCOBRADOS` ADD CONSTRAINT `FPK_SERVIC2` FOREIGN KEY (`SER_CODIGO`) REFERENCES `RHY_SERVICIOS` (`SER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTROLPAGOS` ADD CONSTRAINT `FPK_SERVICOBRA1` FOREIGN KEY (`FAC_CODIGO`, `SER_CODIGO`) REFERENCES `RHY_SERVICIOSCOBRADOS` (`FAC_CODIGO`, `SER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONTROLPAGOS` ADD CONSTRAINT `FPK_MATRICUL2` FOREIGN KEY (`CUR_CODIGO`, `EST_CODIGO`, `EST_ACA_COD`) REFERENCES `RHY_MATRICULA` (`MAT_CUR_COD`, `EST_CODIGO`, `EST_ACA_COD`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_IMAGENCURSO` ADD CONSTRAINT `FPK_IMAGEN1` FOREIGN KEY (`IMG_CODIGO`) REFERENCES `RHY_IMAGENES` (`IMG_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_IMAGENCURSO` ADD CONSTRAINT `FPK_CURSO4` FOREIGN KEY (`CUR_CODIGO`) REFERENCES `RHY_CURSOS` (`CUR_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONFIGWEB` ADD CONSTRAINT `FK_USUARIO1` FOREIGN KEY (`CON_PER_COD`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONFIGWEB` ADD CONSTRAINT `FPK_ACADEMI2` FOREIGN KEY (`CON_ACA_COD`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_WEBCASILLERO` ADD CONSTRAINT `FK_CONFIG1` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_CONFIGWEB` (`CON_ACA_COD`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_USUACADEMIA` ADD CONSTRAINT `FPK_ACADEMI1` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_USUACADEMIA` ADD CONSTRAINT `FPK_USUARIO2` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_USUARIO` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONFIGWEB` ADD CONSTRAINT `FK_TIPOCONT1` FOREIGN KEY (`CON_CORREOTIPCOD`) REFERENCES `RHY_TIPOCONTACTO` (`TIP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CONFIGWEB` ADD CONSTRAINT `FK_TIPOCONT2` FOREIGN KEY (`CON_TELTIPCOD`) REFERENCES `RHY_TIPOCONTACTO` (`TIP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ACCESOIMGWEB` ADD CONSTRAINT `FPK_IMAGEN2` FOREIGN KEY (`IMG_CODIGO`) REFERENCES `RHY_IMAGENES` (`IMG_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_ACCESOIMGWEB` ADD CONSTRAINT `PFK_CONFIG2` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_CONFIGWEB` (`CON_ACA_COD`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_PAGOS` ADD CONSTRAINT `FK_TIPOPAGO1` FOREIGN KEY (`PAG_TIPOCODIGO`) REFERENCES `RHY_PAGOSTIPOS` (`PAG_TIPOCODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_CURSOS` ADD CONSTRAINT `FK_TIPOCURSO01` FOREIGN KEY (`TIP_CODIGO`) REFERENCES `RHY_TIPO_CURSOS` (`TIP_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_HISTORIAL_MEDICO` ADD CONSTRAINT `PFK_PERSONA08` FOREIGN KEY (`PER_CODIGO`) REFERENCES `RHY_PERSONAS` (`PER_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;

ALTER TABLE `RHY_FACTURACION` ADD CONSTRAINT `FK_ACADEMI11` FOREIGN KEY (`ACA_CODIGO`) REFERENCES `RHY_ACADEMIAS` (`ACA_CODIGO`) ON DELETE RESTRICT ON UPDATE RESTRICT
;


text:
//-----------------------------------------------------------------------
// <copyright file="CategoryViewModel.cs" company="Sitecore Corporation">
//     Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>Defines the CategoryViewModel class.</summary>
//-----------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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.
// -------------------------------------------------------------------------------------------

namespace Sitecore.Commerce.Storefront.Models
{
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;

    using Sitecore.Data.Fields;
    using Sitecore.Data.Items;
    using Sitecore.Mvc;
    using Sitecore.Mvc.Common;
    using Sitecore.Mvc.Presentation;

    using Sitecore.Commerce.Connect.CommerceServer.Search.Models;
    using Sitecore.Commerce.Storefront.Managers;

    /// <summary>
    /// Used to represent a category
    /// </summary>
    public class CategoryViewModel : Sitecore.Mvc.Presentation.RenderingModel
    {
        private Item _item;
        private List<MediaItem> _images;

        /// <summary>
        /// Initializes a new instance of the <see cref="CategoryViewModel" /> class
        /// </summary>
        public CategoryViewModel()
        {
            ChildProducts = new List<Item>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CategoryViewModel" /> class
        /// </summary>
        /// <param name="item">The item to initialize the class with</param>
        public CategoryViewModel(Item item)
        {
            ChildProducts = new List<Item>();
            _item = item;
        }

        /// <summary>
        /// Gets the item for the current model
        /// </summary>
        public override Item Item
        {
            get
            {
                if (_item == null)
                {
                    return base.Item;
                }

                return _item;
            }
        }

        /// <summary>
        /// Gets the Product DisplayName.
        /// </summary>
        public string DisplayName
        {
            get
            {
                return Item.DisplayName;
            }
        }

        /// <summary>
        /// Gets the display name as a html string
        /// </summary>
        public HtmlString DisplayNameRender
        {
            get
            {
                return PageContext.Current.HtmlHelper.Sitecore().Field(FieldIDs.DisplayName.ToString(), Item);
            }
        }

        /// <summary>
        /// Gets or sets the description
        /// </summary>
        public string Description
        {
            get
            {
                return Item["Description"];
            }

            set
            {
                Item["Description"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the ExternalId
        /// </summary>
        public string ExternalId
        {
            get
            {
                return Item["ExternalId"];
            }

            set
            {
                Item["ExternalId"] = value;
            }
        }

        /// <summary>
        /// Gets a property category link
        /// </summary>
        /// <returns>A Category link</returns>
        public string GetLink()
        {
            return Links.LinkManager.GetDynamicUrl(Item).TrimEnd('/');
        }

        /// <summary>
        /// Gets or sets the Name
        /// </summary>
        public string Name
        {
            get
            {
                return Item.Name;
            }

            set
            {
                Item.Name = value;
            }
        }

        /// <summary>
        /// Gets the description as an html string
        /// </summary>
        public HtmlString DescriptionRender
        {
            get
            {
                return PageContext.Current.HtmlHelper.Sitecore().Field("Description", Item);
            }
        }

        /// <summary>
        /// Gets the description as a html string
        /// </summary>
        public List<MediaItem> Images
        {
            get
            {
                if (_images != null)
                {
                    return _images;
                }

                _images = new List<MediaItem>();

                MultilistField field = Item.Fields["Images"];

                if (field != null)
                {
                    foreach (var id in field.TargetIDs)
                    {
                        MediaItem mediaItem = Item.Database.GetItem(id);
                        _images.Add(mediaItem);
                    }
                }

                return _images;
            }
        }

        /// <summary>
        /// Gets or sets the list of facets
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is the desired behavior")]
        public IEnumerable<CommerceQueryFacet> ChildProductFacets
        {
            get;
            protected set;
        }

        /// <summary>
        /// Gets or sets the list of sortable fields
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is the desired behavior")]
        public IEnumerable<CommerceQuerySort> SortFields
        {
            get;
            protected set;
        }

        /// <summary>
        /// Gets or sets the list of child products
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is the desired behavior")]
        public List<Item> ChildProducts
        {
            get;
            protected set;
        }

        /// <summary>
        /// Gets or sets the pagination details for this category
        /// </summary>
        public PaginationModel Pagination { get; set; }

        /// <summary>
        /// Gets the context for the current view
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        protected ViewContext CurrentViewContext
        {
            get
            {
                return ContextService.Get().GetCurrentOrDefault<ViewContext>();
            }
        }

        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, ProductSearchResults products, IEnumerable<CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 0;

            if (products != null)
            {
                ChildProducts = products.Products;
                ChildProductFacets = products.Facets;
                if (itemsPerPage > products.Products.Count)
                {
                    itemsPerPage = products.Products.Count;
                }
                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalProductCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalProductCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var gulp = require('gulp');
// Load all gulp- node modules
var $ = require('gulp-load-plugins')();
var pkg = require('./package.json');

// Load tasks
var watchifyJSApps = require('./tasks/watchify');
//var watchifyJSWorkers = require('./tasks/watchify-workers');
var minifyJSApps = require('./tasks/minify');

gulp.task('watchify-js-apps', watchifyJSApps);
//gulp.task('watchify-js-workers', watchifyJSWorkers);
gulp.task('minify-js-apps', minifyJSApps);

// watch for changes to build apps using gulp-watch so we can pick up changes
// for any new files.
// watchify-js-apps takes care of watching for src changes
gulp.task('watch-js-apps', function (done) {
    $.watch(pkg.jstest.js.buildDir + '**/*_app.js', function () {
        gulp.start('minify-js-apps', done);
    });
});

gulp.task('default', [
  'server',
  'watchify-js-apps',
  //'watchify-js-workers',
  'watch-js-apps'
]);

gulp.task('server', function (cb) {
  var started = false;

    $.nodemon({
        script: 'index.js',
        watch: ['index.js'],
        //ext: 'js html jade'
    }).on('start', function () {
      if (!started) {
        cb();

        started = true;
      }
    });
});


text:
'use strict';
const fileType = require('file-type');
const isStream = require('is-stream');
const tarStream = require('tar-stream');

module.exports = () => input => {
	if (!Buffer.isBuffer(input) && !isStream(input)) {
		return Promise.reject(new TypeError(`Expected a Buffer or Stream, got ${typeof input}`));
	}

	if (Buffer.isBuffer(input) && (!fileType(input) || fileType(input).ext !== 'tar')) {
		return Promise.resolve([]);
	}

	const extract = tarStream.extract();
	const files = [];

	extract.on('entry', (header, stream, cb) => {
		const chunk = [];

		stream.on('data', data => chunk.push(data));
		stream.on('end', () => {
			const file = {
				data: Buffer.concat(chunk),
				mode: header.mode,
				mtime: header.mtime,
				path: header.name,
				type: header.type
			};

			if (header.type === 'symlink' || header.type === 'link') {
				file.linkname = header.linkname;
			}

			files.push(file);
			cb();
		});
	});

	const promise = new Promise((resolve, reject) => {
		extract.on('finish', () => resolve(files));
		extract.on('error', reject);
	});

	extract.then = promise.then.bind(promise);
	extract.catch = promise.catch.bind(promise);

	if (Buffer.isBuffer(input)) {
		extract.end(input);
	} else {
		input.pipe(extract);
	}

	return extract;
};


text:
module.exports = (api) => {
  api.cache(true);

  return {
    compact: true,
    sourceType: 'unambiguous',
    presets: [
      ['@babel/preset-env', {
        modules: false,
      }],
      '@babel/preset-react',
    ],
    plugins: [
      'lodash',
      '@babel/plugin-proposal-class-properties',
      ['@babel/plugin-proposal-object-rest-spread', {
        loose: true,
      }],
      ['@babel/plugin-transform-spread', {
        loose: true,
      }],
      '@babel/plugin-proposal-export-namespace-from',
      '@babel/plugin-proposal-export-default-from',
      'transform-export-extensions',
      ['@babel/plugin-syntax-dynamic-import', {
        loose: true,
      }],
      ['module-resolver', {
        cwd: 'packagejson',
        alias: {
          Components: './components',
          Config: './config',
          Extensions: './extensions',
          Pages: './pages',
        },
      }],
      ['@babel/plugin-transform-runtime', {
        helpers: false,
        regenerator: true,
      }],
    ],
    env: {
      test: {
        presets: [
          '@babel/preset-env',
          '@babel/preset-react',
        ],
      },
      development: {
        plugins: [
          'react-hot-loader/babel',
        ],
      },
      production: {
        plugins: [
          'transform-react-remove-prop-types',
        ],
      },
    },
  };
};


text:
package com.amazonaws.services.simpleworkflow.model;

import java.io.Serializable;

/**
 *

 * Provides details of the WorkflowExecutionCompleted event.
 *

 */
public class WorkflowExecutionCompletedEventAttributes implements Serializable,
        Cloneable {

    /**
     *

     * The result produced by the workflow execution upon successful completion.
     *

     */
    private String result;
    /**
     *

     * The ID of the DecisionTaskCompleted event corresponding to
     * the decision task that resulted in the
     * CompleteWorkflowExecution decision to complete this
     * execution. This information can be useful for diagnosing problems by
     * tracing back the chain of events leading up to this event.
     *

     */
    private Long decisionTaskCompletedEventId;

    /**
     *

     * The result produced by the workflow execution upon successful completion.
     *

     *
     * @param result
     *        The result produced by the workflow execution upon successful
     *        completion.
     */

    public void setResult(String result) {
        this.result = result;
    }

    /**
     *

     * The result produced by the workflow execution upon successful completion.
     *

     *
     * @return The result produced by the workflow execution upon successful
     *         completion.
     */

    public String getResult() {
        return this.result;
    }

    /**
     *

     * The result produced by the workflow execution upon successful completion.
     *

     *
     * @param result
     *        The result produced by the workflow execution upon successful
     *        completion.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public WorkflowExecutionCompletedEventAttributes withResult(String result) {
        setResult(result);
        return this;
    }

    /**
     *

     * The ID of the DecisionTaskCompleted event corresponding to
     * the decision task that resulted in the
     * CompleteWorkflowExecution decision to complete this
     * execution. This information can be useful for diagnosing problems by
     * tracing back the chain of events leading up to this event.
     *

     *
     * @param decisionTaskCompletedEventId
     *        The ID of the DecisionTaskCompleted event
     *        corresponding to the decision task that resulted in the
     *        CompleteWorkflowExecution decision to complete this
     *        execution. This information can be useful for diagnosing problems
     *        by tracing back the chain of events leading up to this event.
     */

    public void setDecisionTaskCompletedEventId(
            Long decisionTaskCompletedEventId) {
        this.decisionTaskCompletedEventId = decisionTaskCompletedEventId;
    }

    /**
     *

     * The ID of the DecisionTaskCompleted event corresponding to
     * the decision task that resulted in the
     * CompleteWorkflowExecution decision to complete this
     * execution. This information can be useful for diagnosing problems by
     * tracing back the chain of events leading up to this event.
     *

     *
     * @return The ID of the DecisionTaskCompleted event
     *         corresponding to the decision task that resulted in the
     *         CompleteWorkflowExecution decision to complete this
     *         execution. This information can be useful for diagnosing problems
     *         by tracing back the chain of events leading up to this event.
     */

    public Long getDecisionTaskCompletedEventId() {
        return this.decisionTaskCompletedEventId;
    }

    /**
     *

     * The ID of the DecisionTaskCompleted event corresponding to
     * the decision task that resulted in the
     * CompleteWorkflowExecution decision to complete this
     * execution. This information can be useful for diagnosing problems by
     * tracing back the chain of events leading up to this event.
     *

     *
     * @param decisionTaskCompletedEventId
     *        The ID of the DecisionTaskCompleted event
     *        corresponding to the decision task that resulted in the
     *        CompleteWorkflowExecution decision to complete this
     *        execution. This information can be useful for diagnosing problems
     *        by tracing back the chain of events leading up to this event.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public WorkflowExecutionCompletedEventAttributes withDecisionTaskCompletedEventId(
            Long decisionTaskCompletedEventId) {
        setDecisionTaskCompletedEventId(decisionTaskCompletedEventId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getResult() != null)
            sb.append("Result: " + getResult() + ",");
        if (getDecisionTaskCompletedEventId() != null)
            sb.append("DecisionTaskCompletedEventId: "
                    + getDecisionTaskCompletedEventId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof WorkflowExecutionCompletedEventAttributes == false)
            return false;
        WorkflowExecutionCompletedEventAttributes other = (WorkflowExecutionCompletedEventAttributes) obj;
        if (other.getResult() == null ^ this.getResult() == null)
            return false;
        if (other.getResult() != null
                && other.getResult().equals(this.getResult()) == false)
            return false;
        if (other.getDecisionTaskCompletedEventId() == null
                ^ this.getDecisionTaskCompletedEventId() == null)
            return false;
        if (other.getDecisionTaskCompletedEventId() != null
                && other.getDecisionTaskCompletedEventId().equals(
                        this.getDecisionTaskCompletedEventId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getResult() == null) ? 0 : getResult().hashCode());
        hashCode = prime
                * hashCode
                + ((getDecisionTaskCompletedEventId() == null) ? 0
                        : getDecisionTaskCompletedEventId().hashCode());
        return hashCode;
    }

    @Override
    public WorkflowExecutionCompletedEventAttributes clone() {
        try {
            return (WorkflowExecutionCompletedEventAttributes) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
<?php
/**
 * PHPTAL templating engine
 *
 * PHP Version 5
 *
 * @category HTML
 * @package  PHPTAL
 * @author   Laurent Bedubourg <lbedubourg@motion-twin.com>
 * @author   Kornel Lesiński <kornel@aardvarkmedia.co.uk>
 * @license  http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
 * @version  SVN: $Id$
 * @link     http://phptal.org/
 */
/**
 * TAL Specifications 1.4
 *
 *      argument ::= (['text'] | 'structure') expression
 *
 *  Default behaviour : text
 *
 *      Title
 *      Title
 *
 *      This element is a comment.
 *
 *
 *
 * @package PHPTAL
 * @subpackage Php.attribute.tal
 * @author Laurent Bedubourg <lbedubourg@motion-twin.com>
 */
class PHPTAL_Php_Attribute_TAL_Replace
extends PHPTAL_Php_Attribute
implements PHPTAL_Php_TalesChainReader
{
    public function before(PHPTAL_Php_CodeWriter $codewriter)
    {
        // tal:replace="" => do nothing and ignore node
        if (trim($this->expression) == "") {
            return;
        }

        $expression = $this->extractEchoType($this->expression);
        $code = $codewriter->evaluateExpression($expression);

        // chained expression
        if (is_array($code)) {
            return $this->replaceByChainedExpression($codewriter, $code);
        }

        // nothing do nothing
        if ($code == PHPTAL_Php_TalesInternal::NOTHING_KEYWORD) {
            return;
        }

        // default generate default tag content
        if ($code == PHPTAL_Php_TalesInternal::DEFAULT_KEYWORD) {
            return $this->generateDefault($codewriter);
        }

        // replace tag with result of expression
        $this->doEchoAttribute($codewriter, $code);
    }

    public function after(PHPTAL_Php_CodeWriter $codewriter)
    {
    }

    /**
     * support expressions like "foo | bar"
     */
    private function replaceByChainedExpression(PHPTAL_Php_CodeWriter $codewriter, $expArray)
    {
        $executor = new PHPTAL_Php_TalesChainExecutor(
            $codewriter, $expArray, $this
        );
    }

    public function talesChainNothingKeyword(PHPTAL_Php_TalesChainExecutor $executor)
    {
        $executor->continueChain();
    }

    public function talesChainDefaultKeyword(PHPTAL_Php_TalesChainExecutor $executor)
    {
        $executor->doElse();
        $this->generateDefault($executor->getCodeWriter());
        $executor->breakChain();
    }

    public function talesChainPart(PHPTAL_Php_TalesChainExecutor $executor, $exp, $islast)
    {
        if (!$islast) {
            $var = $executor->getCodeWriter()->createTempVariable();
            $executor->doIf('!phptal_isempty('.$var.' = '.$exp.')');
            $this->doEchoAttribute($executor->getCodeWriter(), $var);
            $executor->getCodeWriter()->recycleTempVariable($var);
        } else {
            $executor->doElse();
            $this->doEchoAttribute($executor->getCodeWriter(), $exp);
        }
    }

    /**
     * don't replace - re-generate default content
     */
    private function generateDefault(PHPTAL_Php_CodeWriter $codewriter)
    {
        $this->phpelement->generateSurroundHead($codewriter);
        $this->phpelement->generateHead($codewriter);
        $this->phpelement->generateContent($codewriter);
        $this->phpelement->generateFoot($codewriter);
        $this->phpelement->generateSurroundFoot($codewriter);
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * All queries related to profiles
 */
class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton
{
    protected function __construct()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);

        parent::__construct();
    }

    /**
     * Prevent cloning the instance
     */
    public function __clone()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
    }

    /**
     * Get singleton instance of the class
     */
    public static function getInstance()
    {
        if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
            $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolProfileQuery();

        return $GLOBALS['bxDolClasses'][__CLASS__];
    }

    /**
     * Get all account profiles.
     * @param  string  $iAccountId account id
     * @return profile array
     */
    public function getProfilesByAccount ($iAccountId)
    {
        if (!$iAccountId)
            return array();

        $oAccountQuery = BxDolAccountQuery::getInstance();
        $aAccountInfo = $oAccountQuery->getInfoById($iAccountId);

        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? ORDER BY `id` = ? DESC", $iAccountId, $aAccountInfo['profile_id']);
        return $this->getAllWithKey($sSql, 'id');
    }

    /**
     * Get profile by content id, type and account.
     * @param  string $iAccountId account id
     * @return array  if aprofile ids, key is profile id
     */
    public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId)
    {
        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? AND `type` = ? AND `content_id` = ?", $iAccountId, $sType, $iContentId);
        return $this->getRow($sSql);
    }

    /**
     * Get profile by content id and type.
     * @param  string $iAccountId account id
     * @return array  if aprofile ids, key is profile id
     */
    public function getProfileByContentAndType ($iContentId, $sType, $bClearCache = false)
    {
        $sKey = 'BxDolProfileQuery::getProfileByContentAndType' . $iContentId . $sType;
        if ($bClearCache)
            $this->cleanMemory($sKey);

        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `content_id` = ? AND `type` = ?", $iContentId, $sType);
        $mixedResult = $this->fromMemory($sKey, 'getRow', $sSql);
        if (!$mixedResult)
            $this->cleanMemory($sKey);
        return $mixedResult;
    }

    public function getConnectedProfilesByType ($aSqlParts, $sType, $iStart, $iLimit)
    {
        if(empty($aSqlParts['join']))
            return array();

        $aBindings = array();

        $sSelectClause = '';
        if(!empty($aSqlParts['fields']))
            foreach($aSqlParts['fields'] as $sName => $sField)
                $sSelectClause .= ', ' . $sField;

        $sWhereClause = '';
        if(!empty($sType)) {
            $sWhereClause = ' AND `sys_profiles`.`type`=:type';

            $aBindings['type'] = $sType;
        }

        $sOrderClause = '';
        if(!empty($aSqlParts['fields']['added']))
            $sOrderClause = ' ORDER BY ' . $aSqlParts['fields']['added'] . ' DESC';

        $sLimitClause = '';
        if(!empty($iLimit))
            $sLimitClause = $this->prepareAsString(' LIMIT ?, ?', $iStart, $iLimit);

        return $this->getAllWithKey("SELECT `sys_profiles`.*" . $sSelectClause . " FROM `sys_profiles` " . $aSqlParts['join'] . " WHERE 1" . $sWhereClause . $sOrderClause . $sLimitClause, 'id', $aBindings);
    }

    /**
     * Insert account and content id association. Also if currect profile id is not defined - it updates current profile id in account.
     * @param $iAccountId account id
     * @param $iContentId content id
     * @param $sStatus profile status
     * @param $sType profile content type
     * @return inserted profile's id
     */
    public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system')
    {
        $sSql = $this->prepare("INSERT INTO `sys_profiles` SET `account_id` = ?, `type` = ?, `content_id` = ?, `status` = ?", $iAccountId, $sType, $iContentId, $sStatus);
        if (!$this->query($sSql))
            return false;
        $iProfileId = $this->lastId();
        $this->getCurrentProfileByAccount($iAccountId); // it updates current profile id automatically if it is not defined
        return $iProfileId;
    }

    /**
     * Update profile's status
     * @param $iProfileId profile id
     * @param $sStatus profile status
     * @return true on success or false otherwise
     */
    public function changeStatus ($iProfileId, $sStatus)
    {
        return $this->_updateField ($iProfileId, 'status', $sStatus);
    }

    /**
     * Get current account profile.
     * @param  string  $iAccountId account id
     * @return current account's profile id
     */
    public function getCurrentProfileByAccount ($iAccountId, $bClearCache = false)
    {
        $sKey = 'BxDolProfileQuery::getCurrentProfileByAccount' . $iAccountId;
        if ($bClearCache)
            $this->cleanMemory($sKey);

        $sSql = $this->prepare("SELECT `profile_id` FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iAccountId);
        $iProfileId = $this->fromMemory($sKey, 'getOne', $sSql);
        if (!$iProfileId) {
            $this->cleanMemory($sKey);
            $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? LIMIT 1", $iAccountId);
            $iProfileId = $this->getOne($sSql);
            if (!$iProfileId)
                return false;

            if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
                return false;
        }
        return $iProfileId;
    }

    /**
     * Get profile by specified field name and value.
     * It is for internal usage only.
     * Use other funtions to get profile info, like getInfoById, etc.
     * @param  string $sField database field name
     * @param  mixed  $sValue database field value
     * @return array  with porfile info
     */
    protected function _getDataByField ($sField, $sValue)
    {
        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
        return $this->getRow($sSql);
    }

    /**
     * get profile id by id
     */
    public function getIdById($iId, $bClearCache = false)
    {
        $sKey = 'BxDolProfileQuery::getIdById' . $iId;
        if ($bClearCache)
            $this->cleanMemory($sKey);

        $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iId);
        $mixedResult = $this->fromMemory($sKey, 'getOne', $sSql);
        if (!$mixedResult)
            $this->cleanMemory($sKey);
        return $mixedResult;
    }

    /**
     * get account info by profile id
     */
    public function getAccountInfoByProfileId($iId)
    {
        $sSql = $this->prepare("SELECT `a`.* FROM `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON (`p`.`account_id` = `a`.`id`) WHERE `p`.`id` = ? LIMIT 1", $iId);
        return $this->getRow($sSql);
    }

    /**
     * get account email by profile id
     */
    public function getEmailById($iId)
    {
        $a = $this->getAccountInfoByProfileId($iId);
        if (!$a || empty($a['email']))
            return false;
        return $a['email'];
    }

    /**
     * Get profile info by id
     * @param  int   $iID profile id
     * @return array with profile info
     */
    public function getInfoById( $iID )
    {
        return $this->_getDataByField('id', (int)$iID);
    }

	/**
     * Is profile online by id
     * @param  int $iId profile id
     * @return profile online status
     */
    public function isOnline($iId)
    {
        $sSql = $this->prepare("SELECT
        		`tp`.`id`
        	FROM `sys_profiles` AS `tp`
        	INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
        	INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
        	WHERE
        		`tp`.`id` = ? AND
        		`ta`.`profile_id`=`tp`.`id` AND
        		`ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)
        	LIMIT 1", $iId, (int)getParam('sys_account_online_time'));
        return (int)$this->getOne($sSql) > 0;
    }

    /**
     * Get online profiles count
     * @return online profiles count
     */
    public function getOnlineCount()
    {
        $sSql = $this->prepare("SELECT
        		COUNT(`tp`.`id`)
        	FROM `sys_profiles` AS `tp`
        	INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
        	INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
        	WHERE
        		`ta`.`profile_id`=`tp`.`id` AND
        		`ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)", (int)getParam('sys_account_online_time'));
        return (int)$this->getOne($sSql);
    }

    /**
     * Get profile field by specified field name and value.
     * In most cases it is for internal usage only.
     * Use other funtions to get profile info, like getIdByEmail, etc.
     * @param  string    $sFieldRequested database field name to return
     * @param  string    $sFieldSearch    database field name to search for
     * @param  mixed     $sValue          database field value
     * @return specified profile field value
     */
    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
    {
        $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
        return $this->getOne($sSql);
    }

    /**
     * Update some field by profile id
     * In most cases it is for internal usage only.
     * Use other funtions to get profile info, like updateLogged, etc.
     * @param  string    $sFieldRequested database field name to return
     * @param  string    $sFieldSearch    database field name to search for
     * @param  mixed     $sValue          database field value
     * @return specified profile field value
     */
    protected function _updateField ($iId, $sFieldForUpdate, $sValue)
    {
        $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
        return $this->query($sSql);
    }

    /**
     * Delete profile info by id
     * @param  int      $iID profile id
     * @return affected rows
     */
    public function delete($iID)
    {
        $aInfo = $this->getInfoById($iID);
        $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
        if ($res = $this->query($sSql)) {
            $this->getProfileByContentAndType($aInfo['content_id'], $aInfo['type'], true);
            $this->getCurrentProfileByAccount($aInfo['account_id'], true);
            $this->getIdById($iID, true);
        }
        return $res;
    }

    /**
     * Reset deleted profile ids and assign system profile ids.
     * Should be called after profiles module deletion.
     * It can be called automatically if
     * @code
     * 'process_deleted_profiles' => 1
     * @endcode
     * is specified in module config.php file in 'uninstall' section.
     */
    public function processDeletedProfiles ()
    {
        $bResult = true;

        // reset deleted profiles
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` LEFT OUTER JOIN `sys_profiles` AS `p` ON `a`.`profile_id`=`p`.`id` SET `a`.`profile_id`='0' WHERE `p`.`id` IS NULL") !== false;

        // try to assign another non-system profile to reset accounts
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`<>'system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;

        // assign system profile to reset accounts
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`='system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;

        return $bResult;
    }
}

/** @} */


text:
MTI_METAMACRO_CONCAT_(A, B)

#define MTI_METAMACRO_CONCAT_(A, B) A ## B

#define MTI_DEFER \
try {} @finally {} \
__strong MTIDeferBlock MTI_METAMACRO_CONCAT(MTIExitBlock_, __LINE__) __attribute__((cleanup(MTIExecuteCleanupBlock), unused)) = ^

typedef void (^MTIDeferBlock)(void);

FOUNDATION_EXPORT void MTIExecuteCleanupBlock (__strong MTIDeferBlock *block);


text:
package au.com.gridstone.grex;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import static org.assertj.core.api.Assertions.assertThat;

public class FileIODelegateTest {

    @Rule
    public TemporaryFolder tmpDir = new TemporaryFolder();

    @Test
    public void testGetReader_NonExistentFile() throws Exception {
        IODelegate delegate = new FileIODelegate(tmpDir.newFolder());

        Reader ret = delegate.getReader("non-existent");

        assertThat(ret).isNull();
    }

    @Test
    public void testGetReaderReturnsFileReader() throws Exception {
        tmpDir.newFile("TestKey");
        Reader ret = new FileIODelegate(tmpDir.getRoot()).getReader("TestKey");

        assertThat(ret).isInstanceOf(FileReader.class);
    }

    @Test
    public void testGetWriterReturnsFileWriter() throws Exception {
        tmpDir.newFile("TestKey");
        Writer ret = new FileIODelegate(tmpDir.getRoot()).getWriter("TestKey");

        assertThat(ret).isInstanceOf(FileWriter.class);
    }

    @Test
    public void testWriteDataThenClear() throws IOException {

        final FileIODelegate delegate =
                new FileIODelegate(tmpDir.getRoot());

        delegate.getWriter("TestKey").append("Test data").close();

        boolean ret = delegate.clear("TestKey");

        assertThat(ret).isTrue();

        assertThat(delegate.getReader("TestKey")).isNull();
    }
}


text:
require "seekr/client"
require "seekr/configuration"
require "seekr/errors"
require "seekr/monitor"
require "seekr/occurrence"
require "seekr/report"
require "seekr/version"

require 'active_support/core_ext/time'

Time.zone = "Brasilia"

module Seekr

  def self.configure(&block)
    yield configuration
  end

  def self.configuration
    @configuration ||= Seekr::Configuration.new
  end

  def self.api_key
    configuration.api_key
  end

  def self.api_secret
    configuration.api_secret
  end

  def self.reset
    @configuration = nil
  end
end


text:
package de.felixbruns.jotify.gui.util;

public class JotifyLoginCredentials {
	private String  username;
	private String  password;
	private boolean remember;

	public JotifyLoginCredentials(String username, char[] password){
		this(username, password, false);
	}

	public JotifyLoginCredentials(String username, char[] password, boolean remember){
		this(username, new String(password), remember);
	}

	public JotifyLoginCredentials(String username, String password){
		this(username, password, false);
	}

	public JotifyLoginCredentials(String username, String password, boolean remember){
		this.username = username;
		this.password = password;
		this.remember = remember;
	}

	public String getUsername(){
		return this.username;
	}

	public void setUsername(String username){
		this.username = username;
	}

	public String getPassword(){
		return this.password;
	}

	public void setPassword(String password){
		this.password = password;
	}

	public boolean getRemember(){
		return this.remember;
	}

	public void setRemember(boolean remember){
		this.remember = remember;
	}
}


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

<title>Uses of Package org.security.crypt.x509.types</title>
<meta name="date" content="2014-09-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.security.crypt.x509.types

Packages that use org.security.crypt.x509.types

Package
Description

org.security.crypt.x509

http://en.wikipedia.org/wiki/X.509

org.security.crypt.x509.types

http://en.wikipedia.org/wiki/X.509

Classes in org.security.crypt.x509.types used by org.security.crypt.x509

Class and Description

AccessDescriptionList

Representation of the SEQUENCE of AccessDescription types that
 is the value of the AuthorityInformationAccess extension field
 defined in section 4.2.2.1 of RFC 2459.

AttributeType

Describes the registered values of AttributeType that may appear in a
 RelativeDistinguishedName (RDN) as defined in section 2 of RFC 2253.

AuthorityKeyIdentifier

Representation of the AuthorityKeyIdentifier type defined in
 section 4.2.1.1 of RFC 2459.

BasicConstraints

Representation of the BasicConstraints type defined in section
 4.2.1.10 of RFC 2459.

DistributionPointList

Representation of the SEQUENCE of DistributionPoint types that
 are the value of the CRLDistributionPoints extension field
 described in section 4.2.1.14 of RFC 2459.

GeneralName

Representation of the GeneralName type defined in section
 4.2.1.7 of RFC 2459.

GeneralNameList

Representation of the GeneralNames type defined in section
 4.2.1.7 of RFC 2459, which simply stores a list of GeneralName items.

GeneralNameType

Representation of the options in the CHOICE element describing various
 categories of the GeneralName type defined in section 4.2.1.7 of
 RFC 2459.

KeyIdentifier

Friendly representation of an OCTET STRING representing key identifier data
 as described in section 4.2.1.1 of RFC 2459.

KeyPurposeIdList

Represents the sequence of KeyPurposeId types that are contained
 in the ExtendedKeyUsage extension field described in section
 4.2.1.13 of RFC 2459.

KeyUsage

Representation of the KeyUsage type defined in section 4.2.1.3
 of RFC 2459.

NoticeReference

Representation of the NoticeReference type defined in section
 4.2.1.5 of RFC 2459.

PolicyInformation

Representation of the PolicyInformation type defined in section
 4.2.1.5 of RFC 2459.

PolicyInformationList

Stores a list of PolicyInformation objects that could represent the
 data in the CertificatePolicies extension field defined in
 section 4.2.1.5 of RFC 2459.

PolicyQualifierInfo

Representation of the PolicyQualifierInfo type defined in
 section 4.2.1.5 of RFC 2459.

RelativeDistinguishedName

Representation of RelativeDistinguishedName type described in section 2 of
 RFC 2253.

UserNotice

Representation of the UserNotice type defined in section 4.2.1.5
 of RFC 2459.

Classes in org.security.crypt.x509.types used by org.security.crypt.x509.types

Class and Description

AbstractList

Base class for all types that simply contain collections of other types.

AccessDescription

Representation of the AccessDescription type described in
 section 4.2.2.1 of RFC 2459.

AccessMethod

Enumeration of supported OIDs for the accessMethod field of the
 AccessDescription type described in section 4.2.2.1 of RFC 2459.

AttributeType

Describes the registered values of AttributeType that may appear in a
 RelativeDistinguishedName (RDN) as defined in section 2 of RFC 2253.

AttributeTypeAndValue

Representation of AttributeTypeAndValue type described in section 2 of RFC
 2253.

BitString

Represents a string of bits encoded into octets in network byte order.

DistributionPoint

Representation of the DistributionPoint type defined in section
 4.2.1.14 of RFC 2459.

GeneralName

Representation of the GeneralName type defined in section
 4.2.1.7 of RFC 2459.

GeneralNameList

Representation of the GeneralNames type defined in section
 4.2.1.7 of RFC 2459, which simply stores a list of GeneralName items.

GeneralNameType

Representation of the options in the CHOICE element describing various
 categories of the GeneralName type defined in section 4.2.1.7 of
 RFC 2459.

KeyIdentifier

Friendly representation of an OCTET STRING representing key identifier data
 as described in section 4.2.1.1 of RFC 2459.

KeyPurposeId

Represents the KeyPurposeId type described in section 4.2.1.13
 of RFC 2459, which is used to indicate extended key usage.

KeyUsageBits

Representation of the bit meanings in the KeyUsage BIT STRING
 type defined in section 4.2.1.3 of RFC 2459.

List

Interface describing a type that is simply a collection of other types.

NoticeReference

Representation of the NoticeReference type defined in section
 4.2.1.5 of RFC 2459.

PolicyInformation

Representation of the PolicyInformation type defined in section
 4.2.1.5 of RFC 2459.

PolicyQualifierInfo

Representation of the PolicyQualifierInfo type defined in
 section 4.2.1.5 of RFC 2459.

ReasonFlags

Representation of the ReasonFlags type defined in section
 4.2.1.14 of RFC 2459.

Reasons

Definitions of the meanings of the bits in the ReasonFlags BIT STRING
 defined in section 4.2.1.14 of RFC 2459.

RelativeDistinguishedName

Representation of RelativeDistinguishedName type described in section 2 of
 RFC 2253.

UserNotice

Representation of the UserNotice type defined in section 4.2.1.5
 of RFC 2459.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
@implementation SHCGRectUtils

CGRect CGRectX(CGRect rect, CGFloat x)
{
    rect.origin.x = x;
    return rect;
}

CGRect CGRectY(CGRect rect, CGFloat y)
{
    rect.origin.y = y;
    return rect;
}

CGRect CGRectOrigin(CGRect rect, CGPoint origin)
{
    rect.origin = origin;
    return rect;
}

CGRect CGRectXY(CGRect rect, CGFloat x, CGFloat y)
{
    rect.origin.x = x;
    rect.origin.y = y;
    return rect;
}

CGRect CGRectWidth(CGRect rect, CGFloat width)
{
    rect.size.width = width;
    return rect;
}

CGRect CGRectHeight(CGRect rect, CGFloat height)
{
    rect.size.height = height;
    return rect;
}

CGRect CGRectWidthHeight(CGRect rect, CGFloat width, CGFloat height)
{
    rect.size.width = width;
    rect.size.height = height;
    return rect;
}

CGRect CGRectSize(CGRect rect, CGSize size)
{
    rect.size = size;
    return rect;
}

@end


text:
"""
   Originally created by Burt Peterson
   Updated and maintained by Dustin Roeder (dmroeder@gmail.com)

   Copyright 2019 Dustin Roeder

   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.
"""

import plcConfig  # Info: tests\README.md - Setup test configuration file
import pylogix
import time
import unittest

from pylogix.lgx_response import Response
from pylogix.lgx_tag import Tag  # Need Classes for type checking
from Randomizer import Randomizer

class PylogixTests(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.comm = pylogix.PLC()
        self.r = Randomizer()

    def compare_bool(self, tag):
        # write false
        self.comm.Write(tag, 0)
        response = self.comm.Read(tag)
        self.assertEqual(response.Value, False, response.Status)
        # write true
        self.comm.Write(tag, 1)
        response = self.comm.Read(tag)
        self.assertEqual(response.Value, True, response.Status)

    def compare_tag(self, tag, value):
        self.comm.Write(tag, value)
        response = self.comm.Read(tag)
        self.assertEqual(response.Value, value, response.Status)

    def array_result(self, tagname, arraylen):
        response = self.comm.Read(tagname, arraylen)
        self.assertGreaterEqual(len(response.Value), arraylen, response.Status)

    def basic_fixture(self, prefix=''):
        self.compare_bool(prefix + 'BaseBool')
        self.compare_bool(prefix + 'BaseBits.0')
        self.compare_bool(prefix + 'BaseBits.31')
        self.compare_tag(prefix + 'BaseSINT', self.r.Sint())
        self.compare_tag(prefix + 'BaseINT', self.r.Int())
        self.compare_tag(prefix + 'BaseDINT', self.r.Dint())
        self.compare_tag(prefix + 'BaseLINT', self.r.Dint())
        self.compare_tag(prefix + 'BaseReal', self.r.Sint())
        self.compare_tag(prefix + 'BaseSTRING', self.r.String())
        self.compare_tag(prefix + 'BaseTimer.PRE', abs(self.r.Int()))

    def basic_array_fixture(self, prefix=''):
        self.compare_bool(prefix + 'BaseBoolArray[0]')
        self.compare_bool(prefix + 'BaseBoolArray[31]')
        self.compare_bool(prefix + 'BaseBITSArray[0].0')
        self.compare_bool(prefix + 'BaseBITSArray[0].31')
        self.compare_bool(prefix + 'BaseBITSArray[31].0')
        self.compare_bool(prefix + 'BaseBITSArray[31].31')
        self.compare_tag(prefix + 'BaseSINTArray[0]', self.r.Sint())
        self.compare_tag(prefix + 'BaseSINTArray[31]', self.r.Sint())
        self.compare_tag(prefix + 'BaseINTArray[0]', self.r.Int())
        self.compare_tag(prefix + 'BaseINTArray[31]', self.r.Int())
        self.compare_tag(prefix + 'BaseDINTArray[0]', self.r.Dint())
        self.compare_tag(prefix + 'BaseDINTArray[31]', self.r.Dint())
        self.compare_tag(prefix + 'BaseLINTArray[0]', self.r.Dint())
        self.compare_tag(prefix + 'BaseLINTArray[31]', self.r.Dint())
        self.compare_tag(prefix + 'BaseREALArray[0]', self.r.Sint())
        self.compare_tag(prefix + 'BaseREALArray[31]', self.r.Sint())
        self.compare_tag(prefix + 'BaseSTRINGArray[0]', self.r.String())
        self.compare_tag(prefix + 'BaseSTRINGArray[31]', self.r.String())
        self.compare_tag(prefix + 'BaseTimerArray[0].PRE', abs(self.r.Int()))
        self.compare_tag(prefix + 'BaseTimerArray[31].PRE', abs(self.r.Int()))

    def udt_basic_fixture(self, prefix=''):
        self.compare_bool(prefix + 'UDTBasic.b_BOOL')
        self.compare_bool(prefix + 'UDTBasic.b_BITS.0')
        self.compare_bool(prefix + 'UDTBasic.b_BITS.31')
        self.compare_tag(prefix + 'UDTBasic.b_SINT', self.r.Sint())
        self.compare_tag(prefix + 'UDTBasic.b_INT', self.r.Int())
        self.compare_tag(prefix + 'UDTBasic.b_DINT', self.r.Dint())
        self.compare_tag(prefix + 'UDTBasic.b_LINT', self.r.Dint())
        self.compare_tag(prefix + 'UDTBasic.b_REAL', self.r.Sint())
        self.compare_tag(prefix + 'UDTBasic.b_STRING', self.r.String())
        self.compare_tag('UDTBasic.b_Timer.PRE', abs(self.r.Int()))

    def udt_array_fixture_01(self, prefix=''):
        self.compare_bool(prefix + 'UDTArray.b_BOOL[0]')
        self.compare_bool(prefix + 'UDTArray.b_BOOL[31]')
        self.compare_bool(prefix + 'UDTArray.b_BITS[0].0')
        self.compare_bool(prefix + 'UDTArray.b_BITS[0].31')
        self.compare_bool(prefix + 'UDTArray.b_BITS[31].0')
        self.compare_bool(prefix + 'UDTArray.b_BITS[31].31')
        self.compare_tag(prefix + 'UDTArray.b_SINT[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray.b_SINT[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray.b_INT[0]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray.b_INT[31]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray.b_DINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray.b_DINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray.b_LINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray.b_LINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray.b_REAL[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray.b_REAL[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray.b_STRING[0]', self.r.String())
        self.compare_tag(prefix + 'UDTArray.b_STRING[31]', self.r.String())
        self.compare_tag(prefix + 'UDTArray.b_Timer[0].PRE', abs(self.r.Int()))
        self.compare_tag(prefix + 'UDTArray.b_Timer[31].PRE', abs(self.r.Int()))

    def udt_array_fixture_02(self, prefix=''):
        self.compare_bool(prefix + 'UDTArray2[0].b_BOOL[0]')
        self.compare_bool(prefix + 'UDTArray2[0].b_BOOL[31]')
        self.compare_bool(prefix + 'UDTArray2[0].b_BITS[0].0')
        self.compare_bool(prefix + 'UDTArray2[0].b_BITS[0].31')
        self.compare_bool(prefix + 'UDTArray2[0].b_BITS[31].0')
        self.compare_bool(prefix + 'UDTArray2[0].b_BITS[31].31')
        self.compare_tag(prefix + 'UDTArray2[0].b_SINT[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[0].b_SINT[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[0].b_INT[0]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray2[0].b_INT[31]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray2[0].b_DINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[0].b_DINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[0].b_LINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[0].b_LINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[0].b_REAL[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[0].b_REAL[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[0].b_STRING[0]', self.r.String())
        self.compare_tag(prefix + 'UDTArray2[0].b_STRING[31]', self.r.String())
        self.compare_tag(prefix + 'UDTArray2[0].b_Timer[0].PRE', abs(self.r.Int()))
        self.compare_tag(prefix + 'UDTArray2[0].b_Timer[31].PRE', abs(self.r.Int()))
        self.compare_bool(prefix + 'UDTArray2[31].b_BOOL[0]')
        self.compare_bool(prefix + 'UDTArray2[31].b_BOOL[31]')
        self.compare_bool(prefix + 'UDTArray2[31].b_BITS[0].0')
        self.compare_bool(prefix + 'UDTArray2[31].b_BITS[0].31')
        self.compare_bool(prefix + 'UDTArray2[31].b_BITS[31].0')
        self.compare_bool(prefix + 'UDTArray2[31].b_BITS[31].31')
        self.compare_tag(prefix + 'UDTArray2[31].b_SINT[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[31].b_SINT[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[31].b_INT[0]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray2[31].b_INT[31]', self.r.Int())
        self.compare_tag(prefix + 'UDTArray2[31].b_DINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[31].b_DINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[31].b_LINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[31].b_LINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTArray2[31].b_REAL[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[31].b_REAL[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTArray2[31].b_STRING[0]', self.r.String())
        self.compare_tag(prefix + 'UDTArray2[31].b_STRING[31]', self.r.String())
        self.compare_tag(prefix + 'UDTArray2[31].b_Timer[0].PRE', abs(self.r.Int()))
        self.compare_tag(
            prefix + 'UDTArray2[31].b_Timer[31].PRE', abs(self.r.Int()))

    def udt_combined_fixture(self, prefix=''):
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BOOL[0]')
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BOOL[31]')
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BITS[0].0')
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BITS[0].31')
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BITS[31].0')
        self.compare_bool(prefix + 'UDTCombined.c_Array.b_BITS[31].31')
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_SINT[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_SINT[31]', self.r.Sint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_INT[0]', self.r.Int())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_INT[31]', self.r.Int())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_DINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_DINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_LINT[0]', self.r.Dint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_LINT[31]', self.r.Dint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_REAL[0]', self.r.Sint())
        self.compare_tag(prefix + 'UDTCombined.c_Array.b_REAL[31]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombined.c_Array.b_STRING[0]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombined.c_Array.b_STRING[31]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombined.c_Array.b_Timer[0].PRE', abs(self.r.Int()))
        self.compare_tag(
            prefix + 'UDTCombined.c_Array.b_Timer[31].PRE', abs(self.r.Int()))

    def udt_combined_array_fixture(self, prefix=''):
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BOOL[0]')
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BOOL[31]')
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BITS[0].0')
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BITS[0].31')
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BITS[31].0')
        self.compare_bool(prefix + 'UDTCombinedArray[0].c_Array.b_BITS[31].31')
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_SINT[0]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_SINT[31]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_INT[0]', self.r.Int())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_INT[31]', self.r.Int())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_DINT[0]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_DINT[31]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_LINT[0]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_LINT[31]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_REAL[0]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_REAL[31]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_STRING[0]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_STRING[31]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_Timer[0].PRE',
            abs(self.r.Int()))
        self.compare_tag(
            prefix + 'UDTCombinedArray[0].c_Array.b_Timer[31].PRE',
            abs(self.r.Int()))
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BOOL[0]')
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BOOL[31]')
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BITS[0].0')
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BITS[0].31')
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BITS[31].0')
        self.compare_bool(prefix + 'UDTCombinedArray[9].c_Array.b_BITS[31].31')
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_SINT[0]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_SINT[31]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_INT[0]', self.r.Int())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_INT[31]', self.r.Int())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_DINT[0]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_DINT[31]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_LINT[0]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_LINT[31]', self.r.Dint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_REAL[0]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_REAL[31]', self.r.Sint())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_STRING[0]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_STRING[31]', self.r.String())
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_Timer[0].PRE',
            abs(self.r.Int()))
        self.compare_tag(
            prefix + 'UDTCombinedArray[9].c_Array.b_Timer[31].PRE',
            abs(self.r.Int()))

    def read_array_fixture(self, prefix=''):
        self.array_result('BaseBOOLArray[0]', 10)
        self.array_result('BaseSINTArray[0]', 10)
        self.array_result('BaseINTArray[0]', 10)
        self.array_result('BaseDINTArray[0]', 10)
        self.array_result('BaseLINTArray[0]', 10)
        self.array_result('BaseREALArray[0]', 10)
        self.array_result('BaseSTRINGArray[0]', 10)
        self.array_result('BaseBOOLArray[10]', 10)
        self.array_result('BaseSINTArray[10]', 10)
        self.array_result('BaseINTArray[10]', 10)
        self.array_result('BaseDINTArray[10]', 10)
        self.array_result('BaseLINTArray[10]', 10)
        self.array_result('BaseREALArray[10]', 10)
        self.array_result('BaseSTRINGArray[10]', 10)

    def multi_read_fixture(self, tags):
        response = self.comm.Read(tags)
        self.assertEqual(len(response), len(
            tags), 'Unable to read multiple tags!')

        for i in range(len(response)):
            self.assertEqual('Success', response[i].Status)

    def bool_list_fixture(self, length=8):
        bool_list = []
        for i in range(length):
            bool_list.append('BaseBOOLArray[{}]'.format(i))
        return bool_list

    def nemesis_fixture(self, tag, length):
        # test write BOOL array
        true_val = [1 for i in range(length)]
        false_val = [0 for i  in range(length)]

        # write array to 0
        self.comm.Write(tag, false_val)
        ret = self.comm.Read(tag, length).Value
        self.assertListEqual(ret, false_val, "Failed to write nemesis to 0")

        # write array to 1
        self.comm.Write(tag, true_val)
        ret = self.comm.Read(tag, length).Value
        self.assertListEqual(ret, true_val, "Failed to write nemesis to 1")

    def large_list_fixture(self):
            length = 50
            tags = ["Str{}".format(i) for i in range(length)]
            vals = [self.r.String() for i in range(length)]

            req = [[tags[i], vals[i]] for i in range(length)]
            self.comm.Write(req)

            ret = self.comm.Read(tags)
            read_vals = [r.Value for r in ret]

            self.assertListEqual(vals, read_vals, "Failed to write large list")

    def setUp(self):
        self.comm.IPAddress = plcConfig.plc_ip
        self.comm.ProcessorSlot = plcConfig.plc_slot
        self.comm.Micro800 = plcConfig.isMicro800

    @unittest.skipIf(plcConfig.isMicro800,'for Micro800')
    def test_basic(self):
        self.basic_fixture()
        self.basic_array_fixture()
        self.basic_fixture('PROGRAM:MainProgram.p')
        self.basic_array_fixture('PROGRAM:MainProgram.p')

    @unittest.skipIf(plcConfig.isMicro800,'for Micro800')
    def test_udt(self):
        self.udt_basic_fixture()
        self.udt_array_fixture_01()
        self.udt_array_fixture_02()
        self.udt_basic_fixture('PROGRAM:MainProgram.p')
        self.udt_array_fixture_01('PROGRAM:MainProgram.p')
        self.udt_array_fixture_02('PROGRAM:MainProgram.p')

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_combined(self):
        self.udt_combined_fixture()
        self.udt_combined_array_fixture()
        self.udt_combined_fixture('PROGRAM:MainProgram.p')
        self.udt_combined_array_fixture('PROGRAM:MainProgram.p')

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_array(self):
        self.read_array_fixture()
        self.read_array_fixture('PROGRAM:MainProgram.p')

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_multi_read(self):
        tags = ['BaseDINT', 'BaseINT', 'BaseSTRING']
        self.multi_read_fixture(tags)

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_bool_list(self):
        tags = self.bool_list_fixture(128)
        self.multi_read_fixture(tags)

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_nemesis_write(self):
        self.nemesis_fixture("Nemesis[0]", 64)

    @unittest.skipIf(plcConfig.isMicro800, 'for Micro800')
    def test_large_list(self):
        self.large_list_fixture()

    def test_discover(self):
        devices = self.comm.Discover()
        self.assertEqual(devices.Status, 'Success', devices.Status)

    @unittest.skipIf(plcConfig.isMicro800,'for Micro800')
    def test_time(self):
        self.comm.SetPLCTime()
        time = self.comm.GetPLCTime()
        self.assertEqual(time.Status, 'Success', time.Status)

    def test_get_tags(self):
        tags = self.comm.GetTagList()
        self.assertGreater(len(tags.Value), 1, tags.Status)

    def test_unexistent_tags(self):
        expected_msg = (plcConfig.isMicro800
            and 'Path destination unknown'
            or 'Path segment error'
            )
        response = self.comm.Read('DumbTag')
        self.assertEqual(
            response.Status, expected_msg, response.Status)
        write_response = self.comm.Write('DumbTag', 10)
        self.assertEqual(
            write_response.Status, expected_msg, write_response.Status)

    def test_lgx_tag_class(self):
        tags = self.comm.GetTagList()
        self.assertEqual(
            isinstance(
                tags.Value[0], Tag), True, "LgxTag not found in GetTagList")

    def test_response_class(self):
        one_bool = self.comm.Read('BaseBool')
        self.assertEqual(
            isinstance(one_bool, Response),
            True, "Reponse class not found in Read")
        bool_tags = ['BaseBool', 'BaseBits.0', 'BaseBits.31']
        booleans = self.comm.Read(bool_tags)
        self.assertEqual(
            isinstance(booleans[0], Response),
            True, "Reponse class not found in Multi Read")
        bool_write = self.comm.Write('BaseBool', 1)
        self.assertEqual(
            isinstance(bool_write, Response),
            True, "Reponse class not found in Write")

    @unittest.skipIf(plcConfig.isMicro800,'for Micro800')
    def test_program_list(self):
        programs = self.comm.GetProgramsList()
        self.assertEqual(programs.Status, 'Success', programs.Status)
        self.assertEqual(
            isinstance(programs, Response),
            True, "Reponse class not found in GetProgramsList")

    @unittest.skipIf(plcConfig.isMicro800,'for Micro800')
    def test_program_tag_list(self):
        program_tags = self.comm.GetProgramTagList('Program:MainProgram')
        self.assertEqual(program_tags.Status, 'Success', program_tags.Status)
        self.assertEqual(
            isinstance(program_tags, Response),
            True, "Reponse class not found in GetProgramTagList")
        self.assertEqual(
            isinstance(program_tags.Value[0], Tag),
            True, "LgxTag class not found in GetProgramTagList Value")

    def test_micro_800_init(self):
        self.assertFalse(pylogix.PLC().Micro800)
        self.assertFalse(pylogix.PLC(Micro800=False).Micro800)
        self.assertTrue(pylogix.PLC(Micro800=True).Micro800)

    def tearDown(self):
        self.comm.Close()

if __name__ == "__main__":
    unittest.main()