text:
"""Compute the product of two qubit registers using QFT."""

from typing import Optional
import numpy as np

from qiskit.circuit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import PhaseGate
from qiskit.circuit.library.basis_change import QFT

from .multiplier import Multiplier

class RGQFTMultiplier(Multiplier):
    r"""A QFT multiplication circuit to store product of two input registers out-of-place.

    Multiplication in this circuit is implemented using the procedure of Fig. 3 in [1], where
    weighted sum rotations are implemented as given in Fig. 5 in [1]. QFT is used on the output
    register and is followed by rotations controlled by input registers. The rotations
    transform the state into the product of two input registers in QFT base, which is
    reverted from QFT base using inverse QFT.
    As an example, a circuit that performs a modular QFT multiplication on two 2-qubit
    sized input registers with an output register of 2 qubits, is as follows:

    .. parsed-literal::

          a_0: ────────────────────────────────────────■───────■──────■──────■────────────────
                                                       │       │      │      │
          a_1: ─────────■───────■───────■───────■──────┼───────┼──────┼──────┼────────────────
                        │       │       │       │      │       │      │      │
          b_0: ─────────┼───────┼───────■───────■──────┼───────┼──────■──────■────────────────
                        │       │       │       │      │       │      │      │
          b_1: ─────────■───────■───────┼───────┼──────■───────■──────┼──────┼────────────────
               ┌──────┐ │P(4π)  │       │P(2π)  │      │P(2π)  │      │P(π)  │       ┌───────┐
        out_0: ┤0     ├─■───────┼───────■───────┼──────■───────┼──────■──────┼───────┤0      ├
               │  qft │         │P(2π)          │P(π)          │P(π)         │P(π/2) │  iqft │
        out_1: ┤1     ├─────────■───────────────■──────────────■─────────────■───────┤1      ├
               └──────┘                                                              └───────┘

    **References:**

    [1] Ruiz-Perez et al., Quantum arithmetic with the Quantum Fourier Transform, 2017.
    `arXiv:1411.5949 <https://arxiv.org/pdf/1411.5949.pdf>`_

    """

    def __init__(
        self,
        num_state_qubits: int,
        num_result_qubits: Optional[int] = None,
        name: str = "RGQFTMultiplier",
    ) -> None:
        r"""
        Args:
            num_state_qubits: The number of qubits in either input register for
                state :math:`|a\rangle` or :math:`|b\rangle`. The two input
                registers must have the same number of qubits.
            num_result_qubits: The number of result qubits to limit the output to.
                If number of result qubits is :math:`n`, multiplication modulo :math:`2^n` is performed
                to limit the output to the specified number of qubits. Default
                value is ``2 * num_state_qubits`` to represent any possible
                result from the multiplication of the two inputs.
            name: The name of the circuit object.

        """
        super().__init__(num_state_qubits, num_result_qubits, name=name)

        # define the registers
        qr_a = QuantumRegister(num_state_qubits, name="a")
        qr_b = QuantumRegister(num_state_qubits, name="b")
        qr_out = QuantumRegister(self.num_result_qubits, name="out")
        self.add_register(qr_a, qr_b, qr_out)

        # build multiplication circuit
        circuit = QuantumCircuit(*self.qregs, name=name)

        circuit.append(QFT(self.num_result_qubits, do_swaps=False).to_gate(), qr_out[:])

        for j in range(1, num_state_qubits + 1):
            for i in range(1, num_state_qubits + 1):
                for k in range(1, self.num_result_qubits + 1):
                    lam = (2 * np.pi) / (2 ** (i + j + k - 2 * num_state_qubits))
                    circuit.append(
                        PhaseGate(lam).control(2),
                        [qr_a[num_state_qubits - j], qr_b[num_state_qubits - i], qr_out[k - 1]],
                    )

        circuit.append(QFT(self.num_result_qubits, do_swaps=False).inverse().to_gate(), qr_out[:])

        self.append(circuit.to_gate(), self.qubits)


text:
@class XWSearchController;

extern CGFloat const EXT_SEARCH_BAR_HEIGHT;

@interface XWSearchViewController : HWPBaseViewController

@property (nonatomic, strong) XWSearchController *searchController;
@property (nonatomic, strong) UIView *contentView;

@end

@interface XWSearchController : UIViewController

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UISearchController *searchController;

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Ppap;

use Ppap\ParserFactory;

/**
 * Ppap: a postal address parser.
 *
 * @author	Carlos Afonso <carlos.afonso.perez@gmail.com>
 */
class Ppap {
	private $normalizer;

	public function __construct(NormalizerInterface $normalizer = null) {
		if ($normalizer === null)
		{
			$normalizer = new DefaultNormalizer;
		}

		$this->normalizer = $normalizer;
	}

	public function parse($address, $locale) {
		$parser = ParserFactory::createParser($locale);
		return $parser->parse($this->normalizer->normalize($address));
	}

	public function getNormalizer() {
		return $this->normalizer;
	}
}


text:
{% extends "base.html" %} {% block main %}

				<button class="img-btn" id="menu-button"></button>

{{user.first_name}}

 {{user.first_name}}

				{% if user.role == 'admin' %}

<button class="img-btn" id="new-rest">{{ lang['rest_new'] }}</button>

				{% endif %}
				{% if user.role == 'admin' or place.owner == user.key %}

<button class="img-btn" id="edit">{{ lang['rest_edit']}}</button>

				{% endif %}

<button class="img-btn" id="profile">{{lang['my_profile']}}</button>

				{% if place.owner == user.key %}

<button class="img-btn" id="disc_list">{{ lang['discount_list_all']}}</button>

<button class="img-btn" id="change_rest">{{ lang['change_rest']}}</button>

				{% endif %}
				{% if place.owner != user.key %}

<button class="img-btn" id="coupons">{{ lang['my_coupons']}}</button>

<button class="img-btn" id="rate-more">{{ lang['rate_more']}}</button>

<button class="img-btn" id="near-me">{{ lang['near_me']}}</button>

				{% endif %}

<button class="img-btn" id="logout">{{ lang['log_out']}}</button>

{{place.name}}

{{lang['loading']}}...

			{% if place.address %}

{{place.address.street}}, {{place.address.city}} ({{place.address.province}}, {{place.address.country}})

				{% endif %}

				{% if place.phone %}

{{place.phone}}

				{% endif %}

				{% if place.hours %}

{{ lang['rest_opening_hours'] }}:
				{% for h in place.hours %}

					{% if h.weekday == '1' %}
						{{ lang['opening_mon']}}:
					{% elif h.weekday == '2' %}
						{{ lang['opening_tue']}}:
					{% elif h.weekday == '3' %}
						{{ lang['opening_wed']}}:
					{% elif h.weekday == '4' %}
						{{ lang['opening_thu']}}:
					{% elif h.weekday == '5' %}
						{{ lang['opening_fri']}}:
					{% elif h.weekday == '6' %}
						{{ lang['opening_sat']}}:
					{% elif h.weekday == '7' %}
						{{ lang['opening_sun']}}:
					{% endif %}

					{{ '%s-%s'|format(h.open1, h.close1) if h.open1 and h.close1 else lang['rest_closed_wday']}}
					{{ ', %s-%s'|format(h.open2, h.close2) if h.open2 and h.close2 }}

				{% endfor %}

				{% endif %}

				{% if place.days_closed %}

{{ lang['rest_closed'] }}:
					{% for d in place.days_closed %}
						{{ d }}{% if loop.index != loop.length %}, {% endif %}
					{% endfor %}

				{% endif %}

				{% if place.website %}

{{place.website}}

				{% endif %}

				{% if place.email %}

{{place.email}}

				{% endif %}

				Open in Google Maps

{{place.description}}

{% endblock %} {% block scripts %}

{% endblock %}


text:
> Modify the names of the own enumerable properties (keys) of an object.

