text:
package mil.nga.giat.geowave.datastore.hbase.query;

import java.io.IOException;

import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.log4j.Logger;

import mil.nga.giat.geowave.core.index.StringUtils;
import mil.nga.giat.geowave.core.store.CloseableIterator;
import mil.nga.giat.geowave.core.store.CloseableIteratorWrapper;
import mil.nga.giat.geowave.core.store.adapter.AdapterStore;
import mil.nga.giat.geowave.core.store.callback.ScanCallback;
import mil.nga.giat.geowave.core.store.index.PrimaryIndex;
import mil.nga.giat.geowave.datastore.hbase.operations.BasicHBaseOperations;
import mil.nga.giat.geowave.datastore.hbase.util.HBaseEntryIteratorWrapper;
import mil.nga.giat.geowave.datastore.hbase.util.HBaseUtils.ScannerClosableWrapper;

abstract public class AbstractHBaseRowQuery<T> extends
		HBaseQuery
{

	private static final Logger LOGGER = Logger.getLogger(AbstractHBaseRowQuery.class);
	protected final ScanCallback<T> scanCallback;

	public AbstractHBaseRowQuery(
			final PrimaryIndex index,
			final String[] authorizations,
			final ScanCallback<T> scanCallback ) {
		super(
				index,
				authorizations);
		this.scanCallback = scanCallback;
	}

	public CloseableIterator<T> query(
			final BasicHBaseOperations operations,
			final double[] maxResolutionSubsamplingPerDimension,
			final AdapterStore adapterStore ) {
		final Scan scanner = new Scan();
		scanner.setMaxResultSize(getScannerLimit());
		ResultScanner results = null;
		try {
			results = operations.getScannedResults(
					scanner,
					StringUtils.stringFromBinary(index.getId().getBytes()),
					authorizations);
		}
		catch (final IOException e) {
			LOGGER.error(
					"Unable to get the scanned results.",
					e);
		}

		if (results != null) {
			return new CloseableIteratorWrapper<T>(
					new ScannerClosableWrapper(
							results),
					new HBaseEntryIteratorWrapper(
							adapterStore,
							index,
							results.iterator(),
							null,
							fieldIds,
							maxResolutionSubsamplingPerDimension,
							true,
							false));
		}
		else {
			return new CloseableIterator.Empty<T>();
		}
	}

	abstract protected Integer getScannerLimit();
}


text:
<?php
namespace CLTools;

/**
 *  CLTools
 *  Author: Josh Carlson
 *  Email: jcarlson(at)carlso(dot)net
 */

/*
 *  CalcTest.php - PHP unit test for Calc() library
 */

//require('./CLData/lib/Calc.php');
//
//class CalcTest extends \PHPUnit_Framework_TestCase
//{
//	protected $calc;
//
//	public function setUp()
//	{
//		$this->calc = new Calc();
//	}
//
//	/**
//	 * @param string $measurementType Measurement type to be tested
//	 *
//	 * @dataProvider providerTestSetMeasurementTypeValid
//	 */
//	public function testSetMeasurementTypeValid($measurementType)
//	{
//		$this->assertTrue($this->calc->setMeasurementType($measurementType));
//	}
//
//	public function providerTestSetMeasurementTypeValid()
//	{
//		return array(
//			array('AVG'),
//			array('MAX'),
//			array('MIN'),
//			array('COUNT')
//		);
//	}
//
//	public function testSetMeasurementTypeInvalid()
//	{
//
//	}
//
//	public function testSetDataField()
//	{
//
//	}
//
//	public function testCalculate()
//	{
//
//	}
//}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/appstream/AppStream_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace AppStream
{
namespace Model
{
  enum class FleetAttribute
  {
    NOT_SET,
    VPC_CONFIGURATION,
    VPC_CONFIGURATION_SECURITY_GROUP_IDS,
    DOMAIN_JOIN_INFO,
    IAM_ROLE_ARN,
    USB_DEVICE_FILTER_STRINGS,
    SESSION_SCRIPT_S3_LOCATION
  };

namespace FleetAttributeMapper
{
AWS_APPSTREAM_API FleetAttribute GetFleetAttributeForName(const Aws::String& name);

AWS_APPSTREAM_API Aws::String GetNameForFleetAttribute(FleetAttribute value);
} // namespace FleetAttributeMapper
} // namespace Model
} // namespace AppStream
} // namespace Aws


