text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

// this hack is needed to make this file compiles with -pedantic (gcc)
#ifdef __GNUC__
#define throw(X)
#endif
// discard stack allocation as that too bypasses malloc
#define EIGEN_STACK_ALLOCATION_LIMIT 0
// any heap allocation will raise an assert
#define EIGEN_NO_MALLOC

#include "main.h"
#include <Eigen/Cholesky>
#include <Eigen/Eigenvalues>
#include <Eigen/LU>
#include <Eigen/QR>
#include <Eigen/SVD>

template<typename MatrixType> void nomalloc(const MatrixType& m)
{
  /* this test check no dynamic memory allocation are issued with fixed-size matrices
  */
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;
  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;

  Index rows = m.rows();
  Index cols = m.cols();

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             m3(rows, cols);

  Scalar s1 = internal::random<Scalar>();

  Index r = internal::random<Index>(0, rows-1),
        c = internal::random<Index>(0, cols-1);

  VERIFY_IS_APPROX((m1+m2)*s1,              s1*m1+s1*m2);
  VERIFY_IS_APPROX((m1+m2)(r,c), (m1(r,c))+(m2(r,c)));
  VERIFY_IS_APPROX(m1.cwiseProduct(m1.block(0,0,rows,cols)), (m1.array()*m1.array()).matrix());
  VERIFY_IS_APPROX((m1*m1.transpose())*m2,  m1*(m1.transpose()*m2));

  m2.col(0).noalias() = m1 * m1.col(0);
  m2.col(0).noalias() -= m1.adjoint() * m1.col(0);
  m2.col(0).noalias() -= m1 * m1.row(0).adjoint();
  m2.col(0).noalias() -= m1.adjoint() * m1.row(0).adjoint();

  m2.row(0).noalias() = m1.row(0) * m1;
  m2.row(0).noalias() -= m1.row(0) * m1.adjoint();
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1;
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1.adjoint();
  VERIFY_IS_APPROX(m2,m2);

  m2.col(0).noalias() = m1.template triangularView<Upper>() * m1.col(0);
  m2.col(0).noalias() -= m1.adjoint().template triangularView<Upper>() * m1.col(0);
  m2.col(0).noalias() -= m1.template triangularView<Upper>() * m1.row(0).adjoint();
  m2.col(0).noalias() -= m1.adjoint().template triangularView<Upper>() * m1.row(0).adjoint();

  m2.row(0).noalias() = m1.row(0) * m1.template triangularView<Upper>();
  m2.row(0).noalias() -= m1.row(0) * m1.adjoint().template triangularView<Upper>();
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1.template triangularView<Upper>();
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1.adjoint().template triangularView<Upper>();
  VERIFY_IS_APPROX(m2,m2);

  m2.col(0).noalias() = m1.template selfadjointView<Upper>() * m1.col(0);
  m2.col(0).noalias() -= m1.adjoint().template selfadjointView<Upper>() * m1.col(0);
  m2.col(0).noalias() -= m1.template selfadjointView<Upper>() * m1.row(0).adjoint();
  m2.col(0).noalias() -= m1.adjoint().template selfadjointView<Upper>() * m1.row(0).adjoint();

  m2.row(0).noalias() = m1.row(0) * m1.template selfadjointView<Upper>();
  m2.row(0).noalias() -= m1.row(0) * m1.adjoint().template selfadjointView<Upper>();
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1.template selfadjointView<Upper>();
  m2.row(0).noalias() -= m1.col(0).adjoint() * m1.adjoint().template selfadjointView<Upper>();
  VERIFY_IS_APPROX(m2,m2);

  m2.template selfadjointView<Lower>().rankUpdate(m1.col(0),-1);
  m2.template selfadjointView<Lower>().rankUpdate(m1.row(0),-1);

  // The following fancy matrix-matrix products are not safe yet regarding static allocation
//   m1 += m1.template triangularView<Upper>() * m2.col(;
//   m1.template selfadjointView<Lower>().rankUpdate(m2);
//   m1 += m1.template triangularView<Upper>() * m2;
//   m1 += m1.template selfadjointView<Lower>() * m2;
//   VERIFY_IS_APPROX(m1,m1);
}

template<typename Scalar>
void ctms_decompositions()
{
  const int maxSize = 16;
  const int size    = 12;

  typedef Eigen::Matrix<Scalar,
                        Eigen::Dynamic, Eigen::Dynamic,
                        0,
                        maxSize, maxSize> Matrix;

  typedef Eigen::Matrix<Scalar,
                        Eigen::Dynamic, 1,
                        0,
                        maxSize, 1> Vector;

  typedef Eigen::Matrix<std::complex<Scalar>,
                        Eigen::Dynamic, Eigen::Dynamic,
                        0,
                        maxSize, maxSize> ComplexMatrix;

  const Matrix A(Matrix::Random(size, size)), B(Matrix::Random(size, size));
  Matrix X(size,size);
  const ComplexMatrix complexA(ComplexMatrix::Random(size, size));
  const Matrix saA = A.adjoint() * A;
  const Vector b(Vector::Random(size));
  Vector x(size);

  // Cholesky module
  Eigen::LLT<Matrix>  LLT;  LLT.compute(A);
  X = LLT.solve(B);
  x = LLT.solve(b);
  Eigen::LDLT<Matrix> LDLT; LDLT.compute(A);
  X = LDLT.solve(B);
  x = LDLT.solve(b);

  // Eigenvalues module
  Eigen::HessenbergDecomposition<ComplexMatrix> hessDecomp;        hessDecomp.compute(complexA);
  Eigen::ComplexSchur<ComplexMatrix>            cSchur(size);      cSchur.compute(complexA);
  Eigen::ComplexEigenSolver<ComplexMatrix>      cEigSolver;        cEigSolver.compute(complexA);
  Eigen::EigenSolver<Matrix>                    eigSolver;         eigSolver.compute(A);
  Eigen::SelfAdjointEigenSolver<Matrix>         saEigSolver(size); saEigSolver.compute(saA);
  Eigen::Tridiagonalization<Matrix>             tridiag;           tridiag.compute(saA);

  // LU module
  Eigen::PartialPivLU<Matrix> ppLU; ppLU.compute(A);
  X = ppLU.solve(B);
  x = ppLU.solve(b);
  Eigen::FullPivLU<Matrix>    fpLU; fpLU.compute(A);
  X = fpLU.solve(B);
  x = fpLU.solve(b);

  // QR module
  Eigen::HouseholderQR<Matrix>        hQR;  hQR.compute(A);
  X = hQR.solve(B);
  x = hQR.solve(b);
  Eigen::ColPivHouseholderQR<Matrix>  cpQR; cpQR.compute(A);
  X = cpQR.solve(B);
  x = cpQR.solve(b);
  Eigen::FullPivHouseholderQR<Matrix> fpQR; fpQR.compute(A);
  // FIXME X = fpQR.solve(B);
  x = fpQR.solve(b);

  // SVD module
  Eigen::JacobiSVD<Matrix> jSVD; jSVD.compute(A, ComputeFullU | ComputeFullV);
}

void test_nomalloc()
{
  // check that our operator new is indeed called:
  VERIFY_RAISES_ASSERT(MatrixXd dummy(MatrixXd::Random(3,3)));
  CALL_SUBTEST_1(nomalloc(Matrix<float, 1, 1>()) );
  CALL_SUBTEST_2(nomalloc(Matrix4d()) );
  CALL_SUBTEST_3(nomalloc(Matrix<float,32,32>()) );

  // Check decomposition modules with dynamic matrices that have a known compile-time max size (ctms)
  CALL_SUBTEST_4(ctms_decompositions<float>());

}


text:
package io.github.mzmine.modules.dataprocessing.id_ccscalibration.reference;

