text:
This monorepo contains all sources for SteemWatch 2.0 backend.

## Status

SteemWatch 2.0 is happening right now. Anything is a subject to change,
anything may and everything will change. So in case you want to use a package
from this repository, make sure to lock the revision or just copy the sources out,
with the associated copyright notice as required by Apache License 2.0, obviously.

## Repository Organization

`cmd/` subdirectory contains all executable packages.
The shared packages can be found in `pkg/`.

## Build Process

We are using [dep](https://github.com/golang/dep), so you need to fetch
the dependencies before you can start doing anything meaningful.

Once the dependencies are there, you can `cd` to the executable package
directory of your choice. The package can be build using `go build` or
just by invoking `make`. Running `make docker/build` builds the service
Docker image where it makes sense.

Occasionally there is also `make test` available for running tests.

## License

Apache License 2.0, see the `LICENSE` file.


text:
  <md-whiteframe class="md-whiteframe-2dp md-accent" layout="row" layout-align="center center" style="height:240px;background-color:#64B5F6">

      {{user.name}}
      {{user.username}}
      {{user.bio}}

  </md-whiteframe>

        <md-whiteframe class="md-whiteframe-1dp" style="background-color:#fff;padding:20px;margin-bottom:10px;" layout="column">
            {{repo.name}}
            {{repo.description}}
        </md-whiteframe>

redpajama_set_name: RedPajamaGithub


text:
namespace VulkanCookbook {

  bool SelectQueueFamilyThatSupportsPresentationToGivenSurface( VkPhysicalDevice   physical_device,
                                                                VkSurfaceKHR       presentation_surface,
                                                                uint32_t         & queue_family_index ) {
    std::vector<VkQueueFamilyProperties> queue_families;
    if( !CheckAvailableQueueFamiliesAndTheirProperties( physical_device, queue_families ) ) {
      return false;
    }

    for( uint32_t index = 0; index < static_cast<uint32_t>(queue_families.size()); ++index ) {
      VkBool32 presentation_supported = VK_FALSE;
      VkResult result = vkGetPhysicalDeviceSurfaceSupportKHR( physical_device, index, presentation_surface, &presentation_supported );
      if( (VK_SUCCESS == result) &&
          (VK_TRUE == presentation_supported) ) {
        queue_family_index = index;
        return true;
      }
    }
    return false;
  }

} // namespace VulkanCookbook


text:
<?php

/**
 * Catalog product option factory
 */
namespace Magento\Catalog\Model\Product\Option\Type;

class Factory
{
    /**
     * Object Manager
     *
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * Construct
     *
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
    {
        $this->_objectManager = $objectManager;
    }

    /**
     * Create product option
     *
     * @param string $className
     * @param array $data
     * @return \Magento\Catalog\Model\Product\Option\Type\DefaultType
     * @throws \Magento\Framework\Model\Exception
     */
    public function create($className, array $data = [])
    {
        $option = $this->_objectManager->create($className, $data);

        if (!$option instanceof \Magento\Catalog\Model\Product\Option\Type\DefaultType) {
            throw new \Magento\Framework\Model\Exception(
                $className . ' doesn\'t extends \Magento\Catalog\Model\Product\Option\Type\DefaultType'
            );
        }
        return $option;
    }
}


text:
package org.jongo.marshall.jackson.configuration;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import org.jongo.marshall.jackson.JongoAnnotationIntrospector;

public class AnnotationModifier implements MapperModifier {

    public void modify(ObjectMapper mapper) {
        AnnotationIntrospector jongoIntrospector = new JongoAnnotationIntrospector();
        AnnotationIntrospector defaultIntrospector = mapper.getSerializationConfig().getAnnotationIntrospector();
        AnnotationIntrospector pair = new AnnotationIntrospectorPair(jongoIntrospector, defaultIntrospector);

        mapper.setAnnotationIntrospector(pair);
    }
}


text:
#ifndef NF_HELLO_WORLD_H
#define NF_HELLO_WORLD_H

#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFPluginModule/NFINavigationModule.h"
#include "NFComm/NFNoSqlPlugin/NFRedisClient.h"
#include "NFComm/NFCore/NFPerformance.hpp"

/*
IN THIS PLUGIN:
YOU WILL KNOW HOW TO USE THE "IScriptModule" TO CALL LUA SCRIPT
*/

class NFIHelloWorld7
	: public NFIModule
{

};

class NFHelloWorld7
    : public NFIHelloWorld7
{
public:
    NFHelloWorld7(NFIPluginManager* p)
    {
        m_bIsExecute = true;
        pPluginManager = p;
    }

    virtual bool Init();
    virtual bool AfterInit();

    virtual bool Execute();

    virtual bool BeforeShut();
    virtual bool Shut();

protected:

	bool Test_1();
	bool TestPerformance();

    void TestHash();
    void TestKey();
    void TestList();
    void TestSet();
    void TestSort();
    void TestString();
	void TestPubSub();

protected:
    NFRedisClient mxRedisClient;
};

#endif


text:
require 'rails_helper'

RSpec.describe Api::V1::FacilitiesController, :type => :controller do
	describe "Open Therapist Directory API" do

    it "renders the facilities index as JSON" do
      5.times do
        Facility.create(name1: Faker::Company.name, phone: Faker::PhoneNumber.phone_number, location_state: 'CO', location_zip: Faker::Address.zip, location_city: Faker::Address.city, location_street1: Faker::Address.street_address, services_text1: Faker::Lorem.sentence, services_text2: Faker::Lorem.sentence, services_text3: Faker::Lorem.sentence)
      end

      get :index, format: :json
      expect(response).to be_success
      json = JSON.parse(response.body)
      expect(json['facility'].length).to eq(5)
    end

    # it 'renders a specific facility as JSON' do
    #   get :show, format: :json
    #   expect(response).to be_success
    # end
  end
end


text:
package com.hubspot.singularity.s3.base;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
import java.util.List;

import org.slf4j.Logger;

import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.hubspot.deploy.Artifact;
import com.hubspot.deploy.EmbeddedArtifact;
import com.hubspot.deploy.ExternalArtifact;
import com.hubspot.deploy.RemoteArtifact;
import com.hubspot.deploy.S3Artifact;
import com.hubspot.singularity.runner.base.configuration.SingularityRunnerBaseConfiguration;
import com.hubspot.singularity.runner.base.sentry.SingularityRunnerExceptionNotifier;
import com.hubspot.singularity.runner.base.shared.ProcessFailedException;
import com.hubspot.singularity.runner.base.shared.SimpleProcessManager;
import com.hubspot.singularity.s3.base.config.SingularityS3Configuration;

public class ArtifactManager extends SimpleProcessManager {

  private final Path cacheDirectory;
  private final Logger log;
  private final S3ArtifactDownloader s3ArtifactDownloader;
  private final Optional<String> useCompressProgram;

  public ArtifactManager(SingularityRunnerBaseConfiguration runnerBaseConfiguration, SingularityS3Configuration configuration, Logger log, SingularityRunnerExceptionNotifier exceptionNotifier) {
    super(log);

    this.cacheDirectory = Paths.get(configuration.getArtifactCacheDirectory());
    this.log = log;
    this.s3ArtifactDownloader = new S3ArtifactDownloader(configuration, log, exceptionNotifier);
    this.useCompressProgram = runnerBaseConfiguration.getUseCompressProgram();
  }

  private long getSize(Path path) {
    try {
      return Files.size(path);
    } catch (IOException ioe) {
      throw new RuntimeException(String.format("Couldnt get file size of %s", path), ioe);
    }
  }

  private boolean filesSizeMatches(RemoteArtifact artifact, Path path) {
    return !artifact.getFilesize().isPresent() || (artifact.getFilesize().get() == getSize(path));
  }

  private boolean md5Matches(Artifact artifact, Path path) {
    return !artifact.getMd5sum().isPresent() || artifact.getMd5sum().get().equals(calculateMd5sum(path));
  }

  private void checkFilesize(RemoteArtifact artifact, Path path) {
    if (!filesSizeMatches(artifact, path)) {
      throw new RuntimeException(String.format("Filesize %s (%s) does not match expected (%s)", getSize(path), path, artifact.getFilesize()));
    }
  }

  private void checkMd5(Artifact artifact, Path path) {
    if (!md5Matches(artifact, path)) {
      throw new RuntimeException(String.format("Md5sum %s (%s) does not match expected (%s)", calculateMd5sum(path), path, artifact.getMd5sum().get()));
    }
  }

  private Path createTempPath(String filename) {
    try {
      return Files.createTempFile(cacheDirectory, filename, null);
    } catch (IOException e) {
      throw new RuntimeException(String.format("Couldn't create temporary file for %s", filename), e);
    }
  }

  private void downloadAndCheck(RemoteArtifact artifact, Path downloadTo) {
    if (artifact instanceof ExternalArtifact) {
      downloadExternalArtifact((ExternalArtifact) artifact, downloadTo);
    } else if (artifact instanceof S3Artifact) {
      downloadS3Artifact((S3Artifact) artifact, downloadTo);
    } else {
      throw new IllegalArgumentException("Unknown artifact type: " + artifact.getClass());
    }

    checkFilesize(artifact, downloadTo);
    checkMd5(artifact, downloadTo);
  }

  public void extract(EmbeddedArtifact embeddedArtifact, Path directory) {
    final Path extractTo = directory.resolve(embeddedArtifact.getFilename());

    final Path parent = extractTo.getParent();
    try {
      if (parent != null) {
        Files.createDirectories(parent);
      }
    } catch (IOException e) {
      throw new RuntimeException(String.format("Couldn't extract %s, unable to create directory %s", embeddedArtifact.getName(), parent), e);
    }

    log.info("Extracting {} bytes of {} to {}", embeddedArtifact.getContent().length, embeddedArtifact.getName(), extractTo);

    try (SeekableByteChannel byteChannel = Files.newByteChannel(extractTo, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) {
      byteChannel.write(ByteBuffer.wrap(embeddedArtifact.getContent()));
    } catch (IOException e) {
      throw new RuntimeException(String.format("Couldn't extract %s", embeddedArtifact.getName()), e);
    }

    checkMd5(embeddedArtifact, extractTo);
  }

  private Path downloadAndCache(RemoteArtifact artifact, String filename, String cacheMissMessage) {
    Path tempFilePath = createTempPath(filename);

    downloadAndCheck(artifact, tempFilePath);

    Path cachedPath = getCachedPath(filename);

    try {
      Files.move(tempFilePath, cachedPath, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
      throw new RuntimeException(String.format("Couldn't move %s to cache at %s (Not cached because %s)", tempFilePath, cachedPath, cacheMissMessage), e);
    }

    return cachedPath;
  }

  private Path getCachedPath(String filename) {
    return cacheDirectory.resolve(filename);
  }

  private CacheCheck checkCached(RemoteArtifact artifact, Path cachedPath) {
    if (!Files.exists(cachedPath)) {
      String message = String.format("Cached %s did not exist", cachedPath);
      log.debug(message);
      return new CacheCheck(CacheCheckResult.DOES_NOT_EXIST, message);
    }

    if (!filesSizeMatches(artifact, cachedPath)) {
      String message = String.format("Cached %s (%s) did not match file size %s", cachedPath, getSize(cachedPath), artifact.getFilesize());
      log.debug(message);
      return new CacheCheck(CacheCheckResult.FILE_SIZE_MISMATCH, message);
    }

    if (!md5Matches(artifact, cachedPath)) {
      String message = String.format("Cached %s (%s) did not match md5 %s", cachedPath, calculateMd5sum(cachedPath), artifact.getMd5sum().get());
      log.debug(message);
      return new CacheCheck(CacheCheckResult.MD5_MISMATCH, message);
    }

    return new CacheCheck(CacheCheckResult.FOUND, "");
  }

  public Path fetch(RemoteArtifact artifact) {
    String filename = artifact.getFilenameForCache();
    Path cachedPath = getCachedPath(filename);

    CacheCheck cacheCheck = checkCached(artifact, cachedPath);

    if (cacheCheck.getCacheCheckResult() != CacheCheckResult.FOUND) {
      log.info(cacheCheck.getMessage());
      downloadAndCache(artifact, filename, cacheCheck.getMessage());
    } else {
      log.info("Using cached file {}", cachedPath);
    }

    return cachedPath;
  }

  private void downloadExternalArtifact(ExternalArtifact externalArtifact, Path downloadTo) {
    downloadUri(externalArtifact.getUrl(), downloadTo);
  }

  private void downloadS3Artifact(S3Artifact s3Artifact, Path downloadTo) {
    s3ArtifactDownloader.download(s3Artifact, downloadTo);
  }

  private void downloadUri(String uri, Path path) {
    log.info("Downloading {} to {}", uri, path);

    final List<String> command = ImmutableList.of(
        "wget",
        uri,
        "-O",
        path.toString(),
        "-nv",
        "--no-check-certificate");

    runCommandAndThrowRuntimeException(command);
  }

  public void copy(Path source, Path destination, String destinationFilename) {
    log.info("Copying {} to {}", source, destination);

    try {
      Files.createDirectories(destination);
      Files.copy(source, destination.resolve(destinationFilename));
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  public void untar(Path source, Path destination) {
    log.info("Untarring {} to {}", source, destination);

    final ImmutableList.Builder<String> commandBuilder = ImmutableList.<String>builder().add("tar", "-oxf", source.toString(), "-C", destination.toString());

    if (useCompressProgram.isPresent()) {
      commandBuilder.add("--use-compress-program=" + useCompressProgram.get());
    } else {
      commandBuilder.add("-z");
    }

    runCommandAndThrowRuntimeException(commandBuilder.build());
  }

  private void runCommandAndThrowRuntimeException(List<String> command) {
    try {
      super.runCommand(command);
    } catch (InterruptedException | ProcessFailedException e) {
      throw Throwables.propagate(e);
    }
  }

  private String calculateMd5sum(Path path) {
    try {
      HashCode hc = com.google.common.io.Files.hash(path.toFile(), Hashing.md5());

      return hc.toString();
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }
}


text:
#include <stdio.h>
#include <string.h>
#include "procs.h"
#if !defined(_WIN32)
#include <unistd.h>
#endif

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

#if defined(_WIN32)
const std::string slash = "\\";
#else
const std::string slash = "/";
#endif

const std::string spvExt = ".spv";
std::string gAddrWidth = "";
std::string spvBinariesPath = "spirv_bin";
std::string spvBinariesPathArg = "--spirv-binaries-path";

std::vector<unsigned char> readBinary(const char *file_name)
{
    using namespace std;

    ifstream file(file_name, ios::in | ios::binary | ios::ate);

    std::vector<char> tmpBuffer(0);

    if (file.is_open()) {
        size_t size = file.tellg();
        tmpBuffer.resize(size);
        file.seekg(0, ios::beg);
        file.read(&tmpBuffer[0], size);
        file.close();
    } else {
        log_error("File %s not found\n", file_name);
    }

    std::vector<unsigned char> result(tmpBuffer.begin(), tmpBuffer.end());

    return result;
}

std::vector<unsigned char> readSPIRV(const char *file_name)
{
    std::string full_name_str = spvBinariesPath + slash + file_name + spvExt + gAddrWidth;
    return readBinary(full_name_str.c_str());
}

test_definition *spirvTestsRegistry::getTestDefinitions()
{
    return &testDefinitions[0];
}

size_t spirvTestsRegistry::getNumTests()
{
    return testDefinitions.size();
}

void spirvTestsRegistry::addTestClass(baseTestClass *test, const char *testName,
                                      Version version)
{

    testClasses.push_back(test);
    test_definition testDef;
    testDef.func = test->getFunction();
    testDef.name = testName;
    testDef.min_version = version;
    testDefinitions.push_back(testDef);
}

spirvTestsRegistry& spirvTestsRegistry::getInstance()
{
    static spirvTestsRegistry instance;
    return instance;
}

static int offline_get_program_with_il(clProgramWrapper &prog,
                                       const cl_device_id deviceID,
                                       const cl_context context,
                                       const char *prog_name)
{
    cl_int err = 0;
    std::string outputTypeStr = "binary";
    std::string defaultScript = std::string("..") + slash + std::string("spv_to_binary.py");
    std::string outputFilename = spvBinariesPath + slash + std::string(prog_name);
    std::string sourceFilename = outputFilename +  spvExt;

    std::string scriptArgs =
        sourceFilename + " " +
        outputFilename + " " +
        gAddrWidth + " " +
        outputTypeStr + " " +
        "-cl-std=CL2.0";

    std::string scriptToRunString = defaultScript + scriptArgs;

    // execute script
    log_info("Executing command: %s\n", scriptToRunString.c_str());
    fflush(stdout);
    int returnCode = system(scriptToRunString.c_str());
    if (returnCode != 0) {
        log_error("Command finished with error: 0x%x\n", returnCode);
        return CL_COMPILE_PROGRAM_FAILURE;
    }

    // read output file
    std::vector<unsigned char> buffer_vec = readBinary(outputFilename.c_str());
    size_t file_bytes = buffer_vec.size();
    if (file_bytes == 0) {
        log_error("OfflinerCompiler: Failed to open binary file: %s", outputFilename.c_str());
        return -1;
    }

    const unsigned char *buffer = &buffer_vec[0];
    cl_int status = 0;
    prog = clCreateProgramWithBinary(context, 1, &deviceID, &file_bytes, &buffer, &status, &err);
    SPIRV_CHECK_ERROR((err || status), "Failed to create program with clCreateProgramWithBinary");
    return err;
}

int get_program_with_il(clProgramWrapper &prog, const cl_device_id deviceID,
                        const cl_context context, const char *prog_name,
                        spec_const spec_const_def)
{
    cl_int err = 0;
    if (gCompilationMode == kBinary)
    {
        return offline_get_program_with_il(prog, deviceID, context, prog_name);
    }

    std::vector<unsigned char> buffer_vec = readSPIRV(prog_name);

    int file_bytes = buffer_vec.size();
    if (file_bytes == 0)
    {
        log_error("File %s not found\n", prog_name);
        return -1;
    }

    unsigned char *buffer = &buffer_vec[0];
    if (gCoreILProgram)
    {
        prog = clCreateProgramWithIL(context, buffer, file_bytes, &err);
        SPIRV_CHECK_ERROR(
            err, "Failed to create program with clCreateProgramWithIL");

        if (spec_const_def.spec_value != NULL)
        {
            err = clSetProgramSpecializationConstant(
                prog, spec_const_def.spec_id, spec_const_def.spec_size,
                spec_const_def.spec_value);
            SPIRV_CHECK_ERROR(
                err, "Failed to run clSetProgramSpecializationConstant");
        }
    }
    else
    {
        cl_platform_id platform;
        err = clGetDeviceInfo(deviceID, CL_DEVICE_PLATFORM,
                              sizeof(cl_platform_id), &platform, NULL);
        SPIRV_CHECK_ERROR(err,
                          "Failed to get platform info with clGetDeviceInfo");
        clCreateProgramWithILKHR_fn clCreateProgramWithILKHR = NULL;

        clCreateProgramWithILKHR = (clCreateProgramWithILKHR_fn)
            clGetExtensionFunctionAddressForPlatform(
                platform, "clCreateProgramWithILKHR");
        if (clCreateProgramWithILKHR == NULL)
        {
            log_error(
                "ERROR: clGetExtensionFunctionAddressForPlatform failed\n");
            return -1;
        }
        prog = clCreateProgramWithILKHR(context, buffer, file_bytes, &err);
        SPIRV_CHECK_ERROR(
            err, "Failed to create program with clCreateProgramWithILKHR");
    }

    err = clBuildProgram(prog, 1, &deviceID, NULL, NULL, NULL);
    SPIRV_CHECK_ERROR(err, "Failed to build program");

    return err;
}

test_status InitCL(cl_device_id id)
{
    test_status spirv_status;
    spirv_status = check_spirv_compilation_readiness(id);
    if (spirv_status != TEST_PASS)
    {
        return spirv_status;
    }

    cl_uint address_bits;
    cl_uint err = clGetDeviceInfo(id, CL_DEVICE_ADDRESS_BITS, sizeof(cl_uint),
                                  &address_bits, NULL);
    if (err != CL_SUCCESS)
    {
        log_error("clGetDeviceInfo failed to get address bits!");
        return TEST_FAIL;
    }

    gAddrWidth = address_bits == 32 ? "32" : "64";
    return TEST_PASS;
}

void printUsage() {
    log_info("Reading SPIR-V files from default '%s' path.\n", spvBinariesPath.c_str());
    log_info("In case you want to set other directory use '%s' argument.\n", spvBinariesPathArg.c_str());
}

int main(int argc, const char *argv[])
{
    gReSeed = 1;
    bool modifiedSpvBinariesPath = false;
    for (int i = 0; i < argc; ++i) {
        int argsRemoveNum = 0;
        if (argv[i] == spvBinariesPathArg) {
            if (i + 1 == argc) {
                log_error("Missing value for '%s' argument.\n", spvBinariesPathArg.c_str());
                return TEST_FAIL;
            } else {
                spvBinariesPath = std::string(argv[i + 1]);
                argsRemoveNum += 2;
                modifiedSpvBinariesPath = true;
            }
        }

        if (argsRemoveNum > 0) {
            for (int j = i; j < (argc - argsRemoveNum); ++j)
                argv[j] = argv[j + argsRemoveNum];

            argc -= argsRemoveNum;
            --i;
        }
    }
    if (modifiedSpvBinariesPath == false) {
       printUsage();
    }

    return runTestHarnessWithCheck(
        argc, argv, spirvTestsRegistry::getInstance().getNumTests(),
        spirvTestsRegistry::getInstance().getTestDefinitions(), false, 0,
        InitCL);
}


text:
<?php

/**
 * A service registry holds the services together.
 *
 * @package sfSearch
 * @subpackage Service
 * @author Carl Vondrick
 */
final class xfServiceRegistry
{
  /**
   * The registered services.
   *
   * @var array
   */
  private $services = array();

  /**
   * Registers a new service.
   *
   * @param xfService $service The service
   */
  public function register(xfService $service)
  {
    $this->services[$service->getIdentifier()->getName()] = $service;
  }

  /**
   * Gets a service from name.
   *
   * @param string $name The name
   * @returns xfService
   */
  public function getService($name)
  {
    if (!isset($this->services[$name]))
    {
      throw new xfServiceNotFoundException('Unable to find service with name ' . $name);
    }

    return $this->services[$name];
  }

  /**
   * Gets all the services.
   *
   * @returns array
   */
  public function getServices()
  {
    return $this->services;
  }

  /**
   * Locates a service from input.
   *
   * @param mixed $input
   * @returns xfService
   * @throws xfServiceNotFoundException if service is not found
   */
  public function locate($input)
  {
    $ignored = null;

    foreach ($this->services as $service)
    {
      switch($service->getIdentifier()->match($input))
      {
        case xfIdentifier::MATCH_YES:
          return $service;
        case xfIdentifier::MATCH_IGNORED;
          $ignored = $service;
          break;
        default:
      }
    }

    if ($ignored == null)
    {
      throw new xfServiceNotFoundException('Unable to find service from input');
    }
    else
    {
      throw new xfServiceIgnoredException($ignored);
    }
  }
}


text:
from flask import Blueprint, render_template

article_bp = Blueprint('views_article', __name__, template_folder='templates')

@article_bp.route('/article/writer/')
def index():
    return render_template('article/post_article.html')


text:
0.1.3 / 2014-04-03
==================

  * package: old npm compatible semver

0.1.2 / 2014-04-03
==================

  * package: loosen semver required versions
  * data: just always use the "readable-stream" module

0.1.1 / 2014-02-05
==================

  * http: initial shot at "cached redirects" logic
  * package: pin "ftpd" version to v0.2.4 (for tests)
  * test: refactor tests into their own files
  * file: remove unused `path` require
  * test: fix "file:" URI tests on Windows
  * file: add better Windows support for file:// URIs
  * http: add the Cache-Control and Expires respecting logic
  * http: clean up logic a bit

0.1.0 / 2014-01-12
==================

  * test: add initial "http:" protocol tests
  * package: add "st" as a dev dependency
  * http: don't pass the `res` when there's a response error
  * test: add initial "https:" protocol tests
  * http: initial 304 Not Modified support
  * index: use debug()
  * http: add support for 3xx redirect response codes
  * http, https: initial "http:" and "https:" implementation
  * ftp: fix debug() call
  * package: update "description"
  * test: remove PASV port range from FTP server
  * test: add more "ftp:" protocol tests
  * test: add more "data:" protocol tests
  * test: more "file:" protocol tests
  * test: set `logLevel` to -1 on the FTP server
  * file: close the `fd` upon an error before creating the ReadStream
  * data: use "readable-stream" for node v0.8.x support
  * ftp: add debug() call for the entry logging
  * test: use "ftpd" for the "ftp:" protocol test
  * file: refactor for optimizations and to do proper NotModifiedErrors
  * add .travis.yml file
  * file: decodeURIComponent() on the pathname before normalizing
  * file: beginnings of refactor
  * file: initial async "file:" protocol
  * ftp: tweak comment
  * http, https: prep
  * test: add initial "file:" protocol test
  * data: fix debug() function name
  * notfound: fix jsdoc description
  * data: add NotModifierError() handling logic
  * ftp: handle the "file not found" scenario
  * notfound: add NotFoundError class
  * ftp: better ftp impl, not with NotModified support
  * notmodified: add NotModifiedError() class
  * ftp: fix `onfile()` error handling
  * file: beginnings of "file:" protocol impl
  * test: add initial "ftp" test
  * test: use "stream-to-array" for tests
  * ftp: comment out console.error() call
  * ftp: update to the async interface
  * package: update "data-uri-to-buffer" to v0.0.3
  * test: add initial tests
  * turn into an async interface
  * Add Readme.md
  * initial commit


text:
package jsjf;

/**
 * Defines the interface to a stack collection.
 *
 * @author Java Foundations
 * @version 4.0
 */
public interface StackADT<T>
{
	/**
	 * Returns true if this stack contains no elements.
	 *
	 * @return true if the stack is empty
	 */
	public boolean isEmpty();

	/**
	 * Returns without removing the top element of this stack.
	 *
	 * @return the element on top of the stack
	 */
	public T peek();

	/**
	 * Removes and returns the top element from this stack.
	 *
	 * @return the element removed from the stack
	 */
	public T pop();

	/**
	 * Adds the specified element to the top of this stack.
	 *
	 * @param element
	 *            element to be pushed onto the stack
	 */
	public void push(T element);

	/**
	 * Returns the number of elements in this stack.
	 *
	 * @return the number of elements in the stack
	 */
	public int size();

	/**
	 * Returns a string representation of this stack.
	 *
	 * @return a string representation of the stack
	 */
	@Override
	public String toString();
}


text:
<?php
/**
 * Per-process memory cache for storing items.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Cache
 */
use Wikimedia\Assert\Assert;

/**
 * Handles per process caching of items
 * @ingroup Cache
 */
class ProcessCacheLRU {
	/** @var Array */
	protected $cache = []; // (key => prop => value)

	/** @var Array */
	protected $cacheTimes = []; // (key => prop => UNIX timestamp)

	protected $maxCacheKeys; // integer; max entries

	/**
	 * @param int $maxKeys Maximum number of entries allowed (min 1).
	 * @throws UnexpectedValueException When $maxCacheKeys is not an int or =< 0.
	 */
	public function __construct( $maxKeys ) {
		$this->resize( $maxKeys );
	}

	/**
	 * Set a property field for a cache entry.
	 * This will prune the cache if it gets too large based on LRU.
	 * If the item is already set, it will be pushed to the top of the cache.
	 *
	 * @param string $key
	 * @param string $prop
	 * @param mixed $value
	 * @return void
	 */
	public function set( $key, $prop, $value ) {
		if ( isset( $this->cache[$key] ) ) {
			$this->ping( $key );
		} elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
			reset( $this->cache );
			$evictKey = key( $this->cache );
			unset( $this->cache[$evictKey] );
			unset( $this->cacheTimes[$evictKey] );
		}
		$this->cache[$key][$prop] = $value;
		$this->cacheTimes[$key][$prop] = microtime( true );
	}

	/**
	 * Check if a property field exists for a cache entry.
	 *
	 * @param string $key
	 * @param string $prop
	 * @param float $maxAge Ignore items older than this many seconds (since 1.21)
	 * @return bool
	 */
	public function has( $key, $prop, $maxAge = 0.0 ) {
		if ( isset( $this->cache[$key][$prop] ) ) {
			return ( $maxAge <= 0 ||
				( microtime( true ) - $this->cacheTimes[$key][$prop] ) <= $maxAge
			);
		}

		return false;
	}

	/**
	 * Get a property field for a cache entry.
	 * This returns null if the property is not set.
	 * If the item is already set, it will be pushed to the top of the cache.
	 *
	 * @param string $key
	 * @param string $prop
	 * @return mixed
	 */
	public function get( $key, $prop ) {
		if ( !isset( $this->cache[$key][$prop] ) ) {
			return null;
		}
		$this->ping( $key );
		return $this->cache[$key][$prop];
	}

	/**
	 * Clear one or several cache entries, or all cache entries.
	 *
	 * @param string|array $keys
	 * @return void
	 */
	public function clear( $keys = null ) {
		if ( $keys === null ) {
			$this->cache = [];
			$this->cacheTimes = [];
		} else {
			foreach ( (array)$keys as $key ) {
				unset( $this->cache[$key] );
				unset( $this->cacheTimes[$key] );
			}
		}
	}

	/**
	 * Resize the maximum number of cache entries, removing older entries as needed
	 *
	 * @param int $maxKeys
	 * @return void
	 * @throws UnexpectedValueException
	 */
	public function resize( $maxKeys ) {
		Assert::parameterType( 'integer', $maxKeys, '$maxKeys' );
		Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );

		$this->maxCacheKeys = $maxKeys;
		while ( count( $this->cache ) > $this->maxCacheKeys ) {
			reset( $this->cache );
			$evictKey = key( $this->cache );
			unset( $this->cache[$evictKey] );
			unset( $this->cacheTimes[$evictKey] );
		}
	}

	/**
	 * Push an entry to the top of the cache
	 *
	 * @param string $key
	 */
	protected function ping( $key ) {
		$item = $this->cache[$key];
		unset( $this->cache[$key] );
		$this->cache[$key] = $item;
	}
}


text:
<?php echo $user_profile->first_name.' '.$user_profile->last_name; ?>'s Recent Ads

				<?php  if($user_posts==null){echo "
You have no ads yet!
";} $i=1; foreach($user_posts as $posts){ ?>

								<?php if(@$user_profile->profile_pic!=''){ ?>
								<img src="<?php echo  base_url().'assets/images/'.$user_profile->username.'/adds/'.$user_profile->profile_pic; ?>" style="padding:5px 5px 0 0;" class="img-responsive" alt="...">
								<?php } else{ ?>
								<img src="<?php echo base_url();  ?>assets/images/user.jpg"  class="img-responsive" alt="...">
								<?php } ?>

								<?php echo $user_profile->first_name.' '.$user_profile->last_name;?> / <?php echo $post_detail =	character_limiter(strip_tags($posts->post_excerpt),50); ?><?php if(count($post_detail)  >=50){?>... <?php } ?>
								<a href="<?php echo base_url().'post/detail/'.$posts->ID.'/'.$user_profile->ID; ?>" class="more">
								   <img src="<?php echo base_url(); ?>assets/images/adds/arrow.png" class="" alt="arrow"/>

								   <?php echo $user_profile->city.' '.$user_profile->state; ?>

<?php if (($i++ % 3) == 0){ echo '

'; }}?>

		<?php if($most_view_user_posts==NULL){echo "";} else {foreach($most_view_user_posts as $row){ ?>

			<?php if(@$user_profile->profile_pic!=''){ ?>
								<img src="<?php echo  base_url().'assets/images/'.$user_profile->username.'/services/'.$user_profile->profile_pic; ?>" style=" width:100%; height:191px;" class="img-responsive" alt="">
								<?php } else{ ?>
								<img src="<?php echo base_url();  ?>assets/images/user.jpg"  class="img-responsive" alt="...">
								<?php } ?>

						<a href="<?php echo base_url().'post/detail/'.$row->ID.'/'.$user_profile->ID; ?>" class="adds-name">  <?php echo $post_detail =	character_limiter(strip_tags($row->post_title),10); ?>
						<?php echo $post_detail =	character_limiter(strip_tags($row->post_excerpt),50); ?><?php if(count($post_detail)  >=50){?>... <?php } ?>             <a href="<?php echo base_url().'post/detail/'.$row->ID.'/'.$user_profile->ID; ?>">
						<img src="<?php echo base_url(); ?>assets/images/adds/arrow.png" class="" alt="arrow">

						 <?php echo $user_profile->city.' '.$user_profile->state; ?>

<?php }} ?>

Similar Models

						<?php  if($similar_models==null){echo "
No Similar Model Found !
";} $i=1;foreach($similar_models as $rows){?>

									<a href="<?php echo base_url(); ?>
									user/user_detail/<?php echo $rows->ID;?>"> <?php if($rows->profile_pic==''){ ?>
									<img src="<?php echo base_url();  ?>assets/images/user.jpg"  class="img-responsive" alt="...">
									<?php }else{ ?>
									<img class="img-responsive img-circle" src="<?php echo  base_url().'assets/images/'.$rows->username.'/adds/'.$rows->profile_pic; ?>" title="" alt="" /><?php } ?>

										 <a href="<?php echo base_url(); ?>user/user_detail/<?php echo $rows->ID;?>"><?php echo $rows->first_name.' '.$rows->last_name; ?>

										 (<?php echo $rows->age; ?>y)

                                                <?php echo $rows->likes; ?>

                                             <?php echo $rows->follows; ?>

										<?php echo $limited_word =character_limiter(strip_tags($rows->introduction),25); ?>
										<a href="<?php echo base_url(); ?>user/user_detail/<?php echo $rows->ID;?>" class="more">
								   <img src="<?php echo base_url(); ?>assets/images/adds/arrow.png" class="" alt="arrow">

                                             <?php echo $rows->city.' '.$rows->state; ?>

<?php if (($i++ % 4) == 0){ echo '

'; }?><?php } ?>


text:
search:
   keywords: ['server management', 'administration']
---

# Manage a remote Server instance

## Introduction

A remote server can be managed via API using the OServerAdmin class. Create it using the URL of the remote server as first parameter of the constructor.

```java
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost:2480");
```

You can also use the URL of the remote database:
```java
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost:2480/GratefulDeadConcerts");
```

## Connect to a remote server

```java
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost:2480").connect("admin", "admin");
```

User and password are not the database accounts but the server users configured in `orientdb-server-config.xml` file.

When finished call the OServerAdmin.close() method to release the network connection.

## Create a database

To create a new database in a remote server you can use the console's [create database](../console/Console-Command-Create-Database.md) command  or via API using the OServerAdmin.createDatabase() method.
```java
// ANY VERSION: CREATE A SERVER ADMIN CLIENT AGAINST A REMOTE SERVER
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin", "admin");
serverAdmin.createDatabase("graph", "local");
```

```java
// VERSION >= 1.4: CREATE A SERVER ADMIN CLIENT AGAINST A REMOTE SERVER
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost").connect("admin", "admin");
serverAdmin.createDatabase("GratefulDeadConcerts", "graph", "local");
```

The iStorageMode can be memory or [plocal](https://github.com/orientechnologies/orientdb/wiki/plocal-storage-engine).

## Drop a database

To drop a database from a server you can use the console's  [drop database](../console/Console-Command-Drop-Database.md) command or via API using the OServerAdmin.dropDatabase() method.
```java
// CREATE A SERVER ADMIN CLIENT AGAINST A REMOTE SERVER
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin", "admin");
serverAdmin.dropDatabase("GratefulDeadConcerts");
```

## Check if a database exists

To check if a database exists in a server via API use the OServerAdmin.existsDatabase() method.
```java
// CREATE A SERVER ADMIN CLIENT AGAINST A REMOTE SERVER
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin", "admin");
serverAdmin.existsDatabase("local");
```


text:
import React, { useEffect, ReactElement } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';

import { mathJaxScriptLoader } from '../../../utils/script-loaders';
import { challengeTestsSelector } from '../redux';
import TestSuite from './Test-Suite';
import ToolPanel from './Tool-Panel';

import './side-panel.css';

const mapStateToProps = createSelector(
  challengeTestsSelector,
  (tests: Record<string, unknown>[]) => ({
    tests
  })
);
interface SidePanelProps {
  block: string;
  challengeDescription: ReactElement;
  challengeTitle: ReactElement;
  guideUrl?: string;
  instructionsPanelRef: React.RefObject<HTMLDivElement>;
  showToolPanel: boolean;
  tests?: Record<string, unknown>[];
  videoUrl?: string;
}

export function SidePanel({
  block,
  challengeDescription,
  challengeTitle,
  guideUrl,
  instructionsPanelRef,
  showToolPanel = false,
  tests,
  videoUrl
}: SidePanelProps): JSX.Element {
  useEffect(() => {
    const MathJax = global.MathJax;
    const mathJaxMountPoint = document.querySelector('#mathjax');
    const mathJaxChallenge =
      block === 'rosetta-code' || block === 'project-euler';
    if (MathJax) {
      // Configure MathJax when it's loaded and
      // users navigate from another challenge
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [
            ['$', '$'],
            ['\\(', '\\)']
          ],
          processEscapes: true,
          processClass: 'rosetta-code|project-euler'
        }
      });
      MathJax.Hub.Queue([
        'Typeset',
        MathJax.Hub,
        document.querySelector('.rosetta-code'),
        document.querySelector('.project-euler')
      ]);
    } else if (!mathJaxMountPoint && mathJaxChallenge) {
      mathJaxScriptLoader();
    }
  }, [block]);

  return (
    <div
      className='instructions-panel'
      ref={instructionsPanelRef}
      role='complementary'
      tabIndex={-1}
    >
      {challengeTitle}
      {challengeDescription}
      {/* @ts-expect-error ToolPanel's redux props are being inferred here, but we don't need to provide them here */}
      {showToolPanel && <ToolPanel guideUrl={guideUrl} videoUrl={videoUrl} />}
      <TestSuite tests={tests} />
    </div>
  );
}

SidePanel.displayName = 'SidePanel';

export default connect(mapStateToProps)(SidePanel);


text:
var bindable = require(".."),
expect       = require("expect.js");

describe("object-basic#", function () {

  it("can create a bindable object", function () {
    new bindable.Object();
  });

  it("can call get() with one property", function () {
    var obj = new bindable.Object({ name: "jeff" });
    expect(obj.get("name")).to.be("jeff");
  });

  it("can call get() with a string property expect.jsn", function () {
    var obj = new bindable.Object({ city: { zip: 99999 }, a: { b: { c: { d: 5}}} });
    expect(obj.get("city.zip")).to.be(99999);
    expect(obj.get("a.b.c.d")).to.be(5);
  });

  it("returns undefined if a property doesn't exist", function () {
    expect(new bindable.Object().get("name")).to.be(undefined);
  });

  it("doesn't create an object if a property doesn't exist", function () {
    var obj = new bindable.Object();
    expect(obj.get("a.b.c.d")).to.be(undefined);
    expect(obj.get("a")).to.be(undefined);
  })

  it("can call get() with an array as the property", function () {
    var obj = new bindable.Object({ city: { zip: 99999 } });
    expect(obj.get(["city", "zip"])).to.be(99999);
  });

  it("can check if a property exists", function () {
    var obj = new bindable.Object({
      a: true,
      b: 0,
      c: "true"
    });
    expect(obj.has("a")).to.be(true);
    expect(obj.has("b")).to.be(true);
    expect(obj.has("c")).to.be(true);
  });

  it("returns the friend object", function () {
    var friend = new bindable.Object();
    var obj = new bindable.Object({
      friend: friend
    });

    expect(obj.get("friend")).to.be(friend);
    expect(obj.get(["friend"])).to.be(friend);
  });

  it("properly jsonifys a bindable object", function () {
    var obj = new bindable.Object({
      name: "craig",
      friend: new bindable.Object({
        name: "tim"
      })
    });
    var json = obj.toJSON();
    expect(json.name).to.be("craig");
    expect(json.friend.name).to.be("tim");
  });

  it("properly get()s when a property is a bindable object", function () {
    var obj = new bindable.Object({
      friend: new bindable.Object({
        name: "jake",
        friend: new bindable.Object({
          name: "jeff"
        })
      })
    });
    expect(obj.get("friend.name")).to.be("jake");
    expect(obj.get("friend.friend.name")).to.be("jeff");
  });

  it("can call set() with one property", function () {
    var obj = new bindable.Object();
    obj.set("name", "craig");
    expect(obj.get("name")).to.be("craig");
  });

  it("returns the same value on set() even if it hasn't changed", function () {
    var obj = new bindable.Object({ name: "craig" });
    expect(obj.set("name", "craig"));
    expect(obj.get("name")).to.be("craig");
  })

  it("can set multiple properties", function () {
    var obj = new bindable.Object();
    obj.setProperties({ name: "craig", age: 99 });
    expect(obj.get("name")).to.be("craig");
    expect(obj.get("age")).to.be(99);
  })

  it("can call set() with a string property expect.jsn", function () {
    var obj = new bindable.Object();
    obj.set("city.zip", 99999);
    obj.set("a.b.c.d.e", 33333);
    expect(typeof obj.get("city")).to.be("object");
    expect(obj.get("city.zip")).to.be(99999);
    expect(obj.get("a.b.c.d.e")).to.be(33333);
  });

  it("can set a value to undefined", function () {
    var obj = new bindable.Object({ a: { b: "blah" }});
    obj.set("a.b", undefined);
    expect(obj.get("a.b")).to.be(undefined);
  })

  it("can call set() with an array property", function () {
    var obj = new bindable.Object();
    obj.set(["a", "b", "c", "d", "e"], 99999);
    expect(typeof obj.get("a")).to.be("object");
    expect(obj.get("a.b.c.d.e")).to.be(99999);
  });

  it("returns the value that was assigned", function () {
    var obj = new bindable.Object();
    expect(obj.set("a.b.c.d", 99999)).to.be(99999);
    expect(obj.set("a.b.c.d", 55555)).to.be(55555);
    expect(obj.get("a.b.c.d")).to.be(55555);
  })

  it("properly set()s when a property is a bindable object", function () {
    var friend1 = new bindable.Object();
    var friend2 = new bindable.Object({ friend: friend1 });
    var obj = new bindable.Object({ friend: friend2 });
    obj.set("friend.name", "jake");
    obj.set("friend.friend.name", "jeff");
    expect(obj.get("friend.name")).to.be("jake");
    expect(obj.get("friend.friend.name")).to.be("jeff");
  });

  it("emits a change event when a property changes", function (next) {
    var obj = new bindable.Object();
    obj.once("change", function (key, value) {
      expect(key).to.be("name");
      expect(value).to.be("liam");
      next();
    });
    obj.set("name", "liam");
  });

  it("emits a change:name event when a property changes", function (next) {
    var obj = new bindable.Object({ name: "craig" });
    obj.once("change:name", function (value, oldValue) {
      expect(value).to.be("liam");
      expect(oldValue).to.be("craig");
      next();
    });
    obj.set("name", "liam");
  });

  it("doesn't emit a change event when a property changes", function () {
    var obj = new bindable.Object({ name: "liam" }), emitted;
    obj.once("change", function (key, value) {
      expect(key).to.be("name");
      expect(value).to.be("liam");
      next();
    });
    obj.set("name", "liam");
    expect(emitted).to.be(undefined);
  });

  it("emits a change event on a sub model, and itself if the property changes", function () {
    var friend = new bindable.Object({ name: "jake" }),
    obj = new bindable.Object({ friend: friend }),
    emittedFriend, emittedObj;
    friend.on("change:name", function (value) {
      emittedFriend = value;
    });
    obj.on("change:friend.name", function (value) {
      emittedObj = value;
    });

    obj.set("friend.name", "blake");
    expect(emittedFriend).to.be("blake");
    expect(emittedObj).to.be("blake");
  });

  it("emits dispose after calling dispose()", function () {
    var obj = new bindable.Object(), disposed;
    obj.once("dispose", function () {
      disposed = true;
    });
    obj.dispose();
    expect(disposed).to.be(true);
  });

  it("does not return the context of a value that is a bindable object if watched", function () {
    var friend;
    var obj = new bindable.Object({ a: {friend: friend = new bindable.Object() } });
    obj.bind("a.friend", function (friend2) {
      expect(friend2).to.be(friend);
    }).now();
  });

  it("can bind with an array", function () {
    var obj = new bindable.Object({ name: "john" });
    obj.bind(["name"], function (name) {
      expect(name).to.be("john");
    }).now();
  })
});


text:
package org.judal.inmemory.test;

import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;

import java.io.IOException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import org.judal.storage.DataSource;
import org.judal.storage.EngineFactory;

import javax.jdo.JDOException;
import javax.transaction.SystemException;

import org.judal.storage.java.test.AbstractBucketTest;
import org.judal.storage.keyvalue.Stored;
import org.judal.serialization.BytesConverter;

import org.judal.inmemory.InMemoryEngine;
import org.judal.inmemory.InMemoryRecord;
import org.judal.inmemory.InMemoryDataSource;

public class TestInMemoryAsBucket extends AbstractBucketTest {

	private static Map<String,String> properties;
	private static InMemoryDataSource dts;
	private static String defaultBucketName;

	@BeforeClass
	public static void init() throws ClassNotFoundException, JDOException, IOException {
		properties = new TestInMemory().getTestProperties();
		InMemoryEngine ime = new InMemoryEngine();
		EngineFactory.registerEngine(EngineFactory.NAME_INMEMORY, ime.getClass().getName());
		dts = ime.getDataSource(properties);
		defaultBucketName = bucketName;
		bucketName = properties.getOrDefault(DataSource.URI, "judaltest1");
	}

	@AfterClass
	public static void cleanup() throws JDOException {
		if (dts!=null) dts.close();
		bucketName = defaultBucketName;
	}

	@Test
	public void test01Bucket() throws JDOException, IOException, SystemException {
		super.test01Bucket();
	}

	@Override
	public InMemoryDataSource getBucketDataSource() throws JDOException {
		return dts;
	}

	@Override
	public Stored getByteStored1() throws JDOException {
		Stored obj = new TestStoredInMemory(bucketName);
		obj.setKey(pk);
		obj.setValue(new byte[]{1,2,3,4,5,6,7,8,9});
		return obj;
	}

	@Override
	public Stored getObjectStored2() throws JDOException {
		InMemoryRecord obj = new TestStoredInMemory(bucketName);
		obj.setKey(pk);
		HashMap<String,String> map = new HashMap<String,String>();
		map.put("1", "one");
		map.put("2", "two");
		map.put("3", "three");
		obj.put("column1", "value1");
		obj.put("column2", "value2");
		obj.put("column3", "value3");
		obj.setValue(BytesConverter.toBytes(map,Types.JAVA_OBJECT));
		return obj;
	}

	@Override
	public Stored getRetrieved() throws JDOException {
		return new TestStoredInMemory(bucketName);
	}

}


text:
var _ = require('lodash');

module.exports = function(Model, server, config, log) {

    return function(msg) {
        return Model.list({wrap: msg.wrap, params: _.omit(msg, "credentials"), credentials: msg.credentials });
    }
};


text:
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.LinkType.NONE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.packageStartsWith;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodInvocationTree;
import java.util.regex.Pattern;

/** Check for disallowed access to private_do_not_access_or_else proto fields. */
@BugPattern(
    name = "PrivateSecurityContractProtoAccess",
    summary =
        "Access to a private protocol buffer field is forbidden. This protocol buffer carries"
            + " a security contract, and can only be created using an approved library."
            + " Direct access to the fields is forbidden.",

    severity = ERROR,
    linkType = NONE)
public class PrivateSecurityContractProtoAccess extends BugChecker
    implements MethodInvocationTreeMatcher {

  private static final Pattern PRIVATE_DO_NOT_ACCESS_OR_ELSE =
      Pattern.compile(".*PrivateDoNotAccessOrElse.*");

  private static final Matcher<MethodInvocationTree> SAFEHTML_PRIVATE_FIELD_ACCESS =
      allOf(
          anyOf(
              createFieldMatcher("com.google.common.html.types.SafeHtmlProto"),
              createFieldMatcher("com.google.common.html.types.SafeUrlProto"),
              createFieldMatcher("com.google.common.html.types.TrustedResourceUrlProto"),
              createFieldMatcher("com.google.common.html.types.SafeScriptProto"),
              createFieldMatcher("com.google.common.html.types.SafeStyleProto"),
              createFieldMatcher("com.google.common.html.types.SafeStyleSheetProto")),
          not(packageStartsWith("com.google.common.html.types")));

  private static final String MESSAGE = "Forbidden access to a private proto field. See ";
  private static final String SAFEHTML_LINK = "https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md#protocol-buffer-conversion";

  // Matches instance methods with PrivateDoNotAccessOrElse in their names.
  private static Matcher<MethodInvocationTree> createFieldMatcher(String className) {
    String builderName = className + ".Builder";
    return anyOf(
        instanceMethod().onExactClass(className).withNameMatching(PRIVATE_DO_NOT_ACCESS_OR_ELSE),
        instanceMethod().onExactClass(builderName).withNameMatching(PRIVATE_DO_NOT_ACCESS_OR_ELSE));
  }

  private Description buildErrorMessage(MethodInvocationTree tree, String link) {
    Description.Builder description = buildDescription(tree);
    String message = MESSAGE + link + ".";
    description.setMessage(message);
    return description.build();
  }

  @Override
  public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (SAFEHTML_PRIVATE_FIELD_ACCESS.matches(tree, state)) {
      return buildErrorMessage(tree, SAFEHTML_LINK);
    }
    return Description.NO_MATCH;
  }
}


text:
package ca.ljz.winter.security.filters;

import java.io.IOException;
import java.util.logging.Logger;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.interceptor.Interceptor;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import ca.ljz.winter.core.contexts.PropertyObjectFactory;
import ca.ljz.winter.core.contexts.PropertyReader;
import ca.ljz.winter.security.contexts.AuthenticationContext;
import ca.ljz.winter.security.handlers.AuthenticationContextHandler;

/**
 * This filter is used to collect user's credentials. The priority of this
 * filter is default (2000). Other filters should adjust the priority to an
 * appropriate value by using @Priority annotation.
 *
 * @author william
 *
 */
@WebFilter(urlPatterns = "/*")
@Priority(Interceptor.Priority.APPLICATION)
public class AuthenticationContextFilter implements Filter {

	private final static Logger LOGGER = Logger.getLogger(AuthenticationContextFilter.class.getName());

	protected static final String AUTHENTICATION_CONTEXT_HANDLER = "ca.ljz.winter.security.handlers.BasicAuthenticationContextHandler";

	@Inject
	private AuthenticationContext authenticationContext;

	@Inject
	private PropertyObjectFactory<AuthenticationContextHandler> ahpof;

	@Inject
	private PropertyReader properties;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		LOGGER.info(
				"Enter ca.ljz.winter.security.filters.AuthenticationContextFilter.doFilter(ServletRequest, ServletResponse, FilterChain)");

		ahpof.createObjectByPropertyKey("AuthenticationContextHandler", AUTHENTICATION_CONTEXT_HANDLER)
				.setAuthenticationContext(authenticationContext, request, response, properties);
		chain.doFilter(request, response);

		LOGGER.info(
				"Exit ca.ljz.winter.security.filters.AuthenticationContextFilter.doFilter(ServletRequest, ServletResponse, FilterChain)");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		LOGGER.info("ca.ljz.winter.security.filters.AuthenticationFilter.init(FilterConfig)");
	}

	@Override
	public void destroy() {
		LOGGER.info("ca.ljz.winter.security.filters.AuthenticationFilter.destroy()");
	}
}


text:
Find all anagrams of a word or phrase. The anagrams are output one per line.

```
Usage:
	./Anagramatic [-s] [-d DICTIONARY_FILE] PHRASE...

	PHRASE	The word or words of which to find anagrams.

	-d	Specify which dictionary file to use. Default: "dictionary"
	-h	Display this message. In case you forgot something?
	-s	Only find single-word anagrams.
```

## Compiling
Build with `make` or with something like `g++ -std=c++11 -O3 *.cpp -o Anagramatic`.

## Examples
```
$ ./Anagramatic -s mountaineers
mountaineers
enumerations
```

```
$ ./Anagramatic git hub
hit bug
hug bit
hut big
ugh bit
big hut
bit ugh
bit hug
bug hit
```


text:
from openstack.tests.functional import base

class TestMeter(base.BaseFunctionalTest):

    def test_list(self):
        names = set([o.name for o in self.conn.telemetry.meters()])
        self.assertIn('storage.objects', names)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.

-->
<s:scufl xmlns:s="http://org.embl.ebi.escience/xscufl/0.1alpha" version="0.2" log="0">
  <s:workflowdescription lsid="urn:lsid:net.sf.taverna:wfDefinition:c7016fc0-c2f4-4171-b6f1-430f408f4822" author="" title="nested_iteration" />
  <s:processor name="constant" boring="true">
    <s:stringconstant>constant</s:stringconstant>
  </s:processor>
  <s:processor name="generate_list">
    <s:defaults>
      <s:default name="prefix">prefix</s:default>
    </s:defaults>
    <s:beanshell>
      <s:scriptvalue>list = new ArrayList();
for (int i = 0; i < 20; i++) {
 list.add(prefix + i);
}</s:scriptvalue>
      <s:beanshellinputlist>
        <s:beanshellinput s:syntactictype="'text/plain'">prefix</s:beanshellinput>
      </s:beanshellinputlist>
      <s:beanshelloutputlist>
        <s:beanshelloutput s:syntactictype="l('text/plain')">list</s:beanshelloutput>
      </s:beanshelloutputlist>
      <s:dependencies s:classloader="iteration" />
    </s:beanshell>
  </s:processor>
  <s:processor name="merge">
    <s:workflow>
      <s:scufl version="0.2" log="0">
        <s:workflowdescription lsid="urn:lsid:net.sf.taverna:wfDefinition:3368fb8d-ecc7-4fcd-b511-6ace84b13c81" author="" title="Untitled workflow #24" />
        <s:processor name="Nested_Workflow">
          <s:workflow>
            <s:scufl version="0.2" log="0">
              <s:workflowdescription lsid="urn:lsid:net.sf.taverna:wfDefinition:75b99c76-7a76-4d3c-8d39-8c48df3355ad" author="" title="Untitled workflow #36" />
              <s:processor name="concat">
                <s:beanshell>
                  <s:scriptvalue>Thread.sleep(200);
out = in1 + in2;</s:scriptvalue>
                  <s:beanshellinputlist>
                    <s:beanshellinput s:syntactictype="'text/plain'">in1</s:beanshellinput>
                    <s:beanshellinput s:syntactictype="'text/plain'">in2</s:beanshellinput>
                  </s:beanshellinputlist>
                  <s:beanshelloutputlist>
                    <s:beanshelloutput s:syntactictype="'text/plain'">out</s:beanshelloutput>
                  </s:beanshelloutputlist>
                  <s:dependencies s:classloader="iteration" />
                </s:beanshell>
              </s:processor>
              <s:link source="in1" sink="concat:in1" />
              <s:link source="in2" sink="concat:in2" />
              <s:link source="concat:out" sink="out" />
              <s:source name="in1" />
              <s:source name="in2" />
              <s:sink name="out" />
            </s:scufl>
          </s:workflow>
        </s:processor>
        <s:link source="in1" sink="Nested_Workflow:in1" />
        <s:link source="in2" sink="Nested_Workflow:in2" />
        <s:link source="Nested_Workflow:out" sink="out" />
        <s:source name="in1" />
        <s:source name="in2" />
        <s:sink name="out" />
      </s:scufl>
    </s:workflow>
    <s:mergemode input="in2" mode="merge" />
  </s:processor>
  <s:link source="constant:value" sink="constant" />
  <s:link source="constant:value" sink="merge:in1" />
  <s:link source="generate_list:list" sink="list" />
  <s:link source="generate_list:list" sink="merge:in2" />
  <s:link source="generate_list:list" sink="merge:in2" />
  <s:link source="merge:out" sink="concat" />
  <s:source name="input" />
  <s:sink name="concat">
    <s:metadata>
      <s:mimeTypes>
        <s:mimeType>'text/plain'</s:mimeType>
      </s:mimeTypes>
    </s:metadata>
  </s:sink>
  <s:sink name="list">
    <s:metadata>
      <s:mimeTypes>
        <s:mimeType>l('text/plain')</s:mimeType>
      </s:mimeTypes>
    </s:metadata>
  </s:sink>
  <s:sink name="constant">
    <s:metadata>
      <s:mimeTypes>
        <s:mimeType>'text/plain'</s:mimeType>
      </s:mimeTypes>
    </s:metadata>
  </s:sink>
  <s:coordination name="constant_BLOCKON_generate_list">
    <s:condition>
      <s:state>Completed</s:state>
      <s:target>generate_list</s:target>
    </s:condition>
    <s:action>
      <s:target>constant</s:target>
      <s:statechange>
        <s:from>Scheduled</s:from>
        <s:to>Running</s:to>
      </s:statechange>
    </s:action>
  </s:coordination>
  <s:coordination name="merge_BLOCKON_generate_list">
    <s:condition>
      <s:state>Completed</s:state>
      <s:target>generate_list</s:target>
    </s:condition>
    <s:action>
      <s:target>merge</s:target>
      <s:statechange>
        <s:from>Scheduled</s:from>
        <s:to>Running</s:to>
      </s:statechange>
    </s:action>
  </s:coordination>
</s:scufl>


text:
package com.djn.perfect.ssmnormal.common.test.se;

public class Demo1 {
	static int  a =5;
	static { a += 5;
		System.out.println(a);
	}

	public static void main(String[] args) {
		System.out.println(a);
	}
	static { a/= 3;}
}


text:
package org.apache.arrow.flight;

import org.apache.arrow.flight.impl.Flight;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.ReferenceManager;

import com.google.protobuf.ByteString;

/**
 * A message from the server during a DoPut operation.
 *
 *
This object owns an {@link ArrowBuf} and should be closed when you are done with it.
 */
public class PutResult implements AutoCloseable {

  private ArrowBuf applicationMetadata;

  private PutResult(ArrowBuf metadata) {
    applicationMetadata = metadata;
  }

  /**
   * Create a PutResult with application-specific metadata.
   *
   *
This method assumes ownership of the {@link ArrowBuf}.
   */
  public static PutResult metadata(ArrowBuf metadata) {
    if (metadata == null) {
      return empty();
    }
    return new PutResult(metadata);
  }

  /** Create an empty PutResult. */
  public static PutResult empty() {
    return new PutResult(null);
  }

  /**
   * Get the metadata in this message. May be null.
   *
   *
Ownership of the {@link ArrowBuf} is retained by this object. Call {@link ReferenceManager#retain()} to preserve
   * a reference.
   */
  public ArrowBuf getApplicationMetadata() {
    return applicationMetadata;
  }

  Flight.PutResult toProtocol() {
    if (applicationMetadata == null) {
      return Flight.PutResult.getDefaultInstance();
    }
    return Flight.PutResult.newBuilder().setAppMetadata(ByteString.copyFrom(applicationMetadata.nioBuffer())).build();
  }

  /**
   * Construct a PutResult from a Protobuf message.
   *
   * @param allocator The allocator to use for allocating application metadata memory. The result object owns the
   *     allocated buffer, if any.
   * @param message The gRPC/Protobuf message.
   */
  static PutResult fromProtocol(BufferAllocator allocator, Flight.PutResult message) {
    final ArrowBuf buf = allocator.buffer(message.getAppMetadata().size());
    message.getAppMetadata().asReadOnlyByteBufferList().forEach(bb -> {
      buf.setBytes(buf.writerIndex(), bb);
      buf.writerIndex(buf.writerIndex() + bb.limit());
    });
    return new PutResult(buf);
  }

  @Override
  public void close() {
    if (applicationMetadata != null) {
      applicationMetadata.close();
    }
  }
}


text:
//
//  MessageStopScheduled.h
//  SmsVoice
//
//  Created by Nirwan Nursabda on 7/9/15.
//

#import <Foundation/Foundation.h>
#import "ModelResponse.h"

@interface MessageStopScheduled : ModelResponse
@property NSString *Success;

- (instancetype) initWithJSONString:(NSDictionary*)jsonResp;
- (NSString*) toString;
@end


text:
package com.github.randomcodeorg.netmaven.netmaven.compiler;

public class CompilationException extends RuntimeException {

	private static final long serialVersionUID = 1768659311046174931L;

	public CompilationException() {
	}

	public CompilationException(String message) {
		super(message);
	}

	public CompilationException(Throwable cause) {
		super(cause);
	}

	public CompilationException(String message, Throwable cause) {
		super(message, cause);
	}

	public CompilationException(String message, Throwable cause, boolean enableSuppression,
			boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

}


text:
package org.sensorsink.pond.model.account;

import java.util.List;
import org.apache.zest.api.common.Optional;
import org.apache.zest.api.entity.Identity;
import org.apache.zest.api.property.Property;

public interface UserRole extends Identity
{
//    root, operations, devops, developer, account_owner, account_operator, account_viewer, account_invitee, guest;

//    public boolean authorize( List<UserRole> hasRoles )
//    {
//        return hasRoles.stream().anyMatch( role -> role.name().equals( this.name() ) );
//    }

    @Optional
    Property<String> description();
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <link rel="stylesheet" href="style.css" type="text/css"/>
        <title>Work Package</title>

A Work Package represents a series of actions identified and designed to achieve specific results within specified time and resource constraints.

The central behavioural element is a Work Package. A Work Package is a behaviour element that has a clearly defined start and end date, and realizes a well-defined set of Goals or Deliverables. The Work Package element can be used to model sub-projects or tasks within a project, complete projects, programs, or project portfolios.

Category:

Implementation and Migration

Examples:

"Program to sustain implementation", "Project to secure funding", "Project for CRM system integration"


text:
package de.particity.impexp;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class SchemaVersionHandler extends DefaultHandler {

	private Log m_objLog = LogFactoryUtil.getLog(SchemaVersionHandler.class);

	private String m_strVersion = null;

	@Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

	    if (qName.equals("ImportExportRoot")) {
	    	//m_objLog.info("Found root elem");
	    	if (attributes != null) {
	    		for (int i=0; i<attributes.getLength();i++) {
	    			//m_objLog.info("Found attribute with local "+attributes.getLocalName(i)+", qName "+attributes.getQName(i));
	    			if (attributes.getQName(i).equals("Version")) {
	    				//m_objLog.info("Found attributes!");
	    				m_strVersion = attributes.getValue(i);
	    			}
	    		}
	    	}
	    	// root element has been parsed,
	    	// regardless of the result, stop right here
	    	throw new SchemaVersionEscapeException();
	    }
    }

	public String getVersion() {
		return m_strVersion;
	}

}


text:
from cyclone.web import asynchronous

from sockjs.cyclone.transports import streamingbase

class XhrStreamingTransport(streamingbase.StreamingTransportBase):
    name = 'xhr_streaming'

    @asynchronous
    def post(self, session_id):
        # Handle cookie
        self.preflight()
        self.handle_session_cookie()
        self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
        self.disable_cache()

        # Send prelude and flush any pending messages
        # prelude is needed to workaround an ie8 weirdness:
        # 'http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/'
        #     'comet-streaming-in-internet-explorer-with-xmlhttprequest-'
        #     'and-xdomainrequest.aspx'
        self.write('h' * 2048 + '\n')
        self.flush()

        if not self._attach_session(session_id):
            self.finish()
            return

        if self.session:
            self.session.flush()

    def connectionLost(self, reason):
        self.session.delayed_close()
        self._detach()

    def send_pack(self, message):
        self.write(message + '\n')
        self.flush()

        # Close connection based on amount of data transferred
        if self.should_finish(len(message) + 1):
            self._detach()
            self.safe_finish()


text:
package pe.fu.rbac.resource.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pe.fu.common.utils.JsonUtils;
import pe.fu.rbac.cache.dao.ResourceCacheDao;
import pe.fu.rbac.resource.bean.RbacResource;
import pe.fu.rbac.role.bean.RbacRole;
import pe.fu.rbac.role.service.RoleService;
import pe.fu.rbac.user.bean.RbacUser;
import pe.fu.rbac.user.service.UserService;

/**
 *
资源缓存服务实现类

 *
 * @author Huang Chen Jun Fu (请联系我^_^)
 * @version 1.0
 * @date 2017年5月1日
 * @since 1.7
 */
@Service("resourceCacheService")
public class ResourceCacheServiceImpl implements ResourceCacheService {

    @Autowired
    private ResourceCacheDao resourceCacheDao;
    @Autowired
    private RoleService roleService;

    /**
     * 加载角色的资源列表到缓存
     *
     * @throws Exception
     */
    @Override
    public void loadAllResourceToCache() throws Exception {
        List<RbacRole> roles = roleService.getAll();
        for (RbacRole role : roles) {
            List<RbacResource> ownedResources = roleService.getOwnedResource(role.getId());
            resourceCacheDao.saveResourceList(role.getName(), ownedResources);
        }
    }

    /**
     * 获取资源列表
     * @param rolename 角色名
     * @return
     * @throws Exception
     */
    @Override
    public List<RbacResource> getResourceList(String rolename) throws Exception {
        return resourceCacheDao.getResourceList(rolename);
    }

    /**
     * 获取资源
     *
     * @param rolename   角色名
     * @param resourceId 资源名
     * @return
     * @throws Exception
     */
    @Override
    public RbacResource getResource(String rolename, Long resourceId) throws Exception {
        List<RbacResource> resourceList = getResourceList(rolename);
        for (RbacResource rbacResource : resourceList) {
            if (rbacResource.getId().longValue() == resourceId.longValue()) {
                return rbacResource;
            }
        }
        return null;
    }

    /**
     * 某角色是否拥有某权限
     */
    @Override
    public boolean hasPermission(String rolename, String resourceName) throws Exception {
        boolean result = false;
        List<RbacResource> resourceList = getResourceList(rolename);
        for (RbacResource rbacResource : resourceList) {
            if (resourceName.equals(rbacResource.getName())) {
                result = true;
                break;
            }
        }
        return result;
    }
}


text:
namespace HPHP {

////////MongocClient

////////////////////////////////////////////////////////////////////////////////

Resource get_client_resource(Object obj) {
  auto res = obj->o_realProp(s_mongoc_client, ObjectData::RealPropUnchecked, s_mongoclient);

  if (!res || !res->isResource()) {
    return null_resource;
  }

  return res->toResource();
}

MongocClient *get_client(Object obj) {
  auto res = get_client_resource(obj);

  return res.getTyped<MongocClient>(true, false);
}

MongocClient *MongocClient::GetPersistent(const String& uri) {
  return GetCachedImpl("mongo::persistent_clients", uri);
}

void MongocClient::SetPersistent(const String& uri, MongocClient *client) {
  SetCachedImpl("mongo::persistent_clients", uri, client);
}

MongocClient *MongocClient::GetCachedImpl(const char *name, const String& uri) {
  return dynamic_cast<MongocClient*>(g_persistentResources->get(name, uri.data()));
}

void MongocClient::SetCachedImpl(const char *name, const String& uri, MongocClient *client) {
  g_persistentResources->set(name, uri.data(), client);
}

MongocClient::MongocClient(const String &uri) {
  m_client = mongoc_client_new(uri.c_str());
}

MongocClient::~MongocClient() {
  if (m_client != nullptr) {
    mongoc_client_destroy(m_client);
  }
}

////////MongocCursor

////////////////////////////////////////////////////////////////////////////////

Resource get_cursor_resource(Object obj) {
  auto res = obj->o_realProp(s_mongoc_cursor, ObjectData::RealPropUnchecked, s_mongocursor);

  if (!res || !res->isResource()) {
    return null_resource;
  }

  return res->toResource();
}

MongocCursor *get_cursor(Object obj) {
  auto res = get_cursor_resource(obj);

  return res.getTyped<MongocCursor>(true, false);
}

MongocCursor::MongocCursor(mongoc_client_t           *client,
                const char                *db_and_collection,
                mongoc_query_flags_t       flags,
                uint32_t                   skip,
                uint32_t                   limit,
                uint32_t                   batch_size,
                bool                       is_command,
                const bson_t              *query,
                const bson_t              *fields,
                const mongoc_read_prefs_t *read_prefs) {
  std::string db_name;
  std::string collection_name;

  std::string *db_and_collection_str = new std::string(db_and_collection);

  //namespace format: db.collection
  size_t dot_pos;
  dot_pos = db_and_collection_str->find_first_of( ".", 0 );
  db_name = db_and_collection_str->substr( 0, dot_pos );
  collection_name = db_and_collection_str->substr( dot_pos+1, std::string::npos );

  mongoc_collection_t *collection;

  collection = mongoc_client_get_collection (client, db_name.c_str(), collection_name.c_str());
  m_cursor = mongoc_collection_find (collection,
                                    flags,
                                    skip,
                                   	limit,
                                    batch_size,
                                    query,
                                    fields,
                                    read_prefs);
  mongoc_collection_destroy (collection);
}

MongocCursor::~MongocCursor() {
  if (m_cursor != nullptr) {
    mongoc_cursor_destroy (m_cursor);
  }
}

} // namespace HPHP


text:
namespace cv
{

class CV_EXPORTS_AS(FeatureDetector) javaFeatureDetector
{
public:
    CV_WRAP void detect( const Mat& image, CV_OUT std::vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const
    { return wrapped->detect(image, keypoints, mask); }

    CV_WRAP void detect( const std::vector<Mat>& images, CV_OUT std::vector<std::vector<KeyPoint> >& keypoints, const std::vector<Mat>& masks=std::vector<Mat>() ) const
    { return wrapped->detect(images, keypoints, masks); }

    CV_WRAP bool empty() const
    { return wrapped->empty(); }

    enum
    {
        FAST          = 1,
        STAR          = 2,
        SIFT          = 3,
        SURF          = 4,
        ORB           = 5,
        MSER          = 6,
        GFTT          = 7,
        HARRIS        = 8,
        SIMPLEBLOB    = 9,
        DENSE         = 10,
        BRISK         = 11,
        AKAZE         = 12,

        GRIDDETECTOR = 1000,

        GRID_FAST          = GRIDDETECTOR + FAST,
        GRID_STAR          = GRIDDETECTOR + STAR,
        GRID_SIFT          = GRIDDETECTOR + SIFT,
        GRID_SURF          = GRIDDETECTOR + SURF,
        GRID_ORB           = GRIDDETECTOR + ORB,
        GRID_MSER          = GRIDDETECTOR + MSER,
        GRID_GFTT          = GRIDDETECTOR + GFTT,
        GRID_HARRIS        = GRIDDETECTOR + HARRIS,
        GRID_SIMPLEBLOB    = GRIDDETECTOR + SIMPLEBLOB,
        GRID_DENSE         = GRIDDETECTOR + DENSE,
        GRID_BRISK         = GRIDDETECTOR + BRISK,
        GRID_AKAZE         = GRIDDETECTOR + AKAZE,

        PYRAMIDDETECTOR = 2000,

        PYRAMID_FAST       = PYRAMIDDETECTOR + FAST,
        PYRAMID_STAR       = PYRAMIDDETECTOR + STAR,
        PYRAMID_SIFT       = PYRAMIDDETECTOR + SIFT,
        PYRAMID_SURF       = PYRAMIDDETECTOR + SURF,
        PYRAMID_ORB        = PYRAMIDDETECTOR + ORB,
        PYRAMID_MSER       = PYRAMIDDETECTOR + MSER,
        PYRAMID_GFTT       = PYRAMIDDETECTOR + GFTT,
        PYRAMID_HARRIS     = PYRAMIDDETECTOR + HARRIS,
        PYRAMID_SIMPLEBLOB = PYRAMIDDETECTOR + SIMPLEBLOB,
        PYRAMID_DENSE      = PYRAMIDDETECTOR + DENSE,
        PYRAMID_BRISK      = PYRAMIDDETECTOR + BRISK,
        PYRAMID_AKAZE      = PYRAMIDDETECTOR + AKAZE,

        DYNAMICDETECTOR = 3000,

        DYNAMIC_FAST       = DYNAMICDETECTOR + FAST,
        DYNAMIC_STAR       = DYNAMICDETECTOR + STAR,
        DYNAMIC_SIFT       = DYNAMICDETECTOR + SIFT,
        DYNAMIC_SURF       = DYNAMICDETECTOR + SURF,
        DYNAMIC_ORB        = DYNAMICDETECTOR + ORB,
        DYNAMIC_MSER       = DYNAMICDETECTOR + MSER,
        DYNAMIC_GFTT       = DYNAMICDETECTOR + GFTT,
        DYNAMIC_HARRIS     = DYNAMICDETECTOR + HARRIS,
        DYNAMIC_SIMPLEBLOB = DYNAMICDETECTOR + SIMPLEBLOB,
        DYNAMIC_DENSE      = DYNAMICDETECTOR + DENSE,
        DYNAMIC_BRISK      = DYNAMICDETECTOR + BRISK,
        DYNAMIC_AKAZE      = DYNAMICDETECTOR + AKAZE
    };

    //supported: FAST STAR SIFT SURF ORB MSER GFTT HARRIS BRISK AKAZE Grid(XXXX) Pyramid(XXXX) Dynamic(XXXX)
    //not supported: SimpleBlob, Dense
    CV_WRAP static javaFeatureDetector* create( int detectorType )
    {
        //String name;
        if (detectorType > DYNAMICDETECTOR)
        {
            //name = "Dynamic";
            detectorType -= DYNAMICDETECTOR;
        }
        if (detectorType > PYRAMIDDETECTOR)
        {
            //name = "Pyramid";
            detectorType -= PYRAMIDDETECTOR;
        }
        if (detectorType > GRIDDETECTOR)
        {
            //name = "Grid";
            detectorType -= GRIDDETECTOR;
        }

        Ptr<FeatureDetector> fd;
        switch(detectorType)
        {
        case FAST:
            fd = FastFeatureDetector::create();
            break;
        //case STAR:
        //    fd = xfeatures2d::StarDetector::create();
        //    break;
        //case SIFT:
        //    name = name + "SIFT";
        //    break;
        //case SURF:
        //    name = name + "SURF";
        //    break;
        case ORB:
            fd = ORB::create();
            break;
        case MSER:
            fd = MSER::create();
            break;
        case GFTT:
            fd = GFTTDetector::create();
            break;
        case HARRIS:
            {
            Ptr<GFTTDetector> gftt = GFTTDetector::create();
            gftt->setHarrisDetector(true);
            fd = gftt;
            }
            break;
        case SIMPLEBLOB:
            fd = SimpleBlobDetector::create();
            break;
        //case DENSE:
        //    name = name + "Dense";
        //    break;
        case BRISK:
            fd = BRISK::create();
            break;
        case AKAZE:
            fd = AKAZE::create();
            break;
        default:
            CV_Error( Error::StsBadArg, "Specified feature detector type is not supported." );
            break;
        }

        return new javaFeatureDetector(fd);
    }

    CV_WRAP void write( const String& fileName ) const
    {
        FileStorage fs(fileName, FileStorage::WRITE);
        wrapped->write(fs);
    }

    CV_WRAP void read( const String& fileName )
    {
        FileStorage fs(fileName, FileStorage::READ);
        wrapped->read(fs.root());
    }

private:
    javaFeatureDetector(Ptr<FeatureDetector> _wrapped) : wrapped(_wrapped)
    {}

    Ptr<FeatureDetector> wrapped;
};

class CV_EXPORTS_AS(DescriptorMatcher) javaDescriptorMatcher
{
public:
    CV_WRAP bool isMaskSupported() const
    { return wrapped->isMaskSupported(); }

    CV_WRAP void add( const std::vector<Mat>& descriptors )
    { return wrapped->add(descriptors); }

    CV_WRAP const std::vector<Mat>& getTrainDescriptors() const
    { return wrapped->getTrainDescriptors(); }

    CV_WRAP void clear()
    { return wrapped->clear(); }

    CV_WRAP bool empty() const
    { return wrapped->empty(); }

    CV_WRAP void train()
    { return wrapped->train(); }

    CV_WRAP void match( const Mat& queryDescriptors, const Mat& trainDescriptors,
                CV_OUT std::vector<DMatch>& matches, const Mat& mask=Mat() ) const
    { return wrapped->match(queryDescriptors, trainDescriptors, matches, mask); }

    CV_WRAP void knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors,
                   CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
                   const Mat& mask=Mat(), bool compactResult=false ) const
    { return wrapped->knnMatch(queryDescriptors, trainDescriptors, matches, k, mask, compactResult); }

    CV_WRAP void radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors,
                      CV_OUT std::vector<std::vector<DMatch> >& matches, float maxDistance,
                      const Mat& mask=Mat(), bool compactResult=false ) const
    { return wrapped->radiusMatch(queryDescriptors, trainDescriptors, matches, maxDistance, mask, compactResult); }

    CV_WRAP void match( const Mat& queryDescriptors, CV_OUT std::vector<DMatch>& matches,
                const std::vector<Mat>& masks=std::vector<Mat>() )
    { return wrapped->match(queryDescriptors, matches, masks); }

    CV_WRAP void knnMatch( const Mat& queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
           const std::vector<Mat>& masks=std::vector<Mat>(), bool compactResult=false )
    { return wrapped->knnMatch(queryDescriptors, matches, k, masks, compactResult); }

    CV_WRAP void radiusMatch( const Mat& queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, float maxDistance,
                   const std::vector<Mat>& masks=std::vector<Mat>(), bool compactResult=false )
    { return wrapped->radiusMatch(queryDescriptors, matches, maxDistance, masks, compactResult); }

    enum
    {
        FLANNBASED            = 1,
        BRUTEFORCE            = 2,
        BRUTEFORCE_L1         = 3,
        BRUTEFORCE_HAMMING    = 4,
        BRUTEFORCE_HAMMINGLUT = 5,
        BRUTEFORCE_SL2        = 6
    };

    CV_WRAP_AS(clone) javaDescriptorMatcher* jclone( bool emptyTrainData=false ) const
    {
        return new javaDescriptorMatcher(wrapped->clone(emptyTrainData));
    }

    //supported: FlannBased, BruteForce, BruteForce-L1, BruteForce-Hamming, BruteForce-HammingLUT
    CV_WRAP static javaDescriptorMatcher* create( int matcherType )
    {
        String name;

        switch(matcherType)
        {
        case FLANNBASED:
            name = "FlannBased";
            break;
        case BRUTEFORCE:
            name = "BruteForce";
            break;
        case BRUTEFORCE_L1:
            name = "BruteForce-L1";
            break;
        case BRUTEFORCE_HAMMING:
            name = "BruteForce-Hamming";
            break;
        case BRUTEFORCE_HAMMINGLUT:
            name = "BruteForce-HammingLUT";
            break;
        case BRUTEFORCE_SL2:
            name = "BruteForce-SL2";
            break;
        default:
            CV_Error( Error::StsBadArg, "Specified descriptor matcher type is not supported." );
            break;
        }

        return new javaDescriptorMatcher(DescriptorMatcher::create(name));
    }

    CV_WRAP void write( const String& fileName ) const
    {
        FileStorage fs(fileName, FileStorage::WRITE);
        wrapped->write(fs);
    }

    CV_WRAP void read( const String& fileName )
    {
        FileStorage fs(fileName, FileStorage::READ);
        wrapped->read(fs.root());
    }

private:
    javaDescriptorMatcher(Ptr<DescriptorMatcher> _wrapped) : wrapped(_wrapped)
    {}

    Ptr<DescriptorMatcher> wrapped;
};

class CV_EXPORTS_AS(DescriptorExtractor) javaDescriptorExtractor
{
public:
    CV_WRAP void compute( const Mat& image, CV_IN_OUT std::vector<KeyPoint>& keypoints, Mat& descriptors ) const
    { return wrapped->compute(image, keypoints, descriptors); }

    CV_WRAP void compute( const std::vector<Mat>& images, CV_IN_OUT std::vector<std::vector<KeyPoint> >& keypoints, CV_OUT std::vector<Mat>& descriptors ) const
    { return wrapped->compute(images, keypoints, descriptors); }

    CV_WRAP int descriptorSize() const
    { return wrapped->descriptorSize(); }

    CV_WRAP int descriptorType() const
    { return wrapped->descriptorType(); }

    CV_WRAP bool empty() const
    { return wrapped->empty(); }

    enum
    {
        SIFT  = 1,
        SURF  = 2,
        ORB   = 3,
        BRIEF = 4,
        BRISK = 5,
        FREAK = 6,
        AKAZE = 7,

        OPPONENTEXTRACTOR = 1000,

        OPPONENT_SIFT  = OPPONENTEXTRACTOR + SIFT,
        OPPONENT_SURF  = OPPONENTEXTRACTOR + SURF,
        OPPONENT_ORB   = OPPONENTEXTRACTOR + ORB,
        OPPONENT_BRIEF = OPPONENTEXTRACTOR + BRIEF,
        OPPONENT_BRISK = OPPONENTEXTRACTOR + BRISK,
        OPPONENT_FREAK = OPPONENTEXTRACTOR + FREAK,
        OPPONENT_AKAZE = OPPONENTEXTRACTOR + AKAZE
    };

    //supported SIFT, SURF, ORB, BRIEF, BRISK, FREAK, AKAZE, Opponent(XXXX)
    //not supported: Calonder
    CV_WRAP static javaDescriptorExtractor* create( int extractorType )
    {
        //String name;

        if (extractorType > OPPONENTEXTRACTOR)
        {
            //name = "Opponent";
            extractorType -= OPPONENTEXTRACTOR;
        }

        Ptr<DescriptorExtractor> de;
        switch(extractorType)
        {
        //case SIFT:
        //    name = name + "SIFT";
        //    break;
        //case SURF:
        //    name = name + "SURF";
        //    break;
        case ORB:
            de = ORB::create();
            break;
        //case BRIEF:
        //    name = name + "BRIEF";
        //    break;
        case BRISK:
            de = BRISK::create();
            break;
        //case FREAK:
        //    name = name + "FREAK";
        //    break;
        case AKAZE:
            de = AKAZE::create();
            break;
        default:
            CV_Error( Error::StsBadArg, "Specified descriptor extractor type is not supported." );
            break;
        }

        return new javaDescriptorExtractor(de);
    }

    CV_WRAP void write( const String& fileName ) const
    {
        FileStorage fs(fileName, FileStorage::WRITE);
        wrapped->write(fs);
    }

    CV_WRAP void read( const String& fileName )
    {
        FileStorage fs(fileName, FileStorage::READ);
        wrapped->read(fs.root());
    }

private:
    javaDescriptorExtractor(Ptr<DescriptorExtractor> _wrapped) : wrapped(_wrapped)
    {}

    Ptr<DescriptorExtractor> wrapped;
};

#if 0
//DO NOT REMOVE! The block is required for sources parser
enum
{
          DRAW_OVER_OUTIMG = 1, // Output image matrix will not be created (Mat::create).
                                // Matches will be drawn on existing content of output image.
          NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn.
          DRAW_RICH_KEYPOINTS = 4 // For each keypoint the circle around keypoint with keypoint size and
                                  // orientation will be drawn.
};

// Draw keypoints.
CV_EXPORTS_W void drawKeypoints( const Mat& image, const std::vector<KeyPoint>& keypoints, Mat& outImage,
                               const Scalar& color=Scalar::all(-1), int flags=0 );

// Draws matches of keypints from two images on output image.
CV_EXPORTS_W void drawMatches( const Mat& img1, const std::vector<KeyPoint>& keypoints1,
                             const Mat& img2, const std::vector<KeyPoint>& keypoints2,
                             const std::vector<DMatch>& matches1to2, Mat& outImg,
                             const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
                             const std::vector<char>& matchesMask=std::vector<char>(), int flags=0 );

CV_EXPORTS_AS(drawMatches2) void drawMatches( const Mat& img1, const std::vector<KeyPoint>& keypoints1,
                             const Mat& img2, const std::vector<KeyPoint>& keypoints2,
                             const std::vector<std::vector<DMatch> >& matches1to2, Mat& outImg,
                             const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
                             const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), int flags=0);

#endif

} //cv

#endif // HAVE_OPENCV_FEATURES2D

#endif // __OPENCV_FEATURES_2D_MANUAL_HPP__


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Routing\Annotators;

use InvalidArgumentException;
use ReflectionException;
use Valkyrja\Annotation\Annotator as AnnotationAnnotator;
use Valkyrja\Annotation\Filter;
use Valkyrja\Reflection\Reflector;
use Valkyrja\Routing\Annotations\Route;
use Valkyrja\Routing\Annotator as Contract;
use Valkyrja\Routing\Enums\AnnotationName;
use Valkyrja\Routing\Exceptions\InvalidRoutePath;
use Valkyrja\Routing\Models\Route as RouteModel;
use Valkyrja\Routing\Route as RouteContract;

use function array_merge;
use function trim;

/**
 * Class RouteAnnotator.
 *
 * @author Melech Mizrachi
 */
class Annotator implements Contract
{
    /**
     * The annotator.
     *
     * @var AnnotationAnnotator
     */
    protected AnnotationAnnotator $annotator;

    /**
     * The filter.
     *
     * @var Filter
     */
    protected Filter $filter;

    /**
     * The reflector.
     *
     * @var Reflector
     */
    protected Reflector $reflector;

    /**
     * ContainerAnnotator constructor.
     *
     * @param AnnotationAnnotator $annotator
     * @param Filter              $filter
     * @param Reflector           $reflector
     */
    public function __construct(AnnotationAnnotator $annotator, Filter $filter, Reflector $reflector)
    {
        $this->annotator = $annotator;
        $this->filter    = $filter;
        $this->reflector = $reflector;
    }

    /**
     * @inheritDoc
     *
     * @throws ReflectionException
     * @throws InvalidRoutePath
     * @throws InvalidArgumentException
     */
    public function getRoutes(string ...$classes): array
    {
        $routes = $this->getClassRoutes($classes);
        /** @var RouteContract[] $finalRoutes */
        $finalRoutes = [];

        // Iterate through all the routes
        foreach ($routes as $route) {
            $class = $route->getClass();
            $path  = $route->getPath();

            if (null === $class || null === $path) {
                throw new InvalidArgumentException('Invalid class or path defined in route.');
            }

            // Set the route's properties
            $this->setRouteProperties($route);

            // Get the class's annotations
            $classAnnotations = $this->getClassAnnotations($class);

            // If this route's class has annotations
            if (! empty($classAnnotations)) {
                /** @var Route $annotation */
                // Iterate through all the annotations
                foreach ($classAnnotations as $annotation) {
                    // And set a new route with the controller defined annotation additions
                    $finalRoutes[] = $this->getRouteFromAnnotation($this->getControllerBuiltRoute($annotation, $route));
                }
            } else {
                // Validate the path before setting the route
                $route->setPath($this->validatePath($path));

                // Otherwise just set the route in the final array
                $finalRoutes[] = $this->getRouteFromAnnotation($route);
            }
        }

        return $finalRoutes;
    }

    /**
     * Get all classes' routes.
     *
     * @param array $classes The classes
     *
     * @return Route[]
     */
    protected function getClassRoutes(array $classes): array
    {
        /** @var Route[] $routes */
        $routes = [];

        // Iterate through all the classes
        foreach ($classes as $class) {
            // Get all the routes for each class and iterate through them
            foreach ($this->getClassMemberAnnotations($class) as $annotation) {
                // Set the annotation in the routes list
                $routes[] = $annotation;
            }
        }

        return $routes;
    }

    /**
     * Set the route properties from arguments.
     *
     * @param Route $route
     *
     * @throws InvalidRoutePath
     * @throws ReflectionException
     *
     * @return void
     */
    protected function setRouteProperties(Route $route): void
    {
        if (! $route->getClass()) {
            throw new InvalidArgumentException('Invalid class defined in route.');
        }

        if (null === $route->getProperty()) {
            $methodReflection = $this->reflector->getMethodReflection(
                $route->getClass(),
                $route->getMethod() ?? '__construct'
            );

            // Set the dependencies
            $route->setDependencies($this->reflector->getDependencies($methodReflection));
        }

        // Avoid having large arrays in cached routes file
        $route->setMatches();

        if (null === $route->getPath()) {
            throw new InvalidRoutePath(
                'Invalid route path for route : '
                . $route->getClass()
                . '@' . $route->getMethod()
            );
        }
    }

    /**
     * Get class annotations
     *
     * @param string $class The class
     *
     * @return array
     */
    protected function getClassAnnotations(string $class): array
    {
        return $this->filter->filterAnnotationsByTypes(
            AnnotationName::getValidValues(),
            ...$this->annotator->classAnnotations($class)
        );
    }

    /**
     * Get a route from a route annotation.
     *
     * @param Route $route The route annotation
     *
     * @throws InvalidArgumentException
     *
     * @return RouteContract
     */
    protected function getRouteFromAnnotation(Route $route): RouteContract
    {
        return RouteModel::fromArray($route->asArray());
    }

    /**
     * Get a new route with controller route additions.
     *
     * @param Route $controllerRoute
     * @param Route $route
     *
     * @return Route
     */
    protected function getControllerBuiltRoute(Route $controllerRoute, Route $route): Route
    {
        $newRoute = clone $route;

        if (! $route->getPath()) {
            throw new InvalidArgumentException('Invalid path defined in route.');
        }

        // If there is a base path for this controller
        if (null !== $controllerRoute->getPath()) {
            // Get the route's path
            $path           = $this->validatePath($route->getPath());
            $controllerPath = $this->validatePath($controllerRoute->getPath());

            // Set the path to the base path and route path
            $newRoute->setPath($this->validatePath($controllerPath . $path));
        }

        // If there is a base name for this controller
        if (null !== $controllerRoute->getName()) {
            // Set the name to the base name and route name
            $newRoute->setName($controllerRoute->getName() . '.' . $route->getName());
        }

        // If the base is dynamic
        if ($controllerRoute->isDynamic()) {
            // Set the route to dynamic
            $newRoute->setDynamic();
        }

        // If the base is secure
        if ($controllerRoute->isSecure()) {
            // Set the route to dynamic
            $newRoute->setSecure();
        }

        // If there is a base middleware collection for this controller
        if (null !== $controllerRoute->getMiddleware()) {
            // Merge the route's middleware and the controller's middleware
            // keeping the controller's middleware first
            $middleware = array_merge($controllerRoute->getMiddleware(), $route->getMiddleware() ?? []);

            // Set the middleware in the route
            $newRoute->setMiddleware($middleware);
        }

        return $newRoute;
    }

    /**
     * Validate a path.
     *
     * @param string $path The path
     *
     * @return string
     */
    protected function validatePath(string $path): string
    {
        // Trim slashes from the beginning and end of the path
        if (! $path = trim($path, '/')) {
            // If the path only had a slash return as just slash
            return '/';
        }

        // If the route doesn't begin with an optional or required group
        if ($path[0] !== '[' && $path[0] !== '<') {
            // Append a slash
            return '/' . $path;
        }

        return $path;
    }

    /**
     * Get class member annotations
     *
     * @param string $class The class
     *
     * @return array
     */
    protected function getClassMemberAnnotations(string $class): array
    {
        return $this->filter->filterAnnotationsByTypes(
            AnnotationName::getValidValues(),
            ...$this->annotator->classMembersAnnotations($class)
        );
    }
}