text:
/**
 * @file    hal_nand_lld.c
 * @brief   NAND Driver subsystem low level driver source.
 *
 * @addtogroup NAND
 * @{
 */

#include "hal.h"

#if (HAL_USE_NAND == TRUE) || defined(__DOXYGEN__)

/*===========================================================================*/
/* Driver local definitions.                                                 */
/*===========================================================================*/
#define NAND_DMA_CHANNEL                                                  \
  STM32_DMA_GETCHANNEL(STM32_NAND_DMA_STREAM,                             \
                       STM32_FSMC_DMA_CHN)

/**
 * @brief   Bus width of NAND IC.
 * @details Must be 8 or 16
 */
#if ! defined(STM32_NAND_BUS_WIDTH) || defined(__DOXYGEN__)
#define STM32_NAND_BUS_WIDTH        8
#endif

/**
 * @brief   DMA transaction width on AHB bus in bytes
 */
#define AHB_TRANSACTION_WIDTH       2

/*===========================================================================*/
/* Driver exported variables.                                                */
/*===========================================================================*/

/**
 * @brief   NAND1 driver identifier.
 */
#if STM32_NAND_USE_FSMC_NAND1 || defined(__DOXYGEN__)
NANDDriver NANDD1;
#endif

/**
 * @brief   NAND2 driver identifier.
 */
#if STM32_NAND_USE_FSMC_NAND2 || defined(__DOXYGEN__)
NANDDriver NANDD2;
#endif

/*===========================================================================*/
/* Driver local types.                                                       */
/*===========================================================================*/

/*===========================================================================*/
/* Driver local variables and types.                                         */
/*===========================================================================*/

/*===========================================================================*/
/* Driver local functions.                                                   */
/*===========================================================================*/

/**
 * @brief   Helper function.
 *
 * @notapi
 */
static void align_check(const void *ptr, uint32_t len) {
  osalDbgCheck((((uint32_t)ptr % AHB_TRANSACTION_WIDTH) == 0) &&
                         ((len % AHB_TRANSACTION_WIDTH) == 0) &&
                         (len >= AHB_TRANSACTION_WIDTH));
  (void)ptr;
  (void)len;
}

/**
 * @brief   Work around errata in STM32's FSMC core.
 * @details Constant output clock (if enabled) disappears when CLKDIV value
 *          sets to 1 (FMC_CLK period = 2 × HCLK periods) AND 8-bit async
 *          transaction generated on AHB. This workaround eliminates 8-bit
 *          transactions on bus when you use 8-bit memory. It suitable only
 *          for 8-bit memory (i.e. PWID bits in PCR register must be set
 *          to 8-bit mode).
 *
 * @notapi
 */
static void set_16bit_bus(NANDDriver *nandp) {
#if STM32_NAND_BUS_WIDTH
  nandp->nand->PCR |= FSMC_PCR_PWID_16;
#else
  (void)nandp;
#endif
}

static void set_8bit_bus(NANDDriver *nandp) {
#if STM32_NAND_BUS_WIDTH
  nandp->nand->PCR &= ~FSMC_PCR_PWID_16;
#else
  (void)nandp;
#endif
}

/**
 * @brief   Wakes up the waiting thread.
 *
 * @param[in] nandp  pointer to the @p NANDDriver object
 * @param[in] msg       wakeup message
 *
 * @notapi
 */
static void wakeup_isr(NANDDriver *nandp) {

  osalDbgCheck(nandp->thread != NULL);
  osalThreadResumeI(&nandp->thread, MSG_OK);
}

/**
 * @brief   Put calling thread in suspend and switch driver state
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 */
static void nand_lld_suspend_thread(NANDDriver *nandp) {

  osalThreadSuspendS(&nandp->thread);
}

/**
 * @brief   Caclulate ECCPS register value
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 */
static uint32_t calc_eccps(NANDDriver *nandp) {

  uint32_t i = 0;
  uint32_t eccps = nandp->config->page_data_size;

  eccps = eccps >> 9;
  while (eccps > 0){
    i++;
    eccps >>= 1;
  }

  return i << 17;
}

/*===========================================================================*/
/* Driver interrupt handlers.                                                */
/*===========================================================================*/

/**
 * @brief   Enable interrupts from NAND
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 *
 * @notapi
 */
static void nand_ready_isr_enable(NANDDriver *nandp) {

  nandp->nand->SR &= ~(FSMC_SR_IRS | FSMC_SR_ILS | FSMC_SR_IFS |
                                    FSMC_SR_ILEN | FSMC_SR_IFEN);
  nandp->nand->SR |= FSMC_SR_IREN;
}

/**
 * @brief   Disable interrupts from NAND
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 *
 * @notapi
 */
static void nand_ready_isr_disable(NANDDriver *nandp) {

  nandp->nand->SR &= ~FSMC_SR_IREN;
}

/**
 * @brief   Ready interrupt handler
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 *
 * @notapi
 */
static void nand_isr_handler(NANDDriver *nandp) {

  osalSysLockFromISR();

  osalDbgCheck(nandp->nand->SR & FSMC_SR_IRS); /* spurious interrupt happened */
  nandp->nand->SR &= ~FSMC_SR_IRS;

  switch (nandp->state){
  case NAND_READ:
    nandp->state = NAND_DMA_RX;
    dmaStartMemCopy(nandp->dma, nandp->dmamode, nandp->map_data, nandp->rxdata,
                    nandp->datalen/AHB_TRANSACTION_WIDTH);
    /* thread will be waked up from DMA ISR */
    break;

  case NAND_ERASE:      /* NAND reports about erase finish */
  case NAND_PROGRAM:    /* NAND reports about page programming finish */
  case NAND_RESET:      /* NAND reports about finished reset recover */
    nandp->state = NAND_READY;
    wakeup_isr(nandp);
    break;

  default:
    osalSysHalt("Unhandled case");
    break;
  }
  osalSysUnlockFromISR();
}

/**
 * @brief   DMA RX end IRQ handler.
 *
 * @param[in] nandp    pointer to the @p NANDDriver object
 * @param[in] flags    pre-shifted content of the ISR register
 *
 * @notapi
 */
static void nand_lld_serve_transfer_end_irq(NANDDriver *nandp, uint32_t flags) {
  /* DMA errors handling.*/
#if defined(STM32_NAND_DMA_ERROR_HOOK)
  if ((flags & (STM32_DMA_ISR_TEIF | STM32_DMA_ISR_DMEIF)) != 0) {
    STM32_NAND_DMA_ERROR_HOOK(nandp);
  }
#else
  (void)flags;
#endif

  osalSysLockFromISR();

  dmaStreamDisable(nandp->dma);

  switch (nandp->state){
  case NAND_DMA_TX:
    nandp->state = NAND_PROGRAM;
    nandp->map_cmd[0] = NAND_CMD_PAGEPROG;
    /* thread will be woken up from ready_isr() */
    break;

  case NAND_DMA_RX:
    nandp->state = NAND_READY;
    nandp->rxdata = NULL;
    nandp->datalen = 0;
    wakeup_isr(nandp);
    break;

  default:
    osalSysHalt("Unhandled case");
    break;
  }

  osalSysUnlockFromISR();
}

/*===========================================================================*/
/* Driver exported functions.                                                */
/*===========================================================================*/

/**
 * @brief   Low level NAND driver initialization.
 *
 * @notapi
 */
void nand_lld_init(void) {

  fsmc_init();

#if STM32_NAND_USE_FSMC_NAND1
  /* Driver initialization.*/
  nandObjectInit(&NANDD1);
  NANDD1.rxdata   = NULL;
  NANDD1.datalen  = 0;
  NANDD1.thread   = NULL;
  NANDD1.dma      = STM32_DMA_STREAM(STM32_NAND_DMA_STREAM);
  NANDD1.nand     = FSMCD1.nand1;
  NANDD1.map_data = (void *)FSMC_Bank2_MAP_COMMON_DATA;
  NANDD1.map_cmd  = (uint16_t *)FSMC_Bank2_MAP_COMMON_CMD;
  NANDD1.map_addr = (uint16_t *)FSMC_Bank2_MAP_COMMON_ADDR;
  NANDD1.bb_map   = NULL;
#endif /* STM32_NAND_USE_FSMC_NAND1 */

#if STM32_NAND_USE_FSMC_NAND2
  /* Driver initialization.*/
  nandObjectInit(&NANDD2);
  NANDD2.rxdata   = NULL;
  NANDD2.datalen  = 0;
  NANDD2.thread   = NULL;
  NANDD2.dma      = STM32_DMA_STREAM(STM32_NAND_DMA_STREAM);
  NANDD2.nand     = FSMCD1.nand2;
  NANDD2.map_data = (void *)FSMC_Bank3_MAP_COMMON_DATA;
  NANDD2.map_cmd  = (uint16_t *)FSMC_Bank3_MAP_COMMON_CMD;
  NANDD2.map_addr = (uint16_t *)FSMC_Bank3_MAP_COMMON_ADDR;
  NANDD2.bb_map   = NULL;
#endif /* STM32_NAND_USE_FSMC_NAND2 */
}

/**
 * @brief   Configures and activates the NAND peripheral.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 *
 * @notapi
 */
void nand_lld_start(NANDDriver *nandp) {

  bool b;
  uint32_t dmasize;
  uint32_t pcr_bus_width;

  if (FSMCD1.state == FSMC_STOP)
    fsmc_start(&FSMCD1);

  if (nandp->state == NAND_STOP) {
    b = dmaStreamAllocate(nandp->dma,
                          STM32_EMC_FSMC1_IRQ_PRIORITY,
                          (stm32_dmaisr_t)nand_lld_serve_transfer_end_irq,
                          (void *)nandp);
    osalDbgAssert(!b, "stream already allocated");

#if AHB_TRANSACTION_WIDTH == 4
    dmasize = STM32_DMA_CR_PSIZE_WORD | STM32_DMA_CR_MSIZE_WORD;
#elif AHB_TRANSACTION_WIDTH == 2
    dmasize = STM32_DMA_CR_PSIZE_HWORD | STM32_DMA_CR_MSIZE_HWORD;
#elif AHB_TRANSACTION_WIDTH == 1
    dmasize = STM32_DMA_CR_PSIZE_BYTE | STM32_DMA_CR_MSIZE_BYTE;
#else
#error "Incorrect AHB_TRANSACTION_WIDTH"
#endif

    nandp->dmamode = STM32_DMA_CR_CHSEL(NAND_DMA_CHANNEL) |
                     STM32_DMA_CR_PL(STM32_NAND_NAND1_DMA_PRIORITY) |
                     dmasize |
                     STM32_DMA_CR_DMEIE |
                     STM32_DMA_CR_TEIE |
                     STM32_DMA_CR_TCIE;

#if STM32_NAND_BUS_WIDTH == 8
    pcr_bus_width = FSMC_PCR_PWID_8;
#elif STM32_NAND_BUS_WIDTH == 16
    pcr_bus_width = FSMC_PCR_PWID_16;
#else
#error "Bus width must be 8 or 16 bits"
#endif
    nandp->nand->PCR = pcr_bus_width | calc_eccps(nandp) |
                       FSMC_PCR_PTYP_NAND | FSMC_PCR_PBKEN;
    nandp->nand->PMEM = nandp->config->pmem;
    nandp->nand->PATT = nandp->config->pmem;
    nandp->isr_handler = nand_isr_handler;
    nand_ready_isr_enable(nandp);
  }
}