import io.github.mzmine.datamodel.IMSRawDataFile;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.datamodel.features.ModularFeatureList;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.modules.dataprocessing.id_ccscalibration.CCSCalculator;
import io.github.mzmine.modules.dataprocessing.id_ccscalibration.CCSCalibration;
import io.github.mzmine.modules.dataprocessing.id_ccscalibration.setcalibration.SetCCSCalibrationModule;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.taskcontrol.AbstractTask;
import io.github.mzmine.taskcontrol.TaskStatus;
import io.github.mzmine.util.MemoryMapStorage;
import java.time.Instant;
import java.util.Arrays;
import java.util.logging.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ReferenceCCSCalibrationTask extends AbstractTask {

  private static final Logger logger = Logger.getLogger(
      ReferenceCCSCalibrationTask.class.getName());

  private final CCSCalculator ccsCalculator;
  private final ParameterSet ccsCalculatorParameters;
  private final RawDataFile[] files;
  private final ModularFeatureList[] flists;
  private double progress = 0;
  private int processed = 0;

  public ReferenceCCSCalibrationTask(@Nullable MemoryMapStorage storage,
      @NotNull Instant moduleCallDate, ParameterSet ccsCalculatorParameters) {
    super(storage, moduleCallDate);
    this.ccsCalculator = MZmineCore.getModuleInstance(ReferenceCCSCalibrationModule.class);
    this.ccsCalculatorParameters = ccsCalculatorParameters;
    files = ccsCalculatorParameters.getValue(ReferenceCCSCalibrationParameters.files)
        ? ccsCalculatorParameters.getParameter(ReferenceCCSCalibrationParameters.files)
        .getEmbeddedParameter().getValue().getMatchingRawDataFiles() : new RawDataFile[0];
    flists = ccsCalculatorParameters.getValue(ReferenceCCSCalibrationParameters.flists)
        .getMatchingFeatureLists();
  }

  @Override
  public String getTaskDescription() {
    return "CCS calibration task using feature lists " + Arrays.toString(flists);
  }

  @Override
  public double getFinishedPercentage() {
    return progress;
  }

  @Override
  public void run() {
    setStatus(TaskStatus.PROCESSING);

    // either we have no raw data files and feature lists, or we have 1 feature list and multiple raw files.
    if (files.length != 0 && flists.length > 1) {
      setErrorMessage(
          "Invalid parameter selection. Either select one feature list and >= 1 raw data file or no raw data files. (Reference calibration)");
      setStatus(TaskStatus.CANCELED);
      return;
    }

    // set calibration to feature list's raw data files
    for (ModularFeatureList flist : flists) {
      final CCSCalibration calibration = ccsCalculator.getCalibration(flist,
          ccsCalculatorParameters);
      if (calibration == null) {
        logger.info("No calibration found using " + ccsCalculator + " "
            + ccsCalculatorParameters.toString());
        setErrorMessage("No calibration found.");
        setStatus(TaskStatus.CANCELED);
        return;
      }
      logger.info(() -> "Found ccs calibration " + calibration);

      flist.getRawDataFiles().stream().filter(f -> f instanceof IMSRawDataFile)
          .forEach(f -> ((IMSRawDataFile) f).setCCSCalibration(calibration));
      SetCCSCalibrationModule.setCalibrationToFiles(
          flist.getRawDataFiles().toArray(RawDataFile[]::new), calibration);
      processed++;
      progress = processed / (double) flists.length;

      // set calibration to additional raw files
      for (RawDataFile file : files) {
        if (file instanceof IMSRawDataFile imsFile && !flist.hasRawDataFile(file)) {
          imsFile.setCCSCalibration(calibration);
          processed++;
          progress = processed / (double) files.length;
        }
      }
      // for reproducibility, this might take a bit longer.
      SetCCSCalibrationModule.setCalibrationToFiles(files, calibration);
    }
    setStatus(TaskStatus.FINISHED);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace LVMS.Zipato.Model
{
    public class Schedule
    {
        public Guid Uuid { get; set; }
        public string Name { get; set; }
        public string Link { get; set; }
        [JsonProperty("config")]
        public ScheduleConfig Config { get; set; }
    }
}


text:
import { BreadcrumbItem } from './breadcrumbItem.model';
export declare class BreadcrumbComponent {
    listItems: Array<BreadcrumbItem>;
    linkLastItem: boolean;
    constructor();
}


text:
package org.wso2.carbon.bpel.core.ode.integration.mgt.services;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.common.Filter;
import org.apache.ode.bpel.common.InstanceFilter;
import org.apache.ode.bpel.common.ProcessFilter;
import org.apache.ode.bpel.dao.BpelDAOConnection;
import org.apache.ode.bpel.dao.ProcessDAO;
import org.apache.ode.bpel.dao.ProcessInstanceDAO;
import org.apache.ode.bpel.dd.*;
import org.apache.ode.bpel.engine.BpelDatabase;
import org.apache.ode.bpel.evt.BpelEvent;
import org.apache.ode.bpel.iapi.ProcessConf;
import org.apache.ode.bpel.iapi.ProcessState;
import org.apache.ode.bpel.pmapi.ProcessInfoCustomizer;
import org.apache.ode.bpel.pmapi.TInstanceStatus;
import org.apache.ode.utils.DOMUtils;
import org.apache.ode.utils.ISO8601DateParser;
import org.apache.ode.utils.stl.CollectionsX;
import org.apache.ode.utils.stl.MemberOfFunction;
import org.w3c.dom.Node;
import org.wso2.carbon.bpel.core.ode.integration.BPELServerImpl;
import org.wso2.carbon.bpel.core.ode.integration.store.ProcessConfigurationImpl;
import org.wso2.carbon.bpel.core.ode.integration.store.TenantProcessStoreImpl;
import org.wso2.carbon.bpel.core.ode.integration.utils.AdminServiceUtils;
import org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.ProcessManagementException;
import org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.ProcessManagementServiceSkeletonInterface;
import org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.types.*;
import org.wso2.carbon.core.AbstractAdmin;
import org.wso2.carbon.service.mgt.util.Utils;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * BPEL Process management service implementation.
 */
public class ProcessManagementServiceSkeleton extends AbstractAdmin
        implements ProcessManagementServiceSkeletonInterface {
    private static Log log = LogFactory.getLog(ProcessManagementServiceSkeleton.class);
    private BPELServerImpl bpelServer = BPELServerImpl.getInstance();
    private BpelDatabase bpelDb = bpelServer.getODEBPELServer().getBpelDb();

    public PaginatedProcessInfoList getPaginatedProcessList(String processListFilter,
                                                            String processListOrderByKey,
                                                            int page)
            throws ProcessManagementException {
        int tPage = page;

        PaginatedProcessInfoList processList = new PaginatedProcessInfoList();
        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();

        if (tPage < 0 || tPage == Integer.MAX_VALUE) {
            tPage = 0;
        }

        Integer itemsPerPage = 10;
        Integer startIndexForCurrentPage = tPage * itemsPerPage;
        Integer endIndexForCurrentPage = (tPage + 1) * itemsPerPage;

        final ProcessFilter processFilter =
                new ProcessFilter(processListFilter, processListOrderByKey);
        Collection<ProcessConf> processListForCurrentPage =
                processQuery(processFilter, tenantProcessStore);
        Integer processListSize = processListForCurrentPage.size();
        Integer pages = (int) Math.ceil((double) processListSize / itemsPerPage);
        processList.setPages(pages);

        ProcessConf[] processConfigurations =
                processListForCurrentPage.toArray(new ProcessConf[processListSize]);

        for (int i = startIndexForCurrentPage;
             (i < endIndexForCurrentPage && i < processListSize); i++) {
            processList.addProcessInfo(AdminServiceUtils.createLimitedProcessInfoObject(processConfigurations[i]));
        }

        return processList;
    }

    public java.lang.String[] getAllProcesses(String getAllProcesses)
            throws ProcessManagementException {
        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
        Set<QName> processIds = tenantProcessStore.getProcessConfigMap().keySet();
        List<String> pids = new ArrayList<String>();
        for (QName pid : processIds) {
            pids.add(pid.toString());
        }

        return pids.toArray(new String[pids.size()]);
    }

    /* The methods gets data from ProcessConfigurationImpl and display the details
    *  @param  pid
    *  @return processDeployDetailsList
    *
    */
    public ProcessDeployDetailsList_type0 getProcessDeploymentInfo(QName pid) {

        /* Configuring process basic information*/
        ProcessDeployDetailsList processDeployDetailsList = new ProcessDeployDetailsList();
        ProcessDeployDetailsList_type0 processDeployDetailsListType = new ProcessDeployDetailsList_type0();

        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
        ProcessConf processConf = tenantProcessStore.getProcessConfiguration(pid);
        ProcessConfigurationImpl processConfiguration = (ProcessConfigurationImpl) processConf;

        QName processId = processConfiguration.getProcessId();
        processDeployDetailsListType.setProcessName(processId);
        ProcessStatus processStatus =
                ProcessStatus.Factory.fromValue(processConfiguration.getState().name());
        processDeployDetailsListType.setProcessState(processStatus);
        processDeployDetailsListType.setIsInMemory(processConfiguration.isTransient());

        /* Configuring invoked services by the process*/
        List<TInvoke> invokeList = processConfiguration.getInvokedServices();
        if (invokeList != null) {

            InvokeServiceListType ist = new InvokeServiceListType();

            for (TInvoke invoke : invokeList) {

                InvokedServiceType invokedServiceType = new InvokedServiceType();

                Service_type1 service = new Service_type1();
                service.setName(invoke.getService().getName());
                service.setPort(invoke.getService().getPort());

                invokedServiceType.setService(service);
                invokedServiceType.setPartnerLink(invoke.getPartnerLink());

                ist.addInvokedService(invokedServiceType);
                processDeployDetailsListType.setInvokeServiceList(ist);
            }
        }

        /* Configuring providing services by the process*/
        List<TProvide> provideList = processConfiguration.getProvidedServices();
        if (provideList != null) {

            ProvideServiceListType pst = new ProvideServiceListType();

            for (TProvide provide : provideList) {

                ProvidedServiceType providedServiceType = new ProvidedServiceType();

                Service_type0 service = new Service_type0();
                service.setName(provide.getService().getName());
                service.setPort(provide.getService().getPort());

                providedServiceType.setService(service);

                providedServiceType.setPartnerLink(provide.getPartnerLink());

                pst.addProvidedService(providedServiceType);

            }
            processDeployDetailsListType.setProvideServiceList(pst);
        }

        /* Configuring message exchange interceptors of the process*/
        MexInterpreterListType mxt = new MexInterpreterListType();
        List<String> mexInterceptor = processConfiguration.getMexInterceptors();
        if (mexInterceptor != null) {

            for (String mexInt : mexInterceptor) {

                mxt.addMexinterpreter(mexInt);
            }

        }
        processDeployDetailsListType.setMexInterperterList(mxt);

        /* Configuring process level and scope level enabled events of process*/
        Map<String, Set<BpelEvent.TYPE>> eventsMap = processConfiguration.getEvents();

        ProcessEventsListType processEventsListType = new ProcessEventsListType();
        EnableEventListType enableEventListType = new EnableEventListType();
        ScopeEventListType scopeEventListType = new ScopeEventListType();

        for (Map.Entry<String, Set<BpelEvent.TYPE>> eventEntry : eventsMap.entrySet()) {
            if (eventEntry.getKey() != null) {

                ScopeEventType scopeEvent = new ScopeEventType();
                String scopeName = eventEntry.getKey();
                EnableEventListType enableEventList = new EnableEventListType();
                Set<BpelEvent.TYPE> typeSetforScope = eventEntry.getValue();
                for (BpelEvent.TYPE type : typeSetforScope) {
                    enableEventList.addEnableEvent(type.toString());
                }

                scopeEvent.setScope(scopeName);
                scopeEvent.setEnabledEventList(enableEventList);
                scopeEventListType.addScopeEvent(scopeEvent);
            } else {

                Set<BpelEvent.TYPE> typeSet = eventEntry.getValue();
                for (BpelEvent.TYPE aTypeSet : typeSet) {
                    enableEventListType.addEnableEvent(aTypeSet.toString());
                }
            }
        }

        TProcessEvents.Generate.Enum genEnum = processConfiguration.getGenerateType();
        if (genEnum != null) {
            Generate_type1 generate = Generate_type1.Factory.fromValue(genEnum.toString());
            processEventsListType.setGenerate(generate);
        }
        processEventsListType.setEnableEventsList(enableEventListType);
        processEventsListType.setScopeEventsList(scopeEventListType);

        processDeployDetailsListType.setProcessEventsList(processEventsListType);
        // end of process events

        /* configuring properties defined in the process */
        PropertyListType propertyListType = new PropertyListType();
        Map<QName, Node> propertiesMap = processConfiguration.getProcessProperties();
        Set<Map.Entry<QName, Node>> entries = propertiesMap.entrySet();
        for (Map.Entry entry : entries) {
            ProcessProperty_type0 property = new ProcessProperty_type0();
            property.setName((QName) entry.getKey());
            Node node = (Node) entry.getValue();
            property.setValue(DOMUtils.domToStringLevel2(node));
            propertyListType.addProcessProperty(property);
        }

        processDeployDetailsListType.setPropertyList(propertyListType);

        CleanUpListType cleanUpList = new CleanUpListType();
        Set<ProcessConf.CLEANUP_CATEGORY> sucessTypeCleanups = processConfiguration.getCleanupCategories(true);
        Set<ProcessConf.CLEANUP_CATEGORY> failureTypeCleanups = processConfiguration.getCleanupCategories(false);

        if (sucessTypeCleanups != null) {
            CleanUpType cleanUp = new CleanUpType();
            On_type1 onType = On_type1.success;
            cleanUp.setOn(onType);
            CategoryListType categoryListType = new CategoryListType();
            for (ProcessConf.CLEANUP_CATEGORY sCategory : sucessTypeCleanups) {
                Category_type1 categoryType1 = Category_type1.Factory.fromValue(sCategory.name().toLowerCase());
                categoryListType.addCategory(categoryType1);
            }

            cleanUp.setCategoryList(categoryListType);
            cleanUpList.addCleanUp(cleanUp);
        }

        if (failureTypeCleanups != null) {
            CleanUpType cleanUp = new CleanUpType();
            On_type1 onType = On_type1.failure;
            cleanUp.setOn(onType);
            CategoryListType categoryListType = new CategoryListType();
            for (ProcessConf.CLEANUP_CATEGORY fCategory : failureTypeCleanups) {
                Category_type1 categoryType1 = Category_type1.Factory.fromValue(fCategory.name().toLowerCase());
                categoryListType.addCategory(categoryType1);
            }

            cleanUp.setCategoryList(categoryListType);
            cleanUpList.addCleanUp(cleanUp);
        }
        processDeployDetailsListType.setCleanUpList(cleanUpList);

        processDeployDetailsList.setProcessDeployDetailsList(processDeployDetailsListType);
        return processDeployDetailsListType;
    }

    /*When a user modifies deploy info table they are updated in this method
    *
    * @param processDeployDetailsList
    *
    */

    public void updateDeployInfo(ProcessDeployDetailsList_type0 processDeployDetailsListType)
            throws ProcessManagementException {
        final QName processId = processDeployDetailsListType.getProcessName();
        try {

            TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
            ProcessConfigurationImpl processConf =
                    (ProcessConfigurationImpl) tenantProcessStore.getProcessConfiguration(processId);
            final boolean oldIsInmemory = processConf.isTransient();
            final boolean newIsInmemory = processDeployDetailsListType.getIsInMemory();
            processConf.setState(getProcessState(processDeployDetailsListType));
            processConf.setIsTransient(newIsInmemory);
            processConf.setProcessEventsList(processDeployDetailsListType.getProcessEventsList());
            processConf.setGenerateType(processDeployDetailsListType.getProcessEventsList());
            processConf.setProcessCleanupConfImpl(processDeployDetailsListType.getCleanUpList());
            if (tenantProcessStore.getBPELPackageRepository() != null) {
                tenantProcessStore.getBPELPackageRepository().
                        createPropertiesForUpdatedDeploymentInfo(processConf);
            }
            bpelServer.getODEBPELServer().getContexts().scheduler.execTransaction(new java.util.concurrent.Callable<Boolean>() {
                public Boolean call() throws Exception {

                    ProcessDAO processDAO;
                    ProcessDAO newProcessDAO;

                    if (oldIsInmemory & !newIsInmemory) {
                        processDAO = bpelServer.getODEBPELServer().getContexts().getInMemDao().getConnection().getProcess(processId);
                        if (bpelServer.getODEBPELServer().getContexts().dao.getConnection().getProcess(processId) == null) {
                            newProcessDAO = bpelServer.getODEBPELServer().getContexts().dao.getConnection().createProcess(processDAO.getProcessId(), processDAO.getType(), processDAO.getGuid(), processDAO.getVersion());

                            Set<String> correlatorsSet = processDAO.getCorrelatorsSet();
                            for (String correlator : correlatorsSet) {
                                newProcessDAO.addCorrelator(correlator);
                            }
                        }
                    } else if (!oldIsInmemory & newIsInmemory) {
                        QName pId = processId;
                        processDAO = bpelServer.getODEBPELServer().getContexts().dao.getConnection().getProcess(pId);
                        if (bpelServer.getODEBPELServer().getContexts().getInMemDao().getConnection().getProcess(pId) == null) {
                            newProcessDAO = bpelServer.getODEBPELServer().getContexts().getInMemDao().getConnection().createProcess(processDAO.getProcessId(), processDAO.getType(), processDAO.getGuid(), processDAO.getVersion());

                            Set<String> correlatorsSet = processDAO.getCorrelatorsSet();
                            for (String correlator : correlatorsSet) {
                                newProcessDAO.addCorrelator(correlator);
                            }
                        }
                    }

                    return null;
                }
            });

        } catch (Exception e) {
            String errMsg = "Error occurred while updating deployment info for: " + processId;
            log.error(errMsg, e);
            throw new ProcessManagementException(errMsg, e);
        }
    }

    public ProcessState getProcessState(ProcessDeployDetailsList_type0 deployDetailsListType) {
        ProcessStatus processStatus = deployDetailsListType.getProcessState();
        return ProcessState.valueOf(processStatus.getValue());
    }

    public void retireProcess(QName pid) throws ProcessManagementException {
        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
        try {
            tenantProcessStore.setState(pid, ProcessState.RETIRED);
        } catch (Exception e) {
            String errMsg = "Process: " + pid + " retirement failed.";
            log.error(errMsg, e);
            throw new ProcessManagementException(errMsg, e);
        }
    }

    public void activateProcess(QName pid) throws ProcessManagementException {
        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
        try {
            tenantProcessStore.setState(pid, ProcessState.ACTIVE);
        } catch (Exception e) {
            String errMsg = "Process: " + pid + " activation failed.";
            log.error(errMsg, e);
            throw new ProcessManagementException(errMsg, e);
        }
    }

    public ProcessInfoType getProcessInfo(QName pid) throws ProcessManagementException {
        ProcessInfoType processInfoType = new ProcessInfoType();
        TenantProcessStoreImpl tenantProcessStore = AdminServiceUtils.getTenantProcessStore();
        ProcessConf processConf = tenantProcessStore.getProcessConfiguration(pid);
        fillProcessInfo(processInfoType, processConf, ProcessInfoCustomizer.ALL, tenantProcessStore);

        return processInfoType;
    }

//    private java.lang.String[] getServiceLocationForProcess(QName processId)
//            throws ProcessManagementException {
//        AxisConfiguration axisConf = getConfigContext().getAxisConfiguration();
//        Map<String, AxisService> services = axisConf.getServices();
//        ArrayList<String> serviceEPRs = new ArrayList<String>();
//
//        for (AxisService service : services.values()) {
//            Parameter pIdParam = service.getParameter(BPELConstants.PROCESS_ID);
//            if (pIdParam != null) {
//                if (pIdParam.getValue().equals(processId)) {
//                    serviceEPRs.addAll(Arrays.asList(service.getEPRs()));
//                }
//            }
//        }
//
//        if (serviceEPRs.size() > 0) {
//            return serviceEPRs.toArray(new String[serviceEPRs.size()]);
//        }
//
//        String errMsg = "Cannot find service for process: " + processId;
//        log.error(errMsg);
//        throw new ProcessManagementException(errMsg);
//    }

    private void fillPartnerLinks(ProcessInfoType pInfo, TDeployment.Process processInfo)
            throws ProcessManagementException {
        if (processInfo.getProvideList() != null) {
            EndpointReferencesType eprsType = new EndpointReferencesType();
            for (TProvide provide : processInfo.getProvideList()) {
                String plinkName = provide.getPartnerLink();
                TService service = provide.getService();
                /* NOTE:Service cannot be null for provider partner link*/
                if (service == null) {
                    String errorMsg = "Error in <provide> element for process " +
                            processInfo.getName() + " partnerlink" + plinkName +
                            " did not identify an endpoint";
                    log.error(errorMsg);
                    throw new ProcessManagementException(errorMsg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Processing <provide> element for process " + processInfo.getName() +
                            ": partnerlink " + plinkName + " --> " + service.getName() + " : " +
                            service.getPort());
                }

                QName serviceName = service.getName();
                EndpointRef_type0 eprType = new EndpointRef_type0();
                eprType.setPartnerLink(plinkName);
                eprType.setService(serviceName);
                ServiceLocation sLocation = new ServiceLocation();
                try {
                    String url = Utils.getTryitURL(serviceName.getLocalPart(), getConfigContext());
                    sLocation.addServiceLocation(url);
                    String[] wsdls = Utils.getWsdlInformation(serviceName.getLocalPart(),
                            getConfigContext().getAxisConfiguration());
                    if(wsdls.length == 2){
                        if(wsdls[0].endsWith("?wsdl")) {
                            sLocation.addServiceLocation(wsdls[0]);
                        } else {
                            sLocation.addServiceLocation(wsdls[1]);
                        }
                    }
                } catch (AxisFault axisFault) {
                    String errMsg = "Error while getting try-it url for the service: " + serviceName;
                    log.error(errMsg, axisFault);
                    throw new ProcessManagementException(errMsg, axisFault);
                }
                eprType.setServiceLocations(sLocation);
                eprsType.addEndpointRef(eprType);
            }
            pInfo.setEndpoints(eprsType);
        }

//        if (processInfo.getInvokeList() != null) {
//            for (TInvoke invoke : processInfo.getInvokeList()) {
//                String plinkName = invoke.getPartnerLink();
//                TService service = invoke.getService();
//                /* NOTE:Service can be null for partner links*/
//                if (service == null) {
//                    continue;
//                }
//                if (log.isDebugEnabled()) {
//                    log.debug("Processing <invoke> element for process " + processInfo.getName() + ": partnerlink" +
//                              plinkName + " -->" + service);
//                }
//
//                QName serviceName = service.getName();
//            }
//        }

    }

    /**
     * Query processes based on a {@link org.apache.ode.bpel.common.ProcessFilter} criteria. This is
     * implemented in memory rather than via database calls since the processes
     * are managed by the {@link org.apache.ode.bpel.iapi.ProcessStore} object and we don't want to make
     * this needlessly complicated.
     *
     * @param filter              process filter
     * @param tenantsProcessStore Current Tenant's process store
     * @return ProcessConf collection
     * @throws ProcessManagementException if an error occurred while processing query
     */
    private Collection<ProcessConf> processQuery(ProcessFilter filter,
                                                 TenantProcessStoreImpl tenantsProcessStore)
            throws ProcessManagementException {

        Map<QName, ProcessConfigurationImpl> processes = tenantsProcessStore.getProcessConfigMap();
        if (log.isDebugEnabled()) {
            for (Map.Entry<QName, ProcessConfigurationImpl> process : processes.entrySet()) {
                log.debug("Process " + process.getKey() + " in state " + process.getValue());
            }
        }

        Set<QName> pids = processes.keySet();

        // Name filter can be implemented using only the PIDs.
        if (filter != null && filter.getNameFilter() != null) {
            // adding escape sequences to [\^$.|?*+(){} characters
            String nameFilter = filter.getNameFilter().replace("\\", "\\\\").replace("]", "\\]").
                    replace("[", "\\[").replace("^", "\\^").replace("$", "\\$").replace("|", "\\|").
                    replace("?", "\\?").replace(".", "\\.").replace("+", "\\+").replace("(", "\\(").
                    replace(")", "\\)").replace("{", "\\{").replace("}", "\\}").replace("*", ".*");
            final Pattern pattern = Pattern.compile(nameFilter + "(-\\d*)?");
            CollectionsX.remove_if(pids, new MemberOfFunction<QName>() {
                @Override
                public boolean isMember(QName o) {
                    return !pattern.matcher(o.getLocalPart()).matches();
                }
            });
        }

        if (filter != null && filter.getNamespaceFilter() != null) {
            // adding escape sequences to [\^$.|?*+(){} characters
            String namespaceFilter = filter.getNamespaceFilter().replace("\\", "\\\\").
                    replace("]", "\\]").replace("[", "\\[").replace("^", "\\^").replace("$", "\\$").
                    replace("|", "\\|").replace("?", "\\?").replace(".", "\\.").replace("+", "\\+").
                    replace("(", "\\(").replace(")", "\\)").replace("{", "\\{").replace("}", "\\}").
                    replace("*", ".*");
            final Pattern pattern = Pattern.compile(namespaceFilter);
            CollectionsX.remove_if(pids, new MemberOfFunction<QName>() {
                @Override
                public boolean isMember(QName o) {
                    String ns = o.getNamespaceURI() == null ? "" : o.getNamespaceURI();
                    return !pattern.matcher(ns).matches();
                }

            });
        }

        // Now we need the process conf objects, we need to be
        // careful since someone could have deleted them by now
        List<ProcessConf> confs = new LinkedList<ProcessConf>();
        for (QName pid : pids) {
            ProcessConf pConf = tenantsProcessStore.getProcessConfiguration(pid);
            if (pConf != null) {
                confs.add(pConf);
            }
        }

        if (filter != null) {
            // TODO Implement process status filtering when status will exist
            // Specific filter for deployment date.
            if (filter.getDeployedDateFilter() != null) {
                for (final String ddf : filter.getDeployedDateFilter()) {
                    final Date dd;
                    try {
                        dd = ISO8601DateParser.parse(Filter.getDateWithoutOp(ddf));
                    } catch (ParseException e) {
                        // Should never happen.
                        String errMsg = "Exception while parsing date";
                        log.error(errMsg, e);
                        throw new ProcessManagementException(errMsg, e);
                    }

                    CollectionsX.remove_if(confs, new MemberOfFunction<ProcessConf>() {
                        @Override
                        public boolean isMember(ProcessConf o) {
                            if (ddf.startsWith("=")) {
                                return !o.getDeployDate().equals(dd);
                            }
                            if (ddf.startsWith("<=")) {
                                return o.getDeployDate().getTime() > dd.getTime();
                            }
                            if (ddf.startsWith(">=")) {
                                return o.getDeployDate().getTime() < dd.getTime();
                            }
                            if (ddf.startsWith("<")) {
                                return o.getDeployDate().getTime() >= dd.getTime();
                            }
                            return ddf.startsWith(">") && (o.getDeployDate().getTime() <= dd.getTime());
                        }
                    });
                }
            }

            // Ordering
            if (filter.getOrders() != null) {
                ComparatorChain cChain = new ComparatorChain();
                for (String key : filter.getOrders()) {
                    boolean ascending = true;
                    String orderKey = key;
                    if (key.startsWith("+") || key.startsWith("-")) {
                        orderKey = key.substring(1, key.length());
                        if (key.startsWith("-")) {
                            ascending = false;
                        }
                    }

                    Comparator c;
                    if ("name".equals(orderKey)) {
                        c = new Comparator<ProcessConf>() {
                            public int compare(ProcessConf o1, ProcessConf o2) {
                                return o1.getProcessId().getLocalPart().compareTo(o2.getProcessId().
                                        getLocalPart());
                            }
                        };
                    } else if ("namespace".equals(orderKey)) {
                        c = new Comparator<ProcessConf>() {
                            public int compare(ProcessConf o1, ProcessConf o2) {
                                String ns1 = o1.getProcessId().getNamespaceURI() == null ? "" :
                                        o1.getProcessId().getNamespaceURI();
                                String ns2 = o2.getProcessId().getNamespaceURI() == null ? "" :
                                        o2.getProcessId().getNamespaceURI();
                                return ns1.compareTo(ns2);
                            }
                        };
                    } else if ("version".equals(orderKey)) {
                        c = new Comparator<ProcessConf>() {
                            public int compare(ProcessConf o1, ProcessConf o2) {
                                return (int) (o1.getVersion() - o2.getVersion());
                            }
                        };
                    } else if ("deployed".equals(orderKey)) {
                        c = new Comparator<ProcessConf>() {
                            public int compare(ProcessConf o1, ProcessConf o2) {
                                return o1.getDeployDate().compareTo(o2.getDeployDate());
                            }
                        };
                    } else if ("status".equals(orderKey)) {
                        c = new Comparator<ProcessConf>() {
                            public int compare(ProcessConf o1, ProcessConf o2) {
                                return o1.getState().compareTo(o2.getState());
                            }
                        };
                    } else {
                        // unrecognized
                        if (log.isDebugEnabled()) {
                            log.debug("unrecognized order key" + orderKey);
                        }
                        continue;
                    }

                    cChain.addComparator(c, !ascending);
                }

                Collections.sort(confs, cChain);
            }
        }

        return confs;
    }

    /**
     * Fill in the <code>ProcessInfo</code> element of the transfer object.
     *
     * @param info               destination XMLBean
     * @param pconf              process configuration object (from store)
     * @param custom             used to customize the quantity of information produced in the
     *                           info
     * @param tenantProcessStore Tenant's Process store
     * @throws ProcessManagementException If an error occurred while filling process information
     */
    private void fillProcessInfo(ProcessInfoType info, ProcessConf pconf,
                                 ProcessInfoCustomizer custom,
                                 TenantProcessStoreImpl tenantProcessStore)
            throws ProcessManagementException {
        if (pconf == null) {
            String errMsg = "Process configuration cannot be null.";
            log.error(errMsg);
            throw new ProcessManagementException(errMsg);
        }

        info.setPid(pconf.getProcessId().toString());
        // TODO: ACTIVE and RETIRED should be used separately.
        // Active process may be retired at the same time
        if (pconf.getState() == ProcessState.RETIRED) {
            info.setStatus(ProcessStatus.RETIRED);
            info.setOlderVersion(AdminServiceUtils.isOlderVersion(pconf, tenantProcessStore));
        } else if (pconf.getState() == ProcessState.DISABLED) {
            info.setStatus(ProcessStatus.DISABLED);
            info.setOlderVersion(0);
        } else {
            info.setStatus(ProcessStatus.ACTIVE);
            info.setOlderVersion(0);
        }
        info.setVersion(pconf.getVersion());

        DefinitionInfo defInfo = new DefinitionInfo();
        defInfo.setProcessName(pconf.getType());
        BpelDefinition bpelDefinition = new BpelDefinition();
        bpelDefinition.setExtraElement(getProcessDefinition(pconf));
        defInfo.setDefinition(bpelDefinition);

        info.setDefinitionInfo(defInfo);

        DeploymentInfo depInfo = new DeploymentInfo();
        depInfo.setPackageName(pconf.getPackage());
        depInfo.setDocument(pconf.getBpelDocument());
        depInfo.setDeployDate(AdminServiceUtils.toCalendar(pconf.getDeployDate()));
        // TODO: Need to fix this by adding info to process conf.
        depInfo.setDeployer(org.wso2.carbon.bpel.core.BPELConstants.BPEL_DEPLOYER_NAME);
        info.setDeploymentInfo(depInfo);

        if (custom.includeInstanceSummary()) {
            InstanceSummary instanceSummary = new InstanceSummary();
            addInstanceSummaryEntry(instanceSummary, pconf, InstanceStatus.ACTIVE);
            addInstanceSummaryEntry(instanceSummary, pconf, InstanceStatus.COMPLETED);
            addInstanceSummaryEntry(instanceSummary, pconf, InstanceStatus.FAILED);
            addInstanceSummaryEntry(instanceSummary, pconf, InstanceStatus.SUSPENDED);
            addInstanceSummaryEntry(instanceSummary, pconf, InstanceStatus.TERMINATED);
            addFailuresToInstanceSummary(instanceSummary, pconf);

            info.setInstanceSummary(instanceSummary);

        }

        if (custom.includeProcessProperties()) {
            ProcessProperties processProps = new ProcessProperties();
            for (Map.Entry<QName, Node> propEntry : pconf.getProcessProperties().entrySet()) {
                QName key = propEntry.getKey();
                if (key != null) {
                    Property_type0 prop = new Property_type0();
                    prop.setName(new QName(key.getNamespaceURI(), key.getLocalPart()));
                    OMFactory omFac = OMAbstractFactory.getOMFactory();
                    OMElement propEle = omFac.createOMElement("PropertyValue", null);
                    propEle.setText(propEntry.getValue().getNodeValue());
                    prop.addExtraElement(propEle);
                    processProps.addProperty(prop);
                }
            }
            info.setProperties(processProps);
        }

        fillPartnerLinks(info, ((ProcessConfigurationImpl) pconf).getProcessDeploymentInfo());
    }

    private void addInstanceSummaryEntry(InstanceSummary instSum, ProcessConf pconf,
                                         InstanceStatus state) throws ProcessManagementException {
        Instances_type0 instances = new Instances_type0();
        instances.setState(state);
        String queryStatus = InstanceFilter.StatusKeys.valueOf(state.toString()).toString().
                toLowerCase();
        final InstanceFilter instanceFilter = new InstanceFilter("status=" + queryStatus
                + " pid=" + pconf.getProcessId());

        int count = dbexec(new BpelDatabase.Callable<Integer>() {

            public Integer run(BpelDAOConnection conn) throws Exception {
                return conn.instanceCount(instanceFilter).intValue();
            }
        });
        instances.setCount(count);
        instSum.addInstances(instances);
    }

    private void addFailuresToInstanceSummary(final InstanceSummary instSum, ProcessConf pconf)
            throws ProcessManagementException {
        final FailuresInfo failureInfo = new FailuresInfo();
        String queryStatus = InstanceFilter.StatusKeys.valueOf(TInstanceStatus.ACTIVE.toString()).
                toString().toLowerCase();
        final InstanceFilter instanceFilter = new InstanceFilter("status=" + queryStatus
                + " pid=" + pconf.getProcessId());
        dbexec(new BpelDatabase.Callable<Void>() {
            public Void run(BpelDAOConnection conn) throws Exception {
                Date lastFailureDt = null;
                int failureInstances = 0;
                for (ProcessInstanceDAO instance : conn.instanceQuery(instanceFilter)) {
                    int count = instance.getActivityFailureCount();
                    if (count > 0) {
                        ++failureInstances;
                        Date failureDt = instance.getActivityFailureDateTime();
                        if (lastFailureDt == null || lastFailureDt.before(failureDt)) {
                            lastFailureDt = failureDt;
                        }
                    }
                }
                if (failureInstances > 0) {
                    failureInfo.setCount(failureInstances);
                    failureInfo.setFailureDate(AdminServiceUtils.toCalendar(lastFailureDt));
                    instSum.setFailures(failureInfo);
                }
                return null;
            }
        });
    }

    /**
     * Execute a database transaction, unwrapping nested
     * {@link org.apache.ode.bpel.pmapi.ManagementException}s.
     *
     * @param callable action to run
     * @return object of type T
     * @throws ProcessManagementException if exception occurred during transaction
     */
    protected <T> T dbexec(BpelDatabase.Callable<T> callable) throws ProcessManagementException {
        try {
            return bpelDb.exec(callable);
        } catch (Exception ex) {
            String errMsg = "Exception during database operation ";
            log.error(errMsg, ex);
            throw new ProcessManagementException(errMsg, ex);
        }
    }

    private OMElement getProcessDefinition(ProcessConf pConf) throws ProcessManagementException {
        if (pConf == null) {
            String errMsg = "Process configuration cannot be null.";
            log.error(errMsg);
            throw new ProcessManagementException(errMsg);
        }

        String bpelDoc = pConf.getBpelDocument();
        List<File> files = pConf.getFiles();

        for (final File file : files) {
            if (file.getPath().endsWith(bpelDoc) ||
                    file.getPath().endsWith(bpelDoc.replaceAll("/", "\\\\"))) {
                XMLStreamReader reader;
                FileInputStream fis = null;
                OMElement bpelDefinition;
                try {
                    fis = new FileInputStream(file);
                    XMLInputFactory xif = XMLInputFactory.newInstance();
                    reader = xif.createXMLStreamReader(fis);
                    StAXOMBuilder builder = new StAXOMBuilder(reader);
                    bpelDefinition = builder.getDocumentElement();
                    bpelDefinition.build();
                } catch (XMLStreamException e) {
                    String errMsg = "XML stream reader exception: " + file.getAbsolutePath();
                    log.error(errMsg, e);
                    throw new ProcessManagementException(errMsg, e);
                } catch (FileNotFoundException e) {
                    String errMsg = "BPEL File reading exception: " + file.getAbsolutePath();
                    log.error(errMsg, e);
                    throw new ProcessManagementException(errMsg, e);
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            log.warn("Cannot close file input stream.", e);
                        }
                    }
                }

                return bpelDefinition;
            }
        }

        String errMsg = "Process Definition for: " + pConf.getProcessId() + " not found";
        log.error(errMsg);
        throw new ProcessManagementException(errMsg);
    }
}


