text:
"""Class to perform under-sampling based on nearmiss methods."""
from __future__ import print_function
from __future__ import division

import warnings

import numpy as np

from collections import Counter

from sklearn.neighbors import NearestNeighbors

from ..base import BaseMulticlassSampler

class NearMiss(BaseMulticlassSampler):
    """Class to perform under-sampling based on NearMiss methods.

    Parameters
    ----------
    ratio : str or float, optional (default='auto')
        If 'auto', the ratio will be defined automatically to balance
        the dataset. Otherwise, the ratio is defined as the number
        of samples in the minority class over the the number of samples
        in the majority class.

    return_indices : bool, optional (default=False)
        Whether or not to return the indices of the samples randomly
        selected from the majority class.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by np.random.

    version : int, optional (default=1)
        Version of the NearMiss to use. Possible values
        are 1, 2 or 3.

    size_ngh : int, optional (default=3)
        Size of the neighbourhood to consider to compute the
        average distance to the minority point samples.

    ver3_samp_ngh : int, optional (default=3)
        NearMiss-3 algorithm start by a phase of re-sampling. This
        parameter correspond to the number of neighbours selected
        create the sub_set in which the selection will be performed.

    n_jobs : int, optional (default=-1)
        The number of threads to open if possible.

    **kwargs : keywords
        Parameter to use for the Nearest Neighbours object.

    Attributes
    ----------
    min_c_ : str or int
        The identifier of the minority class.

    max_c_ : str or int
        The identifier of the majority class.

    stats_c_ : dict of str/int : int
        A dictionary in which the number of occurences of each class is
        reported.

    X_shape_ : tuple of int
        Shape of the data `X` during fitting.

    Notes
    -----
    The methods are based on [1]_.

    The class support multi-classes.

    Examples
    --------

    >>> from collections import Counter
    >>> from sklearn.datasets import make_classification
    >>> from imblearn.under_sampling import NearMiss
    >>> X, y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9],
    ...                            n_informative=3, n_redundant=1, flip_y=0,
    ...                            n_features=20, n_clusters_per_class=1,
    ...                            n_samples=1000, random_state=10)
    >>> print('Original dataset shape {}'.format(Counter(y)))
    Original dataset shape Counter({1: 900, 0: 100})
    >>> nm = NearMiss(random_state=42)
    >>> X_res, y_res = nm.fit_sample(X, y)
    >>> print('Resampled dataset shape {}'.format(Counter(y_res)))
    Resampled dataset shape Counter({0: 100, 1: 100})

    References
    ----------
    .. [1] I. Mani, I. Zhang. "kNN approach to unbalanced data distributions:
       a case study involving information extraction," In Proceedings of
       workshop on learning from imbalanced datasets, 2003.

    """

    def __init__(self, ratio='auto', return_indices=False, random_state=None,
                 version=1, size_ngh=3, ver3_samp_ngh=3, n_jobs=-1, **kwargs):
        super(NearMiss, self).__init__(ratio=ratio)
        self.return_indices = return_indices
        self.random_state = random_state
        self.version = version
        self.size_ngh = size_ngh
        self.ver3_samp_ngh = ver3_samp_ngh
        self.n_jobs = n_jobs
        self.kwargs = kwargs

    def _selection_dist_based(self, X, y, dist_vec, num_samples, key,
                              sel_strategy='nearest'):
        """Select the appropriate samples depending of the strategy selected.

        Parameters
        ----------
        X : ndarray, shape (n_samples, n_features)
            Original samples.

        y : ndarray, shape (n_samples, )
            Associated label to X.

        dist_vec : ndarray, shape (n_samples, )
            The distance matrix to the nearest neigbour.

        num_samples: int
            The desired number of samples to select.

        key : str or int,
            The target class.

        sel_strategy : str, optional (default='nearest')
            Strategy to select the samples. Either 'nearest' or 'farthest'

        Returns
        -------
        X_sel : ndarray, shape (num_samples, n_features)
            Selected samples.

        y_sel : ndarray, shape (num_samples, )
            The associated label.

        idx_sel : ndarray, shape (num_samples, )
            The list of the indices of the selected samples.

        """

        # Compute the distance considering the farthest neighbour
        dist_avg_vec = np.sum(dist_vec[:, -self.size_ngh:], axis=1)

        self.logger.debug('The size of the distance matrix is %s',
                          dist_vec.shape)
        self.logger.debug('The size of the samples that can be selected is %s',
                          X[y == key].shape)

        if dist_vec.shape[0] != X[y == key].shape[0]:
            raise RuntimeError('The samples to be selected do not correspond'
                               ' to the distance matrix given. Ensure that'
                               ' both `X[y == key]` and `dist_vec` are'
                               ' related.')

        # Sort the list of distance and get the index
        if sel_strategy == 'nearest':
            sort_way = False
        elif sel_strategy == 'farthest':
            sort_way = True
        else:
            raise NotImplementedError

        sorted_idx = sorted(range(len(dist_avg_vec)),
                            key=dist_avg_vec.__getitem__,
                            reverse=sort_way)

        # Throw a warning to tell the user that we did not have enough samples
        # to select and that we just select everything
        if len(sorted_idx) < num_samples:
            warnings.warn('The number of the samples to be selected is larger'
                          ' than the number of samples available. The'
                          ' balancing ratio cannot be ensure and all samples'
                          ' will be returned.')

        # Select the desired number of samples
        sel_idx = sorted_idx[:num_samples]

        return (X[y == key][sel_idx], y[y == key][sel_idx],
                np.flatnonzero(y == key)[sel_idx])

    def _sample(self, X, y):
        """Resample the dataset.

        Parameters
        ----------
        X : ndarray, shape (n_samples, n_features)
            Matrix containing the data which have to be sampled.

        y : ndarray, shape (n_samples, )
            Corresponding label for each sample in X.

        Returns
        -------
        X_resampled : ndarray, shape (n_samples_new, n_features)
            The array containing the resampled data.

        y_resampled : ndarray, shape (n_samples_new)
            The corresponding label of `X_resampled`

        idx_under : ndarray, shape (n_samples, )
            If `return_indices` is `True`, a boolean array will be returned
            containing the which samples have been selected.

        """

        # Assign the parameter of the element of this class
        # Check that the version asked is implemented
        if self.version not in [1, 2, 3]:
            raise ValueError('Parameter `version` must be 1, 2 or 3, got'
                             ' {}'.format(self.version))

        # Start with the minority class
        X_min = X[y == self.min_c_]
        y_min = y[y == self.min_c_]

        # All the minority class samples will be preserved
        X_resampled = X_min.copy()
        y_resampled = y_min.copy()

        # Compute the number of cluster needed
        if self.ratio == 'auto':
            num_samples = self.stats_c_[self.min_c_]
        else:
            num_samples = int(self.stats_c_[self.min_c_] / self.ratio)

        # If we need to offer support for the indices
        if self.return_indices:
            idx_under = np.flatnonzero(y == self.min_c_)

        # For each element of the current class, find the set of NN
        # of the minority class
        # Call the constructor of the NN
        nn_obj = NearestNeighbors(n_neighbors=self.size_ngh,
                                  n_jobs=self.n_jobs,
                                  **self.kwargs)

        # Fit the minority class since that we want to know the distance
        # to these point
        nn_obj.fit(X[y == self.min_c_])

        # Loop over the other classes under picking at random
        for key in self.stats_c_.keys():

            # If the minority class is up, skip it
            if key == self.min_c_:
                continue

            # Get the samples corresponding to the current class
            sub_samples_x = X[y == key]
            sub_samples_y = y[y == key]

            if self.version == 1:
                # Find the NN
                dist_vec, idx_vec = nn_obj.kneighbors(
                    sub_samples_x,
                    n_neighbors=self.size_ngh)

                # Select the right samples
                sel_x, sel_y, idx_tmp = self._selection_dist_based(
                    X,
                    y,
                    dist_vec,
                    num_samples,
                    key,
                    sel_strategy='nearest')

            elif self.version == 2:
                # Find the NN
                dist_vec, idx_vec = nn_obj.kneighbors(
                    sub_samples_x,
                    n_neighbors=self.stats_c_[self.min_c_])

                # Select the right samples
                sel_x, sel_y, idx_tmp = self._selection_dist_based(
                    X,
                    y,
                    dist_vec,
                    num_samples,
                    key,
                    sel_strategy='nearest')

            elif self.version == 3:
                # We need a new NN object to fit the current class
                nn_obj_cc = NearestNeighbors(n_neighbors=self.ver3_samp_ngh,
                                             n_jobs=self.n_jobs,
                                             **self.kwargs)
                nn_obj_cc.fit(sub_samples_x)

                # Find the set of NN to the minority class
                dist_vec, idx_vec = nn_obj_cc.kneighbors(X_min)

                # Create the subset containing the samples found during the NN
                # search. Linearize the indexes and remove the double values
                idx_vec = np.unique(idx_vec.reshape(-1))

                # Create the subset
                sub_samples_x = sub_samples_x[idx_vec, :]
                sub_samples_y = sub_samples_y[idx_vec]

                # Compute the NN considering the current class
                dist_vec, idx_vec = nn_obj.kneighbors(
                    sub_samples_x,
                    n_neighbors=self.size_ngh)

                sel_x, sel_y, idx_tmp = self._selection_dist_based(
                    sub_samples_x,
                    sub_samples_y,
                    dist_vec,
                    num_samples,
                    key,
                    sel_strategy='farthest')
            else:
                raise NotImplementedError

            # If we need to offer support for the indices selected
            if self.return_indices:
                idx_under = np.concatenate((idx_under, idx_tmp), axis=0)

            X_resampled = np.concatenate((X_resampled, sel_x), axis=0)
            y_resampled = np.concatenate((y_resampled, sel_y), axis=0)

        self.logger.info('Under-sampling performed: %s', Counter(
            y_resampled))

        # Check if the indices of the samples selected should be returned too
        if self.return_indices:
            # Return the indices of interest
            return X_resampled, y_resampled, idx_under
        else:
            return X_resampled, y_resampled