Bug? Feature request? [Please create an issue](https://github.com/jonschlinkert/rename-keys/issues).

## Quickstart

### [npm](npmjs.org):

```
npm i rename-keys --save
```

### [bower](https://github.com/bower/bower):

```
bower install rename-keys --save
```

## Usage

```js
var rename = require('rename-keys');
rename( object, function );
```

**Arguments**

* `object {Object}`: the object to iterate over.
* `function {Function}`: the function to use to rename each own enumerable property of `object`.

## Example

The object to iterate over:

```js
var pkg = require('./package.json');
```

and this renaming function:

```js
var addDashes = function(str) {
  return '--' + str;
};
console.log(rename(pkg, addDashes));
```
results in:

```js
{ "--name": "rename-keys",
  "--description": "Modify the names of the own enumerable properties (keys) of an object.",
  "--version": "0.1.0",
  "--homepage": "https://github.com/jonschlinkert/rename-keys",
  "--author": {
    "name": "Jon Schlinkert",
    "url": "https://github.com/jonschlinkert"
  } ... }
```

## Authors

**Jon Schlinkert**

+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+ [github/jonschlinkert](https://github.com/jonschlinkert)

## License
Copyright (c) 2014-2015, Jon Schlinkert.
Released under the MIT license


text:
"""
A classifier implementing that performs chained learning averaged over
K distinct orderings of label chains.
"""

__all__ = [
    "KRandomClassifierChains"
]

from joblib import Parallel, delayed
import numpy as np
from numpy.random import RandomState

from ..base.constants import MAX_SEED

from sklearn.base import clone
from sklearn.multioutput import ClassifierChain
from sklearn.metrics import hamming_loss

MAX_INT = MAX_SEED

def _fit_chain(estimator, X, y, **fit_params):
    return estimator.fit(X, y, **fit_params)

def _predict_proba_chain(estimator, X):
    return estimator.predict_proba(X)

class KRandomClassifierChains(object):
    """A meta-estimator which fits `k` random ordered Classifier
    chains and soft-averages prediction probabilities over all chains
    using an un-weighted mean.

    Parameters
    ----------
    base_esimtaors : estimator
        A `Scikit-Learn` estimator supporting `fit`, `predict` and
        `predict_proba`.

    k : int, optional, default: 10
        Number of random chains to train.

    cv : int, cross-validation generator or an iterable, optional, default: None
        Determines whether to use cross validated predictions or true labels
        for the results of previous estimators in the chain. See link below for
        further details.

    n_jobs : int, optional, default: 1
        Number of processes to use when fitting each label.

    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.

        The random number generator is used to generate random chain orders.
        See link below for further details.

    See Also
    --------
    `Classifier Chain <http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.ClassifierChain.html#sklearn.multioutput.ClassifierChain>`_
    """

    def __init__(self, base_estimator, k=10, cv=None, n_jobs=1,
                 random_state=None):
        self.random_state = random_state
        self.base_estimator = base_estimator
        self.cv = cv
        self.n_jobs = n_jobs

        self.rng_ = self._check_random_state(random_state)
        self.k_ = self._check_k(k)
        self.fitted_ = False
        self._set_estimators_reset_fitted()

    def __repr__(self):
        return (
            "KRandomClassifierChains(base_estimator={}, k={}, cv={}, "
            "random_state={})".format(
                self.base_estimator, self.k, self.cv, self.random_state
            )
        )

    def get_params(self, deep=True):
        return {
            "base_estimator": self.base_estimator,
            "k": self.k,
            "cv": self.cv,
            'n_jobs': self.n_jobs,
            "random_state": self.random_state,
        }

    def _set_random_state_of_estimators(self):
        for e in self.estimators_:
            if self.rng_ is None:
                state = None
            else:
                state = self.rng_.randint(MAX_INT)
            e.set_params(**{'random_state': state})

    def set_params(self, **params):
        for key, value in params.items():
            if "__" in key:
                for estimator in self.estimators_:
                    estimator.set_params(**{key: value})
            else:
                if key in self.get_params().keys():
                    if key == 'random_state':
                        setattr(self, 'rng_', self._check_random_state(value))
                        setattr(self, 'random_state', value)
                        self._set_random_state_of_estimators()

                    elif key == "k":
                        self.k = value  # this will also create new estimators

                    elif key == 'base_estimator':
                        self.base_estimator = clone(value)
                        self._set_estimators_reset_fitted()
                    else:
                        setattr(self, key, value)
                else:
                    raise AttributeError(
                        "Invalid param '{}' for class {}.".format(
                            key, self.__class__.__name__
                        )
                    )
        return self

    @property
    def k(self):
        return self.k_

    @k.setter
    def k(self, value):
        self.k_ = self._check_k(value)
        self._set_estimators_reset_fitted()

    def _set_estimators_reset_fitted(self):
        self.estimators_ = [
            ClassifierChain(
                clone(self.base_estimator), order="random",
                cv=self.cv, random_state=None
            )
            for _ in range(self.k_)
        ]
        self._set_random_state_of_estimators()
        self.fitted_ = False

    def _check_fitted(self):
        if not self.fitted_:
            raise ValueError("Please run fit method first.")

    def _check_k(self, k):
        if not isinstance(k, int):
            raise TypeError("k must be an integer.")
        if k <= 0:
            raise ValueError("k must be a positive integer.")
        return int(k)

    def _check_random_state(self, random_state):
        if random_state is None:
            return None
        elif isinstance(random_state, int):
            return RandomState(seed=random_state)
        elif isinstance(random_state, RandomState):
            return random_state
        else:
            raise TypeError("random_state must be None, int or RandomState")

    def _check_y_shape(self, y):
        try:
            if y.shape[1] <= 1:
                raise ValueError(
                    "y must be in multi-label indicator matrix format. "
                    "For binary or multi-class classification use scikit-learn."
                )
        except IndexError:
            raise ValueError(
                "y must be in multi-label indicator matrix format. "
                "For binary or multi-class classification use scikit-learn."
            )

    def fit(self, X, y, **fit_params):
        """
        Fit the model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            Training vector, where n_samples is the number of samples and
            n_features is the number of features.

        y : array-like, shape (n_samples, n_labels)
            Target vector relative to X.

        Returns
        -------
        self : object
            Returns self.
        """
        self._check_y_shape(y)
        self.estimators_ = Parallel(n_jobs=self.n_jobs)(
            delayed(_fit_chain)(estimator, X, y, **fit_params)
            for estimator in self.estimators_
        )
        self.fitted_ = True
        return self

    def predict(self, X):
        """
        Predict class labels for samples in X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = (n_samples, n_features)
            Samples.

        Returns
        -------
        C : array, shape = (n_samples, n_labels)
            Predicted class labels per sample.
        """
        self._check_fitted()
        predictions = (self.predict_proba(X) >= 0.5).astype(int)
        return predictions

    def predict_proba(self, X):
        """
        Probability estimates for each label.

        Parameters
        ----------
        X : array-like, shape = (n_samples, n_features)

        Returns
        -------
        T : array-like, shape = (n_samples, n_labels)
            Returns the probability of the sample for each label in the model,
            where labels are ordered as the indices of 'y' used during fit.
        """
        self._check_fitted()
        probas_ls = np.asarray(Parallel(n_jobs=self.n_jobs)(
            delayed(_predict_proba_chain)(estimator, X)
            for estimator in self.estimators_
        ))
        probas = probas_ls.mean(axis=0)
        return probas

    def score(self, X, y, sample_weight=None, use_proba=False,
              scorer=hamming_loss, **scorer_kwargs):
        """
        Returns the score as determined by `scoring` on the given
        test data and labels.

        In multi-label classification, this is the subset accuracy
        which is a harsh metric since you require for each sample that
        each label set be correctly predicted.

        Parameters
        ----------
        X : array-like, shape = (n_samples, n_features)
            Test samples.

        y : array-like, shape = (n_samples, n_labels)
            True labels for X.

        sample_weight : array-like, shape = [n_samples], optional
            Sample weights.

        use_proba : boolean, default: False
            If True, apply scoring function to probability estimates.

        scorer : function, optional
            The scoring method to apply to predictions.

        scorer_kwargs : dict, optional
            Keyword arguments for scorer.

        Returns
        -------
        `float`
            Mean score of self.predict(X) wrt. y.
        """
        self._check_fitted()
        self._check_y_shape(y)

        if use_proba:
            y_pred = self.predict_proba(X)
        else:
            y_pred = self.predict(X)

        average = scorer_kwargs.get("average", None)
        if average == "binary":
            return np.asarray([
                scorer(
                    y[:, i], y_pred[:, i],
                    sample_weight=sample_weight,
                    **scorer_kwargs
                )
                for i in range(y.shape[1])
            ])
        else:
            return scorer(
                y, y_pred, sample_weight=sample_weight,
                **scorer_kwargs
            )


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SpecimenFilesComponent } from './specimen-files.component';
import {NgxPaginationModule} from 'ngx-pagination';
import {RobustLinkComponent} from '../../shared/robust-link/robust-link.component';
import {HttpClientTestingModule} from '@angular/common/http/testing';

describe('SpecimenFilesComponent', () => {
  let component: SpecimenFilesComponent;
  let fixture: ComponentFixture<SpecimenFilesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SpecimenFilesComponent,
        RobustLinkComponent
      ],
      imports: [
        NgxPaginationModule,
        HttpClientTestingModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SpecimenFilesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>DevMeetings ES6 Application</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.4/simplex/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
    <script src="dist/main.js"></script>
</body>
</html>


text:
<?php
/**
*	This file contains the Conditions Enum class.
*
*	@package	Frozensheep\RightmoveADF
*	@author		Jacob Wyke <jacob@frozensheep.com>
*	@license	MIT
*
*/

namespace Frozensheep\RightmoveADF\Values;

use Frozensheep\RightmoveADF\Values\ValuesBase;

/**
*	Conditions Enum Class
*
*	Class for the different Conditions.
*
*	@package	Frozensheep\RightmoveADF
*
*/
class Conditions extends ValuesBase {

	const Good = 1;
	const SomeWorkNeeded = 2;
	const WorkRequiredThroughout = 3;
	const MajorRenovationRequired = 4;
}


text:
package com.squareup.moshi;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;

import static com.squareup.moshi.Util.jsonAnnotations;

final class AdapterMethodsFactory implements JsonAdapter.Factory {
  private final List<AdapterMethod> toAdapters;
  private final List<AdapterMethod> fromAdapters;

  AdapterMethodsFactory(List<AdapterMethod> toAdapters, List<AdapterMethod> fromAdapters) {
    this.toAdapters = toAdapters;
    this.fromAdapters = fromAdapters;
  }

  @Override public @Nullable JsonAdapter<?> create(
      final Type type, final Set<? extends Annotation> annotations, final Moshi moshi) {
    final AdapterMethod toAdapter = get(toAdapters, type, annotations);
    final AdapterMethod fromAdapter = get(fromAdapters, type, annotations);
    if (toAdapter == null && fromAdapter == null) return null;

    final JsonAdapter<Object> delegate;
    if (toAdapter == null || fromAdapter == null) {
      try {
        delegate = moshi.nextAdapter(this, type, annotations);
      } catch (IllegalArgumentException e) {
        String missingAnnotation = toAdapter == null ? "@ToJson" : "@FromJson";
        throw new IllegalArgumentException("No " + missingAnnotation + " adapter for "
            + type + " annotated " + annotations);
      }
    } else {
      delegate = null;
    }

    if (toAdapter != null) toAdapter.bind(moshi, this);
    if (fromAdapter != null) fromAdapter.bind(moshi, this);

    return new JsonAdapter<Object>() {
      @Override public void toJson(JsonWriter writer, @Nullable Object value) throws IOException {
        if (toAdapter == null) {
          delegate.toJson(writer, value);
        } else if (!toAdapter.nullable && value == null) {
          writer.nullValue();
        } else {
          try {
            toAdapter.toJson(moshi, writer, value);
          } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof IOException) throw (IOException) cause;
            throw new JsonDataException(cause + " at " + writer.getPath(), cause);
          }
        }
      }

      @Override public @Nullable Object fromJson(JsonReader reader) throws IOException {
        if (fromAdapter == null) {
          return delegate.fromJson(reader);
        } else if (!fromAdapter.nullable && reader.peek() == JsonReader.Token.NULL) {
          reader.nextNull();
          return null;
        } else {
          try {
            return fromAdapter.fromJson(moshi, reader);
          } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof IOException) throw (IOException) cause;
            throw new JsonDataException(cause + " at " + reader.getPath(), cause);
          }
        }
      }

      @Override public String toString() {
        return "JsonAdapter" + annotations + "(" + type + ")";
      }
    };
  }

  public static AdapterMethodsFactory get(Object adapter) {
    List<AdapterMethod> toAdapters = new ArrayList<>();
    List<AdapterMethod> fromAdapters = new ArrayList<>();

    for (Class<?> c = adapter.getClass(); c != Object.class; c = c.getSuperclass()) {
      for (Method m : c.getDeclaredMethods()) {
        if (m.isAnnotationPresent(ToJson.class)) {
          AdapterMethod toAdapter = toAdapter(adapter, m);
          AdapterMethod conflicting = get(toAdapters, toAdapter.type, toAdapter.annotations);
          if (conflicting != null) {
            throw new IllegalArgumentException("Conflicting @ToJson methods:\n"
                + "    " + conflicting.method + "\n"
                + "    " + toAdapter.method);
          }
          toAdapters.add(toAdapter);
        }

        if (m.isAnnotationPresent(FromJson.class)) {
          AdapterMethod fromAdapter = fromAdapter(adapter, m);
          AdapterMethod conflicting = get(fromAdapters, fromAdapter.type, fromAdapter.annotations);
          if (conflicting != null) {
            throw new IllegalArgumentException("Conflicting @FromJson methods:\n"
                + "    " + conflicting.method + "\n"
                + "    " + fromAdapter.method);
          }
          fromAdapters.add(fromAdapter);
        }
      }
    }

    if (toAdapters.isEmpty() && fromAdapters.isEmpty()) {
      throw new IllegalArgumentException("Expected at least one @ToJson or @FromJson method on "
          + adapter.getClass().getName());
    }

    return new AdapterMethodsFactory(toAdapters, fromAdapters);
  }

  /**
   * Returns an object that calls a {@code method} method on {@code adapter} in service of
   * converting an object to JSON.
   */
  static AdapterMethod toAdapter(Object adapter, Method method) {
    method.setAccessible(true);
    final Type returnType = method.getGenericReturnType();
    final Type[] parameterTypes = method.getGenericParameterTypes();
    final Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    if (parameterTypes.length >= 2
        && parameterTypes[0] == JsonWriter.class
        && returnType == void.class
        && parametersAreJsonAdapters(2, parameterTypes)) {
      // void pointToJson(JsonWriter jsonWriter, Point point) {
      // void pointToJson(JsonWriter jsonWriter, Point point, JsonAdapter<?> adapter, ...) {
      Set<? extends Annotation> qualifierAnnotations = jsonAnnotations(parameterAnnotations[1]);
      return new AdapterMethod(parameterTypes[1], qualifierAnnotations, adapter, method,
          parameterTypes.length, 2, true) {
        @Override public void toJson(Moshi moshi, JsonWriter writer, @Nullable Object value)
            throws IOException, InvocationTargetException {
          invoke(writer, value);
        }
      };

    } else if (parameterTypes.length == 1 && returnType != void.class) {
      // List<Integer> pointToJson(Point point) {
      final Set<? extends Annotation> returnTypeAnnotations = jsonAnnotations(method);
      Set<? extends Annotation> qualifierAnnotations = jsonAnnotations(parameterAnnotations[0]);
      boolean nullable = Util.hasNullable(parameterAnnotations[0]);
      return new AdapterMethod(parameterTypes[0], qualifierAnnotations, adapter, method,
          parameterTypes.length, 1, nullable) {
        private JsonAdapter<Object> delegate;

        @Override public void bind(Moshi moshi, JsonAdapter.Factory factory) {
          super.bind(moshi, factory);
          delegate = moshi.adapter(returnType, returnTypeAnnotations);
        }

        @Override public void toJson(Moshi moshi, JsonWriter writer, @Nullable Object value)
            throws IOException, InvocationTargetException {
          Object intermediate = invoke(value);
          delegate.toJson(writer, intermediate);
        }
      };

    } else {
      throw new IllegalArgumentException("Unexpected signature for " + method + ".\n"
          + "@ToJson method signatures may have one of the following structures:\n"
          + "    <any access modifier> void toJson(JsonWriter writer, T value) throws <any>;\n"
          + "    <any access modifier> void toJson(JsonWriter writer,"
          + " JsonAdapter<any> delegate, <any more delegates>) throws <any>;\n"
          + "    <any access modifier> void toJson(JsonWriter writer, T value"
          + " JsonAdapter<any> delegate, <any more delegates>) throws <any>;\n"
          + "    <any access modifier> R toJson(T value) throws <any>;\n");
    }
  }

  /** Returns true if {@code parameterTypes[offset..]} contains only JsonAdapters. */
  private static boolean parametersAreJsonAdapters(int offset, Type[] parameterTypes) {
    for (int i = offset, length = parameterTypes.length; i < length; i++) {
      if (!(parameterTypes[i] instanceof ParameterizedType)) return false;
      if (((ParameterizedType) parameterTypes[i]).getRawType() != JsonAdapter.class) return false;
    }
    return true;
  }

  /**
   * Returns an object that calls a {@code method} method on {@code adapter} in service of
   * converting an object from JSON.
   */
  static AdapterMethod fromAdapter(Object adapter, Method method) {
    method.setAccessible(true);
    final Type returnType = method.getGenericReturnType();
    Set<? extends Annotation> returnTypeAnnotations = jsonAnnotations(method);
    final Type[] parameterTypes = method.getGenericParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    if (parameterTypes.length >= 1
        && parameterTypes[0] == JsonReader.class
        && returnType != void.class
        && parametersAreJsonAdapters(1, parameterTypes)) {
      // Point pointFromJson(JsonReader jsonReader) {
      // Point pointFromJson(JsonReader jsonReader, JsonAdapter<?> adapter, ...) {
      return new AdapterMethod(returnType, returnTypeAnnotations, adapter, method,
          parameterTypes.length, 1, true) {
        @Override public Object fromJson(Moshi moshi, JsonReader reader)
            throws IOException, InvocationTargetException {
          return invoke(reader);
        }
      };

    } else if (parameterTypes.length == 1 && returnType != void.class) {
      // Point pointFromJson(List<Integer> o) {
      final Set<? extends Annotation> qualifierAnnotations
          = jsonAnnotations(parameterAnnotations[0]);
      boolean nullable = Util.hasNullable(parameterAnnotations[0]);
      return new AdapterMethod(returnType, returnTypeAnnotations, adapter, method,
          parameterTypes.length, 1, nullable) {
        JsonAdapter<Object> delegate;

        @Override public void bind(Moshi moshi, JsonAdapter.Factory factory) {
          super.bind(moshi, factory);
          delegate = moshi.adapter(parameterTypes[0], qualifierAnnotations);
        }

        @Override public Object fromJson(Moshi moshi, JsonReader reader)
            throws IOException, InvocationTargetException {
          Object intermediate = delegate.fromJson(reader);
          return invoke(intermediate);
        }
      };

    } else {
      throw new IllegalArgumentException("Unexpected signature for " + method + ".\n"
          + "@FromJson method signatures may have one of the following structures:\n"
          + "    <any access modifier> R fromJson(JsonReader jsonReader) throws <any>;\n"
          + "    <any access modifier> R fromJson(JsonReader jsonReader,"
          + " JsonAdapter<any> delegate, <any more delegates>) throws <any>;\n"
          + "    <any access modifier> R fromJson(T value) throws <any>;\n");
    }
  }

  /** Returns the matching adapter method from the list. */
  private static @Nullable AdapterMethod get(
      List<AdapterMethod> adapterMethods, Type type, Set<? extends Annotation> annotations) {
    for (int i = 0, size = adapterMethods.size(); i < size; i++) {
      AdapterMethod adapterMethod = adapterMethods.get(i);
      if (adapterMethod.type.equals(type) && adapterMethod.annotations.equals(annotations)) {
        return adapterMethod;
      }
    }
    return null;
  }

  abstract static class AdapterMethod {
    final Type type;
    final Set<? extends Annotation> annotations;
    final Object adapter;
    final Method method;
    final int adaptersOffset;
    final JsonAdapter<?>[] jsonAdapters;
    final boolean nullable;

    AdapterMethod(Type type, Set<? extends Annotation> annotations, Object adapter,
        Method method, int parameterCount, int adaptersOffset, boolean nullable) {
      this.type = Types.canonicalize(type);
      this.annotations = annotations;
      this.adapter = adapter;
      this.method = method;
      this.adaptersOffset = adaptersOffset;
      this.jsonAdapters = new JsonAdapter[parameterCount - adaptersOffset];
      this.nullable = nullable;
    }

    public void bind(Moshi moshi, JsonAdapter.Factory factory) {
      if (jsonAdapters.length > 0) {
        Type[] parameterTypes = method.getGenericParameterTypes();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = adaptersOffset, size = parameterTypes.length; i < size; i++) {
          Type type = ((ParameterizedType) parameterTypes[i]).getActualTypeArguments()[0];
          Set<? extends Annotation> jsonAnnotations = jsonAnnotations(parameterAnnotations[i]);
          jsonAdapters[i - adaptersOffset] =
              Types.equals(this.type, type) && annotations.equals(jsonAnnotations)
                  ? moshi.nextAdapter(factory, type, jsonAnnotations)
                  : moshi.adapter(type, jsonAnnotations);
        }
      }
    }

    public void toJson(Moshi moshi, JsonWriter writer, @Nullable Object value)
        throws IOException, InvocationTargetException {
      throw new AssertionError();
    }

    public @Nullable Object fromJson(Moshi moshi, JsonReader reader)
        throws IOException, InvocationTargetException {
      throw new AssertionError();
    }

    /** Invoke the method with one fixed argument, plus any number of JSON adapter arguments. */
    protected @Nullable Object invoke(@Nullable Object a1) throws InvocationTargetException {
      Object[] args = new Object[1 + jsonAdapters.length];
      args[0] = a1;
      System.arraycopy(jsonAdapters, 0, args, 1, jsonAdapters.length);

      try {
        return method.invoke(adapter, args);
      } catch (IllegalAccessException e) {
        throw new AssertionError();
      }
    }

    /** Invoke the method with two fixed arguments, plus any number of JSON adapter arguments. */
    protected Object invoke(@Nullable Object a1, @Nullable Object a2)
        throws InvocationTargetException {
      Object[] args = new Object[2 + jsonAdapters.length];
      args[0] = a1;
      args[1] = a2;
      System.arraycopy(jsonAdapters, 0, args, 2, jsonAdapters.length);

      try {
        return method.invoke(adapter, args);
      } catch (IllegalAccessException e) {
        throw new AssertionError();
      }
    }
  }
}


