text:
package mainecoon

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.meta._
import Util._

import collection.immutable.Seq

/**
 * auto generates an instance of [[InvariantK]]
 */
@compileTimeOnly("Cannot expand @autoInvariantK")
class autoInvariantK(autoDerivation: Boolean) extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    val autoDerivation: Boolean = this match {
      case q"new $_(${Lit.Boolean(arg)})" => arg
      case q"new $_(autoDerivation = ${Lit.Boolean(arg)})" => arg
      case _  => true
    } //todo: code dup with autoFunctorK
    enrichAlgebra(defn)(a => new InvariantKInstanceGenerator(a, autoDerivation).newTypeDef)
  }
}

class InvariantKInstanceGenerator(algDefn: AlgDefn, autoDerivation: Boolean) extends FunctorKInstanceGenerator(algDefn) {
  import algDefn._
  import cls._

  case class EffParam(p: Term.Param, tpeArg: Type)

  class ParamParser(params: Seq[Term.Param]) {
    lazy val effParams: Seq[EffParam] =
      params.collect {
        case p @ Term.Param(_, _, Some(Type.Apply(Type.Name(`effectTypeName`), Seq(tpeArg))), _) =>
          EffParam(p, tpeArg)
      }

    lazy val newArgs: Seq[Term] =
      params.map {
        case p if effParams.exists(_.p == p) => q"gk(${Term.Name(p.name.value)})"
        case p => Term.Name(p.name.value)
      }

    lazy val newParams: Seq[Term.Param] =
      params.map { p =>
        effParams.find(_.p == p).fold(p) { effP =>
          effP.p.copy(decltpe = Some(Type.Apply(Type.Name("G"), Seq(effP.tpeArg))))
        }
      }
  }

  lazy val instanceDef: Seq[Defn] = {
    def newMethod(methodName: Term.Name,
                  params: Seq[Term.Param],
                  resultType: Type,
                  mTParams: Seq[Type.Param]): Defn.Def = {
      val pp = new ParamParser(params)

      if(pp.effParams.isEmpty) {
        val (newResultType, newImpl) = covariantTransform(resultType, q"af.$methodName(..${arguments(params)})" )

        q"""override def $methodName[..$mTParams](..$params): $newResultType = $newImpl"""
      } else {
        val (newResultType, newImpl) = covariantTransform(resultType, q"af.$methodName(..${pp.newArgs})" )
        q"""override def $methodName[..$mTParams](..${pp.newParams}): $newResultType = $newImpl """
      }
    }

    //todo: duplicated with newMethod
    def newMethodCurry(methodName: Term.Name,
                  params: Seq[Term.Param],
                  params2: Seq[Term.Param],
                  resultType: Type,
                  mTParams: Seq[Type.Param]): Defn.Def = {
      val pp = new ParamParser(params)
      val pp2= new ParamParser(params2)

      if(pp.effParams.isEmpty) {
        val (newResultType, newImpl) = covariantTransform(resultType, q"af.$methodName(..${arguments(params)})(..${arguments(params2)})" )

        q"""override def $methodName[..$mTParams](..$params)(..$params2): $newResultType = $newImpl"""
      } else {
        val (newResultType, newImpl) = covariantTransform(resultType, q"af.$methodName(..${pp.newArgs})(..${pp2.newArgs})" )
        q"""override def $methodName[..$mTParams](..${pp.newParams})(..${pp2.newParams}): $newResultType = $newImpl """
      }
    }

    val methods = fromExistingStats {
      case q"def $methodName[..$mTParams](..$params): $resultType" =>
        newMethod(methodName, params, resultType, mTParams)
      case st @ q"def $methodName[..$mTParams](..$params) = $impl" =>
        abort(s"mainecoon.autoInvariantK does not support method without declared return type. as in $st ")
      case q"def $methodName[..$mTParams](..$params): $resultType = $impl"  =>
        newMethod(methodName, params, resultType.get, mTParams)

      case q"def $methodName[..$mTParams](..$params)(..$params2): $resultType" =>
        newMethodCurry(methodName, params, params2, resultType, mTParams)
      case st @ q"def $methodName[..$mTParams](..$params)(..$params2) = $impl" =>
        abort(s"mainecoon.autoInvariantK does not support method without declared return type. as in $st ")
      case q"def $methodName[..$mTParams](..$params)(..$params2): $resultType = $impl"  =>
        newMethodCurry(methodName, params, params2, resultType.get, mTParams)

    } ++ defWithoutParams

    val from = Term.Name("af")
    //create a mapK method in the companion object with more precise refined type signature

    def newInstance(newTypeMembers: Seq[Defn.Type]): Term.New =
      q"""
         new ${Ctor.Ref.Name(name.value)}[..${tArgs("G")}] {
                  ..$newTypeMembers
                   ..$methods
                 }
       """
    Seq(
      q"""
        def imapK[F[_], G[_], ..$extraTParams]($from: ${newTypeSig("F")})(fk: _root_.cats.~>[F, G])(gk: _root_.cats.~>[G, F]): ${dependentRefinedTypeSig("G", from)} =
          ${newInstance(newTypeMember(from))}
      """,
      q"""
        implicit def ${Term.Name("invariantKFor" + name.value)}[..$extraTParams]: _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffect] =
          new _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffect] {
            def imapK[F[_], G[_]]($from: $name[..${tArgs("F")}])(fk: _root_.cats.~>[F, G])(gk: _root_.cats.~>[G, F]): $name[..${tArgs("G")}] =
            ${newInstance(newTypeMember(from))}
          }
       """,
      q"""
       object fullyRefined {
         implicit def ${Term.Name("invariantKForFullyRefined" + name.value)}[..$fullyRefinedTParams]: _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffectFullyRefined] =
            new _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffectFullyRefined] {
              def imapK[F[_], G[_]]($from: ${fullyRefinedTypeSig("F")})(fk: _root_.cats.~>[F, G])(gk: _root_.cats.~>[G, F]): ${fullyRefinedTypeSig("G")} =
                ${newInstance(newTypeMemberFullyRefined)}
            }
         object autoDerive {
           @SuppressWarnings(Array("org.wartremover.warts.ImplicitParameter"))
           implicit def fromInvariantK[${effectType}, G[_], ..${fullyRefinedTParams}](
             implicit af: ${fullyRefinedTypeSig()},
             IK: _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffectFullyRefined],
             fk: _root_.cats.~>[F, G],
             gk: _root_.cats.~>[G, F])
               : ${fullyRefinedTypeSig("G")}= IK.imapK(af)(fk)(gk)
         }
       }
      """)
  }

  lazy val autoDerivationDef  = if(autoDerivation)
      Seq(q"""
          object autoDerive {
            @SuppressWarnings(Array("org.wartremover.warts.ImplicitParameter"))
            implicit def autoDeriveFromInvariantK[${effectType}, G[_], ..${extraTParams}](
              implicit af: $name[..${tArgs()}],
              IK: _root_.mainecoon.InvariantK[$typeLambdaVaryingHigherKindedEffect],
              fk: _root_.cats.~>[F, G],
              gk: _root_.cats.~>[G, F])
                : $name[..${tArgs("G")}] = IK.imapK(af)(fk)(gk)
          }
        """)
    else Nil

  lazy val newTypeDef = cls.copy(companion = companion.addStats(instanceDef ++ autoDerivationDef))
}


text:
//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#ifdef _MSC_VER
#pragma warning(disable: 4251)
#pragma warning(disable: 4275)
#endif

#ifndef URHO3D_API_H
#define URHO3D_API_H

#ifdef URHO3D_STATIC_DEFINE
#  define URHO3D_API
#  define URHO3D_NO_EXPORT
#else
#  ifndef URHO3D_API
#    ifdef URHO3D_EXPORTS
        /* We are building this library */
#      define URHO3D_API __declspec(dllexport)
#    else
        /* We are using this library */
#      define URHO3D_API __declspec(dllimport)
#    endif
#  endif

#  ifndef URHO3D_NO_EXPORT
#    define URHO3D_NO_EXPORT
#  endif
#endif

#ifndef URHO3D_DEPRECATED
#  define URHO3D_DEPRECATED __declspec(deprecated)
#  define URHO3D_DEPRECATED_EXPORT URHO3D_API __declspec(deprecated)
#  define URHO3D_DEPRECATED_NO_EXPORT URHO3D_NO_EXPORT __declspec(deprecated)
#endif

