text:
#import "UIKit-Structs.h"
#import <Foundation/NSObject.h>
#import <Availability2.h>

@interface UIHardware : NSObject {
}
+(float)statusBarHeight;
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_3_2
+(void)_setStatusBarHeight:(float)height;
#endif
+(CGSize)mainScreenSize;
+(CGRect)fullScreenApplicationContentRect;
+(int)ringerState;
+(int)deviceOrientation:(BOOL)orientation;
+(BOOL)setSpeakerPhoneEnabled:(BOOL)enabled;
+(BOOL)isTTYEnabled;
+(CGSize)TVScreenSize;
+(float)TVHorizontalPixelScale;
+(BOOL)_TVOutStatus:(BOOL)status;
+(BOOL)TVOutCapableAndPreferred;
+(BOOL)TVOutCapable;
+(void)TVOutResetPreferred;
+(void)alertSheet:(id)sheet buttonClicked:(int)clicked;
+(void)accessoryAvailabilityChanged;
+(id)deviceName;
+(id)localizedDeviceName;
+(void)_updateSystemSoundActiveStatus:(id)status;
+(void)_registerForSystemSounds:(id)systemSounds;
+(void)_unregisterForSystemSounds:(id)systemSounds;
+(void)_playSystemSound:(unsigned long)sound;
@end


text:
[![Build Status][travis-image]][travis-url]
[![Coverage Status][coveralls-image]][coveralls-url]

## What is this?
Example for testing **`gulpfile.js`**.
The test suite executes gulp tasks programmatically.
This means you can easily get the code coverage for the test.