text:
/* globals describe, expect, it */

import { Queue } from '../../../src/main.js'

describe('Queue.js', function () {

  describe('first ()', function () {

    it('returns null if no item in the queue', function () {
      var queue = new Queue()
      expect(queue.first()).toEqual(null)
    })

    it('returns the first value in the queue', function () {
      var queue = new Queue()
      queue.push(1)
      expect(queue.first()).toBe(1)
      queue.push(2)
      expect(queue.first()).toBe(1)
    })
  })

  describe('last ()', function () {

    it('returns null if no item in the queue', function () {
      var queue = new Queue()
      expect(queue.last()).toEqual(null)
    })

    it('returns the last value added', function () {
      var queue = new Queue()
      queue.push(1)
      expect(queue.last()).toBe(1)
      queue.push(2)
      expect(queue.last()).toBe(2)
    })
  })

  describe('push ()', function () {

    it('adds an element to the end of the queue', function () {
      var queue = new Queue()
      queue.push(1)
      queue.push(2)
      queue.push(3)

      expect(queue.first()).toBe(1)
      expect(queue.last()).toBe(3)
    })

    it('adds an item to the end of the queue', function () {
      var queue = new Queue()
      queue.push(1)
      const item = queue.push(2)
      queue.push(3)
      queue.remove(item)
      queue.push(item)

      expect(queue.first()).toBe(1)
      expect(queue.last()).toBe(2)
    })
  })

  describe('remove ()', function () {
    it('removes the given item from the queue', function () {
      var queue = new Queue()
      queue.push(1)
      queue.push(2)
      var item = queue.push(3)

      queue.remove(item)

      expect(queue.last()).toBe(2)
      expect(queue.first()).toBe(1)
    })

    it('removes the given item from the queue', function () {
      var queue = new Queue()
      var item = queue.push(1)
      queue.push(2)
      queue.push(3)

      queue.remove(item)

      expect(queue.last()).toBe(3)
      expect(queue.first()).toBe(2)
    })
  })

  describe('shift ()', function () {
    it('returns nothing if queue is empty', function () {
      var queue = new Queue()
      var val = queue.shift()
      expect(val).toBeFalsy()
    })

    it('returns the first item of the queue and removes it', function () {
      var queue = new Queue()
      queue.push(1)
      queue.push(2)
      queue.push(3)

      var val = queue.shift()

      expect(queue.last()).toBe(3)
      expect(queue.first()).toBe(2)

      expect(val).toBe(1)
    })
  })
})