#define DEFINE_NO_DEPRECATED 0
#if DEFINE_NO_DEPRECATED
# define URHO3D_NO_DEPRECATED
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/graphnode/vpl-runner.svg?branch=master)](https://travis-ci.org/graphnode/vpl-runner)
[![Dependency Status](https://david-dm.org/graphnode/vpl-runner.svg)](https://david-dm.org/graphnode/vpl-runner)
[![devDependency Status](https://david-dm.org/graphnode/vpl-runner/dev-status.svg)](https://david-dm.org/graphnode/vpl-runner#info=devDependencies)
[![Coverage Status](https://coveralls.io/repos/github/graphnode/vpl-runner/badge.svg?branch=master)](https://coveralls.io/github/graphnode/vpl-runner?branch=master)

___
## What is it?

VPL-Runner is a small prototype on how a code graph, which connects single responsibility processes, would run.
The graph is written in JSON and the schema based on the noflo schema seen [here](https://github.com/noflo/noflo/blob/master/graph-schema.json).

## How to install and run

Just run `npm install` in the project directory and then `node index graph_file` where `graph_file` is the path to graph file in json format.

## Is it any good?

Not yet. :worried:


text:
#ifndef PROFILE_AFS_H
#define PROFILE_AFS_H

#include "program.h"

void profile_afs(int argc, char ** argv);

#endif


text:
package org.apache.activemq.artemis.utils.critical;

import java.util.ConcurrentModificationException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.activemq.artemis.core.server.ActiveMQScheduledComponent;
import org.apache.activemq.artemis.utils.ConcurrentHashSet;
import org.jboss.logging.Logger;

public class CriticalAnalyzerImpl implements CriticalAnalyzer {

   private final Logger logger = Logger.getLogger(CriticalAnalyzer.class);

   private volatile long timeoutNanoSeconds;

   // one minute by default.. the server will change it for sure
   private volatile long checkTimeNanoSeconds = TimeUnit.SECONDS.toNanos(60);

   private final ActiveMQScheduledComponent scheduledComponent;

   private final AtomicBoolean running = new AtomicBoolean(false);

   public CriticalAnalyzerImpl() {
      // this will make the scheduled component to start its own pool

      /* Important: The scheduled component should have its own thread pool...
       *  otherwise in case of a deadlock, or a starvation of the server the analyzer won't pick up any
       *  issues and won't be able to shutdown the server or halt the VM
       */
      this.scheduledComponent = new ActiveMQScheduledComponent(null, null, checkTimeNanoSeconds, TimeUnit.NANOSECONDS, false) {
         @Override
         public void run() {
            logger.trace("Checking critical analyzer");
            check();
         }
      };

   }

   @Override
   public void clear() {
      actions.clear();
      components.clear();
   }

   private CopyOnWriteArrayList<CriticalAction> actions = new CopyOnWriteArrayList<>();

   private final ConcurrentHashSet<CriticalComponent> components = new ConcurrentHashSet<>();

   @Override
   public int getNumberOfComponents() {
      return components.size();
   }

   @Override
   public boolean isMeasuring() {
      return true;
   }

   @Override
   public void add(CriticalComponent component) {
      components.add(component);
   }

   @Override
   public void remove(CriticalComponent component) {
      components.remove(component);
   }

   @Override
   public CriticalAnalyzer setCheckTime(long timeout, TimeUnit unit) {
      this.checkTimeNanoSeconds = unit.toNanos(timeout);
      this.scheduledComponent.setPeriod(timeout, unit);
      return this;
   }

   @Override
   public long getCheckTimeNanoSeconds() {
      if (checkTimeNanoSeconds == 0) {
         checkTimeNanoSeconds = getTimeout(TimeUnit.NANOSECONDS) / 2;
      }
      return checkTimeNanoSeconds;
   }

   @Override
   public CriticalAnalyzer setTimeout(long timeout, TimeUnit unit) {
      if (checkTimeNanoSeconds <= 0) {
         this.setCheckTime(timeout / 2, unit);
      }
      this.timeoutNanoSeconds = unit.toNanos(timeout);
      return this;
   }

   @Override
   public long getTimeout(TimeUnit unit) {
      if (timeoutNanoSeconds == 0) {
         timeoutNanoSeconds = TimeUnit.MINUTES.toNanos(2);
      }
      return unit.convert(timeoutNanoSeconds, TimeUnit.NANOSECONDS);
   }

   @Override
   public CriticalAnalyzer addAction(CriticalAction action) {
      this.actions.add(action);
      return this;
   }

   @Override
   public void check() {
      boolean retry = true;
      while (retry) {
         try {
            for (CriticalComponent component : components) {

               if (component.isExpired(timeoutNanoSeconds)) {
                  fireAction(component);
                  // no need to keep running if there's already a component failed
                  return;
               }
            }
            retry = false; // got to the end of the list, no need to retry
         } catch (ConcurrentModificationException dontCare) {
            // lets retry on the loop
         }
      }
   }

   private void fireAction(CriticalComponent component) {
      for (CriticalAction action : actions) {
         try {
            action.run(component);
         } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
         }
      }

      actions.clear();
   }

   @Override
   public void start() {
      scheduledComponent.start();

   }

   @Override
   public void stop() {
      scheduledComponent.stop();
   }

   @Override
   public boolean isStarted() {
      return scheduledComponent.isStarted();
   }
}


text:
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';

const useStyles = makeStyles(theme => ({
  close: {
    padding: theme.spacing(0.5),
  },
}));

function SimpleSnackbar() {
  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  function handleClick() {
    setOpen(true);
  }

  function handleClose(event, reason) {
    if (reason === 'clickaway') {
      return;
    }

    setOpen(false);
  }

  return (

      <Button onClick={handleClick}>Open simple snackbar</Button>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        open={open}
        autoHideDuration={6000}
        onClose={handleClose}
        ContentProps={{
          'aria-describedby': 'message-id',
        }}
        message={Note archived}
        action={[
          <Button key="undo" color="secondary" size="small" onClick={handleClose}>
            UNDO
          </Button>,
          <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            className={classes.close}
            onClick={handleClose}
          >
            <CloseIcon />
          </IconButton>,
        ]}
      />

  );
}

export default SimpleSnackbar;


text: Classifying Botnets using different machine learning methods


text:
<?php

/**
 *
 *
 * @author      HiPay <support.tpp@hipay.com>
 * @copyright   Copyright (c) 2018 - HiPay
 * @license     https://github.com/hipay/hipay-fullservice-sdk-magento1/blob/master/LICENSE.md
 * @link    https://github.com/hipay/hipay-fullservice-sdk-magento1
 */
class Allopass_Hipay_CheckoutController extends Mage_Core_Controller_Front_Action
{

    /**
     * @return Mage_Core_Controller_Front_Action
     */
    public function preDispatch()
    {
        parent::preDispatch();
    }

    public function pendingAction()
    {
        $session = $this->getOnepage()->getCheckout();
        if (!$session->getLastSuccessQuoteId()) {
            $this->_redirect('checkout/cart');
            return;
        }

        $lastQuoteId = $session->getLastQuoteId();
        $lastOrderId = $session->getLastOrderId();
        $lastRecurringProfiles = $session->getLastRecurringProfileIds();
        if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
            $this->_redirect('checkout/cart');
            return;
        }

        $session->clear();
        $this->loadLayout();
        $this->_initLayoutMessages('checkout/session');
        $this->renderLayout();
    }

    /**
     * Get one page checkout model
     *
     * @return Mage_Checkout_Model_Type_Onepage
     */
    public function getOnepage()
    {
        return Mage::getSingleton('checkout/type_onepage');
    }
}


text:
#include <stdio.h>
#include <math.h>

#include "gps_demo.h"
#include <src/utils.h>
#include <src/logInterface.h>

/* creates random GPSSamp data for simulation.
 directly sets samp value rather than generate a cusom NMEA sentence
 ** for that see RPiGPSDemo
*/
int getGPSSample_DEMO(FullGPSData* samp, bool passToLog, void* userData){
	//TODO: introduce some randomizing factor
	samp->spdKph = 1.34f;
	samp->course = 50.0f;

	samp->longitude = 6.7f;
	samp->latitude += 0.5f;
	//samp->latitude = samp->latitude +  samp->spdKph * sin(samp->course * PI/180);
	//samp->longitude = samp->latitude +  samp->spdKph * cos(samp->course * PI/180);
	samp->altitude = 280.0f;

	char logStr[120];
	sprintf(logStr, "DEMO: lat: %f, lon: %f, alt: %f, crs: %f, spd(kph): %f |", samp->latitude, samp->longitude,
			samp->altitude, samp->course, samp->spdKph);

	logEvent(logStr, LOG4C_PRIORITY_INFO, INFO, &logMaster);
	return FULL_SAMPLE;
}


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load bootstrap3 %}
{% block head_title %}{% trans "Change Password" %}{% endblock %}

{% block content %}

{% trans "Change Password" %}

        <form method="POST" action="{% url 'account_change_password' %}" class="password_change">
            {% csrf_token %}
            {% bootstrap_form form %}
            <button type="submit" name="action" class="btn btn-primary btn-block">{% trans "Change Password" %}</button>
        </form>

{% endblock %}


text:
title: OAuth2 Authentication | Kubernetes Ingress
menu:
  docs_{{ .version }}:
    identifier: oauth2-google
    name: OAuth2 Google
    parent: oauth2-security
    weight: 20
product_name: voyager
menu_name: docs_{{ .version }}
section_menu_id: guides
---

> New to Voyager? Please start [here](/docs/concepts/overview.md).

# OAuth2 Authentication Using Google

This example will demonstrate how to configure external authentication in both TLS and non-TLS mode using Google as auth provider.

## Example using Google (no TLS)

First configure google auth provider by following instructions provided [here](https://github.com/bitly/oauth2_proxy#google-auth-provider) and generate client-id and client-secret.

In this example `Authorized JavaScript origins` is set to `http://voyager.appscode.ninja`
and `Authorized redirect URIs` is set to `http://voyager.appscode.ninja/oauth2/callback`.

Now deploy and expose a test server:

```bash
$ kubectl run test-server --image=gcr.io/google_containers/echoserver:1.8
$ kubectl expose deployment test-server --port=80 --target-port=8080
```

Configure, deploy and expose oauth2-proxy:

```yaml
$ kubectl apply -f oauth2-proxy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    k8s-app: oauth2-proxy
  name: oauth2-proxy
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: oauth2-proxy
  template:
    metadata:
      labels:
        k8s-app: oauth2-proxy
    spec:
      containers:
      - args:
        - --provider=google
        - --email-domain=*
        - --upstream=file:///dev/null
        - --http-address=0.0.0.0:4180
        - --cookie-secure=false
        - --pass-authorization-header=true
        - --set-authorization-header=true
        - --set-xauthrequest=true
        env:
        - name: OAUTH2_PROXY_CLIENT_ID
          value: ...
        - name: OAUTH2_PROXY_CLIENT_SECRET
          value: ...
        - name: OAUTH2_PROXY_COOKIE_SECRET
          value: ...
        image: quay.io/pusher/oauth2_proxy:v3.1.0
        imagePullPolicy: Always
        name: oauth2-proxy
        ports:
        - containerPort: 4180
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    k8s-app: oauth2-proxy
  name: oauth2-proxy
  namespace: default
spec:
  ports:
  - name: http
    port: 4180
    protocol: TCP
    targetPort: 4180
  selector:
    k8s-app: oauth2-proxy
```

Here, `--set-xauthrequest` flag sets `X-Auth-Request-User` and `X-Auth-Request-Email` headers, which will be forwarded to backend. `--pass-authorization-header` and `--set-authorization-header` set OIDC IDToken via `Authorization` Bearer header and `X-Auth-Request-Id-Token` header.

Finally create the ingress:

```yaml
$ kubectl apply -f auth-ingress.yaml

apiVersion: voyager.appscode.com/v1
kind: Ingress
metadata:
  name: auth-ingress
  namespace: default
spec:
  frontendRules:
  - port: 80
    auth:
      oauth:
      - host: voyager.appscode.ninja
        authBackend: auth-be
        authPath: /oauth2/auth
        signinPath: /oauth2/start
        paths:
        - /app
  rules:
  - host: voyager.appscode.ninja
    http:
      paths:
      - path: /health
        backend:
          service:
            name: test-server
            port:
              number: 80
      - path: /app
        backend:
          service:
            name: test-server
            port:
              number: 80
      - path: /oauth2
        backend:
          name: auth-be
          service:
            name: oauth2-proxy
            port:
              number: 4180
```

Now browse the followings:

- http://voyager.appscode.ninja/app (external-auth required)
- http://voyager.appscode.ninja/health (external-auth not required)

## Example using Google (with TLS)

First configure google auth provider by following instructions provided [here](https://github.com/bitly/oauth2_proxy#google-auth-provider) and generate client-id and client-secret.

In this example `Authorized JavaScript origins` is set to `https://voyager.appscode.ninja`
and `Authorized redirect URIs` is set to `https://voyager.appscode.ninja/oauth2/callback`.

Now deploy and expose a test server:

```bash
$ kubectl run test-server --image=gcr.io/google_containers/echoserver:1.8
$ kubectl expose deployment test-server --port=80 --target-port=8080
```

Create TLS secret:

```bash
$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /tmp/tls.key -out /tmp/tls.crt -subj "/CN=voyager.appscode.ninja"
$ kubectl create secret tls tls-secret --key /tmp/tls.key --cert /tmp/tls.crt
```

Configure, deploy and expose oauth2-proxy:

```yaml
$ kubectl apply -f oauth2-proxy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    k8s-app: oauth2-proxy
  name: oauth2-proxy
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: oauth2-proxy
  template:
    metadata:
      labels:
        k8s-app: oauth2-proxy
    spec:
      containers:
      - args:
        - --provider=google
        - --email-domain=*
        - --upstream=file:///dev/null
        - --http-address=0.0.0.0:4180
        - --cookie-secure=true
        - --set-xauthrequest=true
        env:
        - name: OAUTH2_PROXY_CLIENT_ID
          value: ...
        - name: OAUTH2_PROXY_CLIENT_SECRET
          value: ...
        - name: OAUTH2_PROXY_COOKIE_SECRET
          value: ...
        image: quay.io/pusher/oauth2_proxy:v3.1.0
        imagePullPolicy: Always
        name: oauth2-proxy
        ports:
        - containerPort: 4180
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    k8s-app: oauth2-proxy
  name: oauth2-proxy
  namespace: default
spec:
  ports:
  - name: http
    port: 4180
    protocol: TCP
    targetPort: 4180
  selector:
    k8s-app: oauth2-proxy
```

Finally create the ingress:

```yaml
$ kubectl apply -f auth-ingress.yaml

apiVersion: voyager.appscode.com/v1
kind: Ingress
metadata:
  name: auth-ingress
  namespace: default
spec:
  tls:
  - secretName: tls-secret
    hosts:
    - voyager.appscode.ninja
  frontendRules:
  - port: 443
    auth:
      oauth:
      - host: voyager.appscode.ninja
        authBackend: auth-be
        authPath: /oauth2/auth
        signinPath: /oauth2/start
        paths:
        - /app
  rules:
  - host: voyager.appscode.ninja
    http:
      paths:
      - path: /health
        backend:
          service:
            name: test-server
            port:
              number: 80
      - path: /app
        backend:
          service:
            name: test-server
            port:
              number: 80
      - path: /oauth2
        backend:
          name: auth-be
          service:
            name: oauth2-proxy
            port:
              number: 4180
```

Now browse the followings:

- https://voyager.appscode.ninja/app (external-auth required)
- https://voyager.appscode.ninja/health (external-auth not required)


text:
package org.optaplanner.osgi.common.app;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class DelegationClassloader extends ClassLoader {
	private final ClassLoader[] delegates;

	public DelegationClassloader(ClassLoader... classLoaders) {
		if (classLoaders == null)
			throw new NullPointerException();

		delegates = classLoaders;
	}

	@Override
	public URL getResource(String name) {
		for (ClassLoader cl : delegates) {
			URL res = cl.getResource(name);
			if (res != null)
				return res;
		}
		return null;
	}

	@Override
	public InputStream getResourceAsStream(String name) {
		for (ClassLoader cl : delegates) {
			InputStream is = cl.getResourceAsStream(name);
			if (is != null)
				return is;
		}
		return null;
	}

	@Override
	public Enumeration<URL> getResources(String name) throws IOException {
		List<URL> urls = new ArrayList<URL>();
		for (ClassLoader cl : delegates) {
			urls.addAll(Collections.list(cl.getResources(name)));
		}
		return Collections.enumeration(urls);
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		ClassNotFoundException lastEx = null;
		for (ClassLoader cl : delegates) {
			try {
				return cl.loadClass(name);
			} catch (ClassNotFoundException e) {
				lastEx = e;
			}
		}
		throw lastEx;
	}
}


text:
"""Extract-transform-load utility.

Currently only download and upload of Course Builder 1.3 data is implemented.
Example use:

$ python etl.py download course /cs101 myapp server.appspot.com \
    archive.zip --sdk_path=/path/to/my/appengine/sdk

This will result in a file called archive.zip that contains the contents of
the Course Builder 1.3 course found at the URL /cs101 on the application with id
myapp running on the server named server.appspot.com.  archive.zip will contain
assets and data from the course along with a manifest.json enumerating them.
The format of archive.zip will change and should not be relied upon.

For upload,

$ python etl.py upload course /cs101 myapp server.appspot.com \
    archive.zip --sdk_path/path/to/my_appengine/sdk

In order to run this script, you must first ensure all third-party libraries
required by Course Builder are installed and importable.

Pass --help for additional usage information.
"""

__author__ = [
    'johncox@google.com (John Cox)',
]

import argparse
import logging
import os
import sys
import zipfile
import yaml

# Placeholders for modules we'll import after setting up sys.path. This allows
# us to avoid lint suppressions at every callsite.
appengine_config = None
courses = None
remote = None
sites = None
transforms = None
vfs = None

# String. Path to course.json in an archive.
_COURSE_JSON_PATH = 'data/course.json'
# String. Path to course.yaml in an archive.
_COURSE_YAML_PATH = 'course.yaml'
# Path strings from local disk that will be included in the archive.
_LOCAL_WHITELIST = frozenset([_COURSE_YAML_PATH, 'assets', 'data'])
# logging.Logger. Module logger.
_LOG = logging.getLogger('coursebuilder.tools.etl')
logging.basicConfig()
# String. Name of the manifest file.
_MANIFEST_FILENAME = 'manifest.json'
# String. Identifier for download mode.
_MODE_DOWNLOAD = 'download'
# String. Identifer for upload mode.
_MODE_UPLOAD = 'upload'
# List of all modes.
_MODES = [_MODE_DOWNLOAD, _MODE_UPLOAD]
# Frozenset of strings containing App Engine SDK versions we support.
_SUPPORTED_APP_ENGINE_SDK_VERSIONS = frozenset(['1.7.0'])
# String. Identifier for type course.
_TYPE_COURSE = 'course'
# List of all types.
_TYPES = [_TYPE_COURSE]

# Command-line argument configuration.
_PARSER = argparse.ArgumentParser()
_PARSER.add_argument(
    'mode', choices=_MODES,
    help='indicates whether we are downloading or uploading data', type=str)
_PARSER.add_argument(
    'type', choices=_TYPES, help='type of entity to download', type=str)
_PARSER.add_argument(
    'course_url_prefix',
    help=(
        "URL prefix of the course you want to download (e.g. '/foo' in "
        "'course:/foo:/directory:namespace'"), type=str)
_PARSER.add_argument(
    'application_id',
    help="the id of the application to read from (e.g. 'myapp')", type=str)
_PARSER.add_argument(
    'server',
    help=('the full name of the source application to read from (e.g. '
          'myapp.appspot.com)'), type=str)
_PARSER.add_argument(
    'archive_path',
    help='absolute path of the archive file to read or write', type=str)
_PARSER.add_argument(
    '--log_level', help='Level of logging messages to emit', default='WARNING',
    type=lambda s: s.upper())
_PARSER.add_argument(
    '--sdk_path', help='absolute path of the App Engine SDK', required=True,
    type=str)

class _Archive(object):
    """Manager for local archives of Course Builder data.

    The internal format of the archive may change from version to version; users
    must not depend on it.

    Archives contain assets and data from a single course, along with a manifest
    detailing the course's raw definition string, version of Course Builder the
    course is compatible with, and the list of course files contained within
    the archive.

    # TODO(johncox): possibly obfuscate this archive so it cannot be unzipped
    # outside etl.py. Add a command-line flag for creating a zip instead. For
    # uploads, require an obfuscated archive, not a zip.
    """

    def __init__(self, path):
        """Constructs a new archive.

        Args:
            path: string. Absolute path where the archive will be written.
        """
        self._path = path
        self._zipfile = None

    def add(self, filename, contents):
        """Adds contents to the archive.

        Args:
            filename: string. Path of the contents to add.
            contents: bytes. Contents to add.
        """
        self._zipfile.writestr(_remove_bundle_root(filename), contents)

    def close(self):
        """Closes archive and test for integrity; must close before read."""
        self._zipfile.testzip()
        self._zipfile.close()

    def get(self, path):
        """Return the raw bytes of the archive entity found at path.

        Returns None if path is not in the archive.

        Args:
            path: string. Path of file to retrieve from the archive.

        Returns:
            Bytes of file contents.
        """
        assert self._zipfile
        try:
            return self._zipfile.read(path)
        except KeyError:
            pass

    def open(self, mode):
        """Opens archive in the mode given by mode string ('r', 'w', 'a')."""
        assert not self._zipfile
        self._zipfile = zipfile.ZipFile(self._path, mode)

    @property
    def manifest(self):
        """Returns the archive's manifest."""
        return _Manifest.from_json(self.get(_MANIFEST_FILENAME))

    @property
    def path(self):
        return self._path

class _Manifest(object):
    """Manifest that lists the contents and version of an archive folder."""

    def __init__(self, raw, version):
        """Constructs a new manifest.

        Args:
            raw: string. Raw course definition string.
            version: string. Version of Course Builder course this manifest was
                generated from.
        """
        self._entities = []
        self._raw = raw
        self._version = version

    @classmethod
    def from_json(cls, json):
        """Returns a manifest for the given JSON string."""
        parsed = transforms.loads(json)
        instance = cls(parsed['raw'], parsed['version'])
        for entity in parsed['entities']:
            instance.add(_ManifestEntity(entity['path'], entity['is_draft']))
        return instance

    def add(self, entity):
        self._entities.append(entity)

    def get(self, path):
        """Gets _Entity by path string; returns None if not found."""
        for entity in self._entities:
            if entity.path == path:
                return entity

    @property
    def entities(self):
        return sorted(self._entities, key=lambda e: e.path)

    @property
    def raw(self):
        return self._raw

    @property
    def version(self):
        return self._version

    def __str__(self):
        """Returns JSON representation of the manifest."""
        manifest = {
            'entities': [e.__dict__ for e in self.entities],
            'raw': self.raw,
            'version': self.version,
        }
        return transforms.dumps(manifest, indent=2, sort_keys=2)

class _ManifestEntity(object):
    """Object that represents an entity in a manifest."""

    def __init__(self, path, is_draft):
        self.is_draft = is_draft
        self.path = _remove_bundle_root(path)

class _ReadWrapper(object):
    """Wrapper for raw bytes that supports read()."""

    def __init__(self, data):
        """Constructs a new read wrapper.

        Args:
            data: bytes. The bytes to return on read().
        """
        self._data = data

    def read(self):
        return self._data

def _check_sdk(sdk_path):
    """Ensure that the SDK exists; warn if the version is not supported."""
    version = None
    try:
        with open(os.path.join(sdk_path, 'VERSION')) as f:
            # Cannot import transforms wrapper yet; use plain yaml module.
            contents = yaml.load(f.read())
            version = contents.get('release')
            if not version:  # SDK is malformed somehow.
                raise IOError
    except IOError:
        _die('Unable to find App Engine SDK at ' + sdk_path)
    if version not in _SUPPORTED_APP_ENGINE_SDK_VERSIONS:
        _LOG.warning(
            ('SDK version %s found at %s is not supported; behavior may be '
             'unpredictable') % (version, sdk_path))

def _die(message):
    _LOG.critical(message)
    sys.exit(1)

def _download(archive_path, course_url_prefix):
    """Downloads one course to an archive."""
    context = _get_requested_context(sites.get_all_courses(), course_url_prefix)
    if not context:
        _die('No course found with course_url_prefix %s' % course_url_prefix)
    course = _get_course_from(context)
    if course.version < courses.COURSE_MODEL_VERSION_1_3:
        _die(
            'Cannot export course with version < %s' % (
                courses.COURSE_MODEL_VERSION_1_3))
    archive = _Archive(archive_path)
    archive.open('w')
    manifest = _Manifest(context.raw, course.version)
    _LOG.info('Processing course with URL prefix ' + course_url_prefix)
    datastore_files = set(
        context.fs.impl.list(appengine_config.BUNDLE_ROOT))
    all_files = set(_filter_filesystem_files(context.fs.impl.list(
        appengine_config.BUNDLE_ROOT, include_inherited=True)))
    filesystem_files = all_files - datastore_files
    _LOG.info('Adding files from datastore')
    for path in datastore_files:
        stream = context.fs.impl.get(path)
        entity = _ManifestEntity(path, stream.metadata.is_draft)
        archive.add(path, stream.read())
        manifest.add(entity)
    _LOG.info('Adding files from filesystem')
    for path in filesystem_files:
        with open(path) as f:
            archive.add(path, f.read())
            manifest.add(_ManifestEntity(path, False))
    _LOG.info('Adding manifest')
    archive.add(_MANIFEST_FILENAME, str(manifest))
    archive.close()
    _LOG.info('Done; archive saved to ' + archive.path)

def _filter_filesystem_files(files):
    """Filters out unnecessary files from a local filesystem.

    If we just read from disk, we'll pick up and archive lots of files that we
    don't need to upload later.

    Args:
        files: list of string. Absolute file paths.

    Returns:
        List of string. Absolute filepaths we want to archive.
    """
    return [
        f for f in files if _remove_bundle_root(f).split('/')[0]
        in _LOCAL_WHITELIST]

def _get_course_from(app_context):
    """Gets a courses.Course from the given sites.ApplicationContext."""

    class _Adapter(object):
        def __init__(self, app_context):
            self.app_context = app_context

    return courses.Course(_Adapter(app_context))

def _get_root_path():
    """Finds absolute Course Builder root path."""
    path = os.path.abspath(__file__)
    while not path.endswith('coursebuilder'):
        path = os.path.split(path)[0]
    return path

def _import_modules_into_global_scope():
    """Import helper; run after _set_up_sys_path() for imports to resolve."""
    # pylint: disable-msg=g-import-not-at-top,global-variable-not-assigned,
    # pylint: disable-msg=redefined-outer-name,unused-variable
    global appengine_config
    global sites
    global courses
    global transforms
    global vfs
    global remote
    import appengine_config
    from controllers import sites
    from models import courses
    from models import transforms
    from models import vfs
    from tools.etl import remote

def _get_requested_context(app_contexts, course_url_prefix):
    """Gets requested app_context from list based on course_url_prefix str."""
    found = None
    for context in app_contexts:
        if context.raw.startswith('course:%s:' % course_url_prefix):
            found = context
            break
    return found

def _remove_bundle_root(path):
    """Removes BUNDLE_ROOT prefix from a path."""
    if path.startswith(appengine_config.BUNDLE_ROOT):
        path = path.split(appengine_config.BUNDLE_ROOT)[1]
    # Path must not start with / so it is os.path.join()able.
    if path.startswith('/'):
        path = path[1:]
    return path

def _set_up_sys_path(sdk_path):
    """Sets up sys.path so App Engine/Course Builder imports work."""
    assert os.path.exists(sdk_path)
    for path in [
            # Find course builder root by navigating up two folders from here.
            os.path.abspath(__file__).rsplit(os.sep, 3)[0],
            sdk_path,
            # Add webapp2 so we can find webapp2_extras.
            os.path.join(sdk_path, 'lib', 'webapp2')]:
        if path not in sys.path:
            # Have to insert at head or app engine imports won't resolve.
            sys.path.insert(0, path)

def _upload(archive_path, course_url_prefix):
    _LOG.info((
        'Processing course with URL prefix %s from archive path %s' % (
            course_url_prefix, archive_path)))
    context = _get_requested_context(sites.get_all_courses(), course_url_prefix)
    if not context:
        _die('No course found with course_url_prefix %s' % course_url_prefix)
    course = _get_course_from(context)
    if course.get_units():
        _die(
            'Cannot upload to non-empty course with course_url_prefix %s' % (
                course_url_prefix))
    archive = _Archive(archive_path)
    try:
        archive.open('r')
    except IOError:
        _die('Cannot open archive_path ' + archive_path)
    course_json = archive.get(_COURSE_JSON_PATH)
    if course_json:
        try:
            courses.PersistentCourse13().deserialize(course_json)
        except (AttributeError, ValueError):
            _die((
                'Cannot upload archive at %s containing malformed '
                'course.json') % archive_path)
    course_yaml = archive.get(_COURSE_YAML_PATH)
    if course_yaml:
        try:
            yaml.safe_load(course_yaml)
        except Exception:  # pylint: disable-msg=broad-except
            _die((
                'Cannot upload archive at %s containing malformed '
                'course.yaml') % archive_path)
    _LOG.info('Validation passed; beginning upload')
    count = 0
    for entity in archive.manifest.entities:
        context.fs.impl.non_transactional_put(
            os.path.join(appengine_config.BUNDLE_ROOT, entity.path),
            _ReadWrapper(archive.get(entity.path)), is_draft=entity.is_draft)
        count += 1
        _LOG.info('Uploaded ' + entity.path)
    courses.CachedCourse13.delete(context)  # Force update in UI.
    _LOG.info(
        'Done; %s entit%s uploaded' % (count, 'y' if count == 1 else 'ies'))

def _validate_arguments(parsed_args):
    """Validate parsed args for additional constraints."""
    if (parsed_args.mode == _MODE_DOWNLOAD and
        os.path.exists(parsed_args.archive_path)):
        _die(
            'Cannot download to archive path %s; file already exists.' % (
                parsed_args.archive_path))

def main(parsed_args, environment_class=None):
    """Performs the requested ETL operation.

    Args:
        parsed_args: argparse.Namespace. Parsed command-line arguments.
        environment_class: None or remote.Environment. Environment setup class
            used to configure the service stub map. Injectable for tests only;
            defaults to remote.Environment if not specified.
    """
    _validate_arguments(parsed_args)
    _set_up_sys_path(parsed_args.sdk_path)
    _LOG.setLevel(parsed_args.log_level.upper())
    _check_sdk(parsed_args.sdk_path)
    _import_modules_into_global_scope()
    if not environment_class:
        environment_class = remote.Environment
    _LOG.info('Mode is %s' % parsed_args.mode)
    _LOG.info(
        'Target is url %s from application_id %s on server %s' % (
            parsed_args.course_url_prefix, parsed_args.application_id,
            parsed_args.server))
    environment_class(
        parsed_args.application_id, parsed_args.server).establish()
    if parsed_args.mode == _MODE_DOWNLOAD:
        _download(parsed_args.archive_path, parsed_args.course_url_prefix)
    elif parsed_args.mode == _MODE_UPLOAD:
        _upload(parsed_args.archive_path, parsed_args.course_url_prefix)

if __name__ == '__main__':
    main(_PARSER.parse_args())


text:
import { expect } from 'chai';

import { Translation } from '../src';

describe('Translate', () => {
  describe('dictionary()', () => {
    let t;
    before(() => {
      t = new Translation();
    });

    it('is an empty plain object after construction', () => {
      expect(t.dictionary()).to.be.deep.equal({});
    });

    it('doesn\'t return clones', () => {
      const snapshot1 = t.dictionary();
      const snapshot2 = t.dictionary();
      expect(snapshot1).to.equal(snapshot2);
    });

    it('mutation of original tree is possible', () => {
      const snapshot = t.dictionary();
      snapshot.en = { test: 'Test expression' };
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });
    });
  });

  describe('load(locale, pairs)', () => {
    let t;
    beforeEach(() => {
      t = new Translation();
      t.load('en', { 'test': 'Test expression' });
    });

    it('sets localization tree if it doesn\'t exist', () => {
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });
    });

    it('extends existing tree - doesn\'t replace it', () => {
      t.load('en', { 'new': 'New test expression' });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression',
          new: 'New test expression' }
      });
    });

    it('replaces the values with already existing keys', () => {
      t.load('en', { test: 'Slightly different expression' });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Slightly different expression' }
      });
    });

    it('doesn\'t replace existing value if new value is undefined', () => {
      t.load('en', { test: undefined });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });
    });

    it('sets trees of different locales independently', () => {
      t.load('ru', { 'test': 'Тестовое выражение' });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' },
        ru: { test: 'Тестовое выражение' }
      });
    });

    it('is chainable', () => {
      expect(t.load()).to.equal(t);
    });
  });

  describe('loadRoot(root)', () => {
    let t;
    beforeEach(() => {
      t = new Translation();
    });

    it('extends empty dictionary - doesn\'t replace', () => {
      const snapshot = t.dictionary();

      expect(snapshot).to.be.equal(
        t.loadRoot({}).dictionary()
      );
      expect(snapshot).to.be.equal(
        t.loadRoot({ en: {} }).dictionary()
      );
      expect(snapshot).to.be.equal(
        t.loadRoot({ en: { test: 'Test expression' } }).dictionary()
      );
      expect(snapshot).to.deep.equal({
        en: { test: 'Test expression' }
      });
    });

    it('extends existing tree deeply', () => {
      t.loadRoot({ en: { test: 'Test expression' } });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });

      t.loadRoot({ en: { new: 'New test expression' } });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression', new: 'New test expression' }
      });

      t.loadRoot({ ru: { test: 'Тестовое выражение' } });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression', new: 'New test expression' },
        ru: { test: 'Тестовое выражение' }
      });
    });

    it('doesn\'t replace existing value if new value is undefined', () => {
      t.loadRoot({ en: { test: 'Test expression' } });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });

      t.loadRoot({ en: { test: undefined } });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });
    });

    it('is chainable', () => {
      expect(t.loadRoot({})).to.equal(t);
    });
  });

  describe('setLocale(locale, dic)', () => {
    let t;
    beforeEach(() => {
      t = new Translation();
    });

    it('sets dictionary of given locale forcefully', () => {
      t.setLocale('en', { test: 'Test expression' });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' }
      });

      t.setLocale('en', { new: 'New test expression' });
      expect(t.dictionary()).to.deep.equal({
        en: { new: 'New test expression' }
      });
    });

    it('sets different locales independently from each other', () => {
      t.setLocale('en', { test: 'Test expression' });
      t.setLocale('ru', { test: 'Тестовое выражение' });
      expect(t.dictionary()).to.deep.equal({
        en: { test: 'Test expression' },
        ru: { test: 'Тестовое выражение' }
      });
    });

    it('is chainable', () => {
      expect(t.setLocale('en', {})).to.equal(t);
    });
  });

  describe('translate(phrase, locale)', () => {
    describe('without fallback locale', () => {
      let t;
      before(() => {
        t = new Translation();
        t.loadRoot({
          en: { test: 'Test expression' },
          ru: { test: 'Тестовое выражение' }
        });
      });

      it('returns empty string if phrase doesn\'t exist', () => {
        expect(t.translate('doesn\'t exist', 'en')).to.equal('');
      });

      it('returns empty string if locale doesn\'t exist', () => {
        expect(t.translate('test', 'it')).to.equal('');
      });
    });

    describe('with fallback locale', () => {
      let t;
      before(() => {
        t = new Translation();
        t.loadRoot({
          en: { test: 'Test expression' },
          ru: { test: 'Тестовое выражение' }
        });
        t.fallbackLocale = 'en';
      });

      it('returns phrase of fallback locale if given locale doesn\'t have it', () => {
        expect(t.translate('doesn\'t exist', 'it')).to.equal(
          t.translate('doesn\'t exist', 'en')
        );
        expect(t.translate('doesn\'t exist', 'en')).to.equal('');
      });

      it('returns phrase of fallback locale if given locale doesn\'t exist', () => {
        expect(t.translate('test', 'it')).to.equal(
          t.translate('test', 'en')
        );
      });
    });

    describe('common', () => {
      let t;
      before(() => {
        t = new Translation();
        t.loadRoot({
          en: { test: 'Test expression' },
          ru: { test: 'Тестовое выражение' }
        });
      });

      it('returns matching phrase with given key and locale', () => {
        expect(t.translate('test', 'en')).to.equal('Test expression');
        expect(t.translate('test', 'ru')).to.equal('Тестовое выражение');
      });
    });
  });

  describe('translateTo(locale)', () => {
    let t;
    before(() => {
      t = new Translation();
      t.loadRoot({
        en: { test: 'Test expression' },
        ru: { test: 'Тестовое выражение' }
      });
    });

    it('returns translate function: (phrase: string) => string', () => {
      const f = t.translateTo('en');
      expect(f).is.instanceof(Function);
      expect(f).to.have.lengthOf(1);
      expect('').to.satisfy(x => typeof f(x) === 'string');
    });

    it('returns translate function if given locale doesn\'t exist', () => {
      expect(t.translateTo('it')('test')).to.equal(
        t.translate('test', 'it')
      );
    });

    it('translate function works', () => {
      expect(t.translateTo('en')('test')).to.equal('Test expression');
      expect(t.translateTo('ru')('test')).to.equal('Тестовое выражение');
    });
  });

  describe('translateCurrent(phrase)', () => {
    let t;
    before(() => {
      t = new Translation();
      t.loadRoot({
        en: { test: 'Test expression', new: 'New test expression' },
        ru: { test: 'Тестовое выражение' }
      });
    });

    it('returns \'\' if neither currentLocale not fallbackLocale are present', () => {
      expect(t.translateCurrent('test')).to.equal('');
    });

    it('returns phrase from fallbackLocale if currentLocale isn\'t present', () => {
      t.fallbackLocale = 'en';
      expect(t.translateCurrent('test')).to.equal('Test expression');
    });

    it('returns phrase from fallbackLocale if currentLocale doesn\'t have it', () => {
      t.currentLocale = 'ru';
      expect(t.translateCurrent('new')).to.equal('New test expression');
    });

    it('returns phrase with given key from currentLocale', () => {
      expect(t.translateCurrent('test')).to.equal('Тестовое выражение');
    });
  });

  describe('format(phrase, locale, ...args)', () => {
    let t;
    before(() => {
      t = new Translation();
      t.loadRoot({
        en: {
          from0: 'Count is zero-based: %1',
          multiple: 'Expression: %0 + %1 = %2',
          repeat: 'Repeat: %0 * %0 = %1'
        },
        ru: { test: 'Тестовое выражение' }
      });
    });

    describe('without fallback locale', () => {
      it('returns \'\' if neither given locale exists nor fallback locale is present', () => {
        expect(t.format('repeat', 'it', 8, 64)).to.equal('');
      });
    });

    describe('with fallback locale', () => {
      before(() => {
        t.fallbackLocale = 'en';
      });

      it('returns \'\' if given phrase isn\'t present in given and fallback locales', () => {
        expect(t.format('doesn\'t exist', 'ru', 'argument')).to.equal('');
      });

      it('returns phrase for fallback locale if given locale doesn\'t exist', () => {
        expect(t.format('repeat', 'it', 8, 64)).to.equal(
          'Repeat: 8 * 8 = 64'
        );
      });
    });

    describe('common', () => {
      before(() => {
        t.fallbackLocale = null;
      });

      it('arguments indexes\' count is zero-based', () => {
        expect(t.format('from0', 'en', 'argument')).to.equal(
          'Count is zero-based: undefined'
        );

        expect(t.format('from0', 'en', 'argument #0', 'argument #1')).to.equal(
          'Count is zero-based: argument #1'
        );
      });

      it('returns phrase filled with given arguments', () => {
        expect(t.format('multiple', 'en', 5, 6, '11')).to.equal(
          'Expression: 5 + 6 = 11'
        );
      });

      it('returns phrase if arguments aren\'t present', () => {
        expect(t.format('multiple', 'en')).to.equal(
          'Expression: undefined + undefined = undefined'
        );
      });

      it('uses the same arguments as many times as expected', () => {
        expect(t.format('repeat', 'en', 8, 64)).to.equal(
          'Repeat: 8 * 8 = 64'
        );
      });
    });
  });

  describe('formatTo(locale)', () => {
    let t;
    before(() => {
      t = new Translation();
      t.loadRoot({
        en: { test: 'Test expression: %0' },
        ru: { test: 'Тестовое выражение: %0' }
      });
    });

    it('returns format function: (phrase: string, ...args: Array<Any>) => string', () => {
      const f = t.formatTo('en');
      expect(f).is.instanceof(Function);
      expect(f).to.have.lengthOf(1);
      expect('').to.satisfy(x => typeof f(x) === 'string');
      expect('').to.satisfy(x => typeof f(x, 1) === 'string');
    });

    it('returns format function if given locale doesn\'t exist', () => {
      expect(t.formatTo('it')('test', 1)).to.equal(
        t.format('test', 'it', 1)
      );
    });

    it('format function works', () => {
      expect(t.formatTo('en')('test', 1)).to.equal('Test expression: 1');
      expect(t.formatTo('ru')('test', 1)).to.equal('Тестовое выражение: 1');
    });
  });

  describe('formatCurrent(phrase, ...args)', () => {
    let t;
    before(() => {
      t = new Translation();
      t.loadRoot({
        en: { test: 'Test expression: %0', new: 'New test expression: %0' },
        ru: { test: 'Тестовое выражение: %0' }
      });
    });

    it('returns \'\' if neither currentLocale not fallbackLocale are present', () => {
      expect(t.formatCurrent('test', 1)).to.equal('');
    });

    it('returns phrase from fallbackLocale if currentLocale isn\'t present', () => {
      t.fallbackLocale = 'en';
      expect(t.formatCurrent('test', 1)).to.equal('Test expression: 1');
    });

    it('returns phrase from fallbackLocale if currentLocale doesn\'t have it', () => {
      t.currentLocale = 'ru';
      expect(t.formatCurrent('new', 1)).to.equal('New test expression: 1');
    });

    it('returns phrase with given key from currentLocale', () => {
      expect(t.formatCurrent('test', 1)).to.equal('Тестовое выражение: 1');
    });
  });
});