text:
package org.webrtc;

/** Java wrapper for a C++ AudioTrackInterface */
public class AudioTrack extends MediaStreamTrack {
  public AudioTrack(long nativeTrack) {
    super(nativeTrack);
  }

  /** Sets the volume for the underlying MediaSource. Volume is a gain value in the range
   *  0 to 10.
   */
  public void setVolume(double volume) {
    nativeSetVolume(super.nativeTrack, volume);
  }

  private static native void nativeSetVolume(long nativeTrack, double volume);
}


text:
<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script to create the `#__solr_search_searchcomponents` table
 **/
class Migration20180126160144ComSearch extends Base
{
	static $tableName = '#__solr_search_searchcomponents';

	public function up()
	{
		$tableName = self::$tableName;
		if (!$this->db->tableExists($tableName))
		{
			$createTable = "CREATE TABLE `{$tableName}` (
			  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `name` varchar(45) NOT NULL,
			  `created` datetime DEFAULT NULL,
			  `indexed` datetime DEFAULT NULL,
			  `state` varchar(45) DEFAULT NULL,
			  `indexed_records` int(10) unsigned DEFAULT NULL,
			  PRIMARY KEY (`id`)
			);";
			$this->db->setQuery($createTable);
			$this->db->query();
		}
		$params = $this->getParams('com_search');
		$params->set('solr_commit', '300000');
		$params->set('solr_batchsize', '1500');
		$this->saveParams('com_search', $params);
	}

	public function	down()
	{
		$tableName = self::$tableName;

		if ($this->db->tableExists($tableName))
		{
			$dropTable = "DROP TABLE {$tableName};";
			$this->db->setQuery($dropTable);
			$this->db->query();
		}

	}
}