/**
 * @brief   Deactivates the NAND peripheral.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 *
 * @notapi
 */
void nand_lld_stop(NANDDriver *nandp) {

  if (nandp->state == NAND_READY) {
    dmaStreamRelease(nandp->dma);
    nandp->nand->PCR &= ~FSMC_PCR_PBKEN;
    nand_ready_isr_disable(nandp);
    nandp->isr_handler = NULL;
  }
}

/**
 * @brief   Read data from NAND.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 * @param[out] data         pointer to data buffer
 * @param[in] datalen       size of data buffer in bytes
 * @param[in] addr          pointer to address buffer
 * @param[in] addrlen       length of address
 * @param[out] ecc          pointer to store computed ECC. Ignored when NULL.
 *
 * @notapi
 */
void nand_lld_read_data(NANDDriver *nandp, uint16_t *data, size_t datalen,
                        uint8_t *addr, size_t addrlen, uint32_t *ecc){

  align_check(data, datalen);

  nandp->state = NAND_READ;
  nandp->rxdata = data;
  nandp->datalen = datalen;

  set_16bit_bus(nandp);
  nand_lld_write_cmd(nandp, NAND_CMD_READ0);
  nand_lld_write_addr(nandp, addr, addrlen);
  osalSysLock();
  nand_lld_write_cmd(nandp, NAND_CMD_READ0_CONFIRM);
  set_8bit_bus(nandp);

  /* Here NAND asserts busy signal and starts transferring from memory
     array to page buffer. After the end of transmission ready_isr functions
     starts DMA transfer from page buffer to MCU's RAM.*/
  osalDbgAssert((nandp->nand->PCR & FSMC_PCR_ECCEN) == 0,
          "State machine broken. ECCEN must be previously disabled.");

  if (NULL != ecc){
    nandp->nand->PCR |= FSMC_PCR_ECCEN;
  }

  nand_lld_suspend_thread(nandp);
  osalSysUnlock();

  /* thread was woken up from DMA ISR */
  if (NULL != ecc){
    while (! (nandp->nand->SR & FSMC_SR_FEMPT))
      ;
    *ecc = nandp->nand->ECCR;
    nandp->nand->PCR &= ~FSMC_PCR_ECCEN;
  }
}

/**
 * @brief   Write data to NAND.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 * @param[in] data          buffer with data to be written
 * @param[in] datalen       size of data buffer in bytes
 * @param[in] addr          pointer to address buffer
 * @param[in] addrlen       length of address
 * @param[out] ecc          pointer to store computed ECC. Ignored when NULL.
 *
 * @return    The operation status reported by NAND IC (0x70 command).
 *
 * @notapi
 */
uint8_t nand_lld_write_data(NANDDriver *nandp, const uint16_t *data,
                size_t datalen, uint8_t *addr, size_t addrlen, uint32_t *ecc) {

  align_check(data, datalen);

  nandp->state = NAND_WRITE;

  set_16bit_bus(nandp);
  nand_lld_write_cmd(nandp, NAND_CMD_WRITE);
  osalSysLock();
  nand_lld_write_addr(nandp, addr, addrlen);
  set_8bit_bus(nandp);

  /* Now start DMA transfer to NAND buffer and put thread in sleep state.
     Tread will be woken up from ready ISR. */
  nandp->state = NAND_DMA_TX;
  osalDbgAssert((nandp->nand->PCR & FSMC_PCR_ECCEN) == 0,
          "State machine broken. ECCEN must be previously disabled.");

  if (NULL != ecc){
    nandp->nand->PCR |= FSMC_PCR_ECCEN;
  }

  dmaStartMemCopy(nandp->dma, nandp->dmamode, data, nandp->map_data,
                  datalen/AHB_TRANSACTION_WIDTH);

  nand_lld_suspend_thread(nandp);
  osalSysUnlock();

  if (NULL != ecc){
    while (! (nandp->nand->SR & FSMC_SR_FEMPT))
      ;
    *ecc = nandp->nand->ECCR;
    nandp->nand->PCR &= ~FSMC_PCR_ECCEN;
  }

  return nand_lld_read_status(nandp);
}

/**
 * @brief   Soft reset NAND device.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 *
 * @notapi
 */
void nand_lld_reset(NANDDriver *nandp) {

  nandp->state = NAND_RESET;

  set_16bit_bus(nandp);
  nand_lld_write_cmd(nandp, NAND_CMD_RESET);
  set_8bit_bus(nandp);

  osalSysLock();
  nand_lld_suspend_thread(nandp);
  osalSysUnlock();
}

/**
 * @brief   Erase block.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 * @param[in] addr          pointer to address buffer
 * @param[in] addrlen       length of address
 *
 * @return    The operation status reported by NAND IC (0x70 command).
 *
 * @notapi
 */
uint8_t nand_lld_erase(NANDDriver *nandp, uint8_t *addr, size_t addrlen) {

  nandp->state = NAND_ERASE;

  set_16bit_bus(nandp);
  nand_lld_write_cmd(nandp, NAND_CMD_ERASE);
  nand_lld_write_addr(nandp, addr, addrlen);
  osalSysLock();
  nand_lld_write_cmd(nandp, NAND_CMD_ERASE_CONFIRM);
  set_8bit_bus(nandp);

  nand_lld_suspend_thread(nandp);
  osalSysUnlock();

  return nand_lld_read_status(nandp);
}

/**
 * @brief   Send addres to NAND.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 * @param[in] len           length of address array
 * @param[in] addr          pointer to address array
 *
 * @notapi
 */
void nand_lld_write_addr(NANDDriver *nandp, const uint8_t *addr, size_t len) {
  size_t i = 0;

  for (i=0; i<len; i++)
    nandp->map_addr[i] = addr[i];
}

/**
 * @brief   Send command to NAND.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 * @param[in] cmd           command value
 *
 * @notapi
 */
void nand_lld_write_cmd(NANDDriver *nandp, uint8_t cmd) {
  nandp->map_cmd[0] = cmd;
}

/**
 * @brief   Read status byte from NAND.
 *
 * @param[in] nandp         pointer to the @p NANDDriver object
 *
 * @return    Status byte.
 *
 * @notapi
 */
uint8_t nand_lld_read_status(NANDDriver *nandp) {

  uint16_t status;

  set_16bit_bus(nandp);
  nand_lld_write_cmd(nandp, NAND_CMD_STATUS);
  set_8bit_bus(nandp);
  status = nandp->map_data[0];

  return status & 0xFF;
}

#endif /* HAL_USE_NAND */

/** @} */


text:
<?php

namespace Sylius\Component\Grid\Filtering;