text:
package setup

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/sacloud/libsacloud/v2/helper/defaults"

	"github.com/sacloud/libsacloud/v2/sacloud"
	"github.com/sacloud/libsacloud/v2/sacloud/accessor"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
)

// MaxRetryCountExceededError リトライ最大数超過エラー
type MaxRetryCountExceededError error

// CreateFunc リソース作成関数
type CreateFunc func(ctx context.Context, zone string) (accessor.ID, error)

// ProvisionBeforeUpFunc リソース作成後、起動前のプロビジョニング関数
//
// リソース作成後に起動が行われないリソース(VPCルータなど)向け。
// 必要であればこの中でリソース起動処理を行う。
type ProvisionBeforeUpFunc func(ctx context.Context, zone string, id types.ID, target interface{}) error

// DeleteFunc リソース削除関数。
//
// リソース作成時のコピー待ちの間にリソースのAvailabilityがFailedになった場合に利用される。
type DeleteFunc func(ctx context.Context, zone string, id types.ID) error

// ReadFunc リソース起動待ちなどで利用するリソースのRead用Func
type ReadFunc func(ctx context.Context, zone string, id types.ID) (interface{}, error)

// RetryableSetup リソース作成時にコピー待ちや起動待ちが必要なリソースのビルダー。
//
// リソースのビルドの際、必要に応じてリトライ(リソースの削除&再作成)を行う。
type RetryableSetup struct {
	// Create リソース作成用関数
	Create CreateFunc
	// IsWaitForCopy コピー待ちを行うか
	IsWaitForCopy bool
	// IsWaitForUp 起動待ちを行うか
	IsWaitForUp bool
	// ProvisionBeforeUp リソース起動前のプロビジョニング関数
	ProvisionBeforeUp ProvisionBeforeUpFunc
	// Delete リソース削除用関数
	Delete DeleteFunc
	// WaitForUp リソース起動待ち関数
	Read ReadFunc
	// RetryCount リトライ回数
	RetryCount int
	// ProvisioningRetryCount プロビジョニングリトライ回数
	ProvisioningRetryCount int
	// ProvisioningRetryInterval プロビジョニングリトライ間隔
	ProvisioningRetryInterval time.Duration
	// DeleteRetryCount 削除リトライ回数
	DeleteRetryCount int
	// DeleteRetryInterval 削除リトライ間隔
	DeleteRetryInterval time.Duration
	// sacloud.StateWaiterによるステート待ちの間隔
	PollingInterval time.Duration
}