text:
package de.lessvoid.nifty.examples.lwjgl.defaultcontrolsxml;

import de.lessvoid.nifty.examples.defaultcontrolsxml.WindowExample;
import de.lessvoid.nifty.examples.lwjgl.NiftyExampleLoaderLWJGL3;

/**
 * @author Aaron Mahan <aaron@forerunnergames.com>
 */
public class WindowDemoMain {
  public static void main(final String[] args) {
    NiftyExampleLoaderLWJGL3.run(new WindowExample());
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Humbug\PhpScoper\Scoper;

use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Prophecy\Prophecy\ObjectProphecy;
use function is_a;

/**
 * @covers \Humbug\PhpScoper\Scoper\FileWhitelistScoper
 *
 * @internal
 */
class FileWhitelistScoperTest extends TestCase
{
    use ProphecyTrait;

    /**
     * @var ObjectProphecy<Scoper>
     */
    private ObjectProphecy $decoratedScoperProphecy;

    private Scoper $decoratedScoper;

    protected function setUp(): void
    {
        $this->decoratedScoperProphecy = $this->prophesize(Scoper::class);
        $this->decoratedScoper = $this->decoratedScoperProphecy->reveal();
    }

    public function test_is_a_scoper(): void
    {
        self::assertTrue(is_a(FileWhitelistScoper::class, Scoper::class, true));
    }

    public function test_it_scopes_the_file_contents_with_the_decorated_scoper_if_file_not_whitelisted_and_the_contents_unchanged_when_is_whitelisted(): void
    {
        $whitelistedFilePath = '/path/to/whitelist-file.php';
        $notWhitelistedFilePath = '/path/to/not-file.php';
        $contents = 'Original file content';

        $this->decoratedScoperProphecy
            ->scope($notWhitelistedFilePath, $contents)
            ->willReturn($scopedContents = 'Decorated scoper contents');

        $scoper = new FileWhitelistScoper($this->decoratedScoper, $whitelistedFilePath);

        self::assertSame(
            $scopedContents,
            $scoper->scope($notWhitelistedFilePath, $contents),
        );

        self::assertSame(
            $contents,
            $scoper->scope($whitelistedFilePath, $contents),
        );

        $this->decoratedScoperProphecy->scope(Argument::cetera())->shouldHaveBeenCalledTimes(1);
    }
}


text: from edl import List


text:
Stepik.org has REST API in JSON format. API endpoints are listed on https://stepik.org/api/docs, and you can also make API call there (but this page is limited to `GET` requests).

Stepik.org use the same API for its web front-end (JS app) and its iOS/Android applications. Therefore, almost all the platform features are supported in this API.

All API examples are up to date and working if the build status is `passing`: [![Build Status](https://travis-ci.org/StepicOrg/Stepik-API.svg?branch=master)](https://travis-ci.org/StepicOrg/Stepik-API)

## Flat

Stepik API schema is flat, i.e. there are no nested end-points.

Every request returns a list of objects, even if only one object was requested. This list can contain 0 or more elements.

For example: `https://stepik.org/api/courses/1` returns not a single course, but a list with single course.

## Pagination

All responses to `GET` requests are paginated. They contain extra `meta` object with the information about pagination. It may look like this:
```
{
    meta: {
        page: 1,
        has_next: true,
        has_previous: false
    },
    requested_objects: [...]
}
```

If the next page exists, then it can be requested using get parameter `?page=...`. By default, if no parameter is given, it's equal to 1.

For example: `https://stepik.org/api/courses` is equal to `https://stepik.org/api/courses?page=1`. Next page: `https://stepik.org/api/courses?page=2` and so on.

Usual page size is equal to 20 elements, but it can vary due to API endpoint, user's permissions etc. We <b>do not recommend to rely on a constant page size</b>.

## Side-Loading

Response may also contain multiple objects, related to the requested object.

For example: for registered user, response from `https://stepik.org/api/courses` also includes user's course `enrollments`.

## OAuth 2

In order to call Stepik.org API as a registered user, you can use this user's OAuth2 keys.
You can get your keys by creating an application on https://stepik.org/oauth2/applications/ (while being logged in), and you can also set `redirect_uri`, `Client type` and `Authorization grant type` there.

Authorization endpoint (Authorization code, Implicit grant; redirect_uri needed): `https://stepik.org/oauth2/authorize/.`

Token endpoint (Authorization code, Password and Client credentials): `https://stepik.org/oauth2/token/`.

#### Client credentials flow

You can then obtain access token using the following client credential flow:

`curl -X POST -d "grant_type=client_credentials" -u"CLIENT_ID:CLIENT_SECRET" https://stepik.org/oauth2/token/`

Response:

`{"access_token": "ACCESS_TOKEN", "scope": "read write", "expires_in": 36000, "token_type": "Bearer"}`

Example with access token:

`curl -H "Authorization: Bearer ACCESS_TOKEN" "https://stepik.org/api/social-accounts?provider=github&uid=1216"`

Response:

`{"meta": {"page": 1, "has_next": false, "has_previous": false}, "social-accounts": []}`

#### Authorization code flow

- Set `grant type = autorization_code` and set `redirect_uri` in your application;
- Redirect user to `https://stepik.org/oauth2/authorize/?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI`;
- User should authenticate or register, and grant permissions to application;
- It redirects to `redirect_uri` and receives the `CODE`;
- Application asks for `ACCESS_TOKEN`: `curl -X POST -d "grant_type=authorization_code&code=CODE&redirect_uri=REDIRECT_URI" -u"CLIENT_ID:SECRET_ID" https://stepik.org/oauth2/token/`;
- Application behaves as user, adding `Authorization: Bearer ACCESS_TOKEN;` to request headers.
- Request to `https://stepik.org/api/stepics/1` returns the current user.

## Multiple IDs Calls

You can request multiple objects using the single API call by using `?ids[]=2&ids[]=3...`.

For example: to get courses with IDs = `2`, `67`, `76` and `70`; you can to call `https://stepik.org/api/courses?ids[]=2&ids[]=67&ids[]=76&ids[]=70`.

This syntax is supported by all API endpoints.

Don't make calls with large size of `ids[]`. Such calls may be rejected by the server because of a large HTTP header.

## Examples

#### Simple operations:

- OAuth authorization example: [oauth_auth_example.py](/examples/oauth_auth_example.py)

#### Complete examples:

* VideoDownloader: [stepik-oauth2-videodownloader](https://github.com/StepicOrg/stepic-oauth2-videodownloader)
* iOS app: [Stepik iOS app](https://github.com/StepicOrg/stepic-ios)
* Android app: [Stepik Android app](https://github.com/StepicOrg/stepic-android)
* Code Challenge submitter: [submitter.py](https://github.com/StepicOrg/SubmissionUtility/blob/master/submitter.py)
* Video uploading (C#): [CoursePublishing](https://github.com/okulovsky/CoursePublishing/tree/master/Publishing/Stepic)
* PyCharm Edu & IntelliJ integration: [intellij-community](https://github.com/JetBrains/intellij-community/tree/7e16c042a19767d5f548c84f88cc5edd5f9d1721/python/educational-core/student/src/com/jetbrains/edu/learning/stepic)
* IntelliJ Plugin for Code Challenges: [intellij-plugins](https://github.com/StepicOrg/intellij-plugins)


text:
A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.
## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**key** | **String** | key is the label key that the selector applies to. |
**operator** | **String** | operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. |
**values** | **List<String>** | values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. |  [optional]


text:
package com.codahale.gpgj;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(Theories.class)
public class RoundTripTest {
    @DataPoints
    public static MasterKeyGenerator[] MASTER_GENERATORS = {
            DsaKeyGenerator.dsa1024(),
            DsaKeyGenerator.dsa2048(),
            DsaKeyGenerator.dsa3072(),
            RsaKeyGenerator.rsa1024(),
            RsaKeyGenerator.rsa2048(),
    };

    @DataPoints
    public static SubKeyGenerator[] SUB_GENERATORS = {
            ElgamalKeyGenerator.elgamal1536(),
            ElgamalKeyGenerator.elgamal2048(),
            ElgamalKeyGenerator.elgamal4096(),
            RsaKeyGenerator.rsa1024(),
            RsaKeyGenerator.rsa2048(),
    };

    private static ExecutorService THREAD_POOL;

    @BeforeClass
    public static void setUp() throws Exception {
        THREAD_POOL = Executors.newFixedThreadPool(8);
    }

    @AfterClass
    public static void tearDown() throws Exception {
        THREAD_POOL.shutdown();
    }

    @Theory
    public void roundTripsAMessage(MasterKeyGenerator masterGenerator,
                                   SubKeyGenerator subKeyGenerator) throws Exception {
        final KeySetGenerator generator = new KeySetGenerator(new SecureRandom(),
                                                              THREAD_POOL,
                                                              masterGenerator,
                                                              subKeyGenerator,
                                                              SymmetricAlgorithm.AES_128);
        final KeySet keySet = generator.generate("one", "yay".toCharArray());
        final UnlockedKeySet unlockedKeySet = keySet.unlock("yay".toCharArray());

        final MessageWriter writer = new MessageWriter(unlockedKeySet,
                                                       Arrays.asList(keySet),
                                                       new SecureRandom());
        final byte[] encrypted = writer.write("oh hello".getBytes(StandardCharsets.US_ASCII));

        final MessageReader reader = new MessageReader(keySet, unlockedKeySet);
        final byte[] decrypted = reader.read(encrypted);

        assertThat(new String(decrypted, StandardCharsets.US_ASCII))
                .isEqualTo("oh hello");
    }
}


text:
package com.github.tomakehurst.wiremock.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.tomakehurst.wiremock.common.xml.Xml;
import com.github.tomakehurst.wiremock.http.ContentTypeHeader;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;

import java.net.URI;
import java.util.List;
import java.util.Map;

import static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;
import static com.github.tomakehurst.wiremock.common.TextType.JSON;
import static com.google.common.collect.Iterables.any;
import static java.util.Arrays.asList;
import static org.apache.commons.lang3.StringUtils.substringAfterLast;

public class ContentTypes {

    private static final Map<String, String> COMMON_MIME_TYPES = ImmutableMap.<String, String>builder()
        .put("image/jpeg",      "jpeg")
        .put("image/gif",       "gif")
        .put("image/tiff",      "tiff")
        .put("image/png",       "png")
        .put("image/x-icon",    "ico")
        .put("image/svg+xml",   "svg")
        .put("audio/x-aiff",    "aiff")
        .put("video/x-ms-asf",  "asf")
        .put("video/mpeg",      "mp2")
        .put("audio/mpeg",      "mp3")
        .put("video/quicktime", "mov")
        .put("application/pdf", "pdf")
        .build();

    public static final List<String> TEXT_FILE_EXTENSIONS = asList(
        "txt",
        "json",
        "xml",
        "html",
        "htm",
        "yaml",
        "csv"
    );

    public static final List<String> TEXT_MIME_TYPE_PATTERNS = asList(
        ".*text.*",
        ".*json.*",
        ".*xml.*",
        ".*html.*",
        ".*yaml.*",
        ".*csv.*",
        ".*x-www-form-urlencoded.*"
    );

    public static String determineFileExtension(String url, ContentTypeHeader contentTypeHeader, byte[] responseBody) {
        if (contentTypeHeader.isPresent()) {
            if (contentTypeHeader.mimeTypePart().contains("json")) {
                return "json";
            }
            if (contentTypeHeader.mimeTypePart().contains("xml")) {
                return "xml";
            }
            if (contentTypeHeader.mimeTypePart().contains("text")) {
                return "txt";
            }

            String extension = COMMON_MIME_TYPES.get(contentTypeHeader.mimeTypePart());
            if (extension != null) {
                return extension;
            }
        }

        String path = URI.create(url).getPath();
        String lastPathSegment = substringAfterLast(path, "/");
        if (lastPathSegment.indexOf('.') != -1) {
            return substringAfterLast(lastPathSegment, ".");
        }

        return determineTextFileExtension(stringFromBytes(responseBody, contentTypeHeader.charset()));
    }

    public static TextType determineTextType(String content) {
        try {
            Json.read(content, JsonNode.class);
            return JSON;
        } catch (Exception e) {
            try {
                Xml.read(content);
                return TextType.XML;
            } catch (Exception e1) {
                return TextType.PLAIN_TEXT;
            }
        }
    }

    public static String determineTextFileExtension(String content) {
        TextType textType = determineTextType(content);
        switch(textType) {
            case JSON:
                return "json";
            case XML:
                return "xml";
            default:
                return "txt";
        }
    }

    public static boolean determineIsTextFromExtension(String extension) {
        return TEXT_FILE_EXTENSIONS.contains(extension);
    }

    public static boolean determineIsTextFromMimeType(final String mimeType) {
        return any(TEXT_MIME_TYPE_PATTERNS, new Predicate<String>() {
            @Override
            public boolean apply(String pattern) {
                return mimeType != null && mimeType.matches(pattern);
            }
        });
    }

    public static boolean determineIsText(String extension, String mimeType) {
        return determineIsTextFromExtension(extension) || determineIsTextFromMimeType(mimeType);
    }
}


text:
package com.example.coolweather.util;

/**
 * Created by dengm on 17-3-20.
 */

public interface HttpCallBacklistener{
    void onError(Exception e);
    void onFinish(String response);
}


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

package com.google.api.services.dialogflow.v2beta1.model;

/**
 * A knowledge document to be used by a KnowledgeBase. For more information, see the [knowledge base
 * guide](https://cloud.google.com/dialogflow/docs/how/knowledge-bases). Note: The
 * `projects.agent.knowledgeBases.documents` resource is deprecated; only use
 * `projects.knowledgeBases.documents`.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2beta1Document extends com.google.api.client.json.GenericJson {

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types. Note: This field is in the process of being deprecated, please use raw_content
   * instead.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String content;

  /**
   * The URI where the file content is located. For documents stored in Google Cloud Storage, these
   * URIs must have the form `gs:`. NOTE: External URLs must correspond to public webpages, i.e.,
   * they must be indexed by Google Search. In particular, URLs for showing documents in Google
   * Cloud Storage (i.e. the URL in your browser) are not supported. Instead use the `gs://` format
   * URI described above.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String contentUri;

  /**
   * Required. The display name of the document. The name must be 1024 bytes or less; otherwise, the
   * creation request fails.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String displayName;

  /**
   * Optional. If true, we try to automatically reload the document every day (at a time picked by
   * the system). If false or unspecified, we don't try to automatically reload the document.
   * Currently you can only enable automatic reload for documents sourced from a public url, see
   * `source` field for the source types. Reload status can be tracked in `latest_reload_status`. If
   * a reload fails, we will keep the document unchanged. If a reload fails with internal errors,
   * the system will try to reload the document on the next day. If a reload fails with non-
   * retriable errors (e.g. PERMISSION_DENIED), the system will not try to reload the document
   * anymore. You need to manually reload the document successfully by calling `ReloadDocument` and
   * clear the errors.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean enableAutoReload;

  /**
   * Required. The knowledge type of document content.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> knowledgeTypes;

  /**
   * Output only. The time and status of the latest reload. This reload may have been triggered
   * automatically or manually and may not have succeeded.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudDialogflowV2beta1DocumentReloadStatus latestReloadStatus;

  /**
   * Optional. Metadata for the document. The metadata supports arbitrary key-value pairs. Suggested
   * use cases include storing a document's title, an external URL distinct from the document's
   * content_uri, etc. The max size of a `key` or a `value` of the metadata is 1024 bytes.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> metadata;

  /**
   * Required. The MIME type of this document.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String mimeType;

  /**
   * Optional. The document resource name. The name must be empty when creating a document. Format:
   * `projects//locations//knowledgeBases//documents/`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String rawContent;

  /**
   * Output only. The current state of the document.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String state;

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types. Note: This field is in the process of being deprecated, please use raw_content
   * instead.
   * @return value or {@code null} for none
   */
  public java.lang.String getContent() {
    return content;
  }

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types. Note: This field is in the process of being deprecated, please use raw_content
   * instead.
   * @param content content or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setContent(java.lang.String content) {
    this.content = content;
    return this;
  }

  /**
   * The URI where the file content is located. For documents stored in Google Cloud Storage, these
   * URIs must have the form `gs:`. NOTE: External URLs must correspond to public webpages, i.e.,
   * they must be indexed by Google Search. In particular, URLs for showing documents in Google
   * Cloud Storage (i.e. the URL in your browser) are not supported. Instead use the `gs://` format
   * URI described above.
   * @return value or {@code null} for none
   */
  public java.lang.String getContentUri() {
    return contentUri;
  }

  /**
   * The URI where the file content is located. For documents stored in Google Cloud Storage, these
   * URIs must have the form `gs:`. NOTE: External URLs must correspond to public webpages, i.e.,
   * they must be indexed by Google Search. In particular, URLs for showing documents in Google
   * Cloud Storage (i.e. the URL in your browser) are not supported. Instead use the `gs://` format
   * URI described above.
   * @param contentUri contentUri or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setContentUri(java.lang.String contentUri) {
    this.contentUri = contentUri;
    return this;
  }

  /**
   * Required. The display name of the document. The name must be 1024 bytes or less; otherwise, the
   * creation request fails.
   * @return value or {@code null} for none
   */
  public java.lang.String getDisplayName() {
    return displayName;
  }

  /**
   * Required. The display name of the document. The name must be 1024 bytes or less; otherwise, the
   * creation request fails.
   * @param displayName displayName or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setDisplayName(java.lang.String displayName) {
    this.displayName = displayName;
    return this;
  }

  /**
   * Optional. If true, we try to automatically reload the document every day (at a time picked by
   * the system). If false or unspecified, we don't try to automatically reload the document.
   * Currently you can only enable automatic reload for documents sourced from a public url, see
   * `source` field for the source types. Reload status can be tracked in `latest_reload_status`. If
   * a reload fails, we will keep the document unchanged. If a reload fails with internal errors,
   * the system will try to reload the document on the next day. If a reload fails with non-
   * retriable errors (e.g. PERMISSION_DENIED), the system will not try to reload the document
   * anymore. You need to manually reload the document successfully by calling `ReloadDocument` and
   * clear the errors.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getEnableAutoReload() {
    return enableAutoReload;
  }

  /**
   * Optional. If true, we try to automatically reload the document every day (at a time picked by
   * the system). If false or unspecified, we don't try to automatically reload the document.
   * Currently you can only enable automatic reload for documents sourced from a public url, see
   * `source` field for the source types. Reload status can be tracked in `latest_reload_status`. If
   * a reload fails, we will keep the document unchanged. If a reload fails with internal errors,
   * the system will try to reload the document on the next day. If a reload fails with non-
   * retriable errors (e.g. PERMISSION_DENIED), the system will not try to reload the document
   * anymore. You need to manually reload the document successfully by calling `ReloadDocument` and
   * clear the errors.
   * @param enableAutoReload enableAutoReload or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setEnableAutoReload(java.lang.Boolean enableAutoReload) {
    this.enableAutoReload = enableAutoReload;
    return this;
  }

  /**
   * Required. The knowledge type of document content.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getKnowledgeTypes() {
    return knowledgeTypes;
  }

  /**
   * Required. The knowledge type of document content.
   * @param knowledgeTypes knowledgeTypes or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setKnowledgeTypes(java.util.List<java.lang.String> knowledgeTypes) {
    this.knowledgeTypes = knowledgeTypes;
    return this;
  }

  /**
   * Output only. The time and status of the latest reload. This reload may have been triggered
   * automatically or manually and may not have succeeded.
   * @return value or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1DocumentReloadStatus getLatestReloadStatus() {
    return latestReloadStatus;
  }

  /**
   * Output only. The time and status of the latest reload. This reload may have been triggered
   * automatically or manually and may not have succeeded.
   * @param latestReloadStatus latestReloadStatus or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setLatestReloadStatus(GoogleCloudDialogflowV2beta1DocumentReloadStatus latestReloadStatus) {
    this.latestReloadStatus = latestReloadStatus;
    return this;
  }

  /**
   * Optional. Metadata for the document. The metadata supports arbitrary key-value pairs. Suggested
   * use cases include storing a document's title, an external URL distinct from the document's
   * content_uri, etc. The max size of a `key` or a `value` of the metadata is 1024 bytes.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getMetadata() {
    return metadata;
  }

  /**
   * Optional. Metadata for the document. The metadata supports arbitrary key-value pairs. Suggested
   * use cases include storing a document's title, an external URL distinct from the document's
   * content_uri, etc. The max size of a `key` or a `value` of the metadata is 1024 bytes.
   * @param metadata metadata or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setMetadata(java.util.Map<String, java.lang.String> metadata) {
    this.metadata = metadata;
    return this;
  }

  /**
   * Required. The MIME type of this document.
   * @return value or {@code null} for none
   */
  public java.lang.String getMimeType() {
    return mimeType;
  }

  /**
   * Required. The MIME type of this document.
   * @param mimeType mimeType or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setMimeType(java.lang.String mimeType) {
    this.mimeType = mimeType;
    return this;
  }

  /**
   * Optional. The document resource name. The name must be empty when creating a document. Format:
   * `projects//locations//knowledgeBases//documents/`.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Optional. The document resource name. The name must be empty when creating a document. Format:
   * `projects//locations//knowledgeBases//documents/`.
   * @param name name or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types.
   * @see #decodeRawContent()
   * @return value or {@code null} for none
   */
  public java.lang.String getRawContent() {
    return rawContent;
  }

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types.
   * @see #getRawContent()
   * @return Base64 decoded value or {@code null} for none
   *
   * @since 1.14
   */
  public byte[] decodeRawContent() {
    return com.google.api.client.util.Base64.decodeBase64(rawContent);
  }

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types.
   * @see #encodeRawContent()
   * @param rawContent rawContent or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setRawContent(java.lang.String rawContent) {
    this.rawContent = rawContent;
    return this;
  }

  /**
   * The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ
   * knowledge types.
   * @see #setRawContent()
   *
   *

   * The value is encoded Base64 or {@code null} for none.
   *

   *
   * @since 1.14
   */
  public GoogleCloudDialogflowV2beta1Document encodeRawContent(byte[] rawContent) {
    this.rawContent = com.google.api.client.util.Base64.encodeBase64URLSafeString(rawContent);
    return this;
  }

  /**
   * Output only. The current state of the document.
   * @return value or {@code null} for none
   */
  public java.lang.String getState() {
    return state;
  }

  /**
   * Output only. The current state of the document.
   * @param state state or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1Document setState(java.lang.String state) {
    this.state = state;
    return this;
  }

  @Override
  public GoogleCloudDialogflowV2beta1Document set(String fieldName, Object value) {
    return (GoogleCloudDialogflowV2beta1Document) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDialogflowV2beta1Document clone() {
    return (GoogleCloudDialogflowV2beta1Document) super.clone();
  }

}


text:
<?php
require_once dirname(__FILE__) . '/../../../bootstrap.php';

class Elastica_Query_TextTest extends PHPUnit_Framework_TestCase
{
	public function setUp() {
	}

	public function tearDown() {
	}

	public function testToArray() {
		$queryText = 'Nicolas Ruflin';
		$type = 'text_phrase';
		$analyzer = 'myanalyzer';
		$maxExpansions = 12;
		$field = 'test';

		$query = new Elastica_Query_Text();
		$query->setFieldQuery($field, $queryText);
		$query->setFieldType($field, $type);
		$query->setFieldParam($field, 'analyzer', $analyzer);
		$query->setFieldMaxExpansions($field, $maxExpansions);

		$expectedArray = array(
			'text' => array(
				$field => array(
					'query' => $queryText,
					'type' => $type,
					'analyzer' => $analyzer,
					'max_expansions' => $maxExpansions,
				)
			)
		);

		$this->assertEquals($expectedArray, $query->toArray());
	}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IFriends.cs" company="NBusy">
//   Copyright (c) Teoman Soygul. All rights reserved. See License.md in the project root for license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace NBusy.Client.Resources
{
	using System.Collections.Generic;
	using System.Threading.Tasks;

	using NBusy.Client.HttpClient;
	using NBusy.Client.Objects;

	/// <summary>
	/// Provides access to friends of a user.
	/// </summary>
	public interface IFriends
	{
		/// <summary>
		/// Retrieves the friends list for the current user denoted by the access token.
		/// </summary>
		/// <returns>A list of user objects.</returns>
		Task<IHttpResponse<List<User>>> GetFriends();
	}
}


text:
<?php

namespace PHPhotoSuit\Tests\PhotoSuite\Infrastructure\Persistence;

use PHPhotoSuit\PhotoSuite\Domain\HttpUrl;
use PHPhotoSuit\PhotoSuite\Domain\Model\Photo;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoAltCollection;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoId;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoName;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoThumb;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoThumbMode;
use PHPhotoSuit\PhotoSuite\Domain\Model\PhotoThumbSize;
use PHPhotoSuit\PhotoSuite\Domain\Model\ThumbId;
use PHPhotoSuit\PhotoSuite\Domain\Position;
use PHPhotoSuit\PhotoSuite\Domain\ResourceId;
use PHPhotoSuit\PhotoSuite\Infrastructure\Persistence\SqliteConfig;
use PHPhotoSuit\PhotoSuite\Infrastructure\Persistence\SqlitePDORegistry;
use PHPhotoSuit\PhotoSuite\Infrastructure\Persistence\SqlitePhotoRepository;
use PHPhotoSuit\PhotoSuite\Infrastructure\Persistence\SqlitePhotoThumbRepository;

class SqlitePhotoThumbRepositoryTest extends \PHPUnit_Framework_TestCase
{
    /** @var string */
    private $dbPath = __DIR__ . '/database/test.db';
    /** @var SqlitePhotoRepository */
    private $photoRepository;
    /** @var SqlitePhotoThumbRepository */
    private $thumbRepository;
    /** @var PhotoId */
    private $photoId;
    /** @var Photo */
    private $photo;
    /** @var ThumbId */
    private $thumbId;
    /** @var PhotoThumb */
    private $thumb;

    public function setUp()
    {
        file_put_contents($this->dbPath, '');
        $sqliteConfig = new SqliteConfig($this->dbPath);
        $this->photoRepository = new SqlitePhotoRepository($sqliteConfig);
        $this->photoRepository->initialize();
        $this->thumbRepository = new SqlitePhotoThumbRepository($sqliteConfig);
        $this->thumbRepository->initialize();
        $httpUrl = new HttpUrl('http://test');
        $this->photoId = new PhotoId();
        $this->photo = new Photo(
            $this->photoId,
            new ResourceId('test'),
            new PhotoName('test'),
            $httpUrl,
            new PhotoAltCollection(),
            new Position()
        );
        $this->thumbId = new ThumbId();
        $this->thumb = new PhotoThumb(
            $this->thumbId,
            $this->photoId,
            $httpUrl,
            new PhotoThumbSize(1,1)
        );
        $this->photoRepository->save($this->photo);
        $this->thumbRepository->save($this->thumb);
    }

    /**
     * @test
     */
    public function findOneBy()
    {
        $this->assertEquals(
            $this->thumb,
            $this->thumbRepository->findOneBy(
                $this->photoId,
                new PhotoThumbSize(1,1)
            )
        );
        $this->assertNull($this->thumbRepository->findOneBy(
            new PhotoId(),
            new PhotoThumbSize(1,1)
        ));
    }

    /**
     * @test
     */
    public function ensureUniqueThumbId()
    {
        $this->assertNotEquals($this->thumbRepository->ensureUniqueThumbId($this->thumbId), $this->thumbId);
    }

    public function tearDown()
    {
        SqlitePDORegistry::removeInstance($this->dbPath);
        unlink($this->dbPath);
    }
}


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

package com.google.api.services.logging.v2.model;

/**
 * Specifies a set of buckets with arbitrary widths.There are size(bounds) + 1 (= N) buckets. Bucket
 * i has the following boundaries:Upper bound (0 <= i < N-1): boundsi Lower bound (1 <= i < N);
 * boundsi - 1The bounds field must contain at least one element. If bounds has only one element,
 * then there are no finite buckets, and that single element is the common boundary of the overflow
 * and underflow buckets.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Logging API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Explicit extends com.google.api.client.json.GenericJson {

  /**
   * The values must be monotonically increasing.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.Double> bounds;

  /**
   * The values must be monotonically increasing.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.Double> getBounds() {
    return bounds;
  }

  /**
   * The values must be monotonically increasing.
   * @param bounds bounds or {@code null} for none
   */
  public Explicit setBounds(java.util.List<java.lang.Double> bounds) {
    this.bounds = bounds;
    return this;
  }

  @Override
  public Explicit set(String fieldName, Object value) {
    return (Explicit) super.set(fieldName, value);
  }

  @Override
  public Explicit clone() {
    return (Explicit) super.clone();
  }

}


text:
class Project < ApplicationRecord
  has_many :user_projects
  has_many :users, through: :user_projects
  has_many :organizations, through: :users
  has_many :requests
  has_many :comments, through: :requests

  validates :title, presence: true, uniqueness: true

  default_scope {order(created_at: :asc)}

  def user_attributes=(user_attributes)
    user_attributes.values.each do |user_attribute|
      user = User.find_by(email: user_attribute[:email])
      if user
        self.users << user unless self.users.include?(user)
      end
    end
  end

  def increase_request_count
    #this is called in the request model after a new request is created for the project
    self.request_counter += 1
    self.save
  end

  def filtered_requests(status_code)
    if status_code.nil?
      self.requests.order(:request_number)
    elsif status_code == "open"
      self.requests.where(status: 'Open').order(:request_number)
    elsif status_code == "client_submitted"
      self.requests.where(status: 'Client Submitted').order(:request_number)
    elsif status_code == "closed"
      self.requests.where(status: 'Closed').order(:request_number)
    else
      self.requests.order(:request_number)
    end
  end

end


text:
/*
 * hdlcdrv.h  -- HDLC packet radio network driver.
 * The Linux soundcard driver for 1200 baud and 9600 baud packet radio
 * (C) 1996-1998 by Thomas Sailer, HB9JNX/AE4WA
 */

#ifndef _HDLCDRV_H
#define _HDLCDRV_H

/* -------------------------------------------------------------------- */
/*
 * structs for the IOCTL commands
 */

struct hdlcdrv_params {
	int iobase;
	int irq;
	int dma;
	int dma2;
	int seriobase;
	int pariobase;
	int midiiobase;
};

struct hdlcdrv_channel_params {
	int tx_delay;  /* the transmitter keyup delay in 10ms units */
	int tx_tail;   /* the transmitter keyoff delay in 10ms units */
	int slottime;  /* the slottime in 10ms; usually 10 = 100ms */
	int ppersist;  /* the p-persistence 0..255 */
	int fulldup;   /* some driver do not support full duplex, setting */
	               /* this just makes them send even if DCD is on */
};

struct hdlcdrv_old_channel_state {
  	int ptt;
  	int dcd;
  	int ptt_keyed;
};

struct hdlcdrv_channel_state {
 	int ptt;
 	int dcd;
 	int ptt_keyed;
 	unsigned long tx_packets;
 	unsigned long tx_errors;
 	unsigned long rx_packets;
 	unsigned long rx_errors;
};

struct hdlcdrv_ioctl {
	int cmd;
	union {
		struct hdlcdrv_params mp;
		struct hdlcdrv_channel_params cp;
		struct hdlcdrv_channel_state cs;
		struct hdlcdrv_old_channel_state ocs;
		unsigned int calibrate;
		unsigned char bits;
		char modename[128];
		char drivername[32];
	} data;
};

/* -------------------------------------------------------------------- */

/*
 * ioctl values
 */
#define HDLCDRVCTL_GETMODEMPAR       0
#define HDLCDRVCTL_SETMODEMPAR       1
#define HDLCDRVCTL_MODEMPARMASK      2  /* not handled by hdlcdrv */
#define HDLCDRVCTL_GETCHANNELPAR    10
#define HDLCDRVCTL_SETCHANNELPAR    11
#define HDLCDRVCTL_OLDGETSTAT       20
#define HDLCDRVCTL_CALIBRATE        21
#define HDLCDRVCTL_GETSTAT          22

/*
 * these are mainly for debugging purposes
 */
#define HDLCDRVCTL_GETSAMPLES       30
#define HDLCDRVCTL_GETBITS          31

/*
 * not handled by hdlcdrv, but by its depending drivers
 */
#define HDLCDRVCTL_GETMODE          40
#define HDLCDRVCTL_SETMODE          41
#define HDLCDRVCTL_MODELIST         42
#define HDLCDRVCTL_DRIVERNAME       43

/*
 * mask of needed modem parameters, returned by HDLCDRVCTL_MODEMPARMASK
 */
#define HDLCDRV_PARMASK_IOBASE      (1<<0)
#define HDLCDRV_PARMASK_IRQ         (1<<1)
#define HDLCDRV_PARMASK_DMA         (1<<2)
#define HDLCDRV_PARMASK_DMA2        (1<<3)
#define HDLCDRV_PARMASK_SERIOBASE   (1<<4)
#define HDLCDRV_PARMASK_PARIOBASE   (1<<5)
#define HDLCDRV_PARMASK_MIDIIOBASE  (1<<6)

/* -------------------------------------------------------------------- */

#endif /* _HDLCDRV_H */

/* -------------------------------------------------------------------- */


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ec-sink-fund-actions',
  template: `
    <p>
      sink-fund-actions Works!
    </p>
  `,
  styles: []
})
export class SinkFundActionsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

#include "JITServerPch.h"

__declspec(dllexport)
HRESULT JsInitializeJITServer(
    __in UUID* connectionUuid,
    __in_opt void* securityDescriptor,
    __in_opt void* alpcSecurityDescriptor)
{
    RPC_STATUS status;
    RPC_BINDING_VECTOR* bindingVector = NULL;
    UUID_VECTOR uuidVector;

    uuidVector.Count = 1;
    uuidVector.Uuid[0] = connectionUuid;

    status = RpcServerUseProtseqW(
        (RPC_WSTR)L"ncalrpc",
        RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
        alpcSecurityDescriptor);
    if (status != RPC_S_OK)
    {
        return status;
    }

    if (AutoSystemInfo::Data.IsWin8OrLater())
    {
        status = RPCLibrary::Instance->RpcServerRegisterIf3(
            ServerIChakraJIT_v0_0_s_ifspec,
            NULL,
            NULL,
            RPC_IF_AUTOLISTEN,
            RPC_C_LISTEN_MAX_CALLS_DEFAULT,
            (ULONG)-1,
            NULL,
            securityDescriptor);
    }
    else
    {
        status = RpcServerRegisterIf2(
            ServerIChakraJIT_v0_0_s_ifspec,
            NULL,
            NULL,
            RPC_IF_AUTOLISTEN,
            RPC_C_LISTEN_MAX_CALLS_DEFAULT,
            (ULONG)-1,
            NULL);
    }
    if (status != RPC_S_OK)
    {
        return status;
    }

    status = RpcServerInqBindings(&bindingVector);
    if (status != RPC_S_OK)
    {
        return status;
    }

    JITManager::GetJITManager()->SetIsJITServer();
    PageAllocatorPool::Initialize();

    status = RpcEpRegister(
        ServerIChakraJIT_v0_0_s_ifspec,
        bindingVector,
        &uuidVector,
        NULL);
    if (status != RPC_S_OK)
    {
        return status;
    }

    status = RpcBindingVectorFree(&bindingVector);

    if (status != RPC_S_OK)
    {
        return status;
    }

    status = RpcServerListen(1, RPC_C_LISTEN_MAX_CALLS_DEFAULT, FALSE);

    return status;
}

HRESULT
ShutdownCommon()
{
    HRESULT status = RpcMgmtStopServerListening(NULL);
    if (status != RPC_S_OK)
    {
        return status;
    }

    status = RpcServerUnregisterIf(ServerIChakraJIT_v0_0_s_ifspec, NULL, FALSE);

    ServerContextManager::Shutdown();
    PageAllocatorPool::Shutdown();
    return status;
}

HRESULT
ServerShutdown(
    /* [in] */ handle_t binding)
{
    return ShutdownCommon();
}

void
__RPC_USER PTHREADCONTEXT_HANDLE_rundown(__RPC__in PTHREADCONTEXT_HANDLE phContext)
{
    ServerCleanupThreadContext(nullptr, &phContext);
}

void
__RPC_USER PSCRIPTCONTEXT_HANDLE_rundown(__RPC__in PSCRIPTCONTEXT_HANDLE phContext)
{
    ServerCloseScriptContext(nullptr, phContext);
    ServerCleanupScriptContext(nullptr, &phContext);
}

HRESULT
ServerConnectProcessWithProcessHandle(
    handle_t binding,
    HANDLE processHandle,
    intptr_t chakraBaseAddress,
    intptr_t crtBaseAddress
)
{
    DWORD clientPid;
    HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
    if (FAILED(hr))
    {
        return hr;
    }
    HANDLE targetHandle = nullptr;
    // RPC handle marshalling is only available on 8.1+
    if (!DuplicateHandle(GetCurrentProcess(), processHandle, GetCurrentProcess(), &targetHandle, 0, false, DUPLICATE_SAME_ACCESS))
    {
        Assert(UNREACHED);
        return E_ACCESSDENIED;
    }
    return ProcessContextManager::RegisterNewProcess(clientPid, targetHandle, chakraBaseAddress, crtBaseAddress);
}

#if !(WINVER >= _WIN32_WINNT_WINBLUE)
HRESULT
ServerConnectProcess(
    handle_t binding,
    intptr_t chakraBaseAddress,
    intptr_t crtBaseAddress
)
{
    // Should use ServerConnectProcessWithProcessHandle on 8.1+
    if (AutoSystemInfo::Data.IsWin8Point1OrLater())
    {
        Assert(UNREACHED);
        return E_ACCESSDENIED;
    }

    DWORD clientPid;
    HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
    if (FAILED(hr))
    {
        return hr;
    }
    HANDLE targetHandle = nullptr;
    targetHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, clientPid);
    if (!targetHandle)
    {
        Assert(UNREACHED);
        return E_ACCESSDENIED;
    }
    return ProcessContextManager::RegisterNewProcess(clientPid, targetHandle, chakraBaseAddress, crtBaseAddress);
}
#endif

#pragma warning(push)
#pragma warning(disable:6387 28196) // PREFast does not understand the out context can be null here
HRESULT
ServerInitializeThreadContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in ThreadContextDataIDL * threadContextData,
    /* [out] */ __RPC__deref_out_opt PPTHREADCONTEXT_HANDLE threadContextInfoAddress,
    /* [out] */ __RPC__out intptr_t *prereservedRegionAddr,
    /* [out] */ __RPC__out intptr_t *jitThunkAddr)
{
    if (threadContextInfoAddress == nullptr || prereservedRegionAddr == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    *threadContextInfoAddress = nullptr;
    *prereservedRegionAddr = 0;
    *jitThunkAddr = 0;

    ServerThreadContext * contextInfo = nullptr;

    DWORD clientPid;
    HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
    if (FAILED(hr))
    {
        return hr;
    }
    ProcessContext* processContext = ProcessContextManager::GetProcessContext(clientPid);
    if (processContext == nullptr)
    {
        return E_ACCESSDENIED;
    }
    try
    {
        AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory));
        contextInfo = HeapNew(ServerThreadContext, threadContextData, processContext);
        ServerContextManager::RegisterThreadContext(contextInfo);
    }
    catch (Js::OutOfMemoryException)
    {
        if (contextInfo)
        {
            // If we OOM while registering the ThreadContext, we need to free it
            HeapDelete(contextInfo);
        }
        else
        {
            // If we OOM while creating the ThreadContext, then we haven't transfered ownership
            // of the ProcessContext reference, so we must release it here
            processContext->Release();
        }
        return E_OUTOFMEMORY;
    }

    return ServerCallWrapper(contextInfo, [&]()->HRESULT
    {
        if (clientPid != contextInfo->GetRuntimePid())
        {
            return E_ACCESSDENIED;
        }

        *threadContextInfoAddress = (PTHREADCONTEXT_HANDLE)EncodePointer(contextInfo);

#if defined(_CONTROL_FLOW_GUARD)
        if (!PHASE_OFF1(Js::PreReservedHeapAllocPhase))
        {
            *prereservedRegionAddr = (intptr_t)contextInfo->GetPreReservedSectionAllocator()->EnsurePreReservedRegion();
            contextInfo->SetCanCreatePreReservedSegment(*prereservedRegionAddr != 0);
        }
#if !defined(_M_ARM)
        *jitThunkAddr = (intptr_t)contextInfo->GetJITThunkEmitter()->EnsureInitialized();
#endif
#endif

        return hr;
    });
}

HRESULT
ServerInitializeScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in ScriptContextDataIDL * scriptContextData,
    /* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
    /* [out] */ __RPC__deref_out_opt PPSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
    if (scriptContextInfoAddress == nullptr || threadContextInfoAddress == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    *scriptContextInfoAddress = nullptr;
    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);

    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        ServerScriptContext * contextInfo = HeapNew(ServerScriptContext, scriptContextData, threadContextInfo);
        ServerContextManager::RegisterScriptContext(contextInfo);
        *scriptContextInfoAddress = (PSCRIPTCONTEXT_HANDLE)EncodePointer(contextInfo);

#if !FLOATVAR
        // TODO: should move this to ServerInitializeThreadContext, also for the fields in IDL
        XProcNumberPageSegmentImpl::Initialize(contextInfo->IsRecyclerVerifyEnabled(), contextInfo->GetRecyclerVerifyPad());
#endif
        return S_OK;
    });
}
#pragma warning(pop)

HRESULT
ServerCleanupThreadContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__deref_inout_opt PPTHREADCONTEXT_HANDLE threadContextInfoAddress)
{
    if (threadContextInfoAddress == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }
    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(*threadContextInfoAddress);
    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    // This tells the run-time, when it is marshalling the out
    // parameters, that the context handle has been closed normally.
    *threadContextInfoAddress = nullptr;

    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        threadContextInfo->Close();
        ServerContextManager::UnRegisterThreadContext(threadContextInfo);
        return S_OK;
    });
}