text:
function hfile = dmr_SaveDWI(hfile, totio)
% DMR::SaveDWI  - save memory-bound DWI data
%
% FORMAT:       [dmr] = dmr.SaveDWI([totio]);
%
% Input fields:
%
%       totio       if given and true convert data to transio object
%
% No output fields.
%
% Note: if the DWIData field is a transio, the function does nothing.

% Version:  v0.9d
% Build:    14061710
% Date:     Jun-17 2014, 10:30 AM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
%
% Copyright (c) 2010, 2011, 2014, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% argument check
if nargin ~= 1 || ...
    numel(hfile) ~= 1 || ...
   ~xffisobject(hfile, true, 'dmr')
    error( ...
        'xff:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
if nargin < 2 || ...
   ~islogical(totio) || ...
    isempty(totio)
    totio = false;
else
    totio = totio(1);
end

% try saving the DWI
sc = xffgetscont(hfile.L);
bc = sc.C;
if istransio(bc.DWIData)
    return;
end
[dfpn{1:3}] = fileparts(sc.F);
dsf = bc.DataStorageFormat;
nov = bc.NrOfVolumes;
nos = bc.NrOfSlices;
rsx = bc.ResolutionX;
rsy = bc.ResolutionY;
switch (dsf)
    case {2}
        dds = [rsx, rsy, nov, nos];
    case {3}
        dds = [rsx, rsy, nos, nov];
    case {4}
        dds = [nov, rsx, rsy, nos];
    otherwise
        error( ...
            'xff:InvalidObject', ...
            'Unsupported DataStorageFormat field.' ...
        );
end
if ~isequal(size(bc.DWIData), dds) || ...
   (~isa(bc.DWIData, 'uint16') && ...
    ~isa(bc.DWIData, 'single') && ...
    ~istransio(bc.DWIData))
    error( ...
        'xff:InvalidObject', ...
        'Invalid DataStorageFormat, dimensions and/or datatype.' ...
    );
end

% create filename
if any(dfpn{3}(2:end) == upper(dfpn{3}(2:end)))
    dfpn{3} = '.DWI';
else
    dfpn{3} = '.dwi';
end
dwif = [dfpn{1} '/' dfpn{2} dfpn{3}];
try
    dwii = fopen(dwif, 'w', 'ieee-le');
    if dwii < 1
        error('FILEOPEN_FAILED');
    end
    if bc.DataType == 1
        fwrite(dwii, bc.DWIData(:), 'uint16');
    else
        fwrite(dwii, bc.DWIData(:), 'single');
    end
    fclose(dwii);
catch ne_eo;
    neuroelf_lasterr(ne_eo);
    error( ...
        'BQVXfile:FileNotWritable', ...
        'File not writable: ''%s''.', ...
        dwif ...
    );
end

% reload as transio?
if totio
    try
        if bc.DataType == 1
            bc.DWIData = transio(dwif, 'ieee-le', 'uint16', 0, dds);
        else
            bc.DWIData = transio(dwif, 'ieee-le', 'single', 0, dds);
        end
    catch ne_eo;
        error( ...
            'xff:transioError', ...
            'Error reopening the written file as transio: %s.', ...
            ne_eo.message ...
        );
    end
    xffsetcont(hfile.L, bc);
end


text:
<%def name="topbar(project=None, team=None)">
% if project or team:
<%
  target = project if project else team
%>

            Create New Issue

      Sort By:

        % if order=='hot':

            DATE

            HOT

        % else:

            DATE

            HOT

        % endif

% endif
</%def>


text:
import { html, PolymerElement } from 'https://unpkg.com/@polymer/polymer@3.4.1/polymer-element.js';

export default class NumericEditor extends PolymerElement {
    static get template() {
        return html`
        <input id="input" on-keydown="onKeyDown" value="{{value::input}}">
        `;
    }

    agInit(params) {
        this.params = params;
        this.value = this.params.value;

        // only start edit if key pressed is a number, not a letter
        this.cancelBeforeStart = params.charPress && ('1234567890'.indexOf(params.charPress) < 0);
    }

    ready() {
        super.ready();
        this.$.input.focus();
    }

    getValue() {
        return this.value;
    }

    isCancelBeforeStart() {
        return this.cancelBeforeStart;
    }

    // will reject the number if it greater than 1,000,000
    // not very practical, but demonstrates the method.
    isCancelAfterEnd() {
        return this.value > 1000000;
    };

    finishedEditingPressed(event) {
        const KEY_ENTER = 13;
        const KEY_TAB = 9;
        const KEY_ESC = 27;

        const charCode = this.getCharCodeFromEvent(event);
        return charCode === KEY_ENTER || charCode === KEY_TAB || charCode === KEY_ESC;
    }

    onKeyDown(event) {
        if (!this.finishedEditingPressed(event) && !this.isKeyPressedNumeric(event)) {
            if (event.preventDefault) event.preventDefault();
        }
    }

    getCharCodeFromEvent(event) {
        event = event || window.event;
        return typeof event.which == 'undefined' ? event.keyCode : event.which;
    }

    isCharNumeric(charStr) {
        return !!/\d/.test(charStr);
    }

    isKeyPressedNumeric(event) {
        var charCode = this.getCharCodeFromEvent(event);
        var charStr = String.fromCharCode(charCode);
        return this.isCharNumeric(charStr);
    }

    static get properties() {
        return {
            value: Number
        };
    }
}

customElements.define('numeric-editor', NumericEditor);


text:
//
//  CJUploadImagePickerUtil.m
//  CJPickerDemo
//
//  Created by ciyouzen on 2017/8/30.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "CJUploadImagePickerUtil.h"

#import <AVFoundation/AVFoundation.h>
#import <CJFile/CJFileManager+GetCreatePath.h>
#import <CJFile/CJFileManager+SaveFileData.h>

@implementation CJUploadImagePickerUtil

/* 完整的描述请参见文件头部 */
+ (CJSystemImagePickerController *)takePhotoPickerWithPickCompleteBlock:(void (^)(NSArray<CJImageUploadFileModelsOwner *> *pickedImageItems))pickImageCompleteBlock
{
    CJSystemImagePickerController *singleImagePickerController = [[CJSystemImagePickerController alloc] init];
    [singleImagePickerController setSingleMediaTypeForVideo:NO];
    singleImagePickerController.saveLocation = CJSaveLocationNone;
    [singleImagePickerController pickImageFinishBlock:^(UIImage *image)
     {
         CJImageUploadFileModelsOwner *imageItem = [self saveImageToSandbox:image];  //保存图片到APP沙盒中
         if (pickImageCompleteBlock) {
             pickImageCompleteBlock(@[imageItem]);
         }

     } pickVideoFinishBlock:nil pickCancelBlock:^{

     }];

    return singleImagePickerController;
}

/* 完整的描述请参见文件头部 */
+ (CJImagePickerViewController *)choosePhotoPickerWithCanMaxChooseImageCount:(NSInteger)canMaxChooseImageCount pickCompleteBlock:(void (^)(NSArray<CJImageUploadFileModelsOwner *> *pickedImageItems))pickImageCompleteBlock
{
    /*
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //NSArray<NSString *> *mediaTypes = @[(NSString *)kUTTypeImage];

    UIImagePickerControllerUtil *imagePickerControllerUtil = [UIImagePickerControllerUtil sharedInstance];
    imagePickerControllerUtil.saveLocation = CJSaveLocationNone;
    [imagePickerControllerUtil openImagePickerControllerWithSourceType:sourceType isVideo:NO inViewController:self.belongToViewController pickImageFinishBlock:^(UIImage *image)
     {
         CJImageUploadFileModelsOwner *imageItem = [self saveImageToSandbox:image];  //保存图片到APP沙盒中

         [self.dataModels addObject:imageItem];

         [self reloadData];
         if (self.pickImageCompleteBlock) {
             self.pickImageCompleteBlock();
         }

     } pickVideoFinishBlock:nil pickCancelBlock:^{

     }];
    return;
    */
    return nil;
//    CJImagePickerViewController *imagePickerViewController = [[CJImagePickerViewController alloc] init];
//    imagePickerViewController.canMaxChooseImageCount = canMaxChooseImageCount;
//    imagePickerViewController.pickCompleteBlock = ^(NSArray<AlumbImageModel *> *imageModels) {
//        NSMutableArray *pickerImageModels = [[NSMutableArray alloc] init];
//        for (NSInteger i = 0; i < imageModels.count; i++) {
//            AlumbImageModel *item = imageModels[i];
//            UIImage *image = item.image;
//
//            CJImageUploadFileModelsOwner *imageItem = [self saveImageToSandbox:image];   //保存图片到APP沙盒中
//            [pickerImageModels addObject:imageItem];
//        }
//        //选择结束
//        if (pickImageCompleteBlock) {
//            pickImageCompleteBlock(pickerImageModels);
//        }
//    };
//
//    return imagePickerViewController;
}

/**< 保存图片到APP沙盒中 */
+ (CJImageUploadFileModelsOwner *)saveImageToSandbox:(UIImage *)image {
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

    //文件名
    NSString *identifier = [[NSProcessInfo processInfo] globallyUniqueString];
    NSString *imageName = [identifier stringByAppendingPathExtension:@"jpg"];

    NSString *fileRelativePath =
    [CJFileManager getLocalDirectoryPathType:CJLocalPathTypeRelative
                          bySubDirectoryPath:@"CJUploadImage"
                       inSearchPathDirectory:NSCachesDirectory
                             createIfNoExist:YES];
    [CJFileManager saveFileData:imageData withFileName:imageName toRelativeDirectoryPath:fileRelativePath];

    //图片
    CJUploadFileModel *imageUploadModel = [[CJUploadFileModel alloc] initWithItemType:CJUploadItemTypeImage itemName:imageName itemData:imageData itemKey:@"file"];

    CJImageUploadFileModelsOwner *imageItem =
    [[CJImageUploadFileModelsOwner alloc] initWithShowImage:image
                          imageLocalRelativePath:fileRelativePath
                                uploadFileModels:@[imageUploadModel]];

    return imageItem;
}

@end


text:
@implementation XDLCityModel
+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"districts" : NSClassFromString(@"XDLDistrictModel")};
}
@end