// Setup リソースのビルドを行う。必要に応じてリトライ(リソースの削除&再作成)を行う。
func (r *RetryableSetup) Setup(ctx context.Context, zone string) (interface{}, error) {
	if (r.IsWaitForCopy || r.IsWaitForUp) && r.Read == nil {
		return nil, errors.New("failed: Read is required when IsWaitForCopy or IsWaitForUp is true")
	}

	r.init()

	var created interface{}
	for r.RetryCount+1 > 0 {
		r.RetryCount--

		// リソース作成
		target, err := r.createResource(ctx, zone)
		if err != nil {
			return nil, err
		}
		id := target.GetID()

		// コピー待ち
		if r.IsWaitForCopy {
			// コピー待ち、Failedになった場合はリソース削除
			state, err := r.waitForCopyWithCleanup(ctx, zone, id)
			if err != nil {
				return state, err
			}
			if state != nil {
				created = state
			}
		} else {
			created = target
		}

		// 起動前の設定など
		if err := r.provisionBeforeUp(ctx, zone, id, created); err != nil {
			return created, err
		}

		// 起動待ち
		if err := r.waitForUp(ctx, zone, id, created); err != nil {
			return created, err
		}

		if created != nil {
			break
		}
	}

	if created == nil {
		return nil, MaxRetryCountExceededError(fmt.Errorf("max retry count exceeded"))
	}
	return created, nil
}

