text:
meta:
 - name: description
   content: Guide to deploy your Ts.ED application on AWS.
 - name: keywords
   content: ts.ed express typescript aws node.js javascript decorators
---

# Serverless HTTP

<Banner src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Amazon_Web_Services_Logo.svg/langfr-220px-Amazon_Web_Services_Logo.svg.png" href="https://aws.amazon.com/fr/" :height="180" />

Amazon Web Services is one possible way to host your Node.js application.

This tutorial shows you how to configure Ts.ED application, to be executed as an AWS Lambda Function. Under the hood,
@tsed/platform-aws uses [serverless-http](https://www.npmjs.com/package/serverless-http) to handle AWS event and call
Express.js/Koa.js application.

::: tip
[Serverless](https://www.serverless.com/) is a free and open-source web framework written using Node.js. Serverless is
the first framework developed for building applications on AWS Lambda, a serverless computing platform provided by
Amazon as a part of Amazon Web Services. This tutorial will show you how to install and use Serverless with Ts.ED.
:::

More information here: [Official AWS Docs](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

## Features

This package allows the creation of a Lambda AWS with an Express.js/Koa.js server.

It supports:

- Mounting Express.js/Koa.js app with `serverless-http` module,
- DI injection with `@tsed/di`,
- Models mapping using `@tsed/schema` and `@tsed/json-mapper`,
- Params decorators can be used from `@tsed/platform-params` to get Query, Body, etc...
- Operation descriptions like `@Returns`,
- `@tsed/async-hook-context` to inject Context anywhere in your class!

## Installation

Generate a new project with the CLI (you can also start from an existing project):

```bash
tsed init .
? Choose the target platform: Express.js
? Choose the architecture for your project: Ts.ED
? Choose the convention file styling: Ts.ED
? Check the features needed for your project Swagger, Testing, Linter
? Choose unit framework Jest
? Choose linter tools framework EsLint
? Choose extra linter tools Prettier, Lint on commit
? Choose the package manager: Yarn
```

::: tip This tutorial works also with NPM package manager!
:::

<Tabs class="-code">
  <Tab label="Yarn">

```bash
yarn add @tsed/platform-serverless-http serverless-http serverless-offline
yarn add -D @types/aws-lambda
```

  </Tab>
  <Tab label="NPM">

```bash
npm install @tsed/platform-serverless-http serverless-http serverless-offline
npm install --save-dev @types/aws-lambda
```

  </Tab>
</Tabs>

In the `src/lambda` create a new Lambda class:

```typescript
import {Controller, Inject} from "@tsed/di";
import {Get, Returns, Summary} from "@tsed/schema";
import {QueryParams} from "@tsed/platform-params";
import {TimeslotsService} from "../services/TimeslotsService";
import {TimeslotModel} from "../models/TimeslotModel";

@Controller("/timeslots")
export class TimeslotsController {
  @Inject()
  protected timeslotsService: TimeslotsService;

  @Get("/")
  @Summary("Return a list of timeslots")
  @Returns(200, Array).Of(TimeslotModel)
  get(@QueryParams("date_start") dateStart: Date, @QueryParams("date_end") dateEnd: Date) {
    return this.timeslotsService.find({
      dateStart,
      dateEnd
    });
  }
}
```

Remove the http and https port configuration from `Server.ts`:

```typescript
@Configuration({
  // httpPort: 8080,
  // httpsPort: false
})
export class Server {
}
```

And add the http port for our local server directly on `index.ts` file:

```typescript
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";

async function bootstrap() {
  const platform = await PlatformExpress.bootstrap(Server, {
    httpsPort: false,
    httpPort: process.env.PORT || 8080,
    disableComponentsScan: true
  });

  await platform.listen();

  return platform;
}

bootstrap();
```

Create new `handler.ts` to expose your lambda:

```typescript
import {PlatformServerlessHttp} from "@tsed/platform-serverless-http";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";

const platform = PlatformServerlessHttp.bootstrap(Server, {
  adapter: PlatformExpress
})

export const handler = platform.handler();
```

Finally, create the `serverless.yml`:

```yml
service: timeslots

frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs14.x
  lambdaHashingVersion: '20201221'

plugins:
  - serverless-offline

functions:
  any:
    handler: dist/handler.handler
    events:
      - http:
          method: ANY
          path: /
      - http:
          method: ANY
          path: '{proxy+}'
```

## Invoke a lambda with serverless

Serverless provide a plugin named `serverless-offline`. This Serverless plugin emulates AWS λ and API Gateway on your
local machine to speed up your development cycles. To do so, it starts an HTTP server that handles the request's
lifecycle like API does and invokes your handlers.

So, by using the `serverless offline` command, we'll be able to invoke our function. For that, we need also to build our
code before invoke the lambda.

To simplify our workflow, we can add the following npm script command in our `package.json`:

```json
{
  "scripts": {
    "invoke": "yarn serverless invoke local -f any --data '{\"path\":\"/timeslots\", \"httpMethod\": \"GET\"}'"
  }
}
```

Now, we can run the following command to invoke our lambda:

```
yarn invoke
// OR
npm run invoke
```

You should see in the terminal the following result:

```json
{
  "statusCode": 200,
  "body": "[{\"id\":\"b6de4fc7-faaa-4cd7-a144-42f6af0dec6b\",\"title\":\"title\",\"description\":\"description\",\"start_date\":\"2021-10-29T10:40:57.019Z\",\"end_date\":\"2021-10-29T10:40:57.019Z\",\"created_at\":\"2021-10-29T10:40:57.019Z\",\"update_at\":\"2021-10-29T10:40:57.019Z\"}]",
  "headers": {
    "content-type": "application/json",
    "x-request-id": "ebb52d5e-113b-40da-b34e-c14811df596b"
  },
  "isBase64Encoded": false
}
```

## Get Aws Context and Aws Event

This package includes decorators to easily get the event object Lambda received from API Gateway:

```typescript
import {Controller, Get} from "@tsed/common";
import {ServerlessEvent, ServerlessContext} from "@tsed/platform-serverless-http";

@Controller("/")
class MyCtrl {
  @Get("/")
  get(@ServerlessEvent() event: any, @ServerlessContext() context: ServerlessContext) {
    console.log("Event", event);
    console.log("Context", context);

    return { event, context };
  }
}
```

## Testing

Ts.ED provide a way to test you lambda with mocked Aws event and context by using the @@PlatformServerlessTest@@ util.

Here an example to test a Lambda controller:

```typescript
import {PlatformServerless} from "@tsed/platform-serverless-http";
import {PlatformServerlessTest} from "@tsed/platform-serverless-testing";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";

@Controller("/timeslots")
class TimeslotsController {
  @Get("/")
  getAll() {
    return [];
  }
}

describe("TimeslotsController", () => {
  beforeEach(
    PlatformServerlessTest.bootstrap(PlatformServerlessHttp, {
      server: Server,
      mount: {
        "/": [TimeslotsLambdaController]
      }
    })
  );
  afterEach(() => PlatformServerlessTest.reset());

  it("should call getAll Lambda", async () => {
    const response = await PlatformServerlessTest.request.get("/timeslots");

    expect(response.statusCode).toEqual(200);
    expect(JSON.parse(response.body)).toEqual([]);
  });
});
```

## Author

<GithubContributors :users="['Romakita']"/>

## Maintainers <Badge text="Help wanted" />

<GithubContributors :users="['Romakita']"/>

<div class="flex items-center justify-center p-5">
<Button href="/contributing.html" class="rounded-medium">
 Become maintainer
</Button>
</div>


text:
int intel_decode(uint32_t *data, int count, uint32_t hw_offset, uint32_t devid);
void intel_decode_context_reset(void);

redpajama_set_name: RedPajamaGithub


text:
module Backup
  module Configuration
    module Syncer
      class RSync < Base
        class << self

          ##
          # Server credentials
          attr_accessor :username, :password

          ##
          # Server IP Address and SSH port
          attr_accessor :ip

          ##
          # The SSH port to connect to
          attr_accessor :port

          ##
          # Directories to sync
          attr_accessor :directories

          ##
          # Path to store the synced files/directories to
          attr_accessor :path

          ##
          # Flag for mirroring the files/directories
          attr_accessor :mirror

          ##
          # Flag for compressing (only compresses for the transfer)
          attr_accessor :compress

          ##
          # Additional options for the rsync cli
          attr_accessor :additional_options

        end
      end
    end
  end
end


text:
package org.optaplanner.benchmark.config;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import org.optaplanner.benchmark.api.PlannerBenchmark;
import org.optaplanner.benchmark.config.blueprint.SolverBenchmarkBluePrintConfig;
import org.optaplanner.benchmark.config.report.BenchmarkReportConfig;
import org.optaplanner.benchmark.impl.PlannerBenchmarkRunner;
import org.optaplanner.benchmark.impl.result.PlannerBenchmarkResult;
import org.optaplanner.benchmark.impl.result.ProblemBenchmarkResult;
import org.optaplanner.benchmark.impl.result.SolverBenchmarkResult;
import org.optaplanner.core.config.AbstractConfig;
import org.optaplanner.core.config.util.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@XStreamAlias("plannerBenchmark")
public class PlannerBenchmarkConfig {

    public static final String PARALLEL_BENCHMARK_COUNT_AUTO = "AUTO";
    /**
     * @see Runtime#availableProcessors()
     */
    public static final String AVAILABLE_PROCESSOR_COUNT = "availableProcessorCount";
    public static final Pattern VALID_NAME_PATTERN;
    // TODO Remove workaround for Java 6 (once we no longer support it) and unignore tests related to PLANNER-348.
    static {
        Pattern validNamePattern;
        try {
            validNamePattern = Pattern.compile("(?U)^[\\w\\d _\\-\\.\\(\\)]+$");
        } catch (PatternSyntaxException e) {
            // Java 6 does not support (?U)
            validNamePattern = Pattern.compile("^[\\w\\d _\\-\\.\\(\\)]+$");
        }
        VALID_NAME_PATTERN = validNamePattern;
    }

    private static final Logger logger = LoggerFactory.getLogger(PlannerBenchmarkConfig.class);

    private String name = null;
    private File benchmarkDirectory = null;

    private String parallelBenchmarkCount = null;
    private Long warmUpMillisecondsSpentLimit = null;
    private Long warmUpSecondsSpentLimit = null;
    private Long warmUpMinutesSpentLimit = null;
    private Long warmUpHoursSpentLimit = null;

    @XStreamAlias("benchmarkReport")
    private BenchmarkReportConfig benchmarkReportConfig = null;

    @XStreamAlias("inheritedSolverBenchmark")
    private SolverBenchmarkConfig inheritedSolverBenchmarkConfig = null;

    @XStreamImplicit(itemFieldName = "solverBenchmarkBluePrint")
    private List<SolverBenchmarkBluePrintConfig> solverBenchmarkBluePrintConfigList = null;
    @XStreamImplicit(itemFieldName = "solverBenchmark")
    private List<SolverBenchmarkConfig> solverBenchmarkConfigList = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public File getBenchmarkDirectory() {
        return benchmarkDirectory;
    }

    public void setBenchmarkDirectory(File benchmarkDirectory) {
        this.benchmarkDirectory = benchmarkDirectory;
    }

    /**
     * Using multiple parallel benchmarks can decrease the reliability of the results.
     * <p>
     * If there aren't enough processors available, it will be decreased.
     * @return null, {@value #PARALLEL_BENCHMARK_COUNT_AUTO}
     * or a JavaScript calculation using {@value #AVAILABLE_PROCESSOR_COUNT}.
     */
    public String getParallelBenchmarkCount() {
        return parallelBenchmarkCount;
    }

    public void setParallelBenchmarkCount(String parallelBenchmarkCount) {
        this.parallelBenchmarkCount = parallelBenchmarkCount;
    }

    public Long getWarmUpMillisecondsSpentLimit() {
        return warmUpMillisecondsSpentLimit;
    }

    public void setWarmUpMillisecondsSpentLimit(Long warmUpMillisecondsSpentLimit) {
        this.warmUpMillisecondsSpentLimit = warmUpMillisecondsSpentLimit;
    }

    public Long getWarmUpSecondsSpentLimit() {
        return warmUpSecondsSpentLimit;
    }

    public void setWarmUpSecondsSpentLimit(Long warmUpSecondsSpentLimit) {
        this.warmUpSecondsSpentLimit = warmUpSecondsSpentLimit;
    }

    public Long getWarmUpMinutesSpentLimit() {
        return warmUpMinutesSpentLimit;
    }

    public void setWarmUpMinutesSpentLimit(Long warmUpMinutesSpentLimit) {
        this.warmUpMinutesSpentLimit = warmUpMinutesSpentLimit;
    }

    public Long getWarmUpHoursSpentLimit() {
        return warmUpHoursSpentLimit;
    }

    public void setWarmUpHoursSpentLimit(Long warmUpHoursSpentLimit) {
        this.warmUpHoursSpentLimit = warmUpHoursSpentLimit;
    }

    public BenchmarkReportConfig getBenchmarkReportConfig() {
        return benchmarkReportConfig;
    }

    public void setBenchmarkReportConfig(BenchmarkReportConfig benchmarkReportConfig) {
        this.benchmarkReportConfig = benchmarkReportConfig;
    }

    public SolverBenchmarkConfig getInheritedSolverBenchmarkConfig() {
        return inheritedSolverBenchmarkConfig;
    }

    public void setInheritedSolverBenchmarkConfig(SolverBenchmarkConfig inheritedSolverBenchmarkConfig) {
        this.inheritedSolverBenchmarkConfig = inheritedSolverBenchmarkConfig;
    }

    public List<SolverBenchmarkBluePrintConfig> getSolverBenchmarkBluePrintConfigList() {
        return solverBenchmarkBluePrintConfigList;
    }

    public void setSolverBenchmarkBluePrintConfigList(List<SolverBenchmarkBluePrintConfig> solverBenchmarkBluePrintConfigList) {
        this.solverBenchmarkBluePrintConfigList = solverBenchmarkBluePrintConfigList;
    }

    public List<SolverBenchmarkConfig> getSolverBenchmarkConfigList() {
        return solverBenchmarkConfigList;
    }

    public void setSolverBenchmarkConfigList(List<SolverBenchmarkConfig> solverBenchmarkConfigList) {
        this.solverBenchmarkConfigList = solverBenchmarkConfigList;
    }

    // ************************************************************************
    // Builder methods
    // ************************************************************************

    public PlannerBenchmark buildPlannerBenchmark() {
        validate();
        generateSolverBenchmarkConfigNames();
        List<SolverBenchmarkConfig> effectiveSolverBenchmarkConfigList = buildEffectiveSolverBenchmarkConfigList();

        PlannerBenchmarkResult plannerBenchmarkResult = new PlannerBenchmarkResult();
        plannerBenchmarkResult.setName(name);
        plannerBenchmarkResult.setAggregation(false);
        PlannerBenchmarkRunner plannerBenchmarkRunner = new PlannerBenchmarkRunner(plannerBenchmarkResult);
        plannerBenchmarkRunner.setBenchmarkDirectory(benchmarkDirectory);
        plannerBenchmarkResult.setParallelBenchmarkCount(resolveParallelBenchmarkCount());
        plannerBenchmarkResult.setWarmUpTimeMillisSpentLimit(calculateWarmUpTimeMillisSpentLimit());
        BenchmarkReportConfig benchmarkReportConfig_ = benchmarkReportConfig == null ? new BenchmarkReportConfig()
                : benchmarkReportConfig;
        plannerBenchmarkRunner.setBenchmarkReport(benchmarkReportConfig_.buildBenchmarkReport(plannerBenchmarkResult));

        plannerBenchmarkResult.setUnifiedProblemBenchmarkResultList(new ArrayList<ProblemBenchmarkResult>());
        plannerBenchmarkResult.setSolverBenchmarkResultList(new ArrayList<SolverBenchmarkResult>(
                effectiveSolverBenchmarkConfigList.size()));
        for (SolverBenchmarkConfig solverBenchmarkConfig : effectiveSolverBenchmarkConfigList) {
            solverBenchmarkConfig.buildSolverBenchmark(plannerBenchmarkResult);
        }
        return plannerBenchmarkRunner;
    }

    protected void validate() {
        if (name != null) {
            if (!PlannerBenchmarkConfig.VALID_NAME_PATTERN.matcher(name).matches()) {
                throw new IllegalStateException("The plannerBenchmark name (" + name
                        + ") is invalid because it does not follow the nameRegex ("
                        + PlannerBenchmarkConfig.VALID_NAME_PATTERN.pattern() + ")" +
                        " which might cause an illegal filename.");
            }
            if (!name.trim().equals(name)) {
                throw new IllegalStateException("The plannerBenchmark name (" + name
                        + ") is invalid because it starts or ends with whitespace.");
            }
        }
        if (ConfigUtils.isEmptyCollection(solverBenchmarkBluePrintConfigList)
                && ConfigUtils.isEmptyCollection(solverBenchmarkConfigList)) {
            throw new IllegalArgumentException(
                    "Configure at least 1 <solverBenchmark> (or 1 <solverBenchmarkBluePrint>)"
                    + " in the <plannerBenchmark> configuration.");
        }
    }

    protected void generateSolverBenchmarkConfigNames() {
        if (solverBenchmarkConfigList != null) {
            Set<String> nameSet = new HashSet<String>(solverBenchmarkConfigList.size());
            Set<SolverBenchmarkConfig> noNameBenchmarkConfigSet = new LinkedHashSet<SolverBenchmarkConfig>(solverBenchmarkConfigList.size());
            for (SolverBenchmarkConfig solverBenchmarkConfig : solverBenchmarkConfigList) {
                if (solverBenchmarkConfig.getName() != null) {
                    boolean unique = nameSet.add(solverBenchmarkConfig.getName());
                    if (!unique) {
                        throw new IllegalStateException("The benchmark name (" + solverBenchmarkConfig.getName()
                                + ") is used in more than 1 benchmark.");
                    }
                } else {
                    noNameBenchmarkConfigSet.add(solverBenchmarkConfig);
                }
            }
            int generatedNameIndex = 0;
            for (SolverBenchmarkConfig solverBenchmarkConfig : noNameBenchmarkConfigSet) {
                String generatedName = "Config_" + generatedNameIndex;
                while (nameSet.contains(generatedName)) {
                    generatedNameIndex++;
                    generatedName = "Config_" + generatedNameIndex;
                }
                solverBenchmarkConfig.setName(generatedName);
                generatedNameIndex++;
            }
        }
    }

    protected List<SolverBenchmarkConfig> buildEffectiveSolverBenchmarkConfigList() {
        List<SolverBenchmarkConfig> effectiveSolverBenchmarkConfigList = new ArrayList<SolverBenchmarkConfig>(0);
        if (solverBenchmarkConfigList != null) {
            effectiveSolverBenchmarkConfigList.addAll(solverBenchmarkConfigList);
        }
        if (solverBenchmarkBluePrintConfigList != null) {
            for (SolverBenchmarkBluePrintConfig solverBenchmarkBluePrintConfig : solverBenchmarkBluePrintConfigList) {
                effectiveSolverBenchmarkConfigList.addAll(
                        solverBenchmarkBluePrintConfig.buildSolverBenchmarkConfigList());
            }
        }
        if (inheritedSolverBenchmarkConfig != null) {
            for (SolverBenchmarkConfig solverBenchmarkConfig : effectiveSolverBenchmarkConfigList) {
                // Side effect: changes the unmarshalled solverBenchmarkConfig
                solverBenchmarkConfig.inherit(inheritedSolverBenchmarkConfig);
            }
        }
        return effectiveSolverBenchmarkConfigList;
    }

    protected int resolveParallelBenchmarkCount() {
        int availableProcessorCount = Runtime.getRuntime().availableProcessors();
        int resolvedParallelBenchmarkCount;
        if (parallelBenchmarkCount == null) {
            resolvedParallelBenchmarkCount = 1;
        } else if (parallelBenchmarkCount.equals(PARALLEL_BENCHMARK_COUNT_AUTO)) {
            // TODO Tweak it based on experience
            if (availableProcessorCount <= 2) {
                resolvedParallelBenchmarkCount = 1;
            } else if (availableProcessorCount <= 4) {
                resolvedParallelBenchmarkCount = 2;
            } else {
                resolvedParallelBenchmarkCount = (availableProcessorCount / 2) + 1;
            }
        } else {
            String scriptLanguage = "JavaScript";
            ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(scriptLanguage);
            scriptEngine.put(AVAILABLE_PROCESSOR_COUNT, availableProcessorCount);
            Object scriptResult;
            try {
                scriptResult = scriptEngine.eval(parallelBenchmarkCount);
            } catch (ScriptException e) {
                throw new IllegalArgumentException("The parallelBenchmarkCount (" + parallelBenchmarkCount
                        + ") is not " + PARALLEL_BENCHMARK_COUNT_AUTO + " and cannot be parsed in " + scriptLanguage
                        + " with the variables ([" + AVAILABLE_PROCESSOR_COUNT + "]).", e);
            }
            if (!(scriptResult instanceof Number)) {
                throw new IllegalArgumentException("The parallelBenchmarkCount (" + parallelBenchmarkCount
                        + ") is resolved to scriptResult (" + scriptResult + ") in " + scriptLanguage
                        + " and is not a Number.");
            }
            resolvedParallelBenchmarkCount = ((Number) scriptResult).intValue();
        }
        if (resolvedParallelBenchmarkCount < 1) {
            throw new IllegalArgumentException("The parallelBenchmarkCount (" + parallelBenchmarkCount
                    + ") resulted in a resolvedParallelBenchmarkCount (" + resolvedParallelBenchmarkCount
                    + ") that is lower than 1.");
        }
        if (resolvedParallelBenchmarkCount > availableProcessorCount) {
            logger.warn("Because the resolvedParallelBenchmarkCount (" + resolvedParallelBenchmarkCount
                    + ") is higher than the availableProcessorCount (" + availableProcessorCount
                    + "), it is reduced to availableProcessorCount.");
            resolvedParallelBenchmarkCount = availableProcessorCount;
        }
        return resolvedParallelBenchmarkCount;
    }

    protected long calculateWarmUpTimeMillisSpentLimit() {
        long warmUpTimeMillisSpentLimit = 0L;
        if (warmUpMillisecondsSpentLimit != null) {
            warmUpTimeMillisSpentLimit += warmUpMillisecondsSpentLimit;
        }
        if (warmUpSecondsSpentLimit != null) {
            warmUpTimeMillisSpentLimit += warmUpSecondsSpentLimit * 1000L;
        }
        if (warmUpMinutesSpentLimit != null) {
            warmUpTimeMillisSpentLimit += warmUpMinutesSpentLimit * 60000L;
        }
        if (warmUpHoursSpentLimit != null) {
            warmUpTimeMillisSpentLimit += warmUpHoursSpentLimit * 3600000L;
        }
        return warmUpTimeMillisSpentLimit;
    }

}


text:
package bio.terra.stairway;

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetryRuleFixedInterval implements RetryRule {
  private static final Logger logger = LoggerFactory.getLogger(RetryRule.class);

  // Fixed parameters
  private final int intervalSeconds;
  private final int maxCount;

  // Initialized parameters
  private int retryCount;

  /**
   * Sleep for fixed intervals a fixed number of times.
   *
   * @param intervalSeconds - number of seconds to sleep
   * @param maxCount - number of times to retry
   */
  public RetryRuleFixedInterval(int intervalSeconds, int maxCount) {
    this.intervalSeconds = intervalSeconds;
    this.maxCount = maxCount;
    initialize();
  }

  @Override
  public void initialize() {
    retryCount = 0;
  }

  @Override
  public boolean retrySleep() throws InterruptedException {
    retryCount++;
    if (retryCount > maxCount) {
      logger.info("Retry rule fixed: retried {} times - not retrying", maxCount);
      return false;
    }

    logger.info(
        "Retry rule fixed: starting retry {} of {} after sleep of {} seconds",
        retryCount,
        maxCount,
        intervalSeconds);

    TimeUnit.SECONDS.sleep(intervalSeconds);
    return true;
  }
}


text:
namespace WarehouseSystem.Web.Areas.Administration.ViewModels
{
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web;
    using AutoMapper;
    using WarehouseSystem.Data.Models;
    using WarehouseSystem.Web.Infrastructure.Mapping;

    public class ProductViewModel : IMapFrom<Product>, IHaveCustomMappings
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(50, MinimumLength = 2)]
        public string Name { get; set; }

        [Required]
        [DisplayName("SKU")]
        public int Sku { get; set; }

        [StringLength(20, MinimumLength = 4)]
        public string Barcode { get; set; }

        [DisplayName("Heigth")]
        public double HeigthInCm { get; set; }

        [DisplayName("Width")]
        public double WidthInCm { get; set; }

        [DisplayName("Weight")]
        public int WeightInGr { get; set; }

        [DisplayName("Delivery Unit")]
        public double DeliveryUnit { get; set; }

        [DisplayName("Day of expires")]
        public int MinDayOfExpiryInDays { get; set; }

        [DisplayName("Blocked")]
        public bool IsBlocked { get; set; }

        public int CategoryId { get; set; }

        public string Category { get; set; }

        public int? ImageId { get; set; }

        public string Size => $"{this.HeigthInCm} cm. / {this.WidthInCm} cm. - {this.WeightInGr} gr.";

        public HttpPostedFileBase UploadedImage { get; set; }

        public void CreateMappings(IConfiguration configuration)
        {
            configuration.CreateMap<Product, ProductViewModel>()
                .ForMember(x => x.Category, opt => opt.MapFrom(x => x.Category.Name))
                .ReverseMap();
        }
    }
}


text:
/**
 * This is the base configure file for the build process.
 * (Do NOT modify unless you want to apply to all build configures)
 * (It does NOT have the view engine files in the javascript.framework section, see default.js)
 *
 * Base Path
 * ---------
 * All path are based on the project root.
 * [Not relative to this configure file]
 *
 * Configure
 * ---------
 * 1. plugins:
 * 	  	settings for some gulp plugins.
 * 2. control aspects:
 * 		dist path,
 * 		compress[minify, gzip],
 * 		js[es6, concat],
 * 		css,
 * 		template,
 * 		assets (copy, re-dirname),
 * 		watch
 *
 *
 * Override (create another configure)
 * -----------------------------------
 * use `gulp -C <name> or --config <name>` to load up other configure file instead of this one.
 *
 * *Hint*: how to create another configure file?
 * ```
 * 		module.exports = require('lodash').merge(require('./_base'), {
 * 			...
 * 		 	...
 *   	});
 *
 * 		or
 *
 * 		var config = require('./_base.js');
 * 		config.<item> = ...
 * 		...
 *
 * 		module.exports = config;
 * ```
 *
 * Gotcha
 * ------
 * 1. All non-concatenated .js files will be treated as es6, thus should use `import` and `expose` module key words.
 * 2. Concatenated lib/vendor .js files can be used directly using their globally exposed vars.
 * 3. We embed sourcemaps inside compiled/concatenated js targets, thus resulting x3 file size.
 * 4. Minified js, css and html will not contain sourcemaps and comments (except for special / *!..* /)
 * 5. Watch task only recompile js, less and tpl.html files, skipping concatenated js targets.
 *
 * Important Note
 * --------------
 * We use babel for es6 -> commonjs and browserfiy for commonjs -> browser. Thus the package.json file in this build
 * folder could contain npm modules in the `dependencies` block and gets bundled by browserify. Although we do NOT encourage
 * bundling browser side libraries this way, the `dependencies` block is left clean open and up to you.
 *
 * We highly recommend using the `gulp libs` task and bower package manager for browser side library management.
 *
 *
 * @author Tim Lauv
 * @created 2015.02.19
 *
 */

module.exports = {

	//---------------dist path--------------
	output: 'public',

	//------------js (modules/libs)---------
	// 'entrypoint' compile & bundle as es6 modules (import, expose. re-process during `watch`)
	// '[...]' as vanilla js concat (won't re-process during `watch`)
	javascript: {
		//app.js
		app: 'src/entrypoint.js',

		//libs.js
		libs: [
			'libs/bower_components/detectizr/dist/detectizr.js',
			'libs/bower_components/lodash/lodash.js',
			'libs/bower_components/jquery/dist/jquery.js',
			'libs/vendor/jquery-ui/position.js',
			'libs/bower_components/fastclick/lib/fastclick.js',
			'libs/bower_components/interact/interact.js',
			'libs/bower_components/eventemitter2/lib/eventemitter2.js',
			'libs/bower_components/async/lib/async.js',
			'libs/bower_components/director/build/director.js',
			'libs/bower_components/i18next/i18next.js',
			'libs/bower_components/validator-js/validator.js',
			//------------------------ve deps:tpl engine, mvvm, fx plugins-------
			'libs/bower_components/handlebars/handlebars.js',
			'libs/bower_components/kendo-ui-core/src/js/kendo.core.js',
			'libs/bower_components/kendo-ui-core/src/js/kendo.data.js',
			'libs/bower_components/kendo-ui-core/src/js/kendo.binder.js',
			//'libs/bower_components/velocity/velocity.js', //$.velocity - animation [optional]
			//'libs/bower_components/velocity/velocity.ui.js' //$.velocity.RegisterEffect/RunSequence - animation-seq [optional]
			//------------------------no tpl framework, widgets------------------
		],

		//framework.js
		framework: [
			'libs/vendor/stagejsv2/infrastructure.js',
			'libs/vendor/stagejsv2/coop-ee2-async.js',
			'libs/vendor/stagejsv2/utils.js',
			'libs/vendor/stagejsv2/com-ajax-ws-rtc.js',
			'libs/vendor/stagejsv2/i18n-i18next.js',
			'libs/vendor/stagejsv2/validate-validator.js',
			'libs/vendor/stagejsv2/navigation-director.js',
			//------------------------view engine--------------------------------
			'libs/vendor/stagejsv2/template-helpers-hbs.js',
			'libs/vendor/stagejsv2/view-engine.js'
		]
	},

	//------------templates.json------------
	// put together with js modules under /src (re-combine during `watch`)
	templates: ['src/**/*.html'],

	//-----------------style----------------
	// into app.css, (re-compile during `watch`)
	stylesheet: 'styles/_base.less',

	//----------------assets----------------
	//'string' --> as glob, copy as is
	//{key: value} --> copy & re-dir
	//
	// overlapping folder will be merged.
	assets: [
		//glob (copy/exclude as is)
		'assets/**/*',
		'!*.empty',
		//copy and re-dir (put in different folder) *NOT rename!*
		{
			'libs/bower_components/modernizr/modernizr.js':'js',
		},
	],

	//----------gulp plugin configs---------
	//Don't change unless sure about...
	plugins: {

		autoprefixer: {},
		'minify-css': {
			keepSpecialComments: '*' //special comment only (e.g license)
		}, //use clean-css internally

		babel: {}, //es6 -> commonjs
		browserify: {}, //commonjs -> browser
		uglify: {
			preserveComments: 'some' //special comment only (e.g license)
		},

		'minify-html': {
			empty: true,
			conditionals: true, //remove comments but not the ie ones.
			spare: true
		},

		gzip: {}

	},

	//------------watch params--------------
	//Don't change unless sure about...
	watch: {
		usePolling: true,
		delay: {
			unit: 300, // ms
			factor: { // unit * factor
				poll: 1,
				debounce: 2
			}
		},
		//watch globs (different than the corresponding tasks' globs)
		glob: {
			js: 'src/**/*.js',
			css: 'styles/**/*.less',
			//templates: as in config.templates
		}
	}
};


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php_mustache.h"
#include "mustache_private.hpp"
#include "mustache_ast.hpp"
#include "mustache_data.hpp"
#include "mustache_exceptions.hpp"
#include "mustache_template.hpp"
#include "mustache_mustache.hpp"

/* {{{ ZE2 OO definitions */
zend_class_entry * Mustache_ce_ptr;
static zend_object_handlers Mustache_obj_handlers;
/* }}} */

/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(Mustache____construct_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__getEscapeByDefault_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__getStartSequence_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__getStopSequence_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__setEscapeByDefault_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
	ZEND_ARG_INFO(0, escapeByDefault)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__setStartSequence_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
	ZEND_ARG_INFO(0, startSequence)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__setStopSequence_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
	ZEND_ARG_INFO(0, stopSequence)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__parse_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
	ZEND_ARG_INFO(0, tmpl)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__render_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 3)
	ZEND_ARG_INFO(0, str)
        ZEND_ARG_INFO(0, vars)
        ZEND_ARG_INFO(0, partials)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__tokenize_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
	ZEND_ARG_INFO(0, tmpl)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(Mustache__debugDataStructure_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
        ZEND_ARG_INFO(0, vars)
ZEND_END_ARG_INFO()
/* }}} */

/* {{{ Mustache_methods */
static zend_function_entry Mustache_methods[] = {
  PHP_ME(Mustache, __construct, Mustache____construct_args, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
  PHP_ME(Mustache, getEscapeByDefault, Mustache__getEscapeByDefault_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, getStartSequence, Mustache__getStartSequence_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, getStopSequence, Mustache__getStopSequence_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, setEscapeByDefault, Mustache__setEscapeByDefault_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, setStartSequence, Mustache__setStartSequence_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, setStopSequence, Mustache__setStopSequence_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, parse, Mustache__parse_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, render, Mustache__render_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, tokenize, Mustache__tokenize_args, ZEND_ACC_PUBLIC)
  PHP_ME(Mustache, debugDataStructure, Mustache__debugDataStructure_args, ZEND_ACC_PUBLIC)
  { NULL, NULL, NULL }
};
/* }}} */

/* {{{ php_mustache_mustache_object_fetch_object */
static inline struct php_obj_Mustache * php_mustache_mustache_fetch_object(zend_object * obj)
{
  return (struct php_obj_Mustache *) ((char *)(obj) - XtOffsetOf(struct php_obj_Mustache, std));
}

struct php_obj_Mustache * php_mustache_mustache_object_fetch_object(zval * zv)
{
  return php_mustache_mustache_fetch_object(Z_OBJ_P(zv));
}
/* }}} */

/* {{{ Mustache_obj_free */
static void Mustache_obj_free(zend_object * object)
{
  try {
    struct php_obj_Mustache * payload = php_mustache_mustache_fetch_object(object);

    if( payload->mustache != NULL ) {
      delete payload->mustache;
    }

    zend_object_std_dtor((zend_object *) object);
  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} */

/* {{{ Mustache_obj_create */
static zend_object * Mustache_obj_create(zend_class_entry * ce)
{
  struct php_obj_Mustache * intern;

  try {
    intern = (struct php_obj_Mustache *) ecalloc(1, sizeof(php_obj_Mustache) + zend_object_properties_size(ce));
    zend_object_std_init(&intern->std, ce);
    intern->std.handlers = &Mustache_obj_handlers;

    intern->mustache = mustache_new_Mustache();
    return &intern->std;
  } catch(...) {
    mustache_exception_handler();
  }

  return NULL;
}
/* }}} */

/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(mustache_mustache)
{
  try {
    zend_class_entry ce;

    INIT_CLASS_ENTRY(ce, "Mustache", Mustache_methods);
    ce.create_object = Mustache_obj_create;
    Mustache_ce_ptr = zend_register_internal_class(&ce);
    memcpy(&Mustache_obj_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    Mustache_obj_handlers.offset = XtOffsetOf(php_obj_Mustache, std);
    Mustache_obj_handlers.free_obj = Mustache_obj_free;
    Mustache_obj_handlers.clone_obj = NULL;

    return SUCCESS;
  } catch(...) {
    mustache_exception_handler();
    return FAILURE;
  }
}
/* }}} */

/* {{{ mustache_new_Mustache */
mustache::Mustache * mustache_new_Mustache() {
  mustache::Mustache * mustache = new mustache::Mustache();

  // Set ini settings
  if( MUSTACHEG(default_escape_by_default) ) {
    mustache->setEscapeByDefault(true);
  } else {
    mustache->setEscapeByDefault(false);
  }
  if( MUSTACHEG(default_start_sequence) ) {
    mustache->setStartSequence(MUSTACHEG(default_start_sequence), 0);
  }
  if( MUSTACHEG(default_stop_sequence) ) {
    mustache->setStopSequence(MUSTACHEG(default_stop_sequence), 0);
  }

  return mustache;
}
/* }}} */

/* {{{ mustache_parse_data_param */
bool mustache_parse_data_param(zval * data, mustache::Mustache * mustache, mustache::Data ** node)
{
  struct php_obj_MustacheData * mdPayload = NULL;

  if( Z_TYPE_P(data) == IS_OBJECT ) {
    if( Z_OBJCE_P(data) == MustacheData_ce_ptr ) {
      mdPayload = php_mustache_data_object_fetch_object(data);
      *node = mdPayload->data;
      return true;
    } else {
      mustache_data_from_zval(*node, data);
      return true;
    }
  } else {
    mustache_data_from_zval(*node, data);
    return true;
  }
}
/* }}} */

/* {{{ mustache_parse_partials_param */
static inline void mustache_parse_partial_param(char * key, zval * data,
        mustache::Mustache * mustache, mustache::Node::Partials * partials)
{
    std::string ckey;
    std::string tmpl;
    mustache::Node node;
    mustache::Node * nodePtr = NULL;
    struct php_obj_MustacheAST * maPayload;

    if( Z_TYPE_P(data) == IS_STRING ) {
      // String key, string value
      ckey.assign(key);
      tmpl.assign(Z_STRVAL_P(data));
      partials->insert(std::make_pair(ckey, node));
      mustache->tokenize(&tmpl, &(*partials)[ckey]);
    } else if( Z_TYPE_P(data) == IS_OBJECT ) {
        // String key, object value
        if( Z_OBJCE_P(data) == MustacheTemplate_ce_ptr ) {
            zval rv;
#if PHP_VERSION_ID < 80000
            zval * value = zend_read_property(Z_OBJCE_P(data), data, "template", sizeof("template")-1, 1, &rv);
#else
            zval * value = zend_read_property(Z_OBJCE_P(data), Z_OBJ_P(data), "template", sizeof("template")-1, 1, &rv);
#endif
            convert_to_string(value);
            std::string tmpstr(Z_STRVAL_P(value));
            ckey.assign(key);
            partials->insert(std::make_pair(ckey, node));
            mustache->tokenize(&tmpstr, &(*partials)[ckey]);
        } else if( Z_OBJCE_P(data) == MustacheAST_ce_ptr ) {
            ckey.assign(key);
            maPayload = php_mustache_ast_object_fetch_object(data);
            partials->insert(std::make_pair(ckey, node));
            nodePtr = &(*partials)[ckey];
            nodePtr->type = mustache::Node::TypeContainer;
            nodePtr->child = maPayload->node;
        } else {
            php_error(E_WARNING, "Object not an instance of MustacheTemplate or MustacheAST");
        }
    } else {
        php_error(E_WARNING, "Partial array contains an invalid value");
    }
}

bool mustache_parse_partials_param(zval * array, mustache::Mustache * mustache,
        mustache::Node::Partials * partials)
{
    HashTable * data_hash = NULL;
    zend_ulong key_nindex = 0;

    // Ignore if not an array
    if( array == NULL || Z_TYPE_P(array) != IS_ARRAY ) {
        return false;
    }

    data_hash = HASH_OF(array);

    zval * data_entry = NULL;
    zend_string * key = NULL;

    ZEND_HASH_FOREACH_KEY_VAL(data_hash, key_nindex, key, data_entry) {
        (void)key_nindex;
        if( !key ) {
            php_error(E_WARNING, "Partial array contains a non-string key");
        } else {
            mustache_parse_partial_param(key->val, data_entry, mustache, partials);
        }
    } ZEND_HASH_FOREACH_END();

  return true;
}
/* }}} */

/* {{{ mustache_parse_template_param */
bool mustache_parse_template_param(zval * tmpl, mustache::Mustache * mustache,
        mustache::Node ** node)
{
  // Prepare template string
  if( Z_TYPE_P(tmpl) == IS_STRING ) {
    // Tokenize template
    char * tmpstr = Z_STRVAL_P(tmpl);
    std::string templateStr(tmpstr/*, (size_t) Z_STRLEN_P(tmpl)*/);
    mustache->tokenize(&templateStr, *node);
    return true;

  } else if( Z_TYPE_P(tmpl) == IS_OBJECT ) {
    // Use compiled template
    if( Z_OBJCE_P(tmpl) == MustacheTemplate_ce_ptr ) {
        zval rv;
#if PHP_VERSION_ID < 80000
        zval * value = zend_read_property(Z_OBJCE_P(tmpl), tmpl, "template", sizeof("template")-1, 1, &rv);
#else
        zval * value = zend_read_property(Z_OBJCE_P(tmpl), Z_OBJ_P(tmpl), "template", sizeof("template")-1, 1, &rv);
#endif
        convert_to_string(value);
        std::string tmpstr(Z_STRVAL_P(value));

      if( !tmpstr.length() ) {
        php_error(E_WARNING, "Empty MustacheTemplate");
        return false;
      } else {
        mustache->tokenize(&tmpstr, *node);
      }
      return true;
    } else if( Z_OBJCE_P(tmpl) == MustacheAST_ce_ptr ) {
      struct php_obj_MustacheAST * maPayload = php_mustache_ast_object_fetch_object(tmpl);
      if( maPayload->node == NULL ) {
        php_error(E_WARNING, "Empty MustacheAST");
        return false;
      }
      *node = maPayload->node;
      return true;
    } else {
      php_error(E_WARNING, "Object not an instance of MustacheTemplate or MustacheAST");
      return false;
    }
  } else {
    php_error(E_WARNING, "Invalid argument");
    return false;
  }
}
/* }}} */

/* {{{ proto void Mustache::__construct() */
PHP_METHOD(Mustache, __construct)
{
  try {
    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "O",
            &_this_zval, Mustache_ce_ptr) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::__construct */

/* {{{ proto boolean Mustache::getEscapeByDefault() */
PHP_METHOD(Mustache, getEscapeByDefault)
{
  try {
    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "O",
            &_this_zval, Mustache_ce_ptr) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    if( payload->mustache->getEscapeByDefault() ) {
      RETURN_TRUE;
    } else {
      RETURN_FALSE;
    }

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::getEscapeByDefault */

/* {{{ proto string Mustache::getStartSequence() */
PHP_METHOD(Mustache, getStartSequence)
{
  try {
    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "O",
            &_this_zval, Mustache_ce_ptr) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    const std::string & str = payload->mustache->getStartSequence();
    RETVAL_STRINGL(str.c_str(), str.length());

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::getStartSequence */

/* {{{ proto string Mustache::getStopSequence() */
PHP_METHOD(Mustache, getStopSequence)
{
  try {
    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "O",
            &_this_zval, Mustache_ce_ptr) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    const std::string & str = payload->mustache->getStopSequence();
    RETVAL_STRINGL(str.c_str(), str.length());

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::getStopSequence */

/* {{{ proto boolean Mustache::setStartSequence(bool flag) */
PHP_METHOD(Mustache, setEscapeByDefault)
{
  try {
    // Custom parameters
    long flag = 0;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Ol",
            &_this_zval, Mustache_ce_ptr, &flag) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    payload->mustache->setEscapeByDefault((bool) flag != 0);
    RETURN_TRUE;

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::setEscapeByDefault */

/* {{{ proto boolean Mustache::setStartSequence(string str) */
PHP_METHOD(Mustache, setStartSequence)
{
  try {
    // Custom parameters
    char * str = NULL;
    long str_len = 0;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Os",
            &_this_zval, Mustache_ce_ptr, &str, &str_len) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    payload->mustache->setStartSequence(str/*, str_len*/);
    RETURN_TRUE;

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::setStartSequence */

/* {{{ proto boolean Mustache::setStopSequence(string str) */
PHP_METHOD(Mustache, setStopSequence)
{
  try {
    // Custom parameters
    char * str = NULL;
    long str_len = 0;

    // Check parameters
    zval * _this_zval;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Os",
            &_this_zval, Mustache_ce_ptr, &str, &str_len) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Main
    payload->mustache->setStopSequence(str/*, str_len*/);
    RETURN_TRUE;

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::setStartSequence */

/* {{{ proto MustacheAST Mustache::parse(string template) */
PHP_METHOD(Mustache, parse)
{
  try {
    // Custom parameters
    zval * tmpl = NULL;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Oz",
            &_this_zval, Mustache_ce_ptr, &tmpl) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Check template parameter
    mustache::Node * templateNodePtr = new mustache::Node();
    if( !mustache_parse_template_param(tmpl, payload->mustache, &templateNodePtr) ) {
      delete templateNodePtr;
      RETURN_FALSE;
      return;
    }

    // Handle return value
    if( Z_TYPE_P(tmpl) == IS_STRING ) {
      if( MustacheAST_ce_ptr == NULL ) {
        delete templateNodePtr;
        php_error_docref(NULL, E_WARNING, "Class MustacheAST does not exist");
        RETURN_FALSE;
        return;
      }

      // Initialize new object
      object_init_ex(return_value, MustacheAST_ce_ptr);
      struct php_obj_MustacheAST * intern = php_mustache_ast_object_fetch_object(return_value);
      intern->node = templateNodePtr;

    // Ref - not sure if this is required
//    Z_SET_REFCOUNT_P(return_value, 1);
//    Z_SET_ISREF_P(return_value);

    } else if( Z_TYPE_P(tmpl) == IS_OBJECT ) {
      // Handle return value for object parameter
      // @todo return the object itself?
      RETURN_TRUE;
    }

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::parse */

/* {{{ proto string Mustache::render(mixed template, array data, array partials) */
PHP_METHOD(Mustache, render)
{
  try {
    // Custom parameters
    zval * tmpl = NULL;
    zval * data = NULL;
    zval * partials = NULL;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Ozz|a/",
            &_this_zval, Mustache_ce_ptr, &tmpl, &data, &partials) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Prepare template tree
    mustache::Node templateNode;
    mustache::Node * templateNodePtr = &templateNode;
    if( !mustache_parse_template_param(tmpl, payload->mustache, &templateNodePtr) ) {
      RETURN_FALSE;
      return;
    }

    // Prepare template data
    mustache::Data templateData;
    mustache::Data * templateDataPtr = &templateData;
    if( !mustache_parse_data_param(data, payload->mustache, &templateDataPtr) ) {
      RETURN_FALSE;
      return;
    }

    // Tokenize partials
    mustache::Node::Partials templatePartials;
    mustache_parse_partials_param(partials, payload->mustache, &templatePartials);

    // Reserve length of template
    std::string output;
    if( Z_TYPE_P(tmpl) == IS_STRING ) {
      output.reserve(Z_STRLEN_P(tmpl));
    }

    // Render template
    payload->mustache->render(templateNodePtr, templateDataPtr, &templatePartials, &output);

    // Output
    RETVAL_STRINGL(output.c_str(), output.length());

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::render */

/* {{{ proto array Mustache::tokenize(string template) */
PHP_METHOD(Mustache, tokenize)
{
  try {
    // Custom parameters
    char * template_str = NULL;
    long template_len = 0;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Os",
            &_this_zval, Mustache_ce_ptr, &template_str, &template_len) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();
    struct php_obj_Mustache * payload = php_mustache_mustache_object_fetch_object(_this_zval);

    // Assign template to string
    std::string templateStr(template_str/*, template_len*/);

    // Tokenize template
    mustache::Node root;
    payload->mustache->tokenize(&templateStr, &root);

    // Convert to PHP array
    mustache_node_to_zval(&root, return_value);

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::tokenize */

/* {{{ proto array Mustache::debugDataStructure(array data) */
PHP_METHOD(Mustache, debugDataStructure)
{
  try {
    // Custom parameters
    zval * data = NULL;

    // Check parameters
    zval * _this_zval = NULL;
    if( zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), (char *) "Oz",
            &_this_zval, Mustache_ce_ptr, &data) == FAILURE) {
      throw PhpInvalidParameterException();
    }

    // Class parameters
    _this_zval = getThis();

    // Prepare template data
    mustache::Data templateData;
    mustache_data_from_zval(&templateData, data);

    // Reverse template data
    mustache_data_to_zval(&templateData, return_value);

  } catch(...) {
    mustache_exception_handler();
  }
}
/* }}} Mustache::debugDataStructure */


text:
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Oblqo.Tasks
{
    [AccountFileStateChange(AccountFileStates.New, "UploadedFile")]
    public class UploadFileTask : AsyncTask
    {
        public string FileName { get; private set; }
        public AccountFile DestFolder { get; private set; }
        public AccountFile UploadedFile { get; private set; }
        public UploadFileTask() { }
        public UploadFileTask(Account account, string accountName, int priority, AsyncTask[] parent, string fileName, AccountFile destFolder)
            : base(account, accountName, priority, parent)
        {
            FileName = fileName;
            DestFolder = destFolder;
        }

        protected override async Task OnStartAsync()
        {
            var destFolder = DestFolder;
            if (destFolder == null && Common.IsSingle(Parents) && Parents[0] is CreateFolderTask)
                destFolder = ((CreateFolderTask)Parents[0]).CreatedFolder;

            // sync dest folder on all drives
            var tasks = (from drive in Account.Drives
                         where DestFolder.GetDriveFile(drive) == null
                         select DestFolder.GetFileAndCreateIfFolderIsNotExistsAsync(drive, CancellationTokenSource.Token)
                         ).Cast<Task>().ToList();
            await Task.WhenAll(tasks);

            UploadedFile = await
                Account.UploadFileAsync(FileName, destFolder, CancellationTokenSource.Token,
                    e => OnProgress(new AsyncTaskProgressEventArgs(e.PercentDone, null)));
        }

        public override async Task LoadAsync(Account account, string id, XElement xml, CancellationToken token)
        {
            await base.LoadAsync(account, id, xml, token);
            FileName = xml.Attribute("fileName").Value;
            DestFolder = await account.GetFileAsync(xml.Element("destFolder"), token);
        }

        public override XElement ToXml()
        {
            var xml = base.ToXml();
            xml.SetAttributeValue("fileName", FileName);
            xml.Add(DestFolder.ToXml("destFolder"));
            return xml;
        }

    }
}


text:
package org.finra.herd.app.security;

import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.finra.herd.core.helper.ConfigurationHelper;
import org.finra.herd.dao.helper.HerdStringHelper;
import org.finra.herd.model.dto.ApplicationUser;
import org.finra.herd.model.dto.ConfigurationValue;

/**
 * Http headers based Application user builder.
 */
@SuppressFBWarnings(value = "MS_PKGPROTECT", justification = "We will leave CALENDAR_PATTERNS as public since AbstractAppTest needs access to it.")
public class HttpHeaderApplicationUserBuilder implements ApplicationUserBuilder
{
    private static final Logger LOGGER = Logger.getLogger(ApplicationUserBuilder.class);

    @Autowired
    private ConfigurationHelper configurationHelper;

    @Autowired
    private HerdStringHelper herdStringHelper;

    public static final String HTTP_HEADER_USER_ID = "useridHeader";
    public static final String HTTP_HEADER_FIRST_NAME = "firstNameHeader";
    public static final String HTTP_HEADER_LAST_NAME = "lastNameHeader";
    public static final String HTTP_HEADER_EMAIL = "emailHeader";
    public static final String HTTP_HEADER_ROLES = "rolesHeader";
    public static final String HTTP_HEADER_SESSION_INIT_TIME = "sessionInitTimeHeader";
    public static final String HTTP_HEADER_SESSION_ID = "sessionid";

    // The password expire date format (e.g. 20080202211030Z)
    public static final String CALENDAR_PATTERN_PWD = "yyyyMMddHHmmss'Z'";

    // The session init and expire date format (e.g. Fri, 19 Oct 2007 17:24:09)
    public static final String CALENDAR_PATTERN_SESSION = "EEE, dd MMM yyyy HH:mm:ss";

    // The session init and expire date format with timezone (e.g. Fri, 19 Oct 2007 17:24:09 GMT)
    public static final String CALENDAR_PATTERN_SESSION_TZ = "EEE, dd MMM yyyy HH:mm:ss z";

    // The array of all calendar patterns
    public static final String[] CALENDAR_PATTERNS = {CALENDAR_PATTERN_PWD, CALENDAR_PATTERN_SESSION, CALENDAR_PATTERN_SESSION_TZ};

    @Override
    public ApplicationUser build(HttpServletRequest request)
    {
        return buildUser(getHttpHeaders(request), true);
    }

    @Override
    public ApplicationUser buildNoRoles(HttpServletRequest request)
    {
        // Return the application user without roles.
        return buildUser(getHttpHeaders(request), false);
    }

    /**
     * Creates a map of the HTTP headers contained within the servlet request. The session Id is also placed in the HTTP_HEADER_SESSION_ID key.
     *
     * @param request the HTTP servlet request.
     *
     * @return the map of headers.
     */
    private Map<String, String> getHttpHeaders(HttpServletRequest request)
    {
        // Create a hash map to contain the headers.
        Map<String, String> headerMap = new HashMap<String, String>();

        // Enumerate through each header and store it in the map.
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements())
        {
            String header = enumeration.nextElement();
            headerMap.put(header.toLowerCase(), request.getHeader(header));
        }

        // Place the session Id in a special key so it can retrieved later on when building the user.
        headerMap.put(HTTP_HEADER_SESSION_ID, request.getSession().getId());

        // Return the header map.
        return headerMap;
    }

    /**
     * Builds the application user from the header map.
     *
     * @param headerMap the map of headers.
     * @param includeRoles If true, the user's roles will be included. Otherwise, not.
     *
     * @return the application user.
     */
    protected ApplicationUser buildUser(Map<String, String> headerMap, boolean includeRoles)
    {
        LOGGER.debug("Creating Application User From Headers");

        Map<String, String> headerNames = getHeaderNames();
        // Build the user in pieces.
        ApplicationUser applicationUser = createNewApplicationUser();

        buildUserId(applicationUser, headerMap, headerNames.get(HTTP_HEADER_USER_ID));
        buildFirstName(applicationUser, headerMap, headerNames.get(HTTP_HEADER_FIRST_NAME));
        buildLastName(applicationUser, headerMap, headerNames.get(HTTP_HEADER_LAST_NAME));
        buildEmail(applicationUser, headerMap, headerNames.get(HTTP_HEADER_EMAIL));
        buildSessionId(applicationUser, headerMap, HTTP_HEADER_SESSION_ID);
        buildSessionInitTime(applicationUser, headerMap, headerNames.get(HTTP_HEADER_SESSION_INIT_TIME));

        if (includeRoles)
        {
            buildRoles(applicationUser, headerMap, headerNames.get(HTTP_HEADER_ROLES));
        }

        LOGGER.debug("Application user created successfully: " + applicationUser);

        return applicationUser;
    }

    /**
     * A Factory Method for creating a new ApplicationUser. Provide ability for subclasses to override this if a custom user class is required. The
     * custom user class must extend ApplicationUser.
     *
     * @return ApplicationUser (or a subtype)
     */
    protected ApplicationUser createNewApplicationUser()
    {
        return new ApplicationUser(this.getClass());
    }

    /**
     * Builds a user Id.
     *
     * @param applicationUser the application user.
     * @param httpHeaders the HTTP headers.
     * @param headerName the header name for the user Id.
     */
    protected void buildUserId(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        String userId = getHeaderValueString(headerName, httpHeaders);
        if (userId == null)
        {
            throw new IllegalArgumentException("userId is required. No value for userId was found in the header " + headerName);
        }

        applicationUser.setUserId(userId);
    }

    protected void buildFirstName(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        applicationUser.setFirstName(getHeaderValueString(headerName, httpHeaders));
    }

    protected void buildLastName(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        applicationUser.setLastName(getHeaderValueString(headerName, httpHeaders));
    }

    protected void buildEmail(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        applicationUser.setEmail(getHeaderValueString(headerName, httpHeaders));
    }

    protected void buildSessionId(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        applicationUser.setSessionId(getHeaderValueString(headerName, httpHeaders));
    }

    protected void buildSessionInitTime(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        applicationUser.setSessionInitTime(getHeaderValueDate(headerName, httpHeaders));
    }

    /**
     * Parses the header and assigns roles to the given user object. The header value of the given header name will be parsed for roles. See parseRoles(String,
     * Set) method for details on the parsing process.
     *
     * @param applicationUser - the user object to populate the roles to
     * @param httpHeaders - the HTTP headers given in the current request
     * @param headerName - the name of the header containing the roles
     */
    protected void buildRoles(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName)
    {
        Set<String> roles = new HashSet<>();
        applicationUser.setRoles(roles);

        String rolesHeaderValue = getHeaderValueString(headerName, httpHeaders);
        if (rolesHeaderValue != null)
        {
            parseRoles(rolesHeaderValue, roles);
        }

        /*
         * If we need to have a mechanism to retrieve roles such that a single header represents a unique role, then the extra code to handle this situation
         * could be added here.
         */
    }

    /**
     *
 Parses the given header value for roles, and adds them to the given collection of roles.

 The roles are parsed using the configured regex and
     * regex group name retrieved from {@link #getHttpHeaderRoleRegex()} and {@link #getHttpHeaderRoleRegexGroupName()}.

 The regex is matched against
     * the value until no more matches are found. If the regex group name is set (not empty), then the group with the configured name will be extracted from the
     * match and be set as the role. If the regex group name is not set, then the entire match will be used as the role. Each matching role is then added to the
     * collection of roles supplied.

 If no regex is configured (regex is empty), then this method does nothing (ie. The app is configured to not use
     * multiple role header).

     *
     * @param value - the string value to parse
     * @param roles - the collection of roles to add the parsed roles to
     *
     * @see How to use named groups
     * @see Pattern
     */
    private void parseRoles(String value, Collection<String> roles)
    {
        String regex = getHttpHeaderRoleRegex();

        // Do nothing if regex is not configured
        if (StringUtils.isNotBlank(regex))
        {
            // Compile the regex
            Pattern pattern = Pattern.compile(regex);

            // Create a matcher from the regex and the given value
            Matcher matcher = pattern.matcher(value);

            String roleRegexGroupName = getHttpHeaderRoleRegexGroupName();

            // Use regex group name if group name is configured
            // Do this outside the loop below to avoid calling isNotBlank() repeatedly
            boolean useRoleRegexGroupName = StringUtils.isNotBlank(roleRegexGroupName);
            while (matcher.find())
            {
                String role = null;

                // Decide whether to use group or not
                if (useRoleRegexGroupName)
                {
                    // Extract role name based on the regex group name
                    role = matcher.group(roleRegexGroupName);
                }
                else
                {
                    // Use entire match as the role
                    role = matcher.group();
                }

                // If a role was matched
                if (role != null)
                {
                    // Add the role to the result
                    roles.add(role);
                }
            }
        }
    }

    /**
     * Gets an HTTP header string value from the map of headers for the specified header name. If the header value is blank, null will be returned in its place.
     * The header name is case-insensitive, but will be converted to lower-case before retrieving the header value. The returned header value is trimmed.
     *
     * @param headerName the HTTP header name to get.
     * @param httpHeaders the HTTP headers.
     *
     * @return the HTTP header value.
     */
    protected String getHeaderValueString(String headerName, Map<String, String> httpHeaders)
    {
        String headerNameLocal = headerName;

        if (headerNameLocal != null)
        {
            headerNameLocal = headerNameLocal.toLowerCase();
        }

        String headerValue = httpHeaders.get(headerNameLocal);
        if (StringUtils.isBlank(headerValue))
        {
            headerValue = null;
        }
        else
        {
            headerValue = headerValue.trim();
        }
        return headerValue;
    }

    /**
     * Gets an HTTP header date value from the map of headers for the specified header name. If the header value is blank or can't be converted to a Date, null
     * will be returned in its place.
     *
     * @param headerName the HTTP header name to get.
     * @param httpHeaders the HTTP headers.
     *
     * @return the HTTP header value.
     */
    public Date getHeaderValueDate(String headerName, Map<String, String> httpHeaders)
    {
        // Default the return value to null.
        Date dateValue = null;

        // Get the string value for the header name.
        String stringValue = getHeaderValueString(headerName, httpHeaders);

        // Try to convert it to a Date if possible
        if (stringValue != null)
        {
            try
            {
                dateValue = DateUtils.parseDate(stringValue, CALENDAR_PATTERNS);
            }
            catch (Exception ex)
            {
                // The value couldn't be converted to a Date so leave the dateValue null.
                dateValue = null;
            }
        }

        // Return the calendar value.
        return dateValue;
    }

    /**
     * Gets the header names from configuration in the current environment.
     *
     * @return map of header name key to header value
     */
    private Map<String, String> getHeaderNames()
    {
        Map<String, String> headerNames = new HashMap<>();

        List<String> headers = herdStringHelper.splitStringWithDefaultDelimiter(getSecurityHeaderNames());

        for (String header : headers)
        {
            String[] keyValueString = header.split("=");

            headerNames.put(keyValueString[0], keyValueString[1]);
        }

        return headerNames;
    }

    /**
     * Gets the delimited security header names.
     *
     * @return header names
     */
    private String getSecurityHeaderNames()
    {
        return getProperty(ConfigurationValue.SECURITY_HTTP_HEADER_NAMES);
    }

    /**
     * Gets the regex to use to parse a role from a string which may contain multiple roles. May return empty string, in which case the application should not
     * attempt to apply role parsing.
     *
     * @return regex
     */
    private String getHttpHeaderRoleRegex()
    {
        return getProperty(ConfigurationValue.SECURITY_HTTP_HEADER_ROLE_REGEX);
    }

    /**
     * Gets the group name of a regex match which represents a role. May return empty string, in which case the application should not use named groups.
     *
     * @return regex group name
     */
    private String getHttpHeaderRoleRegexGroupName()
    {
        return getProperty(ConfigurationValue.SECURITY_HTTP_HEADER_ROLE_REGEX_GROUP);
    }

    /**
     * Gets the property value from the current environment. If no value is configured, uses whatever default is configured in the given configurationValue.
     *
     * @param configurationValue - the configuration value to retrieve
     *
     * @return the value in the environment
     */
    private String getProperty(ConfigurationValue configurationValue)
    {
        return configurationHelper.getProperty(configurationValue);
    }
}


text:
% Copyright 2011 The Avalon Project Authors. All rights reserved.
% Use of this source code is governed by the Apache License 2.0
% that can be found in the LICENSE file.
% Steffen Grundmann, April 2011

function debug_switch_init()
% function debug_switch_init()
% Use all forces in the forces calculation.
% Switch printing of forces off.

debug_switch_force_off();
global debug_switches;
debug_switches.print_forces = 0;
endfunction


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Punjab pl. 51. 1869

#### Original name
null

### Remarks
null


text:
//
//  PlayerTurnLayer.h
//  SurvivalDungeon
//
//  Created by Marlon Andrade on 6/2/15.
//
//

#ifndef __SurvivalDungeon__PlayerTurnLayer__
#define __SurvivalDungeon__PlayerTurnLayer__

#include "cocos2d.h"

class DiceSelectLayer;
class GameplayLayer;

class PlayerTurnLayer : public cocos2d::Layer {
public:
  virtual bool init();
  CREATE_FUNC(PlayerTurnLayer);

  void playerTurnHasStarted();

  void showDiceSelectLayer();
  void showGameplayLayer();

private:
  DiceSelectLayer* _getDiceSelectLayer();
  GameplayLayer* _getGameplayLayer();

  void _setupChildren();
};

#endif /* defined(__SurvivalDungeon__PlayerTurnLayer__) */


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_post_trainadv.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_xbus_post_trainadv.H
/// @brief Post-Training PHY Status Function.
///
///-----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 3
/// *HWP Consumed by      : FSP:HB
///-----------------------------------------------------------------------------

#ifndef _P9_IO_XBUS_POST_TRAINADV_H_
#define _P9_IO_XBUS_POST_TRAINADV_H_

// ----------------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------------
#include <fapi2.H>

//-----------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------

// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_io_xbus_post_trainadv_FP_t)
(const fapi2::Target < fapi2::TARGET_TYPE_XBUS >&,
 const uint8_t&,
 const fapi2::Target < fapi2::TARGET_TYPE_XBUS >&,
 const uint8_t&);

// ----------------------------------------------------------------------------
// Constant Definitions
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// Function Protoypes
// ----------------------------------------------------------------------------
extern "C" {

    /**
     * @brief A simple HWP that runs after io_run_trainig.
     *  This function is called on every Xbus.
     * @param[in] i_target   Fapi2 Target
     * @param[in] i_group    Clock Group
     * @param[in] i_ctarget  Fapi2 Connected Target
     * @param[in] i_cgroup   Connected Clock Group
     * @retval ReturnCode
     */
    fapi2::ReturnCode p9_io_xbus_post_trainadv(
        const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target,
        const uint8_t& i_group,
        const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget,
        const uint8_t& i_cgroup);

} // extern "C"

#endif // _P9_IO_XBUS_POST_TRAINADV_H_