text:
"""
Fake VMEM REST client for testing drivers.
"""

import sys

import mock

# The following gymnastics to fake an exception class globally is done because
# we want to globally model and make available certain exceptions.  If we do
# not do this, then the real-driver's import will not see our fakes.
class NoMatchingObjectIdError(Exception):
    pass

error = mock.Mock()
error.NoMatchingObjectIdError = NoMatchingObjectIdError

core = mock.Mock()
core.attach_mock(error, 'error')

vmemclient = mock.Mock()
vmemclient.__version__ = "unknown"
vmemclient.attach_mock(core, 'core')

sys.modules['vmemclient'] = vmemclient

mock_client_conf = [
    'basic',
    'basic.login',
    'basic.get_node_values',
    'basic.save_config',
    'lun',
    'lun.export_lun',
    'lun.unexport_lun',
    'snapshot',
    'snapshot.export_lun_snapshot',
    'snapshot.unexport_lun_snapshot',
    'iscsi',
    'iscsi.bind_ip_to_target',
    'iscsi.create_iscsi_target',
    'iscsi.delete_iscsi_target',
    'igroup',
    'client',
    'client.get_client_info',
    'client.create_client',
    'client.delete_client',
    'adapter',
    'adapter.get_fc_info',
    'pool',
    'utility',
]


