text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.camunda.bpm.engine.impl.test;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.history.UserOperationLogEntry;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.SchemaOperationsProcessEngineBuild;
import org.camunda.bpm.engine.impl.application.ProcessApplicationManager;
import org.camunda.bpm.engine.impl.bpmn.deployer.BpmnDeployer;
import org.camunda.bpm.engine.impl.cfg.IdGenerator;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.cmmn.deployer.CmmnDeployer;
import org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity;
import org.camunda.bpm.engine.impl.db.DbIdGenerator;
import org.camunda.bpm.engine.impl.db.PersistenceSession;
import org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager;
import org.camunda.bpm.engine.impl.dmn.deployer.DecisionDefinitionDeployer;
import org.camunda.bpm.engine.impl.history.HistoryLevel;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.camunda.bpm.engine.impl.persistence.deploy.DeploymentCache;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.PropertyEntity;
import org.camunda.bpm.engine.impl.util.ClassNameUtil;
import org.camunda.bpm.engine.impl.util.ReflectUtil;
import org.camunda.bpm.engine.repository.DeploymentBuilder;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.cmmn.CmmnModelInstance;
import org.camunda.commons.utils.cache.Cache;
import org.junit.Assert;
import org.junit.runner.Description;
import org.slf4j.Logger;

import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author Tom Baeyens
 */
public abstract class TestHelper {

  private static Logger LOG = ProcessEngineLogger.TEST_LOGGER.getLogger();

  public static final String EMPTY_LINE = "                                                                                ";

  public static final List<String> TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK = Arrays.asList(
    "ACT_GE_PROPERTY"
  );

  static Map<String, ProcessEngine> processEngines = new HashMap<String, ProcessEngine>();

  public final static List<String> RESOURCE_SUFFIXES = new ArrayList<String>();

  static {
    RESOURCE_SUFFIXES.addAll(Arrays.asList(BpmnDeployer.BPMN_RESOURCE_SUFFIXES));
    RESOURCE_SUFFIXES.addAll(Arrays.asList(CmmnDeployer.CMMN_RESOURCE_SUFFIXES));
    RESOURCE_SUFFIXES.addAll(Arrays.asList(DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES));
  }

  /**
   * use {@link ProcessEngineAssert} instead.
   */
  @Deprecated
  public static void assertProcessEnded(ProcessEngine processEngine, String processInstanceId) {
    ProcessEngineAssert.assertProcessEnded(processEngine, processInstanceId);
  }

  public static String annotationDeploymentSetUp(ProcessEngine processEngine, Class<?> testClass, String methodName, Deployment deploymentAnnotation) {
    String deploymentId = null;
    Method method = null;
    boolean onMethod = true;

    try {
      method = getMethod(testClass, methodName);
    } catch (Exception e) {
      if (deploymentAnnotation == null) {
        // we have neither the annotation, nor can look it up from the method
        return null;
      }
    }

    if (deploymentAnnotation == null) {
      deploymentAnnotation = method.getAnnotation(Deployment.class);
    }
    // if not found on method, try on class level
    if (deploymentAnnotation == null) {
      onMethod = false;
      Class<?> lookForAnnotationClass = testClass;
      while (lookForAnnotationClass != Object.class) {
        deploymentAnnotation = lookForAnnotationClass.getAnnotation(Deployment.class);
        if (deploymentAnnotation != null) {
          testClass = lookForAnnotationClass;
          break;
        }
        lookForAnnotationClass = lookForAnnotationClass.getSuperclass();
      }
    }

    if (deploymentAnnotation != null) {
      LOG.debug("annotation @Deployment creates deployment for {}.{}", ClassNameUtil.getClassNameWithoutPackage(testClass), methodName);
      String[] resources = deploymentAnnotation.resources();
      if (resources.length == 0 && method != null) {
        String name = onMethod ? method.getName() : null;
        String resource = getBpmnProcessDefinitionResource(testClass, name);
        resources = new String[]{resource};
      }

      DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService()
        .createDeployment()
        .name(ClassNameUtil.getClassNameWithoutPackage(testClass)+"."+methodName);

      for (String resource: resources) {
        deploymentBuilder.addClasspathResource(resource);
      }

      deploymentId = deploymentBuilder.deploy().getId();
    }

    return deploymentId;
  }

  public static String annotationDeploymentSetUp(ProcessEngine processEngine, Class<?> testClass, String methodName) {
    return annotationDeploymentSetUp(processEngine, testClass, methodName, null);
  }

  public static void annotationDeploymentTearDown(ProcessEngine processEngine, String deploymentId, Class<?> testClass, String methodName) {
    LOG.debug("annotation @Deployment deletes deployment for {}.{}", ClassNameUtil.getClassNameWithoutPackage(testClass), methodName);
    deleteDeployment(processEngine, deploymentId);
  }

  public static void deleteDeployment(ProcessEngine processEngine, String deploymentId) {
    if(deploymentId != null) {
      processEngine.getRepositoryService().deleteDeployment(deploymentId, true);
    }
  }

  /**
   * get a resource location by convention based on a class (type) and a
   * relative resource name. The return value will be the full classpath
   * location of the type, plus a suffix built from the name parameter:
   * BpmnDeployer.BPMN_RESOURCE_SUFFIXES.
   * The first resource matching a suffix will be returned.
   */
  public static String getBpmnProcessDefinitionResource(Class< ? > type, String name) {
    for (String suffix : RESOURCE_SUFFIXES) {
      String resource = createResourceName(type, name, suffix);
      InputStream inputStream = ReflectUtil.getResourceAsStream(resource);
      if (inputStream == null) {
        continue;
      } else {
        return resource;
      }
    }
    return createResourceName(type, name, BpmnDeployer.BPMN_RESOURCE_SUFFIXES[0]);
  }

  private static String createResourceName(Class< ? > type, String name, String suffix) {
    StringBuffer r = new StringBuffer(type.getName().replace('.', '/'));
    if (name != null) {
      r.append("." + name);
    }
    return r.append("." + suffix).toString();
  }

  public static boolean annotationRequiredHistoryLevelCheck(ProcessEngine processEngine, Description description) {
    RequiredHistoryLevel annotation = description.getAnnotation(RequiredHistoryLevel.class);

    if (annotation != null) {
      return historyLevelCheck(processEngine, annotation);

    } else {
      return annotationRequiredHistoryLevelCheck(processEngine, description.getTestClass(), description.getMethodName());
    }
  }

  private static boolean historyLevelCheck(ProcessEngine processEngine, RequiredHistoryLevel annotation) {
    ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();

    HistoryLevel requiredHistoryLevel = getHistoryLevelForName(processEngineConfiguration.getHistoryLevels(), annotation.value());
    HistoryLevel currentHistoryLevel = processEngineConfiguration.getHistoryLevel();

    return currentHistoryLevel.getId() >= requiredHistoryLevel.getId();
  }

  private static HistoryLevel getHistoryLevelForName(List<HistoryLevel> historyLevels, String name) {
    for (HistoryLevel historyLevel : historyLevels) {

      if (historyLevel.getName().equalsIgnoreCase(name)) {
        return historyLevel;
      }
    }
    throw new IllegalArgumentException("Unknown history level: " + name);
  }

  public static boolean annotationRequiredHistoryLevelCheck(ProcessEngine processEngine, Class<?> testClass, String methodName) {
    RequiredHistoryLevel annotation = getAnnotation(processEngine, testClass, methodName, RequiredHistoryLevel.class);

    if (annotation != null) {
      return historyLevelCheck(processEngine, annotation);
    } else {
      return true;
    }
  }

  private static <T extends Annotation> T getAnnotation(ProcessEngine processEngine, Class<?> testClass, String methodName, Class<T> annotationClass) {
    Method method = null;
    T annotation = null;

    try {
      method = getMethod(testClass, methodName);
      annotation = method.getAnnotation(annotationClass);
    } catch (Exception e) {
      // - ignore if we cannot access the method
      // - just try again with the class
      // => can for example be the case for parameterized tests where methodName does not correspond to the actual method name
      //    (note that method-level annotations still work in this
      //     scenario due to Description#getAnnotation in annotationRequiredHistoryLevelCheck)
    }

    // if not found on method, try on class level
    if (annotation == null) {
      annotation = testClass.getAnnotation(annotationClass);
    }
    return annotation;
  }

  protected static Method getMethod(Class<?> clazz, String methodName) throws SecurityException, NoSuchMethodException {
    return clazz.getMethod(methodName, (Class<?>[]) null);
  }

  /**
   * Ensures that the deployment cache and database is clean after a test. If not the cache
   * and database will be cleared.
   *
   * @param processEngine the {@link ProcessEngine} to test
   * @throws AssertionError if the deployment cache or database was not clean
   */
  public static void assertAndEnsureCleanDbAndCache(ProcessEngine processEngine) {
    assertAndEnsureCleanDbAndCache(processEngine, true);
  }

  /**
   * Ensures that the deployment cache and database is clean after a test. If not the cache
   * and database will be cleared.
   *
   * @param processEngine the {@link ProcessEngine} to test
   * @param fail if true the method will throw an {@link AssertionError} if the deployment cache or database is not clean
   * @throws AssertionError if the deployment cache or database was not clean
   */
  public static void assertAndEnsureCleanDbAndCache(ProcessEngine processEngine, boolean fail) {
    String cacheMessage = assertAndEnsureCleanDeploymentCache(processEngine, false);
    String dbMessage = assertAndEnsureCleanDb(processEngine, false);
    String paRegistrationMessage = assertAndEnsureNoProcessApplicationsRegistered(processEngine);

    StringBuilder message = new StringBuilder();
    if (cacheMessage != null) {
      message.append(cacheMessage);
    }
    if (dbMessage != null) {
      message.append(dbMessage);
    }
    if (paRegistrationMessage != null) {
      message.append(paRegistrationMessage);
    }

    if (fail && message.length() > 0) {
      Assert.fail(message.toString());
    }
  }

  /**
   * Ensures that the deployment cache is empty after a test. If not the cache
   * will be cleared.
   *
   * @param processEngine the {@link ProcessEngine} to test
   * @throws AssertionError if the deployment cache was not clean
   */
  public static void assertAndEnsureCleanDeploymentCache(ProcessEngine processEngine) {
    assertAndEnsureCleanDb(processEngine, true);
  }