text:
**muZic** (v0.1.0-alpha)
========================
**</> by [@nkprince007][6] with ❤**

A light weight **music** player built around web technologies.

Screenshots
-----------
![On GDE](https://raw.githubusercontent.com/NIT-dgp/muZic-electron/master/screenies/Linux-01.png)

What does it use?
-----------------
- [**Node.js**][1] for backend
- [**electron**][2] for Chromium Browser
- [**React.js**][3] for the front-end
- [**Redux**][4] as data-flow pattern
- [**masonry**][5], [**jQuery**][8] and [**twitter-bs**][7] for design and styling

Developer Notes
---------------
To test:
- clone the repo;
- run `$ npm install --no-optional`;
- run `$ npm run dev`;

>This project is still under development and proxies node server via localhost to send content,
> so be sure enough to add **localhost** to excluded proxies in your *Network Configuration*,
> if you work under a corporate proxy.

Highly Production & Development ready;
It works with **webpack-dev-server** to provide Hot Module Reloading.

Any one who'd like to collaborate, feel free to mail me at [nkprince007@gmail.com](mailto:nkprince007@gmail.com)

[1]: http://nodejs.org/en
[2]: http://electron.atom.io/
[3]: http://facebook.github.io/react/
[4]: http://redux.js.org/
[5]: http://masonry.desandro.com/
[6]: http://fb.com/naveen.007.prince/
[7]: http://getbootstrap.com/
[8]: http://jquery.com/


text:
About the Project

The project was created to show features of the famous framework Angular 2. Achieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering. Angular puts you in control over scalability. Meet huge data requirements by building data models on RxJS, Immutable.js or another push-model.

There is also used such libraries as Bootstrap and JQuery. Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. Bootstrap is completely free to download and use!

Get in Touch


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute

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

package EnsEMBL::REST::EnsemblModel::TranslationProteinFeature;

=pod

=head1 NAME

EnsEMBL::REST::EnsemblModel::TranslationProteinFeature

=head1 DESCRIPTION

Provides a wrapper for ProteinFeature objects so we can add to the
summary hash and control the addition of seq_region_name since
these objects lack a slice (and GFFSerialiser hates that).

=cut

use Moose;

=head2 ATTRIBUTES

=over 8

=item translation - Translation this ProteinFeature is linked to

=item protein_feature - The protein feature in question

=back

=cut

has 'translation' => (isa => 'Bio::EnsEMBL::Translation', is => 'ro', required => 1);
has 'protein_feature' => (isa => 'Bio::EnsEMBL::ProteinFeature', is => 'ro', required => 1);

=head2 get_from_ProteinFeatures

	Args [1]		:	ArrayRef[Bio::EnsEMBL::ProteinFeature] Array of protein features to link to a Translation
  Args [2]    : Bio::EnsEMBL::Translation Translation to link a ProteinFeature to
  Description : Loops through all available ProteinFeature objects creating an instance of this
  							class for each one
  Returntype  : ArrayRef of TranslationProteinFeature objects

=cut

sub get_from_ProteinFeatures {
	my ($class, $protein_features, $translation) = @_;
	my @features;
	foreach my $pf (@{$protein_features}) {
		push(@features, $class->new(translation => $translation, protein_feature => $pf));
	}
	return \@features;
}

=head2 summary_as_hash

  Description : Calls the summary_as_hash for ProteinFeature and adds
  							the current linked Translation's stable id as a
  							seq_region_name attribute
  Returntype  : HashRef Summary of this object as a hash

=cut

sub summary_as_hash {
	my ($self) = @_;
	my $summary = $self->protein_feature->summary_as_hash();
	$summary->{seq_region_name} = $self->translation()->stable_id();
        $summary->{Parent} = $self->translation->transcript->stable_id();
	return $summary;
}

=head2 SO_term

  Description : Returns the SO term polypeptide_region
  Returntype  : String the SO term polypeptide_region

=cut

sub SO_term {
  my ($self) = @_;
  return 'SO:0000839'; #polypeptide_region
}

=head seq_region_name

  Description : Returns the stable id of the current Translation
  Returntype  : A fake slice name which is just the stable id of the attached Translation

=cut

sub seq_region_name {
  my ($self) = @_;
  return $self->translation()->stable_id();
}

=head seq_region_start

  Description : Returns the start of the current attached protein feature
  Returntype  : A start which is just the protein feature's

=cut

sub seq_region_start {
  my ($self) = @_;
  return $self->protein_feature->start();
}

=head seq_region_end

  Description : Returns the start of the current attached protein feature
  Returntype  : A start which is just the protein feature's

=cut

sub seq_region_end {
  my ($self) = @_;
  return $self->protein_feature->end();
}

=head seq_region_strand

  Description : Returns the strand of the current attached protein feature
  Returntype  : A strand which is just the protein feature's

=cut

sub seq_region_strand {
  my ($self) = @_;
  return $self->protein_feature->strand();
}

=head display_id

  Description : Returns the display id of the feature
  Returntype  : String display identifier

=cut

sub display_id {
  my ($self) = @_;
  return $self->protein_feature->display_id();
}

1;


text:
import unittest
from botocore.exceptions import ClientError
import sys
import datetime
import threading
from queue import Queue

from . import util

class ExecuteWorkflowDefaultsTestCase(unittest.TestCase):
    def test_ExecuteWorkflow_MissingDefault(self):
        swf = util.BasicSwfSetup(self)
        domain_name = swf.create_domain()
        new_workflow_type_name = util.create_new_name()
        swf.client.register_workflow_type(
            domain=domain_name,
            name=new_workflow_type_name,
            version='1.0',
            description='workflow type ' + new_workflow_type_name,
            # defaultTaskStartToCloseTimeout='1000',
            # defaultExecutionStartToCloseTimeout='2000',
            # defaultTaskList={'name': 'task_list'},
            defaultTaskPriority='-2',
            defaultChildPolicy='TERMINATE',
            defaultLambdaRole='lambda-role')
        new_activity_type_name = util.create_new_name()
        swf.client.register_activity_type(
            domain=domain_name,
            name=new_activity_type_name,
            version='abcd',
            description='activity type ' + new_activity_type_name,
            defaultTaskStartToCloseTimeout='10',
            defaultTaskHeartbeatTimeout='20',
            defaultTaskList={'name': 'activity_task list'},
            defaultTaskPriority='-10',
            defaultTaskScheduleToStartTimeout='30',
            defaultTaskScheduleToCloseTimeout='40'
        )

        workflow_id = util.create_new_name().replace(":", "-")
        try:
            swf.client.start_workflow_execution(
                domain=domain_name,
                workflowId=workflow_id,
                workflowType={
                    'name': new_workflow_type_name,
                    'version': '1.0'
                }
                # No more optional parameters
            )
            self.fail("Did not cause a server error")
        except ClientError as e:
            # TODO examine error
            # self.assertEqual()
            text = str(e)
            self.assertIn(
                "(DefaultUndefinedFault)",
                text,
                "Error does not include correct fault")
            # print(text)

class ExecuteWorkflowTestCase(unittest.TestCase):
    def test_StartWorkflowExecution_ListOpenWorkflowExecutions_TerminateWorkflow_ListClosedWorkflowExecutions(self):
        swf = util.BasicSwfSetup(self)
        domain_name = swf.create_domain()
        workflow_type = swf.create_workflow_type()

        # StartWorkflowExecution
        tagList = [util.create_new_name()]
        workflow_id, run_id = swf.start_workflow_execution(workflow_type, tagList=tagList)

        # ListOpenWorkflowExecutions, filter on workflow id
        info_count = 0
        open_exec_pager = swf.client.get_paginator('list_open_workflow_executions')
        for page in open_exec_pager.paginate(
                domain=domain_name,
                executionFilter={
                    'workflowId': workflow_id
                },
                startTimeFilter={
                    'oldestDate': datetime.datetime(2015, 1, 1)
                },
                reverseOrder=True):
            if 'executionInfos' in page:
                for exec_info in page['executionInfos']:
                    info_count += 1
                    self.assertEqual(
                        exec_info['execution']['workflowId'],
                        workflow_id,
                        "workflowId")
                    self.assertEqual(
                        exec_info['execution']['runId'],
                        run_id,
                        "runId")
                    self.assertEqual(
                        exec_info['workflowType']['name'],
                        workflow_type.name,
                        "type name")
                    self.assertEqual(
                        exec_info['workflowType']['version'],
                        workflow_type.version,
                        "type version")
                    self.assertTrue(
                        ('closeTimestamp' not in exec_info) or exec_info['closeTimestamp'] is None,
                        "closeTimestamp was incorrectly set")
                    self.assertTrue(
                        ('closeStatus' not in exec_info) or exec_info['closeStatus'] is None,
                        "closeStatus was incorrectly set")
                    self.assertTrue(
                        ('parent' not in exec_info) or exec_info['parent'] is None,
                        "parent was incorrectly set")
                    self.assertEqual(
                        exec_info['tagList'],
                        tagList,
                        "tagList set wrong")
                    self.assertTrue(
                        not exec_info['cancelRequested'],
                        'cancelRequested should be false')
                    # {
                    #     'execution': {
                    #         'workflowId': 'string',
                    #         'runId': 'string'
                    #     },
                    #     'workflowType': {
                    #         'name': 'string',
                    #         'version': 'string'
                    #     },
                    #     'startTimestamp': datetime(2015, 1, 1),
                    #     'closeTimestamp': datetime(2015, 1, 1),
                    #     'executionStatus': 'OPEN'|'CLOSED',
                    #     'closeStatus': 'COMPLETED'|'FAILED'|'CANCELED'|'TERMINATED'|'CONTINUED_AS_NEW'|'TIMED_OUT',
                    #     'parent': {
                    #         'workflowId': 'string',
                    #         'runId': 'string'
                    #     },
                    #     'tagList': [
                    #         'string',
                    #     ],
                    #     'cancelRequested': True|False
                    # },
        self.assertEqual(
            info_count,
            1,
            'open workflow count')

        swf.client.terminate_workflow_execution(
            domain=domain_name,
            workflowId=workflow_id,
            reason='Stop test',
            details='Stopped'
        )

        # ListOpenWorkflowExecutions, filter on tag list
        open_exec_pager = swf.client.get_paginator('list_open_workflow_executions')
        for page in open_exec_pager.paginate(
                domain=domain_name,
                tagFilter={
                    'tag': 'exec_' + workflow_id
                },
                startTimeFilter={
                    'oldestDate': datetime.datetime(2015, 1, 1)
                },
                reverseOrder=True):
            if 'executionInfos' in page:
                for info in page['executionInfos']:
                    self.assertTrue(False,
                        "found open exec " + info['execution']['workflowId'])

        # ListClosedWorkflowExecutions
        info_count = 0
        close_exec_pager = swf.client.get_paginator('list_closed_workflow_executions')
        for page in close_exec_pager.paginate(
                domain=domain_name,
                executionFilter={
                    'workflowId': workflow_id
                },
                startTimeFilter={
                    'oldestDate': datetime.datetime(2015, 1, 1)
                },
                reverseOrder=True):
            if 'executionInfos' in page:
                for exec_info in page['executionInfos']:
                    info_count += 1
                    self.assertEqual(
                        exec_info['execution']['workflowId'],
                        workflow_id,
                        "workflowId")
                    self.assertEqual(
                        exec_info['execution']['runId'],
                        run_id,
                        "runId")
                    self.assertEqual(
                        exec_info['workflowType']['name'],
                        workflow_type.name,
                        "type name")
                    self.assertEqual(
                        exec_info['workflowType']['version'],
                        workflow_type.version,
                        "type version")
                    self.assertTrue(
                        ('closeTimestamp' in exec_info) and exec_info['closeTimestamp'] is not None,
                        "closeTimestamp was incorrectly set")
                    self.assertEqual(
                        exec_info['closeStatus'],
                        'TERMINATED',
                        "closeStatus was incorrectly set")
                    self.assertTrue(
                        ('parent' not in exec_info) or exec_info['parent'] is None,
                        "parent was incorrectly set")
                    self.assertEqual(
                        exec_info['tagList'],
                        tagList,
                        "tagList set wrong")
                    self.assertTrue(
                        not exec_info['cancelRequested'],
                        'cancelRequested should be false')
                    # {
                    #     'execution': {
                    #         'workflowId': 'string',
                    #         'runId': 'string'
                    #     },
                    #     'workflowType': {
                    #         'name': 'string',
                    #         'version': 'string'
                    #     },
                    #     'startTimestamp': datetime(2015, 1, 1),
                    #     'closeTimestamp': datetime(2015, 1, 1),
                    #     'executionStatus': 'OPEN'|'CLOSED',
                    #     'closeStatus': 'COMPLETED'|'FAILED'|'CANCELED'|'TERMINATED'|'CONTINUED_AS_NEW'|'TIMED_OUT',
                    #     'parent': {
                    #         'workflowId': 'string',
                    #         'runId': 'string'
                    #     },
                    #     'tagList': [
                    #         'string',
                    #     ],
                    #     'cancelRequested': True|False
                    # },
        self.assertEqual(
            info_count,
            1,
            'closed workflow count')

class DecisionTaskTestCase(unittest.TestCase):
    def test_PollForDecisionTask_terminated(self):
        swf = util.BasicSwfSetup(self)
        domain_name = swf.create_domain()
        workflow_type = swf.create_workflow_type()
        workflow_id, run_id = swf.start_workflow_execution(workflow_type)

        # Poll for a decision in the background.
        poller_wait = Queue()
        tester_wait = Queue()
        def decision_poller():
            poller_wait.get()
            try:
                response = swf.poll_for_decision()
                if response is None:
                    results = []
                else:
                    results = response['events']
                tester_wait.put([True, results])
            except:
                tester_wait.put([False, sys.exc_info()[1]])

        t = threading.Thread(target=decision_poller)
        t.daemon = True
        t.start()

        # Request the workflow to die
        swf.client.terminate_workflow_execution(
            domain=domain_name,
            workflowId=workflow_id,
            reason='Stop test',
            details='Stopped'
        )
        # Tell the decision that we've made the event post
        poller_wait.put(0)

        # Wait for the decision to post the result
        events = tester_wait.get()
        if not events[0]:
            raise events[1]
        events = events[1]

        # It should have a started workflow and terminated workflow entries.
        self.assertTrue(len(events) > 1, "Not enough events: " + repr(events))

        # FIXME check result in more detail

if __name__ == '__main__':
    unittest.main()


text:
package com.cisco.trex.stateless.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class L3Configuration {

  @JsonProperty("dst")
  private String dst;

  @JsonProperty("src")
  private String src;

  @JsonProperty("state")
  private String state;

  @JsonProperty("dst")
  public String getDst() {
    return dst;
  }

  @JsonProperty("dst")
  public void setDst(String dst) {
    this.dst = dst;
  }

  @JsonProperty("src")
  public String getSrc() {
    return src;
  }

  @JsonProperty("src")
  public void setSrc(String src) {
    this.src = src;
  }

  @JsonProperty("state")
  public String getState() {
    return state;
  }

  @JsonProperty("state")
  public void setState(String state) {
    this.state = state;
  }
}


text:
{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "Password Change Successfully" %}{% endblock %}

{% block main_content %}

{% trans "Your password has been changed successfully." %}

{% trans "Log in again" %}

{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="Mocha Tests" time="0.067" tests="5" failures="0">
  <testsuite name="Root Suite" timestamp="2017-04-06T02:34:45" tests="0" failures="0" time="0">
  </testsuite>
  <testsuite name="Validate Article functionality" timestamp="2017-04-06T02:34:45" tests="4" file="/Users/minzhou/Downloads/hw6/back-end/src/articles.spec.js" failures="0" time="0.058">
    <testcase name="Validate Article functionality should give me three or more articles" time="0.032" classname="should give me three or more articles">
    </testcase>
    <testcase name="Validate Article functionality should return an article with a specified id" time="0.007" classname="should return an article with a specified id">
    </testcase>
    <testcase name="Validate Article functionality should return nothing for an invalid id" time="0.003" classname="should return nothing for an invalid id">
    </testcase>
    <testcase name="Validate Article functionality should add an article and test the new id and text" time="0.016" classname="should add an article and test the new id and text">
    </testcase>
  </testsuite>
  <testsuite name="Validate Profile functionality" timestamp="2017-04-06T02:34:45" tests="1" file="/Users/minzhou/Downloads/hw6/back-end/src/profile.spec.js" failures="0" time="0.009">
    <testcase name="Validate Profile functionality should update headline after use PUT" time="0.009" classname="should update headline after use PUT">
    </testcase>
  </testsuite>
</testsuites>


text:
anti:modals
===========

Modals and dialogs: the Meteor way

Usage
-----

    meteor add anti:modals

Demo app: [https://github.com/anticoders/meteor-modals-demo](https://github.com/anticoders/meteor-modals-demo).

API
---

- [overlay](#antimodalsoverlay)
- [dismissOverlay](#antimodalsdismissoverlay)
- [alert](#antimodalsalert)
- [confirm](#antimodalsconfirm)
- [prompt](#antimodalsprompt)

---

### `AntiModals.overlay()`

Display given template as a dialog.

---

### `AntiModals.dismissOverlay()`

Dismiss displayed dialog.

---

### `AntiModals.alert()`

Display alert dialog.

---

### `AntiModals.confirm()`

Display confirm dialog.

---

### `AntiModals.prompt()`

Display prompt dialog.

---


text:
<?php

defined('_JEXEC') or die;

/**
 * View to edit an language override
 *
 * @since  2.5
 */
class LanguagesViewOverride extends JViewLegacy
{
	/**
	 * The form to use for the view.
	 *
	 * @var		object
	 * @since	2.5
	 */
	protected $form;

	/**
	 * The item to edit.
	 *
	 * @var		object
	 * @since	2.5
	 */
	protected $item;

	/**
	 * The model state.
	 *
	 * @var		object
	 * @since	2.5
	 */
	protected $state;

	/**
	 * Displays the view.
	 *
	 * @param   string  $tpl  The name of the template file to parse
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	public function display($tpl = null)
	{
		$this->form  = $this->get('Form');
		$this->item  = $this->get('Item');
		$this->state = $this->get('State');

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors));
		}

		// Check whether the cache has to be refreshed.
		$cached_time = JFactory::getApplication()->getUserState(
			'com_languages.overrides.cachedtime.' . $this->state->get('filter.client') . '.' . $this->state->get('filter.language'),
			0
		);

		if (time() - $cached_time > 60 * 5)
		{
			$this->state->set('cache_expired', true);
		}

		// Add strings for translations in Javascript.
		JText::script('COM_LANGUAGES_VIEW_OVERRIDE_NO_RESULTS');
		JText::script('COM_LANGUAGES_VIEW_OVERRIDE_REQUEST_ERROR');

		$this->addToolbar();
		parent::display($tpl);
	}

	/**
	 * Adds the page title and toolbar.
	 *
	 * @return void
	 *
	 * @since	2.5
	 */
	protected function addToolbar()
	{
		JFactory::getApplication()->input->set('hidemainmenu', true);

		$canDo = JHelperContent::getActions('com_languages');

		JToolbarHelper::title(JText::_('COM_LANGUAGES_VIEW_OVERRIDE_EDIT_TITLE'), 'comments-2 langmanager');

		if ($canDo->get('core.edit'))
		{
			JToolbarHelper::apply('override.apply');
			JToolbarHelper::save('override.save');
		}

		// This component does not support Save as Copy.
		if ($canDo->get('core.edit') && $canDo->get('core.create'))
		{
			JToolbarHelper::save2new('override.save2new');
		}

		if (empty($this->item->key))
		{
			JToolbarHelper::cancel('override.cancel');
		}
		else
		{
			JToolbarHelper::cancel('override.cancel', 'JTOOLBAR_CLOSE');
		}

		JToolbarHelper::divider();
		JToolbarHelper::help('JHELP_EXTENSIONS_LANGUAGE_MANAGER_OVERRIDES_EDIT');
	}
}


text:
var program = require('commander');
var shell = require("shelljs");
require("./deps");
program.description('Customized pack iClient.');

var excludeFields = ['title', 'description', 'description_en'];

program.command('- <key> [modules]')
    .description('pack iClent9')
    .action(function (key, modules) {
        var packages = [];
        for (var pack in deps) {
            packages.push(pack);
        }
        if (!key || packages.indexOf(key) === -1) {
            console.log(key + "值输入有误,可选值为" + packages.toString());
            return;
        }
        shell.exec('npm install ./src/common');
        var modulePaths = "";
        if (key === "common") {
            modulePaths = getCommonModulePaths();
            shell.exec('npm run deploy ' + modulePaths);
            return;
        }
        var clientModules = deps[key];
        if (!modules) {
            for (var clientModule in clientModules) {
                for (var module in clientModules[clientModule]) {
                    if (excludeFields.indexOf(module) > -1) {
                        continue;
                    }
                    clientModules[clientModule][module].src.map(function (src) {
                        modulePaths += src + " ";
                    })
                }
            }
            shell.exec('npm run deploy-' + key + ' ' + modulePaths);
            return;
        }
        if (modules.indexOf("common") !== -1) {
            modulePaths = getCommonModulePaths();
        }
        modules.split(',').map(function (packModule) {
            for (var clientModule in clientModules) {
                for (var module in clientModules[clientModule]) {
                    if (excludeFields.indexOf(module) > -1) {
                        continue;
                    }
                    clientModules[clientModule][module].src.map(function (src) {
                        if (module === packModule) {
                            modulePaths += src + " ";
                        }
                    })

                }
            }
        });
        shell.exec('npm run deploy-' + key + ' ' + modulePaths);
    });

program.parse(process.argv);

function getCommonModulePaths() {
    var modulePaths = "";
    for (var commonModule in deps.common) {
        deps.common[commonModule].map(function (module) {
            modulePaths += module + " ";
        })
    }
    return modulePaths;
}


text:
JWFlipNavigation
==========================

A simple and easy to use navigation controller for flipping through the views like pages in a book.

## Usage

Subclass ```JWFlipNavigationController``` and override the inherited method ```- (void)viewControllerForIndex:(NSInteger)index``` to return the view controller for the requested index. Return ```nil``` when no more view controllers are available.

Override the method ```- (FlipMode)flipMode``` to control horizontal or vertical page flipping.

## Requirements

### Frameworks
Requires the frameworks ```QuartzCore``` and ```CoreGraphics``` to be added to your project.

### ARC
JWFlipNavigation uses ARC. If you would like to add JWFlipNavigation to a project not using ARC, you can enable ARC for the JWFlipNavigation source files explicitly by adding the compiler flag ```-fobjc-arc``` for each file.

## License
Available under the MIT license. See the LICENSE file for more info.

## Acknowledgements
Credits to the FlipBoard app and the developers behind it, of course a strong inspiration when creating this implementation.


text:
package org.keycloak.protocol.oidc;

import org.jboss.logging.Logger;
import org.keycloak.common.ClientConnection;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientSessionModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.ProtocolMapper;
import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenMapper;
import org.keycloak.protocol.oidc.mappers.OIDCIDTokenMapper;
import org.keycloak.protocol.oidc.utils.OIDCResponseType;
import org.keycloak.protocol.oidc.utils.WebOriginsUtils;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.ClientSessionCode;
import org.keycloak.services.managers.UserSessionManager;
import org.keycloak.util.TokenUtil;
import org.keycloak.common.util.Time;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Stateless object that creates tokens and manages oauth access codes
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class TokenManager {
    protected static final Logger logger = Logger.getLogger(TokenManager.class);

    public static void applyScope(RoleModel role, RoleModel scope, Set<RoleModel> visited, Set<RoleModel> requested) {
        if (visited.contains(scope)) return;
        visited.add(scope);
        if (role.hasRole(scope)) {
            requested.add(scope);
            return;
        }
        if (!scope.isComposite()) return;

        for (RoleModel contained : scope.getComposites()) {
            applyScope(role, contained, visited, requested);
        }
    }

    public static class TokenValidation {
        public final UserModel user;
        public final UserSessionModel userSession;
        public final ClientSessionModel clientSession;
        public final AccessToken newToken;

        public TokenValidation(UserModel user, UserSessionModel userSession, ClientSessionModel clientSession, AccessToken newToken) {
            this.user = user;
            this.userSession = userSession;
            this.clientSession = clientSession;
            this.newToken = newToken;
        }
    }

    public TokenValidation validateToken(KeycloakSession session, UriInfo uriInfo, ClientConnection connection, RealmModel realm, AccessToken oldToken, HttpHeaders headers) throws OAuthErrorException {
        UserModel user = session.users().getUserById(oldToken.getSubject(), realm);
        if (user == null) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown user");
        }

        if (!user.isEnabled()) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "User disabled", "User disabled");
        }

        UserSessionModel userSession = null;
        ClientSessionModel clientSession = null;
        if (TokenUtil.TOKEN_TYPE_OFFLINE.equals(oldToken.getType())) {

            UserSessionManager sessionManager = new UserSessionManager(session);
            clientSession = sessionManager.findOfflineClientSession(realm, oldToken.getClientSession(), oldToken.getSessionState());
            if (clientSession != null) {
                userSession = clientSession.getUserSession();

                // Revoke timeouted offline userSession
                if (userSession.getLastSessionRefresh() < Time.currentTime() - realm.getOfflineSessionIdleTimeout()) {
                    sessionManager.revokeOfflineUserSession(userSession);
                    userSession = null;
                    clientSession = null;
                }
            }
        } else {
            // Find userSession regularly for online tokens
            userSession = session.sessions().getUserSession(realm, oldToken.getSessionState());
            if (!AuthenticationManager.isSessionValid(realm, userSession)) {
                AuthenticationManager.backchannelLogout(session, realm, userSession, uriInfo, connection, headers, true);
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Session not active", "Session not active");
            }

            for (ClientSessionModel clientSessionModel : userSession.getClientSessions()) {
                if (clientSessionModel.getId().equals(oldToken.getClientSession())) {
                    clientSession = clientSessionModel;
                    break;
                }
            }
        }

        if (clientSession == null) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Client session not active", "Client session not active");
        }

        ClientModel client = clientSession.getClient();

        if (!client.getClientId().equals(oldToken.getIssuedFor())) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Unmatching clients", "Unmatching clients");
        }

        if (oldToken.getIssuedAt() < client.getNotBefore()) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token");
        }
        if (oldToken.getIssuedAt() < realm.getNotBefore()) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token");
        }

        // recreate token.
        String scopeParam = clientSession.getNote(OAuth2Constants.SCOPE);
        Set<RoleModel> requestedRoles = TokenManager.getAccess(scopeParam, true, clientSession.getClient(), user);
        AccessToken newToken = createClientAccessToken(session, requestedRoles, realm, client, user, userSession, clientSession);
        verifyAccess(oldToken, newToken);

        return new TokenValidation(user, userSession, clientSession, newToken);

    }

    public RefreshResult refreshAccessToken(KeycloakSession session, UriInfo uriInfo, ClientConnection connection, RealmModel realm, ClientModel authorizedClient, String encodedRefreshToken, EventBuilder event, HttpHeaders headers) throws OAuthErrorException {
        RefreshToken refreshToken = verifyRefreshToken(realm, encodedRefreshToken);

        event.user(refreshToken.getSubject()).session(refreshToken.getSessionState())
                .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
                .detail(Details.REFRESH_TOKEN_TYPE, refreshToken.getType());

        TokenValidation validation = validateToken(session, uriInfo, connection, realm, refreshToken, headers);
        // validate authorizedClient is same as validated client
        if (!validation.clientSession.getClient().getId().equals(authorizedClient.getId())) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token. Token client and authorized client don't match");
        }

        int currentTime = Time.currentTime();

        if (realm.isRevokeRefreshToken()) {
            int serverStartupTime = (int)(session.getKeycloakSessionFactory().getServerStartupTimestamp() / 1000);

            if (refreshToken.getIssuedAt() < validation.clientSession.getTimestamp() && (serverStartupTime != validation.clientSession.getTimestamp())) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token");
            }

        }

        validation.clientSession.setTimestamp(currentTime);
        validation.userSession.setLastSessionRefresh(currentTime);

        AccessTokenResponse res = responseBuilder(realm, authorizedClient, event, session, validation.userSession, validation.clientSession)
                .accessToken(validation.newToken)
                .generateIDToken()
                .generateRefreshToken()
                .build();

        return new RefreshResult(res, TokenUtil.TOKEN_TYPE_OFFLINE.equals(refreshToken.getType()));
    }

    public RefreshToken verifyRefreshToken(RealmModel realm, String encodedRefreshToken) throws OAuthErrorException {
        try {
            JWSInput jws = new JWSInput(encodedRefreshToken);
            RefreshToken refreshToken = null;
            if (!RSAProvider.verify(jws, realm.getPublicKey())) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token");
            }
            refreshToken = jws.readJsonContent(RefreshToken.class);

            if (refreshToken.getExpiration() != 0 && refreshToken.isExpired()) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Refresh token expired");
            }

            if (refreshToken.getIssuedAt() < realm.getNotBefore()) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale refresh token");
            }
            return refreshToken;
        } catch (JWSInputException e) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", e);
        }
    }
    public IDToken verifyIDToken(RealmModel realm, String encodedIDToken) throws OAuthErrorException {
        try {
            JWSInput jws = new JWSInput(encodedIDToken);
            IDToken idToken;
            if (!RSAProvider.verify(jws, realm.getPublicKey())) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid IDToken");
            }
            idToken = jws.readJsonContent(IDToken.class);

            if (idToken.isExpired()) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "IDToken expired");
            }

            if (idToken.getIssuedAt() < realm.getNotBefore()) {
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale IDToken");
            }
            return idToken;
        } catch (JWSInputException e) {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid IDToken", e);
        }
    }

    public AccessToken createClientAccessToken(KeycloakSession session, Set<RoleModel> requestedRoles, RealmModel realm, ClientModel client, UserModel user, UserSessionModel userSession, ClientSessionModel clientSession) {
        AccessToken token = initToken(realm, client, user, userSession, clientSession, session.getContext().getUri());
        for (RoleModel role : requestedRoles) {
            addComposites(token, role);
        }
        token = transformAccessToken(session, token, realm, client, user, userSession, clientSession);
        return token;
    }

    public static void attachClientSession(UserSessionModel session, ClientSessionModel clientSession) {
        if (clientSession.getUserSession() != null) {
            return;
        }

        UserModel user = session.getUser();
        clientSession.setUserSession(session);
        Set<String> requestedRoles = new HashSet<String>();
        // todo scope param protocol independent
        String scopeParam = clientSession.getNote(OAuth2Constants.SCOPE);
        for (RoleModel r : TokenManager.getAccess(scopeParam, true, clientSession.getClient(), user)) {
            requestedRoles.add(r.getId());
        }
        clientSession.setRoles(requestedRoles);

        Set<String> requestedProtocolMappers = new HashSet<String>();
        for (ProtocolMapperModel protocolMapper : clientSession.getClient().getProtocolMappers()) {
            if (protocolMapper.getProtocol().equals(clientSession.getAuthMethod())) {
                requestedProtocolMappers.add(protocolMapper.getId());
            }
        }
        clientSession.setProtocolMappers(requestedProtocolMappers);

        Map<String, String> transferredNotes = clientSession.getUserSessionNotes();
        for (Map.Entry<String, String> entry : transferredNotes.entrySet()) {
            session.setNote(entry.getKey(), entry.getValue());
        }

    }

    public static void dettachClientSession(UserSessionProvider sessions, RealmModel realm, ClientSessionModel clientSession) {
        UserSessionModel userSession = clientSession.getUserSession();
        if (userSession == null) {
            return;
        }

        clientSession.setUserSession(null);
        clientSession.setRoles(null);
        clientSession.setProtocolMappers(null);

        if (userSession.getClientSessions().isEmpty()) {
            sessions.removeUserSession(realm, userSession);
        }
    }

    public static void addGroupRoles(GroupModel group, Set<RoleModel> roleMappings) {
        roleMappings.addAll(group.getRoleMappings());
        if (group.getParentId() == null) return;
        addGroupRoles(group.getParent(), roleMappings);
    }

    public static Set<RoleModel> getAccess(String scopeParam, boolean applyScopeParam, ClientModel client, UserModel user) {
        Set<RoleModel> requestedRoles = new HashSet<RoleModel>();

        Set<RoleModel> mappings = user.getRoleMappings();
        Set<RoleModel> roleMappings = new HashSet<>();
        roleMappings.addAll(mappings);
        for (GroupModel group : user.getGroups()) {
            addGroupRoles(group, roleMappings);
        }

        if (client.isFullScopeAllowed()) {
            requestedRoles = roleMappings;
        } else {

            Set<RoleModel> scopeMappings = client.getScopeMappings();
            scopeMappings.addAll(client.getRoles());

            for (RoleModel role : roleMappings) {
                for (RoleModel desiredRole : scopeMappings) {
                    Set<RoleModel> visited = new HashSet<RoleModel>();
                    applyScope(role, desiredRole, visited, requestedRoles);
                }
            }
        }

        if (applyScopeParam) {
            Collection<String> scopeParamRoles;
            if (scopeParam != null) {
                String[] scopes = scopeParam.split(" ");
                scopeParamRoles = Arrays.asList(scopes);
            } else {
                scopeParamRoles = Collections.emptyList();
            }

            Set<RoleModel> roles = new HashSet<>();
            for (RoleModel role : requestedRoles) {
                String roleName = getRoleNameForScopeParam(role);
                if (!role.isScopeParamRequired() || scopeParamRoles.contains(roleName)) {
                    roles.add(role);
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.tracef("Role '%s' excluded by scope param. Client is '%s', User is '%s', Scope param is '%s' ", role.getName(), client.getClientId(), user.getUsername(), scopeParam);
                    }
                }
            }

            // Add all roles specified in scope parameter directly into requestedRoles, even if they are available just through composite role
            List<RoleModel> scopeRoles = new LinkedList<>();
            for (String scopeParamPart : scopeParamRoles) {
                RoleModel scopeParamRole = getRoleFromScopeParam(client.getRealm(), scopeParamPart);
                if (scopeParamRole != null) {
                    for (RoleModel role : roles) {
                        if (role.hasRole(scopeParamRole)) {
                            scopeRoles.add(scopeParamRole);
                        }
                    }
                }
            }

            roles.addAll(scopeRoles);
            requestedRoles = roles;
        }

        return requestedRoles;
    }

    // For now, just use "roleName" for realm roles and "clientId/roleName" for client roles
    private static String getRoleNameForScopeParam(RoleModel role) {
        if (role.getContainer() instanceof RealmModel) {
            return role.getName();
        } else {
            ClientModel client = (ClientModel) role.getContainer();
            return client.getClientId() + "/" + role.getName();
        }
    }

    // For now, just use "roleName" for realm roles and "clientId/roleName" for client roles
    private static RoleModel getRoleFromScopeParam(RealmModel realm, String scopeParamRole) {
        String[] parts = scopeParamRole.split("/");
        if (parts.length == 1) {
            return realm.getRole(parts[0]);
        } else {
            ClientModel roleClient = realm.getClientByClientId(parts[0]);
            return roleClient!=null ? roleClient.getRole(parts[1]) : null;
        }
    }

    public void verifyAccess(AccessToken token, AccessToken newToken) throws OAuthErrorException {
        if (token.getRealmAccess() != null) {
            if (newToken.getRealmAccess() == null) throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm roles");

            for (String roleName : token.getRealmAccess().getRoles()) {
                if (!newToken.getRealmAccess().getRoles().contains(roleName)) {
                    throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm role: " + roleName);
                }
            }
        }
        if (token.getResourceAccess() != null) {
            for (Map.Entry<String, AccessToken.Access> entry : token.getResourceAccess().entrySet()) {
                AccessToken.Access appAccess = newToken.getResourceAccess(entry.getKey());
                if (appAccess == null && !entry.getValue().getRoles().isEmpty()) {
                    throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User or client no longer has role permissions for client key: " + entry.getKey());

                }
                for (String roleName : entry.getValue().getRoles()) {
                    if (!appAccess.getRoles().contains(roleName)) {
                        throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for client role " + roleName);
                    }
                }
            }
        }
    }

    public AccessToken transformAccessToken(KeycloakSession session, AccessToken token, RealmModel realm, ClientModel client, UserModel user,
                                            UserSessionModel userSession, ClientSessionModel clientSession) {
        Set<ProtocolMapperModel> mappings = new ClientSessionCode(realm, clientSession).getRequestedProtocolMappers();
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        for (ProtocolMapperModel mapping : mappings) {

            ProtocolMapper mapper = (ProtocolMapper)sessionFactory.getProviderFactory(ProtocolMapper.class, mapping.getProtocolMapper());
            if (mapper == null || !(mapper instanceof OIDCAccessTokenMapper)) continue;
            token = ((OIDCAccessTokenMapper)mapper).transformAccessToken(token, mapping, session, userSession, clientSession);

        }
        return token;
    }
    public void transformIDToken(KeycloakSession session, IDToken token, RealmModel realm, ClientModel client, UserModel user,
                                      UserSessionModel userSession, ClientSessionModel clientSession) {
        Set<ProtocolMapperModel> mappings = new ClientSessionCode(realm, clientSession).getRequestedProtocolMappers();
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        for (ProtocolMapperModel mapping : mappings) {

            ProtocolMapper mapper = (ProtocolMapper)sessionFactory.getProviderFactory(ProtocolMapper.class, mapping.getProtocolMapper());
            if (mapper == null || !(mapper instanceof OIDCIDTokenMapper)) continue;
            token = ((OIDCIDTokenMapper)mapper).transformIDToken(token, mapping, session, userSession, clientSession);

        }
    }

    protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user, UserSessionModel session, ClientSessionModel clientSession, UriInfo uriInfo) {
        AccessToken token = new AccessToken();
        if (clientSession != null) token.clientSession(clientSession.getId());
        token.id(KeycloakModelUtils.generateId());
        token.type(TokenUtil.TOKEN_TYPE_BEARER);
        token.subject(user.getId());
        token.audience(client.getClientId());
        token.issuedNow();
        token.issuedFor(client.getClientId());
        token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
        token.setNonce(clientSession.getNote(OIDCLoginProtocol.NONCE_PARAM));
        if (session != null) {
            token.setSessionState(session.getId());
        }
        int tokenLifespan = getTokenLifespan(realm, clientSession);
        if (tokenLifespan > 0) {
            token.expiration(Time.currentTime() + tokenLifespan);
        }
        Set<String> allowedOrigins = client.getWebOrigins();
        if (allowedOrigins != null) {
            token.setAllowedOrigins(WebOriginsUtils.resolveValidWebOrigins(uriInfo, client));
        }
        return token;
    }

    private int getTokenLifespan(RealmModel realm, ClientSessionModel clientSession) {
        boolean implicitFlow = false;
        String responseType = clientSession.getNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM);
        if (responseType != null) {
            implicitFlow = OIDCResponseType.parse(responseType).isImplicitFlow();
        }
        return implicitFlow ? realm.getAccessTokenLifespanForImplicitFlow() : realm.getAccessTokenLifespan();
    }

    protected void addComposites(AccessToken token, RoleModel role) {
        AccessToken.Access access = null;
        if (role.getContainer() instanceof RealmModel) {
            access = token.getRealmAccess();
            if (token.getRealmAccess() == null) {
                access = new AccessToken.Access();
                token.setRealmAccess(access);
            } else if (token.getRealmAccess().getRoles() != null && token.getRealmAccess().isUserInRole(role.getName()))
                return;

        } else {
            ClientModel app = (ClientModel) role.getContainer();
            access = token.getResourceAccess(app.getClientId());
            if (access == null) {
                access = token.addAccess(app.getClientId());
                if (app.isSurrogateAuthRequired()) access.verifyCaller(true);
            } else if (access.isUserInRole(role.getName())) return;

        }
        access.addRole(role.getName());
        if (!role.isComposite()) return;

        for (RoleModel composite : role.getComposites()) {
            addComposites(token, composite);
        }

    }

    public String encodeToken(RealmModel realm, Object token) {
        String encodedToken = new JWSBuilder()
                .jsonContent(token)
                .rsa256(realm.getPrivateKey());
        return encodedToken;
    }

    public AccessTokenResponseBuilder responseBuilder(RealmModel realm, ClientModel client, EventBuilder event, KeycloakSession session, UserSessionModel userSession, ClientSessionModel clientSession) {
        return new AccessTokenResponseBuilder(realm, client, event, session, userSession, clientSession);
    }

    public class AccessTokenResponseBuilder {
        RealmModel realm;
        ClientModel client;
        EventBuilder event;
        KeycloakSession session;
        UserSessionModel userSession;
        ClientSessionModel clientSession;

        AccessToken accessToken;
        RefreshToken refreshToken;
        IDToken idToken;

        public AccessTokenResponseBuilder(RealmModel realm, ClientModel client, EventBuilder event, KeycloakSession session, UserSessionModel userSession, ClientSessionModel clientSession) {
            this.realm = realm;
            this.client = client;
            this.event = event;
            this.session = session;
            this.userSession = userSession;
            this.clientSession = clientSession;
        }

        public AccessTokenResponseBuilder accessToken(AccessToken accessToken) {
            this.accessToken = accessToken;
            return this;
        }
        public AccessTokenResponseBuilder refreshToken(RefreshToken refreshToken) {
            this.refreshToken = refreshToken;
            return this;
        }

        public AccessTokenResponseBuilder generateAccessToken() {
            UserModel user = userSession.getUser();
            String scopeParam = clientSession.getNote(OIDCLoginProtocol.SCOPE_PARAM);
            Set<RoleModel> requestedRoles = getAccess(scopeParam, true, client, user);
            accessToken = createClientAccessToken(session, requestedRoles, realm, client, user, userSession, clientSession);
            return this;
        }

        public AccessTokenResponseBuilder generateRefreshToken() {
            if (accessToken == null) {
                throw new IllegalStateException("accessToken not set");
            }

            String scopeParam = clientSession.getNote(OIDCLoginProtocol.SCOPE_PARAM);
            boolean offlineTokenRequested = TokenUtil.isOfflineTokenRequested(scopeParam);
            if (offlineTokenRequested) {
                UserSessionManager sessionManager = new UserSessionManager(session);
                if (!sessionManager.isOfflineTokenAllowed(clientSession)) {
                    event.error(Errors.NOT_ALLOWED);
                    throw new ErrorResponseException("not_allowed", "Offline tokens not allowed for the user or client", Response.Status.BAD_REQUEST);
                }

                refreshToken = new RefreshToken(accessToken);
                refreshToken.type(TokenUtil.TOKEN_TYPE_OFFLINE);
                sessionManager.createOrUpdateOfflineSession(clientSession, userSession);
            } else {
                refreshToken = new RefreshToken(accessToken);
                refreshToken.expiration(Time.currentTime() + realm.getSsoSessionIdleTimeout());
            }
            refreshToken.id(KeycloakModelUtils.generateId());
            refreshToken.issuedNow();
            return this;
        }

        public AccessTokenResponseBuilder generateIDToken() {
            if (accessToken == null) {
                throw new IllegalStateException("accessToken not set");
            }
            idToken = new IDToken();
            idToken.id(KeycloakModelUtils.generateId());
            idToken.type(TokenUtil.TOKEN_TYPE_ID);
            idToken.subject(accessToken.getSubject());
            idToken.audience(client.getClientId());
            idToken.issuedNow();
            idToken.issuedFor(accessToken.getIssuedFor());
            idToken.issuer(accessToken.getIssuer());
            idToken.setNonce(accessToken.getNonce());
            idToken.setSessionState(accessToken.getSessionState());
            idToken.expiration(accessToken.getExpiration());
            transformIDToken(session, idToken, realm, client, userSession.getUser(), userSession, clientSession);
            return this;
        }

        public AccessTokenResponse build() {
            if (accessToken != null) {
                event.detail(Details.TOKEN_ID, accessToken.getId());
            }

            if (refreshToken != null) {
                if (event.getEvent().getDetails().containsKey(Details.REFRESH_TOKEN_ID)) {
                    event.detail(Details.UPDATED_REFRESH_TOKEN_ID, refreshToken.getId());
                } else {
                    event.detail(Details.REFRESH_TOKEN_ID, refreshToken.getId());
                }
                event.detail(Details.REFRESH_TOKEN_TYPE, refreshToken.getType());
            }

            AccessTokenResponse res = new AccessTokenResponse();
            if (idToken != null) {
                String encodedToken = new JWSBuilder().jsonContent(idToken).rsa256(realm.getPrivateKey());
                res.setIdToken(encodedToken);
            }
            if (accessToken != null) {
                String encodedToken = new JWSBuilder().jsonContent(accessToken).rsa256(realm.getPrivateKey());
                res.setToken(encodedToken);
                res.setTokenType("bearer");
                res.setSessionState(accessToken.getSessionState());
                if (accessToken.getExpiration() != 0) {
                    res.setExpiresIn(accessToken.getExpiration() - Time.currentTime());
                }
            }
            if (refreshToken != null) {
                String encodedToken = new JWSBuilder().jsonContent(refreshToken).rsa256(realm.getPrivateKey());
                res.setRefreshToken(encodedToken);
                if (refreshToken.getExpiration() != 0) {
                    res.setRefreshExpiresIn(refreshToken.getExpiration() - Time.currentTime());
                }
            }
            int notBefore = realm.getNotBefore();
            if (client.getNotBefore() > notBefore) notBefore = client.getNotBefore();
            res.setNotBeforePolicy(notBefore);
            return res;
        }
    }

    public class RefreshResult {

        private final AccessTokenResponse response;
        private final boolean offlineToken;

        private RefreshResult(AccessTokenResponse response, boolean offlineToken) {
            this.response = response;
            this.offlineToken = offlineToken;
        }

        public AccessTokenResponse getResponse() {
            return response;
        }

        public boolean isOfflineToken() {
            return offlineToken;
        }
    }

}


