text:
>**NOTE:** If you have deployed your Cloud Foundry by following the latest [guidance](../../guidance.md) via ARM templates on Azure, you already have Diego as default architecture, and don't need to follow this guide.

Cloud Foundry has used two architectures for managing application containers: Droplet Execution Agents (DEA) and Diego.
With the DEA architecture, the Cloud Controller schedules and manages applications on the DEA nodes.
In the Diego architecture, Diego components replace the DEAs and the Health Manager (HM9000), and assume application scheduling and management responsibility from the Cloud Controller.

This document describes the steps to update your Cloud Foundry to use Diego as default architecture on Azure.

## 1 Prerequisites

* A deployment of BOSH

  It is assumed that you have already deployed your **BOSH director VM** on Azure by following the [guidance](../../guidance.md) via ARM templates.

* Manifests

  It is assumed that you have manifests for Cloud Foundry which use DEA as default architecture. Prior to commit [604a163](https://github.com/Azure/azure-quickstart-templates/commit/604a1634126646ba83c9e98e6b50b10019183168), the templates use DEA as default architecture, you will learn how to switch to Diego-default in this guide. Here we take multiple-vm-cf.yml as an example.

## 2 Update manifest and deploy Cloud Foundry with Diego

1. Update manifest.

    * Change for DEA nodes

        * If you want to keep DEA nodes, just keep the original manifest as what it is and go ahead to `Change for Diego`

            _You may want to migrate DEA applications to Diego, please refer to [guide](https://docs.cloudfoundry.org/adminguide/apps-enable-diego.html) to do migration after the deployment is done._

        * If you want to remove DEA nodes, remove DEA and hm9000 related configuration out of the manifest

            * remove jobs.hm9000_z1 and jobs.runner_z1

                ```
                - name: hm9000_z1
                  instances: 1
                  resource_pool: resource_z1
                  ...
                ```

                ```
                - name: runner_z1
                  instances: 1
                  resource_pool: resource_z1
                  ...
                ```

            * remove properties.dea_next and properties.hm9000

                ```
                dea_next:
                  advertise_interval_in_seconds: 5
                  heartbeat_interval_in_seconds: 10
                  memory_mb: 33996
                  enable_ssl: true
                  ...
                ```

                ```
                hm9000:
                  url: https://hm9000.REPLACE_WITH_SYSTEM_DOMAIN
                  port: 5155
                  ...
                ```

    * Change for Diego

        >**NOTE:** The versions and job specs below could be different in your environment, depending on which version of cf-release / diego-release you are using and how you deploy your Cloud Foundry.

        * Add Diego related releases. Example:

            ```yaml
            releases:
            - {name: diego, version: 0.1476.0}
            - {name: garden-linux, version: 0.338.0}
            - {name: cflinuxfs2-rootfs , version: 1.16.0}
            ```

        * Add Diego related jobs. Example:

            ```yaml
            jobs:
            - name: database_z1
              instances: 1
              templates:
              - name: consul_agent
                release: cf
              - name: etcd
                release: cf
              - name: bbs
                release: diego
              - name: metron_agent
                release: cf
              persistent_disk: 20480
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: true
                max_in_flight: 1
              properties:
                consul:
                  agent:
                    services:
                      etcd: {}
                metron_agent:
                  zone: z1
            - name: brain_z1
              instances: 1
              templates:
              - name: consul_agent
                release: cf
              - name: auctioneer
                release: diego
              - name: converger
                release: diego
              - name: metron_agent
                release: cf
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: true
                max_in_flight: 1
              properties:
                metron_agent:
                  zone: z1
            - name: cell_z1
              instances: 2
              templates:
              - name: consul_agent
                release: cf
              - name: rep
                release: diego
              - name: garden
                release: garden-linux
              - name: cflinuxfs2-rootfs-setup
                release: cflinuxfs2-rootfs
              - name: metron_agent
                release: cf
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: false
                max_in_flight: 1
              properties:
                metron_agent:
                  zone: z1
                diego:
                  rep:
                    zone: z1
            - name: cc_bridge_z1
              instances: 1
              templates:
              - name: consul_agent
                release: cf
              - name: stager
                release: cf
              - name: nsync
                release: cf
              - name: tps
                release: cf
              - name: cc_uploader
                release: cf
              - name: metron_agent
                release: cf
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: false
                max_in_flight: 1
              properties:
                metron_agent:
                  zone: z1
            - name: access_z1
              instances: 1
              templates:
              - name: consul_agent
                release: cf
              - name: ssh_proxy
                release: diego
              - name: metron_agent
                release: cf
              - name: file_server
                release: diego
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: false
                max_in_flight: 1
              properties:
                metron_agent:
                  zone: z1
            - name: route_emitter_z1
              instances: 1
              templates:
              - name: consul_agent
                release: cf
              - name: route_emitter
                release: diego
              - name: metron_agent
                release: cf
              resource_pool: resource_z1
              networks:
                - name: cf_private
              update:
                serial: false
                max_in_flight: 1
              properties:
                metron_agent:
                  zone: z1
            ```

    * Add diego properties. Example:

        ```yaml
        properties:
          capi:
            nsync:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              cc:
                base_url: https://api.REPLACE_WITH_SYSTEM_DOMAIN
                basic_auth_password: REPLACE_WITH_PASSWORD
            tps:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              cc:
                base_url: https://api.REPLACE_WITH_SYSTEM_DOMAIN
                basic_auth_password: REPLACE_WITH_PASSWORD
              traffic_controller_url: wss://doppler.REPLACE_WITH_SYSTEM_DOMAIN:443
            tps_listener:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              cc:
                base_url: https://api.REPLACE_WITH_SYSTEM_DOMAIN
                basic_auth_password: REPLACE_WITH_PASSWORD
            stager:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              cc:
                base_url: https://api.REPLACE_WITH_SYSTEM_DOMAIN
                basic_auth_password: REPLACE_WITH_PASSWORD
          diego:
            auctioneer:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
            bbs:
              active_key_label: active
              encryption_keys:
              - label: active
                passphrase: REPLACE_WITH_PASSWORD
              ca_cert: ""
              etcd:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              require_ssl: false
              server_cert: ""
              server_key: ""
            converger:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
            rep:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              preloaded_rootfses: ["cflinuxfs2:/var/vcap/packages/cflinuxfs2/rootfs"]
            route_emitter:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              nats:
                machines: [REPLACE_WITH_NATS_IP]
                password: REPLACE_WITH_PASSWORD
                port: 4222
                user: nats
            ssl:
              skip_cert_verify: true
            ssh_proxy:
              bbs:
                ca_cert: ""
                client_cert: ""
                client_key: ""
                require_ssl: false
              enable_cf_auth: true
              enable_diego_auth: false
              host_key: |
                REPLACE_WITH_SSH_HOST_KEY
              uaa_secret: REPLACE_WITH_PASSWORD
              uaa_token_url: https://uaa.REPLACE_WITH_SYSTEM_DOMAIN/oauth/token
        ```

        * Remember to change the REPLACE\_WITH* to proper values in your manifest

        * For production, you should use your certs and keys to set above ca_cert, client_cert and client_key. And You should set 'ssl.skip_cert_verify' to false and set 'require_ssl' to true.  For cert configuration, please refer to this [guide](https://github.com/cloudfoundry/diego-release/blob/develop/docs/tls-configuration.md); for additional changes when ssl is enabled, please refer to documents and job specs in [diego-release](https://github.com/cloudfoundry/diego-release/).

    * Add `properties.hm9000.port`. (In cf-release v238, even if hm9000 is not used, properties.hm9000.port is still requred.) Example:

        ```yaml
        properties:
          hm9000:
            port: 5525
        ```

    * Add/change `properties.cc.default_to_diego_backend` as true. This value will make Diego as default backend.

        ```yaml
        properties:
          cc:
            default_to_diego_backend: true
        ```

1. Deploy

    * Log on to your dev-box and login to your BOSH director VM. Example:

        ```
        bosh target 10.0.0.4
        ```

    * Upload addition Diego releases besides cf-release and stemcell. Example:

        ```
        bosh upload stemcell https://bosh.io/d/stemcells/bosh-azure-hyperv-ubuntu-trusty-go_agent?v=3232.11 --sha1 575a284a3e314a5e1dc78fed8ff73e8a1da9b78b --skip-if-exists
        bosh upload release https://bosh.io/d/github.com/cloudfoundry/cf-release?v=238 --sha1 fa6d35300f4fcd74a75fd8c7138f592acfcb32b0 --skip-if-exists
        bosh upload release https://bosh.io/d/github.com/cloudfoundry-incubator/diego-release?v=0.1476.0 --sha1 4b66fde250472e47eb2a0151bb676fc1be840f47 --skip-if-exists
        bosh upload release https://bosh.io/d/github.com/cloudfoundry-incubator/garden-linux-release?v=0.338.0 --sha1 432225d88edc9731be4453cb61eba33fa829ebdc --skip-if-exists
        bosh upload release https://bosh.io/d/github.com/cloudfoundry/cflinuxfs2-rootfs-release?v=1.16.0 --sha1 acfa1c4aad1fa9ef4623bf189cbab788a53f678e --skip-if-exists
        ```

    * deploy

        ```
        bosh deployment ~/example_manifests/multiple-vm-cf.yml
        bosh -n deploy
        ```

## 3 Push your first application to Diego

1. Log on to your dev-box

1. Install CF CLI and the plugin

    ```
    wget -O cf.deb http://go-cli.s3-website-us-east-1.amazonaws.com/releases/v6.14.1/cf-cli-installer_6.14.1_x86-64.deb
    sudo dpkg -i cf.deb
    ```

1. Configure your space. Example:

    ```
    cf login -a https://api.REPLACE_WITH_CLOUD_FOUNDRY_PUBLIC_IP.xip.io --skip-ssl-validation -u admin -p REPLACE_WITH_PASSWORD
    cf create-org diego
    cf target -o diego
    cf create-space diego
    cf target -s diego
    ```

1. Download a demo application and extract it. Example:

    ```
    sudo apt-get -y install git
    git clone https://github.com/bingosummer/2048
    ```

1. Push the application. Example:

    ```
    cd 2048
    cf push
    ```

1. Check whether the application is running on Diego, you can ssh into the running container for a check.

    ```
    cf ssh game-2048
    ```


text:
<?php

class Google_Service_ShoppingContent_OrdersCustomBatchRequestEntryRefund extends Google_Model
{
  protected $amountType = 'Google_Service_ShoppingContent_Price';
  protected $amountDataType = '';
  public $reason;
  public $reasonText;

  public function setAmount(Google_Service_ShoppingContent_Price $amount)
  {
    $this->amount = $amount;
  }
  public function getAmount()
  {
    return $this->amount;
  }
  public function setReason($reason)
  {
    $this->reason = $reason;
  }
  public function getReason()
  {
    return $this->reason;
  }
  public function setReasonText($reasonText)
  {
    $this->reasonText = $reasonText;
  }
  public function getReasonText()
  {
    return $this->reasonText;
  }
}

redpajama_set_name: RedPajamaGithub


text:
feature_name: Collections and Iterators (ES6)
chrome_version: 38
feature_id: 4696563918045184
---

Background

  There are several new types of collections and ways of iterating over collections in the
  draft ECMAScript 6 specification.

  This sample demonstrates creating and working with two types of collections, Set
  and Map. It also demonstrates using the  for...of syntax to iterate over
  each type of collection.

{% include output_helper.html %}

{% include js_snippet.html filename='demo.js' %}


text:
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from btctxstore import deserialize
from btctxstore import exceptions

class TestNulldataTxOut(unittest.TestCase):

    def test_max_data(self):

        # fourty bytes ok
        max_data = 40 * b"aa"
        deserialize.nulldata_txout(max_data)

        # > fourty bytes fails
        def callback():
            over_max_data = 41 * b"aa"
            deserialize.nulldata_txout(over_max_data)
        self.assertRaises(exceptions.MaxNulldataExceeded, callback)

class TestHash160DataTxOut(unittest.TestCase):

    def test_data_size(self):

        # twenty bytes ok
        max_data = 20 * b"aa"
        deserialize.hash160data_txout(max_data)

        # > twenty bytes fails
        def callback():
            over_max_data = 21 * b"aa"
            deserialize.hash160data_txout(over_max_data)
        self.assertRaises(exceptions.InvalidHash160DataSize, callback)

        # < twenty bytes fails
        def callback():
            over_max_data = 19 * b"aa"
            deserialize.hash160data_txout(over_max_data)
        self.assertRaises(exceptions.InvalidHash160DataSize, callback)

class TestKey(unittest.TestCase):

    def test_invalid_netcode(self):
        testnet_wif = "cNf7CMEHfD2jLtiTASbCAEneVnVmD4syA4A9KhUXqAkRs26Ke6xw"
        mainnet_wif = "KzU3561hXZwFPrzmHkJ6FLWvykFJMQnMEwSKXW5VPpz6HcxuvpZq"

        # test positive
        deserialize.key(True, testnet_wif)  # testnet
        deserialize.key(False, mainnet_wif)  # mainnet

        # testnet negative
        def callback():
            deserialize.key(False, testnet_wif)
        self.assertRaises(exceptions.InvalidWif, callback)

        # mainnet negative
        def callback():
            deserialize.key(True, mainnet_wif)
        self.assertRaises(exceptions.InvalidWif, callback)

        # testnet non string
        def callback():
            deserialize.key(False, None)
        self.assertRaises(exceptions.InvalidInput, callback)

        # mainnet non string
        def callback():
            deserialize.key(True, None)
        self.assertRaises(exceptions.InvalidInput, callback)

        # testnet garbage string
        def callback():
            deserialize.key(False, "garbage")
        self.assertRaises(exceptions.InvalidWif, callback)

        # mainnet garbage string
        def callback():
            deserialize.key(True, "garbage")
        self.assertRaises(exceptions.InvalidWif, callback)

class TestAddress(unittest.TestCase):

    def test_invalid_netcode(self):
        testnet_address = "mgBJ5bG9mQw8mHHcVEJghMamQEXeNLtvpt"
        mainnet_address = "1BTF7gU1EmgasGh85ypacDvsVKg4weZMfz"

        # testnet positive
        address = deserialize.address(True, testnet_address)
        self.assertEqual(testnet_address, address)

        # mainnet positive
        address = deserialize.address(False, mainnet_address)
        self.assertEqual(mainnet_address, address)

        # testnet negative
        def callback():
            deserialize.address(False, testnet_address)
        self.assertRaises(exceptions.InvalidAddress, callback)

        # mainnet negative
        def callback():
            deserialize.address(True, mainnet_address)
        self.assertRaises(exceptions.InvalidAddress, callback)

        # non string testnet
        def callback():
            deserialize.address(False, None)
        self.assertRaises(exceptions.InvalidInput, callback)

        # non string mainnet
        def callback():
            deserialize.address(True, None)
        self.assertRaises(exceptions.InvalidInput, callback)

        # garbage string testnet
        def callback():
            deserialize.address(False, "garbage")
        self.assertRaises(exceptions.InvalidAddress, callback)

        # garbage string mainnet
        def callback():
            deserialize.address(True, "garbage")
        self.assertRaises(exceptions.InvalidAddress, callback)


text:
package com.github.nethad.clustermeister.node.common;

/**
 * Launches a JPPF-Driver in a new spawned process (JVM).
 *
 * @author daniel
 */
public class ClustermeisterDriverLauncher extends ClustermeisterLauncher {

    /**
     * JPPF Class to use for launching the driver.
     */
    protected static final String DRIVER_RUNNER = "org.jppf.server.JPPFDriver";

    private final boolean useRmi;

    /**
     * Start a JPPF-driver.
     *
     * The main method will spawn a new process for the JPPF-driver.
     * If an independent process is launched it will kill this JVM as soon as it
     * obtained the UUID. Otherwise it will block until the child process dies.
     *
     * @param args
     *      The first argument "false" to launch an independent process or
     *      "true" to launch a dependent child process. If no argument is set,
     *      "true" is assumed.
     *      The second argument is "true" if RMI should be used (for local drivers) or
     *      "false" if not (default).
     *      The third argument is "true" if the UUID should be printed to stdout
     *      or "false" otherwise. If it is not set, "false" is assumed.
     */
    public static void main(String... args) {
        boolean launchAsChildProcess = getBooleanArgument(args, 0, true);
        boolean useRmi = getBooleanArgument(args, 1, false);
        boolean printUUID = getBooleanArgument(args, 2, false);
        ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(useRmi);
        launcher.setPrintUUIDtoStdOut(printUUID);
        launcher.doLaunch(launchAsChildProcess, null);
        if(!launchAsChildProcess) {
            //Exit from this JVM. The spawned process continues to run.
            System.exit(0);
        }
    }

    public ClustermeisterDriverLauncher(boolean useRmi) {
        this.useRmi = useRmi;
    }

    public ClustermeisterDriverLauncher() {
        this.useRmi = false;
    }

    @Override
    protected String getRunner() {
        return DRIVER_RUNNER;
    }

    @Override
    protected ClustermeisterProcessLauncher createProcessLauncher() {
        ClustermeisterProcessLauncher launcher = super.createProcessLauncher();
        launcher.setUseRmi(useRmi);
        return launcher;
    }

}


text:
package com.goodskill.job.simple;

import com.goodskill.api.service.GoodsService;
import com.goodskill.entity.Goods;
import com.goodskill.es.api.GoodsEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MyJob implements SimpleJob {
    @DubboReference
    private GoodsService goodsService;
    @Resource
    private GoodsEsService goodsEsService;

    @Override
    public void execute(ShardingContext context) {
        switch (context.getShardingItem()) {
            case 0:
                try {
                    log.info("分片0 商品es索引开始更新。。。");
                    List list = goodsService.list().parallelStream().map(g -> {
                        Goods goods = new Goods();
                        BeanUtils.copyProperties(g, goods);
                        return goods;
                    }).collect(Collectors.toList());
                    goodsEsService.saveBatch(list);
                    log.info("分片0 商品es索引更新成功,条数:{}", list.size());
                } catch (Exception e) {
                    log.warn("分片0 商品es索引定时任务更新失败!", e);
                }
                break;
            case 1:
                try {
                    log.info("分片1 商品es索引开始更新。。。");
                } catch (Exception e) {
                    log.warn("分片1 商品es索引定时任务更新失败!", e);
                }
                break;
            case 2:
                try {
                    log.info("分片2 商品es索引开始更新。。。");
                } catch (Exception e) {
                    log.warn("分片2 商品es索引定时任务更新失败!", e);
                }
                break;
            // case n: ...
            default:
                break;
        }
    }
}


text:
import java.io.*;
import java.util.*;

class ListNode
{
    int val;
    ListNode next;

    public ListNode(int x)
    {
	val = x;
	next = null;
    }

    public String toString()
    {
	return val+"";
    }
}

class DeleteDuplicates2
{
    public static void main(String[] args)
    {
	System.out.println("=== welcome to DeleteDuplicates ===");

	Solution solution = new Solution();

	ListNode n1 = new ListNode(1);
	ListNode n2 = new ListNode(2);
	ListNode n3 = new ListNode(2);
	ListNode n4 = new ListNode(3);
	ListNode n5 = new ListNode(3);
	ListNode n6 = new ListNode(4);

	n1.next = n2;
	n2.next = n3;
	//n3.next = n4;
	//n4.next = n5;
	//n5.next = n6;

	print_list(n1);
	System.out.println("after removing duplicates:");
	ListNode head = solution.deleteDuplicates(n1);

	print_list(head);
    }

    public static void print_list(ListNode head)
    {
	ListNode n = head;

	System.out.println(">>> print_list");
	while(n != null)
	{
	    System.out.print(n.val+", ");
	    n = n.next;
	}

	System.out.println();
    }
}

class Solution
{
    public ListNode deleteDuplicates(ListNode head)
    {
	ListNode result = null;
	ListNode tail = null;

	ListNode parent = null;

	ListNode node = head;

	while(node != null)
	{

	    if( (parent == null || parent.val != node.val) &&
		(node.next == null || node.next.val != node.val) )
	    {
		// this is a good node
		if(tail == null)
		{
		    tail = node;
		    result = node;
		}
		else
		{
		    tail.next = node;
		    tail = node;
		}
	    }

	    parent = node;
	    node = node.next;
	}

	if(tail != null)
	{
	    tail.next = null;
	}
	return result;
    }
}


text: module.exports = require('./kenobi.js');


text:
// @flow

import React from 'react';
import { Button, Typography } from '@material-ui/core';
import { FormattedMessage } from 'react-intl';

import { View, Scroller, Shimmer } from '../../elements';
import { itemStyle } from '../../elements/Shimmer';
import { spacing } from '../../style/theme';
import GameLink from './GameLink';
import BookLink from './BookLink';
import LevelHR from '../Level/LevelHR';
import BrowseLink, { type Props as BrowseLinkProps } from '../BrowseLink';
import type { Book } from './BookLink';

import type {
  GameList_games_results as Game,
  ReadingLevel
} from '../../gqlTypes';

type Props = {
  items: $ReadOnlyArray<Game | Book>,
  loading?: boolean,
  heading: typeof FormattedMessage,
  browseLinkProps?: BrowseLinkProps,
  level?: ReadingLevel | 'Games',
  shouldBeColorized?: boolean
};

// Add a wrapper around each book or game list, so we can apply padding on the last element to get our wanted "overscroll effect" on mobile
const BooksAndShimmerView = ({
  items,
  loading,
  heading,
  browseLinkProps,
  level,
  shouldBeColorized
}: Props) => (
  <div
    css={{
      visibility: `${!loading && items.length === 0 ? 'hidden' : 'visible'}`
    }}
  >
    <View
      flexDirection="row"
      alignItems="center"
      justifyContent="space-between"
      style={{
        visibility: !loading && items.length === 0 ? 'hidden' : 'visible'
      }}
    >
      <Typography component="h1" variant="h5" style={{ textAlign: 'left' }}>
        {heading}
      </Typography>
      {browseLinkProps && (
        <BrowseLink {...browseLinkProps}>
          {/* Negative margin to align the link against the edge of the container */}
          <Button
            data-cy="browse-more-button"
            color="primary"
            size="small"
            variant="outlined"
          >
            <FormattedMessage id="More" defaultMessage="More" />
          </Button>
        </BrowseLink>
      )}
    </View>

    {/* Adjust the space between items and the hr */}
    {shouldBeColorized && (
      <LevelHR level={level} css={{ marginBottom: spacing.medium }} />
    )}
    <Scroller>
      {loading
        ? [...Array(5)].map((_, index) => <Shimmer key={index} />)
        : items.slice(0, 5).map((item: any) => (
            <div className={itemStyle} key={item.id}>
              {level === 'Games' ? (
                <GameLink game={(item: Game)} />
              ) : (
                <BookLink book={(item: Book)} />
              )}
            </div>
          ))}
    </Scroller>
  </div>
);

export default BooksAndShimmerView;


text: from . rest import OpenPage, Rest


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'Diablo 3 item extraction tracker';

  constructor() {
  }

  ngOnInit() {
  }
}


text:
<?php

namespace Mduk\Gowi;

interface Transcoder {
	public function encode( $in );
	public function decode( $in );
}


text:
#ifndef __OGGLENGTH_H__
#define __OGGLENGTH_H__

#include <vorbis/vorbisfile.h>
#include <boost/shared_ptr.hpp>
#include <stdexcept>

// ogglength is reusable code.
namespace ogglength
{

// Gets the length in seconds of an Ogg Vorbis file that will be reported by most media players and utilities.
// Can throw ogglength::OggVorbisError if there is a problem opening or reading the file.
double GetReportedTime(const char* filePath);

// Gets the real length in seconds of an Ogg Vorbis file. This can differ from the reported length if the file has
// been tampered with.
// Can throw ogglength::OggVorbisError if there is a problem opening or reading the file.
double GetRealTime(const char* filePath);

// Sets the length of an Ogg Vorbis file in seconds.
// This is done by changing the granule position field of the last Ogg page.
// The file must be a normal Ogg Vorbis file (1 logical bitstream).
// ogglength::OggVorbisError can be thrown for various error conditions, including being unable to open
// the file, the file not being an Ogg Vorbis file, or the file appearing to be corrupt.
// If the function returns without throwing an exception, it succeeded.
void ChangeSongLength(const char* filePath, double numSeconds);

// Represents an error while opening or reading an Ogg Vorbis file.
class OggVorbisError : public std::runtime_error
{
public:
	OggVorbisError(const std::string& message) : std::runtime_error(message)
	{
	}
};

// Helper struct for OggVorbisFile, not intended to be used by other code.
struct _OggVorbisFile
{
	OggVorbis_File file; // Vorbis file handle
	bool opened; // Whether the file has actually been opened yet and the handle is valid

	explicit _OggVorbisFile() : file(), opened(false)
	{
	}

	~_OggVorbisFile()
	{
		// This is what we need this struct for - only call ov_clear if we succeeded in opening the file.
		if(opened)
		{
			ov_clear(&file);
		}
	}
};

// Resource-managing class for an OggVorbis_File handle from libvorbisfile.
// The underlying handle is reference counted. Copying an object of this class
// increments the reference count and both objects will have the same handle.
// The file is only closed when the last reference is done with it.
class OggVorbisFile
{
private:
	boost::shared_ptr<_OggVorbisFile> m_handle; // reference counting made easy

public:
	// Opens the given file as an Ogg Vorbis file.
	// Throws ogglength::OggVorbisError if an error occurs.
	explicit OggVorbisFile(const char* filePath);

	// Compiler-supplied copy constructor, copy assignment, and destructor are ok

	// Gets the underlying OggVorbis_File handle
	OggVorbis_File* get();
};

} // end namespace ogglength

#endif // end include guard


text:
package com.twu.biblioteca;

import java.util.ArrayList;

public class PredefinedMenuOption implements MenuOptionInterface {
    private PredefinedMenuOption parent = null;

    private String option;
    private String title;
    public String messageBeforeUserInput;
    public static final String rootMessage = "Type the number or word before the colon (:) to select an option.\n";
    public static final String quitOption = "Quit";
    public static final String quitTitle = "Quit: Exit Biblioteca.";
    public static final String backOption = "Back";
    public static final String backTitle = "Back: Go back to previous menu.";

    public String getOption(){return option;}
    public String getTitle(){return title;}
    public String getMessageBeforeUserInput(){return messageBeforeUserInput;}
    public void setMessageBeforeUserInput(String newMessage){
        messageBeforeUserInput = newMessage;}

    public PredefinedMenuOption getParent(){return parent;}

    public static String invalidOptionMessage = "Select a valid option!";

    public ArrayList<MenuOptionInterface> generateOptions(BibliotecaItemShelf shelf, BibliotecaItem item, String userLogin) {
        ArrayList<MenuOptionInterface> childOptions = new ArrayList<MenuOptionInterface>();
        childOptions.add(new ListItemsMenuOption(ListItemsMenuOption.typeBooksToCheckout));
        childOptions.add(new ListItemsMenuOption(ListItemsMenuOption.typeBooksToReturn));
        childOptions.add(new ListItemsMenuOption(ListItemsMenuOption.typeMoviesToCheckout));
        childOptions.add(new ListItemsMenuOption(ListItemsMenuOption.typeMoviesToReturn));
        childOptions.add(createQuitOption());
        return childOptions;
    }

    public String printOptions(ArrayList<? extends MenuOptionInterface> options) {
        String textToReturn = PredefinedMenuOption.rootMessage;
        for (int i = 0; i < options.size(); i++) {
            if (i != 0) textToReturn += "\n";
            textToReturn += options.get(i).getTitle();
        }
        return textToReturn;
    }

    public MenuOptionInterface getOptionByUserInput(String userInput, ArrayList<? extends MenuOptionInterface> options) {
        for (int i = 0; i < options.size(); i++) {
            MenuOptionInterface option = options.get(i);
            if (userInput.toLowerCase().equals(option.getOption().toLowerCase()))
                return option;
        }
        if (!messageBeforeUserInput.contains(invalidOptionMessage))
            messageBeforeUserInput = invalidOptionMessage + "\n" + rootMessage;
        return this;
    }

    public PredefinedMenuOption(String option, String title, String messageBeforeUserInput) {
        this.option = option;
        this.title = title;
        this.messageBeforeUserInput = messageBeforeUserInput;
    }

    public PredefinedMenuOption() {
        messageBeforeUserInput = rootMessage;
    }

    public static PredefinedMenuOption createQuitOption() {
        return new PredefinedMenuOption(quitOption, quitTitle, null);
    }

    public static PredefinedMenuOption createBackOption() {
        return new PredefinedMenuOption(backOption, backTitle, null);
    }

}


text:
import * as tl from 'azure-pipelines-task-lib/task';
import * as webapim from 'vso-node-api/WebApi';
import * as models from './models';

export class TestAgent {
    public static async createAgent(environment: models.DtaEnvironment, retries: number) {
        var currentRetryCount = retries;
        while(currentRetryCount > 0) {
            currentRetryCount--;
            try {
                const envUrlRef: any = { Url: environment.environmentUri };
                const machineNameRef: any = { Name: environment.agentName };
                // TODO : Change any to appropriate types once promiseme package is avialable
                const testAgent: any = {
                                    Name: environment.agentName,
                                    Capabilities: [],
                                    DtlEnvironment: envUrlRef,
                                    DtlMachine: machineNameRef };
                const webapi: any = new webapim.WebApi(environment.tfsCollectionUrl, webapim.getBearerHandler(environment.patToken));
                const testApi: any = webapi.getTestApi();
                const registeredAgent = await testApi.createAgent(testAgent);
                tl.debug('created the test agent entry in DTA service, id : ' + registeredAgent.id);
                return registeredAgent.id;
            } catch (error) {
                tl.error('Error : created the test agent entry in DTA service, so retrying => retries pending  : ' + currentRetryCount
                        + 'error details :' + error);
                if(currentRetryCount === 0) {
                    throw new Error(tl.loc("configureDtaAgentFailed", retries, error));
                }
            }
        }
    }
}


text:
require "helper"

require "gapic/grpc/service_stub"

require "google/area120/tables/v1alpha1/tables_service"

class ::Google::Area120::Tables::V1alpha1::TablesService::ClientPathsTest < Minitest::Test
  def test_row_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Area120::Tables::V1alpha1::TablesService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.row_path table: "value0", row: "value1"
      assert_equal "tables/value0/rows/value1", path
    end
  end

  def test_table_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Area120::Tables::V1alpha1::TablesService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.table_path table: "value0"
      assert_equal "tables/value0", path
    end
  end

  def test_workspace_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Area120::Tables::V1alpha1::TablesService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.workspace_path workspace: "value0"
      assert_equal "workspaces/value0", path
    end
  end
end


text:
.. _data:

Data Loading
============

Configuration data is loaded from python modules named after the selected
:term:`environment`, :term:`role`, :term:`component`, and :term:`host`, plus a
standard set of defaults. For example, if Confab is operating on an environment
named ``foo``, a role named ``bar``, a component named ``baz``, and a host
named ``host``, configuration data would be loaded from ``foo.py``, ``bar.py``,
``baz.py``, ``host.py``, and ``default.py``.

If a configuration data module is not found, Confab will also look for a file
with a ``.py_tmpl`` suffix and treat it as a Jinja2 template for the same
module, allowing configuration data to use Jinja2 template syntax (including
:class:`include<jinja2.nodes.Include>`).

Confab uses the ``__dict__`` property of the loaded module to generate
dictionaries, filtering out any entries starting with ``_``. In other words,
this module::

    foo = 'bar'
    _ignore = 'this'

results in this dictionary::

    {'foo': 'bar'}

The dictionaries from all of the loaded modules (if any) are recursively merged
into a single dictionary, which is then used to populate :ref:`templates`.
Merging operates in the following order:

1.  Host-specific values are used first.
2.  Environment-specific values are used next.
3.  Role or component-specific values are used next.
4.  Default values are used last.

Confab's recursive merge operation can be futher customized by using callable
wrappers around configuration values. Confab will always delegate to a callable
to define how values are overriden, e.g. allowing lists values to be
appended/prepended to default values.

Data Hooks
==========

DataLoader supports adding callbacks by scope in order to load additional data.
Hooks are added and removed via::

    from confab.api import Hook, add_data_hook, remove_data_hook

    hook = Hook(hook_func)
    hooks.add_data_hook(scope, hook)
    hooks.remove_data_hook(scope, hook)

Hooks can also be used via a ContextManager ``ScopeAndHooks`` which accepts an
arbitrary number of hooks and loads them appropriately in context.::

    with ScopeAndHooks((scope, Hook(hook_func))):
        dostuff()

Hooks will be loaded after file data for each scope, but before the file data from
the next scope.


text:
<!DOCTYPE html>

    <title></title>

        <form method="post" action="{{ url_for('sign_up') }}">
            <input type="text" name="username" placeholder="Username">

            <input type="text" name="password" placeholder="Password">

            <button type="submit">Sign up for Vocab</button>
        </form>


text:
\begin{abstract}

Need to write

\end{abstract}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/pubsub/v1/pubsub.proto

package com.google.pubsub.v1;

public interface ListSubscriptionsRequestOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.pubsub.v1.ListSubscriptionsRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The name of the cloud project that subscriptions belong to.
   * Format is `projects/{project}`.
   *

   *
   * string project = 1;
   */
  java.lang.String getProject();
  /**
   *

   * The name of the cloud project that subscriptions belong to.
   * Format is `projects/{project}`.
   *

   *
   * string project = 1;
   */
  com.google.protobuf.ByteString
      getProjectBytes();

  /**
   *

   * Maximum number of subscriptions to return.
   *

   *
   * int32 page_size = 2;
   */
  int getPageSize();

  /**
   *

   * The value returned by the last `ListSubscriptionsResponse`; indicates that
   * this is a continuation of a prior `ListSubscriptions` call, and that the
   * system should return the next page of data.
   *

   *
   * string page_token = 3;
   */
  java.lang.String getPageToken();
  /**
   *

   * The value returned by the last `ListSubscriptionsResponse`; indicates that
   * this is a continuation of a prior `ListSubscriptions` call, and that the
   * system should return the next page of data.
   *

   *
   * string page_token = 3;
   */
  com.google.protobuf.ByteString
      getPageTokenBytes();
}


text:
from aladdin_product import get_product

if __name__ == '__main__':
    get_product('clkx', {'keyword': 'clkx'})


text:
class Pathname
  if OS.mac?
    require "os/mac/mach"
    include MachOShim
  elsif OS.linux?
    require "os/linux/elf"
    include ELF
  end
end


text:
using UnityEngine;
using System.Collections;

public class Knapspack : MonoBehaviour {

    public static Knapspack _instance;

    private EquipPopup equip;
    private InventoryPopup inventoryPopup;
    private UILabel priceLabel;
    private UIButton sellBtn;
    private UIButton closeBtn;
    private TweenPosition knapspackTween;
    private InventoryItemUI itUI;
    void Awake()
    {
        equip = transform.Find("EquipPanel/EquipPopup").GetComponent<EquipPopup>();
        inventoryPopup = transform.Find("InventoryPanel/inventoryPopup").GetComponent<InventoryPopup>();

        priceLabel = transform.Find("Inventory/PriceBg/Label").GetComponent<UILabel>();
        sellBtn = transform.Find("Inventory/SellButton").GetComponent<UIButton>();
        closeBtn = transform.Find("CloseButton").GetComponent<UIButton>();
        knapspackTween = this.GetComponent<TweenPosition>();

        //注册点击事件
        EventDelegate ed1 = new EventDelegate(this, "On_knapSpack_Close_Click");
        closeBtn.onClick.Add(ed1);
        EventDelegate ed3 = new EventDelegate(this, "On_knapspack_sell_Click");
        sellBtn.onClick.Add(ed3);

        DisenableButton();

    }

    //接受点击每个小格子传来消息
    public void OnInventoryClick(object[] objectArray)
    {
        InventoryItem it = objectArray[0] as InventoryItem;
        InventoryItemUI itUI =null;
        KnapspackRoleEquip kre = null;
        bool isLeft=false;
        if(it.Inventory.InventoryTYPE==InventoryType.Equip)
        {
           isLeft= (bool)objectArray[1];
            if(isLeft)
            {
                itUI = objectArray[2] as InventoryItemUI;
            }
            else
            {
                kre = objectArray[2] as KnapspackRoleEquip;
            }
            equip.Show(it,itUI,isLeft);
        }
        else
        {
            itUI = objectArray[2] as InventoryItemUI;
            inventoryPopup.Show(it,itUI);
        }
        if((it.Inventory.InventoryTYPE==InventoryType.Equip&&isLeft)||it.Inventory.InventoryTYPE!=InventoryType.Equip)
        {
            this.itUI = objectArray[2] as InventoryItemUI;
            EnableButton(itUI.it.Inventory.Price*itUI.it.Count);
        }
    }
    public void Show()
    {
        knapspackTween.gameObject.SetActive(true);
        knapspackTween.PlayReverse();
    }
    void DisenableButton()
    {
        sellBtn.isEnabled = false;
        priceLabel.text = "";
    }
    void EnableButton(int price)
    {
        sellBtn.isEnabled = true;
        priceLabel.text =price.ToString();
    }
    void On_knapspack_sell_Click()
    {
        //角色所拥有的金钱数量增加
        playerInfo._instance.AddCoin(itUI.it.Inventory.Price);
        //点击出售减少该物品,从内存中清楚该物品
        InventoryManager._instance.inventoryItemList.Remove(itUI.it);
        itUI.Clear();
        equip.gameObject.SetActive(false);
        inventoryPopup.gameObject.SetActive(false);
        //数量的更新
        InventoryUI._instance.SendMessage("UpdateCount");
        DisenableButton();
    }
    void On_knapSpack_Close_Click()
    {
        knapspackTween.PlayForward();
        StartCoroutine(HidePanel(knapspackTween.gameObject));
    }
    IEnumerator HidePanel(GameObject go)
    {
        yield return new WaitForSeconds(0.4f);
        go.SetActive(false);
    }
}


text:
id: 982
title: Developer Guide Released
date: 2013-02-22T19:59:43+00:00
author: Michael Hrivnak
layout: post
guid: http://www.pulpproject.org/?p=982
permalink: /2013/02/22/developer-guide-released/
categories:
  - Releases
---
Today we are happy to present the official and mostly-new Pulp Developer Guide, available from our [documentation page](/docs/). The most notable addition is a detailed guide on how to add support for new content types, including examples. The Developer Guide also includes sections on Pulp's architecture, how to integrate with Pulp, as well as the policies and conventions used by the Pulp Team.

This release is a continuation of the Pulp Team's commitment to providing documentation that is comprehensive, accurate, and above-all: useful. Please have a look, and as always, your feedback is valued and appreciated.


text:
.. _contents:

Table of contents
=================

.. toctree::
   :maxdepth: 4
   :numbered:

   develop
   user
   devops
   buildsystem
   infra/jenkins_master_deployment
   infra/jenkins_slave_deployment
   infra/overview
   infra/puppet_master_deployment
   infra/seed_server_deployment
   infra/third_party
   infra/zabbix_server_deployment
   packaging


text:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version = "3.2"
         xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd">
    <enterprise-beans>
        <session>
            <ejb-name>ExternalRoutingService</ejb-name>
            <env-entry>
                <env-entry-name>graphTraversalUrl</env-entry-name>
                <env-entry-type>java.lang.String</env-entry-type>
                <env-entry-value>http://localhost:8080/cargo-tracker/rest/graph-traversal/shortest-path</env-entry-value>
            </env-entry>
        </session>
        <message-driven>
            <ejb-name>MisdirectedCargoConsumer</ejb-name>
            <ejb-class>net.java.cargotracker.infrastructure.messaging.jms.SimpleLoggingConsumer</ejb-class>
            <messaging-type>javax.jms.MessageListener</messaging-type>
            <message-destination-type>javax.jms.Queue</message-destination-type>
            <activation-config>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationType
                    </activation-config-property-name>
                    <activation-config-property-value>
                        javax.jms.Queue
                    </activation-config-property-value>
                </activation-config-property>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationLookup
                    </activation-config-property-name>
                    <activation-config-property-value>
                        java:global/jms/MisdirectedCargoQueue
                    </activation-config-property-value>
                </activation-config-property>
            </activation-config>
        </message-driven>
        <message-driven>
            <ejb-name>DeliveredCargoConsumer</ejb-name>
            <ejb-class>net.java.cargotracker.infrastructure.messaging.jms.SimpleLoggingConsumer</ejb-class>
            <messaging-type>javax.jms.MessageListener</messaging-type>
            <message-destination-type>javax.jms.Queue</message-destination-type>
            <activation-config>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationType
                    </activation-config-property-name>
                    <activation-config-property-value>
                        javax.jms.Queue
                    </activation-config-property-value>
                </activation-config-property>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationLookup
                    </activation-config-property-name>
                    <activation-config-property-value>
                        java:global/jms/DeliveredCargoQueue
                    </activation-config-property-value>
                </activation-config-property>
            </activation-config>
        </message-driven>
        <message-driven>
            <ejb-name>RejectedRegistrationAttemptsConsumer</ejb-name>
            <ejb-class>net.java.cargotracker.infrastructure.messaging.jms.SimpleLoggingConsumer</ejb-class>
            <messaging-type>javax.jms.MessageListener</messaging-type>
            <message-destination-type>javax.jms.Queue</message-destination-type>
            <activation-config>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationType
                    </activation-config-property-name>
                    <activation-config-property-value>
                        javax.jms.Queue
                    </activation-config-property-value>
                </activation-config-property>
                <activation-config-property>
                    <activation-config-property-name>
                        destinationLookup
                    </activation-config-property-name>
                    <activation-config-property-value>
                        java:global/jms/RejectedRegistrationAttemptsQueue
                    </activation-config-property-value>
                </activation-config-property>
            </activation-config>
        </message-driven>
    </enterprise-beans>
</ejb-jar>


text:
<form class="form-horizontal">

		Name

			<input type="text" class="form-control" ng-model="project.Name" id="inputName" placeholder="Project Name">

		Desc

			<input type="text" ng-model="project.Desc" class="form-control" id="inputDesc" placeholder="Desc">

			<button ng-click="create()" type="submit" class="btn btn-primary">Add</button>

</form>


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

{% block title %}Password Reset{% endblock %}

{% block content %}

Password Reset

  <form action="{% url 'password_reset' %}" method="post" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
      <button type="submit" class="btn btn-primary">Reset password</button>
    {% endbuttons %}
  </form>

{% endblock %}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.async;

import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;

import javax.inject.Inject;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import org.apache.aurora.common.quantity.Amount;
import org.apache.aurora.common.quantity.Time;

import static java.util.Objects.requireNonNull;

/**
 * An executor that queues work until flushed.
 */
class GatedDelayExecutor implements DelayExecutor, FlushableWorkQueue {

  private final ScheduledExecutorService executor;
  private final Queue<Runnable> queue = Lists.newLinkedList();

  /**
   * Creates a gated delay executor that will flush work to the provided {@code delegate}.
   *
   * @param delegate Delegate to execute work with when flushed.
   */
  @Inject
  GatedDelayExecutor(ScheduledExecutorService delegate) {
    this.executor = requireNonNull(delegate);
  }

  synchronized int getQueueSize() {
    return queue.size();
  }

  private synchronized void enqueue(Runnable work) {
    queue.add(work);
  }

  @Override
  public synchronized void flush() {
    for (Runnable work : Iterables.consumingIterable(queue)) {
      work.run();
    }
  }

  @Override
  public synchronized void execute(Runnable command) {
    enqueue(() -> executor.execute(command));
  }

  @Override
  public synchronized void execute(Runnable work, Amount<Long, Time> minDelay) {
    enqueue(() -> executor.schedule(work, minDelay.getValue(), minDelay.getUnit().getTimeUnit()));
  }
}


text:
class SessionsController < ApplicationController

  skip_load_and_authorize_resource

  def new
  end

  def create
    if params[:session][:email].blank? || params[:session][:password].blank?
      flash.now[:error] = "You must provide an email address and password."
      render 'new'
    else
      contact = Contact.find_by_email(params[:session][:email].downcase)
      if contact.nil?
        flash.now[:error] = "Sorry. We couldn't find a user with that email address."
        render 'new'
      else
        account = contact.contactable.account
        if account && account.authenticate(params[:session][:password])
          sign_in account
          redirect_back_or account.user
        else
          flash.now[:error] = "Invalid email/password combination"
          render 'new'
        end
      end
    end
  end

  def destroy
    sign_out
    redirect_to root_url
  end

end


text:
O Projeto #ajogada é bem mais do que uma metodologia de gamificação. O Projeto é uma rede de pessoas colaborando em iniciativas criativas diversas tendo como princípio a visão de jogos desenvolvida pela metodologia A Jogada.

### O Jogo do Projeto

![](img/Board_site-ajogada.png)

(inserir link para o svg)

### Roadmap


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Arke.DependencyInjection;
using Arke.DSL.Step;
using Arke.SipEngine.CallObjects;
using Arke.SipEngine.Processors;

namespace Arke.IVR.DSL
{
    public class DslProcessor
    {
        public Dictionary<int,Step> Dsl { get; set; }
        private readonly ICall _call;

        public DslProcessor(ICall call)
        {
            _call = call;
            Dsl = new Dictionary<int, Step>();
        }

        public async Task ProcessStepAsync(int stepIndex)
        {
            if (!Dsl.ContainsKey(stepIndex))
                throw new ArgumentOutOfRangeException(nameof(stepIndex), "Step Index does not exist");
            var step = Dsl.Single(i => i.Key == stepIndex).Value;

            var stepName = step.NodeData.Category + "Processor";
            var stepType = AppDomain.CurrentDomain.GetAssemblies()
                // Xunit assemblies cause issues during unit tests, so omit from assembly search.
                // and apparently datadog serialization is causing issues on load too so leave those out.
                .Where(assembly => !assembly.FullName.Contains("xunit")
                && !assembly.FullName.Contains("MsgPack.Serialization"))
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => typeof(IStepProcessor).IsAssignableFrom(type))
                .Single(type => type.Name == stepName);

            var stepProcessor = ObjectContainer.GetInstance().GetObjectInstance(stepType);
            _call.Logger.Debug($"{_call.CallId}: Processing Step: {stepType.FullName}");
#pragma warning disable CS4014 // We do not want to wait to continue execution here.
            Task.Run(() => ((IStepProcessor) stepProcessor).DoStepAsync(step, _call));
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }
    }
}