use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Definition\Grid;
use Sylius\Component\Grid\Parameters;
use Sylius\Component\Registry\ServiceRegistryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class FiltersApplicator implements FiltersApplicatorInterface
{
    /**
     * @var ServiceRegistryInterface
     */
    private $filtersRegistry;

    /**
     * @param ServiceRegistryInterface $filtersRegistry
     */
    public function __construct(ServiceRegistryInterface $filtersRegistry)
    {
        $this->filtersRegistry = $filtersRegistry;
    }

    /**
     * {@inheritdoc}
     */
    public function apply(DataSourceInterface $dataSource, Grid $grid, Parameters $parameters)
    {
        if (!$parameters->has('criteria')) {
            return;
        }

        $criteria = $parameters->get('criteria');

        foreach ($criteria as $name => $data) {
            if (!$grid->hasFilter($name)) {
                continue;
            }

            $filter = $grid->getFilter($name);

            $this->filtersRegistry->get($filter->getType())->apply($dataSource, $name, $data, $filter->getOptions());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.carbon.user.mgt;

import java.io.IOException;
import java.io.InputStream;

import javax.activation.DataHandler;

import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.mgt.common.*;

public class UserAdmin {

    private static Log log = LogFactory.getLog(UserAdmin.class);

    private static Log audit = CarbonConstants.AUDIT_LOG;

    private static String AUDIT_MESSAGE = "Initiator : %s | Action : %s | Target : %s | Data : { %s } | Result : %s ";

    public UserAdmin() {

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#listInternalUsers(java.lang.String)
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#listUsers(java.lang.String)
     */
	public String[] listUsers(String filter, int limit) throws UserAdminException {
		String[] users;
		users = getUserAdminProxy().listUsers(filter, limit);
		return users;
	}

    /**
     *
     * @param filter
     * @param limit
     * @return
     * @throws UserAdminException
     */
	public FlaggedName[] listAllUsers(String filter, int limit) throws UserAdminException {
		FlaggedName[] names;
		names = getUserAdminProxy().listAllUsers(filter, limit);
		return names;
	}

    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.UserAdmin#getInternalRoles()
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#getAllRolesNames()
     */
    public FlaggedName[] getAllRolesNames(String filter, int limit) throws UserAdminException {
        return  getUserAdminProxy().getAllRolesNames(filter, limit);
    }

    public FlaggedName[] getAllSharedRoleNames(String filter, int limit) throws UserAdminException {
        return  getUserAdminProxy().getAllRolesNames(filter, limit);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#isWritable()
     */
    public UserRealmInfo getUserRealmInfo() throws UserAdminException {
        return  getUserAdminProxy().getUserRealmInfo();
    }    ///

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#addUserToInternalStore(java.lang.String
     * , java.lang.String, java.lang.String[])
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#addUser(java.lang.String,
     * java.lang.String, java.lang.String[], java.util.Map, java.lang.String)
     */
	public void addUser(String userName, String password, String[] roles, ClaimValue[] claims,
			String profileName) throws UserAdminException {
		String result = null;
		try {
			getUserAdminProxy().addUser(userName, password, roles, claims, profileName);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			// ################### <Audit Logs> ##########################################
			StringBuilder builder = new StringBuilder();
			if (roles != null) {
				for (int i = 0; i < roles.length; i++) {
					builder.append(roles[i] + ",");
				}
			}
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Add User", userName, "Roles :"
					+ builder.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.UserAdmin#changePassword(java.lang.String,
     * java.lang.String)
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#changePassword(java.lang.String,
     * java.lang.String)
     */
    public void changePassword(String userName, String newPassword) throws UserAdminException {

		String result = null;

		try {
			getUserAdminProxy().changePassword(userName, newPassword);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Change Password by Administrator",
					userName, "", result));
			// ################### </Audit Logs> ##########################################
		}

	}

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#deleteUserFromInternalStore(java.lang
     * .String)
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#deleteUser(java.lang.String)
     */
	public void deleteUser(String userName) throws UserAdminException {

		String result = null;

		try {
			getUserAdminProxy().deleteUser(userName,
					CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.USER_CONFIGURATION));
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Delete User",
					userName, "", result));
			// ################### </Audit Logs> ##########################################
		}

	}

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#addRoleToInternalStore(java.lang.String
     * , java.lang.String[], java.lang.String[])
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#addRole(java.lang.String,
     * java.lang.String[], java.util.Map)
     */
    public void addRole(String roleName, String[] userList, String[] permissions, boolean isSharedRole)
            throws UserAdminException {
		String result = null;

		try {
			UserRealm realm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
			if (!isAllowedRoleName(roleName, realm)) {
				throw new UserAdminException("Role name is reserved by the system");
			}
			getUserAdminProxy().addRole(roleName, userList, permissions, isSharedRole);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			StringBuilder users = new StringBuilder();
			if (userList != null) {
				for (int i = 0; i < userList.length; i++) {
					users.append(userList[i] + ",");
				}
			}

			StringBuilder perms = new StringBuilder();
			if (permissions != null) {
				for (int i = 0; i < permissions.length; i++) {
					perms.append(permissions[i] + ",");
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Add Role", roleName, "Users : "
					+ users.toString() + " Permissions : " + permissions.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

    /**
     *
     * @param roleName
     * @param userList
     * @param permissions
     * @throws UserAdminException
     */
	public void addInternalRole(String roleName, String[] userList, String[] permissions)
			throws UserAdminException {
		String result = null;

		try {
			UserRealm realm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
			if (!isAllowedRoleName(roleName, realm)) {
				throw new UserAdminException("Role name is reserved by the system");
			}
			getUserAdminProxy().addInternalRole(roleName, userList, permissions);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			StringBuilder users = new StringBuilder();
			if (userList != null) {
				for (int i = 0; i < userList.length; i++) {
					users.append(userList[i] + ",");
				}
			}

			StringBuilder perms = new StringBuilder();
			if (permissions != null) {
				for (int i = 0; i < permissions.length; i++) {
					perms.append(permissions[i] + ",");
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Add Internal Role", roleName, "Users : "
					+ users.toString() + " Permissions : " + permissions.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param roleName
	 * @param realm
	 * @return
	 * @throws UserAdminException
	 */
	private boolean isAllowedRoleName(String roleName, UserRealm realm) throws UserAdminException {

        int index;
		index = roleName.indexOf("/");

		if (index > 0) {
			roleName = roleName.substring(index + 1);
		}

		try {
			return !realm.getRealmConfiguration().isReservedRoleName(roleName);
		} catch (UserStoreException e) {
			throw new UserAdminException(e.getMessage(), e);
		}
	}
    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#deleteRoleFromInternalStore(java.lang
     * .String)
     */
    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.TestClass#deleteRole(java.lang.String)
     */
	public void deleteRole(String roleName) throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().deleteRole(roleName);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Delete Role", roleName, "",
					result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param roleName
	 * @param newRoleName
	 * @throws UserAdminException
	 */
	public void updateRoleName(String roleName, String newRoleName) throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().updateRoleName(roleName, newRoleName);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Update Role Name", roleName,
					"Old : " + roleName + " New : " + newRoleName, result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @return
	 * @throws UserAdminException
	 */
    public boolean hasMultipleUserStores() throws UserAdminException{
        return getUserAdminProxy().hasMultipleUserStores();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.UserAdmin#getUsersInRole(java.lang.String)
     */
    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.TestClass#getUsersInfoOfRole(java.lang.String,
     * java.lang.String)
     */
    public FlaggedName[] getUsersOfRole(String roleName, String filter, int limit) throws UserAdminException {
        return getUserAdminProxy().getUsersOfRole(roleName, filter, limit);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.UserAdmin#updateUsersOfRole(java.lang.String,
     * java.lang.String[], java.lang.String[])
     */
    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.TestClass#updateUsersOfRole(java.lang.String,
     * java.lang.String[], java.lang.String[])
     */
	public void updateUsersOfRole(String roleName, FlaggedName[] userList)
			throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().updateUsersOfRole(roleName, userList);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			StringBuilder users = new StringBuilder();
			if (userList != null) {
				for (int i = 0; i < userList.length; i++) {
					if (userList[i] != null) {
						users.append(userList[i].getItemName() + ",");
					}
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Update Users of Role", roleName,
					"Users : " + users.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

    /*
     * (non-Javadoc)
     *
     * @see org.wso2.carbon.user.mgt.UserAdmin#getUsersInRole(java.lang.String)
     */
    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.TestClass#getRoleInfoOfUser(java.lang.String)
     */
    public FlaggedName[] getRolesOfUser(String userName, String filter, int limit) throws UserAdminException {
        return getUserAdminProxy().getRolesOfUser(userName, filter, limit);
    }

    // FIXME: Fix the documentation of this class including this.
    public FlaggedName[] getRolesOfCurrentUser() throws UserAdminException {
        return getRolesOfUser(CarbonContext.getThreadLocalCarbonContext().getUsername(), "*", -1);
    }   ///

    /*
     * (non-Javadoc)
     *
     * @see
     * org.wso2.carbon.user.mgt.TestClass#updateRolesOfUser(java.lang.String,
     * java.lang.String)
     */
	public void updateRolesOfUser(String userName, String[] newUserList) throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().updateRolesOfUser(userName, newUserList);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			StringBuilder roles = new StringBuilder();
			if (newUserList != null) {
				for (int i = 0; i < newUserList.length; i++) {
					if (newUserList[i] != null) {
						roles.append(newUserList[i] + ",");
					}
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Update Users of Role", userName,
					"Roles : " + roles.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @return
	 * @throws UserAdminException
	 */
    public UIPermissionNode getAllUIPermissions() throws UserAdminException {
        int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        return getUserAdminProxy().getAllUIPermissions(tenantId);
    }

    /**
     *
     * @param roleName
     * @return
     * @throws UserAdminException
     */
    public UIPermissionNode getRolePermissions(String roleName) throws UserAdminException {
        int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        return getUserAdminProxy().getRolePermissions(roleName, tenantId);
    }

    /**
     *
     * @param roleName
     * @param rawResources
     * @throws UserAdminException
     */
	public void setRoleUIPermission(String roleName, String[] rawResources)
			throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().setRoleUIPermission(roleName, rawResources);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			StringBuilder permissions = new StringBuilder();
			if (rawResources != null) {
				for (int i = 0; i < rawResources.length; i++) {
					if (rawResources[i] != null) {
						permissions.append(rawResources[i] + ",");
					}
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Set Role UI Permissions", roleName,
					"Permissions : " + permissions.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param fileName
	 * @param handler
	 * @param defaultPassword
	 * @throws UserAdminException
	 */
    public void bulkImportUsers(String fileName, DataHandler handler, String defaultPassword)
            throws UserAdminException {
        if(fileName == null || handler == null || defaultPassword == null) {
            throw new UserAdminException("Required data not provided");
        }
        try {
            InputStream inStream = handler.getInputStream();
            getUserAdminProxy().bulkImportUsers(fileName, inStream, defaultPassword);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new UserAdminException(e.getMessage(), e);
        }

    }

    /**
     *
     * @param oldPassword
     * @param newPassword
     * @throws UserAdminException
     * @throws AxisFault
     */
	public void changePasswordByUser(String oldPassword, String newPassword)
			throws UserAdminException, AxisFault {
		String result = null;

		try {
			getUserAdminProxy().changePasswordByUser(oldPassword, newPassword);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Change Password by User",
					getUser(), "", result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param roleName
	 * @param newUsers
	 * @param deletedUsers
	 * @throws UserAdminException
	 */
	public void addRemoveUsersOfRole(String roleName, String[] newUsers, String[] deletedUsers)
			throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().updateUsersOfRole(roleName, newUsers, deletedUsers);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {

			StringBuilder newUsersList = new StringBuilder();
			if (newUsers != null) {
				for (int i = 0; i < newUsers.length; i++) {
					newUsersList.append(newUsers[i] + ",");
				}
			}

			StringBuilder deletedUsersList = new StringBuilder();
			if (deletedUsers != null) {
				for (int i = 0; i < deletedUsers.length; i++) {
					deletedUsersList.append(deletedUsers[i] + ",");
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Add/Remove Users from Role",
					roleName, "New Users : " + newUsersList.toString() + " Deleted Users : "
							+ deletedUsersList.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param userName
	 * @param newRoles
	 * @param deletedRoles
	 * @throws UserAdminException
	 */
	public void addRemoveRolesOfUser(String userName, String[] newRoles, String[] deletedRoles)
			throws UserAdminException {
		String result = null;

		try {
			getUserAdminProxy().updateRolesOfUser(userName, newRoles, deletedRoles);
			result = "Success";
		} catch (UserAdminException e) {
			result = "Failed";
			throw e;
		} finally {
			StringBuilder newRolesList = new StringBuilder();
			if (newRoles != null) {
				for (int i = 0; i < newRoles.length; i++) {
					newRolesList.append(newRoles[i] + ",");
				}
			}

			StringBuilder deletedUsersList = new StringBuilder();
			if (deletedRoles != null) {
				for (int i = 0; i < deletedRoles.length; i++) {
					deletedUsersList.append(deletedRoles[i] + ",");
				}
			}

			// ################### <Audit Logs> ##########################################
			audit.info(String.format(AUDIT_MESSAGE, getUser(), "Add/Remove Roles from User",
					userName, "New Roles : " + newRolesList.toString() + " Deleted Roles : "
							+ deletedUsersList.toString(), result));
			// ################### </Audit Logs> ##########################################
		}
	}

	/**
	 *
	 * @param claimValue
	 * @param filter
	 * @param maxLimit
	 * @return
	 * @throws UserAdminException
	 */
	public FlaggedName[] listUserByClaim(ClaimValue claimValue, String filter, int maxLimit)
			throws UserAdminException {
		return getUserAdminProxy().listUsers(claimValue, filter, maxLimit);
	}

	/**
	 *
	 * @return
	 */
	private UserRealmProxy getUserAdminProxy() {
		UserRealm realm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
		return new UserRealmProxy(realm);
	}

	/**
	 *
	 * @return
	 */
    private String getUser(){
        return CarbonContext.getThreadLocalCarbonContext().getUsername() + "@" +
                CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    }

    public boolean isSharedRolesEnabled() throws UserAdminException{
    	return  getUserAdminProxy().isSharedRolesEnabled();
    }
}


text:
画箭头

https://matplotlib.org/tutorials/colors/colormaps.html

选择色域


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.HealthBot.Models
{
    public partial class HealthBotKeyVaultProperties : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("keyName");
            writer.WriteStringValue(KeyName);
            if (Optional.IsDefined(KeyVersion))
            {
                writer.WritePropertyName("keyVersion");
                writer.WriteStringValue(KeyVersion);
            }
            writer.WritePropertyName("keyVaultUri");
            writer.WriteStringValue(KeyVaultUri.AbsoluteUri);
            if (Optional.IsDefined(UserIdentity))
            {
                writer.WritePropertyName("userIdentity");
                writer.WriteStringValue(UserIdentity);
            }
            writer.WriteEndObject();
        }

        internal static HealthBotKeyVaultProperties DeserializeHealthBotKeyVaultProperties(JsonElement element)
        {
            string keyName = default;
            Optional<string> keyVersion = default;
            Uri keyVaultUri = default;
            Optional<string> userIdentity = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("keyName"))
                {
                    keyName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("keyVersion"))
                {
                    keyVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("keyVaultUri"))
                {
                    keyVaultUri = new Uri(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("userIdentity"))
                {
                    userIdentity = property.Value.GetString();
                    continue;
                }
            }
            return new HealthBotKeyVaultProperties(keyName, keyVersion.Value, keyVaultUri, userIdentity.Value);
        }
    }
}


text:
VERSION=$1
mkdir -p $HOME/.docker

echo $DOCKER_CONFIG_JSON | base64 -d > $HOME/.docker/config.json
echo VERSION=$VERSION
ARCH=arm
#echo DOCKER_AUTH=$DOCKER_AUTH

ln -s /run/docker.sock.outer /run/docker.sock

rm -rf /images
mkdir -p /images
node /builder/docker-2-docker.js clavator-os-image-arm-rpi23-$VERSION /images.docker ${DOCKER_REGISTRY} $DOCKER_HTTP_REGISTRY
node /builder/docker-extract.js /images.docker /images

. /builder/setup_image_name.sh /images/create-os-image-arm-rpi23-$VERSION.img
xz -d $image_name.xz
ls -la /images

. /builder/map-os-image-arm-rpi23.sh

. /builder/load-clavator-docker.sh

mkdir -p /mnt
mount $root_disk /mnt

/bin/sh /builder/run-construqt.sh eth0 arm /mnt
chroot /mnt /usr/bin/qemu-arm-static /bin/sh /deployer.sh force_hostname

. /builder/load-into-docker.sh

ln -nfs /run/docker.sock.outer /run/docker.sock
umount $root_disk
sh /builder/retry_losetup.sh -d $root_disk

. /builder/create-os-image-docker-arm-rpi23.sh

. /builder/docker-push.sh clavator-image-arm-rpi23-$GNUPGVERSION-$NODEVERSION-$VERSION /result


text:
using System;
using System.Windows.Forms;
using Clase15Listas.Objetos;

namespace Clase15Listas
{

    public partial class ListasEnlazadasForm
    {
        public ListasEnlazadasForm()
        {
            InitializeComponent();
        }

        private ListaEnlazada<string> _lista;

        private void ListasEnlazadasForm_Load(object sender, EventArgs e)
        {
            _lista = new ListaEnlazada<string>();
        }

        private void AgregarItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                var valor = IngresoTextBox.Text;
                _lista.AgregarItem(valor);

                ActualizarLista();

                IngresoTextBox.Text = "";
                IngresoTextBox.Focus();
            }
            catch (FormatException)
            {
                MessageBox.Show("Ingrese un valor numerico", "Error");
            }

        }

        private void EliminarItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                var valor = IngresoTextBox.Text;
                _lista.EliminarItem(valor);

                ActualizarLista();

                IngresoTextBox.Text = "";
                IngresoTextBox.Focus();
            }
            catch (FormatException)
            {
                MessageBox.Show("Ingrese un valor numerico", "Error");
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }

        }

        private void MostrarListaButton_Click(object sender, EventArgs e)
        {
            ActualizarLista();
        }

        private void ActualizarLista()
        {
            DatosListBox.Items.Clear();
            foreach (var item in _lista.ObtenerValores())
            {
                DatosListBox.Items.Add(item);
            }
        }
    }
}


text:
<?php
/*
 * Template Name: Full Width without Sidebar
 * Description: Page template without sidebar
 */
__( 'Full Width without Sidebar', 'sevenx-theme' );
?>

<?php get_header(); ?>

<?php _e( 'Latest Posts', 'sevenx-theme' ); ?>

            <?php get_template_part('loop'); ?>

            <?php get_template_part('template-parts/pagination'); ?>

<?php get_footer(); ?>


text:
"""Models for Oppia users."""

from core.platform import models
import feconf

from google.appengine.datastore.datastore_query import Cursor
from google.appengine.ext import ndb

(base_models,) = models.Registry.import_models([models.NAMES.base_model])

class UserSettingsModel(base_models.BaseModel):
    """Settings and preferences for a particular user.

    Instances of this class are keyed by the user id.
    """
    # Email address of the user.
    email = ndb.StringProperty(required=True, indexed=True)

    # Identifiable username to display in the UI. May be None.
    username = ndb.StringProperty(indexed=True)
    # Normalized username to use for duplicate-username queries. May be None.
    normalized_username = ndb.StringProperty(indexed=True)
    # When the user last agreed to the terms of the site. May be None.
    last_agreed_to_terms = ndb.DateTimeProperty(default=None)
    # When the user last started the state editor tutorial. May be None.
    last_started_state_editor_tutorial = ndb.DateTimeProperty(default=None)  # pylint: disable=invalid-name
    # When the user last logged in. This may be out-of-date by up to
    # feconf.PROXIMAL_TIMEDELTA_SECS seconds.
    last_logged_in = ndb.DateTimeProperty(default=None)
    # When the user last edited an exploration.
    last_edited_an_exploration = ndb.DateTimeProperty(default=None)
    # When the user last created an exploration.
    last_created_an_exploration = ndb.DateTimeProperty(default=None)
    # User uploaded profile picture as a dataURI string. May be None.
    profile_picture_data_url = ndb.TextProperty(default=None, indexed=False)
    # User specified biography (to be shown on their profile page).
    user_bio = ndb.TextProperty(indexed=False)
    # Subject interests specified by the user.
    subject_interests = ndb.StringProperty(repeated=True, indexed=True)
    # The time, in milliseconds, when the user first contributed to Oppia.
    # May be None.
    first_contribution_msec = ndb.FloatProperty(default=None)
    # Exploration language preferences specified by the user.
    # TODO(sll): Add another field for the language that the user wants the
    # site to display in. These language preferences are mainly for the purpose
    # of figuring out what to show by default in the library index page.
    preferred_language_codes = ndb.StringProperty(
        repeated=True,
        indexed=True,
        choices=[lc['code'] for lc in feconf.ALL_LANGUAGE_CODES])
    # System language preference (for I18N).
    preferred_site_language_code = ndb.StringProperty(
        default=None, choices=[
            language['id'] for language in feconf.SUPPORTED_SITE_LANGUAGES])

    @classmethod
    def is_normalized_username_taken(cls, normalized_username):
        """Returns whether or a given normalized_username is taken."""
        return bool(cls.get_all().filter(
            cls.normalized_username == normalized_username).get())

    @classmethod
    def get_by_normalized_username(cls, normalized_username):
        """Returns a user model given a normalized username"""
        return cls.get_all().filter(
            cls.normalized_username == normalized_username).get()

class UserContributionsModel(base_models.BaseModel):
    """Tracks explorations created/edited for a particular user.

    Instances of this class are keyed by the user id.
    """
    # IDs of explorations that this user has created
    # Includes subsequently deleted and private explorations.
    created_exploration_ids = ndb.StringProperty(
        repeated=True, indexed=True, default=None)
    # IDs of explorations that this user has made a positive
    # (i.e. non-revert) commit to.
    # Includes subsequently deleted and private explorations.
    edited_exploration_ids = ndb.StringProperty(
        repeated=True, indexed=True, default=None)

class UserEmailPreferencesModel(base_models.BaseModel):
    """Email preferences for a particular user.

    Instances of this class are keyed by the user id.
    """
    # The user's preference for receiving general site updates. This is set to
    # None if the user has never set a preference.
    site_updates = ndb.BooleanProperty(indexed=True)

    # The user's preference for receiving email when user is added as a member
    # in exploration. This is set to True when user has never set a preference.
    editor_role_notifications = ndb.BooleanProperty(
        indexed=True, default=feconf.DEFAULT_EDITOR_ROLE_EMAIL_PREFERENCE)

    # The user's preference for receiving email when user receives feedback
    # message for his/her exploration.
    feedback_message_notifications = ndb.BooleanProperty(
        indexed=True, default=feconf.DEFAULT_FEEDBACK_MESSAGE_EMAIL_PREFERENCE)

class UserSubscriptionsModel(base_models.BaseModel):
    """A list of things that a user subscribes to.

    Instances of this class are keyed by the user id.
    """
    # IDs of activities (e.g., explorations) that this user subscribes to.
    # TODO(bhenning): Rename this to exploration_ids and perform a migration.
    activity_ids = ndb.StringProperty(repeated=True, indexed=True)
    # IDs of collections that this user subscribes to.
    collection_ids = ndb.StringProperty(repeated=True, indexed=True)
    # IDs of feedback thread ids that this user subscribes to.
    feedback_thread_ids = ndb.StringProperty(repeated=True, indexed=True)
    # When the user last checked notifications. May be None.
    last_checked = ndb.DateTimeProperty(default=None)

class UserRecentChangesBatchModel(base_models.BaseMapReduceBatchResultsModel):
    """A list of recent changes corresponding to things a user subscribes to.

    This is computed using a MapReduce batch job and may not be up to date.
    Instances of this class are keyed by the user id.
    """
    # The output of the batch job.
    output = ndb.JsonProperty(indexed=False)
    # The time, in milliseconds since the epoch, when the job that computed
    # this batch model was queued.
    job_queued_msec = ndb.FloatProperty(indexed=False)

class UserStatsModel(base_models.BaseMapReduceBatchResultsModel):
    """User-specific statistics keyed by user id.
    Values for total plays and average ratings are recorded by aggregating over
    all explorations owned by a user.
    Impact scores are calculated over explorations for which a user
    is listed as a contributor

    The impact score for a particular user is defined as:
    Sum of (
    ln(playthroughs) * (ratings_scaler) * (average(ratings) - 2.5))
    *(multiplier),
    where multiplier = 10, and ratings_scaler is .1 * (number of ratings)
    if there are < 10 ratings for that exploration.

    The impact score is 0 for an exploration with 0 playthroughs or with an
    average rating of less than 2.5.
    """
    # The impact score.
    impact_score = ndb.FloatProperty(indexed=True)

    # The total plays of all the explorations.
    total_plays = ndb.IntegerProperty(indexed=True, default=0)

    # The average of average ratings of all explorations.
    average_ratings = ndb.FloatProperty(indexed=True)

    # The number of ratings of all explorations.
    num_ratings = ndb.IntegerProperty(indexed=True, default=0)

    # A list which stores history of creator stats.
    # Each item in the list is a Json object keyed by a datetime string and
    # value as another Json object containing key-value pairs to be stored.
    # [
    #  {
    #   (date_1): {
    #    "average_ratings": 4.3,
    #    "total_plays": 40
    #   }
    #  },
    #  {
    #   (date_2): {
    #    "average_ratings": 4.1,
    #    "total_plays": 60
    #   }
    #  },
    # ]
    weekly_creator_stats_list = ndb.JsonProperty(repeated=True)

    # The version of dashboard stats schema.
    schema_version = (
        ndb.IntegerProperty(
            required=True,
            default=feconf.CURRENT_DASHBOARD_STATS_SCHEMA_VERSION,
            indexed=True))

    @classmethod
    def get_or_create(cls, user_id):
        """Creates a new UserStatsModel instance, if it does not already
        exist.
        """
        entity = cls.get(user_id, strict=False)
        if not entity:
            entity = cls(id=user_id)
        return entity

class ExplorationUserDataModel(base_models.BaseModel):
    """User-specific data pertaining to a specific exploration.

    Instances of this class have keys of the form
    [USER_ID].[EXPLORATION_ID]
    """

    # The user id.
    user_id = ndb.StringProperty(required=True, indexed=True)

    # The exploration id.
    exploration_id = ndb.StringProperty(required=True, indexed=True)

    # The rating (1-5) the user assigned to the exploration. Note that this
    # represents a rating given on completion of the exploration.
    rating = ndb.IntegerProperty(default=None, indexed=True)

    # When the most recent rating was awarded, or None if not rated.
    rated_on = ndb.DateTimeProperty(default=None, indexed=False)

    # List of uncommitted changes made by the user to the exploration.
    draft_change_list = ndb.JsonProperty(default=None)

    # Timestamp of when the change list was last updated.
    draft_change_list_last_updated = ndb.DateTimeProperty(default=None)

    # The exploration version that this change list applied to.
    draft_change_list_exp_version = ndb.IntegerProperty(default=None)

    @classmethod
    def _generate_id(cls, user_id, exploration_id):
        return '%s.%s' % (user_id, exploration_id)

    @classmethod
    def create(cls, user_id, exploration_id):
        """Creates a new ExplorationUserDataModel entry and returns it.

        Note that the client is responsible for actually saving this entity to
        the datastore.
        """
        instance_id = cls._generate_id(user_id, exploration_id)
        return cls(
            id=instance_id, user_id=user_id, exploration_id=exploration_id)

    @classmethod
    def get(cls, user_id, exploration_id):
        """Gets the ExplorationUserDataModel for the given ids."""
        instance_id = cls._generate_id(user_id, exploration_id)
        return super(ExplorationUserDataModel, cls).get(
            instance_id, strict=False)

class CollectionProgressModel(base_models.BaseModel):
    """Stores progress a user has made within a collection, including all
    explorations which have been completed within the context of the collection.

    Please note instances of this progress model will persist even after a
    collection is deleted.

    TODO(bhenning): Implement a job which removes stale versions of this model
    in the data store. That is, it should go through all completion models and
    ensure both the user and collection it is associated with still exist within
    the data store, otherwise it should remove the instance of the completion
    model.
    """

    # The user id.
    user_id = ndb.StringProperty(required=True, indexed=True)
    # The collection id.
    collection_id = ndb.StringProperty(required=True, indexed=True)
    # The list of explorations which have been completed within the context of
    # the collection represented by collection_id.
    completed_explorations = ndb.StringProperty(repeated=True)

    @classmethod
    def _generate_id(cls, user_id, collection_id):
        return '%s.%s' % (user_id, collection_id)

    @classmethod
    def create(cls, user_id, collection_id):
        """Creates a new CollectionProgressModel entry and returns it.

        Note: the client is responsible for actually saving this entity to the
        datastore.
        """
        instance_id = cls._generate_id(user_id, collection_id)
        return cls(
            id=instance_id, user_id=user_id, collection_id=collection_id)

    @classmethod
    def get(cls, user_id, collection_id):
        """Gets the CollectionProgressModel for the given ids."""

        instance_id = cls._generate_id(user_id, collection_id)
        return super(CollectionProgressModel, cls).get(
            instance_id, strict=False)

    @classmethod
    def get_or_create(cls, user_id, collection_id):
        """Gets the CollectionProgressModel for the given ids, or creates a new
        entry with the given ids if no such instance yet exists within the data
        store.
        """
        instance_model = cls.get(user_id, collection_id)
        if instance_model:
            return instance_model
        else:
            return cls.create(user_id, collection_id)

class UserQueryModel(base_models.BaseModel):
    """Model for storing result of queries.

    The id of each instance of this model is alphanumeric id of length 12
    unique to each model instance.
    """
    # Options for a query specified by query submitter.
    # Query option to specify whether user has created or edited one or more
    # explorations in last n days. This only returns users who have ever
    # created or edited at least one exploration.
    inactive_in_last_n_days = ndb.IntegerProperty(default=None)
    # Query option to check whether given user has logged in
    # since last n days.
    has_not_logged_in_for_n_days = ndb.IntegerProperty(default=None)
    # Query option to check whether user has created at least
    # n explorations.
    created_at_least_n_exps = ndb.IntegerProperty(default=None)
    # Query option to check whether user has created fewer than
    # n explorations.
    created_fewer_than_n_exps = ndb.IntegerProperty(default=None)
    # Query option to check if user has edited at least n explorations.
    edited_at_least_n_exps = ndb.IntegerProperty(default=None)
    # Query option to check if user has edited fewer than n explorations.
    edited_fewer_than_n_exps = ndb.IntegerProperty(default=None)
    # List of all user_ids who satisfy all parameters given in above query.
    # This list will be empty initially. Once query has completed its execution
    # this list will be populated with all qualifying user ids.
    user_ids = ndb.StringProperty(indexed=True, repeated=True)
    # Id of the user who submitted the query.
    submitter_id = ndb.StringProperty(indexed=True, required=True)
    # Current status of the query.
    query_status = ndb.StringProperty(
        indexed=True,
        choices=[
            feconf.USER_QUERY_STATUS_PROCESSING,
            feconf.USER_QUERY_STATUS_COMPLETED,
            feconf.USER_QUERY_STATUS_ARCHIVED,
            feconf.USER_QUERY_STATUS_FAILED
        ])

    @classmethod
    def fetch_page(cls, page_size, cursor):
        cursor = Cursor(urlsafe=cursor)
        query_models, next_cursor, more = (
            cls.query().order(-cls.created_on).
            fetch_page(page_size, start_cursor=cursor))
        next_cursor = next_cursor.urlsafe() if (next_cursor and more) else None
        return query_models, next_cursor, more


text:
package com.iksgmbh.sql.pojomemodb.dataobjects.persistent.oracle;

import com.iksgmbh.sql.pojomemodb.dataobjects.persistent.Table;
import com.iksgmbh.sql.pojomemodb.dataobjects.persistent.Sequence;
import com.iksgmbh.sql.pojomemodb.dataobjects.temporal.OrderCondition;
import com.iksgmbh.sql.pojomemodb.dataobjects.temporal.WhereCondition;

import java.math.BigDecimal;
import java.sql.SQLDataException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.iksgmbh.sql.pojomemodb.SQLKeyWords.DUAL;
import static com.iksgmbh.sql.pojomemodb.SQLKeyWords.NEXTVAL;

public class DualTable extends Table {

	public static final String DOT_NEXTVAL = "." + NEXTVAL;

	private HashMap<String, Sequence> sequenceMap;

	public DualTable(final HashMap<String, Sequence> aSequenceMap) {
		super(DUAL);
		this.sequenceMap = aSequenceMap;
	}

	@Override
	public List<Object[]> select(final List<String> selectedColumns,
								 final List<WhereCondition> whereConditions, List<OrderCondition> orderConditions) throws SQLDataException
	{
		if (selectedColumns == null || selectedColumns.size() == 0) {
			return new ArrayList<Object[]>();
		}

		if (selectedColumns.get(0).toLowerCase().endsWith(DOT_NEXTVAL.toLowerCase()))
		{
			final int pos = selectedColumns.get(0).indexOf(DOT_NEXTVAL);
			final String sequenceName = selectedColumns.get(0).substring(0, pos);
			final Sequence sequence = sequenceMap.get(sequenceName);

			if (sequence == null) {
				throw new SQLDataException("Unkown sequence: " + sequenceName);
			}

			final Object[] arr = new Object[1];
			arr[0] = new BigDecimal( sequence.nextVal() );
			final List<Object[]> toReturn = new ArrayList<Object[]>();
			toReturn.add(arr);
			return toReturn;
		}

		return null;
	}

}


text:
const Article = require("../db");

module.exports.index = (req, res, next) => {
    Article.getArticles().then((article) => {
        res.send(article);
    });
}

module.exports.create = (req, res, next) => {
    let data = req.body;
    console.log(data);
    Article.createArticle(data).then((result) => {
        res.send(result);
    })
}

module.exports.show =(req, res, next) => {
    let id = req.params.id;
    console.log(id);
    Article.getArticle(id).then((article) => {
        res.send(article);
    });
}

module.exports.delete = (req, res, next) => {
    let id = req.params.id;
    console.log(id);
    Article.deleteArticle(id).then((article) => {
        res.send(article);
    });
}

module.exports.createArticle = (req, res, next) => {
    let url = req.body.url;
    fetchArticle(url).then(res => {
        let { content, title, html } = res;
        return { content, title, html };
    }).then(articles => {
        return Article.createArticle(articles);
    }).then(result => {
        res.send(result);
    })
}

module.exports.showArticle = (req, res, next) => {
    Article.getArticles().then((articles) => {
        res.format({
            html: () => {
                res.render('articles', { articles, test: "success" }, (err, html) => {
                    res.send(html);
                });
            },
            json: () => {
                res.send(articles);
            }
        })

    });
}

module.exports.collectArticle = (req, res, next) => {
    res.render('collect-article');
}


text:
"""Will combined images distributed over multiple
extensions into a single image.
It will be able to handle multiple images in a single FITS file and will also update the header information with all of the relevant details.
"""

# Ensure python 2.5 compatibility
from __future__ import with_statement

from pyraf import iraf
from pyraf.iraf import pysalt

import saltsafekey
import saltsafeio
import saltstring
import salttran
import os
import time
import numpy as np
import pyfits
from saltsafelog import logging, history
from salterror import SaltIOError, SaltError

debug=True

def slotmerge(images,outimages,outpref,geomfile,clobber,logfile,verbose):

    with logging(logfile,debug) as log:
        # are the arguments defined
        saltsafeio.argdefined('images',images)
        saltsafeio.argdefined('geomfile',geomfile)
        saltsafeio.argdefined('logfile',logfile)

        # if the input file is a list, does it exist?
        if images[0] == '@':
            saltsafeio.listexists('Input',images)

        # parse list of input files
        infiles=saltsafeio.listparse('Raw image',images,'','','')

        # check input files exist
        saltsafeio.filesexist(infiles,'','r')

        # load output name list: @list, * and comma separated
        outimages = outimages.strip()
        outpref = outpref.strip()
        if len(outpref) == 0 and len(outimages) == 0:
            raise SaltIOError('Output file(s) not specified')

        # test output @filelist exists
        if len(outimages) > 0 and outimages[0] == '@':
            saltsafeio.listexists('Output',outimages)

        # parse list of output files
        outfiles=saltsafeio.listparse('Output image',outimages,outpref,infiles,'')

        # are input and output lists the same length?
        saltsafeio.comparelists(infiles,outfiles,'Input','output')

        # do the output files already exist?
        if not clobber:
            saltsafeio.filesexist(outfiles,'','w')

        # does CCD geometry definition file exist
        geomfilefile = geomfile.strip()
        saltsafeio.fileexists(geomfile)

        # read geometry definition file
        gap = 0
        xshift = [0, 0]
        yshift = [0, 0]
        rotation = [0, 0]

        gap, xshift, yshift, rotation=saltsafeio.readccdgeom(geomfile)
        for ro in rotation:
            if ro!=0:
                log.warning('SLOTMERGE currently ignores CCD rotation')

        # Begin processes each file
        for infile, outfile in zip(infiles, outfiles):
            # determine the name for the output file
            outpath = outfile.rstrip(os.path.basename(outfile))
            if (len(outpath) == 0):
                outpath = '.'

            # open each raw image
            struct=saltsafeio.openfits(infile)

            # identify instrument
            instrume,keyprep,keygain,keybias,keyxtalk,keyslot=saltsafekey.instrumid(struct,infile)

            # how many amplifiers?
            nccds=saltsafekey.get('NCCDS',struct[0],infile)
            amplifiers = nccds * 2
            #if (nccds != 2):
            #    raise SaltError('Can not currently handle more than two CCDs')

            # CCD geometry coefficients
            if instrume == 'RSS' or instrume == 'PFIS':
                xsh = [xshift[0], 0., xshift[1]]
                ysh = [yshift[0], 0., yshift[1]]
                rot = [rotation[0], 0., rotation[1]]
                refid = 1
            if instrume == 'SALTICAM':
                xsh = [xshift[0], 0.]
                ysh = [yshift[0], 0.]
                rot = [rotation[0], 0]
                refid = 1

            # how many extensions?
            nextend=saltsafekey.get('NEXTEND',struct[0],infile)

            # how many exposures
            exposures = nextend/amplifiers

            # CCD on-chip binning
            xbin, ybin=saltsafekey.ccdbin(struct[0],infile)
            gp = int(gap / xbin)

            # create output hdu structure
            outstruct = [None] * int(exposures+1)
            outstruct[0]=struct[0]

            # iterate over exposures, stitch them to produce file of CCD images
            for i in range(exposures):
                # Determine the total size of the image
                xsize=0
                ysize=0
                for j in range(amplifiers):
                    hdu=i*amplifiers+j+1
                    try:
                        xsize += len(struct[hdu].data[0])
                        if ysize < len(struct[hdu].data):
                            ysize=len(struct[hdu].data)
                    except:
                        msg='Unable to access extension %i ' % hdu
                        raise SaltIOError(msg)
                xsize += gp* (nccds-1)
                maxxsh, minxsh = determineshifts(xsh)
                maxysh, minysh = determineshifts(ysh)
                xsize += (maxxsh-minxsh)
                ysize += (maxysh-minysh)

                # Determine the x and y origins for each frame
                xdist=0
                ydist=0
                shid=0
                x0=np.zeros(amplifiers)
                y0=np.zeros(amplifiers)
                for j in range(amplifiers):
                    x0[j]=xdist+xsh[shid]-minxsh
                    y0[j]=ysh[shid]-minysh
                    hdu=i*amplifiers+j+1
                    darr=struct[hdu].data
                    xdist += len(darr[0])
                    if j%2==1:
                        xdist += gp
                        shid += 1

                # make the out image
                outarr=np.zeros((ysize, xsize), np.float64)

                # Embed each frame into the output array
                for j in range(amplifiers):
                    hdu=i*amplifiers+j+1
                    darr=struct[hdu].data
                    outarr=salttran.embed(darr, x0[j], y0[j], outarr)

                # Add the outimage to the output structure
                hdu=i*amplifiers+1
                outhdu=i+1
                outstruct[outhdu] = pyfits.ImageHDU(outarr)
                outstruct[outhdu].header=struct[hdu].header

                # Fix the headers in each extension
                datasec='[1:%4i,1:%4i]' % (xsize, ysize)
                saltsafekey.put('DATASEC',datasec, outstruct[outhdu], outfile)
                saltsafekey.rem('DETSIZE',outstruct[outhdu],outfile)
                saltsafekey.rem('DETSEC',outstruct[outhdu],outfile)
                saltsafekey.rem('CCDSEC',outstruct[outhdu],outfile)
                saltsafekey.rem('AMPSEC',outstruct[outhdu],outfile)

                # add housekeeping key words
                outstruct[outhdu]=addhousekeeping(outstruct[outhdu], outhdu, outfile)

            # close input FITS file
            saltsafeio.closefits(struct)

            # housekeeping keywords
            keymosaic='SLOTMERG'
            fname, hist=history(level=1, wrap=False)
            saltsafekey.housekeeping(struct[0],keymosaic,'Amplifiers have been mosaiced', hist)
            #saltsafekey.history(outstruct[0],hist)

            # this is added for later use by
            saltsafekey.put('NCCDS', 0.5, outstruct[0])
            saltsafekey.put('NSCIEXT', exposures, outstruct[0])
            saltsafekey.put('NEXTEND', exposures, outstruct[0])

            # write FITS file of mosaiced image
            outstruct=pyfits.HDUList(outstruct)
            saltsafeio.writefits(outstruct, outfile, clobber=clobber)

def determineshifts(shift):
    """Determine the maximum shifts in the data."""

    maxsh=0
    minsh=0
    for sh in shift:
        if sh > maxsh: maxsh=sh
        if sh < minsh: minsh=sh
    return maxsh, minsh

def addWCS(struct, xbin, ybin, outfile):
    """WCS keywords"""

    saltsafekey.new('CRPIX1',1,'WCS: X reference pixel',struct,outfile)
    saltsafekey.new('CRPIX2',1,'WCS: Y reference pixel',struct,outfile)
    saltsafekey.new('CRVAL1',float(xbin), 'WCS: X reference coordinate value',struct,outfile)
    saltsafekey.new('CRVAL2',float(ybin), 'WCS: Y reference coordinate value',struct,outfile)
    saltsafekey.new('CDELT1',float(xbin),'WCS: X pixel size',struct,outfile)
    saltsafekey.new('CDELT2',float(ybin),'WCS: Y pixel size',struct,outfile)
    saltsafekey.new('CTYPE1','pixel','X type',struct,outfile)
    saltsafekey.new('CTYPE2','pixel','Y type',struct,outfile)

    return struct

def addhousekeeping(struct, outhdu, outfile):
    """housekeeping keywords"""

    saltsafekey.put('SAL-TLM',time.asctime(time.localtime()),struct,outfile)
    saltsafekey.new('EXTNAME','SCI','Extension name',struct,outfile)
    saltsafekey.new('EXTVER',outhdu,'Extension number',struct,outfile)

    return struct

# -----------------------------------------------------------
# main code

parfile = iraf.osfn("slottools$slotmerge.par")
t = iraf.IrafTaskFactory(taskname="slotmerge",value=parfile,function=slotmerge, pkgname='slottools')


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

namespace OpenCvSharp;

/// <summary>
/// Line segment structure retrieved from cvHoughLines2
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[SuppressMessage("Design", "CA1051: Do not declare visible instance fields")]
public struct LineSegmentPoint : IEquatable<LineSegmentPoint>
{
    /// <summary>
    /// 1st Point
    /// </summary>
    public Point P1;

    /// <summary>
    /// 2nd Point
    /// </summary>
    public Point P2;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="p1">1st Point</param>
    /// <param name="p2">2nd Point</param>
    public LineSegmentPoint(Point p1, Point p2)
    {
        P1 = p1;
        P2 = p2;
    }

    #region Operators

    /// <summary>
    /// Specifies whether this object contains the same members as the specified Object.
    /// </summary>
    /// <param name="other">The Object to test.</param>
    /// <returns>This method returns true if obj is the same type as this object and has the same members as this object.</returns>
    public bool Equals(LineSegmentPoint other)
    {
        return (P1 == other.P1 && P2 == other.P2);
    }

    /// <summary>
    /// Compares two CvPoint objects. The result specifies whether the members of each object are equal.
    /// </summary>
    /// <param name="lhs">A Point to compare.</param>
    /// <param name="rhs">A Point to compare.</param>
    /// <returns>This operator returns true if the members of left and right are equal; otherwise, false.</returns>
    public static bool operator ==(LineSegmentPoint lhs, LineSegmentPoint rhs)
    {
        return lhs.Equals(rhs);
    }

    /// <summary>
    /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal.
    /// </summary>
    /// <param name="lhs">A Point to compare.</param>
    /// <param name="rhs">A Point to compare.</param>
    /// <returns>This operator returns true if the members of left and right are unequal; otherwise, false.</returns>
    public static bool operator !=(LineSegmentPoint lhs, LineSegmentPoint rhs)
    {
        return !lhs.Equals(rhs);
    }

    #endregion

    #region Overrided methods

    /// <summary>
    /// Specifies whether this object contains the same members as the specified Object.
    /// </summary>
    /// <param name="obj">The Object to test.</param>
    /// <returns>This method returns true if obj is the same type as this object and has the same members as this object.</returns>
    public override bool Equals(object? obj)
    {
        return base.Equals(obj);
    }

    /// <summary>
    /// Returns a hash code for this object.
    /// </summary>
    /// <returns>An integer value that specifies a hash value for this object.</returns>
    public override int GetHashCode()
    {
        return P1.GetHashCode() + P2.GetHashCode();
    }

    /// <summary>
    /// Converts this object to a human readable string.
    /// </summary>
    /// <returns>A string that represents this object.</returns>
    public override string ToString()
    {
        return $"CvLineSegmentPoint (P1:{P1} P2:{P2})";
    }

    #endregion

    #region Methods

    #region Line and Line

    /// <summary>
    /// Calculates a intersection of the specified two lines
    /// </summary>
    /// <param name="line1"></param>
    /// <param name="line2"></param>
    /// <returns></returns>
    public static Point? LineIntersection(LineSegmentPoint line1, LineSegmentPoint line2)
    {
        var x1 = line1.P1.X;
        var y1 = line1.P1.Y;
        var f1 = line1.P2.X - line1.P1.X;
        var g1 = line1.P2.Y - line1.P1.Y;
        var x2 = line2.P1.X;
        var y2 = line2.P1.Y;
        var f2 = line2.P2.X - line2.P1.X;
        var g2 = line2.P2.Y - line2.P1.Y;

        double det = f2*g1 - f1*g2;
        if (Math.Abs(det) < 1e-9)
        {
            return null;
        }

        var dx = x2 - x1;
        var dy = y2 - y1;
        var t1 = (f2*dy - g2*dx)/det;
        //var t2 = (f1*dy - g1*dx)/det;

        return new Point
        {
            X = (int) Math.Round(x1 + (f1*t1)),
            Y = (int) Math.Round(y1 + (g1*t1))
        };
    }

    /// <summary>
    /// Calculates a intersection of the specified two lines
    /// </summary>
    /// <param name="line"></param>
    /// <returns></returns>
    public Point? LineIntersection(LineSegmentPoint line)
    {
        return LineIntersection(this, line);
    }

    #endregion

    #region Segment and Segment

    /// <summary>
    /// Calculates a intersection of the specified two segments
    /// </summary>
    /// <param name="seg1"></param>
    /// <param name="seg2"></param>
    /// <returns></returns>
    public static Point? SegmentIntersection(LineSegmentPoint seg1, LineSegmentPoint seg2)
    {
        if (IntersectedSegments(seg1, seg2))
            return LineIntersection(seg1, seg2);
        else
            return null;
    }

    /// <summary>
    /// Calculates a intersection of the specified two segments
    /// </summary>
    /// <param name="seg"></param>
    /// <returns></returns>
    public Point? SegmentIntersection(LineSegmentPoint seg)
    {
        return SegmentIntersection(this, seg);
    }

    /// <summary>
    /// Returns a boolean value indicating whether the specified two segments intersect.
    /// </summary>
    /// <param name="seg1"></param>
    /// <param name="seg2"></param>
    /// <returns></returns>
    public static bool IntersectedSegments(LineSegmentPoint seg1, LineSegmentPoint seg2)
    {
        var p1 = seg1.P1;
        var p2 = seg1.P2;
        var p3 = seg2.P1;
        var p4 = seg2.P2;

        checked
        {
            if (p1.X >= p2.X)
            {
                if ((p1.X < p3.X && p1.X < p4.X) || (p2.X > p3.X && p2.X > p4.X))
                    return false;
            }
            else
            {
                if ((p2.X < p3.X && p2.X < p4.X) || (p1.X > p3.X && p1.X > p4.X))
                    return false;
            }
            if (p1.Y >= p2.Y)
            {
                if ((p1.Y < p3.Y && p1.Y < p4.Y) || (p2.Y > p3.Y && p2.Y > p4.Y))
                    return false;
            }
            else
            {
                if ((p2.Y < p3.Y && p2.Y < p4.Y) || (p1.Y > p3.Y && p1.Y > p4.Y))
                    return false;
            }

            if (((long) (p1.X - p2.X)*(p3.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p3.X))*
                ((long) (p1.X - p2.X)*(p4.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p4.X)) > 0)
                return false;
            if (((long) (p3.X - p4.X)*(p1.Y - p3.Y) + (long) (p3.Y - p4.Y)*(p3.X - p1.X))*
                ((long) (p3.X - p4.X)*(p2.Y - p3.Y) + (long) (p3.Y - p4.Y)*(p3.X - p2.X)) > 0)
                return false;
        }
        return true;
    }

    /// <summary>
    /// Returns a boolean value indicating whether the specified two segments intersect.
    /// </summary>
    /// <param name="seg"></param>
    /// <returns></returns>
    public bool IntersectedSegments(LineSegmentPoint seg)
    {
        return IntersectedSegments(this, seg);
    }

    #endregion

    #region Line and Segment

    /// <summary>
    /// Returns a boolean value indicating whether a line and a segment intersect.
    /// </summary>
    /// <param name="line">Line</param>
    /// <param name="seg">Segment</param>
    /// <returns></returns>
    public static bool IntersectedLineAndSegment(LineSegmentPoint line, LineSegmentPoint seg)
    {
        var p1 = line.P1;
        var p2 = line.P2;
        var p3 = seg.P1;
        var p4 = seg.P2;
        if (((long) (p1.X - p2.X)*(p3.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p3.X))*
            ((long) (p1.X - p2.X)*(p4.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p4.X)) > 0)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// Calculates a intersection of a line and a segment
    /// </summary>
    /// <param name="line"></param>
    /// <param name="seg"></param>
    /// <returns></returns>
    public static Point? LineAndSegmentIntersection(LineSegmentPoint line, LineSegmentPoint seg)
    {
        if (IntersectedLineAndSegment(line, seg))
            return LineIntersection(line, seg);
        else
            return null;
    }

    #endregion

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public double Length()
    {
        return P1.DistanceTo(P2);
    }

    /// <summary>
    /// Translates the Point by the specified amount.
    /// </summary>
    /// <param name="x">The amount to offset the x-coordinate. </param>
    /// <param name="y">The amount to offset the y-coordinate. </param>
    /// <returns></returns>
    public void Offset(int x, int y)
    {
        P1.X += x;
        P1.Y += y;
        P2.X += x;
        P2.Y += y;
    }

    /// <summary>
    /// Translates the Point by the specified amount.
    /// </summary>
    /// <param name="p">The Point used offset this CvPoint.</param>
    /// <returns></returns>
    public void Offset(Point p)
    {
        Offset(p.X, p.Y);
    }

    #endregion
}


text:
using System;
using EnsureThat;

namespace MeepMeep
{
    /// <summary>
    /// Represents a single operation performed within a workload.
    /// Contained in <see cref="WorkloadResult"/>.
    /// </summary>
    public class WorkloadOperationResult
    {
        public TimeSpan TimeTaken { get; set; }
        public bool Succeeded { get; set; }
        public string Message { get; set; }
        public int DocSize { get; set; }

        public WorkloadOperationResult(Exception ex, TimeSpan timeTaken)
        {
            Ensure.That(ex, "ex").IsNotNull();

            Succeeded = false;
            Message = ex.Message;
            TimeTaken = timeTaken;
        }

        public WorkloadOperationResult(bool succeeded, string message, TimeSpan timeTaken)
        {
            Succeeded = succeeded;
            Message = message;
            TimeTaken = timeTaken;
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('homes', '0002_branch'),
    ]

    operations = [
        migrations.CreateModel(
            name='SearchPrice',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('type', models.IntegerField(choices=[(1, 'Letting'), (2, 'Sale')])),
                ('label', models.CharField(max_length=20)),
                ('price', models.DecimalField(decimal_places=2, max_digits=11)),
            ],
        ),
    ]


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.analytics.synapse.artifacts.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** Binary read settings. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("BinaryReadSettings")
@Fluent
public final class BinaryReadSettings extends FormatReadSettings {
    /*
     * Compression settings.
     */
    @JsonProperty(value = "compressionProperties")
    private CompressionReadSettings compressionProperties;

    /**
     * Get the compressionProperties property: Compression settings.
     *
     * @return the compressionProperties value.
     */
    public CompressionReadSettings getCompressionProperties() {
        return this.compressionProperties;
    }

    /**
     * Set the compressionProperties property: Compression settings.
     *
     * @param compressionProperties the compressionProperties value to set.
     * @return the BinaryReadSettings object itself.
     */
    public BinaryReadSettings setCompressionProperties(CompressionReadSettings compressionProperties) {
        this.compressionProperties = compressionProperties;
        return this;
    }
}


text:
{% extends "base.html" %}

{% block header %}Experiment Setup{% endblock %}
{% block title %}Experiment Setup{% endblock %}
{% block scripts %}
{{form.media}}
	<script type="text/javascript">
	 $(document).ready(function() {
		$('#id_date').datepicker({dateFormat: 'yy-mm-dd'});
	});
	</script>
{% endblock %}
{% block content %}
<form method="POST" action=".">{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}


text:
layout: post
title: "Nomeando Unidades"
date: 2016-07-18
description: Veja porque devemos utilizar nomes hierárquicos nas Unidades do projeto.
summary: Veja porque devemos utilizar nomes hierárquicos nas Unidades do projeto.
image: /images/photo-1434030216411-0b793f4b4173.jpg
categories:
  - Pascal
tags:
  - naming
keywords:
  - naming
  - nomeando
  - unit
---

Acredito que todos os nomes de Unidades em um Projeto *Object Pascal*, quiça em qualquer outra linguagem, deveriam ser hierárquicos do mais genérico para o mais específico.

Neste artigo irei escrever sobre a lógica em utilizar uma nomenclatura hieraquizada para deixar seu projeto mais coeso e elegante.

<!--more-->

![Imagem]({{ page.image }})

##Introdução {#introducao}

Foi-se o tempo quando programávamos utilizando nomes de Unidades como: `uUtils`, `uPerson`, `frmClient`, etc.

Em projetos pequenos tais nomes de Unidades ainda são utilizados (será?), mas essa nomenclatura não é nada profissional.

Por quê?

O motivo é que uma Unidade deve encapsular um Contexto **bem definido**. Um Contexto pode ser genérico ou ser uma especialização.

Um nome de Unidade como esses acima não transmitem um Contexto bem definido.

Para que a idéia de Contexto fique clara, uma Unidade deve ter um nome sem ambiguidades.

Veja esse exemplo de nomes de Unidades:

  1. frmClient
  2. AcmeClientEditForm

Qual dos nomes é mais claro, passando imediatamente a ideia do que essa Unidade faz?

O item #2, é claro.

  1. `Acme` é o nome do Projeto ou nome da Empresa.
  2. `Client` é o Contexto mais genérico.
  3. `Edit` é o Contexto mais específico.
  4. `Form` determina hierarquia da Classe ou o seu propósito.

A medida que um projeto cresce e novas Unidades são inseridas, colisões de nomes podem ocorrer. Ter bons nomes de Unidades no projeto fará muita diferença no longo prazo. Será mais fácil determinar o impacto de alguma alteração apenas olhando a hierarquia no nome da Unidade.

Mas existem regras ou dicas para escolhermos bons nomes de Unidades?

É o que iremos ver a seguir.

##Regra 1: Prefixos {#regra-1-prefixos}

Um nome de Unidade hieraquizado nada mais é do que utilizar **prefixos**. A cada prefixo adicionado, damos o nome de Contexto. O nome para cada Contexto ou prefixo utilizado vai depender de cada projeto.

Um Contexto pode identificar uma tecnologia, protocolo, setor da empresa, entidade ou até mesmo um outro sistema.

Para sistemas comerciais, o próprio usuário irá lhe dar os nomes desses Contextos. Os nomes dos setores na empresa serão o ponto de partida.

##Regra 2: Nome do Projeto ou Empresa {#regra-2-nome-do-projeto-ou-empresa}

Toda Unidade deve ser precedida com o nome do Projeto ou nome da Empresa.

Se teus projetos são feitos somente dentro de tua empresa para seu próprios clientes, basta utilizar o nome do Projeto como prefixo para todas as Unidades.

Caso sua empresa faça *frameworks* ou projetos OpenSource, ou seja, se o projeto terá um contexto mais global, é uma boa ideia utilizar o nome da Empresa como prefixo.

Qual dos dois será utilizado dependerá do propósito geral do Projeto.

##Regra 3: Genérico para o mais Especializado {#regra-3-generico-para-especializado}

O nome de uma Unidade deve ser hierarquizado do mais genérico para o mais especializado.

No artigo sobre [Nomenclatura de Classes]({% post_url 2016-04-25-nomeando-classes %}) eu lhes dei um exemplo de nomenclatura (errada) para uma hipotética Classe do meu [Projeto AWS](https://github.com/mdbs99/aws) que foi `TAWSNetHTTPClient`.

O nome de uma Classe não deve ser uma hierarquia.

Classes nem deveriam fazer parte de uma [hieraquia de herança]({% post_url 2016-05-23-heranca-pode-ser-o-mal-da-orientacao-a-objetos-parte-1 %}) na maioria das vezes.

A hierarquia deve estar no nome da Unidade.

Então como ficariam os nomes, da Classe e da Unidade, considerando o exemplo acima?

  1. Unidade: AWSNetHttpClient
  2. Classe: THttpClient

O `Http` se repete no nome da Classe. O motivo é porque o nome da Classe deve ser constituído de **Contexto + Nome**, conforme já explicado [aqui]({% post_url 2016-04-25-nomeando-classes %}).

Outros exemplos de bons nomes para Unidades:

  * AcmeData
  * AcmeDataXml
  * AcmeDataJson

  * AcmeReport
  * AcmeReportRBuilder

  * AcmeWeb
  * AcmeWebHttp
  * AcmeWebFtp

  * AcmeFinances
  * AcmeFinancesClient
  * AcmeFinancesClientReports

##Regra 4: Interfaces numa Unidade, Classes noutra {#regra-4-interfaces-e-classes}

Toda Classe deveria [implementar ao menos uma Interface]({% post_url 2016-01-18-interfaces-em-todo-lugar %}) e todo o Projeto deveria trabalhar com variáveis e argumentos do tipo Interface. Dessa forma um argumento poderia receber qualquer instância de Classe que implementa o tipo da Interface.

Então temos que definir as Interfaces numa Unidade e suas implementações *default* em outra Unidade. Caso o programador queira codificar sua própria implementação da Interface, ele só precisa adicionar no *uses* apenas a Unidade que contém as Interfaces.

Como nomear ambas as Unidades?

Bem, eu utilizo uma nomenclatura que a princípio você não verá muita lógica, mas ficou como um costume pra mim. Talvez você pense numa nomenclatura melhor e nos diga na área de comentários.

Vamos lá. Para Unidades sobre Finanças, por exemplo, eu teria o seguinte:

  1. Unidade das Interfaces: AcmeFinances
  2. Unidade das Classes: AcmeFinancesA

Isso aí. Apenas a letra `A` como sufixo.

O motivo é que as Unidades são exibidas em ordem alfabética, então a Unidade de Interfaces virá antes da Unidade de Classes.

Caso eu tenha outro sub prefixo que também começe com `A`, exemplo `AcmeFinancesAction`, ainda assim a ordem visual seria mantida, do mais genérico para o mais especializado.

##Regra 5: Uma Unidade especializada utiliza a mais genérica, nunca o contrário {#regra-5-unidade-especializada}

Essa regra é clara, mas sempre é bom lembrar que uma Unidade genérica **nunca** poderá ter um *uses* para uma mais especializada dentro da mesma hierarquia.

Veja o esquema abaixo:

  1. AcmeFinances
  2. AcmeFinancesClient >> uses AcmeFinances
  3. AcmeFinancesClientReports >> uses AcmeFinancesClient

##Regra 6: Se uma Unidade está sendo utilizada em muitas outras hierarquias, ela não pertence ao Projeto {#regra-6-unidade-nao-pertence-ao-projeto}

Se uma Unidade ou um pequeno conjunto delas, sempre aparecem no *uses* de várias hierarquias diferentes, isso pode indicar que essa(s) Unidade(s) não fazem parte do *core* do projeto devem ser refatoradas/extraídas para outro projeto ou *package*.

Se essas Unidades podem ser reaproveitadas em outros projetos por serem muito genéricas, é também outro grande indício para refatorar e extraí-las do projeto.

##Bônus

###Nomes de Unidades Pontilhadas {#unidades-pontilhadas}

Hoje e dia o Delphi e FreePascal/Lazarus tem suporte para "Nomes de Unidades Pontilhadas", ou seja, podemos nomear uma Unidade utilizando pontos que separam contextos. No Java sempre foi assim e o .NET fez igual.

E em que isso muda as regras acima?

Nada.

Sem considerar os pontos, não há nenhuma diferença técnica ou de utilização para utilizar `Acme.Finances.Client.Reports` ao invés de `AcmeFinancesClientReports`.

A "vantagem" em utilizar "Nomes de Unidades Pontilhadas", na minha opinião, é apenas visual.

Veja um exemplo:

  1. AcmeWebHTTPClient
  2. Acme.Web.HTTP.Client

A opção #2 é mais *clean* que a opção #1 devido ao Contexto `HTTP` ter sido escrito em maiúsculo.

Obs.: Já ouvi falar que o compilador do Delphi atualmente tem parâmetros que podem selecionar um *namespace* específico para compilar Unidades específicas e isso pode ter haver com esse tipo de nomenclatura que utiliza pontos. Caso você saiba mais sobre isso, porfavor deixei seu comentário.

###Abreviações em Pascal-case ou tudo em maiúsculas {#abreviacoes-maiusculas}

Qual nomenclatura utilizar para abreviações, por exemplo, `HTTP`?

Sendo `HTTP` uma abreviação de *Hypertext Transfer Protocol*, o mais correto na escrita seria `HTTP` e não `Http`. Mas visualmente, quando uma abreviação faz parte do nome de uma Classe, fica mais elegante ou mais fácil de ler utilizando Pascal-case.

Teoricamente `THttpClient` é mais fácil de ler do que `THTTPClient`.

Mas nesse quesito eu mesmo ainda não tomei uma decisão. Algumas vezes eu utilizo tudo em maiúsculo, outras vezes em Pascal-case. Ainda tenho um conflito interior entre o "certo na escrita" vs. "visual elegante".

##Conclusão {#conclusao}

Escolher bons nomes para Unidades, Classes, Interfaces e métodos sempre será uma arte. Não existe o **certo absoluto**. Cada projeto nos dará seus requisitos e os nomes irão aparecer.

Essas Regras podem ajudar, mas cabe ao arquiteto ter bom senso, conhecer bem o domínio e pensar bem antes de nomear suas Unidades.

Até logo.


text:
require 'genio/parser/version'
require 'genio/parser/logging'

module Genio
  module Parser
    autoload :Types, 'genio/parser/types'
    module Format
      autoload :Base,       'genio/parser/format/base'
      autoload :JsonSchema, 'genio/parser/format/json_schema'
      autoload :IODocs,     'genio/parser/format/iodocs'
      autoload :Wadl,       'genio/parser/format/wadl'
      autoload :Wsdl,       'genio/parser/format/wsdl'
    end
  end
end


text:
from pandas import timedelta_range
import pandas._testing as tm

class TestPickle:
    def test_pickle_after_set_freq(self):
        tdi = timedelta_range("1 day", periods=4, freq="s")
        tdi = tdi._with_freq(None)

        res = tm.round_trip_pickle(tdi)
        tm.assert_index_equal(res, tdi)


text:
class ModuleDocFragment(object):

    # Standard files documentation fragment
    DOCUMENTATION = r'''
options:
  authorize:
    description:
      - B(Deprecated)
      - "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes)."
      - For more information please see the L(IOS Platform Options guide, ../network/user_guide/platform_ios.html).
      - HORIZONTALLINE
      - Instructs the module to enter privileged mode on the remote device
        before sending any commands.  If not specified, the device will
        attempt to execute all commands in non-privileged mode. If the value
        is not specified in the task, the value of environment variable
        C(ANSIBLE_NET_AUTHORIZE) will be used instead.
    type: bool
    default: no
  auth_pass:
    description:
      - B(Deprecated)
      - "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes) with C(become_pass)."
      - For more information please see the L(IOS Platform Options guide, ../network/user_guide/platform_ios.html).
      - HORIZONTALLINE
      - Specifies the password to use if required to enter privileged mode
        on the remote device.  If I(authorize) is false, then this argument
        does nothing. If the value is not specified in the task, the value of
        environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead.
    type: str
  provider:
    description:
      - B(Deprecated)
      - "Starting with Ansible 2.5 we recommend using C(connection: network_cli)."
      - For more information please see the L(IOS Platform Options guide, ../network/user_guide/platform_ios.html).
      - HORIZONTALLINE
      - A dict object containing connection details.
    type: dict
    suboptions:
      host:
        description:
          - Specifies the DNS host name or address for connecting to the remote
            device over the specified transport.  The value of host is used as
            the destination address for the transport.
        type: str
        required: true
      port:
        description:
          - Specifies the port to use when building the connection to the remote device.
        type: int
        default: 22
      username:
        description:
          - Configures the username to use to authenticate the connection to
            the remote device.  This value is used to authenticate
            the SSH session. If the value is not specified in the task, the
            value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead.
        type: str
      password:
        description:
          - Specifies the password to use to authenticate the connection to
            the remote device.   This value is used to authenticate
            the SSH session. If the value is not specified in the task, the
            value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead.
        type: str
      timeout:
        description:
          - Specifies the timeout in seconds for communicating with the network device
            for either connecting or sending commands.  If the timeout is
            exceeded before the operation is completed, the module will error.
        type: int
        default: 10
      ssh_keyfile:
        description:
          - Specifies the SSH key to use to authenticate the connection to
            the remote device.   This value is the path to the
            key used to authenticate the SSH session. If the value is not specified
            in the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE)
            will be used instead.
        type: path
      authorize:
        description:
          - Instructs the module to enter privileged mode on the remote device
            before sending any commands.  If not specified, the device will
            attempt to execute all commands in non-privileged mode. If the value
            is not specified in the task, the value of environment variable
            C(ANSIBLE_NET_AUTHORIZE) will be used instead.
        type: bool
        default: no
      auth_pass:
        description:
          - Specifies the password to use if required to enter privileged mode
            on the remote device.  If I(authorize) is false, then this argument
            does nothing. If the value is not specified in the task, the value of
            environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead.
        type: str
notes:
  - For more information on using Ansible to manage network devices see the :ref:`Ansible Network Guide <network_guide>`
  - For more information on using Ansible to manage Cisco devices see the `Cisco integration page <https://www.ansible.com/integrations/networks/cisco>`_.
'''


text:
<?php

namespace Filehosting\Validation;

use Slim\Container;
use Slim\Http\UploadedFile;
use Filehosting\Entity\Comment;
use Filehosting\Helper\Utils;

/**
 * Validates File and Comment entities.
 *
 * @package Filehosting\Validation
 * @author foobar1643 <foobar76239@gmail.com>
 */
class Validation
{
    /**
     * @var \Slim\Container Slim framework DI container instance.
     */
    private $container;

    /**
     * @var \Filehosting\Database\CommentMapper CommentMapper instance.
     */
    private $commentMapper;

    /**
     * @var \Filehosting\Database\FileMapper FileMapper instance.
     */
    private $fileMapper;

    /**
     * Constructor.
     *
     * @param \Slim\Container $c DI container.
     */
    public function __construct(Container $c)
    {
        $this->container = $c;
        $this->commentMapper = $c->get('CommentMapper');
        $this->fileMapper = $c->get('FileMapper');
    }

    /**
     * Validates given UploadedFile object and returns an array with or without errors.
     *
     * @param \Slim\Http\UploadedFile $uploadedFile UploadedFile object to validate.
     *
     * @return array
     */
    public function validateUploadedFile(UploadedFile $uploadedFile)
    {
        $config = $this->container->get('config');
        $errors = null;
        if (is_null($uploadedFile->getClientFilename())) {
            $errors['noFile'] = _("Attach a file and try again.");
        }
        if (!is_null($uploadedFile->getClientFilename())
            && $uploadedFile->getSize() > $config->getValue('app', 'sizeLimit')) {
            $errors['sizeLimit'] = _("File size is exceeding the maximum.");
        }
        if (!is_null($uploadedFile->getClientFilename()) && $uploadedFile->getError() != UPLOAD_ERR_OK) {
            $errors['other'] = Utils::parseFileFormErrorCode($uploadedFile->getError());
        }
        return $errors;
    }

    /**
     * Validates given Comment object and returns an array with or without errors.
     *
     * @param \Filehosting\Entity\Comment $comment Comment object to validate.
     *
     * @return array
     */
    public function validateComment(Comment $comment)
    {
        $parentComment = null;
        $errors = null;
        if ($comment->getParentId() != null) {
            $parentComment = $this->commentMapper->getComment($comment->getParentId());
        }
        if ($this->fileMapper->getFile($comment->getFileId()) == false) {
            $errors["noFile"] = _("File does not exists.");
        }
        if (trim($comment->getCommentText()) == "") {
            $errors["noComment"] = _("The comment field is empty.");
        }
        if (strlen(trim($comment->getCommentText())) > 300) {
            $errors["commentTooBig"] = _("Comment mustn't be longer than 300 symbols.");
        }
        if ($comment->getParentId() != null && !$parentComment) {
            $errors["noParent"] = _("Parent comment does not exists.");
        }
        if ($comment->getParentId() != null && $parentComment && $parentComment->getDepth() >= 5) {
            $errors["maxDepthReached"] = _("Maximum comment depth reached.");
        }
        return $errors;
    }
}