func (r *RetryableSetup) init() {
	if r.RetryCount <= 0 {
		r.RetryCount = defaults.DefaultMaxRetryCount
	}
	if r.DeleteRetryCount <= 0 {
		r.DeleteRetryCount = defaults.DefaultDeleteRetryCount
	}
	if r.DeleteRetryInterval <= 0 {
		r.DeleteRetryInterval = defaults.DefaultDeleteWaitInterval
	}
	if r.ProvisioningRetryCount <= 0 {
		r.ProvisioningRetryCount = defaults.DefaultProvisioningRetryCount
	}
	if r.ProvisioningRetryInterval <= 0 {
		r.ProvisioningRetryInterval = defaults.DefaultProvisioningWaitInterval
	}
	if r.PollingInterval <= 0 {
		r.PollingInterval = defaults.DefaultPollingInterval
	}
}

func (r *RetryableSetup) createResource(ctx context.Context, zone string) (accessor.ID, error) {
	if r.Create == nil {
		return nil, fmt.Errorf("create func is required")
	}
	return r.Create(ctx, zone)
}

func (r *RetryableSetup) waitForCopyWithCleanup(ctx context.Context, zone string, id types.ID) (interface{}, error) {
	waiter := &sacloud.StatePollingWaiter{
		ReadFunc: func() (interface{}, error) {
			return r.Read(ctx, zone, id)
		},
		TargetAvailability: []types.EAvailability{
			types.Availabilities.Available,
			types.Availabilities.Failed,
		},
		PendingAvailability: []types.EAvailability{
			types.Availabilities.Unknown,
			types.Availabilities.Migrating,
			types.Availabilities.Uploading,
			types.Availabilities.Transferring,
			types.Availabilities.Discontinued,
		},
		PollingInterval: r.PollingInterval,
	}

	//wait
	compChan, progChan, errChan := waiter.AsyncWaitForState(ctx)
	var state interface{}
	var err error

loop:
	for {
		select {
		case v := <-compChan:
			state = v
			break loop
		case v := <-progChan:
			state = v
		case e := <-errChan:
			err = e
			break loop
		}
	}

	if state != nil {
		// Availabilityを持ち、Failedになっていた場合はリソースを削除してリトライ
		if f, ok := state.(accessor.Availability); ok && f != nil {
			if f.GetAvailability().IsFailed() {
				// FailedになったばかりだとDelete APIが失敗する(コピー進行中など)場合があるため、
				// 任意の回数リトライ&待機を行う
				for i := 0; i < r.DeleteRetryCount; i++ {
					time.Sleep(r.DeleteRetryInterval)
					if err = r.Delete(ctx, zone, id); err == nil {
						break
					}
				}

				return nil, nil
			}
		}

		return state, nil
	}
	if err != nil {
		return nil, err
	}

	return nil, nil
}