  /**
   * Ensures that the deployment cache is empty after a test. If not the cache
   * will be cleared.
   *
   * @param processEngine the {@link ProcessEngine} to test
   * @param fail if true the method will throw an {@link AssertionError} if the deployment cache is not clean
   * @return the deployment cache summary if fail is set to false or null if deployment cache was clean
   * @throws AssertionError if the deployment cache was not clean and fail is set to true
   */
  public static String assertAndEnsureCleanDeploymentCache(ProcessEngine processEngine, boolean fail) {
    StringBuilder outputMessage = new StringBuilder();
    ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration();
    DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache();

    Cache<String, ProcessDefinitionEntity> processDefinitionCache = deploymentCache.getProcessDefinitionCache();

    if (!processDefinitionCache.isEmpty()) {
      outputMessage.append("\tProcess Definition Cache: ").append(processDefinitionCache.keySet()).append("\n");
      processDefinitionCache.clear();
    }

    Cache<String, BpmnModelInstance> bpmnModelInstanceCache = deploymentCache.getBpmnModelInstanceCache();

    if (!bpmnModelInstanceCache.isEmpty()) {
      outputMessage.append("\tBPMN Model Instance Cache: ").append(bpmnModelInstanceCache.keySet()).append("\n");
      bpmnModelInstanceCache.clear();
    }

    Cache<String, CaseDefinitionEntity> caseDefinitionCache = deploymentCache.getCaseDefinitionCache();

    if (!caseDefinitionCache.isEmpty()) {
      outputMessage.append("\tCase Definition Cache: ").append(caseDefinitionCache.keySet()).append("\n");
      caseDefinitionCache.clear();
    }

    Cache<String, CmmnModelInstance> cmmnModelInstanceCache = deploymentCache.getCmmnModelInstanceCache();

    if (!cmmnModelInstanceCache.isEmpty()) {
      outputMessage.append("\tCMMN Model Instance Cache: ").append(cmmnModelInstanceCache.keySet()).append("\n");
      cmmnModelInstanceCache.clear();
    }

    if (outputMessage.length() > 0) {
      outputMessage.insert(0, "Deployment cache not clean:\n");
      LOG.error(outputMessage.toString());

      if (fail) {
        Assert.fail(outputMessage.toString());
      }

      return outputMessage.toString();
    }
    else {
      LOG.debug("Deployment cache was clean");
      return null;
    }
  }

  /**
   * Ensures that the database is clean after the test. This means the test has to remove
   * all resources it entered to the database.
   * If the DB is not clean, it is cleaned by performing a create a drop.
   *
   * @param processEngine the {@link ProcessEngine} to check
   * @throws AssertionError if the database was not clean
   */
  public static void assertAndEnsureCleanDb(ProcessEngine processEngine) {
    assertAndEnsureCleanDb(processEngine, true);
  }

  /**
   * Ensures that the database is clean after the test. This means the test has to remove
   * all resources it entered to the database.
   * If the DB is not clean, it is cleaned by performing a create a drop.
   *
   * @param processEngine the {@link ProcessEngine} to check
   * @param fail if true the method will throw an {@link AssertionError} if the database is not clean
   * @return the database summary if fail is set to false or null if database was clean
   * @throws AssertionError if the database was not clean and fail is set to true
   */
  public static String assertAndEnsureCleanDb(ProcessEngine processEngine, boolean fail) {
    ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration();
    String databaseTablePrefix = processEngineConfiguration.getDatabaseTablePrefix().trim();

    // clear user operation log in case some operations are
    // executed with an authenticated user
    clearUserOperationLog(processEngineConfiguration);

    LOG.debug("verifying that db is clean after test");
    Map<String, Long> tableCounts = processEngine.getManagementService().getTableCount();

    StringBuilder outputMessage = new StringBuilder();
    for (String tableName : tableCounts.keySet()) {
      String tableNameWithoutPrefix = tableName.replace(databaseTablePrefix, "");
      if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
        Long count = tableCounts.get(tableName);
        if (count!=0L) {
          outputMessage.append("\t").append(tableName).append(": ").append(count).append(" record(s)\n");
        }
      }
    }

    if (outputMessage.length() > 0) {
      outputMessage.insert(0, "DB NOT CLEAN: \n");
      LOG.error(outputMessage.toString());

      /** skip drop and recreate if a table prefix is used */
      if (databaseTablePrefix.isEmpty()) {
        LOG.error("Dropping and recreating database");

        processEngineConfiguration
          .getCommandExecutorSchemaOperations()
          .execute(new Command<Object>() {
            public Object execute(CommandContext commandContext) {
              PersistenceSession persistenceSession = commandContext.getSession(PersistenceSession.class);
              persistenceSession.dbSchemaDrop();
              persistenceSession.dbSchemaCreate();
              SchemaOperationsProcessEngineBuild.dbCreateHistoryLevel(commandContext.getDbEntityManager());
              return null;
            }
          });
      }
      else {
        LOG.info("Skipping recreating of database as a table prefix is used");
      }

      if (fail) {
        Assert.fail(outputMessage.toString());
      }
      else {
        return outputMessage.toString();
      }

    } else {
      LOG.debug("Database was clean");
    }
    return null;
  }

  public static String assertAndEnsureNoProcessApplicationsRegistered(ProcessEngine processEngine) {
    ProcessEngineConfigurationImpl engineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
    ProcessApplicationManager processApplicationManager = engineConfiguration.getProcessApplicationManager();

    if (processApplicationManager.hasRegistrations()) {
      processApplicationManager.clearRegistrations();
      return "There are still process applications registered";
    }
    else {
      return null;
    }

  }

  public static void waitForJobExecutorToProcessAllJobs(ProcessEngineConfigurationImpl processEngineConfiguration, long maxMillisToWait, long intervalMillis) {
    JobExecutor jobExecutor = processEngineConfiguration.getJobExecutor();
    jobExecutor.start();

    try {
      Timer timer = new Timer();
      InteruptTask task = new InteruptTask(Thread.currentThread());
      timer.schedule(task, maxMillisToWait);
      boolean areJobsAvailable = true;
      try {
        while (areJobsAvailable && !task.isTimeLimitExceeded()) {
          Thread.sleep(intervalMillis);
          areJobsAvailable = areJobsAvailable(processEngineConfiguration);
        }
      } catch (InterruptedException e) {
      } finally {
        timer.cancel();
      }
      if (areJobsAvailable) {
        throw new ProcessEngineException("time limit of " + maxMillisToWait + " was exceeded");
      }

    } finally {
      jobExecutor.shutdown();
    }
  }

  public static boolean areJobsAvailable(ProcessEngineConfigurationImpl processEngineConfiguration) {
    return !processEngineConfiguration
      .getManagementService()
      .createJobQuery()
      .executable()
      .list()
      .isEmpty();
  }

  public static void resetIdGenerator(ProcessEngineConfigurationImpl processEngineConfiguration) {
    IdGenerator idGenerator = processEngineConfiguration.getIdGenerator();

    if (idGenerator instanceof DbIdGenerator) {
      ((DbIdGenerator) idGenerator).reset();
    }
  }

  private static class InteruptTask extends TimerTask {
    protected boolean timeLimitExceeded = false;
    protected Thread thread;
    public InteruptTask(Thread thread) {
      this.thread = thread;
    }
    public boolean isTimeLimitExceeded() {
      return timeLimitExceeded;
    }
    @Override
    public void run() {
      timeLimitExceeded = true;
      thread.interrupt();
    }
  }

  public static ProcessEngine getProcessEngine(String configurationResource) {
    ProcessEngine processEngine = processEngines.get(configurationResource);
    if (processEngine==null) {
      LOG.debug("==== BUILDING PROCESS ENGINE ========================================================================");
      processEngine = ProcessEngineConfiguration
        .createProcessEngineConfigurationFromResource(configurationResource)
        .buildProcessEngine();
      LOG.debug("==== PROCESS ENGINE CREATED =========================================================================");
      processEngines.put(configurationResource, processEngine);
    }
    return processEngine;
  }

  public static void closeProcessEngines() {
    for (ProcessEngine processEngine: processEngines.values()) {
      processEngine.close();
    }
    processEngines.clear();
  }

  public static void createSchema(ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration.getCommandExecutorTxRequired()
        .execute(new Command<Object>() {
          public Object execute(CommandContext commandContext) {

            commandContext.getSession(PersistenceSession.class).dbSchemaCreate();
            return null;
          }
        });
  }

  public static void dropSchema(ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration.getCommandExecutorTxRequired()
        .execute(new Command<Object>() {
         public Object execute(CommandContext commandContext) {
           commandContext.getDbSqlSession().dbSchemaDrop();
           return null;
         }
        });
  }

  public static void createOrUpdateHistoryLevel(final ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration.getCommandExecutorTxRequired()
      .execute(new Command<Object>() {
       public Object execute(CommandContext commandContext) {
         DbEntityManager dbEntityManager = commandContext.getDbEntityManager();
         PropertyEntity historyLevelProperty = dbEntityManager.selectById(PropertyEntity.class, "historyLevel");
         if (historyLevelProperty != null) {
           if (processEngineConfiguration.getHistoryLevel().getId() != new Integer(historyLevelProperty.getValue())) {
             historyLevelProperty.setValue(Integer.toString(processEngineConfiguration.getHistoryLevel().getId()));
             dbEntityManager.merge(historyLevelProperty);
           }
         } else {
           SchemaOperationsProcessEngineBuild.dbCreateHistoryLevel(dbEntityManager);
         }
         return null;
       }
      });
  }

  public static void deleteHistoryLevel(ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration.getCommandExecutorTxRequired()
      .execute(new Command<Object>() {
       public Object execute(CommandContext commandContext) {
         DbEntityManager dbEntityManager = commandContext.getDbEntityManager();
         PropertyEntity historyLevelProperty = dbEntityManager.selectById(PropertyEntity.class, "historyLevel");
         if (historyLevelProperty != null) {
           dbEntityManager.delete(historyLevelProperty);
         }
         return null;
       }
      });
  }

  public static void clearUserOperationLog(ProcessEngineConfigurationImpl processEngineConfiguration) {
    if (processEngineConfiguration.getHistoryLevel().equals(HistoryLevel.HISTORY_LEVEL_FULL)) {
      HistoryService historyService = processEngineConfiguration.getHistoryService();
      List<UserOperationLogEntry> logs = historyService.createUserOperationLogQuery().list();
      for (UserOperationLogEntry log : logs) {
        historyService.deleteUserOperationLogEntry(log.getId());
      }
    }
  }

}


text:
"""Exposes Twitch chat to the application.
"""
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.words.protocols import irc
from threading import Thread
from pubsub import pub

def connect(username, password, autojoin):
    factory = IRCClientFactory(username, password, autojoin)

    host = 'irc.twitch.tv'
    port = 6667

    reactor.connectTCP(host, port, factory)