text:
<?php
	defined('BASEPATH') OR exit('No direct script access allowed');

	class Page extends CI_Controller{

		public function __construct (){
	        parent::__construct();
	        $this->load->model("dao/DaoPage");
		}

		public function index($pageid){
			//$data['PAGE_NAME']  = $pageName;
			//$data['TITLE'] = $pageName;
			$data['PAGE'] = $this->DaoPage->getPageById($pageid);
			if($data['PAGE']==null){
				redirect('page_no_found');
			}
			$this->load->view('page', $data);
		}
	}
?>


text:
$version="1.0.0"

$searchPath = [System.Environment]::GetEnvironmentVariable("Path")
# Copy-Item ../../mq4/MtApi.ex4 ./build/MtApi.ex4 -Force
# [Environment]::SetEnvironmentVariable("Path", "$searchPath;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\16.0\Bin")
[Environment]::SetEnvironmentVariable("Path", "$searchPath;C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\16.0\Bin;E:\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin")
#cmd.exe /c "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools\\VsMSBuildCmd.bat"
Write-Output "building clrwrapper..."
msbuild ../P23.MetaTrader4.Manager.ClrWrapper.Core/P23.MetaTrader4.Manager.ClrWrapper.Core.vcxproj -target:clean -target:restore -target:build -p:configuration=Release -p:platform=win32
Write-Output "build clrwrapper nuget package..."
./nuget.exe pack .\clrwrapper.nuspec -Version $version

Write-Output "pushing clrwrapper package"
./nuget.exe push P23.MetaTrader4.Manager.ClrWrapper.Core.$version.nupkg -source mohun -source mohun2 -configfile nuget.config -ApiKey dummy