text:
[![CircleCI](https://circleci.com/gh/teekkarispeksi/nappikauppa2.svg?style=svg)](https://circleci.com/gh/teekkarispeksi/nappikauppa2)

## Development enviroment

Project uses Visual Studio Code devcontainers for creating platform independent isolated development environment.

### Requirements

Check that these requirements are installed before proceeding futher

1. [Docker](https://www.docker.com)
2. [Visual Studio Code](https://https://code.visualstudio.com/)
3. [Visual Studio Code Remote Development](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack)

Other project requirements and VSCode extensions are managed by devcontainer system.

### Developing

1. Open project folder with VSCode
2. Check enviroment variables and directory mounts in `.devcontainer/docker-compose.yml` file. Pay attention to `UID` and `GID` variables
3. Reopen project in remote container enviroment. Project installs development database and dependencies automatically.
4. Use `ctrl+shift+b` to start dev server
5. Go to [http://localhost:3000/](http://localhost:3000/). For admin site go to [http://localhost:3000/admin](http://localhost:3000/admin). Default username is admin and password nappiadmin5.

### Notes

Project is migrated  back from [yarn](https://yarnpkg.com/lang/en/) to [npm](https://www.npmjs.com/). Please use npm for installing dependencies as production Dockerfile uses `package-lock.json` file for dependency installation.

Development server supports livereload for detecting frontend changes

## Setting up database for production
( Assuming that you have [mysql (maridb)](https://mariadb.org/) installed )

1. Run db/tables.sql and db/venues.sql against your database (e.g. `mysql nappikauppa2 < db/tables.sql`)
2. Run db/evolutions/01_add_production_to_discount_code.sql against your database
3. Run db/evolutions/02_add_payment_provider_to_order.sql against your database

### Notes

**DO NOT USE DEVELOPEMENT DOCKER DATABASE IN PRODUCTION** Development docker database file is not for production use, if you want to run database inside docker, please create own image for that purposes.

## Building docker image

1. Check out this repository
2. Move to repository root
3. Run `docker build -t teekkarispeksi/nappikauppa2:latest .` and wait magic to happen

Build results to single alpine based docker image which is ready for execution.

## Deploying docker image to production

We use [portainer](https://www.portainer.io/) on top of [docker swarm](https://docs.docker.com/engine/swarm/) for running application stack in production.

### Sample stack.yml

Sample swarm stack configuration

```yml
version: '3.7'

services:
  nappikauppa:
    image: teekkarispeksi/nappikauppa2:latest
    configs:
      - source: nappikauppa-config
        target: /app/config/config.js
      - source: nappikauppa-frontend-config
        target: /app/config/frontend-config.js
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
        delay: 5s
        order: start-first
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s

configs:
  nappikauppa-config:
    name: nappikauppa2.config.v1.js
    external: true
  nappikauppa-frontend-config:
    name: nappikauppa2.frontend-config.v1.js
    external: true

```


text:
title: "500 Internal server error"
cleanurls: false
---
Everything falls into a singularity at times. This is that time.


text:
<?php
namespace RybakDigital\Bundle\UserBundle\Entity\Traits;

use Doctrine\Common\Collections\ArrayCollection;
use RybakDigital\Bundle\UserBundle\Entity\Role;

/**
 * RybakDigital\Bundle\UserBundle\Entity\Traits\GroupRoles
 *
 * @author Kris Rybak <kris.rybak@krisrybak.com>
 */
trait GroupRoles {
    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="groups")
     * @ORM\JoinTable(name="acl_roles_to_groups")
     */
    private $roles;

    /**
     * Add role
     *
     * @param Role $role
     * @return Group
     */
    public function addRole(Role $role)
    {
        $this->roles[] = $role;

        return $this;
    }

    /**
     * Remove role
     *
     * @param Role $role
     */
    public function removeRole(Role $role)
    {
        $this->roles->removeElement($role);

        return $this;
    }

    /**
     * Get roles
     *
     * @return ArrayCollection
     */
    public function getRoles()
    {
        return $this->roles;
    }
}


text:
package org.gradle.composite.internal;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.Transformer;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.artifacts.component.ProjectComponentSelector;
import org.gradle.api.initialization.IncludedBuild;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.LocalComponentRegistry;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.invocation.Gradle;
import org.gradle.internal.component.local.model.DefaultLocalComponentMetadata;
import org.gradle.internal.component.local.model.DefaultProjectComponentSelector;
import org.gradle.internal.component.local.model.LocalComponentArtifactMetadata;
import org.gradle.internal.component.local.model.LocalComponentMetadata;
import org.gradle.internal.component.model.ComponentArtifactMetadata;
import org.gradle.internal.component.model.LocalOriginDependencyMetadata;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.gradle.internal.component.local.model.DefaultProjectComponentIdentifier.newProjectId;

public class IncludedBuildDependencyMetadataBuilder {
    public Map<ProjectComponentIdentifier, RegisteredProject> build(IncludedBuildInternal build) {
        Map<ProjectComponentIdentifier, RegisteredProject> registeredProjects = Maps.newHashMap();
        Gradle gradle = build.getConfiguredBuild();
        for (Project project : gradle.getRootProject().getAllprojects()) {
            registerProject(registeredProjects, build, (ProjectInternal) project);
        }
        return registeredProjects;
    }

    private void registerProject(Map<ProjectComponentIdentifier, RegisteredProject> registeredProjects, IncludedBuild build, ProjectInternal project) {
        LocalComponentRegistry localComponentRegistry = project.getServices().get(LocalComponentRegistry.class);
        ProjectComponentIdentifier originalIdentifier = newProjectId(project);
        DefaultLocalComponentMetadata originalComponent = (DefaultLocalComponentMetadata) localComponentRegistry.getComponent(originalIdentifier);

        ProjectComponentIdentifier componentIdentifier = newProjectId(build, project.getPath());
        LocalComponentMetadata compositeComponent = createCompositeCopy(build, componentIdentifier, originalComponent);
        List<LocalComponentArtifactMetadata> artifacts = Lists.newArrayList();
        for (LocalComponentArtifactMetadata artifactMetaData : localComponentRegistry.getAdditionalArtifacts(originalIdentifier)) {
            artifacts.add(createCompositeCopy(componentIdentifier, artifactMetaData));
        }
        registeredProjects.put(componentIdentifier, new RegisteredProject(compositeComponent, artifacts));
    }

    private LocalComponentMetadata createCompositeCopy(final IncludedBuild build, final ProjectComponentIdentifier componentIdentifier, DefaultLocalComponentMetadata originalComponentMetadata) {
        return originalComponentMetadata.copy(componentIdentifier, new Transformer<LocalComponentArtifactMetadata, LocalComponentArtifactMetadata>() {
            @Override
            public LocalComponentArtifactMetadata transform(LocalComponentArtifactMetadata originalArtifact) {
                File artifactFile = originalArtifact.getFile();
                Set<String> targetTasks = getArtifactTasks(originalArtifact);
                return new CompositeProjectComponentArtifactMetadata(componentIdentifier, originalArtifact.getName(), artifactFile, targetTasks);
            }
        }, new Transformer<LocalOriginDependencyMetadata, LocalOriginDependencyMetadata>() {
            @Override
            public LocalOriginDependencyMetadata transform(LocalOriginDependencyMetadata originalDependency) {
                if (originalDependency.getSelector() instanceof ProjectComponentSelector) {
                    ProjectComponentSelector requested = (ProjectComponentSelector) originalDependency.getSelector();
                    return originalDependency.withTarget(DefaultProjectComponentSelector.newSelector(build, requested));
                }
                return originalDependency;
            }
        });
    }

    private LocalComponentArtifactMetadata createCompositeCopy(ProjectComponentIdentifier project, LocalComponentArtifactMetadata artifactMetaData) {
        File artifactFile = artifactMetaData.getFile();
        return new CompositeProjectComponentArtifactMetadata(project, artifactMetaData.getName(), artifactFile, getArtifactTasks(artifactMetaData));
    }

    private Set<String> getArtifactTasks(ComponentArtifactMetadata artifactMetaData) {
        Set<String> taskPaths = Sets.newLinkedHashSet();
        Set<? extends Task> tasks = artifactMetaData.getBuildDependencies().getDependencies(null);
        for (Task task : tasks) {
            taskPaths.add(task.getPath());
        }
        return taskPaths;
    }
}


text:
namespace IECoreImageBindings
{

void bindClientDisplayDriver();

}

#endif // IECOREIMAGEBINDINGS_CLIENTDISPLAYDRIVERBINDING_H


text:
int twice (int i) { /* THIS LINE */
  /* We purposefully put the return type, function prototype and
     opening curly brace on the same line, in an effort to make sure
     that the function prologue would be associated to that line.  */
  return 2 * i;
}

int
main (void)
{
  int t = twice (1);
  return 0;
}


text:
//
//  EvaluateController.m
//  项目A_汽车之家
//
//  Created by zyana on 15/11/16.
//  Copyright © 2015年 zyana. All rights reserved.
//

#import "EvaluateController.h"
#import "EvaluateManager.h"
#import "EvaluateTableViewCell.h"
#import "DetailsController.h"

@interface EvaluateController ()

@end

@implementation EvaluateController

static NSString *evaluateIdentifier = @"evaluateCell";

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor cyanColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"EvaluateTableViewCell" bundle:nil] forCellReuseIdentifier:evaluateIdentifier];
    [EvaluateManager sharedManager].myUpDataUI = ^(){
        [self.tableView reloadData];
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [EvaluateManager sharedManager].allNews.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT / 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EvaluateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:evaluateIdentifier forIndexPath:indexPath];

    Evaluate *evaluate = [[EvaluateManager sharedManager] evaluateWithIndex:indexPath.row];
    cell.evaluate = evaluate;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailsController *detailsVC = [[DetailsController alloc] init];
    Evaluate *evaluate = [[EvaluateManager sharedManager] evaluateWithIndex:indexPath.row];
    detailsVC.ID = evaluate.ID;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailsVC];
    nav.navigationBar.translucent = NO;
    [self presentViewController:nav animated:YES completion:nil];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
union A
{
	int i;
};

void f(union A a) // CHECK: error: union arguments are not yet implemented
{
}


text:
@interface VSMVVMViewModel : NSObject

PP_STRONG(NSString, labelText)          //文字改变,视图也跟着改变
- (void)viewButtonClick;                //view的事件,这里面更新Model的值
- (void)setModel:(VSMVVMModel *)model;  //设置目标Model

@end


text:
using namespace v8;

StreamDecode::StreamDecode() : next_in(NULL), available_in(0) {
  state = BrotliCreateState(Allocator::Alloc, Allocator::Free, &alloc);
  alloc.ReportMemoryToV8();
}

StreamDecode::~StreamDecode() {
  BrotliDestroyState(state);
}

void StreamDecode::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
  Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  tpl->SetClassName(Nan::New("StreamDecode").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(tpl, "transform", Transform);
  Nan::SetPrototypeMethod(tpl, "flush", Flush);

  constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
  Nan::Set(target, Nan::New("StreamDecode").ToLocalChecked(),
    Nan::GetFunction(tpl).ToLocalChecked());
}

NAN_METHOD(StreamDecode::New) {
  StreamDecode* obj = new StreamDecode();
  obj->Wrap(info.This());
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(StreamDecode::Transform) {
  StreamDecode* obj = ObjectWrap::Unwrap<StreamDecode>(info.Holder());

  Local<Object> buffer = info[0]->ToObject();
  obj->next_in = (const uint8_t*) node::Buffer::Data(buffer);
  obj->available_in = node::Buffer::Length(buffer);

  Nan::Callback *callback = new Nan::Callback(info[1].As<Function>());
  StreamDecodeWorker *worker = new StreamDecodeWorker(callback, obj);
  if (info[2]->BooleanValue()) {
    worker->SaveToPersistent(0U, buffer);
    worker->SaveToPersistent(1U, obj->handle());
    Nan::AsyncQueueWorker(worker);
  } else {
    worker->Execute();
    worker->WorkComplete();
    worker->Destroy();
  }
}

NAN_METHOD(StreamDecode::Flush) {
  StreamDecode* obj = ObjectWrap::Unwrap<StreamDecode>(info.Holder());

  Nan::Callback *callback = new Nan::Callback(info[0].As<Function>());
  StreamDecodeWorker *worker = new StreamDecodeWorker(callback, obj);
  if (info[1]->BooleanValue()) {
    Nan::AsyncQueueWorker(worker);
  } else {
    worker->Execute();
    worker->WorkComplete();
    worker->Destroy();
  }
}

Nan::Persistent<Function> StreamDecode::constructor;


text:
local yaml = require "yaml"
local path = require("path").new("/")
local stringy = require "stringy"
local constants = require "kong.constants"

local _M = {}

_M.path = path

---
-- Checks existence of a file.
-- @param path path/file to check
-- @return `true` if found, `false` + error message otherwise
function _M.file_exists(path)
  local f, err = io.open(path, "r")
  if f ~= nil then
    io.close(f)
    return true
  else
    return false, err
  end
end

---
-- Execute an OS command and catch the output.
-- @param command OS command to execute
-- @return string containing command output (both stdout and stderr)
-- @return exitcode
function _M.os_execute(command)
  local n = os.tmpname() -- get a temporary file name to store output
  local f = os.tmpname() -- get a temporary file name to store script
  _M.write_to_file(f, command)
  local exit_code = os.execute("/bin/bash "..f.." > "..n.." 2>&1")
  local result = _M.read_file(n)
  os.remove(n)
  os.remove(f)
  return string.gsub(string.gsub(result, "^"..f..":[%s%w]+:%s*", ""), "[%\r%\n]", ""), exit_code / 256
end

---
-- Check existence of a command.
-- @param cmd command being searched for
-- @return `true` of found, `false` otherwise
function _M.cmd_exists(cmd)
  local _, code = _M.os_execute("hash "..cmd)
  return code == 0
end

--- Kill a process by PID.
-- Kills the process and waits until it's terminated
-- @param pid_file the file containing the pid to kill
-- @param signal the signal to use
-- @return `os_execute` results, see os_execute.
function _M.kill_process_by_pid_file(pid_file, signal)
  if _M.file_exists(pid_file) then
    local pid = stringy.strip(_M.read_file(pid_file))
    return _M.os_execute("while kill -0 "..pid.." >/dev/null 2>&1; do kill "..(signal and "-"..tostring(signal).." " or "")..pid.."; sleep 0.1; done")
  end
end

--- Read file contents.
-- @param path filepath to read
-- @return file contents as string, or `nil` if not succesful
function _M.read_file(path)
  local contents = nil
  local file = io.open(path, "rb")
  if file then
    contents = file:read("*all")
    file:close()
  end
  return contents
end

--- Write file contents.
-- @param path filepath to write to
-- @return `true` upon success, or `false` + error message on failure
function _M.write_to_file(path, value)
  local file, err = io.open(path, "w")
  if err then
    return false, err
  end

  file:write(value)
  file:close()
  return true
end

--- Get the filesize.
-- @param path path to file to check
-- @return size of file, or `nil` on failure
function _M.file_size(path)
  local size
  local file = io.open(path, "rb")
  if file then
    size = file:seek("end")
    file:close()
  end
  return size
end

--- Load a yaml configuration file.
-- The return config will get 2 extra fields; `pid_file` of the nginx process
-- and `dao_config` as a shortcut to the dao configuration
-- @param configuration_path path to configuration file to load
-- @return config Loaded configuration table
-- @return dao_factory the accompanying DAO factory
function _M.load_configuration_and_dao(configuration_path)
  local configuration_file = _M.read_file(configuration_path)
  if not configuration_file then
    error("No configuration file at: "..configuration_path)
  end

  -- Configuration should already be validated by the CLI at this point
  local configuration = yaml.load(configuration_file)

  local dao_config = configuration.databases_available[configuration.database]
  if dao_config == nil then
    error('No "'..configuration.database..'" dao defined')
  end

  -- Adding computed properties to the configuration
  configuration.pid_file = path:join(configuration.nginx_working_dir, constants.CLI.NGINX_PID)

  -- Alias the DAO configuration we are using for this instance for easy access
  configuration.dao_config = dao_config

  -- Load absolute path for the nginx working directory
  if not stringy.startswith(configuration.nginx_working_dir, "/") then
    -- It's a relative path, convert it to absolute
    local fs = require "luarocks.fs"
    configuration.nginx_working_dir = fs.current_dir().."/"..configuration.nginx_working_dir
  end

  -- Instantiate the DAO Factory along with the configuration
  local DaoFactory = require("kong.dao."..configuration.database..".factory")
  local dao_factory = DaoFactory(dao_config.properties, configuration.plugins_available)

  return configuration, dao_factory
end

return _M


text:
package io.galeb.router.client.hostselectors;

import io.galeb.router.client.ExtendedLoadBalancingProxyClient.Host;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public interface HostSelector {

    AttachmentKey<String> REAL_DEST = AttachmentKey.create(String.class);

    int DEFAULT_POS = 0;

    int selectHost(Host[] availableHosts, HttpServerExchange exchange);

    default Stream<Map.Entry<Integer, Host>> convertToMapStream(final Host[] availableHosts) {
        return IntStream.range(0, availableHosts.length)
                .boxed()
                .collect(Collectors.toMap(i -> i, i -> availableHosts[i]))
                .entrySet()
                .stream();
    }
}


text:
package org.jetbrains.plugins.groovy.runner;

import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.Location;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.execution.application.ApplicationConfigurationProducer;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunConfigurationModule;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.extensions.GroovyScriptTypeDetector;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass;

import java.util.List;

/**
 * @author ilyas
 */
public class GroovyScriptRunConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable {
  protected PsiElement mySourceElement;

  public GroovyScriptRunConfigurationProducer() {
    super(GroovyScriptRunConfigurationType.getInstance());
  }

  public PsiElement getSourceElement() {
    return mySourceElement;
  }

  protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context) {
    final PsiElement element = location.getPsiElement();
    final PsiFile file = element.getContainingFile();
    if (!(file instanceof GroovyFile)) {
      return null;
    }

    GroovyFile groovyFile = (GroovyFile)file;
    final PsiClass aClass = GroovyRunnerUtil.getRunningClass(location.getPsiElement());
    if (aClass instanceof GroovyScriptClass || GroovyRunnerUtil.isRunnable(aClass)) {
      final RunnerAndConfigurationSettings settings = createConfiguration(aClass);
      if (settings != null) {
        mySourceElement = element;
        final GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration)settings.getConfiguration();
        GroovyScriptTypeDetector.getScriptType(groovyFile).tuneConfiguration(groovyFile, configuration, location);
        return settings;
      }
    }

    if (file.getText().contains("@Grab")) {
      ApplicationConfigurationProducer producer = new ApplicationConfigurationProducer();
      ConfigurationFromContext settings = producer.createConfigurationFromContext(context);
      if (settings != null) {
        PsiElement src = settings.getSourceElement();
        mySourceElement = src;
        return createConfiguration(src instanceof PsiMethod ? ((PsiMethod)src).getContainingClass() : (PsiClass)src);
      }

      return null;
    }
    else {
      return null;
    }
  }

  @Override
  protected RunnerAndConfigurationSettings findExistingByElement(Location location,
                                                                 @NotNull List<RunnerAndConfigurationSettings> existingConfigurations,
                                                                 ConfigurationContext context) {
    for (RunnerAndConfigurationSettings existingConfiguration : existingConfigurations) {
      final RunConfiguration configuration = existingConfiguration.getConfiguration();
      final GroovyScriptRunConfiguration existing = (GroovyScriptRunConfiguration)configuration;
      final String path = existing.getScriptPath();
      if (path != null) {
        final PsiFile file = location.getPsiElement().getContainingFile();
        if (file instanceof GroovyFile) {
          final VirtualFile vfile = file.getVirtualFile();
          if (vfile != null && FileUtil.toSystemIndependentName(path).equals(vfile.getPath())) {
            if (!((GroovyFile)file).isScript() ||
                GroovyScriptTypeDetector.getScriptType((GroovyFile)file).isConfigurationByLocation(existing, location)) {
              return existingConfiguration;
            }
          }
        }
      }
    }
    return null;
  }

  public int compareTo(final Object o) {
    return PREFERED;
  }

  @Nullable
  private RunnerAndConfigurationSettings createConfiguration(@Nullable final PsiClass aClass) {
    if (aClass == null) return null;

    final Project project = aClass.getProject();
    RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).createConfiguration("", getConfigurationFactory());
    final GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration)settings.getConfiguration();
    final PsiFile file = aClass.getContainingFile().getOriginalFile();
    final PsiDirectory dir = file.getContainingDirectory();
    if (dir == null) return null;
    configuration.setWorkDir(dir.getVirtualFile().getPath());
    final VirtualFile vFile = file.getVirtualFile();
    if (vFile == null) return null;
    configuration.setScriptPath(vFile.getPath());
    RunConfigurationModule module = configuration.getConfigurationModule();

    String name = GroovyRunnerUtil.getConfigurationName(aClass, module);
    configuration.setName(name);
    configuration.setModule(JavaExecutionUtil.findModule(aClass));
    return settings;
  }
}


text:
<?php

namespace Google\Cloud\Core;

use DrSlump\Protobuf;
use google\protobuf\Value;
use google\protobuf\ListValue;
use google\protobuf\NullValue;
use google\protobuf\Struct;

/**
 * Extend the Protobuf-PHP array codec to allow messages to match the format
 * used for REST.
 * @deprecated
 * @codeCoverageIgnore
 */
class PhpArray extends Protobuf\Codec\PhpArray
{
    /**
     * @var array
     */
    private $customFilters;

    /**
     * @var bool
     */
    private $useCamelCase;

    /**
     * @param array $customFilters A set of callbacks to apply to properties in
     *        a gRPC response.
     * @param bool $useCamelCase Whether to convert key casing to camelCase.
     * }
     */
    public function __construct(array $customFilters = [], $useCamelCase = true)
    {
        $this->customFilters = $customFilters;
        $this->useCamelCase = $useCamelCase;
    }

    /**
     * Borrowed heavily from {@see DrSlump\Protobuf\Codec\PhpArray::encodeMessage()}.
     * With this approach we are able to transform the response with minimal
     * overhead.
     */
    protected function encodeMessage(Protobuf\Message $message)
    {
        $descriptor = Protobuf::getRegistry()->getDescriptor($message);
        $data = [];

        foreach ($descriptor->getFields() as $tag => $field) {
            $empty = !$message->_has($tag);
            if ($field->isRequired() && $empty) {
                throw new \UnexpectedValueException(
                    sprintf(
                        'Message %s\'s field tag %s(%s) is required but has no value',
                        get_class($message),
                        $tag,
                        $field->getName()
                    )
                );
            }

            if ($empty) {
                continue;
            }

            $key = $this->useTagNumber ? $field->getNumber() : $field->getName();
            $v = $message->_get($tag);

            if ($field->isRepeated()) {
                // Make sure the value is an array of values
                $v = is_array($v) ? $v : array($v);
                $arr = [];

                foreach ($v as $k => $vv) {
                    // Skip nullified repeated values
                    if (null === $vv) {
                        continue;
                    }

                    $filteredValue = $this->filterValue($vv, $field);

                    if ($this->isKeyValueMessage($vv)) {
                        $arr[key($filteredValue)] = current($filteredValue);
                    } else {
                        $arr[$k] = $filteredValue;
                    }

                    $v = $arr;
                }
            } else {
                $v = $this->filterValue($v, $field);
            }

            $key = ($this->useCamelCase) ? $this->toCamelCase($key) : $key;

            if (isset($this->customFilters[$key])) {
                $v = call_user_func($this->customFilters[$key], $v);
            }

            $data[$key] = $v;
        }

        return $data;
    }

    /**
     * Borrowed heavily from {@see DrSlump\Protobuf\Codec\PhpArray::decodeMessage()}.
     * The only addition here is converting camel case field names to snake case.
     */
    protected function decodeMessage(Protobuf\Message $message, $data)
    {
        // Get message descriptor
        $descriptor = Protobuf::getRegistry()->getDescriptor($message);

        foreach ($data as $key => $v) {
            // Get the field by tag number or name
            $field = $this->useTagNumber
                   ? $descriptor->getField($key)
                   : $descriptor->getFieldByName($this->toSnakeCase($key));

            // Unknown field found
            if (!$field) {
                $unknown = new Protobuf\Codec\PhpArray\Unknown($key, gettype($v), $v);
                $message->addUnknown($unknown);
                continue;
            }

            if ($field->isRepeated()) {
                // Make sure the value is an array of values
                $v = is_array($v) && is_int(key($v)) ? $v : array($v);
                foreach ($v as $k => $vv) {
                    $v[$k] = $this->filterValue($vv, $field);
                }
            } else {
                $v = $this->filterValue($v, $field);
            }

            $message->_set($field->getNumber(), $v);
        }

        return $message;
    }

    protected function filterValue($value, Protobuf\Field $field)
    {
        if (trim($field->getReference(), '\\') === NullValue::class) {
            return null;
        }

        if ($value instanceof Protobuf\Message) {
            if ($this->isKeyValueMessage($value)) {
                $v = $value->getValue();

                return [
                    $value->getKey() => $v instanceof Protobuf\Message
                        ? $this->encodeMessage($v)
                        : $v
                ];
            }

            if ($value instanceof Struct) {
                $vals = [];

                foreach ($value->getFields() as $field) {
                    $val = $this->filterValue(
                        $field->getValue(),
                        $field->descriptor()->getFieldByName('value')
                    );
                    $vals[$field->getKey()] = $val;
                }

                return $vals;
            }

            if ($value instanceof ListValue) {
                $vals = [];

                foreach ($value->getValuesList() as $val) {
                    $fields = $val->descriptor()->getFields();

                    foreach ($fields as $field) {
                        $name = $field->getName();
                        if ($val->$name !== null) {
                            $vals[] = $this->filterValue($val->$name, $field);
                        }
                    }
                }

                return $vals;
            }

            if ($value instanceof Value) {
                $fields = $value->descriptor()->getFields();

                foreach ($fields as $field) {
                    $name = $field->getName();
                    if ($value->$name !== null) {
                        return $this->filterValue($value->$name, $field);
                    }
                }
            }
        }

        return parent::filterValue($value, $field);
    }

    private function toSnakeCase($key)
    {
        return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $key));
    }

    private function toCamelCase($key)
    {
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
    }

    private function isKeyValueMessage($value)
    {
        return property_exists($value, 'key') && property_exists($value, 'value');
    }
}