class IRCClient(irc.IRCClient):

    def connectionMade(self):
        irc.IRCClient.connectionMade(self)

    def connectionLost(self, reason):
        irc.IRCClient.connectionLost(self, reason)

    def signedOn(self):
        self.join(self.factory.autojoin)

    def privmsg(self, user, channel, msg):
        if user == 'jtv':
            return

        pub.sendMessage("service.chat.message", user=user, message=msg)

    def _get_nickname(self):
        return self.factory.username

    def _get_realname(self):
        return self.factory.username

    def _get_username(self):
        return self.factory.username

    def _get_password(self):
        return self.factory.password

    nickname = property(_get_nickname)
    realname = property(_get_realname)
    username = property(_get_username)
    password = property(_get_password)

class IRCClientFactory(protocol.ClientFactory):
    protocol = IRCClient

    def __init__(self, username, password, autojoin):
        self.username = username.lower()
        self.password = password
        self.autojoin = autojoin

    def clientConnectionLost(self, connector, reason):
        print 'irc: connection lost: ', reason
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print 'irc: connection failed: ', reason
        # reactor.stop()
        connector.disconnect()
        pub.sendMessage('command.quit')

redpajama_set_name: RedPajamaGithub


text:
from tests import base
import json
import dbm
import urllib
import os

def setUpModule():
    base.enabledPlugins.append('cumulus')
    base.enabledPlugins.append('pvwproxy')
    base.startServer()

def tearDownModule():
    base.stopServer()

class ProxyTestCase(base.TestCase):

    def setUp(self):
        super(ProxyTestCase, self).setUp()

        self._proxy_file_path = '/tmp/proxy'
        full_path = '%s.db' % self._proxy_file_path
        if os.path.exists(full_path):
            os.remove(full_path)

        users = ({
            'email': 'cumulus@email.com',
            'login': 'cumulus',
            'firstName': 'First',
            'lastName': 'Last',
            'password': 'goodpassword'
        }, {
            'email': 'regularuser@email.com',
            'login': 'regularuser',
            'firstName': 'First',
            'lastName': 'Last',
            'password': 'goodpassword'
        }, {
            'email': 'another@email.com',
            'login': 'another',
            'firstName': 'First',
            'lastName': 'Last',
            'password': 'goodpassword'
        })
        self._cumulus, self._user, self._another_user = \
            [self.model('user').createUser(**user) for user in users]

        self._group = self.model('group').createGroup('cumulus', self._cumulus)

        # Create test job
        body = {
            'onComplete': {
                'cluster': 'terminate'
            },
            'input': [
                {
                    'itemId': '546a1844ff34c70456111185',
                    'path': ''
                }
            ],
            'commands': [
                ''
            ],
            'name': 'test',
            'output': {
                'itemId': '546a1844ff34c70456111185'
            }
        }

        json_body = json.dumps(body)
        r = self.request('/jobs', method='POST',
                         type='application/json', body=json_body, user=self._user)

        self.assertStatus(r, 201)
        self._job_id = r.json['_id']

        # Create test config
        body = {
            'config': {
                'cluster': [{
                    'default_cluster': {}
                }],
            'name': 'test'
            }
        }
        body = json.dumps(body)

        r = self.request('/starcluster-configs', method='POST',
                         type='application/json', body=body, user=self._cumulus)
        self.assertStatus(r, 201)
        config_id = r.json['_id']

        # Create test cluster
        body = {
            'config': [
                {
                    '_id': config_id
                }
            ],
            'name': 'test',
            'template': 'default_cluster'
        }

        json_body = json.dumps(body)

        r = self.request('/clusters', method='POST',
                         type='application/json', body=json_body, user=self._user)
        self.assertStatus(r, 201)
        self._cluster_id = r.json['_id']

    def test_add_entry(self):
        host = 'some.com'
        port = 8080
        body = {
            'key': self._cluster_id + '%2F' + self._job_id,
            'host': host,
            'port': port
        }

        json_body = json.dumps(body)

        r = self.request('/proxy', method='POST',
                         type='application/json', body=json_body, user=self._user)

        self.assertStatusOk(r)

        db = dbm.open(self._proxy_file_path)
        keys = db.keys()
        self.assertEqual(len(keys), 1)
        expected_key = urllib.quote_plus('%s/%s' % (self._cluster_id, self._job_id))
        self.assertEquals(keys[0], expected_key)
        expected_value = '%s:%s' % (host, port)
        self.assertEquals(db[keys[0]], expected_value)


text:
FROM nginx

ADD docker/apt-packages.txt \
    /express/install/

RUN apt-get update && \
    apt-get install --no-install-recommends -y `tr '\n' ' ' < /express/install/apt-packages.txt`

RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -

RUN apt-get install -y nodejs

RUN apt-get clean

ADD docker/supervisor.expresshome.conf /express/supervisor.expresshome.conf

ADD package.json webpack_build.sh /express/

RUN cd /express && npm install

ADD blogsrc/package.json /express/blogsrc/

RUN cd /express/blogsrc && npm install

ADD blogsrc /express/blogsrc

RUN cd /express/blogsrc && npm run build

ADD client /express/client

ADD .babelrc server.js webpack.config.babel.js newrelic.js \
    /express/

RUN cd /express && npm run build

ADD server /express/server

ADD config /express/config

ADD nginx.expresshome.conf /express/

ADD entrypoint.sh /express/

ENV PORT=80

CMD ["/bin/bash", "-c", "/express/entrypoint.sh"]


text:
module Autotest
  module Users
    VERSION = "0.1"
  end
end


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Garagemanagement;
using System.Diagnostics;

namespace GaragemanagementTEST
{
    [TestClass]
    public class DataReaderTEST
    {
        [TestMethod]
        public void TEST()
        {

        }
    }
}


text:
Recent Articles

                        {{ article.title }}

                        {{ article.date }} | {{ article.tags }}

Upcoming Articles

                        {{ article.title }}

                        {{ article.date }} | {{ article.tags }}

Current Projects

Static section here.

Online Presence


text:
namespace CymaticLabs.InfluxDB.Data
{
    /// <summary>
    /// Different InfluxDB fill types.
    /// </summary>
    public enum InfluxDbFillTypes
    {
        /// <summary>
        /// Exhibits the same behavior as the default (sets NULL as the value for intervals with no data).
        /// </summary>
        Null,

        /// <summary>
        /// Reports the value of the previous "time window".
        /// </summary>
        Previous,