func (r *RetryableSetup) provisionBeforeUp(ctx context.Context, zone string, id types.ID, created interface{}) error {
	if r.ProvisionBeforeUp != nil && created != nil {
		var err error
		for i := 0; i < r.ProvisioningRetryCount; i++ {
			if err = r.ProvisionBeforeUp(ctx, zone, id, created); err == nil {
				break
			}
			time.Sleep(r.ProvisioningRetryInterval)
		}
		return err
	}
	return nil
}

func (r *RetryableSetup) waitForUp(ctx context.Context, zone string, id types.ID, created interface{}) error {
	if r.IsWaitForUp && created != nil {
		waiter := &sacloud.StatePollingWaiter{
			ReadFunc: func() (interface{}, error) {
				return r.Read(ctx, zone, id)
			},
			TargetAvailability: []types.EAvailability{
				types.Availabilities.Available,
			},
			PendingAvailability: []types.EAvailability{
				types.Availabilities.Unknown,
				types.Availabilities.Migrating,
				types.Availabilities.Uploading,
				types.Availabilities.Transferring,
				types.Availabilities.Discontinued,
			},
			TargetInstanceStatus: []types.EServerInstanceStatus{
				types.ServerInstanceStatuses.Up,
			},
			PendingInstanceStatus: []types.EServerInstanceStatus{
				types.ServerInstanceStatuses.Unknown,
				types.ServerInstanceStatuses.Cleaning,
				types.ServerInstanceStatuses.Down,
			},
			PollingInterval: r.PollingInterval,
		}
		_, err := waiter.WaitForState(ctx)
		return err
	}
	return nil
}


text:
use std::convert::TryFrom;
use std::mem;
use std::result;
use std::slice;

use devices::PciAddress;
use devices::PciInterruptPin;
use libc::c_char;
use remain::sorted;
use thiserror::Error;
use vm_memory::GuestAddress;
use vm_memory::GuestMemory;

use crate::mpspec::*;

#[sorted]
#[derive(Error, Debug)]
pub enum Error {
    /// The MP table has too little address space to be stored.
    #[error("The MP table has too little address space to be stored")]
    AddressOverflow,
    /// Failure while zeroing out the memory for the MP table.
    #[error("Failure while zeroing out the memory for the MP table")]
    Clear,
    /// There was too little guest memory to store the entire MP table.
    #[error("There was too little guest memory to store the MP table")]
    NotEnoughMemory,
    /// Failure to write MP bus entry.
    #[error("Failure to write MP bus entry")]
    WriteMpcBus,
    /// Failure to write MP CPU entry.
    #[error("Failure to write MP CPU entry")]
    WriteMpcCpu,
    /// Failure to write MP interrupt source entry.
    #[error("Failure to write MP interrupt source entry")]
    WriteMpcIntsrc,
    /// Failure to write MP ioapic entry.
    #[error("Failure to write MP ioapic entry")]
    WriteMpcIoapic,
    /// Failure to write MP local interrupt source entry.
    #[error("Failure to write MP local interrupt source entry")]
    WriteMpcLintsrc,
    /// Failure to write MP table header.
    #[error("Failure to write MP table header")]
    WriteMpcTable,
    /// Failure to write the MP floating pointer.
    #[error("Failure to write the MP floating pointer")]
    WriteMpfIntel,
}

pub type Result<T> = result::Result<T, Error>;

// Convenience macro for making arrays of diverse character types.
macro_rules! char_array {
    ($t:ty; $( $c:expr ),*) => ( [ $( $c as $t ),* ] )
}

// Most of these variables are sourced from the Intel MP Spec 1.4.
const SMP_MAGIC_IDENT: [c_char; 4] = char_array!(c_char; '_', 'M', 'P', '_');
const MPC_SIGNATURE: [c_char; 4] = char_array!(c_char; 'P', 'C', 'M', 'P');
const MPC_SPEC: i8 = 4;
const MPC_OEM: [c_char; 8] = char_array!(c_char; 'C', 'R', 'O', 'S', 'V', 'M', ' ', ' ');
const MPC_PRODUCT_ID: [c_char; 12] = ['0' as c_char; 12];
const BUS_TYPE_ISA: [u8; 6] = char_array!(u8; 'I', 'S', 'A', ' ', ' ', ' ');
const BUS_TYPE_PCI: [u8; 6] = char_array!(u8; 'P', 'C', 'I', ' ', ' ', ' ');
// source: linux/arch/x86/include/asm/apicdef.h
pub const IO_APIC_DEFAULT_PHYS_BASE: u32 = 0xfec00000;
// source: linux/arch/x86/include/asm/apicdef.h
pub const APIC_DEFAULT_PHYS_BASE: u32 = 0xfee00000;
const APIC_VERSION: u8 = 0x14;
const CPU_STEPPING: u32 = 0x600;
const CPU_FEATURE_APIC: u32 = 0x200;
const CPU_FEATURE_FPU: u32 = 0x001;
const MPTABLE_START: u64 = 0x400 * 639; // Last 1k of Linux's 640k base RAM.

fn compute_checksum<T: Copy>(v: &T) -> u8 {
    // Safe because we are only reading the bytes within the size of the `T` reference `v`.
    let v_slice = unsafe { slice::from_raw_parts(v as *const T as *const u8, mem::size_of::<T>()) };
    let mut checksum: u8 = 0;
    for i in v_slice {
        checksum = checksum.wrapping_add(*i);
    }
    checksum
}

fn mpf_intel_compute_checksum(v: &mpf_intel) -> u8 {
    let checksum = compute_checksum(v).wrapping_sub(v.checksum);
    (!checksum).wrapping_add(1)
}

fn compute_mp_size(num_cpus: u8) -> usize {
    mem::size_of::<mpf_intel>()
        + mem::size_of::<mpc_table>()
        + mem::size_of::<mpc_cpu>() * (num_cpus as usize)
        + mem::size_of::<mpc_ioapic>()
        + mem::size_of::<mpc_bus>() * 2
        + mem::size_of::<mpc_intsrc>()
        + mem::size_of::<mpc_intsrc>() * 16
        + mem::size_of::<mpc_lintsrc>() * 2
}