HRESULT
ServerUpdatePropertyRecordMap(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
    /* [in] */ __RPC__in_opt BVSparseNodeIDL * updatedPropsBVHead)
{
    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);

    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        typedef ServerThreadContext::BVSparseNode BVSparseNode;
        CompileAssert(sizeof(BVSparseNode) == sizeof(BVSparseNodeIDL));
        threadContextInfo->UpdateNumericPropertyBV((BVSparseNode*)updatedPropsBVHead);

        return S_OK;
    });
}

HRESULT
ServerAddModuleRecordInfo(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
    /* [in] */ unsigned int moduleId,
    /* [in] */ intptr_t localExportSlotsAddr)
{
    ServerScriptContext * serverScriptContext = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);
    if (serverScriptContext == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(serverScriptContext, [&]()->HRESULT
    {
        serverScriptContext->AddModuleRecordInfo(moduleId, localExportSlotsAddr);
        return S_OK;
    });

}

HRESULT
ServerSetWellKnownHostTypeId(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
    /* [in] */ int typeId)
{
    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);

    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        threadContextInfo->SetWellKnownHostTypeId((Js::TypeId)typeId);
        return S_OK;
    });
}

HRESULT
ServerCleanupScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__deref_inout_opt PPSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
    if (scriptContextInfoAddress == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(*scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!scriptContextInfo->IsClosed())
    {
        scriptContextInfo->Close();
        ServerContextManager::UnRegisterScriptContext(scriptContextInfo);
    }

    // This tells the run-time, when it is marshalling the out
    // parameters, that the context handle has been closed normally.
    *scriptContextInfoAddress = nullptr;

    HeapDelete(scriptContextInfo);

    return S_OK;
}