text:
module HttpProxy; end

require "http_proxy/headers_parser"
require "http_proxy/connection"
require "http_proxy/proxy"
require "http_proxy/version"


text:
<?php
namespace RazorUserTest\Doctrine\ORM;

use RazorUser\Doctrine\ORM\EntityRepository;

use RazorUserTest\Bootstrap;

class EntityRepositoryTest
    extends \PHPUnit_Framework_TestCase
{
    public function testSetGetServiceLocator()
    {
        $serviceManager = Bootstrap::getServiceManager();
        $entityManager = $serviceManager->get('razoruser.doctrine.em');
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $entityRepository = new EntityRepository($entityManager, $classMetadata);
        $entityRepository->setServiceLocator($serviceManager);

        $this->assertSame($serviceManager, $entityRepository->getServiceLocator());
    }
}


text:
require 'formula'

class Mairix < Formula
  desc "Email index and search tool"
  homepage 'http://www.rpcurnow.force9.co.uk/mairix/'
  url 'https://downloads.sourceforge.net/project/mairix/mairix/0.23/mairix-0.23.tar.gz'
  sha1 '1621d60db5fb76453e48b98d12ca86b4a68ea1de'

  head 'https://github.com/rc0/mairix.git'

  def install
    ENV.j1
    system "./configure", "--prefix=#{prefix}", "--mandir=#{man}"
    system "make"
    system "make install"
  end
end


text:
'use strict';

/**
 * @ngdoc function
 * @name vnfAsteriskControllerApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the vnfAsteriskControllerApp
 */

vacApp.controller('AboutCtrl', ['$scope', '$location', '$http', '$routeParams', function($scope,$location,$http,$routeParams) {

    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.foo = "bar!!!";

    console.log("about controller");
}]);