/// Performs setup of the MP table for the given `num_cpus`.
pub fn setup_mptable(
    mem: &GuestMemory,
    num_cpus: u8,
    pci_irqs: &[(PciAddress, u32, PciInterruptPin)],
) -> Result<()> {
    // Used to keep track of the next base pointer into the MP table.
    let mut base_mp = GuestAddress(MPTABLE_START);

    // Calculate ISA bus number in the system, report at least one PCI bus.
    let isa_bus_id = match pci_irqs.iter().max_by_key(|v| v.0.bus) {
        Some(pci_irq) => pci_irq.0.bus + 1,
        _ => 1,
    };
    let mp_size = compute_mp_size(num_cpus);

    // The checked_add here ensures the all of the following base_mp.unchecked_add's will be without
    // overflow.
    if let Some(end_mp) = base_mp.checked_add(mp_size as u64 - 1) {
        if !mem.address_in_range(end_mp) {
            return Err(Error::NotEnoughMemory);
        }
    } else {
        return Err(Error::AddressOverflow);
    }

    mem.get_slice_at_addr(base_mp, mp_size)
        .map_err(|_| Error::Clear)?
        .write_bytes(0);

    {
        let size = mem::size_of::<mpf_intel>();
        let mut mpf_intel = mpf_intel::default();
        mpf_intel.signature = SMP_MAGIC_IDENT;
        mpf_intel.length = 1;
        mpf_intel.specification = 4;
        mpf_intel.physptr = (base_mp.offset() + mem::size_of::<mpf_intel>() as u64) as u32;
        mpf_intel.checksum = mpf_intel_compute_checksum(&mpf_intel);
        mem.write_obj_at_addr(mpf_intel, base_mp)
            .map_err(|_| Error::WriteMpfIntel)?;
        base_mp = base_mp.unchecked_add(size as u64);
    }

    // We set the location of the mpc_table here but we can't fill it out until we have the length
    // of the entire table later.
    let table_base = base_mp;
    base_mp = base_mp.unchecked_add(mem::size_of::<mpc_table>() as u64);

    let mut checksum: u8 = 0;
    let ioapicid: u8 = num_cpus + 1;

    for cpu_id in 0..num_cpus {
        let size = mem::size_of::<mpc_cpu>();
        let mpc_cpu = mpc_cpu {
            type_: MP_PROCESSOR as u8,
            apicid: cpu_id,
            apicver: APIC_VERSION,
            cpuflag: CPU_ENABLED as u8
                | if cpu_id == 0 {
                    CPU_BOOTPROCESSOR as u8
                } else {
                    0
                },
            cpufeature: CPU_STEPPING,
            featureflag: CPU_FEATURE_APIC | CPU_FEATURE_FPU,
            ..Default::default()
        };
        mem.write_obj_at_addr(mpc_cpu, base_mp)
            .map_err(|_| Error::WriteMpcCpu)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_cpu));
    }
    {
        let size = mem::size_of::<mpc_ioapic>();
        let mpc_ioapic = mpc_ioapic {
            type_: MP_IOAPIC as u8,
            apicid: ioapicid,
            apicver: APIC_VERSION,
            flags: MPC_APIC_USABLE as u8,
            apicaddr: IO_APIC_DEFAULT_PHYS_BASE,
        };
        mem.write_obj_at_addr(mpc_ioapic, base_mp)
            .map_err(|_| Error::WriteMpcIoapic)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_ioapic));
    }
    for pci_bus_id in 0..isa_bus_id {
        let size = mem::size_of::<mpc_bus>();
        let mpc_bus = mpc_bus {
            type_: MP_BUS as u8,
            busid: pci_bus_id,
            bustype: BUS_TYPE_PCI,
        };
        mem.write_obj_at_addr(mpc_bus, base_mp)
            .map_err(|_| Error::WriteMpcBus)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_bus));
    }
    {
        let size = mem::size_of::<mpc_bus>();
        let mpc_bus = mpc_bus {
            type_: MP_BUS as u8,
            busid: isa_bus_id,
            bustype: BUS_TYPE_ISA,
        };
        mem.write_obj_at_addr(mpc_bus, base_mp)
            .map_err(|_| Error::WriteMpcBus)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_bus));
    }
    {
        let size = mem::size_of::<mpc_intsrc>();
        let mpc_intsrc = mpc_intsrc {
            type_: MP_LINTSRC as u8,
            irqtype: mp_irq_source_types_mp_INT as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbus: isa_bus_id,
            srcbusirq: 0,
            dstapic: 0,
            dstirq: 0,
        };
        mem.write_obj_at_addr(mpc_intsrc, base_mp)
            .map_err(|_| Error::WriteMpcIntsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc));
    }
    let sci_irq = super::X86_64_SCI_IRQ as u8;
    // Per kvm_setup_default_irq_routing() in kernel
    for i in 0..sci_irq {
        let size = mem::size_of::<mpc_intsrc>();
        let mpc_intsrc = mpc_intsrc {
            type_: MP_INTSRC as u8,
            irqtype: mp_irq_source_types_mp_INT as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbus: isa_bus_id,
            srcbusirq: i,
            dstapic: ioapicid,
            dstirq: i,
        };
        mem.write_obj_at_addr(mpc_intsrc, base_mp)
            .map_err(|_| Error::WriteMpcIntsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc));
    }
    // Insert SCI interrupt before PCI interrupts. Set the SCI interrupt
    // to be the default trigger/polarity of PCI bus, which is level/low.
    // This setting can be changed in future if necessary.
    {
        let size = mem::size_of::<mpc_intsrc>();
        let mpc_intsrc = mpc_intsrc {
            type_: MP_INTSRC as u8,
            irqtype: mp_irq_source_types_mp_INT as u8,
            irqflag: (MP_IRQDIR_HIGH | MP_LEVEL_TRIGGER) as u16,
            srcbus: isa_bus_id,
            srcbusirq: sci_irq,
            dstapic: ioapicid,
            dstirq: sci_irq,
        };
        mem.write_obj_at_addr(mpc_intsrc, base_mp)
            .map_err(|_| Error::WriteMpcIntsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc));
    }

    // Insert PCI interrupts after platform IRQs.
    for (address, irq_num, irq_pin) in pci_irqs.iter() {
        let size = mem::size_of::<mpc_intsrc>();
        let mpc_intsrc = mpc_intsrc {
            type_: MP_INTSRC as u8,
            irqtype: mp_irq_source_types_mp_INT as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbus: address.bus,
            srcbusirq: address.dev << 2 | irq_pin.to_mask() as u8,
            dstapic: ioapicid,
            dstirq: u8::try_from(*irq_num).map_err(|_| Error::WriteMpcIntsrc)?,
        };
        mem.write_obj_at_addr(mpc_intsrc, base_mp)
            .map_err(|_| Error::WriteMpcIntsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc));
    }

    let starting_isa_irq_num = pci_irqs
        .iter()
        .map(|(_, irq_num, _)| irq_num + 1)
        .fold(super::X86_64_IRQ_BASE, u32::max) as u8;

    // Finally insert ISA interrupts.
    for i in starting_isa_irq_num..16 {
        let size = mem::size_of::<mpc_intsrc>();
        let mpc_intsrc = mpc_intsrc {
            type_: MP_INTSRC as u8,
            irqtype: mp_irq_source_types_mp_INT as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbus: isa_bus_id,
            srcbusirq: i as u8,
            dstapic: ioapicid,
            dstirq: i as u8,
        };
        mem.write_obj_at_addr(mpc_intsrc, base_mp)
            .map_err(|_| Error::WriteMpcIntsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc));
    }
    {
        let size = mem::size_of::<mpc_lintsrc>();
        let mpc_lintsrc = mpc_lintsrc {
            type_: MP_LINTSRC as u8,
            irqtype: mp_irq_source_types_mp_ExtINT as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbusid: isa_bus_id,
            srcbusirq: 0,
            destapic: 0,
            destapiclint: 0,
        };
        mem.write_obj_at_addr(mpc_lintsrc, base_mp)
            .map_err(|_| Error::WriteMpcLintsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc));
    }
    {
        let size = mem::size_of::<mpc_lintsrc>();
        let mpc_lintsrc = mpc_lintsrc {
            type_: MP_LINTSRC as u8,
            irqtype: mp_irq_source_types_mp_NMI as u8,
            irqflag: MP_IRQDIR_DEFAULT as u16,
            srcbusid: isa_bus_id,
            srcbusirq: 0,
            destapic: 0xFF, // Per SeaBIOS
            destapiclint: 1,
        };
        mem.write_obj_at_addr(mpc_lintsrc, base_mp)
            .map_err(|_| Error::WriteMpcLintsrc)?;
        base_mp = base_mp.unchecked_add(size as u64);
        checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc));
    }

    // At this point we know the size of the mp_table.
    let table_end = base_mp;

    {
        let mut mpc_table = mpc_table {
            signature: MPC_SIGNATURE,
            length: table_end.offset_from(table_base) as u16,
            spec: MPC_SPEC,
            oem: MPC_OEM,
            productid: MPC_PRODUCT_ID,
            lapic: APIC_DEFAULT_PHYS_BASE,
            ..Default::default()
        };
        checksum = checksum.wrapping_add(compute_checksum(&mpc_table));
        mpc_table.checksum = (!checksum).wrapping_add(1) as i8;
        mem.write_obj_at_addr(mpc_table, table_base)
            .map_err(|_| Error::WriteMpcTable)?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use base::pagesize;

    use super::*;

    fn compute_page_aligned_mp_size(num_cpus: u8) -> u64 {
        let mp_size = compute_mp_size(num_cpus);
        let pg_size = pagesize();
        (mp_size + pg_size - (mp_size % pg_size)) as u64
    }

    fn table_entry_size(type_: u8) -> usize {
        match type_ as u32 {
            MP_PROCESSOR => mem::size_of::<mpc_cpu>(),
            MP_BUS => mem::size_of::<mpc_bus>(),
            MP_IOAPIC => mem::size_of::<mpc_ioapic>(),
            MP_INTSRC => mem::size_of::<mpc_intsrc>(),
            MP_LINTSRC => mem::size_of::<mpc_lintsrc>(),
            _ => panic!("unrecognized mpc table entry type: {}", type_),
        }
    }

    #[test]
    fn bounds_check() {
        let num_cpus = 4;
        let mem = GuestMemory::new(&[(
            GuestAddress(MPTABLE_START),
            compute_page_aligned_mp_size(num_cpus),
        )])
        .unwrap();

        setup_mptable(&mem, num_cpus, &[]).unwrap();
    }

    #[test]
    fn bounds_check_fails() {
        let num_cpus = 255;
        let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), 0x1000)]).unwrap();

        assert!(setup_mptable(&mem, num_cpus, &[]).is_err());
    }

    #[test]
    fn mpf_intel_checksum() {
        let num_cpus = 1;
        let mem = GuestMemory::new(&[(
            GuestAddress(MPTABLE_START),
            compute_page_aligned_mp_size(num_cpus),
        )])
        .unwrap();

        setup_mptable(&mem, num_cpus, &[]).unwrap();

        let mpf_intel = mem.read_obj_from_addr(GuestAddress(MPTABLE_START)).unwrap();

        assert_eq!(mpf_intel_compute_checksum(&mpf_intel), mpf_intel.checksum);
    }

    #[test]
    fn mpc_table_checksum() {
        let num_cpus = 4;
        let mem = GuestMemory::new(&[(
            GuestAddress(MPTABLE_START),
            compute_page_aligned_mp_size(num_cpus),
        )])
        .unwrap();

        setup_mptable(&mem, num_cpus, &[]).unwrap();

        let mpf_intel: mpf_intel = mem.read_obj_from_addr(GuestAddress(MPTABLE_START)).unwrap();
        let mpc_offset = GuestAddress(mpf_intel.physptr as u64);
        let mpc_table: mpc_table = mem.read_obj_from_addr(mpc_offset).unwrap();

        let mut buf = vec![0; mpc_table.length as usize];
        mem.read_at_addr(&mut buf[..], mpc_offset).unwrap();
        let mut sum: u8 = 0;
        for &v in &buf {
            sum = sum.wrapping_add(v);
        }

        assert_eq!(sum, 0);
    }

    #[test]
    fn cpu_entry_count() {
        const MAX_CPUS: u8 = 0xff;
        let mem = GuestMemory::new(&[(
            GuestAddress(MPTABLE_START),
            compute_page_aligned_mp_size(MAX_CPUS),
        )])
        .unwrap();

        for i in 0..MAX_CPUS {
            setup_mptable(&mem, i, &[]).unwrap();

            let mpf_intel: mpf_intel = mem.read_obj_from_addr(GuestAddress(MPTABLE_START)).unwrap();
            let mpc_offset = GuestAddress(mpf_intel.physptr as u64);
            let mpc_table: mpc_table = mem.read_obj_from_addr(mpc_offset).unwrap();
            let mpc_end = mpc_offset.checked_add(mpc_table.length as u64).unwrap();

            let mut entry_offset = mpc_offset
                .checked_add(mem::size_of::<mpc_table>() as u64)
                .unwrap();
            let mut cpu_count = 0;
            while entry_offset < mpc_end {
                let entry_type: u8 = mem.read_obj_from_addr(entry_offset).unwrap();
                entry_offset = entry_offset
                    .checked_add(table_entry_size(entry_type) as u64)
                    .unwrap();
                assert!(entry_offset <= mpc_end);
                if entry_type as u32 == MP_PROCESSOR {
                    cpu_count += 1;
                }
            }
            assert_eq!(cpu_count, i);
        }
    }
}