text: Role that has access to parent Page


text:
package org.apache.jsp.include_005fjsp.myTerrier;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import net.violet.platform.util.StaticTools;
import net.violet.platform.util.SessionTools;
import net.violet.platform.datamodel.Lang;
import net.violet.platform.util.DicoTools;
import net.violet.platform.util.MyConstantes;

public final class inc_005fmyTerrierEditComment_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static java.util.List _jspx_dependants;

  static {
    _jspx_dependants = new java.util.ArrayList(1);
    _jspx_dependants.add("/include_jsp/utils/inc_dico.jsp");
  }

  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_form_styleId_action;
  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_hidden_value_property_nobody;
  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_textarea_style_rows_property_nobody;
  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_logic_empty_property_name;
  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_logic_notEmpty_property_name;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _jspx_tagPool_html_form_styleId_action = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _jspx_tagPool_html_hidden_value_property_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _jspx_tagPool_html_textarea_style_rows_property_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _jspx_tagPool_logic_empty_property_name = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _jspx_tagPool_logic_notEmpty_property_name = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
  }

  public void _jspDestroy() {
    _jspx_tagPool_html_form_styleId_action.release();
    _jspx_tagPool_html_hidden_value_property_nobody.release();
    _jspx_tagPool_html_textarea_style_rows_property_nobody.release();
    _jspx_tagPool_logic_empty_property_name.release();
    _jspx_tagPool_logic_notEmpty_property_name.release();
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\r\n\n\r\n");
 response.setContentType("text/html;charset=UTF-8");
      out.write("\r\n\r\n\r\n\r\n\r\n");
      out.write('\n');
      out.write('\r');
      out.write('\n');
      out.write("\r\n\n\n");
	Lang dico_lang =	SessionTools.getLangFromSession(session, request);
      out.write("\n\r\n
\r\n");
      out.print(DicoTools.dico(dico_lang, "myTerrier/comment_intro"));
      out.write('\r');
      out.write('\n');
      //  html:form
      org.apache.struts.taglib.html.FormTag _jspx_th_html_form_0 = (org.apache.struts.taglib.html.FormTag) _jspx_tagPool_html_form_styleId_action.get(org.apache.struts.taglib.html.FormTag.class);
      _jspx_th_html_form_0.setPageContext(_jspx_page_context);
      _jspx_th_html_form_0.setParent(null);
      _jspx_th_html_form_0.setAction("/action/myTerrierEditComment");
      _jspx_th_html_form_0.setStyleId("editComment");
      int _jspx_eval_html_form_0 = _jspx_th_html_form_0.doStartTag();
      if (_jspx_eval_html_form_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
        do {
          out.write('\r');
          out.write('\n');
          out.write('	');
          if (_jspx_meth_html_hidden_0(_jspx_th_html_form_0, _jspx_page_context))
            return;
          out.write('\r');
          out.write('\n');
          out.write('	');
          if (_jspx_meth_html_textarea_0(_jspx_th_html_form_0, _jspx_page_context))
            return;
          out.write("\r\n\t
\r\n\t\t");
          //  logic:empty
          org.apache.struts.taglib.logic.EmptyTag _jspx_th_logic_empty_0 = (org.apache.struts.taglib.logic.EmptyTag) _jspx_tagPool_logic_empty_property_name.get(org.apache.struts.taglib.logic.EmptyTag.class);
          _jspx_th_logic_empty_0.setPageContext(_jspx_page_context);
          _jspx_th_logic_empty_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0);
          _jspx_th_logic_empty_0.setName("myTerrierEditCommentForm");
          _jspx_th_logic_empty_0.setProperty("rabbitAnnounce");
          int _jspx_eval_logic_empty_0 = _jspx_th_logic_empty_0.doStartTag();
          if (_jspx_eval_logic_empty_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
            do {
              out.write("\r\n\t\t\t<input type=\"button\" name=\"txtsave\" value=\"");
              out.print(DicoTools.dico(dico_lang, "myTerrier/comment_add"));
              out.write("\" onclick=\"simpleAjaxSubmit('editComment')\">\r\n\t\t");
              int evalDoAfterBody = _jspx_th_logic_empty_0.doAfterBody();
              if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
                break;
            } while (true);
          }
          if (_jspx_th_logic_empty_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
            _jspx_tagPool_logic_empty_property_name.reuse(_jspx_th_logic_empty_0);
            return;
          }
          _jspx_tagPool_logic_empty_property_name.reuse(_jspx_th_logic_empty_0);
          out.write("\r\n\t\t");
          //  logic:notEmpty
          org.apache.struts.taglib.logic.NotEmptyTag _jspx_th_logic_notEmpty_0 = (org.apache.struts.taglib.logic.NotEmptyTag) _jspx_tagPool_logic_notEmpty_property_name.get(org.apache.struts.taglib.logic.NotEmptyTag.class);
          _jspx_th_logic_notEmpty_0.setPageContext(_jspx_page_context);
          _jspx_th_logic_notEmpty_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0);
          _jspx_th_logic_notEmpty_0.setName("myTerrierEditCommentForm");
          _jspx_th_logic_notEmpty_0.setProperty("rabbitAnnounce");
          int _jspx_eval_logic_notEmpty_0 = _jspx_th_logic_notEmpty_0.doStartTag();
          if (_jspx_eval_logic_notEmpty_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
            do {
              out.write("\r\n\t\t\t<input type=\"reset\" name=\"txtsave\" value=\"");
              out.print(DicoTools.dico(dico_lang, "myTerrier/comment_modify"));
              out.write("\" onclick=\"simpleAjaxSubmit('editComment', function(){profilEndUpdateComment()})\">\r\n\t\t");
              int evalDoAfterBody = _jspx_th_logic_notEmpty_0.doAfterBody();
              if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
                break;
            } while (true);
          }
          if (_jspx_th_logic_notEmpty_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
            _jspx_tagPool_logic_notEmpty_property_name.reuse(_jspx_th_logic_notEmpty_0);
            return;
          }
          _jspx_tagPool_logic_notEmpty_property_name.reuse(_jspx_th_logic_notEmpty_0);
          out.write("\r\n\t
\r\n");
          int evalDoAfterBody = _jspx_th_html_form_0.doAfterBody();
          if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
            break;
        } while (true);
      }
      if (_jspx_th_html_form_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
        _jspx_tagPool_html_form_styleId_action.reuse(_jspx_th_html_form_0);
        return;
      }
      _jspx_tagPool_html_form_styleId_action.reuse(_jspx_th_html_form_0);
      out.write("\r\n
");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }

  private boolean _jspx_meth_html_hidden_0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_form_0, PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  html:hidden
    org.apache.struts.taglib.html.HiddenTag _jspx_th_html_hidden_0 = (org.apache.struts.taglib.html.HiddenTag) _jspx_tagPool_html_hidden_value_property_nobody.get(org.apache.struts.taglib.html.HiddenTag.class);
    _jspx_th_html_hidden_0.setPageContext(_jspx_page_context);
    _jspx_th_html_hidden_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0);
    _jspx_th_html_hidden_0.setProperty("modify");
    _jspx_th_html_hidden_0.setValue("1");
    int _jspx_eval_html_hidden_0 = _jspx_th_html_hidden_0.doStartTag();
    if (_jspx_th_html_hidden_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_html_hidden_value_property_nobody.reuse(_jspx_th_html_hidden_0);
      return true;
    }
    _jspx_tagPool_html_hidden_value_property_nobody.reuse(_jspx_th_html_hidden_0);
    return false;
  }

  private boolean _jspx_meth_html_textarea_0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_form_0, PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  html:textarea
    org.apache.struts.taglib.html.TextareaTag _jspx_th_html_textarea_0 = (org.apache.struts.taglib.html.TextareaTag) _jspx_tagPool_html_textarea_style_rows_property_nobody.get(org.apache.struts.taglib.html.TextareaTag.class);
    _jspx_th_html_textarea_0.setPageContext(_jspx_page_context);
    _jspx_th_html_textarea_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0);
    _jspx_th_html_textarea_0.setRows("6");
    _jspx_th_html_textarea_0.setProperty("rabbitAnnounce");
    _jspx_th_html_textarea_0.setStyle("width:100%");
    int _jspx_eval_html_textarea_0 = _jspx_th_html_textarea_0.doStartTag();
    if (_jspx_th_html_textarea_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_html_textarea_style_rows_property_nobody.reuse(_jspx_th_html_textarea_0);
      return true;
    }
    _jspx_tagPool_html_textarea_style_rows_property_nobody.reuse(_jspx_th_html_textarea_0);
    return false;
  }
}