        /// <summary>
        /// Suppresses timestamps and values where the value is null (won't add downsampled points for intervals with no data).
        /// </summary>
        None
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.ow2.authzforce</groupId>
		<artifactId>authzforce-ce-core</artifactId>
		<version>17.1.3-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>authzforce-ce-core-pdp-benchmark</artifactId>
	<name>${project.groupId}:${project.artifactId}</name>
	<description>AuthzForce - Core PDP Benchmark against AT&T XACML and WSO2 Balana</description>
	<url>${project.url}</url>
	<scm>
		<!-- Used by Jenkins - Maven release plugin -->
		<connection>scm:git:${git.url.base}/core.git/pdp-benchmark</connection>
		<developerConnection>scm:git:${git.url.base}/core.git/pdp-benchmark</developerConnection>
		<tag>HEAD</tag>
		<!-- Publicly browsable repository URL. For example, via Gitlab web UI. -->
		<url>${git.url.base}/core/pdp-benchmark</url>
	</scm>
	<!-- distributionManagement defined in parent POM already -->
	<dependencies>
		<dependency>
			<groupId>org.ow2.authzforce</groupId>
			<artifactId>authzforce-ce-core-pdp-testutils</artifactId>
			<version>17.1.3-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.authzforce</groupId>
			<artifactId>authzforce-ce-core-pdp-io-xacml-json</artifactId>
			<version>17.1.3-SNAPSHOT</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<!-- Test dependencies -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>7.5</version>
			<scope>test</scope>
		</dependency>
		<!-- Other XACML engines -->
		<dependency>
			<groupId>com.att.research.xacml</groupId>
			<artifactId>xacml-pdp</artifactId>
			<version>3.0</version>
			<exclusions>
				<exclusion>
					<!-- Replaced with jcl-over-slf4j depended on by AuthzForce -->
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.wso2.balana</groupId>
			<artifactId>org.wso2.balana</artifactId>
			<version>1.2.11</version>
			<exclusions>
				<exclusion>
					<!-- Replaced with jcl-over-slf4j depended on by AuthzForce -->
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
				<exclusion>
					<!-- already in org.wso2.balana bundle -->
					<groupId>org.wso2.balana</groupId>
					<artifactId>org.wso2.balana.utils</artifactId>
				</exclusion>
				<exclusion>
					<!-- Overlaps slf4j, logback -->
					<groupId>org.ops4j.pax.logging</groupId>
					<artifactId>pax-logging-api</artifactId>
				</exclusion>
			</exclusions>
			<scope>test</scope>
		</dependency>
		<!-- <dependency> -->
		<!-- Do not use WSO2 version of xercesImpl. See https://github.com/wso2/balana/issues/82 . This org.wso2.balana.utils runtime dependency overlaps with att xacml-pdp's dependency xml-apis -->
		<!-- <groupId>xerces.wso2</groupId> -->
		<!-- <artifactId>xercesImpl</artifactId> -->
		<!-- <version>2.8.1.wso2v2</version> -->
		<!-- </dependency> -->
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
			<version>2.12.2</version>
			<scope>test</scope>
		</dependency>
		<!-- /Test dependencies -->
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<!-- Consider combining with Red Hat Victims and OSS Index. More info on Victims vs. Dependency-check: https://bugzilla.redhat.com/show_bug.cgi?id=1388712 -->
				<groupId>org.owasp</groupId>
				<artifactId>dependency-check-maven</artifactId>
				<configuration>
					<cveValidForHours>24</cveValidForHours>
					<!-- The plugin has numerous issues with version matching, which triggers false positives, so we need a "suppression" file for those. More info: https://github.com/jeremylong/DependencyCheck/issues -->
					<suppressionFile>owasp-dependency-check-suppression.xml</suppressionFile>
					<failBuildOnAnyVulnerability>true</failBuildOnAnyVulnerability>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<!-- target JDK already set by parent project's maven.compiler.target property -->
				<configuration>
					<verbose>true</verbose>
					<excludeRoots>
						<excludeRoot>target/generated-sources/xjc</excludeRoot>
						<excludeRoot>target/generated-test-sources/xjc</excludeRoot>
						<excludeRoot>target/generated-test-sources/cxf</excludeRoot>
					</excludeRoots>
				</configuration>
				<executions>
					<execution>
						<phase>verify</phase>
						<goals>
							<goal>check</goal>
							<goal>cpd-check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>com.github.spotbugs</groupId>
               <artifactId>spotbugs-maven-plugin</artifactId>
				<executions>
					<execution>
						<phase>verify</phase>
						<goals>
							<goal>check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>com.mycila</groupId>
				<artifactId>license-maven-plugin</artifactId>
				<configuration>
					<header>license/alv2-header.txt</header>
					<headerDefinitions>
						<headerDefinition>license/header-defs.xml</headerDefinition>
					</headerDefinitions>
					<includes>
						<include>src/main/java/org/ow2/authzforce/**</include>
						<!-- Include test files also -->
						<include>src/test/java/org/ow2/authzforce/**</include>
					</includes>
				</configuration>
				<executions>
					<execution>
						<id>format-sources-license</id>
						<phase>process-sources</phase>
						<goals>
							<goal>format</goal>
						</goals>
					</execution>
					<execution>
						<id>format-test-sources-license</id>
						<phase>process-test-sources</phase>
						<goals>
							<goal>format</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<!-- This execution of surefire is overwritten by a default one unless we specify a different version in pluginManagement. -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<executions>
					<execution>
						<id>xml-tests</id>
						<configuration>
							<skipTests>false</skipTests>
							<!-- XACML/XML tests (JUnit) -->
							<includes>
								<include>**/ComparativePdpTest.java</include>
							</includes>
							<skipAfterFailureCount>1</skipAfterFailureCount>
							<!-- redirectTestOutputToFile: set this to 'true' to redirect the unit test standard output to a file (found in reportsDirectory/testName-output.txt) -->
							<redirectTestOutputToFile>false</redirectTestOutputToFile>
							<systemPropertyVariables>
								<javax.xml.accessExternalSchema>all</javax.xml.accessExternalSchema>
							</systemPropertyVariables>
							<properties>
								<property>
									<name>surefire.testng.verbose</name>
									<!-- verbosity level from 0 to 10 (10 is the most detailed), or -1 for debug More info: http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html -->
									<value>3</value>
								</property>
							</properties>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
local ValueMatcher = require 'test.mock.ValueMatcher'

--- Wraps a function and records the calls.
-- For each call the arguments and return values are saved.
local Spy =
{
    mt = {},
    prototype = {}
}
Spy.mt.__index = Spy.prototype
setmetatable(Spy.prototype, Spy.prototype)
setmetatable(Spy, Spy)

function Spy:__call( wrappedFn )
    return self:new(wrappedFn)
end

function Spy:new( wrappedFn )
    local instance = setmetatable({ wrappedFn = wrappedFn }, self.mt)
    instance:reset()
    return instance
end

function Spy.mt:__call( ... )
    local returnValues = { self.wrappedFn(...) }
    local call = {
        arguments = {...},
        returnValues = returnValues
    }
    table.insert(self.calls, call)
    return table.unpack(returnValues)
end

function Spy.prototype:reset()
    self.calls = {}
    return self
end

--- Test if the spy was called exactly `count` times.
function Spy.prototype:assertCallCount( count )
    if #self.calls ~= count then
        error('Should be called '..count..' times, but was called '..#self.calls..' times.', 2)
    end
    return self
end

function Spy.prototype:getSelectedCalls_( query, level )
    level = level or 1
    local selectedCalls = {}

    if query.atIndex then
        local call = self.calls[query.atIndex]
        if call then
            table.insert(selectedCalls, call)
        else
            error('No call at index '..query.atIndex..'.  Recorded only '..#self.calls..' calls.', level+1)
        end
    end

    -- Use wildcard as default:
    if not query.atIndex then
        selectedCalls = self.calls
    end

    if not #selectedCalls then
        error('No calls selected.', level+1)
    end

    return selectedCalls
end

local argumentMismatchedMessage = 'Argument %d of call %d mismatched:  %s'
local returnValueMismatchedMessage = 'Return value %d of call %d mismatched:  %s'

--- Test if some calls match specific properties.
--
-- Specify a set of calls to test, by adding:
-- - 'atIndex': Test only the call at the given index.
-- - nothing: Acts as a wildcard and will select all calls.
--
-- Specify a set of call attributes to test, by adding:
-- - 'arguments': A list of value matchers, that is compared to the actual arguments.
-- - 'returnValues': A list of value matchers, that is compared to the actual return values.
function Spy.prototype:assertCallMatches( query, level )
    level = level or 1

    local selectedCalls = self:getSelectedCalls_(query, level+1)

    for callIndex, call in ipairs(selectedCalls) do
        if query.arguments then
            local matches, mismatchedIndex, mismatchReason =
                ValueMatcher.matches(call.arguments, query.arguments)
            if not matches then
                error(argumentMismatchedMessage:format(mismatchedIndex,
                                                       callIndex,
                                                       mismatchReason),
                      level+1)
            end
        end

        if query.returnValues then
            local matches, mismatchedIndex, mismatchReason =
                ValueMatcher.matches(call.returnValues, query.returnValues)
            if not matches then
                error(returnValueMismatchedMessage:format(mismatchedIndex,
                                                          callIndex,
                                                          mismatchReason),
                      level+1)
            end
        end
    end

    return self
end

--- Test if at least one call match specific properties.
-- Acts like #Spy.prototype:assertCallMatches, but succeeds if at least one
-- call matches.
function Spy.prototype:assertAnyCallMatches( query, level )
    level = level or 1

    local selectedCalls = self:getSelectedCalls_(query, level+1)

    local oneMatched = false
    for _, call in ipairs(selectedCalls) do
        local argumentsMatch = true
        if query.arguments then
            argumentsMatch = ValueMatcher.matches(call.arguments, query.arguments)
        end

        local returnValuesMatch = true
        if query.returnValues then
            returnValuesMatch = ValueMatcher.matches(call.returnValues, query.returnValues)
        end

        if argumentsMatch and returnValuesMatch then
            oneMatched = true
            break
        end
    end

    if not oneMatched then
        error('No call matched.', level+1)
    end

    return self
end

return Spy


text:
'use strict';

var hiredis = require('hiredis');
var ReplyError = require('../reply_error');

function HiredisReplyParser(options) {
  this.options = options || {};
  this.reset();
}

module.exports = HiredisReplyParser;

HiredisReplyParser.prototype.reset = function () {
  this.reader = new hiredis.Reader({
    return_buffers: true
  });
};

HiredisReplyParser.prototype.execute = function (data) {
  var reply;
  this.reader.feed(data);
  while (true) {
    try {
      reply = this.reader.get();
    } catch (err) {
      this.sendFatalError(err);
      break;
    }

    if (reply === undefined) {
      break;
    }

    if (reply && reply instanceof Error) {
      this.sendError(new ReplyError(reply.message));
    } else {
      this.sendReply(reply);
    }
  }
};


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Rubix\Mvc;

use Zend\Mvc\Controller\AbstractRestfulController as BaseController;
use Zend\View\Model\JsonModel;

abstract class ControllerRestful extends BaseController {

    /**
     * @var array
     */
    protected $collectionOptions = array('GET', 'POST');

    /**
     * @var array
     */
    protected $resourceOptions = array('GET', 'PUT', 'DELETE');

    /**
     * @var array
     */
    protected $auth = array('user' => '', 'pass' => '');

    /**
     * @var ViewModel
     */
    public $view;

    /**
     *  Método de inicialização
     */
    abstract public function init();

    /**
     * Configure class
     */
    final public function configure() {
        $this->view = new JsonModel();
        $this->parseAuth();
        $this->init();
    }

    /**
     * Parse auth params
     */
    private function parseAuth() {
        if ($this->getRequest()->getServer()->offsetExists('PHP_AUTH_USER')) {
            $this->auth['user'] = $this->getRequest()->getServer()->offsetGet('PHP_AUTH_USER');
        }
        if ($this->getRequest()->getServer()->offsetExists('PHP_AUTH_PW')) {
            $this->auth['pass'] = $this->getRequest()->getServer()->offsetGet('PHP_AUTH_PW');
        }
    }

    final public function getOptions() {
        if ($this->params()->fromRoute('id', false)) {
            return $this->resourceOptions;
        }

        return $this->collectionOptions;
    }

    final public function options() {
        $response = $this->getResponse();

        $response->getHeaders()->addHeaderLine('Allow', implode(',', $this->getOptions()));
        return $response;
    }

    // configure response
    public function getResponseWithHeader() {
        $response = $this->getResponse();
        $response->getHeaders()
                //make can accessed by *
                ->addHeaderLine('Access-Control-Allow-Origin', '*')
                //set allow methods
                ->addHeaderLine('Access-Control-Allow-Methods', 'POST PUT DELETE GET');

        return $response;
    }

    /**
     *
     * @param type $parameter
     * @param type $postParameter
     * @return type
     */
    public function getParam($parameter) {
        $param = null;
        switch ($this->getRequest()->getMethod()) {
            case 'GET':
                $param = $this->getRequest()->getQuery()->get($parameter);
                break;
            case 'POST':
            case 'PUT':
            case 'DELETE':
                $param = $this->getRequest()->getPost()->get($parameter);
                break;
        }

        return $param;
    }

    /**
     *
     */
    private function configureAcl() {
        if (!self::$acl) {
            // Acl
            $acl = new \Zend\Permissions\Acl\Acl();

            // Session Acl
            $sessionAcl = new \Zend\Session\Container('acl');
            if ($sessionAcl->offsetExists('roles')) {
                $roles = $sessionAcl->offsetGet('roles');
            } else {
                $roles = include APPLICATION_PATH . '/config/acl.config.php';
            }

            $allResources = array();

            foreach ($roles as $perfil => $resources) {
                $role = new \Zend\Permissions\Acl\Role\GenericRole($perfil);
                $acl->addRole($role);

                $allResources = array_merge($resources, $allResources);

                foreach ($resources as $resource) {
                    if (!$acl->hasResource($resource)) {
                        $acl->addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource));
                    }
                }

                foreach ($allResources as $resource) {
                    $acl->allow($role, $resource);
                }
            }

            self::$acl = $acl;
        }
    }

    public function getAcl() {
        return self::$acl;
    }

    /**
     *
     * @return type
     */
    protected function isAllowed() {
        if (APPLICATION_LOCKED) {
            $identity = $this->identity();
            $module = strtolower($this->params('module'));
            $controller = strtolower($this->params('controller'));
            $action = strtolower($this->params('action'));

            $resource = "{$module}|{$controller}|{$action}";

            if ($identity && $identity->getIntCod()) {
                $codPerfil = $identity->getIntPerfil()->getIntCod();
                return self::$acl->hasResource($resource) ? self::$acl->isAllowed($codPerfil, $resource) : false;
            } else {
                return self::$acl->hasResource($resource) ? self::$acl->isAllowed('guess', $resource) : false;
            }

            return false;
        } else {
            return true;
        }
    }

    /**
     *
     */
    public function verifyIsAllowed() {
        if (!$this->isAllowed()) {
            $this->flashmessenger()->addErrorMessage('Acesso negado.');
            // @todo fazer o redirect correto
            //$this->redirect()->toRoute('home');
            die();
        }
    }

    /**
     *
     * @param type $strController
     * @return type
     */
    private function explodeController($strController) {
        return explode('\\', $strController);
    }

    /**
     *
     * @param type $strController
     * @return type
     */
    public function getModuleName($strController = null) {
        if (!$strController) {
            $strController = get_class($this);
        }

        $arrController = $this->explodeController($strController);

        if (count($arrController) == 3) {
            return array_shift($arrController);
        }
    }

    /**
     *
     * @param type $model
     * @return
     */
    public function getService($service) {
        return $this->getServiceLocator()->get($service);
    }

    /**
     * Get Entity Manager
     * @return \Doctrine\ORM\EntityManager
     */
    public function getEntityManager() {
        return $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
    }

    /**
     *
     * @param string $name
     * @return \Rubix\Mvc\Entity
     */
    public function getEntity($name) {
        $entity = new $name();
        $entity->setServiceManager($this->getServiceLocator());
        return $entity;
    }

    /**
     *
     * @param string $name
     * @return \Rubix\Mvc\Form
     */
    public function getForm($name = null, $options = array()) {
        $form = new $name(null, $options, $this->getServiceLocator());
        return $form;
    }

    /**
     * Translate strings
     * @param type $message
     * @param type $textDomain
     * @param type $locale
     * @return type
     */
    protected function translate($message, $textDomain = 'default', $locale = null) {
        return $this->getServiceLocator()->get('translator')->translate($message, $textDomain, $locale);
    }

    /**
     * Get client IP
     * @return string
     */
    public function getIP() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            //check ip from share internet
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            //to check ip is pass from proxy
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }

    /**
     * Throw exception message
     * @param type $e
     * @return \Zend\View\Model\JsonModel
     */
    protected function fault($e) {
        return new \Zend\View\Model\JsonModel(array(
            'meta' => array(
                'code' => 500,
                'error-message' => $e->getMessage(),
                'error-num' => $e->getCode()
            )
        ));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  fixture
  %%
  Copyright (C) 2013 Martin Lau
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->
<root>
    <item name="org.springframework.security.core.userdetails.UserDetails java.lang.String getPassword()">
        <annotation name="org.jetbrains.annotations.NotNull"/>
    </item>
    <item name="org.springframework.security.core.userdetails.UserDetails java.lang.String getUsername()">
        <annotation name="org.jetbrains.annotations.NotNull"/>
    </item>
    <item name="org.springframework.security.core.userdetails.UserDetails java.util.Collection<? extends org.springframework.security.core.GrantedAuthority> getAuthorities()">
        <annotation name="jet.runtime.typeinfo.KotlinSignature">
            <val name="value" val=""fun getAuthorities(): Collection<out GrantedAuthority>""/>
        </annotation>
    </item>
    <item name='org.springframework.security.core.userdetails.UserDetailsService org.springframework.security.core.userdetails.UserDetails loadUserByUsername(java.lang.String)'>
        <annotation name='org.jetbrains.annotations.NotNull'/>
    </item>
</root>


text:
=begin
#The Plaid API

#The Plaid REST API. Please see https://plaid.com/docs/api for more details.

The version of the OpenAPI document: 2020-09-14_1.205.3

Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1

=end

require 'date'
require 'time'

module Plaid
  # WalletTransactionGetResponse defines the response schema for `/wallet/transaction/get`
  class WalletTransactionGetResponse
    # A unique ID identifying the transaction
    attr_accessor :transaction_id

    # A reference for the transaction
    attr_accessor :reference

    # The type of the transaction. The supported transaction types that are returned are: `BANK_TRANSFER:` a transaction which credits an e-wallet through an external bank transfer.  `PAYOUT:` a transaction which debits an e-wallet by disbursing funds to a counterparty.  `PIS_PAY_IN:` a payment which credits an e-wallet through Plaid's Payment Initiation Services (PIS) APIs. For more information see the [Payment Initiation endpoints](https://plaid.com/docs/api/products/payment-initiation/).  `REFUND:` a transaction which debits an e-wallet by refunding a previously initiated payment made through Plaid's [PIS APIs](https://plaid.com/docs/api/products/payment-initiation/).
    attr_accessor :type

    attr_accessor :amount

    attr_accessor :counterparty

    attr_accessor :status

    # Timestamp when the transaction was created, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format.
    attr_accessor :created_at

    # The date and time of the last time the `status` was updated, in IS0 8601 format
    attr_accessor :last_status_update

    # The payment id that this transaction is associated with, if any. This is present only for transaction types `PIS_PAY_IN` and `REFUND`.
    attr_accessor :payment_id

    # A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.
    attr_accessor :request_id

    class EnumAttributeValidator
      attr_reader :datatype
      attr_reader :allowable_values

      def initialize(datatype, allowable_values)
        @allowable_values = allowable_values.map do |value|
          case datatype.to_s
          when /Integer/i
            value.to_i
          when /Float/i
            value.to_f
          else
            value
          end
        end
      end

      def valid?(value)
        !value || allowable_values.include?(value)
      end
    end

    # Attribute mapping from ruby-style variable name to JSON key.
    def self.attribute_map
      {
        :'transaction_id' => :'transaction_id',
        :'reference' => :'reference',
        :'type' => :'type',
        :'amount' => :'amount',
        :'counterparty' => :'counterparty',
        :'status' => :'status',
        :'created_at' => :'created_at',
        :'last_status_update' => :'last_status_update',
        :'payment_id' => :'payment_id',
        :'request_id' => :'request_id'
      }
    end

    # Returns all the JSON keys this model knows about
    def self.acceptable_attributes
      attribute_map.values
    end

    # Attribute type mapping.
    def self.openapi_types
      {
        :'transaction_id' => :'String',
        :'reference' => :'String',
        :'type' => :'String',
        :'amount' => :'WalletTransactionAmount',
        :'counterparty' => :'WalletTransactionCounterparty',
        :'status' => :'WalletTransactionStatus',
        :'created_at' => :'Time',
        :'last_status_update' => :'Time',
        :'payment_id' => :'String',
        :'request_id' => :'String'
      }
    end

    # List of attributes with nullable: true
    def self.openapi_nullable
      Set.new([
        :'payment_id',
      ])
    end

    # List of class defined in allOf (OpenAPI v3)
    def self.openapi_all_of
      [
      :'PaymentInitiationRecipientGetResponseAllOf',
      :'WalletTransaction'
      ]
    end

    # Initializes the object
    # @param [Hash] attributes Model attributes in the form of hash
    def initialize(attributes = {})
      if (!attributes.is_a?(Hash))
        fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::WalletTransactionGetResponse` initialize method"
      end

      # check to see if the attribute exists and convert string to symbol for hash key
      attributes = attributes.each_with_object({}) { |(k, v), h|
        if (!self.class.attribute_map.key?(k.to_sym))
          fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::WalletTransactionGetResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
        end
        h[k.to_sym] = v
      }

      if attributes.key?(:'transaction_id')
        self.transaction_id = attributes[:'transaction_id']
      end

      if attributes.key?(:'reference')
        self.reference = attributes[:'reference']
      end

      if attributes.key?(:'type')
        self.type = attributes[:'type']
      end

      if attributes.key?(:'amount')
        self.amount = attributes[:'amount']
      end

      if attributes.key?(:'counterparty')
        self.counterparty = attributes[:'counterparty']
      end

      if attributes.key?(:'status')
        self.status = attributes[:'status']
      end

      if attributes.key?(:'created_at')
        self.created_at = attributes[:'created_at']
      end

      if attributes.key?(:'last_status_update')
        self.last_status_update = attributes[:'last_status_update']
      end

      if attributes.key?(:'payment_id')
        self.payment_id = attributes[:'payment_id']
      end

      if attributes.key?(:'request_id')
        self.request_id = attributes[:'request_id']
      end
    end

    # Show invalid properties with the reasons. Usually used together with valid?
    # @return Array for valid properties with the reasons
    def list_invalid_properties
      invalid_properties = Array.new
      if @transaction_id.nil?
        invalid_properties.push('invalid value for "transaction_id", transaction_id cannot be nil.')
      end

      if @reference.nil?
        invalid_properties.push('invalid value for "reference", reference cannot be nil.')
      end

      if @type.nil?
        invalid_properties.push('invalid value for "type", type cannot be nil.')
      end

      if @amount.nil?
        invalid_properties.push('invalid value for "amount", amount cannot be nil.')
      end

      if @counterparty.nil?
        invalid_properties.push('invalid value for "counterparty", counterparty cannot be nil.')
      end

      if @status.nil?
        invalid_properties.push('invalid value for "status", status cannot be nil.')
      end

      if @created_at.nil?
        invalid_properties.push('invalid value for "created_at", created_at cannot be nil.')
      end

      if @last_status_update.nil?
        invalid_properties.push('invalid value for "last_status_update", last_status_update cannot be nil.')
      end

      if @request_id.nil?
        invalid_properties.push('invalid value for "request_id", request_id cannot be nil.')
      end

      invalid_properties
    end

    # Check to see if the all the properties in the model are valid
    # @return true if the model is valid
    def valid?
      return false if @transaction_id.nil?
      return false if @reference.nil?
      return false if @type.nil?
      type_validator = EnumAttributeValidator.new('String', ["BANK_TRANSFER", "PAYOUT", "PIS_PAY_IN", "REFUND"])
      return false unless type_validator.valid?(@type)
      return false if @amount.nil?
      return false if @counterparty.nil?
      return false if @status.nil?
      return false if @created_at.nil?
      return false if @last_status_update.nil?
      return false if @request_id.nil?
      true
    end

    # Custom attribute writer method checking allowed values (enum).
    # @param [Object] type Object to be assigned
    def type=(type)
      validator = EnumAttributeValidator.new('String', ["BANK_TRANSFER", "PAYOUT", "PIS_PAY_IN", "REFUND"])
      unless validator.valid?(type)
        fail ArgumentError, "invalid value for \"type\", must be one of #{validator.allowable_values}."
      end
      @type = type
    end

    # Checks equality by comparing each attribute.
    # @param [Object] Object to be compared
    def ==(o)
      return true if self.equal?(o)
      self.class == o.class &&
          transaction_id == o.transaction_id &&
          reference == o.reference &&
          type == o.type &&
          amount == o.amount &&
          counterparty == o.counterparty &&
          status == o.status &&
          created_at == o.created_at &&
          last_status_update == o.last_status_update &&
          payment_id == o.payment_id &&
          request_id == o.request_id
    end

    # @see the `==` method
    # @param [Object] Object to be compared
    def eql?(o)
      self == o
    end

    # Calculates hash code according to all attributes.
    # @return [Integer] Hash code
    def hash
      [transaction_id, reference, type, amount, counterparty, status, created_at, last_status_update, payment_id, request_id].hash
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def self.build_from_hash(attributes)
      new.build_from_hash(attributes)
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def build_from_hash(attributes)
      return nil unless attributes.is_a?(Hash)
      self.class.openapi_types.each_pair do |key, type|
        if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
          self.send("#{key}=", nil)
        elsif type =~ /\AArray<(.*)>/i
          # check to ensure the input is an array given that the attribute
          # is documented as an array but the input is not
          if attributes[self.class.attribute_map[key]].is_a?(Array)
            self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
          end
        elsif !attributes[self.class.attribute_map[key]].nil?
          self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
        end
      end

      self
    end

    # Deserializes the data based on type
    # @param string type Data type
    # @param string value Value to be deserialized
    # @return [Object] Deserialized data
    def _deserialize(type, value)
      case type.to_sym
      when :Time
        Time.parse(value)
      when :Date
        Date.parse(value)
      when :String
        value.to_s
      when :Integer
        value.to_i
      when :Float
        value.to_f
      when :Boolean
        if value.to_s =~ /\A(true|t|yes|y|1)\z/i
          true
        else
          false
        end
      when :Object
        # generic object (usually a Hash), return directly
        value
      when /\AArray<(?<inner_type>.+)>\z/
        inner_type = Regexp.last_match[:inner_type]
        value.map { |v| _deserialize(inner_type, v) }
      when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
        k_type = Regexp.last_match[:k_type]
        v_type = Regexp.last_match[:v_type]
        {}.tap do |hash|
          value.each do |k, v|
            hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
          end
        end
      else # model
        # models (e.g. Pet) or oneOf
        klass = Plaid.const_get(type)
        klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
      end
    end

    # Returns the string representation of the object
    # @return [String] String presentation of the object
    def to_s
      to_hash.to_s
    end

    # to_body is an alias to to_hash (backward compatibility)
    # @return [Hash] Returns the object in the form of hash
    def to_body
      to_hash
    end

    # Returns the object in the form of hash
    # @return [Hash] Returns the object in the form of hash
    def to_hash
      hash = {}
      self.class.attribute_map.each_pair do |attr, param|
        value = self.send(attr)
        if value.nil?
          is_nullable = self.class.openapi_nullable.include?(attr)
          next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
        end

        hash[param] = _to_hash(value)
      end
      hash
    end

    # Outputs non-array value in the form of hash
    # For object, use to_hash. Otherwise, just return the value
    # @param [Object] value Any valid value
    # @return [Hash] Returns the value in the form of hash
    def _to_hash(value)
      if value.is_a?(Array)
        value.compact.map { |v| _to_hash(v) }
      elsif value.is_a?(Hash)
        {}.tap do |hash|
          value.each { |k, v| hash[k] = _to_hash(v) }
        end
      elsif value.respond_to? :to_hash
        value.to_hash
      else
        value
      end
    end

  end

end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Bolt.Generators
{
    public class ProxyGenerator : ContractGeneratorBase
    {
        public ProxyGenerator()
            : this(new StringWriter(), new TypeFormatter(), new IntendProvider())
        {
        }

        public ProxyGenerator(StringWriter output, TypeFormatter formatter, IntendProvider intendProvider)
            : base(output, formatter, intendProvider)
        {
            Suffix = "Proxy";
            Modifier = "public";
        }

        public bool ForceAsync { get; set; }

        public string Suffix { get; set; }

        public string Namespace { get; set; }

        public string Name { get; set; }

        public string Modifier { get; set; }

        public IEnumerable<string> BaseInterfaces { get; set; }

        public IUserCodeGenerator UserGenerator { get; set; }

        public override void Generate(object context)
        {
            AddUsings(BoltConstants.Client.Namespace, "System.Threading", "System.Reflection");

            ClassGenerator generator = CreateClassGenerator(ContractDescriptor);
            generator.Modifier = Modifier;
            generator.UserGenerator = UserGenerator;
            generator.GenerateBodyAction = g =>
                {
                    g.GenerateConstructor(g.Descriptor.FullName + " proxy", "proxy");
                    g.GenerateConstructor($"{FormatType(BoltConstants.Client.Pipeline)} channel", $"typeof({ContractDefinition.Root.FullName}), channel");

                    List<Type> contracts = ContractDefinition.GetEffectiveContracts().ToList();
                    foreach (Type type in contracts)
                    {
                        GenerateMethods(g, type);
                    }

                    WriteLine();
                    GenerateStaticActions(g);
                };
            generator.Generate(context);
            WriteLine();
        }

        private void GenerateMethods(ClassGenerator classGenerator, Type contract)
        {
            MethodInfo[] methods = ContractDefinition.GetEffectiveMethods(contract).ToArray();

            foreach (MethodInfo method in methods)
            {
                MethodDescriptor descriptor = MetadataProvider.GetMethodDescriptor(ContractDefinition, method);

                GenerateMethod(classGenerator, descriptor, false);

                bool generateAsync = ShouldBeAsync(method, ForceAsync);
                if (generateAsync)
                {
                    WriteLine();
                }
                else
                {
                    if (!Equals(method, methods.Last()))
                    {
                        WriteLine();
                    }
                }

                if (generateAsync)
                {
                    GenerateMethod(classGenerator, descriptor, true);
                    WriteLine();
                }
            }
        }

        private void GenerateMethod(ClassGenerator classGenerator, MethodDescriptor descriptor, bool forceAsync)
        {
            classGenerator.WriteMethod(
                descriptor.Method,
                forceAsync,
                g =>
                {
                    MethodInfo method = descriptor.Method;
                    string parameters = g.FormatMethodParameters(method, false);
                    if (!string.IsNullOrEmpty(parameters))
                    {
                        parameters = ", " + parameters;
                    }
                    if (HasReturnValue(method))
                    {
                        if (IsAsync(method))
                        {
                            WriteLine(
                                "return this.SendAsync<{0}>({1}{2});",
                                FormatType(method.ReturnType.GenericTypeArguments.FirstOrDefault() ?? method.ReturnType),
                                GetStaticActionName(method),
                                parameters);
                        }
                        else if (forceAsync)
                        {
                            WriteLine(
                                "return this.SendAsync<{0}>({1}{2});",
                                FormatType(method.ReturnType),
                                GetStaticActionName(method),
                                parameters);
                        }
                        else
                        {
                            WriteLine(
                                "return this.Send<{0}>({1}{2});",
                                FormatType(method.ReturnType),
                                GetStaticActionName(method),
                                parameters);
                        }
                    }
                    else
                    {
                        if (IsAsync(method))
                        {
                            WriteLine("return this.SendAsync({0}{1});", GetStaticActionName(method), parameters);
                        }
                        else if (forceAsync)
                        {
                            WriteLine("return this.SendAsync({0}{1});", GetStaticActionName(method), parameters);
                        }
                        else
                        {
                            WriteLine("this.Send({0}{1});", GetStaticActionName(method), parameters);
                        }
                    }
                });
        }

        protected override ClassDescriptor CreateDefaultDescriptor()
        {
            List<string> baseClasses = new List<string>();
            string baseClass = BoltConstants.Client.ProxyBase.FullName;
            baseClasses.Add(baseClass);
            baseClasses.Add(ContractDefinition.Root.FullName);

            if (BaseInterfaces != null)
            {
                baseClasses.AddRange(BaseInterfaces);
            }

            return new ClassDescriptor(
                Name ?? ContractDefinition.Name + Suffix,
                Namespace ?? ContractDefinition.Namespace,
                baseClasses.Distinct().ToArray());
        }

        private void GenerateStaticActions(ClassGenerator generator)
        {
            foreach (MethodInfo effectiveMethod in ContractDefinition.GetEffectiveMethods())
            {
                generator.WriteLine(
                    "private static readonly {0} {1} = typeof({2}).GetMethod(nameof({2}.{3}));",
                    FormatType<MethodInfo>(),
                    GetStaticActionName(effectiveMethod),
                    FormatType(effectiveMethod.DeclaringType),
                    effectiveMethod.Name);
            }
        }

        private static string GetStaticActionName(MethodInfo effectiveMethod)
        {
            return $"__{effectiveMethod.Name}Action";
        }
    }
}


text:
$(document).ready(function() {
  console.log('main.js is ready');

  // =======================================
  // ========== HELP METHODS ZONE ==========
  // =======================================

  // This function helps to use Bootstrap Notify
  var myNotify = function(message, type) {
      $.notify({message}, {type, placement: {from: 'bottom'}});
  };

  // This function helps to show data in the table from the API GET request
  var showTable = function(res) {
    console.log(res);
    var newHTML = '';
    if (res.ITEMS.length == 0) {
        newHTML = [];
        myNotify(`No entries was found. Try another request.`, 'warning');
    } else {
        newHTML = $.map(res.ITEMS, function(value) {
            return `

                                ${value.sum}
                                NZ

DATE: ${moment(value.date).format('L')}
                                ${value.category}

${value.comment}

            `;
        });
    }
    $("#main-table").html(newHTML.join(""));
  };

  // =======================================
  // ============ NEW ENTRY ZONE ===========
  // =======================================

  $('#new-entry-form').validator().on('submit', function(e) {
    var formData = $('form').serializeArray();
    // console.log(formData);
    if (e.isDefaultPrevented()) {
        // handle the invalid form...
        myNotify(`Form is not completed OR you made some mistake!`, 'danger');
        } else {
        // everything looks good!
        $.ajax({
            type: 'POST',
            url: '/api/entries',
            headers: { "X-CSRF-Token": $('input[name="_csrf"]')[0].value },
            dataType: "json",
            data: {
                user      : $('input[name="_userID"]')[0].value,
                date      : formData[2].value,
                sum       : formData[3].value,
                category  : formData[4].value,
                comment   : formData[5].value
            },
            success: function(data) {
                myNotify('New entry posted successfuly!', 'success');
                showALLEntries();
                console.log(data);
            },
            error: function(err) {
                myNotify(`${err.responseText} - ${err.statusText}`, 'danger');
                console.log(err);
            }
        });
        e.preventDefault();
      }
  });

  // =======================================
  // ========== API REQUESTS ZONE ==========
  // =======================================

  // AJAX GET ALL ENTRIES request
  var showALLEntries = function() {
      $.ajax({
          type: 'GET',
          url: '/api/entries',
          success: function(data) {
              showTable(data)
          },
          error: function(err){
              myNotify(`${err.status} - ${err.statusText}`, 'danger');
              console.log(err);
          }
      });
  };

  // =======================================
  // ============= BUTTONS =================
  // =======================================

  // SHOW ALL ENTRIES BUTTON
  $('#show-all-button').click(function() {
      var filter = null;
      if ($('#category-selector')[0].value != 'All entries') {
          filter = $('#category-selector')[0].value;
      }
      $.ajax({
          type  : 'GET',
          url   : '/api/entries/',
          data  : { category: filter },
          success: function(data) {
              showTable(data);
          },
          error: function(err) {
              myNotify(`${err.status} - ${err.statusText}`, 'danger');
              console.log(err);
          }
      });
  });

  // RESET CATEGODY BUTTON
  $('#category-reset-button').click(function() {
      $('#category-selector')[0].value = 'All entries';
      showALLEntries();
  });

  // COPY ELEMENT ID TO THE EDIT FORM
  $(document).on('click', '.entries-list', function() {
      $('#inputId')[0].value = $(this)[0].id;
      return false;
  });

  // GET entry by ID
  $('#show-id-button').click(function() {
      $.ajax({
          type: 'GET',
          url: '/api/entry/' + $('#inputId')[0].value,
          success: function(data) {
              showTable(data);
          },
          error: function(err) {
              myNotify(`${err.status} - ${err.statusText}`, 'danger');
              console.log(err);
          }
      });
  });

  // DELETE entry by ID
  $('#delete-id-button').click(function() {
      $.ajax({
          type: 'DELETE',
          url: '/api/entry/' + $('#inputId')[0].value,
          success: function(response) {
              myNotify(`Enrtry ID: ${$('#inputId')[0].value} deleted successfuly`, 'warning');
              $('#inputId')[0].value = '';
              showALLEntries();
          },
          error: function(err) {
              myNotify(`${err.status} - ${err.statusText}`, 'danger');
              console.log(err);
          }
      });
  });

  // POST NEW ENTRY BUTTON TEST
  $('#test-post-button').click(function() {
      $.ajax({
          type: 'POST',
          url: '/api/entries',
          headers: { "X-CSRF-Token": $('input[type="hidden"]')[0].value },
          dataType: "json",
          data: {
              user      : $('input[name="_userID"]')[0].value,
              date      : new Date(),
              sum       : 20.1,
              category  : "Home",
              comment   : "This post is generated by clicking TEST POST button. Cheers!"
          },
          success: function(data) {
              myNotify('New entry posted successfuly!', 'success');
              showALLEntries();
              console.log(data);
          },
          error: function(err) {
              myNotify(`${err.status} - ${err.statusText}`, 'danger');
              console.log(err);
          }
      });
  });

  // =======================================
  // ============= UPLOAD CSV ==============
  // =======================================

  // Parse CSV using papaparse.min.js
  $('#upload-input').on('change', function() {
        $('#upload-input').parse({
            config: {
                header: false,
                delimiter: ',',
                complete: function(results, file) {
                    var newTable = [];
                    // remove header from the table
                    for (let row of results.data.slice(8)) {
                        // skip emty row
                        if (row[0] == '') continue;
                        newTable.push(`

                            ${row[0]}
                            ${row[4]}
                            ${row[5]}
                            ${row[6]}

                                <select class="form-control" id="selectCategory" name="selectCategory">
                                    <option>Home</option>
                                    <option>Market</option>
                                    <option>Electronics</option>
                                    <option>Gifts</option>
                                    <option>Cafe</option>
                                </select>

                            `);
                    }
                    $("#import-data").html(newTable.join(""));
                }
            },
            complete: function() {
                console.log("All files done!");
            }
        });
    });

    $('.upload-btn').on('click', function (){
        $('#upload-input').click();
        $('.progress-bar').text('0%');
        $('.progress-bar').width('0%');
    });

});


text:
cask 'sparkvue' do
  version '3.2.1.3'
  sha256 '37d54175300cbb75bb1e7fec9384af0b7ae1d1f7366be50bb7b6871cddfafdf1'

  # d207q3v45ji5bb.cloudfront.net was verified as official when first introduced to the cask
  url "https://d207q3v45ji5bb.cloudfront.net/software/sparkvue/#{version.major_minor_patch}/SPARKvue-Trial-#{version}.dmg"
  name 'PASCO SPARKvue'
  homepage 'https://www.pasco.com/prodMulti/sparkvue-software/index.cfm'

  pkg 'SPARKvue.pkg'

  uninstall pkgutil: 'com.pasco.SPARKvue'

  zap trash: [
               '~/Library/Application Support/CrashReporter/SPARKvue_*.plist',
               '~/Library/Application Support/SPARKvueUI',
               '~/Library/Preferences/com.pasco.SPARKvue.plist',
               '~/Library/Caches/com.pasco.SPARKvue',
             ]
end


text:
var utils = require('../utils.js');

exports.check = function(hash, res) {
    hs = 'ae11fd697ec92c7c'
    if (hash.length == hs.length && !utils.isANumber(hash) && !utils.isAlpha(hash) && utils.isAlphaNumeric(hash)) {
      res.push("MD5Half");
    }
    return res;
}


text:
#ifndef CUPP_vector_H
#define CUPP_vector_H

#if defined(__CUDACC__)
#error "Not compatible with CUDA. Don't compile with nvcc."
#endif

// CUPP
#include "cupp/common.h"
#include "cupp/runtime.h"
#include "cupp/kernel_type_binding.h"
#include "cupp/kernel_call_traits.h"
#include "cupp/device.h"
#include "cupp/memory1d.h"

#include "cupp/deviceT/vector.h"

#include "cupp/exception/cuda_runtime_error.h"
#include "cupp/exception/memory_access_violation.h"

// STD
#include <cstddef> // Include std::size_t
#include <algorithm> // Include std::swap
#include <vector>

// CUDA
#include <cuda_runtime.h>

namespace cupp {

// Just used to force the user to configure and get a device.
class device;

/**
 * @class vector
 * @author Jens Breitbart
 * @version 0.2
 * @date 24.08.2007
 * @platform Host only
 * @brief A std::vector wrapper, which can be transfered to the device incl. lazy memory copying.
 */

template< typename T >
class vector {
	private:
		typedef typename get_type<T>::device_type                T_device_type;

	public: /*** TYPEDEFS  ***/
		typedef deviceT::vector< T_device_type >                 device_type;
		typedef vector<T>                                        host_type;

		typedef typename std::vector<T>::size_type               size_type;
		typedef typename std::vector<T>::value_type              value_type;
		typedef typename std::vector<T>::const_iterator          const_iterator;
		typedef typename std::vector<T>::const_reverse_iterator  const_reverse_iterator;

	public: /***  The proxy class  ***/

		/**
		 * @class element_proxy
		 * @author Jens Breitbart
		 * @version 0.2
		 * @date 21.07.2007
		 * @brief This class is returned by some functions of @c cupp::vector to determine if an element inside the vector is changed.
		 * @see More effective C++ (Scott Meyers) §30
		 */
		class element_proxy {
			private: /***  Data elements  ***/
				const size_type at_;
				vector<T>& vector_;

			public: /***  Constructors & Destructors  ***/
				element_proxy(const size_type at, vector<T>& vector) :
					at_(at), vector_(vector) {}

			public: /***  Operators  ***/
				operator T&() const {
					vector_.update_host();
					return vector_.data_[at_];
				}

				const T& get() const {
					vector_.update_host();
					return vector_.data_[at_];
				}

				T& get() {
					vector_.update_host();
					vector_.host_changes_ = true;
					return vector_.data_[at_];
				}

				element_proxy& operator=(const element_proxy &rhs) {
					rhs.vector_.update_host();
					vector_.update_host();
					vector_.host_changes_ = true;
					vector_.data_[at_]=rhs.vector_.data_[ rhs.at_];
					return *this;
				}

				element_proxy& operator=(const T& rhs) {
					vector_.update_host();
					vector_.host_changes_ = true;
					vector_.data_[at_] = rhs;
					return *this;
				}

				T* operator&() {
					vector_.update_host();
					return &vector_.data_[at_];
				}
		};

		/**
		 * @class iterator
		 * @author Jens Breitbart
		 * @version 0.1
		 * @date 24.07.2007
		 * @brief This class is returned by some functions of @c cupp::vector to determine if an element inside the vector is changed.
		 * @see More effective C++ (Scott Meyers) §30
		 */
		class iterator {
			private: /***  Data elements  ***/
				typename std::vector<T>::iterator i_;
				vector<T>& vector_;

			public: /***  Constructors & Destructors  ***/
				iterator(const typename std::vector<T>::iterator i, vector<T>& vector) :
					i_(i), vector_(vector) {}

			public: /***  Operators  ***/
				operator typename std::vector<T>::iterator() const {
					vector_.update_host();
					vector_.host_changes_ = true;
					return i_;
				}

				operator const_iterator() const {
					vector_.update_host();
					return static_cast< const_iterator > (i_);
				}

				const T& operator* () const {
					vector_.update_host();
					return *i_;
				}

				T& operator* () {
					vector_.update_host();
					vector_.host_changes_ = true;
					return *i_;
				}

				const T& operator-> () const {
					vector_.update_host();
					return *i_;
				}

				T& operator-> () {
					vector_.update_host();
					vector_.host_changes_ = true;
					return *i_;
				}

				// prefix
				void operator++ () {
					++i_;
				}

				// postfix
				iterator operator++ (int) {
					const iterator returnee = *this;
					++(*this);
					return returnee;
				}

				// prefix
				void operator-- () {
					--i_;
				}

				// postfix
				iterator operator-- (int) {
					iterator returnee = *this;
					--(*this);
					return returnee;
				}

				bool operator!= (const iterator &other) {
					return i_ != other.i_;
				}

				bool operator== (const iterator &other) {
					return i_ == other.i_;
				}
		};

		typedef          std::reverse_iterator<iterator>         reverse_iterator;

	public: /***  CONSTRUCTORS AND DESTRUCTORS  ***/

		/**
		 * @see @c std::vector
		 */
		vector() : data_(), host_changes_(true), device_changes_(false), ref_invalid_(true), memory_ptr_(0), device_ref_ptr_(0) {}

		/**
		 * @see @c std::vector
		 */
		vector( const vector& c ) : host_changes_(true), device_changes_(false), ref_invalid_(true), memory_ptr_(0), device_ref_ptr_(0) {
			c.update_host();
			data_ = c.data_;
		}

		/**
		 * @see @c std::vector
		 */
		vector( size_type num, const T& val = T() ) : data_(num, val), host_changes_(true), device_changes_(false), ref_invalid_(true), memory_ptr_(0), device_ref_ptr_(0) {}

		/**
		 * @see @c std::vector
		 */
		template <typename input_iterator>
		vector( input_iterator start, input_iterator end ) : data_(start, end), host_changes_(true), device_changes_(false), ref_invalid_(true), memory_ptr_(0), device_ref_ptr_(0) {}

		/**
		 * @see @c std::vector
		 */
		~vector() {
			delete memory_ptr_;
			delete device_ref_ptr_;
		}

	public: /***  OPERATORS  ***/
		/**
		 * @see @c std::vector
		 */
		element_proxy operator[]( size_type index ) {
			return element_proxy (index, *this);
		}

		/**
		 * @see @c std::vector
		 */
		const T& operator[]( size_type index ) const {
			update_host();
			return data_[index];
		}

		/**
		 * @see @c std::vector
		 */
		vector& operator=(const vector& c2) {
			c2.update_host();
			data_ = c2.data_;
			host_changes_ = true;

			// our data have been overwritten ... ignore all old data on the device
			device_changes_ = false;

			return *this;
		}

	public: /***  NORMAL FUNCTIONS  ***/
		/**
		 * @see @c std::vector
		 */
		void assign( size_type num, const T& val ) {
			data_.assign (num, val);

			host_changes_ = true;
			// our data have been overwritten ... ignore all old data on the device
			device_changes_ = false;
		}

		/**
		 * @see @c std::vector
		 */
		template <typename input_iterator>
		void assign( input_iterator start, input_iterator end ) {
			data_.assign (start, end);

			host_changes_ = true;
			// our data have been overwritten ... ignore all old data on the device
			device_changes_ = false;
		}

		/**
		 * @see @c std::vector
		 */
		element_proxy at( size_type loc ) {
			data_.at(loc);
			return element_proxy (loc, *this);
		}

		/**
		 * @see @c std::vector
		 */
		const T& at( size_type loc ) const {
			update_host();
			return data_.at(loc);
		}

		/**
		 * @see @c std::vector
		 */
		element_proxy back() {
			return element_proxy(data_.size()-1, *this);
		}

		/**
		 * @see @c std::vector
		 */
		const T& back() const {
			update_host();
			return data_.back();
		}

		/**
		 * @see @c std::vector
		 */
		iterator begin() {
			update_host();
			return iterator (data_.begin(), *this);
		}

		/**
		 * @see @c std::vector
		 */
		const_iterator begin() const {
			return data_.begin();
		}

		/**
		 * @see @c std::vector
		 */
		size_type capacity() const {
			return data_.capacity();
		}

		/**
		 * @see @c std::vector
		 */
		void clear() {
			data_.clear();
			host_changes_ = true;
			device_changes_ = false;
		}

		/**
		 * @see @c std::vector
		 */
		bool empty() const {
			return data_.empty();
		}

		/**
		 * @see @c std::vector
		 */
		iterator end() {
			update_host();
			return iterator (data_.end(), *this);
		}

		/**
		 * @see @c std::vector
		 */
		const_iterator end() const {
			update_host();
			return data_.end();
		}

		/**
		 * @see @c std::vector
		 */
		iterator erase( iterator loc ) {
			update_host();
			host_changes_ = true;
			return iterator (data_.erase(loc), *this);
		}

		/**
		 * @see @c std::vector
		 */
		iterator erase( iterator start, iterator end ) {
			update_host();
			host_changes_ = true;
			return iterator (data_.erase(start, end), *this);
		}

		/**
		 * @see @c std::vector
		 */
		element_proxy front() {
			return element_proxy(0, *this);
		}

		/**
		 * @see @c std::vector
		 */
		const T& front() const {
			update_host();
			return data_.front();
		}

		/**
		 * @see @c std::vector
		 */
		iterator insert( iterator loc, const T& val ) {
			update_host();
			host_changes_ = true;
			return iterator (data_.insert(loc, val), *this);
		}

		/**
		 * @see @c std::vector
		 */
		void insert( iterator loc, size_type num, const T& val ) {
			update_host();
			host_changes_ = true;
			data_.insert(loc, num, val);
		}

		/**
		 * @see @c std::vector
		 */
		template <typename input_iterator>
		void insert( iterator loc, input_iterator start, input_iterator end ) {
			update_host();
			host_changes_ = true;
			data_.insert(loc, start, end);
		}

		/**
		 * @see @c std::vector
		 */
		size_type max_size() const {
			return data_.max_size();
		}

		/**
		 * @see @c std::vector
		 */
		void pop_back() {
			update_host();
			data_.pop_back();
			host_changes_ = true;
		}

		/**
		 * @see @c std::vector
		 */
		void push_back( const T& val ) {
			update_host();
			data_.push_back(val);
			host_changes_ = true;
		}

		/**
		 * @see @c std::vector
		 */
		reverse_iterator rbegin() {
			update_host();
			host_changes_ = true;
			return data_.rbegin();
		}

		/**
		 * @see @c std::vector
		 */
		const_reverse_iterator rbegin() const {
			update_host();
			return data_.rbegin();
		}

		/**
		 * @see @c std::vector
		 */
		reverse_iterator rend() {
			update_host();
			host_changes_ = true;
			return data_.rend();
		}

		/**
		 * @see @c std::vector
		 */
		const_reverse_iterator rend() const {
			update_host();
			return data_.rend();
		}

		/**
		 * @see @c std::vector
		 */
		void reserve( size_type size ) {
			data_.reserve(size);
		}

		/**
		 * @see @c std::vector
		 */
		void resize( size_type num, const T& val = T() ) {
			update_host();
			data_.resize (num, val);
			host_changes_ = true;
		}

		/**
		 * @see @c std::vector
		 */
		size_type size() const {
			return data_.size();
		}

		/**
		 * @see @c std::vector
		 */
		void swap( vector<T>& from ) {
			update_host();

			from.update_host();
			data_.swap(from.data);

			host_changes_ = true;
			from.host_changes_ = true;
		}

	public: /*** CuPP kernel call traits implementation ***/
		/**
		 * @brief This function is called by the kernel_call_traits
		 * @return The device type for our vector
		 */
		device_type transform (const device &d) {
			update_device(d);

			device_type temp;
			temp.set_size ( size());
			temp.set_device_pointer (memory_ptr_->cuda_pointer().get());
			return temp;
		}

		/**
		 * @brief This function is called by the kernel_call_traits
		 * @return A on the device useable vector reference
		 */
		device_reference< device_type > get_device_reference(const device &d) {

			update_device(d);

			if (ref_invalid_) {
				delete device_ref_ptr_;

				device_ref_ptr_ = new device_reference<device_type> (d, transform(d));

				ref_invalid_ = false;
			}

			assert (device_ref_ptr_!=0);

			return *device_ref_ptr_;
		}

		/**
		 * @brief This function is called by the kernel_call_traits
		 */
		void dirty (device_reference< device_type > device_copy) {
			UNUSED_PARAMETER(device_copy);

			device_changes_ = true;
		}

		/*void update (const device_type &value) {
			UNUSED_PARAMETER(value);

			device_changes_ = true;
		}*/

		vector< T >&  operator= (const device_type& value) {
			UNUSED_PARAMETER(value);

			device_changes_ = true;
			return *this;
		}

		/**
		 * If there is newer data on the device, this function will update the host data with it
		 */
		void update_host() const {
			if (device_changes_) {
				assert(!host_changes_);
				assert(memory_ptr_!=0);

				std::vector< T_device_type > temp( data_.size() );

				memory_ptr_ -> copy_to_host (&temp[0]);

				for (std::size_t i = 0; i<temp.size(); ++i) {
					data_[i] = temp[i];
				}

				device_changes_ = false;
			}
		}

		/**
		 * If there is newer data on the host, this function will update the device data with it
		 */
		void update_device(const device &d) {
			// changes on the host side or we are executed on a new device
			if (host_changes_ || d.id() != device_id_) {

				std::vector< T_device_type > temp;
				/// @todo use a std algo
				for (typename std::vector< T >::iterator it = data_.begin(); it != data_.end(); ++it) {
					temp.push_back ( kernel_call_traits< T, T_device_type >::transform (d, *it) );
				}

				// we don't have any space on the device, or the we have more/less space on the device than we neeed
				// or we are executed on a new device
				if (memory_ptr_ == 0 || memory_ptr_ -> size()!=data_.size() || d.id() != device_id_) {
					// free the memory
					delete memory_ptr_;

					// get new memory and copy the data
					memory_ptr_ = new memory1d<T_device_type>(d, &temp[0], temp.size() );

					// we need to create a new proxy because our memory has a new address
					ref_invalid_ = true;
				} else {
					// copy the data to the device
					memory_ptr_ -> copy_to_device (&temp[0]);
				}

				device_id_ = d.id();
				host_changes_ = false;
			}
		}

	private:
		/**
		 * Our real vector :-)
		 */
		mutable std::vector<T> data_;

		/**
		 * true means, data has been changed on the host and data on the device is out of date
		 */
		mutable bool host_changes_;

		/**
		 * true means, data has been changed on the device and data on the host is out of date
		 */
		mutable bool device_changes_;

		/**
		 * True means we have to recreate our proxy
		 */
		mutable bool ref_invalid_;

		/**
		 * Our device memory :-)
		 */
		mutable memory1d< T_device_type > *memory_ptr_;

		/**
		 * The proxy on our device
		 */
		mutable device_reference<device_type> *device_ref_ptr_;

		/**
		 * A pointer to the device on which our data is stored
		 */
		mutable device::id_t device_id_;
}; // class vector

template <typename T1, typename T2>
bool operator==(const vector<T1>& c1, const vector<T2>& c2) {
	c1.update_host();
	c2.update_host();
	return c1.data_ == c2.data_;
}

template <typename T1, typename T2>
bool operator!=(const vector<T1>& c1, const vector<T2>& c2) {
	return !(c1 == c2);
}

template <typename T1, typename T2>
bool operator<(const vector<T1>& c1, const vector<T2>& c2) {
	c1.update_host();
	c2.update_host();
	return c1.data_ < c2.data_;
}

template <typename T1, typename T2>
bool operator>(const vector<T1>& c1, const vector<T2>& c2) {
	c1.update_host();
	c2.update_host();
	return c1.data_ > c2.data_;
}

template <typename T1, typename T2>
bool operator<=(const vector<T1>& c1, const vector<T2>& c2) {
	return !(c1 > c2);
}

template <typename T1, typename T2>
bool operator>=(const vector<T1>& c1, const vector<T2>& c2) {
	return !(c1 < c2);
}

} // namespace cupp

#endif


text:
<?php

namespace Oro\Bundle\SearchBundle\Soap\Type;

use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use BeSimple\SoapCommon\Type\AbstractKeyValue;

class SelectedValue extends AbstractKeyValue
{
    /**
     * @Soap\ComplexType("string")
     */
    protected $key;

    /**
     * @var string
     * @Soap\ComplexType("string")
     */
    protected $value;

    /**
     * @param $key
     * @param $value
     */
    public function __construct($key, $value)
    {
        if ($value == null) {
            $value = '';
        }

        parent::__construct($key, $value);
    }
}