text:
package org.jetbrains.idea.maven.indices;

import com.intellij.DynamicBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;

import java.util.function.Supplier;

public final class IndicesBundle extends DynamicBundle {
  @NonNls private static final String BUNDLE = "messages.MavenIndicesBundle";
  private static final IndicesBundle INSTANCE = new IndicesBundle();

  private IndicesBundle() { super(BUNDLE); }

  @NotNull
  public static @Nls String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getMessage(key, params);
  }

  @NotNull
  public static Supplier<@Nls String> messagePointer(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getLazyMessage(key, params);
  }
}


text:
=begin
#The Plaid API

#The Plaid REST API. Please see https://plaid.com/docs/api for more details.

The version of the OpenAPI document: 2020-09-14_1.205.3

Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1

=end

require 'date'
require 'time'

module Plaid
  # PaymentInitiationConsentGetResponse defines the response schema for `/payment_initation/consent/get`
  class PaymentInitiationConsentGetResponse
    # The consent ID.
    attr_accessor :consent_id

    attr_accessor :status

    # Consent creation timestamp, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format.
    attr_accessor :created_at

    # The ID of the recipient the payment consent is for.
    attr_accessor :recipient_id

    # A reference for the payment consent.
    attr_accessor :reference

    attr_accessor :constraints

    # An array of payment consent scopes.
    attr_accessor :scopes

    # A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.
    attr_accessor :request_id

    # Attribute mapping from ruby-style variable name to JSON key.
    def self.attribute_map
      {
        :'consent_id' => :'consent_id',
        :'status' => :'status',
        :'created_at' => :'created_at',
        :'recipient_id' => :'recipient_id',
        :'reference' => :'reference',
        :'constraints' => :'constraints',
        :'scopes' => :'scopes',
        :'request_id' => :'request_id'
      }
    end

    # Returns all the JSON keys this model knows about
    def self.acceptable_attributes
      attribute_map.values
    end

    # Attribute type mapping.
    def self.openapi_types
      {
        :'consent_id' => :'String',
        :'status' => :'PaymentInitiationConsentStatus',
        :'created_at' => :'Time',
        :'recipient_id' => :'String',
        :'reference' => :'String',
        :'constraints' => :'PaymentInitiationConsentConstraints',
        :'scopes' => :'Array<PaymentInitiationConsentScope>',
        :'request_id' => :'String'
      }
    end

    # List of attributes with nullable: true
    def self.openapi_nullable
      Set.new([
      ])
    end

    # List of class defined in allOf (OpenAPI v3)
    def self.openapi_all_of
      [
      :'PaymentInitiationConsent',
      :'PaymentInitiationRecipientGetResponseAllOf'
      ]
    end

    # Initializes the object
    # @param [Hash] attributes Model attributes in the form of hash
    def initialize(attributes = {})
      if (!attributes.is_a?(Hash))
        fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::PaymentInitiationConsentGetResponse` initialize method"
      end

      # check to see if the attribute exists and convert string to symbol for hash key
      attributes = attributes.each_with_object({}) { |(k, v), h|
        if (!self.class.attribute_map.key?(k.to_sym))
          fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::PaymentInitiationConsentGetResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
        end
        h[k.to_sym] = v
      }

      if attributes.key?(:'consent_id')
        self.consent_id = attributes[:'consent_id']
      end

      if attributes.key?(:'status')
        self.status = attributes[:'status']
      end

      if attributes.key?(:'created_at')
        self.created_at = attributes[:'created_at']
      end

      if attributes.key?(:'recipient_id')
        self.recipient_id = attributes[:'recipient_id']
      end

      if attributes.key?(:'reference')
        self.reference = attributes[:'reference']
      end

      if attributes.key?(:'constraints')
        self.constraints = attributes[:'constraints']
      end

      if attributes.key?(:'scopes')
        if (value = attributes[:'scopes']).is_a?(Array)
          self.scopes = value
        end
      end

      if attributes.key?(:'request_id')
        self.request_id = attributes[:'request_id']
      end
    end

    # Show invalid properties with the reasons. Usually used together with valid?
    # @return Array for valid properties with the reasons
    def list_invalid_properties
      invalid_properties = Array.new
      if @consent_id.nil?
        invalid_properties.push('invalid value for "consent_id", consent_id cannot be nil.')
      end

      if @consent_id.to_s.length < 1
        invalid_properties.push('invalid value for "consent_id", the character length must be great than or equal to 1.')
      end

      if @status.nil?
        invalid_properties.push('invalid value for "status", status cannot be nil.')
      end

      if @created_at.nil?
        invalid_properties.push('invalid value for "created_at", created_at cannot be nil.')
      end

      if @recipient_id.nil?
        invalid_properties.push('invalid value for "recipient_id", recipient_id cannot be nil.')
      end

      if @recipient_id.to_s.length < 1
        invalid_properties.push('invalid value for "recipient_id", the character length must be great than or equal to 1.')
      end

      if @reference.nil?
        invalid_properties.push('invalid value for "reference", reference cannot be nil.')
      end

      if @constraints.nil?
        invalid_properties.push('invalid value for "constraints", constraints cannot be nil.')
      end

      if @scopes.nil?
        invalid_properties.push('invalid value for "scopes", scopes cannot be nil.')
      end

      if @request_id.nil?
        invalid_properties.push('invalid value for "request_id", request_id cannot be nil.')
      end

      invalid_properties
    end

    # Check to see if the all the properties in the model are valid
    # @return true if the model is valid
    def valid?
      return false if @consent_id.nil?
      return false if @consent_id.to_s.length < 1
      return false if @status.nil?
      return false if @created_at.nil?
      return false if @recipient_id.nil?
      return false if @recipient_id.to_s.length < 1
      return false if @reference.nil?
      return false if @constraints.nil?
      return false if @scopes.nil?
      return false if @request_id.nil?
      true
    end

    # Custom attribute writer method with validation
    # @param [Object] consent_id Value to be assigned
    def consent_id=(consent_id)
      if consent_id.nil?
        fail ArgumentError, 'consent_id cannot be nil'
      end

      if consent_id.to_s.length < 1
        fail ArgumentError, 'invalid value for "consent_id", the character length must be great than or equal to 1.'
      end

      @consent_id = consent_id
    end

    # Custom attribute writer method with validation
    # @param [Object] recipient_id Value to be assigned
    def recipient_id=(recipient_id)
      if recipient_id.nil?
        fail ArgumentError, 'recipient_id cannot be nil'
      end

      if recipient_id.to_s.length < 1
        fail ArgumentError, 'invalid value for "recipient_id", the character length must be great than or equal to 1.'
      end

      @recipient_id = recipient_id
    end

    # Checks equality by comparing each attribute.
    # @param [Object] Object to be compared
    def ==(o)
      return true if self.equal?(o)
      self.class == o.class &&
          consent_id == o.consent_id &&
          status == o.status &&
          created_at == o.created_at &&
          recipient_id == o.recipient_id &&
          reference == o.reference &&
          constraints == o.constraints &&
          scopes == o.scopes &&
          request_id == o.request_id
    end

    # @see the `==` method
    # @param [Object] Object to be compared
    def eql?(o)
      self == o
    end

    # Calculates hash code according to all attributes.
    # @return [Integer] Hash code
    def hash
      [consent_id, status, created_at, recipient_id, reference, constraints, scopes, request_id].hash
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def self.build_from_hash(attributes)
      new.build_from_hash(attributes)
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def build_from_hash(attributes)
      return nil unless attributes.is_a?(Hash)
      self.class.openapi_types.each_pair do |key, type|
        if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
          self.send("#{key}=", nil)
        elsif type =~ /\AArray<(.*)>/i
          # check to ensure the input is an array given that the attribute
          # is documented as an array but the input is not
          if attributes[self.class.attribute_map[key]].is_a?(Array)
            self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
          end
        elsif !attributes[self.class.attribute_map[key]].nil?
          self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
        end
      end

      self
    end

    # Deserializes the data based on type
    # @param string type Data type
    # @param string value Value to be deserialized
    # @return [Object] Deserialized data
    def _deserialize(type, value)
      case type.to_sym
      when :Time
        Time.parse(value)
      when :Date
        Date.parse(value)
      when :String
        value.to_s
      when :Integer
        value.to_i
      when :Float
        value.to_f
      when :Boolean
        if value.to_s =~ /\A(true|t|yes|y|1)\z/i
          true
        else
          false
        end
      when :Object
        # generic object (usually a Hash), return directly
        value
      when /\AArray<(?<inner_type>.+)>\z/
        inner_type = Regexp.last_match[:inner_type]
        value.map { |v| _deserialize(inner_type, v) }
      when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
        k_type = Regexp.last_match[:k_type]
        v_type = Regexp.last_match[:v_type]
        {}.tap do |hash|
          value.each do |k, v|
            hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
          end
        end
      else # model
        # models (e.g. Pet) or oneOf
        klass = Plaid.const_get(type)
        klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
      end
    end

    # Returns the string representation of the object
    # @return [String] String presentation of the object
    def to_s
      to_hash.to_s
    end

    # to_body is an alias to to_hash (backward compatibility)
    # @return [Hash] Returns the object in the form of hash
    def to_body
      to_hash
    end

    # Returns the object in the form of hash
    # @return [Hash] Returns the object in the form of hash
    def to_hash
      hash = {}
      self.class.attribute_map.each_pair do |attr, param|
        value = self.send(attr)
        if value.nil?
          is_nullable = self.class.openapi_nullable.include?(attr)
          next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
        end

        hash[param] = _to_hash(value)
      end
      hash
    end

    # Outputs non-array value in the form of hash
    # For object, use to_hash. Otherwise, just return the value
    # @param [Object] value Any valid value
    # @return [Hash] Returns the value in the form of hash
    def _to_hash(value)
      if value.is_a?(Array)
        value.compact.map { |v| _to_hash(v) }
      elsif value.is_a?(Hash)
        {}.tap do |hash|
          value.each { |k, v| hash[k] = _to_hash(v) }
        end
      elsif value.respond_to? :to_hash
        value.to_hash
      else
        value
      end
    end

  end

end