text:
@extends('app')

@section('title','Thread Edit')

@section('content')

Thread . Edit
	@include('threads.crumbs', ['slug' => $thread->slug ? $thread->slug : $thread->id])

	{!! Form::model($thread, ['route' => ['threads.update', $thread->id], 'method' => 'PATCH']) !!}

		@include('threads.form', ['action' => 'update'])

	{!! Form::close() !!}

{!! delete_form(['threads.destroy', $thread->id]) !!}

Return to list

@stop


text:
Spree.Views.Order.Summary = Backbone.View.extend({
  initialize: function () {
    this.listenTo(this.model, "change", this.render);
    this.render()
  },

  render: function () {
    this.$('dd.order-state').html(this.renderState('order_state', this.model.get("state")))

    this.$("#item_total").text(this.model.get("display_item_total"));
    this.$("#order_total").text(this.model.get("display_total"));

    this.$('.order-shipment_total').toggleClass("hidden", !Number(this.model.get("ship_total")))
    this.$('dd.order-shipment_total').text(this.model.get("display_ship_total"))

    this.$('.order-included_tax_total').toggleClass("hidden", !Number(this.model.get("included_tax_total")))
    this.$('dd.order-included_tax_total').text(this.model.get("display_included_tax_total"))

    this.$('.order-additional_tax_total').toggleClass("hidden", !Number(this.model.get("additional_tax_total")))
    this.$('dd.order-additional_tax_total').text(this.model.get("display_additional_tax_total"))

    this.$('.order-shipment_state').toggleClass("hidden", !this.model.get("completed_at"))
    this.$('dd.order-shipment_state').html(this.renderState('shipment_states', this.model.get("shipment_state")))

    this.$('.order-payment_state').toggleClass("hidden", !this.model.get("completed_at"))
    this.$('dd.order-payment_state').html(this.renderState('payment_states', this.model.get("payment_state")))
  },

  renderState: function(translation_key, value) {
    var state_name = Spree.translations[translation_key][value] || value;
    return $('<span>')
      .addClass('state')
      .addClass(value)
      .text(state_name);
  }
});


text:
\chapter{Built-in modules}
\Reflex has a number of built-in modules that have been created to extend \Reflex using commonly used third party (and open source) libraries. All are implemented as \emph{reflection} based modules.
\section{Statistics module}
The statistics module draws on the Apache Commons Math library. The main function computes the statistics associated with a list of values and is called "statistics". It returns a map with three values, the "mean", the "std" (standard deviation) and "median" (the value of the 50th percentile).

The other three functions in the module work with "Frequency" objects. A frequency object is created using the frequency function - it returns a special Reflex Value that can be passed into the other two methods as the first value. The other two methods calculate the number of values that match the value passed (\Verb+frequency_count+) and the cumulative percentage of values up to a value (\verb+frequency_cum_pct+). This is best illustrated by example:

\begin{lstlisting}[caption={Statistics}]
import reflexStatistics as stat;

points = [ 1,2,3,4,5,6,7,8,9,10,100];

res = $stat.statistics(points);

println("Result is " + res);

multiplePoints = [ 1,2,1,1,1,1,2,1,2,4,5,1,2,3,5];

freq = $stat.frequency(multiplePoints);

println("Count of 1 in frequency is " + $stat.frequency_count(freq, 1));

for i = 1 to 5 do
   println("CumPct at " + i + " is " + $stat.frequency_cum_pct(freq, i));
end

\end{lstlisting}
 The result of running this script would yield the following output:
\begin{Verbatim}
Result is {median=6.0, std=28.637229424141385, mean=14.09090909090909}
Count of 1 in frequency is 7
CumPct at 1 is 0.4666666666666667
CumPct at 2 is 0.7333333333333333
CumPct at 3 is 0.8
CumPct at 4 is 0.8666666666666667
CumPct at 5 is 1.0
\end{Verbatim}
\section{Gamma module}
The Gamma module uses the Apache Commons Math library to compute values relating to the $\Gamma$ function and its derivatives.
\subsection{Gamma function}
The gamma function (\Verb+gamma+) takes zero or one parameter. In its no parameter form, it returns the value of the Euler-Mascheroni constant (also known as Euler's constant), and referred to as $\gamma$. With one parameter it reurns the gamma function on the parameter.
\subsection{DiGamma function}
The digamma function (\Verb+digamma+) takes one parameter and returns the digamma function on the parameter.
\subsection{TriGamma function}
The trigamma function (\Verb+trigamma+) takes one parameter and returns the trigamma function on the parameter.
\section{Erf module}
The Erf module uses the Apache Commons Math library to compute Error Function values. It has two functins - \Verb+erf+ reyurns the error function of its parameter, and \verb+erfc+ returns the error function coefficient of its parameter.
\section{Math module}
The math module provides standard support through the Java Math package. The functions exposed are shown in the table below:
\begin{table}[!h]
  \small
\centering
\begin{tabular} { | l | l | p{9cm}  | }
\hline
Function  & Parameters & Description   \\
\hline
pi & none & Returns the constant $\pi$   \\
e & none & Returns the constant $\epsilon$   \\
abs & value & Returns the absolute value of a number  \\
acos & value & Returns the arc-cosine of the number \\
asin & value & Returns the arc-sine of the number \\
atan & value & Returns the arc-tangent of the number \\
atan2 & x,y & Returns the arc-tangent "2 parameter" result of the (x,y) values passed \\
cbrt & value & Returns the cube root of the number \\
ceil & value & Returns the value rounded up to the nearest integer \\
cos & value & Returns the cosine of the value in radians \\
cosh & value & Returns the hyperbolic cosine of the value \\
exp & value & Returns $\epsilon$ raised to the power of the value \\
expm1 & value & Returns $\epsilon^x - 1 $ \\
floor & value & Returns the value rounded down to the nearest integer \\
hypot & x,y & Computes $ \sqrt { x^2 + y^2 } $ \\
log & value & Computes the natural logarithm of the value \\
log10 & value & Computes the base-10 logarithm of the value \\
log1p & x & Computes \Verb^log(1+x)^ \\
max & x,y & Returns the maximum of x or y \\
min & x,y & Returns the minimum of x or y \\
pow & x,y & Returns $x^y$ \\
sin & value & Returns the sine of the angle in radians \\
sinh & value & Returns the hyperbolic sine \\
sqrt & value & Computes $\sqrt x $ \\
tan & value & Computes the tangent of the angle in radians \\
tanh & value & Computes the hyperbolic tangent \\
degrees & value & Converts radians to degrees \\
radians & value & Converts radians to degrees \\
\hline
\end{tabular}
\caption{Math module in Reflex}
\end{table}


text:
import {
  ApolloLink,
  Observable,
  Operation,
  NextLink,
  GraphQLRequest,
} from 'apollo-link';

export type ContextSetter = (
  operation: GraphQLRequest,
  prevContext: any,
) => Promise<any> | any;

export function setContext(setter: ContextSetter): ApolloLink {
  return new ApolloLink((operation: Operation, forward: NextLink) => {
    const { ...request } = operation;

    return new Observable(observer => {
      let handle;
      Promise.resolve(request)
        .then(req => setter(req, operation.getContext()))
        .then(operation.setContext)
        .then(() => {
          handle = forward(operation).subscribe({
            next: observer.next.bind(observer),
            error: observer.error.bind(observer),
            complete: observer.complete.bind(observer),
          });
        })
        .catch(observer.error.bind(observer));

      return () => {
        if (handle) handle.unsubscribe();
      };
    });
  });
}


text:
.vivid-carousel { margin: 1.2em 0 }

    .carousel-header-wrap { position: relative; min-height: 40px; margin-bottom: 10px; }

        .carousel-header-wrap h2 { margin-top: 0; }
        .carousel-nav-button { cursor: pointer; border-radius: 50%; background: #eee; width: 40px; height: 40px; top: 0; position: absolute; text-align: center; line-height: 0; padding-top: 20px; font-size: 24px; -webkit-transition: .2 ease all; transition: .2s ease all; }
        .carousel-nav-button:hover { background: #ddd; }
        .carousel-nav-button.next { right: 0; }
        .carousel-nav-button.prev { right: 50px; }
        .carousel-nav-button.next:before{
            content: ">";
        }
        .carousel-nav-button.prev:before{
            content: "<";
        }

    ul.carousel-item-container { padding: 0; overflow: hidden; }

        .carousel-overflow-wrap { width: 10000px; position: relative; transition: .2s ease all; }

            li.carousel-item { opacity: 0; list-style: none !important; float: left; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-transition: .5s ease all; transition: .5s ease all; }
            li.carousel-item.vis { opacity: 1; }

                li.carousel-item .item-inner { margin: 5px; }

                li.carousel-item img {  }
                li.carousel-item h3 {  }
                li.carousel-item .carousel-button { display: inline-block; background: #eee; border-radius: 1px solid #ccc; margin-top: 10px; text-decoration: none; color: #444 !important; padding: 6px 15px; border-radius: 3px; }
                li.carousel-item .carousel-button:hover { background: #ddd; }


text:
package jdwp

// GetArrayLength returns the length of the specified array.
func (c *Connection) GetArrayLength(id ArrayID) (int, error) {
	var res int
	err := c.get(cmdSetArrayReference, 1, id, &res)
	return res, err
}

// GetArrayValues the values of the specified array.
func (c *Connection) GetArrayValues(id ArrayID, first, length int) ([]Value, error) {
	req := struct {
		ID     ArrayID
		First  int
		Length int
	}{id, first, length}
	var res []Value
	err := c.get(cmdSetArrayReference, 2, req, &res)
	return res, err
}

// SetArrayValues the values of the specified array.
func (c *Connection) SetArrayValues(id ArrayID, first int, values interface{}) error {
	req := struct {
		ID     ArrayID
		First  int
		Values interface{}
	}{id, first, values}
	return c.get(cmdSetArrayReference, 3, req, nil)
}


text:
Crud.afterFind
^^^^^^^^^^^^^^

After the query has been executed, and a record has been found this event is emitted.

The :ref:`Crud Subject <crud-subject>` contains two keys:

- ``id`` The ID that was originally passed to the action and is usually the primary key of your model.
- ``entity`` The record that was found in the database.

.. note::

  If an entity is not found, the ``RecordNotFound`` event is emitted instead.

Logging the Found Item
""""""""""""""""""""""

.. code-block:: phpinline

  public function delete($id) {
    $this->Crud->on('afterFind', function(\Cake\Event\Event $event) {
      $this->log("Found item: $event->subject->entity->id in the database");
    });

    return $this->Crud->execute();
  }


text:
"""
_PyType_Lookup() returns a borrowed reference.
This attacks PyObject_GenericSetAttr().

NB. on my machine this crashes in 2.5 debug but not release.
"""

class A(object):
    pass

class B(object):
    def __del__(self):
        print "hi"
        del C.d

class D(object):
    def __set__(self, obj, value):
        self.hello = 42

class C(object):
    d = D()

    def g():
        pass

c = C()
a = A()
a.cycle = a
a.other = B()

lst = [None] * 1000000
i = 0
del a
while 1:
    c.d = 42         # segfaults in PyMethod_New(im_func=D.__set__, im_self=d)
    lst[i] = c.g     # consume the free list of instancemethod objects
    i += 1


text:
package github

import (
	"context"
	"net/http"

	"github.com/rockbears/log"

	"github.com/ovh/cds/engine/cache"
	"github.com/ovh/cds/sdk"
)

// User Get a single user
// https://developer.github.com/v3/users/#get-a-single-user
func (g *githubClient) User(ctx context.Context, username string) (User, error) {
	url := "/users/" + username
	status, body, _, err := g.get(ctx, url)
	if err != nil {
		log.Warn(ctx, "githubClient.User> Error %s", err)
		return User{}, err
	}
	if status >= 400 {
		return User{}, sdk.NewError(sdk.ErrRepoNotFound, errorAPI(body))
	}
	user := User{}

	//Github may return 304 status because we are using conditional request with ETag based headers
	if status == http.StatusNotModified {
		//If repo isn't updated, lets get them from cache
		k := cache.Key("vcs", "github", "users", sdk.Hash512(g.OAuthToken+g.username), url)
		if _, err := g.Cache.Get(k, &user); err != nil {
			log.Error(ctx, "cannot get from cache %s: %v", k, err)
		}
	} else {
		if err := sdk.JSONUnmarshal(body, &user); err != nil {
			return User{}, err
		}
		//Put the body on cache for one hour and one minute
		k := cache.Key("vcs", "github", "users", sdk.Hash512(g.OAuthToken+g.username), url)
		if err := g.Cache.SetWithTTL(k, user, 61*60); err != nil {
			log.Error(ctx, "cannot SetWithTTL: %s: %v", k, err)
		}
	}

	return user, nil
}


text: from testcase import TestCase


text:
//
//  FringeObject.h
//
//  Created by Sean Meiners on 2012/10/01.
//  Copyright (c) 2012 Sean Meiners. All rights reserved.
//
//

#import <Foundation/Foundation.h>

extern NSString *fringedata_makeFileNameSafe(NSString *key);
extern NSString *fringedata_makeFileNameUnSafe(NSString *key);

/**
 Like NSManagedObject, this class will dynamically create the property
 getters and setters for any @property you declare as @dynamic.
 Like NSManagedObject, most objects will get a standard getter and setter
 only, but properties of types NSSet and NSOrderedSet will also cause
 the following methods to be generated:

 For an NSSet property named 'foo', implements the following:

    - (NSSet*)foos;
    - (NSUInteger)foosCount;
    - (void)setFoos:(NSSet*)foos;

    - (void)addFoosObject:(Foo *)value;
    - (void)addFoos:(NSSet *)values;

    - (void)removeFoosObject:(Foo *)value;
    - (void)removeFoos:(NSSet *)values;

 For an NSOrderedSet property named 'foo', implements the following:

    - (NSOrderedSet*)foos;
    - (NSUInteger)foosCount;
    - (Foo *)foosAtIndex:(NSUInteger)index;
    - (NSOrderedSet*)foosAtIndexes:(NSIndexSet*)indexes;
    - (void)setFoos:(NSOrderedSet*)foos;

    - (void)addFoosObject:(Foo *)value;
    - (void)addFoos:(NSOrderedSet *)values;

    - (void)removeFoosObject:(Foo *)value;
    - (void)removeFoos:(NSOrderedSet *)values;

    - (void)insertObject:(Foo *)value inFoosAtIndex:(NSUInteger)idx;
    - (void)insertFoos:(NSArray *)value atIndexes:(NSIndexSet *)indexes;

    - (void)replaceObjectInFoosAtIndex:(NSUInteger)idx withObject:(Foo *)value;
    - (void)replaceFoosAtIndexes:(NSIndexSet *)indexes withFoos:(NSArray *)values;

    - (void)removeObjectFromFoosAtIndex:(NSUInteger)idx;
    - (void)removeFoosAtIndexes:(NSIndexSet *)indexes;

  */
@class FringeObjectStore;

NS_REQUIRES_PROPERTY_DEFINITIONS
@interface FringeObject : NSObject

/** The store this object belongs to */
@property (nonatomic, readonly) FringeObjectStore *fringeObjectStore;

/** This object's UUID, this will never change */
@property (nonatomic, readonly) NSString *uuid;

/**
 The default implementation returns `nil`. This must be implmented for any root object.
 @return The directory (as a file:// URL) where objects of this type should be stored.
 */
+ (NSURL*)defaultCommitPath;
/**
 The default implementation returns `nil`. This should be implmented for any root object.
 @return the (NSString*) names of the properties that should be indexed.
 */
+ (NSSet*)indexedPropertyNames;
/**
 The default implementation returns `nil`. This should be implmented for any root object.
 @param name The name of the property that will be indexed.
 @param value The value of the property.
 @param object The FringeObject the property belongs to.
 @return The path (as a file:// URL) to where the index for the specified property should be stored.
*/
+ (NSURL*)indexURLForProperty:(NSString*)name withValue:(id)value forObject:(FringeObject*)object;

/**
 This is the method you should override this instead of init (aka the common initializer)
*/
- (void)setDefaultValues;

/**
 Only use this method when creating a root object that implements defaultCommitPath.
 A FringeObjectStore will be automatically created for you.
 */
- (id)init;

/**
 Use this method when creating a non-root object, or when creating a root object and you already have a FringeObjectStore to add it to.
 @param store The FringeObjectStore to which this object belongs
 */
- (id)initWithStore:(FringeObjectStore*)store;

/**
 Primarily for internal use only. Can be overridden to modify the dictionary on creation.
 @param dictionary The NSDictionary that contains the values parsed from the FringeObjectStore
 @param store The FringeObjectStore to which this object belongs
 */
- (id)initWithDictionary:(NSDictionary*)dictionary inStore:(FringeObjectStore*)store;

/**
 Primarily used by FringeObjectStore for commiting the object to disk.
 */
- (id)proxyForJson;

/**
 Useful when you need to override the default getter or when you want to bypass the built-in type conversion.
 @param name The name of the property to retrieve
 @return The raw value of property `name`
 */
- (id)getProperty:(NSString*)name;

/**
 Useful when you need to override the default setter or when you want to bypass the built-in type conversion.
 @param name The name of the property to set
 @param value The raw value of property `name`
 */
- (void)setProperty:(NSString*)name value:(id)value;

@end