HRESULT
ServerCloseScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(scriptContextInfo, [&]()->HRESULT
    {
#ifdef PROFILE_EXEC
        scriptContextInfo->GetFirstCodeGenProfiler()->ProfilePrint();
#endif
        scriptContextInfo->Close();
        ServerContextManager::UnRegisterScriptContext(scriptContextInfo);

        return S_OK;
    });
}

HRESULT
ServerDecommitInterpreterBufferManager(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
    /* [in] */ boolean asmJsManager)
{
    ServerScriptContext * scriptContext = (ServerScriptContext *)DecodePointer((void*)scriptContextInfoAddress);

    if (scriptContext == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(scriptContext, [&]()->HRESULT
    {
        scriptContext->DecommitEmitBufferManager(asmJsManager != FALSE);
        return S_OK;
    });
}

HRESULT
ServerNewInterpreterThunkBlock(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfo,
    /* [in] */ __RPC__in InterpreterThunkInputIDL * thunkInput,
    /* [out] */ __RPC__out InterpreterThunkOutputIDL * thunkOutput)
{
    memset(thunkOutput, 0, sizeof(InterpreterThunkOutputIDL));

    ServerScriptContext * scriptContext = (ServerScriptContext *)DecodePointer(scriptContextInfo);
    if (scriptContext == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(scriptContext, [&]()->HRESULT
    {
        ServerThreadContext * threadContext = scriptContext->GetThreadContext();

        class AutoLocalAlloc
        {
        public:
            AutoLocalAlloc(ServerThreadContext * threadContext) : localAddress(nullptr), threadContext(threadContext) { }
            ~AutoLocalAlloc()
            {
                if (localAddress)
                {
                    threadContext->GetCodePageAllocators()->FreeLocal(this->localAddress, this->segment);
                }
            }
            char * localAddress;
            void * segment;
            ServerThreadContext * threadContext;
        } localAlloc(threadContext);

        OOPEmitBufferManagerWithLock * emitBufferManager = scriptContext->GetEmitBufferManager(thunkInput->asmJsThunk != FALSE);

        BYTE* runtimeAddress;
        EmitBufferAllocation<SectionAllocWrapper, PreReservedSectionAllocWrapper> * alloc = emitBufferManager->AllocateBuffer(InterpreterThunkEmitter::BlockSize, &runtimeAddress);

        CompileAssert(InterpreterThunkEmitter::BlockSize <= CustomHeap::Page::MaxAllocationSize);
        localAlloc.segment = alloc->allocation->page->segment;

        localAlloc.localAddress = threadContext->GetCodePageAllocators()->AllocLocal((char*)runtimeAddress, InterpreterThunkEmitter::BlockSize, localAlloc.segment);
        if (!localAlloc.localAddress)
        {
            Js::Throw::OutOfMemory();
        }

#if PDATA_ENABLED
        PRUNTIME_FUNCTION pdataStart = {0};
        intptr_t epilogEnd = 0;
#endif
        DWORD thunkCount = 0;

        InterpreterThunkEmitter::FillBuffer(
            threadContext,
            thunkInput->asmJsThunk != FALSE,
            (intptr_t)runtimeAddress,
            InterpreterThunkEmitter::BlockSize,
            (BYTE*)localAlloc.localAddress,
#if PDATA_ENABLED
            &pdataStart,
            &epilogEnd,
#endif
            &thunkCount
        );

        if (!emitBufferManager->CommitBufferForInterpreter(alloc, runtimeAddress, InterpreterThunkEmitter::BlockSize))
        {
            Js::Throw::OutOfMemory();
        }

        // Call to set VALID flag for CFG check
        if (CONFIG_FLAG(OOPCFGRegistration))
        {
            emitBufferManager->SetValidCallTarget(alloc, runtimeAddress, true);
        }

        thunkOutput->thunkCount = thunkCount;
        thunkOutput->mappedBaseAddr = (intptr_t)runtimeAddress;
#if PDATA_ENABLED
        thunkOutput->pdataTableStart = (intptr_t)pdataStart;
        thunkOutput->epilogEndAddr = epilogEnd;
#endif

        return S_OK;
    });
}

#if DBG
HRESULT
ServerIsInterpreterThunkAddr(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
    /* [in] */ intptr_t address,
    /* [in] */ boolean asmjsThunk,
    /* [out] */ __RPC__out boolean * result)
{
    ServerScriptContext * context = (ServerScriptContext*)DecodePointer((void*)scriptContextInfoAddress);

    if (context == nullptr)
    {
        *result = false;
        return RPC_S_INVALID_ARG;
    }
    OOPEmitBufferManagerWithLock * manager = context->GetEmitBufferManager(asmjsThunk != FALSE);
    if (manager == nullptr)
    {
        *result = false;
        return S_OK;
    }

    *result = manager->IsInHeap((void*)address);

    return S_OK;
}
#endif

HRESULT
ServerFreeAllocation(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfo,
    /* [in] */ intptr_t codeAddress)
{
    ServerScriptContext* context = (ServerScriptContext*)DecodePointer(scriptContextInfo);

    if (context == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(context, [&]()->HRESULT
    {
        context->GetCodeGenAllocators()->emitBufferManager.FreeAllocation((void*)codeAddress);
        return S_OK;
    });
}

HRESULT
ServerIsNativeAddr(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfo,
    /* [in] */ intptr_t address,
    /* [out] */ __RPC__out boolean * result)
{
    if (result == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    *result = false;

    ServerThreadContext* context = (ServerThreadContext*)DecodePointer(threadContextInfo);
    if (context == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(context, [&]()->HRESULT
    {
        PreReservedSectionAllocWrapper *preReservedAllocWrapper = context->GetPreReservedSectionAllocator();
        if (preReservedAllocWrapper->IsInRange((void*)address))
        {
            *result = true;
        }
        else if (!context->IsAllJITCodeInPreReservedRegion())
        {
            AutoCriticalSection autoLock(&context->GetCodePageAllocators()->cs);
            *result = context->GetCodePageAllocators()->IsInNonPreReservedPageAllocator((void*)address);
        }
        else
        {
            *result = false;
        }

        return S_OK;
    });
}

HRESULT
ServerSetIsPRNGSeeded(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
    /* [in] */ boolean value)
{
    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    return ServerCallWrapper(scriptContextInfo, [&]()->HRESULT
    {
        scriptContextInfo->SetIsPRNGSeeded(value != FALSE);
        return S_OK;
    });
}

HRESULT
ServerRemoteCodeGen(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
    /* [in] */ __RPC__in CodeGenWorkItemIDL *workItemData,
    /* [out] */ __RPC__out JITOutputIDL *jitData)
{
    memset(jitData, 0, sizeof(JITOutputIDL));

    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }
#if DBG
    size_t serializedRpcDataSize = 0;
    const unsigned char* serializedRpcData = nullptr;
    JITManager::SerializeRPCData(workItemData, &serializedRpcDataSize, &serializedRpcData);
    struct AutoFreeArray
    {
        const byte* arr = nullptr;
        size_t bufferSize = 0;
        ~AutoFreeArray() { HeapDeleteArray(bufferSize, arr); }
    } autoFreeArray;
    autoFreeArray.arr = serializedRpcData;
    autoFreeArray.bufferSize = serializedRpcDataSize;
#endif

    return ServerCallWrapper(scriptContextInfo, [&]() ->HRESULT
    {
        LARGE_INTEGER start_time = { 0 };
        if (PHASE_TRACE1(Js::BackEndPhase))
        {
            QueryPerformanceCounter(&start_time);
        }

        scriptContextInfo->UpdateGlobalObjectThisAddr(workItemData->globalThisAddr);
        ServerThreadContext * threadContextInfo = scriptContextInfo->GetThreadContext();

        AutoReturnPageAllocator autoReturnPageAllocator;
        PageAllocator* pageAllocator = autoReturnPageAllocator.GetPageAllocator();

        NoRecoverMemoryJitArenaAllocator jitArena(L"JITArena", pageAllocator, Js::Throw::OutOfMemory);
#if DBG
        jitArena.SetNeedsDelayFreeList();
#endif
        JITTimeWorkItem * jitWorkItem = Anew(&jitArena, JITTimeWorkItem, workItemData);

        if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
        {
            LARGE_INTEGER freq;
            LARGE_INTEGER end_time;
            QueryPerformanceCounter(&end_time);
            QueryPerformanceFrequency(&freq);

            Output::Print(
                L"BackendMarshalIn - function: %s time:%8.6f mSec\r\n",
                jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
                (((double)((end_time.QuadPart - workItemData->startTime)* (double)1000.0 / (double)freq.QuadPart))) / (1));
            Output::Flush();
        }

#ifdef PROFILE_EXEC
        Js::ScriptContextProfiler* profiler = scriptContextInfo->GetCodeGenProfiler(pageAllocator);
#else
        Js::ScriptContextProfiler* profiler = nullptr;
#endif

#if !FLOATVAR
        if (jitWorkItem->GetWorkItemData()->xProcNumberPageSegment)
        {
            jitData->numberPageSegments = (XProcNumberPageSegment*)midl_user_allocate(sizeof(XProcNumberPageSegment));
            if (!jitData->numberPageSegments)
            {
                return E_OUTOFMEMORY;
            }
            __analysis_assume(jitData->numberPageSegments);

            memcpy_s(jitData->numberPageSegments, sizeof(XProcNumberPageSegment), jitWorkItem->GetWorkItemData()->xProcNumberPageSegment, sizeof(XProcNumberPageSegment));
        }
#endif

        Func::Codegen(
            &jitArena,
            jitWorkItem,
            threadContextInfo,
            scriptContextInfo,
            jitData,
            nullptr,
            nullptr,
            jitWorkItem->GetPolymorphicInlineCacheInfo(),
            scriptContextInfo->GetCodeGenAllocators(),
#if !FLOATVAR
            nullptr, // number allocator
#endif
            profiler,
            true);

#ifdef PROFILE_EXEC
        if (profiler && profiler->IsInitialized())
        {
            profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
        }
#endif

        if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
        {
            LARGE_INTEGER freq;
            LARGE_INTEGER end_time;
            QueryPerformanceCounter(&end_time);
            QueryPerformanceFrequency(&freq);

            Output::Print(
                L"EndBackEndInner - function: %s time:%8.6f mSec\r\n",
                jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
                (((double)((end_time.QuadPart - start_time.QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
            Output::Flush();

        }
        LARGE_INTEGER out_time = { 0 };
        if (PHASE_TRACE1(Js::BackEndPhase))
        {
            QueryPerformanceCounter(&out_time);
            jitData->startTime = out_time.QuadPart;
        }

        Assert(jitData->codeAddress);
        Assert(jitData->codeSize);
        return S_OK;
    });
}

JsUtil::BaseHashSet<ServerThreadContext*, HeapAllocator> ServerContextManager::threadContexts(&HeapAllocator::Instance);
JsUtil::BaseHashSet<ServerScriptContext*, HeapAllocator> ServerContextManager::scriptContexts(&HeapAllocator::Instance);
CriticalSection ServerContextManager::cs;

BaseDictionary<DWORD, ProcessContext*, HeapAllocator> ProcessContextManager::ProcessContexts(&HeapAllocator::Instance);
CriticalSection ProcessContextManager::cs;

HRESULT
ProcessContextManager::RegisterNewProcess(DWORD pid, HANDLE processHandle, intptr_t chakraBaseAddress, intptr_t crtBaseAddress)
{
    AutoCriticalSection autoCS(&cs);
    for (auto iter = ProcessContexts.GetIteratorWithRemovalSupport(); iter.IsValid(); iter.MoveNext())
    {
        ProcessContext* context = iter.CurrentValue();
        // We can delete a ProcessContext if no ThreadContexts refer to it and the process is terminated
        if (!context->HasRef() && WaitForSingleObject(context->processHandle, 0) == WAIT_OBJECT_0)
        {
            iter.RemoveCurrent();
            HeapDelete(context);
        }
    }
    // We cannot register multiple ProcessContexts for a single process
    if (ProcessContexts.ContainsKey(pid))
    {
        Assert(UNREACHED);
        return E_ACCESSDENIED;
    }

    ProcessContext* context = nullptr;
    try
    {
        AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory));

        context = HeapNew(ProcessContext, processHandle, chakraBaseAddress, crtBaseAddress);
        ProcessContexts.Add(pid, context);
    }
    catch (Js::OutOfMemoryException)
    {
        if (context != nullptr)
        {
            // If we OOM while registering the ProcessContext, we should free it
            HeapDelete(context);
        }
        return E_OUTOFMEMORY;
    }

    return S_OK;
}

ProcessContext*
ProcessContextManager::GetProcessContext(DWORD pid)
{
    AutoCriticalSection autoCS(&cs);
    ProcessContext* context = nullptr;
    // It is possible that we don't have a ProcessContext for a pid in case ProcessContext initialization failed,
    // or if the calling process terminated and the ProcessContext was already cleaned up before we got here
    if (ProcessContexts.ContainsKey(pid))
    {
        context = ProcessContexts.Item(pid);
        context->AddRef();
    }
    return context;
}

#ifdef STACK_BACK_TRACE
SList<ServerContextManager::ClosedContextEntry<ServerThreadContext>*, NoThrowHeapAllocator> ServerContextManager::ClosedThreadContextList(&NoThrowHeapAllocator::Instance);
SList<ServerContextManager::ClosedContextEntry<ServerScriptContext>*, NoThrowHeapAllocator> ServerContextManager::ClosedScriptContextList(&NoThrowHeapAllocator::Instance);
#endif

void ServerContextManager::RegisterThreadContext(ServerThreadContext* threadContext)
{
    AutoCriticalSection autoCS(&cs);
    threadContexts.Add(threadContext);
}

void ServerContextManager::UnRegisterThreadContext(ServerThreadContext* threadContext)
{
    AutoCriticalSection autoCS(&cs);
    threadContexts.Remove(threadContext);
    auto iter = scriptContexts.GetIteratorWithRemovalSupport();
    while (iter.IsValid())
    {
        ServerScriptContext* scriptContext = iter.Current().Key();
        if (scriptContext->GetThreadContext() == threadContext)
        {
            if (!scriptContext->IsClosed())
            {
                scriptContext->Close();
            }
            iter.RemoveCurrent();
        }
        iter.MoveNext();
    }
}

void ServerContextManager::RegisterScriptContext(ServerScriptContext* scriptContext)
{
    AutoCriticalSection autoCS(&cs);
    scriptContexts.Add(scriptContext);
}

void ServerContextManager::UnRegisterScriptContext(ServerScriptContext* scriptContext)
{
    AutoCriticalSection autoCS(&cs);
    scriptContexts.Remove(scriptContext);
}

bool ServerContextManager::CheckLivenessAndAddref(ServerScriptContext* context)
{
    AutoCriticalSection autoCS(&cs);
    if (scriptContexts.LookupWithKey(context))
    {
        if (!context->IsClosed() && !context->GetThreadContext()->IsClosed())
        {
            context->AddRef();
            context->GetThreadContext()->AddRef();
            return true;
        }
    }
    return false;
}
bool ServerContextManager::CheckLivenessAndAddref(ServerThreadContext* context)
{
    AutoCriticalSection autoCS(&cs);
    if (threadContexts.LookupWithKey(context))
    {
        if (!context->IsClosed())
        {
            context->AddRef();
            return true;
        }
    }
    return false;
}

template<typename Fn>
HRESULT ServerCallWrapper(ServerThreadContext* threadContextInfo, Fn fn)
{
    MemoryOperationLastError::ClearLastError();
    HRESULT hr = S_OK;
    try
    {
        AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
        AutoReleaseThreadContext autoThreadContext(threadContextInfo);
        hr = fn();
    }
    catch (ContextClosedException&)
    {
        hr = E_ACCESSDENIED;
    }
    catch (Js::OutOfMemoryException)
    {
        hr = E_OUTOFMEMORY;
    }
    catch (Js::StackOverflowException)
    {
        hr = VBSERR_OutOfStack;
    }
    catch (Js::OperationAbortedException)
    {
        hr = E_ABORT;
    }
    catch (...)
    {
        AssertOrFailFastMsg(false, "Unknown exception caught in JIT server call.");
    }

    if (hr == S_OK)
    {
        return MemoryOperationLastError::GetLastError();
    }
    return hr;
}

template<typename Fn>
HRESULT ServerCallWrapper(ServerScriptContext* scriptContextInfo, Fn fn)
{
    try
    {
        AutoReleaseScriptContext autoScriptContext(scriptContextInfo);
        ServerThreadContext* threadContextInfo = scriptContextInfo->GetThreadContext();
        return ServerCallWrapper(threadContextInfo, fn);
    }
    catch (ContextClosedException&)
    {
        return E_ACCESSDENIED;
    }
}