This approach would be helpful when you create a project starter kit or [Yeoman](http://yeoman.io/) generator.

## Setup
```
$ npm install
```

## Run test
This runs unit test for [`gulpfile.js`](gulpfile.js) and [`subproject/gulpfile.js`](subproject/gulpfile.js) using [Mocha](https://mochajs.org/) and [Istanbul](https://github.com/gotwarlost/istanbul).
```
$ npm test
```

Results:
```
gulp
  task "copy"
    ✓ outputs file into "dist" directory
    ✓ outputs file with expected content

gulp in subproject
  task "copy"
    ✓ outputs file into "dist" directory
    ✓ outputs file with expected content

4 passing (48ms)

=============================== Coverage summary ===============================
Statements   : 100% ( 6/6 )
Branches     : 100% ( 0/0 )
Functions    : 100% ( 2/2 )
Lines        : 100% ( 6/6 )
================================================================================
```

## License
Copyright (c) 2016 Hiroyuki Tanjo.
Licensed under the MIT License.

[travis-image]: https://travis-ci.org/htanjo/gulpfile-test.svg?branch=master
[travis-url]: https://travis-ci.org/htanjo/gulpfile-test
[coveralls-image]: https://coveralls.io/repos/htanjo/gulpfile-test/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/r/htanjo/gulpfile-test

redpajama_set_name: RedPajamaGithub


text:
import urllib2
import os, time
import json
path = 'query/'
img_files = [ f for f in os.listdir( path ) if f.endswith('.jpg') ]
url = 'https://api.projectoxford.ai/face/v0/detections?analyzesFaceLandmarks=true&analyzesAge=true&analyzesGender=true&analyzesHeadPose=true'

for img in img_files:
    data = open( path + img, "rb")
    length = os.path.getsize( path + img )
    request = urllib2.Request(url=url, data=data)
    request.add_header('Cache-Control', 'no-cache')
    request.add_header('Content-Length', '%d' % length)
    request.add_header('Content-Type', 'application/octet-stream')
    request.add_header('Ocp-Apim-Subscription-Key', 'FILL YOUR SUBSCRIPTION KEY of OXFORD API')

    result = urllib2.urlopen(request).read().strip()
    res_obj = json.loads( result )

    with open( path + 'attr/' + img[:-4] + '.json', 'w' ) as f:
        json.dump( res_obj, f, indent=4 )


text:
package com.box.sdk;

import java.net.URL;

import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

/**
 * Represents a Metadata Cascade Policy.
 */
@BoxResourceType("metadata_cascade_policy")
public class BoxMetadataCascadePolicy extends BoxResource {

    /**
     * Get All Metadata Cascade Policies URL.
     */
    public static final URLTemplate GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE =
            new URLTemplate("metadata_cascade_policies");

    /**
     * Metadata Cascade Policies URL.
     */
    public static final URLTemplate METADATA_CASCADE_POLICIES_URL_TEMPLATE =
            new URLTemplate("metadata_cascade_policies/%s");

    /**
     * Force Metadata Cascade Policies URL.
     */
    public static final URLTemplate FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE =
            new URLTemplate("metadata_cascade_policies/%s/apply");

    private static final int DEFAULT_LIMIT = 100;

    /**
     * Constructs a BoxMetadataCascadePolicy for a metadata cascade policy with a given ID.
     *
     * @param api the API connection used to make the request.
     * @param id  the ID of the metadata cascade policy.
     */
    public BoxMetadataCascadePolicy(BoxAPIConnection api, String id) {
        super(api, id);
    }

    /**
     * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable.
     *
     * @param api      the API connection to be used by the resource.
     * @param folderID the ID of the folder to retrieve cascade policies for.
     * @param fields   optional fields to retrieve for cascade policies.
     * @return the Iterable of Box Metadata Cascade Policies in your enterprise.
     */
    public static Iterable<BoxMetadataCascadePolicy.Info> getAll(final BoxAPIConnection api,
                                                                 String folderID, String ... fields) {
        return getAll(api, folderID, null, DEFAULT_LIMIT, fields);
    }

    /**
     * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable.
     *
     * @param api               the API connection to be used by the resource.
     * @param folderID          the ID of the folder to retrieve cascade policies for.
     * @param ownerEnterpriseID the ID of the enterprise to retrieve Metadata Cascade Policies for.
     * @param limit             the number of entries for cascade policies to retrieve.
     * @param fields            optional fields to retrieve for cascade policies.
     * @return the Iterable of Box Metadata Cascade Policies in your enterprise.
     */
    public static Iterable<BoxMetadataCascadePolicy.Info> getAll(final BoxAPIConnection api,
                                                                 String folderID, String ownerEnterpriseID, int limit,
                                                                 String... fields) {

        QueryStringBuilder builder = new QueryStringBuilder();
        builder.appendParam("folder_id", folderID);
        if (ownerEnterpriseID != null) {
            builder.appendParam("owner_enterprise_id", ownerEnterpriseID);
        }
        if (fields.length > 0) {
            builder.appendParam("fields", fields);
        }
        return new BoxResourceIterable<Info>(api, GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE
                .buildWithQuery(api.getBaseURL(), builder.toString()), limit) {
            @Override
            protected BoxMetadataCascadePolicy.Info factory(JsonObject jsonObject) {
                BoxMetadataCascadePolicy cascadePolicy =
                        new BoxMetadataCascadePolicy(api, jsonObject.get("id").asString());

                return cascadePolicy.new Info(jsonObject);
            }
        };
    }

    /**
     * Returns the information for a specific BoxMetadataCascadePolicy.
     *
     * @param fields the fields to retrieve.
     * @return the information about this metadata cascade policy.
     */
    public BoxMetadataCascadePolicy.Info getInfo(String... fields) {
        QueryStringBuilder builder = new QueryStringBuilder();
        if (fields.length > 0) {
            builder.appendParam("fields", fields);
        }
        URL url = METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(),
                builder.toString(), this.getID());
        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
        BoxJSONResponse response = (BoxJSONResponse) request.send();
        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
        return new Info(responseJSON);
    }

    /**
     * Creates a new Metadata Cascade Policy on a folder.
     *
     * @param api         the API connection to be used by the resource.
     * @param folderID    the ID of the folder to create a metadata cascade policy on.
     * @param scope       the scope of the metadata cascade policy.
     * @param templateKey the key of the template.
     * @return information about the Metadata Cascade Policy.
     */
    public static BoxMetadataCascadePolicy.Info create(final BoxAPIConnection api, String folderID, String scope,
                                                       String templateKey) {
        URL url = GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(api.getBaseURL());
        BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
        JsonObject requestJSON = new JsonObject()
                .add("folder_id", folderID)
                .add("scope", scope)
                .add("templateKey", templateKey);
        request.setBody(requestJSON.toString());
        BoxJSONResponse response = (BoxJSONResponse) request.send();
        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
        BoxMetadataCascadePolicy createdMetadataCascadePolicy = new BoxMetadataCascadePolicy(api,
                responseJSON.get("id").asString());
        return createdMetadataCascadePolicy.new Info(responseJSON);
    }

    /**
     * If a policy already exists on a folder, this will apply that policy to all existing files and sub folders within
     * the target folder.
     *
     * @param conflictResolution the desired behavior for conflict-resolution. Set to either none or overwrite.
     */
    public void forceApply(String conflictResolution) {

        URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
        JsonObject requestJSON = new JsonObject()
                .add("conflict_resolution", conflictResolution);
        request.setBody(requestJSON.toString());
        BoxJSONResponse response = (BoxJSONResponse) request.send();
    }

    /**
     * Deletes the metadata cascade policy.
     */
    public void delete() {
        URL url = METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
        BoxAPIResponse response = request.send();
    }

    /**
     * Contains information about a BoxMetadataCascadePolicy.
     */
    public class Info extends BoxResource.Info {
        private BoxEnterprise ownerEnterprise;
        private BoxFolder.Info parent;
        private String scope;
        private String templateKey;

        /**
         * Constructs an empty Info object.
         */
        public Info() {
            super();
        }

        /**
         * Constructs an Info object by parsing information from a JSON string.
         *
         * @param json the JSON string to parse.
         */
        public Info(String json) {
            super(json);
        }

        Info(JsonObject jsonObject) {
            super(jsonObject);
        }

        /**
         * Gets the enterprise the metadata cascade policy belongs to.
         *
         * @return the enterprise the metadata cascade policy belongs to.
         */
        public BoxEnterprise getOwnerEnterprise() {
            return this.ownerEnterprise;
        }

        /**
         * Gets the folder the metadata cascade policy is on.
         *
         * @return the folder parent of the metadata cascade policy.
         */
        public BoxFolder.Info getParent() {
            return this.parent;
        }

        /**
         * Gets the scope of the metadata cascade policy.
         *
         * @return the scope of the metadata cascade policy.
         */
        public String getScope() {
            return this.scope;
        }

        /**
         * Gets the template key for the metadata cascade policy.
         *
         * @return the template key for the metadata cascade policy.
         */
        public String getTemplateKey() {
            return this.templateKey;
        }

        @Override
        public BoxMetadataCascadePolicy getResource() {
            return BoxMetadataCascadePolicy.this;
        }

        @Override
        protected void parseJSONMember(JsonObject.Member member) {
            super.parseJSONMember(member);
            String memberName = member.getName();
            JsonValue value = member.getValue();
            try {
                if (memberName.equals("owner_enterprise")) {
                    JsonObject jsonObject = value.asObject();
                    this.ownerEnterprise = new BoxEnterprise(jsonObject);
                } else if (memberName.equals("parent")) {
                    JsonObject parentJSON = value.asObject();
                    if (this.parent == null) {
                        String parentID = parentJSON.get("id").asString();
                        BoxFolder folder = new BoxFolder(getAPI(), parentID);
                        this.parent = folder.new Info(parentJSON);
                    } else {
                        this.parent.update(parentJSON);
                    }
                } else if (memberName.equals("scope")) {
                    this.scope = value.asString();
                } else if (memberName.equals("templateKey")) {
                    this.templateKey = value.asString();
                }
            } catch (Exception e) {
                assert false : "A ParseException indicates a bug in the SDK.";
            }
        }
    }
}


text:
import os
import sys

sys.path.append(os.path.dirname(__name__))

from torc_application.torc_web import create_app

# create an app instance
app = create_app()

# Don't fetch from the CDN..
app.config['BOOTSTRAP_SERVE_LOCAL'] = True

if os.path.isfile('/.dockerenv'):
    print("Running in docker")
    #app.run(host='0.0.0.0',debug=True,threaded=True,ssl_context=context)
    app.run(host='0.0.0.0',debug=True,threaded=True,port=8080)
else:
    #app.run(debug=True,threaded=True,ssl_context=context)
    app.run(debug=True,threaded=True,port=8080)


text:
#include "webrtc/system_wrappers/source/file_impl.h"

#include <assert.h>

#ifdef _WIN32
#include <Windows.h>
#else
#include <stdarg.h>
#include <string.h>
#endif

#include "webrtc/system_wrappers/interface/rw_lock_wrapper.h"

namespace webrtc {

FileWrapper* FileWrapper::Create() {
  return new FileWrapperImpl();
}

FileWrapperImpl::FileWrapperImpl()
    : rw_lock_(RWLockWrapper::CreateRWLock()),
      id_(NULL),
      managed_file_handle_(true),
      open_(false),
      looping_(false),
      read_only_(false),
      max_size_in_bytes_(0),
      size_in_bytes_(0) {
  memset(file_name_utf8_, 0, kMaxFileNameSize);
}

FileWrapperImpl::~FileWrapperImpl() {
  if (id_ != NULL && managed_file_handle_) {
    fclose(id_);
  }
}

int FileWrapperImpl::CloseFile() {
  WriteLockScoped write(*rw_lock_);
  return CloseFileImpl();
}

int FileWrapperImpl::Rewind() {
  WriteLockScoped write(*rw_lock_);
  if (looping_ || !read_only_) {
    if (id_ != NULL) {
      size_in_bytes_ = 0;
      return fseek(id_, 0, SEEK_SET);
    }
  }
  return -1;
}

int FileWrapperImpl::SetMaxFileSize(size_t bytes) {
  WriteLockScoped write(*rw_lock_);
  max_size_in_bytes_ = bytes;
  return 0;
}

int FileWrapperImpl::Flush() {
  WriteLockScoped write(*rw_lock_);
  return FlushImpl();
}

int FileWrapperImpl::FileName(char* file_name_utf8, size_t size) const {
  ReadLockScoped read(*rw_lock_);
  size_t length = strlen(file_name_utf8_);
  if (length > kMaxFileNameSize) {
    assert(false);
    return -1;
  }
  if (length < 1) {
    return -1;
  }

  // Make sure to NULL terminate
  if (size < length) {
    length = size - 1;
  }
  memcpy(file_name_utf8, file_name_utf8_, length);
  file_name_utf8[length] = 0;
  return 0;
}

bool FileWrapperImpl::Open() const {
  ReadLockScoped read(*rw_lock_);
  return open_;
}

int FileWrapperImpl::OpenFile(const char* file_name_utf8, bool read_only,
                              bool loop, bool text) {
  WriteLockScoped write(*rw_lock_);
  if (id_ != NULL && !managed_file_handle_)
    return -1;
  size_t length = strlen(file_name_utf8);
  if (length > kMaxFileNameSize - 1) {
    return -1;
  }

  read_only_ = read_only;

  FILE* tmp_id = NULL;
#if defined _WIN32
  wchar_t wide_file_name[kMaxFileNameSize];
  wide_file_name[0] = 0;

  MultiByteToWideChar(CP_UTF8,
                      0,  // UTF8 flag
                      file_name_utf8,
                      -1,  // Null terminated string
                      wide_file_name,
                      kMaxFileNameSize);
  if (text) {
    if (read_only) {
      tmp_id = _wfopen(wide_file_name, L"rt");
    } else {
      tmp_id = _wfopen(wide_file_name, L"wt");
    }
  } else {
    if (read_only) {
      tmp_id = _wfopen(wide_file_name, L"rb");
    } else {
      tmp_id = _wfopen(wide_file_name, L"wb");
    }
  }
#else
  if (text) {
    if (read_only) {
      tmp_id = fopen(file_name_utf8, "rt");
    } else {
      tmp_id = fopen(file_name_utf8, "wt");
    }
  } else {
    if (read_only) {
      tmp_id = fopen(file_name_utf8, "rb");
    } else {
      tmp_id = fopen(file_name_utf8, "wb");
    }
  }
#endif

  if (tmp_id != NULL) {
    // +1 comes from copying the NULL termination character.
    memcpy(file_name_utf8_, file_name_utf8, length + 1);
    if (id_ != NULL) {
      fclose(id_);
    }
    id_ = tmp_id;
    managed_file_handle_ = true;
    looping_ = loop;
    open_ = true;
    return 0;
  }
  return -1;
}

int FileWrapperImpl::OpenFromFileHandle(FILE* handle,
                                        bool manage_file,
                                        bool read_only,
                                        bool loop) {
  WriteLockScoped write(*rw_lock_);
  if (!handle)
    return -1;

  if (id_ != NULL) {
    if (managed_file_handle_)
      fclose(id_);
    else
      return -1;
  }

  id_ = handle;
  managed_file_handle_ = manage_file;
  read_only_ = read_only;
  looping_ = loop;
  open_ = true;
  return 0;
}

int FileWrapperImpl::Read(void* buf, size_t length) {
  WriteLockScoped write(*rw_lock_);
  if (id_ == NULL)
    return -1;

  size_t bytes_read = fread(buf, 1, length, id_);
  if (bytes_read != length && !looping_) {
    CloseFileImpl();
  }
  return static_cast<int>(bytes_read);
}

int FileWrapperImpl::WriteText(const char* format, ...) {
  WriteLockScoped write(*rw_lock_);
  if (format == NULL)
    return -1;

  if (read_only_)
    return -1;

  if (id_ == NULL)
    return -1;

  va_list args;
  va_start(args, format);
  int num_chars = vfprintf(id_, format, args);
  va_end(args);

  if (num_chars >= 0) {
    return num_chars;
  } else {
    CloseFileImpl();
    return -1;
  }
}

bool FileWrapperImpl::Write(const void* buf, size_t length) {
  WriteLockScoped write(*rw_lock_);
  if (buf == NULL)
    return false;

  if (read_only_)
    return false;

  if (id_ == NULL)
    return false;

  // Check if it's time to stop writing.
  if (max_size_in_bytes_ > 0 &&
      (size_in_bytes_ + length) > max_size_in_bytes_) {
    FlushImpl();
    return false;
  }

  size_t num_bytes = fwrite(buf, 1, length, id_);
  if (num_bytes > 0) {
    size_in_bytes_ += num_bytes;
    return true;
  }

  CloseFileImpl();
  return false;
}

int FileWrapperImpl::CloseFileImpl() {
  if (id_ != NULL) {
    if (managed_file_handle_)
      fclose(id_);
    id_ = NULL;
  }
  memset(file_name_utf8_, 0, kMaxFileNameSize);
  open_ = false;
  return 0;
}

int FileWrapperImpl::FlushImpl() {
  if (id_ != NULL) {
    return fflush(id_);
  }
  return -1;
}

}  // namespace webrtc


text:
#pragma once
#include <aws/resource-explorer-2/ResourceExplorer2_EXPORTS.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/core/client/AWSClient.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/resource-explorer-2/ResourceExplorer2ServiceClientModel.h>

namespace Aws
{
namespace ResourceExplorer2
{
  /**
   *
Amazon Web Services Resource Explorer is a resource search and discovery
   * service. By using Resource Explorer, you can explore your resources using an
   * internet search engine-like experience. Examples of resources include Amazon
   * Relational Database Service (Amazon RDS) instances, Amazon Simple Storage
   * Service (Amazon S3) buckets, or Amazon DynamoDB tables. You can search for your
   * resources using resource metadata like names, tags, and IDs. Resource Explorer
   * can search across all of the Amazon Web Services Regions in your account in
   * which you turn the service on, to simplify your cross-Region workloads.

   *
Resource Explorer scans the resources in each of the Amazon Web Services
   * Regions in your Amazon Web Services account in which you turn on Resource
   * Explorer. Resource Explorer creates
   * and maintains an index in each Region, with the details of that Region's
   * resources.

You can search
   * across all of the indexed Regions in your account by designating one of your
   * Amazon Web Services Regions to contain the aggregator index for the account.
   * When you promote
   * a local index in a Region to become the aggregator index for the account,
   * Resource Explorer automatically replicates the index information from all local
   * indexes in the other Regions to the aggregator index. Therefore, the Region with
   * the aggregator index has a copy of all resource information for all Regions in
   * the account where you turned on Resource Explorer. As a result, views in the
   * aggregator index Region include resources from all of the indexed Regions in
   * your account.

For more information about Amazon Web Services Resource
   * Explorer, including how to enable and configure the service, see the Amazon
   * Web Services Resource Explorer User Guide.

   */
  class AWS_RESOURCEEXPLORER2_API ResourceExplorer2Client : public Aws::Client::AWSJsonClient
  {
    public:
      typedef Aws::Client::AWSJsonClient BASECLASS;
      static const char* SERVICE_NAME;
      static const char* ALLOCATION_TAG;

       /**
        * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ResourceExplorer2Client(const Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration& clientConfiguration = Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration(),
                                std::shared_ptr<ResourceExplorer2EndpointProviderBase> endpointProvider = Aws::MakeShared<ResourceExplorer2EndpointProvider>(ALLOCATION_TAG));

       /**
        * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ResourceExplorer2Client(const Aws::Auth::AWSCredentials& credentials,
                                std::shared_ptr<ResourceExplorer2EndpointProviderBase> endpointProvider = Aws::MakeShared<ResourceExplorer2EndpointProvider>(ALLOCATION_TAG),
                                const Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration& clientConfiguration = Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration());

       /**
        * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
        * the default http client factory will be used
        */
        ResourceExplorer2Client(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
                                std::shared_ptr<ResourceExplorer2EndpointProviderBase> endpointProvider = Aws::MakeShared<ResourceExplorer2EndpointProvider>(ALLOCATION_TAG),
                                const Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration& clientConfiguration = Aws::ResourceExplorer2::ResourceExplorer2ClientConfiguration());

        /* Legacy constructors due deprecation */
       /**
        * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ResourceExplorer2Client(const Aws::Client::ClientConfiguration& clientConfiguration);

       /**
        * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ResourceExplorer2Client(const Aws::Auth::AWSCredentials& credentials,
                                const Aws::Client::ClientConfiguration& clientConfiguration);

       /**
        * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
        * the default http client factory will be used
        */
        ResourceExplorer2Client(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
                                const Aws::Client::ClientConfiguration& clientConfiguration);

        /* End of legacy constructors due deprecation */
        virtual ~ResourceExplorer2Client();

        /**
         *
Sets the specified view as the default for the Amazon Web Services Region in
         * which you call this operation. When a user performs a Search that doesn't
         * explicitly specify which view to use, then Amazon Web Services Resource Explorer
         * automatically chooses this default view for searches performed in this Amazon
         * Web Services Region.

If an Amazon Web Services Region doesn't have a
         * default view configured, then users must explicitly specify a view with every
         * Search operation performed in that Region.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::AssociateDefaultViewOutcome AssociateDefaultView(const Model::AssociateDefaultViewRequest& request) const;

        /**
         * A Callable wrapper for AssociateDefaultView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::AssociateDefaultViewOutcomeCallable AssociateDefaultViewCallable(const Model::AssociateDefaultViewRequest& request) const;

        /**
         * An Async wrapper for AssociateDefaultView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void AssociateDefaultViewAsync(const Model::AssociateDefaultViewRequest& request, const AssociateDefaultViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Retrieves details about a list of views.

See Also:
   AWS
         * API Reference

         */
        virtual Model::BatchGetViewOutcome BatchGetView(const Model::BatchGetViewRequest& request) const;

        /**
         * A Callable wrapper for BatchGetView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::BatchGetViewOutcomeCallable BatchGetViewCallable(const Model::BatchGetViewRequest& request) const;

        /**
         * An Async wrapper for BatchGetView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void BatchGetViewAsync(const Model::BatchGetViewRequest& request, const BatchGetViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Turns on Amazon Web Services Resource Explorer in the Amazon Web Services
         * Region in which you called this operation by creating an index. Resource
         * Explorer begins discovering the resources in this Region and stores the details
         * about the resources in the index so that they can be queried by using the
         * Search operation. You can create only one index in a Region.

         *
This operation creates only a local index. To promote the local index
         * in one Amazon Web Services Region into the aggregator index for the Amazon Web
         * Services account, use the UpdateIndexType operation. For more
         * information, see Turning
         * on cross-Region search by creating an aggregator index in the Amazon Web
         * Services Resource Explorer User Guide.

For more details about
         * what happens when you turn on Resource Explorer in an Amazon Web Services
         * Region, see Turn
         * on Resource Explorer to index your resources in an Amazon Web Services
         * Region in the Amazon Web Services Resource Explorer User Guide.

         *
If this is the first Amazon Web Services Region in which you've created an
         * index for Resource Explorer, then this operation also creates
         * a service-linked role in your Amazon Web Services account that allows
         * Resource Explorer to enumerate your resources to populate the index.

         *

 Action: resource-explorer-2:CreateIndex

         * Resource: The ARN of the index (as it will exist after the operation
         * completes) in the Amazon Web Services Region and account in which you're trying
         * to create the index. Use the wildcard character (*) at the end of
         * the string to match the eventual UUID. For example, the following
         * Resource element restricts the role or user to creating an index in
         * only the us-east-2 Region of the specified account.

         * "Resource":
         * "arn:aws:resource-explorer-2:us-west-2:<account-id>:index/ *"
         *

Alternatively, you can use "Resource": "*" to allow the
         * role or user to create an index in any Region.

 Action:
         * iam:CreateServiceLinkedRole

 Resource: No specific
         * resource (*).

This permission is required only the first time you create
         * an index to turn on Resource Explorer in the account. Resource Explorer uses
         * this to create the service-linked
         * role needed to index the resources in your account. Resource Explorer uses
         * the same service-linked role for all additional indexes you create
         * afterwards.

See Also:
   AWS
         * API Reference

         */
        virtual Model::CreateIndexOutcome CreateIndex(const Model::CreateIndexRequest& request) const;

        /**
         * A Callable wrapper for CreateIndex that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::CreateIndexOutcomeCallable CreateIndexCallable(const Model::CreateIndexRequest& request) const;

        /**
         * An Async wrapper for CreateIndex that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void CreateIndexAsync(const Model::CreateIndexRequest& request, const CreateIndexResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Creates a view that users can query by using the Search operation.
         * Results from queries that you make using this view include only resources that
         * match the view's Filters. For more information about Amazon Web
         * Services Resource Explorer views, see Managing
         * views in the Amazon Web Services Resource Explorer User Guide.

         *
Only the principals with an IAM identity-based policy that grants
         * Allow to the Search action on a Resource
         * with the Amazon
         * resource name (ARN) of this view can Search using views you create
         * with this operation.

See Also:
   AWS
         * API Reference

         */
        virtual Model::CreateViewOutcome CreateView(const Model::CreateViewRequest& request) const;

        /**
         * A Callable wrapper for CreateView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::CreateViewOutcomeCallable CreateViewCallable(const Model::CreateViewRequest& request) const;

        /**
         * An Async wrapper for CreateView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void CreateViewAsync(const Model::CreateViewRequest& request, const CreateViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Deletes the specified index and turns off Amazon Web Services Resource
         * Explorer in the specified Amazon Web Services Region. When you delete an index,
         * Resource Explorer stops discovering and indexing resources in that Region.
         * Resource Explorer also deletes all views in that Region. These actions occur as
         * asynchronous background tasks. You can check to see when the actions are
         * complete by using the GetIndex operation and checking the
         * Status response value.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DeleteIndexOutcome DeleteIndex(const Model::DeleteIndexRequest& request) const;

        /**
         * A Callable wrapper for DeleteIndex that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DeleteIndexOutcomeCallable DeleteIndexCallable(const Model::DeleteIndexRequest& request) const;

        /**
         * An Async wrapper for DeleteIndex that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DeleteIndexAsync(const Model::DeleteIndexRequest& request, const DeleteIndexResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Deletes the specified view.

If the specified view is the default view
         * for its Amazon Web Services Region, then all Search operations in that
         * Region must explicitly specify the view to use until you configure a new default
         * by calling the AssociateDefaultView operation.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::DeleteViewOutcome DeleteView(const Model::DeleteViewRequest& request) const;

        /**
         * A Callable wrapper for DeleteView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DeleteViewOutcomeCallable DeleteViewCallable(const Model::DeleteViewRequest& request) const;

        /**
         * An Async wrapper for DeleteView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DeleteViewAsync(const Model::DeleteViewRequest& request, const DeleteViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
After you call this operation, the affected Amazon Web Services Region no
         * longer has a default view. All Search operations in that Region must
         * explicitly specify a view or the operation fails. You can configure a new
         * default by calling the AssociateDefaultView operation.

If an
         * Amazon Web Services Region doesn't have a default view configured, then users
         * must explicitly specify a view with every Search operation
         * performed in that Region.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DisassociateDefaultViewOutcome DisassociateDefaultView() const;

        /**
         * A Callable wrapper for DisassociateDefaultView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DisassociateDefaultViewOutcomeCallable DisassociateDefaultViewCallable() const;

        /**
         * An Async wrapper for DisassociateDefaultView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DisassociateDefaultViewAsync(const DisassociateDefaultViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
        /**
         *
Retrieves the Amazon Resource Name (ARN) of the view that is the default for
         * the Amazon Web Services Region in which you call this operation. You can then
         * call GetView to retrieve the details of that view.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::GetDefaultViewOutcome GetDefaultView() const;

        /**
         * A Callable wrapper for GetDefaultView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::GetDefaultViewOutcomeCallable GetDefaultViewCallable() const;

        /**
         * An Async wrapper for GetDefaultView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void GetDefaultViewAsync(const GetDefaultViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
        /**
         *
Retrieves details about the Amazon Web Services Resource Explorer index in
         * the Amazon Web Services Region in which you invoked the operation.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::GetIndexOutcome GetIndex() const;

        /**
         * A Callable wrapper for GetIndex that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::GetIndexOutcomeCallable GetIndexCallable() const;

        /**
         * An Async wrapper for GetIndex that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void GetIndexAsync(const GetIndexResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
        /**
         *
Retrieves details of the specified view.

See Also:
   AWS
         * API Reference

         */
        virtual Model::GetViewOutcome GetView(const Model::GetViewRequest& request) const;

        /**
         * A Callable wrapper for GetView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::GetViewOutcomeCallable GetViewCallable(const Model::GetViewRequest& request) const;

        /**
         * An Async wrapper for GetView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void GetViewAsync(const Model::GetViewRequest& request, const GetViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Retrieves a list of all of the indexes in Amazon Web Services Regions that
         * are currently collecting resource information for Amazon Web Services Resource
         * Explorer.

See Also:
   AWS
         * API Reference

         */
        virtual Model::ListIndexesOutcome ListIndexes(const Model::ListIndexesRequest& request) const;

        /**
         * A Callable wrapper for ListIndexes that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListIndexesOutcomeCallable ListIndexesCallable(const Model::ListIndexesRequest& request) const;

        /**
         * An Async wrapper for ListIndexes that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListIndexesAsync(const Model::ListIndexesRequest& request, const ListIndexesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Retrieves a list of all resource types currently supported by Amazon Web
         * Services Resource Explorer.

See Also:
   AWS
         * API Reference

         */
        virtual Model::ListSupportedResourceTypesOutcome ListSupportedResourceTypes(const Model::ListSupportedResourceTypesRequest& request) const;

        /**
         * A Callable wrapper for ListSupportedResourceTypes that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListSupportedResourceTypesOutcomeCallable ListSupportedResourceTypesCallable(const Model::ListSupportedResourceTypesRequest& request) const;

        /**
         * An Async wrapper for ListSupportedResourceTypes that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListSupportedResourceTypesAsync(const Model::ListSupportedResourceTypesRequest& request, const ListSupportedResourceTypesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Lists the tags that are attached to the specified resource.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::ListTagsForResourceOutcome ListTagsForResource(const Model::ListTagsForResourceRequest& request) const;

        /**
         * A Callable wrapper for ListTagsForResource that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListTagsForResourceOutcomeCallable ListTagsForResourceCallable(const Model::ListTagsForResourceRequest& request) const;

        /**
         * An Async wrapper for ListTagsForResource that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListTagsForResourceAsync(const Model::ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Lists the Amazon
         * resource names (ARNs) of the views available in the Amazon Web Services
         * Region in which you call this operation.

Always check the
         * NextToken response parameter for a null value when
         * calling a paginated operation. These operations can occasionally return an empty
         * set of results even when there are more results available. The
         * NextToken response parameter value is null only
         * when there are no more results to display.

See Also:
   AWS
         * API Reference

         */
        virtual Model::ListViewsOutcome ListViews(const Model::ListViewsRequest& request) const;

        /**
         * A Callable wrapper for ListViews that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListViewsOutcomeCallable ListViewsCallable(const Model::ListViewsRequest& request) const;

        /**
         * An Async wrapper for ListViews that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListViewsAsync(const Model::ListViewsRequest& request, const ListViewsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Searches for resources and displays details about all resources that match
         * the specified criteria. You must specify a query string.

All search
         * queries must use a view. If you don't explicitly specify a view, then Amazon Web
         * Services Resource Explorer uses the default view for the Amazon Web Services
         * Region in which you call this operation. The results are the logical
         * intersection of the results that match both the QueryString
         * parameter supplied to this operation and the SearchFilter parameter
         * attached to the view.

For the complete syntax supported by the
         * QueryString parameter, see Search
         * query syntax reference for Resource Explorer.

If your search results
         * are empty, or are missing results that you think should be there, see Troubleshooting
         * Resource Explorer search.

See Also:
   AWS
         * API Reference

         */
        virtual Model::SearchOutcome Search(const Model::SearchRequest& request) const;

        /**
         * A Callable wrapper for Search that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::SearchOutcomeCallable SearchCallable(const Model::SearchRequest& request) const;

        /**
         * An Async wrapper for Search that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void SearchAsync(const Model::SearchRequest& request, const SearchResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Adds one or more tag key and value pairs to an Amazon Web Services Resource
         * Explorer view or index.

See Also:
   AWS
         * API Reference

         */
        virtual Model::TagResourceOutcome TagResource(const Model::TagResourceRequest& request) const;

        /**
         * A Callable wrapper for TagResource that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::TagResourceOutcomeCallable TagResourceCallable(const Model::TagResourceRequest& request) const;

        /**
         * An Async wrapper for TagResource that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void TagResourceAsync(const Model::TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Removes one or more tag key and value pairs from an Amazon Web Services
         * Resource Explorer view or index.

See Also:
   AWS
         * API Reference

         */
        virtual Model::UntagResourceOutcome UntagResource(const Model::UntagResourceRequest& request) const;

        /**
         * A Callable wrapper for UntagResource that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::UntagResourceOutcomeCallable UntagResourceCallable(const Model::UntagResourceRequest& request) const;

        /**
         * An Async wrapper for UntagResource that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void UntagResourceAsync(const Model::UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Changes the type of the index from one of the following types to the other.
         * For more information about indexes and the role they perform in Amazon Web
         * Services Resource Explorer, see Turning
         * on cross-Region search by creating an aggregator index in the Amazon Web
         * Services Resource Explorer User Guide.

         * AGGREGATOR index type

The index contains information
         * about resources from all Amazon Web Services Regions in the Amazon Web Services
         * account in which you've created a Resource Explorer index. Resource information
         * from all other Regions is replicated to this Region's index.

When you
         * change the index type to AGGREGATOR, Resource Explorer turns on
         * replication of all discovered resource information from the other Amazon Web
         * Services Regions in your account to this index. You can then, from this Region
         * only, perform resource search queries that span all Amazon Web Services Regions
         * in the Amazon Web Services account. Turning on replication from all other
         * Regions is performed by asynchronous background tasks. You can check the status
         * of the asynchronous tasks by using the GetIndex operation. When the
         * asynchronous tasks complete, the Status response of that operation
         * changes from UPDATING to ACTIVE. After that, you can
         * start to see results from other Amazon Web Services Regions in query results.
         * However, it can take several hours for replication from all other Regions to
         * complete.

You can have only one aggregator index per Amazon
         * Web Services account. Before you can promote a different index to be the
         * aggregator index for the account, you must first demote the existing aggregator
         * index to type LOCAL.

         * LOCAL index type

The index contains information about
         * resources in only the Amazon Web Services Region in which the index exists. If
         * an aggregator index in another Region exists, then information in this local
         * index is replicated to the aggregator index.

When you change the index
         * type to LOCAL, Resource Explorer turns off the replication of
         * resource information from all other Amazon Web Services Regions in the Amazon
         * Web Services account to this Region. The aggregator index remains in the
         * UPDATING state until all replication with other Regions
         * successfully stops. You can check the status of the asynchronous task by using
         * the GetIndex operation. When Resource Explorer successfully stops all
         * replication with other Regions, the Status response of that
         * operation changes from UPDATING to ACTIVE. Separately,
         * the resource information from other Regions that was previously stored in the
         * index is deleted within 30 days by another background task. Until that
         * asynchronous task completes, some results from other Regions can continue to
         * appear in search results.

After you demote an aggregator
         * index to a local index, you must wait 24 hours before you can promote another
         * index to be the new aggregator index for the account.

         *

See Also:
   AWS
         * API Reference

         */
        virtual Model::UpdateIndexTypeOutcome UpdateIndexType(const Model::UpdateIndexTypeRequest& request) const;

        /**
         * A Callable wrapper for UpdateIndexType that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::UpdateIndexTypeOutcomeCallable UpdateIndexTypeCallable(const Model::UpdateIndexTypeRequest& request) const;

        /**
         * An Async wrapper for UpdateIndexType that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void UpdateIndexTypeAsync(const Model::UpdateIndexTypeRequest& request, const UpdateIndexTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Modifies some of the details of a view. You can change the filter string and
         * the list of included properties. You can't change the name of the
         * view.

See Also:
   AWS
         * API Reference

         */
        virtual Model::UpdateViewOutcome UpdateView(const Model::UpdateViewRequest& request) const;

        /**
         * A Callable wrapper for UpdateView that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::UpdateViewOutcomeCallable UpdateViewCallable(const Model::UpdateViewRequest& request) const;

        /**
         * An Async wrapper for UpdateView that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void UpdateViewAsync(const Model::UpdateViewRequest& request, const UpdateViewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

      void OverrideEndpoint(const Aws::String& endpoint);
      std::shared_ptr<ResourceExplorer2EndpointProviderBase>& accessEndpointProvider();
    private:
      void init(const ResourceExplorer2ClientConfiguration& clientConfiguration);

      ResourceExplorer2ClientConfiguration m_clientConfiguration;
      std::shared_ptr<Aws::Utils::Threading::Executor> m_executor;
      std::shared_ptr<ResourceExplorer2EndpointProviderBase> m_endpointProvider;
  };

} // namespace ResourceExplorer2
} // namespace Aws


text:
using System.Collections.Generic;

namespace OctoAwesome
{
    /// <summary>
    /// Basisklasse für alle nicht-lebendigen Spielelemente (für lebendige Spielelemente siehe <see cref="Entity"/>
    /// </summary>
    public abstract class Item : IItem
    {
        /// <summary>
        /// Der Zustand des Items
        /// </summary>
        public int Condition { get; set; }

        /// <summary>
        /// Die Koordinate, an der das Item in der Welt herumliegt, falls es nicht im Inventar ist
        /// </summary>
        public Coordinate? Position { get; set; }

        /// <summary>
        /// Die Liste aller Ressourcen, die im Item enthalten sind
        /// </summary>
        public List<IResource> Resources { get; private set; }

        /// <summary>
        /// Erzeugt eine neue Instanz der Klasse Item.
        /// </summary>
        public Item()
        {
            Resources = new List<IResource>();
            Condition = 99;
        }

        /// <summary>
        /// Das was passiert wenn das Item zuschlägt.
        /// </summary>
        /// <param name="item">Das interagierende Item</param>
        public abstract void Hit(IItem item);
    }
}


text:
<?php

namespace BackendBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Mapping\Annotation\Slug;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Class Category
 *
 * @package \BackendBundle\Entity
 *
 * @ORM\Entity
 * @ORM\Table(name="category")
 * @DoctrineAssert\UniqueEntity(
 *     fields={"name"},
 *     errorPath="name",
 *     message="Already exist a Category with this name"
 * )
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string")
     * @Gedmo\Translatable
     * @Assert\Length(min="3", minMessage="The name must have 3 characters or more")
     */
    private $name;

    /**
     * @var string
     *
     * @Slug(fields={"name"})
     * @Gedmo\Translatable
     * @ORM\Column(type="string", unique=true, length=128)
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     * @Gedmo\Translatable
     */
    private $icon;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Business", mappedBy="categories")
     */
    private $businesses;

    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent", cascade={"persist"})
     */
    private $children;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     */
    private $parent;

    /**
     * @var string
     *
     * @Gedmo\Locale
     */
    private $locale;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Subscription", mappedBy="categories")
     */
    private $subscriptions;

    public function __construct()
    {
        $this->businesses = new ArrayCollection();
        $this->children = new ArrayCollection();
        $this->subscriptions = new ArrayCollection();
    }

    public function __toString()
    {
        return $this->name;
    }

    /**
     * Adds a bussiness to this category, for keeping the bidirectional
     * relation
     *
     * @param \BackendBundle\Entity\Business $business
     */
    public function addBusiness(Business $business)
    {
        if (!$this->businesses->contains($business)) {
            $this->businesses->add($business);
        }
    }

    /**
     * Remove bussiness from this category.
     *
     * @param \BackendBundle\Entity\Business $business
     */
    public function removeBusiness(Business $business)
    {
        if ($this->businesses->contains($business)) {
            $this->businesses->add($business);
        }
    }

    public function addChildren(Category $category)
    {
        if (!$this->children->contains($category)) {
            $category->setParent($this);
            $this->children->add($category);
        }
    }

    public function removeChildren(Category $category)
    {
        if ($this->children->contains($category)) {
            $this->children->removeElement($category);
        }
    }

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * @param string $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param string $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * @return ArrayCollection
     */
    public function getBusinesses()
    {
        return $this->businesses;
    }

    /**
     * @param ArrayCollection $businesses
     */
    public function setBusinesses($businesses)
    {
        $this->businesses = $businesses;
    }

    /**
     * @return ArrayCollection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * @param ArrayCollection $children
     */
    public function setChildren($children)
    {
        $this->children = $children;
    }

    /**
     * @return Category
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @param Category $parent
     */
    public function setParent(Category $parent)
    {
        $this->parent = $parent;
    }

    /**
     * @return string
     */
    public function getIcon()
    {
        return $this->icon;
    }

    /**
     * @param string $icon
     */
    public function setIcon($icon)
    {
        $this->icon = $icon;
    }

    /**
     * Add subscriptions
     *
     * @param Subscription $subscriptions
     * @return Category
     */
    public function addSubscription(Subscription $subscriptions)
    {
        if (!$this->subscriptions->contains($subscriptions)) {
            $this->subscriptions[] = $subscriptions;
        }

        return $this;
    }

    /**
     * Remove subscriptions
     *
     * @param Subscription $subscriptions
     */
    public function removeSubscription(Subscription $subscriptions)
    {
        if ($this->subscriptions->contains($subscriptions)) {
            $this->subscriptions->removeElement($subscriptions);
        }
    }

    /**
     * Get subscriptions
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSubscriptions()
    {
        return $this->subscriptions;
    }

    /**
     * @param $locale   string
     */
    public function setTranslatableLocale($locale)
    {
        $this->locale = $locale;
    }
}


text:
package be.trojkasoftware.android.diagramming.gestures;

import be.trojkasoftware.android.diagramming.DiagramDesignerView;
import be.trojkasoftware.android.diagramming.gestures.actions.DoSelectedCommandGestureAction;
import be.trojkasoftware.android.diagramming.gestures.conditions.CheckOnSingleCommandCondition;

//import com.hfk.android.gestures.CheckDistanceFromTouchDownExceedsCondition;
import be.trojkasoftware.android.gestures.CheckNot;
import be.trojkasoftware.android.gestures.DoInvalidateGestureGestureAction;
import be.trojkasoftware.android.gestures.IGestureAction;
import be.trojkasoftware.android.gestures.IGestureCondition;
import be.trojkasoftware.android.gestures.IfThenClause;
import be.trojkasoftware.android.gestures.TouchEvent;
import be.trojkasoftware.android.gestures.TouchGesture;
import be.trojkasoftware.android.gestures.dsl.GestureBuilder;

public class ExecuteCommandGesture extends GestureBuilder<DiagramDesignerView> {

	public ExecuteCommandGesture(DiagramDesignerView view) {
		super(view);
	}

	public TouchGesture create()
	{
		TouchGesture gesture = new TouchGesture("ExecuteCommandGesture");

		this.Create(gesture).TouchDown()
				.If(OnSingleCommand())
					.Do2(nothing())
			.AndNext().CanMove()
				.If(within().milliMeters(2).fromTouchDown(1))
			.AndNext().TouchUp()
				.Do1(ExecuteSelectedCommand())
		;

		return gesture;
	}

	public IGestureCondition OnSingleCommand()
	{
		return new CheckOnSingleCommandCondition(getBase());
	}

	public IGestureAction ExecuteSelectedCommand()
	{
		return new DoSelectedCommandGestureAction(getBase());
	}
}


text:
package distribution

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"

	"github.com/Sirupsen/logrus"
	"github.com/docker/distribution"
	"github.com/docker/distribution/manifest/schema2"
	"github.com/docker/docker/api/types"
	dockerdist "github.com/docker/docker/distribution"
	archive "github.com/docker/docker/pkg/chrootarchive"
	"github.com/docker/docker/reference"
	"github.com/docker/docker/registry"
	"golang.org/x/net/context"
)

// PullData is the plugin config and the rootfs
type PullData interface {
	Config() ([]byte, error)
	Layer() (io.ReadCloser, error)
}

type pullData struct {
	repository distribution.Repository
	manifest   schema2.Manifest
	index      int
}

func (pd *pullData) Config() ([]byte, error) {
	blobs := pd.repository.Blobs(context.Background())
	config, err := blobs.Get(context.Background(), pd.manifest.Config.Digest)
	if err != nil {
		return nil, err
	}
	// validate
	var p types.Plugin
	if err := json.Unmarshal(config, &p); err != nil {
		return nil, err
	}
	return config, nil
}

func (pd *pullData) Layer() (io.ReadCloser, error) {
	if pd.index >= len(pd.manifest.Layers) {
		return nil, io.EOF
	}

	blobs := pd.repository.Blobs(context.Background())
	rsc, err := blobs.Open(context.Background(), pd.manifest.Layers[pd.index].Digest)
	if err != nil {
		return nil, err
	}
	pd.index++
	return rsc, nil
}

// GetRef returns the distribution reference for a given name.
func GetRef(name string) (reference.Named, error) {
	ref, err := reference.ParseNamed(name)
	if err != nil {
		return nil, err
	}
	return ref, nil
}

// GetTag returns the tag associated with the given reference name.
func GetTag(ref reference.Named) string {
	tag := DefaultTag
	if ref, ok := ref.(reference.NamedTagged); ok {
		tag = ref.Tag()
	}
	return tag
}

// Pull downloads the plugin from Store
func Pull(ref reference.Named, rs registry.Service, metaheader http.Header, authConfig *types.AuthConfig) (PullData, error) {
	repoInfo, err := rs.ResolveRepository(ref)
	if err != nil {
		logrus.Debugf("pull.go: error in ResolveRepository: %v", err)
		return nil, err
	}

	if err := dockerdist.ValidateRepoName(repoInfo.Name()); err != nil {
		logrus.Debugf("pull.go: error in ValidateRepoName: %v", err)
		return nil, err
	}

	endpoints, err := rs.LookupPullEndpoints(repoInfo.Hostname())
	if err != nil {
		logrus.Debugf("pull.go: error in LookupPullEndpoints: %v", err)
		return nil, err
	}

	var confirmedV2 bool
	var repository distribution.Repository

	for _, endpoint := range endpoints {
		if confirmedV2 && endpoint.Version == registry.APIVersion1 {
			logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL)
			continue
		}

		// TODO: reuse contexts
		repository, confirmedV2, err = dockerdist.NewV2Repository(context.Background(), repoInfo, endpoint, metaheader, authConfig, "pull")
		if err != nil {
			logrus.Debugf("pull.go: error in NewV2Repository: %v", err)
			return nil, err
		}
		if !confirmedV2 {
			logrus.Debug("pull.go: !confirmedV2")
			return nil, ErrUnsupportedRegistry
		}
		logrus.Debugf("Trying to pull %s from %s %s", repoInfo.Name(), endpoint.URL, endpoint.Version)
		break
	}

	tag := DefaultTag
	if ref, ok := ref.(reference.NamedTagged); ok {
		tag = ref.Tag()
	}

	// tags := repository.Tags(context.Background())
	// desc, err := tags.Get(context.Background(), tag)
	// 	if err != nil {
	// 		return nil, err
	// 	}
	//
	msv, err := repository.Manifests(context.Background())
	if err != nil {
		logrus.Debugf("pull.go: error in repository.Manifests: %v", err)
		return nil, err
	}
	manifest, err := msv.Get(context.Background(), "", distribution.WithTag(tag))
	if err != nil {
		// TODO: change 401 to 404
		logrus.Debugf("pull.go: error in msv.Get(): %v", err)
		return nil, err
	}

	_, pl, err := manifest.Payload()
	if err != nil {
		logrus.Debugf("pull.go: error in manifest.Payload(): %v", err)
		return nil, err
	}
	var m schema2.Manifest
	if err := json.Unmarshal(pl, &m); err != nil {
		logrus.Debugf("pull.go: error in json.Unmarshal(): %v", err)
		return nil, err
	}
	if m.Config.MediaType != schema2.MediaTypePluginConfig &&
		m.Config.MediaType != "application/vnd.docker.plugin.image.v0+json" { //TODO: remove this v0 before 1.13 GA
		return nil, ErrUnsupportedMediaType
	}

	pd := &pullData{
		repository: repository,
		manifest:   m,
	}

	logrus.Debugf("manifest: %s", pl)
	return pd, nil
}

// WritePullData extracts manifest and rootfs to the disk.
func WritePullData(pd PullData, dest string, extract bool) error {
	config, err := pd.Config()
	if err != nil {
		return err
	}
	var p types.Plugin
	if err := json.Unmarshal(config, &p); err != nil {
		return err
	}
	logrus.Debugf("%#v", p)

	if err := os.MkdirAll(dest, 0700); err != nil {
		return err
	}

	if extract {
		if err := ioutil.WriteFile(filepath.Join(dest, "config.json"), config, 0600); err != nil {
			return err
		}

		if err := os.MkdirAll(filepath.Join(dest, "rootfs"), 0700); err != nil {
			return err
		}
	}

	for i := 0; ; i++ {
		l, err := pd.Layer()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		if !extract {
			f, err := os.Create(filepath.Join(dest, fmt.Sprintf("layer%d.tar", i)))
			if err != nil {
				l.Close()
				return err
			}
			io.Copy(f, l)
			l.Close()
			f.Close()
			continue
		}

		if _, err := archive.ApplyLayer(filepath.Join(dest, "rootfs"), l); err != nil {
			return err
		}

	}
	return nil
}


text:
var EventEmitter = (function() {

  function EventEmitter () {
    this._events = {};
  }

  var pt = EventEmitter.prototype;

  var _slice = Array.prototype.slice;

  pt.emit = function(type) {
    var handler;

    handler = this._events[type];

    if (handler == null) {
      return false;
    }

    var data = _slice.call(arguments, 1);

    if(typeof handler === 'function') {
      switch (data.length) {
        // fast cases
        case 0:
          handler.call(this);
          break;
        case 1:
          handler.call(this, data[0]);
          break;
        case 2:
          handler.call(this, data[0], data[1]);
          break;
        // slower
        default:
          handler.apply(this, data);
      }
    }
    else {
      var len = handler.length;
      var listeners = handler.slice();
      for (var i = 0; i < len; i++) {
        listeners[i].apply(this, data);
      }
    }

    return true;
  };

  pt.on = function(type, listener) {
    var handler = this._events[type];

    if(handler == null) {
      this._events[type] = listener;
    }
    else if (typeof handler === 'function') {
      this._events[type] = [handler, listener];
    }
    else {
      this._events[type].push(listener);
    }

    return this;
  };

  pt.once = function(type, listener) {
    var fired = false;

    function g() {
      this.off(type, g);

      if (!fired) {
        fired = true;
        listener.apply(null, arguments);
      }
    }

    this.on(type, g);

    return this;
  };

  pt.off = function(type, listener) {
    switch(arguments.length) {
      // remove all events types
      case 0:
        this._events = {}
        break;
      // remove specific event type
      case 1:
        this._events[type] = null;
        break;
      // remove specific listener
      case 2:
        var list = this._events[type];
        if (list == null) {
          return this;
        }
        else if (list === listener) {
          this._events[type] == null;
        }
        else {
          var len = list.length;
          for(var i = 0; i < len; i++) {
            if (list[i] === listener) {
              if (len === 1) {
                this._events[type] = null;
              }
              else {
                list.splice(i, 1);
              }
            }
          }
        }
    }
    return this;
  }

  EventEmitter.listenerCount = function(emitter, type) {
    var ret;
    if (!emitter._events || !emitter._events[type]) {
      ret = 0;
    }
    else if (typeof emitter._events[type] === 'function') {
      ret = 1;
    }
    else {
      ret = emitter._events[type].length;
    }
    return ret;
  };

  return EventEmitter;
})();


text:
=head1 LICENSE

See the NOTICE file distributed with this work for additional information
regarding copyright ownership.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 NAME

Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsOrthologQM_Alignment_conf

=head1 SYNOPSIS

    init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsOrthologQM_Alignment_conf -host mysql-ens-compara-prod-X -port XXXX \
        -member_type <protein_or_ncrna> -strain_collection <murinae_or_sus>

=head1 DESCRIPTION

This pipeline uses whole genome alignments to calculate the coverage of
homologous pairs for Vertebrates strains. See parent class for additional
information.

=cut

package Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsOrthologQM_Alignment_conf;

use strict;
use warnings;

use base ('Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::OrthologQM_Alignment_conf');

sub default_options {
    my ($self) = @_;
    return {
        %{$self->SUPER::default_options},

        'collection'  => $self->o('strain_collection'),

        'compara_db'  => '#expr( (#member_type# eq "protein") ? "#collection#_ptrees" : "#collection#_nctrees" )expr#',
    };
}

sub pipeline_wide_parameters {
    my ($self) = @_;
    return {
        %{$self->SUPER::pipeline_wide_parameters},

        'collection' => $self->o('collection'),
    }
}

1;


text:
package com.example.pengyuanfan.fablix.movieListAdapter;

import com.example.pengyuanfan.fablix.util.JSONCodeLocator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by pengyuanfan on 5/13/2016.
 */
public class MovieListParser {

    public static void parse(String code, List<MvItemBean> result, MvPage mvPage){
        code= JSONCodeLocator.locate(code);
        try {
            JSONObject  mvL = new JSONObject(code);
            JSONArray mvs = mvL.optJSONArray("movies");
            mvPage.setCurPageS(mvL.getString("curPage"));
            mvPage.setMaxPageS(mvL.getString("maxPage"));
            mvPage.setQuery( mvL.getString("title"));
            for(int i=0;i<mvs.length();i++){
                JSONObject mv=mvs.getJSONObject(i);
                result.add(new MvItemBean(mv.getString("banner_url"),
                                          mv.getString("title"),
                                          mv.getString("dirctor")+" "+mv.getString("year"),
                                          mv.getString("id")));
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}


text:
'use strict';
/**
* nodejs project
*
* @author leo <leo16241022@gmail.com>
*/
import validator from 'validator';

module.exports = function(done){

    $.method('topic.add').check({
      author: {required: true, validate: (v) => validator.isMongoId(String(v))},
      title: {required: true},
      content: {required: true},
      tags: {validate: (v) => Array.isArray(v)},
    });

    $.method('topic.add').register(async function (params) {
      console.log('----------');
      const topic = new $.model.Topic(params);
      console.log('1111111111');
      topic.createdAt = new Date();

      return topic.save();

    });

    $.method('topic.get').check({
      _id: {required: true, validate: (v) => validator.isMongoId(String(v))},
    });
    $.method('topic.get').register(async function (params) {

      return $.model.Topic.findOne({_id: params._id})
      .populate({
        path: 'author',
        model: 'User',
        select: 'nickname about',
      }).populate({
        path: 'comments.author',
        model: 'User',
        select: 'nickname about',
      });
    });

    $.method('topic.list').check({
      author: {validate: (v) => validator.isMongoId(String(v))},
      tags: {validate: (v) => Array.isArray(v)},
      skip: {validate: (v) => v >= 0},
      limit: {validate: (v) => v > 0},
    });
    $.method('topic.list').register(async function (params) {

      const query = {};
      if (params.author) query.author = params.author;
      if (params.tags) query.tags = {$all: params.tags};

      const ret = $.model.Topic.find(query, {
        author: 1,
        title: 1,
        tags: 1,
        createdAt: 1,
        updatedAt: 1,
        lastCommentedAt: 1,
        pageView: 1,
      }).populate({
        path: 'author',
        model: 'User',
        select: 'nickname about',
      });

      if (params.skip) ret.skip(Number(params.skip));
      if (params.limit) ret.limit(Number(params.limit));
      return ret;
    });

    $.method('topic.delete').check({
      _id: {required: true, validate: (v) => validator.isMongoId(String(v))},
    });
    $.method('topic.delete').register(async function (params) {
      return $.model.Topic.remove({_id: params._id});
    });

    $.method('topic.update').check({
      _id: {required: true, validate: (v) => validator.isMongoId(String(v))},
      tags: {validate: (v) => Array.isArray(v)},
    });
    $.method('topic.update').register(async function (params) {
      const update = {updatedAt: new Date()};
      if (params.title) update.title = params.title;
      if (params.content) update.content = params.content;
      if (params.tags) update.tags = params.tags;
      return $.model.Topic.update({_id: params._id}, {$set: update});
    });

    $.method('topic.comment.add').check({
      _id: {required: true, validate: (v) => validator.isMongoId(String(v))},
      author: {required: true, validate: (v) => validator.isMongoId(String(v))},
      content: {required: true},
    });
    $.method('topic.comment.add').register(async function (params) {

      const comment = {
        author: params.author,
        content: params.content,
        createdAt: new Date(),
      };

      const topic = await $.method('topic.get').call({_id: params._id});
      if (!topic) throw new Error('帖子不存在!');

      return $.model.Topic.update({_id: params._id}, {
        $push: {comments: comment},
      });
    });

    $.method('topic.comment.delete').check({
      _id: {required: true, validate: (v) => validator.isMongoId(String(v))},
      cid: {required: true, validate: (v) => validator.isMongoId(String(v))},
    });
    $.method('topic.comment.delete').register(async function (params) {

      return $.model.Topic.update({_id: params._id}, {
        $pull: {  comments: {_id: params.cid,}}
      });
    });
  done();
};


text:
/* eslint-disable no-magic-numbers, max-nested-callbacks */
import fs from 'fs';
import path from 'path';
import assert from 'power-assert';
import nock from 'nock';
import {fetchStats, fetchContributions} from '../src';

const fixtureDir = path.resolve('./test/fixtures');

describe('github-contribution-stats', () => {
  let mockSvg = null;
  let mockSvgUnmeasurable = null;
  let mockServer = null;
  before(() => {
    mockSvg = fs.readFileSync(path.join(fixtureDir, 'moqada.svg')).toString();
    mockSvgUnmeasurable = fs.readFileSync(
      path.join(fixtureDir, 'unmeasurable-user.svg')).toString();
  });
  beforeEach(() => {
    mockServer = nock('https://github.com');
  });
  afterEach(() => {
    nock.cleanAll();
  });

  /** @test {fetchStats} */
  describe('fetchStats()', () => {
    beforeEach(() => {
      mockServer
        .get('/users/moqada/contributions')
        .reply(200, mockSvg)
        .get('/users/unmeasurable-user/contributions')
        .reply(200, mockSvgUnmeasurable);
    });

    it('should return valid stats', () => {
      const fixtureFile = fs.readFileSync(path.join(fixtureDir, 'stats-valid-moqada.json'));
      const valid = JSON.parse(fixtureFile.toString());
      return fetchStats('moqada').then(stat => assert.deepEqual(stat, valid));
    });

    it('should return valid stats with summary option', () => {
      const fixtureFile = fs.readFileSync(path.join(fixtureDir, 'stats-valid-moqada.json'));
      const valid = JSON.parse(fixtureFile.toString());
      delete valid.summary;
      return fetchStats('moqada', {summary: false}).then(stat => assert.deepEqual(stat, valid));
    });

    it('should return valid stats with unmeasurable contributions', () => {
      const fixtureFile = fs.readFileSync(
        path.join(fixtureDir, 'stats-valid-unmeasurable-user.json'));
      const valid = JSON.parse(fixtureFile.toString());
      return fetchStats('unmeasurable-user').then(stat => assert.deepEqual(stat, valid));
    });
  });

  /** @test {fetchContributions} */
  describe('fetchContributions()', () => {
    beforeEach(() => {
      mockServer
        .get('/users/moqada/contributions')
        .reply(200, mockSvg);
    });
    it('should return valid contributions', () => {
      const fixtureFile = fs.readFileSync(path.join(fixtureDir, 'contributions-valid-moqada.json'));
      const valid = JSON.parse(fixtureFile.toString());
      return fetchContributions('moqada').then(stat => assert.deepEqual(stat, valid));
    });
  });
});


text:
const replace = require("replace-in-file");
const docusaurusConfig = require("../docusaurus.config")

const CWD = process.cwd();
const docsDir = `${CWD}/docs`;
const versionedDocsDir = `${CWD}/versioned_docs`;
const pagesDir = `${CWD}/src/pages`;

function doReplace(options) {
  replace(options)
    .then((changes) => {
      if (options.dry) {
        console.log("Modified files:");
        console.log(changes.join("\n"));
      }
    })
    .catch((error) => {
      console.error("Error occurred:", error);
    });
}

variablesFrom = []
variablesTo = []
function addVariable(name, value) {
  variablesFrom.push(new RegExp("{{\\s" + name + "\\s}}", "g"))
  variablesTo.push(value)

  variablesFrom.push(new RegExp("{{\\s" + name + "}}", "g"))
  variablesTo.push(value)

  variablesFrom.push(new RegExp("{{" + name + "\\s}}", "g"))
  variablesTo.push(value)

  variablesFrom.push(new RegExp("{{" + name + "}}", "g"))
  variablesTo.push(value)

}

for (const fieldKey in docusaurusConfig.customFields) {
  addVariable("site." + fieldKey, docusaurusConfig.customFields[fieldKey])
}

const options = {
  files: [`${docsDir}/**/*.md`, `${versionedDocsDir}/**/*.md`, `${pagesDir}/*.md`, `${pagesDir}/**/*.md` ],
  from: variablesFrom,
  to: variablesTo,
  dry: false
};

doReplace(options);


text:
/// <reference path="../services/cards.client.service.js" />

'use strict';

angular.module('cards').controller('DailyCardsController', ['$scope', '$stateParams', 'CardsFactory',
	function ($scope, $stateParams, CardsFactory) {

	    //var searchTerm = $stateParams.searchTerm;

	    $scope.doSearch = function (searchTerm) {
	        getSearchResults(searchTerm);
	    };

	    function getSearchResults(searchTerm) {
	        CardsFactory.getDailyMedRecords(searchTerm)
                .success(function (dailyMedRecords) {

                    var processedRecords = [];

                    for (var i = 0; i < dailyMedRecords.results.length; i++) {

                        if (dailyMedRecords.results[i].openfda.spl_set_id) {
                            processedRecords.push(dailyMedRecords.results[i]);
                        }
                    }

                    var totalRecords = processedRecords.length;
                    var remainder = totalRecords % 3;
                    var columnSize = (totalRecords - remainder) / 3;
                    //console.log(remainder > 0 ? 'true' : 'false');

                    var columns = [
                                    {
                                        collection: [],
                                        size: remainder > 0 ? columnSize + 1 : columnSize
                                    },
                                    {
                                        collection: [],
                                        size: remainder > 1 ? columnSize + 1 : columnSize
                                    },
	                                {
	                                    collection: [],
	                                    size: columnSize
                                    }
                                  ];

                    var columnIndex = 0;
                    var currentSize = 0;
                    var fullTitle = '';
                    var fullDescription = '';

                    for (var i = 0; i < processedRecords.length; i++) {
                        fullTitle = '';
                        fullDescription = '';

                        //console.log(processedRecords[i].openfda.generic_name.toString().toLowerCase());

                        //var setId = dailyMedRecords.data[i].setid.toString();

                        if (processedRecords[i].openfda.brand_name)
                        {
                            fullTitle = processedRecords[i].openfda.brand_name.toString() + ' ';
                        }
                        if (processedRecords[i].openfda.generic_name && processedRecords[i].openfda.generic_name.toString().toLowerCase() != processedRecords[i].openfda.brand_name.toString().toLowerCase())
                        {
                            fullTitle += '(' + processedRecords[i].openfda.generic_name + ') ';
                        }
                        if (processedRecords[i].openfda.manufacturer_name)
                        {
                            fullTitle += '[' + processedRecords[i].openfda.manufacturer_name.toString() + ']';
                        }

                        if (processedRecords[i].indications_and_usage && processedRecords[i].indications_and_usage.toString().toLowerCase() != 'INDICATIONS AND USAGE:')
                        {
                            fullDescription = processedRecords[i].indications_and_usage.toString();
                        }
                        if (fullDescription.length == 0 && processedRecords[i].description)
                        {
                            fullDescription = processedRecords[i].description.toString();
                        }

                        columns[columnIndex].collection.push({
                            id: processedRecords[i].openfda.spl_set_id,
                            title: fullTitle,
                            description: fullDescription.substring(0, 300) + '...'
                        });

                        if (currentSize == (columns[columnIndex].size - 1)) {
                            columnIndex++;
                            currentSize = 0;
                        }
                        else
                        {
                            currentSize++;
                        }
                    }

                    $scope.columns = columns;

                    console.log("success getting daily med records");

                })
                .error(function (data, status, headers, config) {
                    console.log("an error occured getting daily med records");
                });

	    }

	    //init();

	    function getDailyMedParagraph(setId, collectionItem)
	    {
	        var p;

	        CardsFactory.getDailyMedRecord(setId)
                .success(function (dailyMedRecord) {

                    var component = dailyMedRecord.document.component[0].structuredBody[0].component;

                    for (var i = 0; i < component.length; i++) {
                        if (component[i].section[0].code[0].$.code == '34067-9') {
                            var description = '';

                            try {
                                if (component[i].section[0].text[0].paragraph.length != undefined)
                                {
                                    for (var j = 0; j < component[i].section[0].text[0].paragraph.length; j++) {
                                        if (typeof(component[i].section[0].text[0].paragraph[j]) != 'string')
                                        {
                                            break;
                                        }
                                        else if (j == 0) {
                                            description += component[i].section[0].text[0].paragraph[j].replace('■', '');
                                        }
                                        else {
                                            description += component[i].section[0].text[0].paragraph[j].replace('■', ';');
                                        }

                                    }
                                }

                                collectionItem.description = description;

                                //Object.getOwnPropertyNames(component[i].section[0]).forEach(function (val, idx, array) {
                                //    console.log(component[i].section[0][val]);
                                //});
                            }
                            catch (err) {
                                console.log("error on " + collectionItem.id + '|' + component[i].section[0].code[0].$.code + '|');

                                //console.log('Error ' + err);
                            }
                        }
                    }

                })
                .error(function (data, status, headers, config) {
                    console.log("an error occured getting a single daily med record");
                });
	    }

	    function extractAllStringsFromJsonObject(jObject)
	    {

	    }

	}
]);


text:
'use strict';

// MODULES //

var isArrayLike = require( 'validate.io-array-like' ),
	isMatrixLike = require( 'validate.io-matrix-like' ),
	isObject = require( 'validate.io-object' ),
	isTypedArrayLike = require( 'validate.io-typed-array-like' );

// FUNCTIONS //

var BETALN = require( './number.js' );

// BETALN FUNCTION //

/**
* FUNCTION: betaln( out, x, y, accessor )
*	Evaluates the natural logarithm of the beta function for each array element using an accessor function.
*
* @param {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} out - output array
* @param {Array} arr - input array
* @param {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number} y - either an array of equal length or a scalar
* @param {Function} accessor - accessor function for accessing array values
* @returns {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array
*/
function betaln( out, arr, y, clbk ) {
	var len = arr.length,
		i,
		arrVal, yVal;

	if ( isMatrixLike( y ) ) {
			throw new Error( 'betaln()::invalid input argument. `y` has to be an array or scalar.' );
	} else if ( isTypedArrayLike( y ) ) {
		if ( len !== y.length ) {
			throw new Error( 'betaln()::invalid input argument. Input arrays must have the same length.' );
		}
		for ( i = 0; i < len; i++ ) {
			arrVal = clbk( arr[ i ], i, 0 );
			if ( typeof arrVal === 'number' ) {
				out[ i ] = BETALN( arrVal, y[ i ] );
			} else {
				out[ i ] = NaN;
			}
		}
	} else if ( isArrayLike( y ) ) {
		if ( len !== y.length ) {
			throw new Error( 'betaln()::invalid input argument. Inputs arrays must have the same length.' );
		}
		if ( !isObject( y[ 0 ] ) ) {
			// Guess that y is a primitive array -> callback does not have to be applied
			for ( i = 0; i < len; i++ ) {
				arrVal = clbk( arr[ i ], i, 0 );
				if ( typeof y[ i ] === 'number' && typeof arrVal === 'number' ) {
					out[ i ] = BETALN( arrVal, y[ i ] );
				} else {
					out[ i ] = NaN;
				}
			}
		} else {
			// y is an object array, too -> callback is applied
			for ( i = 0; i < len; i++ ) {
				arrVal = clbk( arr[ i ], i, 0 );
				yVal = clbk( y[ i ], i, 1 );
				if ( typeof arrVal === 'number' && typeof yVal  === 'number' ) {
					out[ i ] = BETALN( arrVal, yVal );
				} else {
					out[ i ] = NaN;
				}
			}
		}
	} else {
		if ( typeof y === 'number' ) {
			for ( i = 0; i < len; i++ ) {
				arrVal = clbk( arr[ i ], i );
				if ( typeof arrVal === 'number' ) {
					out[ i ] = BETALN( arrVal, y );
				} else {
					out[ i ] = NaN;
				}
			}
		} else {
			for ( i = 0; i < len; i++ ) {
				out[ i ] = NaN;
			}
		}
	}
	return out;
} // end FUNCTION betaln()

// EXPORTS //

module.exports = betaln;


text:
by
{% for author in authors.all %}
{{ author.name }}{% if not forloop.last %}, {% endif %}
{% empty %}
multiple authors
{% endfor %}
{% if is_edited %}
(editor{{ authors.count|pluralize }})
{% endif %}


text:
namespace Atomic
{
    class JSVM;
}

using namespace Atomic;

namespace AtomicPlayer
{

class AtomicPlayerApp : public Application
{
    OBJECT(AtomicPlayerApp);

public:
    /// Construct.
    AtomicPlayerApp(Context* context);

    /// Setup before engine initialization. Verify that a script file has been specified.
    virtual void Setup();
    /// Setup after engine initialization. Load the script and execute its start function.
    virtual void Start();
    /// Cleanup after the main loop. Run the script's stop function if it exists.
    virtual void Stop();

private:

    SharedPtr<JSVM> vm_;

    /// Handle reload start of the script file.
    void HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData);
    /// Handle reload success of the script file.
    void HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData);
    /// Handle reload failure of the script file.
    void HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData);

    void HandleJSError(StringHash eventType, VariantMap& eventData);

    void HandleLogMessage(StringHash eventType, VariantMap& eventData);

    void ReadEngineConfig();

};

}