text:
package com.bq.corbel.resources.rem.operation;

import com.bq.corbel.resources.rem.exception.ImageOperationsException;
import org.im4java.core.IMOps;
import org.junit.Test;

import java.util.Collections;
import java.util.List;

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

public class ImageOperationsTest {

    @Test
    public void cropTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(10, 20, 30, 40)");
        List<String> expectedOutputs = Collections.singletonList("[-crop, 20x20+10+20]");

        operationTest(inputParameters, expectedOutputs, new Crop());
    }

    @Test
    public void cropFromCenterTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(10, 20)");
        List<String> expectedOutputs = Collections.singletonList("[-gravity, center, -crop, 10x20+0+0]");

        operationTest(inputParameters, expectedOutputs, new CropFromCenter());
    }

    @Test
    public void resizeTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(10, 20)");
        List<String> expectedOutputs = Collections.singletonList("[-resize, 10x20>!]");

        operationTest(inputParameters, expectedOutputs, new Resize());
    }

    @Test
    public void blurTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(0, 8)");
        List<String> expectedOutputs = Collections.singletonList("[-blur, 0.0x8.0]");

        operationTest(inputParameters, expectedOutputs, new Blur());
    }

    @Test
    public void blurTestDecimals() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(0.5, 8.4)");
        List<String> expectedOutputs = Collections.singletonList("[-blur, 0.5x8.4]");

        operationTest(inputParameters, expectedOutputs, new Blur());
    }

    @Test
    public void resizeAndFillTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("(10, FF7300)");
        List<String> expectedOutputs = Collections.singletonList("[-resize, 10x10, -background, #FF7300, -gravity, center, -extent, 10x10]");

        operationTest(inputParameters, expectedOutputs, new ResizeAndFill());
    }

    @Test
    public void resizeHeightTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("10");
        List<String> expectedOutputs = Collections.singletonList("[-resize, x10>]");

        operationTest(inputParameters, expectedOutputs, new ResizeHeight());
    }

    @Test
    public void resizeWidthTest() throws ImageOperationsException {
        List<String> inputParameters = Collections.singletonList("10");
        List<String> expectedOutputs = Collections.singletonList("[-resize, 10x-1>]");

        operationTest(inputParameters, expectedOutputs, new ResizeWidth());
    }

    private void operationTest(List<String> inputParameters, List<String> expectedOutputs, ImageOperation operation)
            throws ImageOperationsException {
        assertThat(inputParameters.size()).isEqualTo(expectedOutputs.size());

        for (int i = 0; i < inputParameters.size(); ++i) {
            IMOps imOps = operation.apply(inputParameters.get(i));
            assertThat(imOps.getCmdArgs().toString()).isEqualTo(expectedOutputs.get(i));
        }
    }

}


text:
---
layout: jsdoc
title: "Source: packages/workbox-build/src/lib/inject-manifest.js"
jsdocNav:
  - Modules:
    - workbox-background-sync
    - workbox-broadcast-cache-update
    - workbox-build
    - workbox-cache-expiration
    - workbox-cacheable-response
    - workbox-google-analytics
    - workbox-precaching
    - workbox-range-requests
    - workbox-routing
    - workbox-runtime-caching
    - workbox-sw
    - workbox-webpack-plugin
---

'use strict';

const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');

const getFileManifestEntries = require('./get-file-manifest-entries');
const errors = require('./errors');

/**
 * This method will read an existing service worker file, find an instance of
 * `.precache([])`, and replace the empty array with the contents of a precache
 * manifest. This allows the service worker to efficiently cache assets for
 * offline use, while still giving you control over the rest of the service
 * worker's code.
 *
 * @param {module:workbox-build.Configuration} input
 * @return {Promise} Resolves once the service worker has been written
 * with the injected precache list.
 *
 * @example <caption>Takes an existing service worker file that includes
 * a <code>precache([])</code> placeholder, and injects a manifest of discovered
 * assets into it.</caption>
 * const workboxBuild = require('workbox-build');
 *
 * workboxBuild.injectManifest({
 *   swSrc: './dev/sw.js',
 *   swDest: './dist/sw.js',
 *   globDirectory: './dist/',
 *   globPatterns: ['**\/*.{html,js,css}'],
 *   globIgnores: ['admin.html'],
 *   templatedUrls: {
 *     '/shell': ['dev/templates/app-shell.hbs', 'dev/**\/*.css'],
 *   },
 * })
 * .then(() => {
 *   console.log('Service worker generated.');
 * });
 *
 * @memberof module:workbox-build
 */
const injectManifest = (input) => {
  if (!input || typeof input !== 'object' || Array.isArray(input)) {
    return Promise.reject(
      new Error(errors['invalid-inject-manifest-arg']));
  }

  const injectionPointRegex = /(\.precache\()\s*\[\s*\]\s*(\))/g;

  return getFileManifestEntries(input)
  .then((manifestEntries) => {
    let swFileContents = fs.readFileSync(input.swSrc, 'utf8');
    const injectionResults = swFileContents.match(injectionPointRegex);
    if (!injectionResults) {
      throw new Error(errors['injection-point-not-found']);
    }

    if (injectionResults.length > 1) {
      throw new Error(errors['multiple-injection-points-found']);
    }

    const entriesString = JSON.stringify(manifestEntries, null, 2);
    swFileContents = swFileContents
      .replace(injectionPointRegex, `$1${entriesString}$2`);

    return new Promise((resolve, reject) => {
      mkdirp(path.dirname(input.swDest), (err) => {
        if (err) {
          return reject(
            new Error(
              errors['unable-to-make-injection-directory'] +
              ` '${err.message}'`
            )
          );
        }
        resolve();
      });
    })
    .then(() => {
      fs.writeFileSync(input.swDest, swFileContents);
    });
  });
};

module.exports = injectManifest;

redpajama_set_name: RedPajamaGithub


text:
..  BSD LICENSE
    Copyright 2015 - 2016 CESNET
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.
    * Neither the name of CESNET nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

SZEDATA2 poll mode driver library
=================================

The SZEDATA2 poll mode driver library implements support for cards from COMBO
family (**COMBO-80G**, **COMBO-100G**).
The SZEDATA2 PMD uses interface provided by libsze2 library to communicate
with COMBO cards over sze2 layer.

More information about family of
`COMBO cards <https://www.liberouter.org/technologies/cards/>`_
and used technology
(`NetCOPE platform <https://www.liberouter.org/technologies/netcope/>`_) can be
found on the `Liberouter website <https://www.liberouter.org/>`_.

.. note::

   This driver has external dependencies.
   Therefore it is disabled in default configuration files.
   It can be enabled by setting ``CONFIG_RTE_LIBRTE_PMD_SZEDATA2=y``
   and recompiling.

.. note::

   Currently the driver is supported only on x86_64 architectures.
   Only x86_64 versions of the external libraries are provided.

Prerequisites
-------------

This PMD requires kernel modules which are responsible for initialization and
allocation of resources needed for sze2 layer function.
Communication between PMD and kernel modules is mediated by libsze2 library.
These kernel modules and library are not part of DPDK and must be installed
separately:

*  **libsze2 library**

   The library provides API for initialization of sze2 transfers, receiving and
   transmitting data segments.

*  **Kernel modules**

   * combov3
   * szedata2_cv3

   Kernel modules manage initialization of hardware, allocation and
   sharing of resources for user space applications.

Information about getting the dependencies can be found `here
<https://www.liberouter.org/technologies/netcope/access-to-libsze2-library/>`_.

Configuration
-------------

These configuration options can be modified before compilation in the
``.config`` file:

*  ``CONFIG_RTE_LIBRTE_PMD_SZEDATA2`` default value: **n**

   Value **y** enables compilation of szedata2 PMD.

*  ``CONFIG_RTE_LIBRTE_PMD_SZEDATA2_AS`` default value: **0**

   This option defines type of firmware address space.
   Currently supported value is:

   * **0** for firmwares:

      * NIC_100G1_LR4
      * HANIC_100G1_LR4
      * HANIC_100G1_SR10

Using the SZEDATA2 PMD
----------------------

From DPDK version 16.04 the type of SZEDATA2 PMD is changed to PMD_PDEV.
SZEDATA2 device is automatically recognized during EAL initialization.
No special command line options are needed.

Kernel modules have to be loaded before running the DPDK application.

Example of usage
----------------

Read packets from 0. and 1. receive channel and write them to 0. and 1.
transmit channel:

.. code-block:: console

   $RTE_TARGET/app/testpmd -c 0xf -n 2 \
   -- --port-topology=chained --rxq=2 --txq=2 --nb-cores=2 -i -a

Example output:

.. code-block:: console

   [...]
   EAL: PCI device 0000:06:00.0 on NUMA socket -1
   EAL:   probe driver: 1b26:c1c1 rte_szedata2_pmd
   PMD: Initializing szedata2 device (0000:06:00.0)
   PMD: SZEDATA2 path: /dev/szedataII0
   PMD: Available DMA channels RX: 8 TX: 8
   PMD: resource0 phys_addr = 0xe8000000 len = 134217728 virt addr = 7f48f8000000
   PMD: szedata2 device (0000:06:00.0) successfully initialized
   Interactive-mode selected
   Auto-start selected
   Configuring Port 0 (socket 0)
   Port 0: 00:11:17:00:00:00
   Checking link statuses...
   Port 0 Link Up - speed 10000 Mbps - full-duplex
   Done
   Start automatic packet forwarding
     io packet forwarding - CRC stripping disabled - packets/burst=32
     nb forwarding cores=2 - nb forwarding ports=1
     RX queues=2 - RX desc=128 - RX free threshold=0
     RX threshold registers: pthresh=0 hthresh=0 wthresh=0
     TX queues=2 - TX desc=512 - TX free threshold=0
     TX threshold registers: pthresh=0 hthresh=0 wthresh=0
     TX RS bit threshold=0 - TXQ flags=0x0
   testpmd>


text:
#include <PacketTime.hpp>

namespace blockmon{

/**
         * Returns the current value of the packet clock
         * @return the packet clock value
         */
       ustime_t PacketTime::get_time()
       {
           return m_packet_time.load(std::memory_order_relaxed);
       }

       /**
         * Notifies the class that a time source has been registered.
         * This should not be called directly, as it is done by the
         * constructor of PacketTimeWriter
        */
       void PacketTime::register_time_writer()
       {
           m_writers++;
       }

       /**
         * Updates the value of the packet time.
         * If the new value is smaller than the previous one, an exception is thrown.
         * If there are several potential writers, an atomic exchange is used to make this operation thread safe.
         * @param next_time the new packet time value
         */
       void PacketTime::time_past(ustime_t target_time)
       {
           ustime_t next_time=get_BM_time();
           if(next_time==0)    // first time call
               next_time=target_time;

           ustime_t last_time;

           /* we increase the packet time in 1ms order (same resolution as wall timer)*/
           do {
               next_time = std::min(next_time+1000, target_time);

               if(m_writers > 1)
               {
                   last_time = m_packet_time.exchange(next_time, std::memory_order_relaxed);
               }
               else if(m_writers == 1)
               {
                   last_time = m_packet_time.load( std::memory_order_relaxed);
                   m_packet_time.store(next_time, std::memory_order_relaxed);
               }
               else
               {
                   throw std::runtime_error("inconsistent number of packet time writers");
               }

               if( last_time > next_time){
                   throw std::runtime_error("packet time value out of order");
               }

               /* we must check for timer events now. Otherwise it might be that this packet
                * (which might be quite a bit in the future) is processed before long past
                * timer events are processed.
                */

               TimerThread::instance().process_timer_events();
           }while(next_time<target_time);

       }

       void PacketTimeWriter::advance_packet_time(ustime_t next_time)
       {
           PacketTime::instance().time_past(next_time);
       }

}


text:
<!doctype html>

    <title>Code coverage report for documentation/streams/output/markdown.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../prettify.css">
    <link rel="stylesheet" href="../../../base.css">

Code coverage report for documentation/streams/output/markdown.js

        Statements: 59.52% (25 / 42)
        Branches: 20% (4 / 20)
        Functions: 50% (6 / 12)
        Lines: 62.5% (25 / 40)
        Ignored: none

All files » documentation/streams/output/ » markdown.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

1

1
18
18

18
20
19

1

18

1

1

1

22

22

1
5
5
5

22

22
5

22
18

22
14

'use strict';

var through = require('through'),
  fs = require('fs'),
  path = require('path'),
  Handlebars = require('handlebars'),
  extend = require('extend'),
  inlineLex = require('jsdoc-inline-lex');

/**
 * Format link & tutorial tags with simple code inline tags.
 *
 * @param {string} text input - typically a description
 * @returns {string} markdown-friendly output
 * @private
 * @example
 * formatInlineTags('{@link Foo}'); // "`Foo`"
 */
function formatInlineTags(text) {
  var output = '';
  var tokens = inlineLex(text);

  for (var i = 0; i < tokens.length; i++) {
    if (tokens[i].type === 'text') {
      output += tokens[i].capture[0];
    } else {
      output += '`' + tokens[i].capture[1] + '`';
    }
  }

  return output;
}

/**
 * Format a parameter name. This is used in formatParameters
 * and just needs to be careful about differentiating optional
 * parameters
 *
 * @param {Object} param
 * @returns {String} formatted parameter representation.
 */
function formatParameter(param) {
  return (param.type && param.type.type === 'OptionalType') ?
    '[' + param.name + ']' : param.name;
}

/**
 * Format the parameters of a function into a quickly-readable
 * summary that resembles how you would call the function
 * initially.
 */
function formatParameters() {
  if (!this.params) return '';
  return '(' + this.params.map(function (param) {
    return formatParameter(param);
  }).join(', ') + ')';
}

/**
 * Create a transform stream that formats documentation as Markdown.
 * Receives parsed & pivoted stream of documentation data, and emits
 * strings of Markdown content.
 *
 * @param {Object} opts Options that can customize the output
 * @param {String} [opts.template='../../share/markdown.hbs'] Path to a Handlebars template file that
 * takes the place of the default.
 * @name markdown
 * @return {stream.Transform}
 */
module.exports = function (opts) {

  var options = extend({}, {
    template: path.resolve(path.join(__dirname, '../../share/markdown.hbs'))
  }, opts);

  var template = Handlebars
    .compile(
      fs.readFileSync(options.template, 'utf8'));

  function formatType(type) {
    Iif (!type) return '';
    Eif (type.type === 'NameExpression') {
      return type.name;
    } else if (type.type === 'UnionType') {
      return type.elements.map(function (element) {
        return formatType(element);
      }).join(' or ');
    } else if (type.type === 'AllLiteral') {
      return 'Any';
    } else if (type.type === 'OptionalType') {
      return '[' + formatType(type.expression) + ']';
    } else if (type.type === 'TypeApplication') {
      return formatType(type.expression) + '<' +
        type.applications.map(function (application) {
          return formatType(application);
        }).join(', ') + '>';
    }
  }

  Handlebars.registerHelper('format_params', function(params) {
    return new Handlebars.SafeString(formatParameters(params));
  });

  Handlebars.registerHelper('format_type', function (type) {
    return new Handlebars.SafeString('`' + formatType(type) + '`');
  });

  Handlebars.registerHelper('inlines', function (string) {
    return new Handlebars.SafeString(formatInlineTags(string));
  });

  return through(function (comment) {
    this.push(template(comment));
  });
};

Generated by istanbul at Fri Apr 17 2015 19:18:45 GMT-0400 (EDT)


text:
using System;
using Elastic.Clients.Elasticsearch;

namespace Tests.Core.Serialization
{
	public static class SerializationTestHelper
	{
		public static JsonRoundTripper Expect(object expected, bool preserveNullInExpected = false) =>
			new(expected, preserveNullInExpected: preserveNullInExpected);

		public static ObjectRoundTripper<T> Object<T>(T expected) => new(expected);

		public static IntermediateChangedSettings WithConnectionSettings(Func<ElasticsearchClientSettings, ElasticsearchClientSettings> settings) =>
			new(settings);

		public static IntermediateChangedSettings WithSourceSerializer(ElasticsearchClientSettings.SourceSerializerFactory factory) =>
			new IntermediateChangedSettings(s => s.EnableDebugMode()).WithSourceSerializer(factory);
	}
}


text:
require 'spec_helper'

describe Wpcc::MinimumContributionCalculator, type: :model do
  subject do
    described_class.new(salary_per_year, contribution_preference)
  end

  let(:contribution_preference) { 'minimum' }
  let(:salary_per_year) { 10_000 }

  describe '#eligible_salary' do
    context 'yearly salary greater than Upper Earnings Threshold' do
      let(:salary_per_year) { 51_000 }

      it 'returns the upper threshold minus the lower threshold' do
        expect(subject.eligible_salary).to eq(44_030)
      end
    end
    context 'yearly salary less than or equal to Upper Earnings Threshold' do
      let(:salary_per_year) { 45_000 }

      it 'returns yearly salary minus the lower threshold' do
        expect(subject.eligible_salary).to eq(38_760)
      end
    end
  end

  describe '#employee_percent' do
    it 'returns 5' do
      expect(subject.employee_percent).to eq(5)
    end
  end

  describe '#employer_percent' do
    it 'returns 3' do
      expect(subject.employer_percent).to eq(3)
    end
  end
end


text:
<?php

class TagsList extends CWidget {
	public $Tags = array();
	public $delimiter = ', ';

	public function run() {
		$first = true;
		foreach($this->Tags as $tag){
			if ($first) $first = false; else echo $this->delimiter;
			echo CHtml::link($tag->name,array('/tags/view','id'=>$tag->ID));
		}
        /*
        foreach($this->Tags as $tag){
            echo ''.CHtml::link($tag->name,array('/tags/view','id'=>$tag->ID)).' ';
        }
        */
	}
}
?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 38: 18 (1986)

#### Original name
Cucurbitaria confluens Plowr.

### Remarks
null


text:
import rp from 'request-promise';

const USER_AGENT = 'apollo-accounts-server';

export default ({ access_token }, { key, secret }) =>
  rp({
    uri: 'https://api.github.com/user',
    qs: {
      access_token,
      client_id: key,
      client_secret: secret,
    },
    headers: {
      'User-Agent': USER_AGENT,
    },
    json: true,
  }).then(result => ({ identifier: result.id, username: result.login, profile: result }));


text:
class Person < ActiveRecord::Base
  validates :name, :presence => true
  validates :name, :uniqueness => true
end


text:
#region Licence

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using WmcSoft.Collections.Generic;
using WmcSoft.Diagnostics;

namespace WmcSoft.Benchmark
{
    public class MicrobenchEngine
    {
        readonly TraceSource _trace;
        const int ValuesToDiscard = 5;

        public MicrobenchEngine(TraceSource traceSource) {
            _trace = traceSource;
        }
        public MicrobenchEngine()
            : this(new TraceSource("Microbench")) {
        }

        public void Run(IBenchmarkDescriptor benchmark, params string[] args) {
            _trace.TraceInformation("Benchmarking {0}", benchmark.Name);

            var results = new Dictionary<IMeasureDescriptor, double>();
            foreach (var measure in benchmark.EnumerateMeasures())
                results.Add(measure, 0);

            var measures = results.Keys
                .Repeat(benchmark.Iterations + ValuesToDiscard).ToList();
            measures.Shuffle(new Random(1789));

            try {
                benchmark.Init(args);
            }
            catch (TargetInvocationException e) {
                Exception inner = e.InnerException;
                string message = (inner == null ? null : inner.Message) ?? "No message";
                _trace.TraceError(1000, "  {0}: Failed ({1})", benchmark.Name, message);
                throw;
            }
            catch (Exception e) {
                _trace.TraceError(1000, "  {0}: Failed ({1})", benchmark.Name, e.Message);
                throw;
            }

            for (int i = 0; i < ValuesToDiscard; i++) {
                foreach (var measure in results.Keys) {
                    benchmark.Reset();
                    measure.Invoke();
                }
            }

            foreach (var measure in measures) {
                try {
                    benchmark.Reset();

                    // Give the test as good a chance as possible
                    // of avoiding garbage collection
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();

                    // Now run the test itself
                    var stopwatch = Stopwatch.StartNew();
                    measure.Invoke();
                    stopwatch.Stop();

                    // Check the results (if appropriate)
                    // Note that this doesn't affect the timing
                    benchmark.Check();

                    // If everything's worked, report the time taken,
                    // nicely lined up (assuming no very long method names!)
                    double duration = results[measure];
                    results[measure] = duration + stopwatch.Elapsed.TotalMilliseconds;
                }
                catch (TargetInvocationException e) {
                    Exception inner = e.InnerException;
                    string message = (inner == null ? null : inner.Message) ?? "No message";
                    _trace.TraceError(1001, "  {0}: Failed ({1})", measure.Name, message);
                    throw;
                }
                catch (Exception e) {
                    _trace.TraceError(1001, "  {0}: Failed ({1})", measure.Name, e.Message);
                    throw;
                }
            }

            foreach (var measure in results.OrderBy(r => r.Key.Name)) {
                var duration = measure.Value / benchmark.Iterations;
                if (duration < 1d)
                    _trace.TraceInformation("  {0,-32} {1,10:N3}µs", measure.Key.Name, 1000d * duration);
                else
                    _trace.TraceInformation("  {0,-32} {1,10:N3}ms", measure.Key.Name, duration);
            }
        }
    }
}


text:
namespace si = SageInterface;
namespace sb = SageBuilder;

namespace physis {
namespace translator {

SgFunctionCallExp *BuildTraceStencilPre(SgExpression *msg) {
  SgFunctionSymbol *fs
      = si::lookupFunctionSymbolInParentScopes("__PSTraceStencilPre");
  SgFunctionCallExp *fc =
      sb::buildFunctionCallExp(fs, sb::buildExprListExp(msg));
  return fc;
}

SgFunctionCallExp *BuildTraceStencilPost(SgExpression *time) {
  SgFunctionSymbol *fs
      = si::lookupFunctionSymbolInParentScopes("__PSTraceStencilPost");
  SgFunctionCallExp *fc =
      sb::buildFunctionCallExp(fs, sb::buildExprListExp(time));
  return fc;
}

SgVariableDeclaration *BuildStopwatch(const std::string &name,
                                      SgScopeStatement *scope,
                                      SgScopeStatement *global_scope) {
  SgType *t = si::lookupNamedTypeInParentScopes("__PSStopwatch",
                                                global_scope);
  assert(t);
  SgVariableDeclaration *decl
      = sb::buildVariableDeclaration(
          name, t,
          NULL, scope);
  return decl;
}

SgFunctionCallExp *BuildStopwatchStart(SgExpression *sw) {
  SgFunctionSymbol *fs
      = si::lookupFunctionSymbolInParentScopes("__PSStopwatchStart");
  SgFunctionCallExp *fc =
      sb::buildFunctionCallExp(fs, sb::buildExprListExp(sw));
  return fc;
}

SgFunctionCallExp *BuildStopwatchStop(SgExpression *sw) {
  SgFunctionSymbol *fs
      = si::lookupFunctionSymbolInParentScopes("__PSStopwatchStop");
  SgFunctionCallExp *fc =
      sb::buildFunctionCallExp(fs, sb::buildExprListExp(sw));
  return fc;
}

SgFunctionCallExp *BuildDomainGetBoundary(SgExpression *dom,
                                          int dim, int right,
                                          SgExpression *width,
                                          int factor, int offset) {
  SgFunctionSymbol *fs
      = si::lookupFunctionSymbolInParentScopes("__PSDomainGetBoundary");
  SgFunctionCallExp *fc =
      sb::buildFunctionCallExp(
          fs,
          sb::buildExprListExp(dom, sb::buildIntVal(dim),
                               sb::buildIntVal(right), width,
                               sb::buildIntVal(factor), sb::buildIntVal(offset)));
  return fc;
}

} // namespace translator
} // namespace physis


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 52: 382 (1975)

#### Original name
Cortinarius ochraceolamellatus M.M. Moser

### Remarks
null


text:
package com.nshmura.recyclertablayout.demo.customview01;

import com.nshmura.recyclertablayout.RecyclerTabLayout;
import com.nshmura.recyclertablayout.demo.ColorItem;
import com.nshmura.recyclertablayout.demo.DemoColorPagerAdapter;
import com.nshmura.recyclertablayout.demo.R;

import android.graphics.Typeface;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Shinichi Nishimura on 2015/07/22.
 */
public class DemoCustomView01Adapter extends RecyclerTabLayout.Adapter<DemoCustomView01Adapter.ViewHolder> {

    private DemoColorPagerAdapter mAdapater;

    public DemoCustomView01Adapter(ViewPager viewPager) {
        super(viewPager);
        mAdapater = (DemoColorPagerAdapter) mViewPager.getAdapter();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_custom_view01_tab, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ColorItem colorItem = mAdapater.getColorItem(position);
        holder.title.setText(colorItem.name);
        holder.color.setBackgroundColor(colorItem.color);

        SpannableString name = new SpannableString(colorItem.name);
        if (position == getCurrentIndicatorPosition()) {
            name.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
        }
        holder.title.setText(name);
    }

    @Override
    public int getItemCount() {
        return mAdapater.getCount();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public View color;
        public TextView title;

        public ViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
            color = itemView.findViewById(R.id.color);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getViewPager().setCurrentItem(getAdapterPosition());
                }
            });
        }
    }
}


text:
package exporter

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"testing"

	"github.com/golang/protobuf/ptypes/timestamp"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"

	flowpb "github.com/cilium/cilium/api/v1/flow"
	observerpb "github.com/cilium/cilium/api/v1/observer"
	v1 "github.com/cilium/cilium/pkg/hubble/api/v1"
	nodeTypes "github.com/cilium/cilium/pkg/node/types"
)

func TestExporter(t *testing.T) {
	// override node name for unit test.
	nodeName := nodeTypes.GetName()
	newNodeName := "my-node"
	nodeTypes.SetName(newNodeName)
	defer func() {
		nodeTypes.SetName(nodeName)
	}()
	events := []*v1.Event{
		{
			Event: &observerpb.Flow{
				NodeName: newNodeName,
				Time:     &timestamp.Timestamp{Seconds: 1},
			},
		},
		{Timestamp: &timestamp.Timestamp{Seconds: 2}, Event: &observerpb.AgentEvent{}},
		{Timestamp: &timestamp.Timestamp{Seconds: 3}, Event: &observerpb.DebugEvent{}},
		{Timestamp: &timestamp.Timestamp{Seconds: 4}, Event: &observerpb.LostEvent{}},
	}
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	log := logrus.New()
	log.SetOutput(io.Discard)
	exporter := newExporter(log, encoder)
	ctx := context.Background()
	for _, ev := range events {
		stop, err := exporter.OnDecodedEvent(ctx, ev)
		assert.False(t, stop)
		assert.NoError(t, err)

	}
	assert.Equal(t, `{"flow":{"time":"1970-01-01T00:00:01Z","node_name":"my-node"},"node_name":"my-node","time":"1970-01-01T00:00:01Z"}
{"agent_event":{},"node_name":"my-node","time":"1970-01-01T00:00:02Z"}
{"debug_event":{},"node_name":"my-node","time":"1970-01-01T00:00:03Z"}
{"lost_events":{},"node_name":"my-node","time":"1970-01-01T00:00:04Z"}
`, buf.String())
}

func TestEventToExportEvent(t *testing.T) {
	// override node name for unit test.
	nodeName := nodeTypes.GetName()
	newNodeName := "my-node"
	nodeTypes.SetName(newNodeName)
	defer func() {
		nodeTypes.SetName(nodeName)
	}()

	// flow
	ev := v1.Event{
		Event: &observerpb.Flow{
			NodeName: newNodeName,
			Time:     &timestamp.Timestamp{Seconds: 1},
		},
	}
	res := eventToExportEvent(&ev)
	expected := &observerpb.ExportEvent{
		ResponseTypes: &observerpb.ExportEvent_Flow{Flow: ev.Event.(*flowpb.Flow)},
		NodeName:      newNodeName,
		Time:          ev.GetFlow().Time,
	}
	assert.Equal(t, res, expected)

	// lost event
	ev = v1.Event{
		Timestamp: &timestamp.Timestamp{Seconds: 1},
		Event:     &observerpb.LostEvent{},
	}
	res = eventToExportEvent(&ev)
	expected = &observerpb.ExportEvent{
		ResponseTypes: &observerpb.ExportEvent_LostEvents{LostEvents: ev.Event.(*flowpb.LostEvent)},
		NodeName:      newNodeName,
		Time:          ev.Timestamp,
	}
	assert.Equal(t, res, expected)

	// agent event
	ev = v1.Event{
		Timestamp: &timestamp.Timestamp{Seconds: 1},
		Event:     &observerpb.AgentEvent{},
	}
	res = eventToExportEvent(&ev)
	expected = &observerpb.ExportEvent{
		ResponseTypes: &observerpb.ExportEvent_AgentEvent{AgentEvent: ev.Event.(*flowpb.AgentEvent)},
		NodeName:      newNodeName,
		Time:          ev.Timestamp,
	}
	assert.Equal(t, res, expected)

	// debug event
	ev = v1.Event{
		Timestamp: &timestamp.Timestamp{Seconds: 1},
		Event:     &observerpb.DebugEvent{},
	}
	res = eventToExportEvent(&ev)
	expected = &observerpb.ExportEvent{
		ResponseTypes: &observerpb.ExportEvent_DebugEvent{DebugEvent: ev.Event.(*flowpb.DebugEvent)},
		NodeName:      newNodeName,
		Time:          ev.Timestamp,
	}
	assert.Equal(t, res, expected)
}


text:
package org.cocos2d.nodes;

import android.graphics.Bitmap;
import org.cocos2d.opengl.Texture2D;

import java.util.HashMap;

public class Sprite extends TextureNode implements CocosNode.CocosNodeFrames {
    private HashMap<String, CocosAnimation> animations;

    public static Sprite sprite(String filename) {
        return new Sprite(TextureManager.sharedTextureManager().addImage(filename));
    }

    public static Sprite sprite(Bitmap image) {
        assert image != null : "Image must not be null";

        return new Sprite(TextureManager.sharedTextureManager().addImage(image));
    }

    public static Sprite sprite(Texture2D tex) {
        return new Sprite(tex);
    }

    protected Sprite(Texture2D tex) {
        setTexture(tex);

        animations = null; // lazy alloc
    }

    private void initAnimationDictionary() {
        animations = new HashMap<String, CocosAnimation>(2);
    }

    public void setDisplayFrame(Object frame) {
        setTexture((Texture2D) frame);
    }

    public void setDisplayFrame(String animationName, int frameIndex) {
        if (animations == null)
            initAnimationDictionary();

        CocosAnimation anim = animations.get(animationName);
        Texture2D frame = (Texture2D) anim.frames().get(frameIndex);
        setDisplayFrame(frame);
    }

    public boolean isFrameDisplayed(Object frame) {
        return getTexture() == (Texture2D) frame;
    }

    public Object displayFrame() {
        return getTexture();
    }

    public void addAnimation(CocosAnimation anim) {
        // lazy alloc
        if (animations == null)
            initAnimationDictionary();

        animations.put(anim.name(), anim);
    }

    public CocosAnimation animationByName(String animationName) {
        assert animationName != null : "animationName parameter must be non null";
        return animations.get(animationName);
    }

}


text:
package gentleman

import (
	"net/http"

	"gopkg.in/h2non/gentleman.v1/context"
	"gopkg.in/h2non/gentleman.v1/middleware"
	"gopkg.in/h2non/gentleman.v1/plugin"
	"gopkg.in/h2non/gentleman.v1/plugins/cookies"
	"gopkg.in/h2non/gentleman.v1/plugins/headers"
	"gopkg.in/h2non/gentleman.v1/plugins/url"
)

// NewContext is a convenient alias to context.New factory.
var NewContext = context.New

// NewHandler is a convenient alias to context.NewHandler factory.
var NewHandler = context.NewHandler

// NewMiddleware is a convenient alias to middleware.New factory.
var NewMiddleware = middleware.New

// Client represents a high-level HTTP client entity capable
// with a built-in middleware and context.
type Client struct {
	// Client entity can inherit behavior from a parent Client.
	Parent *Client

	// Each Client entity has it's own Context that will be inherited by requests or child clients.
	Context *context.Context

	// Client entity has its own Middleware layer to compose and inherit behavior.
	Middleware middleware.Middleware
}

// New creates a new high level client entity
// able to perform HTTP requests.
func New() *Client {
	return &Client{
		Context:    context.New(),
		Middleware: middleware.New(),
	}
}

// Request creates a new Request based on the current Client
func (c *Client) Request() *Request {
	req := NewRequest()
	req.SetClient(c)
	return req
}

// Get creates a new GET request.
func (c *Client) Get() *Request {
	req := c.Request()
	req.Method("GET")
	return req
}

// Post creates a new POST request.
func (c *Client) Post() *Request {
	req := c.Request()
	req.Method("POST")
	return req
}

// Put creates a new PUT request.
func (c *Client) Put() *Request {
	req := c.Request()
	req.Method("PUT")
	return req
}

// Delete creates a new DELETE request.
func (c *Client) Delete() *Request {
	req := c.Request()
	req.Method("DELETE")
	return req
}

// Patch creates a new PATCH request.
func (c *Client) Patch() *Request {
	req := c.Request()
	req.Method("PATCH")
	return req
}

// Head creates a new HEAD request.
func (c *Client) Head() *Request {
	req := c.Request()
	req.Method("HEAD")
	return req
}

// Method defines a the default HTTP method used by outgoing client requests.
func (c *Client) Method(name string) *Client {
	c.Middleware.UseRequest(func(ctx *context.Context, h context.Handler) {
		ctx.Request.Method = name
		h.Next(ctx)
	})
	return c
}

// URL defines the URL for client requests.
// Useful to define at client level the base URL and base path used by child requests.
func (c *Client) URL(uri string) *Client {
	c.Use(url.URL(uri))
	return c
}

// BaseURL defines the URL schema and host for client requests.
// Useful to define at client level the base URL used by client child requests.
func (c *Client) BaseURL(uri string) *Client {
	c.Use(url.BaseURL(uri))
	return c
}

// Path defines the URL base path for client requests.
func (c *Client) Path(path string) *Client {
	c.Use(url.Path(path))
	return c
}

// Param replaces a path param based on the given param name and value.
func (c *Client) Param(name, value string) *Client {
	c.Use(url.Param(name, value))
	return c
}

// Params replaces path params based on the given params key-value map.
func (c *Client) Params(params map[string]string) *Client {
	c.Use(url.Params(params))
	return c
}

// SetHeader sets a new header field by name and value.
// If another header exists with the same key, it will be overwritten.
func (c *Client) SetHeader(key, value string) *Client {
	c.Use(headers.Set(key, value))
	return c
}

// AddHeader adds a new header field by name and value
// without overwriting any existent header.
func (c *Client) AddHeader(name, value string) *Client {
	c.Use(headers.Add(name, value))
	return c
}

// SetHeaders adds new header fields based on the given map.
func (c *Client) SetHeaders(fields map[string]string) *Client {
	c.Use(headers.SetMap(fields))
	return c
}

// AddCookie sets a new cookie field bsaed on the given http.Cookie struct
// without overwriting any existent cookie.
func (c *Client) AddCookie(cookie *http.Cookie) *Client {
	c.Use(cookies.Add(cookie))
	return c
}

// AddCookies sets a new cookie field based on a list of http.Cookie
// without overwriting any existent cookie.
func (c *Client) AddCookies(data []*http.Cookie) *Client {
	c.Use(cookies.AddMultiple(data))
	return c
}

// CookieJar creates a cookie jar to store HTTP cookies when they are sent down.
func (c *Client) CookieJar() *Client {
	c.Use(cookies.Jar())
	return c
}

// Use uses a new plugin to the middleware stack.
func (c *Client) Use(p plugin.Plugin) *Client {
	c.Middleware.Use(p)
	return c
}

// UseRequest uses a new middleware function for request phase.
func (c *Client) UseRequest(fn context.HandlerFunc) *Client {
	c.Middleware.UseRequest(fn)
	return c
}

// UseResponse uses a new middleware function for response phase.
func (c *Client) UseResponse(fn context.HandlerFunc) *Client {
	c.Middleware.UseResponse(fn)
	return c
}

// UseError uses a new middleware function for error phase.
func (c *Client) UseError(fn context.HandlerFunc) *Client {
	c.Middleware.UseError(fn)
	return c
}

// UseHandler uses a new middleware function for the given phase.
func (c *Client) UseHandler(phase string, fn context.HandlerFunc) *Client {
	c.Middleware.UseHandler(phase, fn)
	return c
}

// UseParent uses another Client as parent
// inheriting its middleware stack and configuration.
func (c *Client) UseParent(parent *Client) *Client {
	c.Parent = parent
	c.Context.UseParent(parent.Context)
	c.Middleware.UseParent(parent.Middleware)
	return c
}


text:
#include "Mocks/Dispatcher/WeightedPetriNet.h"
#include "PTN_Engine/Place.h"

using namespace ptne;
using namespace std;

Dispatcher::WeightedPetriNet::WeightedPetriNet(shared_ptr<Dispatcher> ptrDispatcher)
: PTN_Engine{}
{

	// Places
	createPlace("InputWaitPackage", 0, true);
	createPlace("WaitPackage", 0);
	createPlace("ChannelA", 0);
	createPlace("ChannelB", 0);

	// Transitions

	createTransition({ "InputWaitPackage" }, // activation
					 vector<size_t>{ 1 }, { "WaitPackage" }, // destination
					 vector<size_t>{ 1 });

	createTransition({ "WaitPackage" }, // activation
					 vector<size_t>{ 3 }, { "ChannelA", "ChannelB" }, // destination
					 vector<size_t>{ 4, 10 });
}

void Dispatcher::WeightedPetriNet::dispatch()
{
	incrementInputPlace("InputWaitPackage");
	execute();
}


text:
import { common } from './../common';
import { nameSpace } from './../utils';

export function Controller(options) {
  options = options || {};
  // Allow shorthand notation of just passing the name as a string
  if (typeof options === 'string') {
    options = { name: options };
  }

  return function ControllerTarget(target) {
    angular.module(common.currentModule)
      .controller(nameSpace(options.name), target);
    return target;
  };
}


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

using System;
using System.Globalization;
using System.Threading;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;

namespace Microsoft.Build.Experimental.Graph
{
    /// <summary>
    /// A callback used to receive notification that a build has completed.
    /// </summary>
    /// <remarks>
    /// When this delegate is invoked, the WaitHandle on the BuildSubmission will have been be signalled and the OverallBuildResult will be valid.
    /// </remarks>
    public delegate void GraphBuildSubmissionCompleteCallback(GraphBuildSubmission submission);

    /// <summary>
    /// A GraphBuildSubmission represents a graph build request which has been submitted to the BuildManager for processing.  It may be used to
    /// execute synchronous or asynchronous graph build requests and provides access to the results upon completion.
    /// </summary>
    /// <remarks>
    /// This class is thread-safe.
    /// </remarks>
    public class GraphBuildSubmission
    {
        /// <summary>
        /// The callback to invoke when the submission is complete.
        /// </summary>
        private GraphBuildSubmissionCompleteCallback _completionCallback;

        /// <summary>
        /// The completion event.
        /// </summary>
        private readonly ManualResetEvent _completionEvent;

        /// <summary>
        /// True if it has been invoked
        /// </summary>
        private int _completionInvoked;

        /// <summary>
        /// Constructor
        /// </summary>
        internal GraphBuildSubmission(BuildManager buildManager, int submissionId, GraphBuildRequestData requestData)
        {
            ErrorUtilities.VerifyThrowArgumentNull(buildManager, nameof(buildManager));
            ErrorUtilities.VerifyThrowArgumentNull(requestData, nameof(requestData));

            BuildManager = buildManager;
            SubmissionId = submissionId;
            BuildRequestData = requestData;
            _completionEvent = new ManualResetEvent(false);
            _completionInvoked = 0;
        }

        /// <summary>
        /// The BuildManager with which this submission is associated.
        /// </summary>
        public BuildManager BuildManager { get; }

        /// <summary>
        /// An ID uniquely identifying this request from among other submissions within the same build.
        /// </summary>
        public int SubmissionId { get; }

        /// <summary>
        /// The asynchronous context provided to <see cref="BuildSubmission.ExecuteAsync(BuildSubmissionCompleteCallback, object)"/>, if any.
        /// </summary>
        public Object AsyncContext { get; private set; }

        /// <summary>
        /// A <see cref="System.Threading.WaitHandle"/> which will be signalled when the build is complete.  Valid after <see cref="BuildSubmission.Execute()"/> or <see cref="BuildSubmission.ExecuteAsync(BuildSubmissionCompleteCallback, object)"/> returns, otherwise null.
        /// </summary>
        public WaitHandle WaitHandle => _completionEvent;

        /// <summary>
        /// Returns true if this submission is complete.
        /// </summary>
        public bool IsCompleted => WaitHandle.WaitOne(new TimeSpan(0));

        /// <summary>
        /// The results of the build per graph node.  Valid only after WaitHandle has become signalled.
        /// </summary>
        public GraphBuildResult BuildResult { get; internal set; }

        /// <summary>
        /// The BuildRequestData being used for this submission.
        /// </summary>
        internal GraphBuildRequestData BuildRequestData { get; }

        /// <summary>
        /// Whether the graph build has started.
        /// </summary>
        internal bool IsStarted { get; set; }

        /// <summary>
        /// Starts the request and blocks until results are available.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">The request has already been started or is already complete.</exception>
        public GraphBuildResult Execute()
        {
            ExecuteAsync(null, null);
            WaitHandle.WaitOne();

            return BuildResult;
        }

        /// <summary>
        /// Starts the request asynchronously and immediately returns control to the caller.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">The request has already been started or is already complete.</exception>
        public void ExecuteAsync(GraphBuildSubmissionCompleteCallback callback, object context)
        {
            ErrorUtilities.VerifyThrowInvalidOperation(!IsCompleted, "SubmissionAlreadyComplete");
            _completionCallback = callback;
            AsyncContext = context;
            BuildManager.ExecuteSubmission(this);
        }

        /// <summary>
        /// Sets the event signaling that the build is complete.
        /// </summary>
        internal void CompleteResults(GraphBuildResult result)
        {
            ErrorUtilities.VerifyThrowArgumentNull(result, nameof(result));
            ErrorUtilities.VerifyThrow(result.SubmissionId == SubmissionId, "GraphBuildResult's submission id doesn't match GraphBuildSubmission's");

            bool hasCompleted = (Interlocked.Exchange(ref _completionInvoked, 1) == 1);
            if (!hasCompleted)
            {
                BuildResult = result;
                _completionEvent.Set();

                if (_completionCallback != null)
                {
                    void Callback(object state)
                    {
                        _completionCallback(this);
                    }

                    ThreadPoolExtensions.QueueThreadPoolWorkItemWithCulture(Callback, CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);
                }
            }
        }
    }
}


text:
class ChartController < ApplicationController
  def show
    [Venue, User, Saying, Plan, Record, Task, Sync, Comment, Photo, Follow, Topic, Question, Tag, Answer].each do |model|
      eval("@#{model.name.downcase}s_per_day = (0..30).map{|a| model.where(:created_at => a.days.ago.beginning_of_day..(a - 1).days.ago.beginning_of_day).size}.reverse")
      eval("@#{model.name.downcase}s_total = #{model.all.size}")
    end

    @douban_syncs = Sync.where(:douban => true).size
    @sina_syncs = Sync.where(:sina => true).size
    @goods_records = Record.where(:actional_id => 3).size
    @time_records = Record.where(:actional_id => 1).size
    @directly_plans = Plan.where(:parent_id => nil).size
    @follow_plans = Plan.where("parent_id is not null").size
  end
end


text:
#include <dart/dart.hpp>
#include <dart/gui/osg/osg.hpp>

using namespace dart::dynamics;

int main()
{
  dart::simulation::WorldPtr world(new dart::simulation::World);

  Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());

  tf.translation() = Eigen::Vector3d(4, -4, 0);
  dart::gui::osg::InteractiveFramePtr frame(
      new dart::gui::osg::InteractiveFrame(
          Frame::World(), "interactive frame", tf, 2.0));
  world->addSimpleFrame(frame);

  tf.translation() = Eigen::Vector3d(-4, 4, 0);
  SimpleFramePtr draggable(new SimpleFrame(frame.get(), "draggable", tf));
  draggable->setShape(std::make_shared<BoxShape>(Eigen::Vector3d(1, 1, 1)));
  draggable->getVisualAspect(true)->setColor(Eigen::Vector3d(0.9, 0.0, 0.0));
  world->addSimpleFrame(draggable);

  tf.translation() = Eigen::Vector3d(8.0, 0.0, 0.0);
  SimpleFramePtr x_marker(new SimpleFrame(Frame::World(), "X", tf));
  std::shared_ptr<BoxShape> x_shape(
      new BoxShape(Eigen::Vector3d(0.2, 0.2, 0.2)));
  x_marker->setShape(x_shape);
  x_marker->getVisualAspect(true)->setColor(Eigen::Vector3d(0.9, 0.0, 0.0));
  world->addSimpleFrame(x_marker);

  tf.translation() = Eigen::Vector3d(0.0, 8.0, 0.0);
  SimpleFramePtr y_marker(new SimpleFrame(Frame::World(), "Y", tf));
  std::shared_ptr<BoxShape> y_shape(
      new BoxShape(Eigen::Vector3d(0.2, 0.2, 0.2)));
  y_marker->setShape(y_shape);
  y_marker->getVisualAspect(true)->setColor(Eigen::Vector3d(0.0, 0.9, 0.0));
  world->addSimpleFrame(y_marker);

  tf.translation() = Eigen::Vector3d(0.0, 0.0, 8.0);
  SimpleFramePtr z_marker(new SimpleFrame(Frame::World(), "Z", tf));
  std::shared_ptr<BoxShape> z_shape(
      new BoxShape(Eigen::Vector3d(0.2, 0.2, 0.2)));
  z_marker->setShape(z_shape);
  z_marker->getVisualAspect(true)->setColor(Eigen::Vector3d(0.0, 0.0, 0.9));
  world->addSimpleFrame(z_marker);

  ::osg::ref_ptr<dart::gui::osg::WorldNode> node
      = new dart::gui::osg::WorldNode(world);

  dart::gui::osg::Viewer viewer;
  viewer.addWorldNode(node);
  viewer.enableDragAndDrop(frame.get());
  viewer.enableDragAndDrop(draggable.get());

  viewer.addInstructionText("\nCtrl + Left-click: Rotate the box\n");
  std::cout << viewer.getInstructions() << std::endl;

  viewer.setUpViewInWindow(0, 0, 640, 480);

  viewer.getCameraManipulator()->setHomePosition(
      ::osg::Vec3(20.0, 17.0, 17.0),
      ::osg::Vec3(0.0, 0.0, 0.0),
      ::osg::Vec3(0, 0, 1));
  viewer.setCameraManipulator(viewer.getCameraManipulator());

  viewer.run();
}


text:
package com.tetris.scenes;

import java.util.List;

import android.content.Context;

import com.framework.Game;
import com.framework.gameobjects.sprites.Sprite;
import com.framework.gameobjects.sprites.Sprite.Transparency;
import com.framework.gamescenes.GameScene;
import com.tetris.controller.TetrisController;
import com.tetris.objects.TetrisBackground;

public class TetrisEndScene extends GameScene {
	final private static String TAG = "TETRISENDSCENE";

	/********************************************************************/
	/* 						ENUMS										*/
	/********************************************************************/

	public enum TetrisEndSceneState {
		UNDEFINED,
		DEFAULT,
		RESTARTREQUESTED
	}

	/********************************************************************/
	/* 						MEMBERS										*/
	/********************************************************************/

	private TetrisEndSceneState mState;
	private TetrisBackground mBackground;
	private Sprite mGameOverSprite;
	private Sprite mRestartSprite;
	private final TetrisController mTetrisController;

	/********************************************************************/
	/* 						CONSTANTS									*/
	/********************************************************************/

	/********************************************************************/
	/* 						CONSTRUCTORS								*/
	/********************************************************************/

	public TetrisEndScene(TetrisController tetrisController) {
		mTetrisController = tetrisController;
	}

	/********************************************************************/
	/* 						GETTERS and SETTERS							*/
	/********************************************************************/

	public void setState(TetrisEndSceneState state) {
		mState = state;
	}

	public TetrisEndSceneState getState() {
		return mState;
	}

	/********************************************************************/
	/* 						FUNCTIONALITIES								*/
	/********************************************************************/
	@Override
    protected void createGameObjects() {
		mBackground = new TetrisBackground();

		float[] topLeftCornerNDC1 = {-1.0f,  (float)2/3};
		mGameOverSprite = new Sprite(topLeftCornerNDC1, 2.0f, (float)2/3, "textures/gameover.png", Transparency.TRANSPARENT);

		float[] topLeftCornerNDC2 = {-1.0f,  (float)0};
		mRestartSprite = new Sprite(topLeftCornerNDC2, 2.0f, (float)2/3, "textures/restart.png", Transparency.TRANSPARENT);
    }

	@Override
    protected void addGameObjects() {
		this.addGameObject(mBackground);
		this.addGameObject(mGameOverSprite);
		this.addGameObject(mRestartSprite);
    }

	@Override
	public void initialize(Context context) {
		super.initialize(context);

		mState = TetrisEndSceneState.DEFAULT;
	}

	@Override
	public void update(Context context, float deltaTS) {
		//Get the new inputs
		List<TetrisController.Action> tmp = mTetrisController.parseAndConsumeMotionEvents(Game.getInputManager().getMotionEventBuffer());

		for(int i = 0; i < tmp.size(); ++i) {
			//TODO: should get a better button implementation!!
			if(tmp.get(i).getY() >= 240 && tmp.get(i).getY() < 360) {
				mState = TetrisEndSceneState.RESTARTREQUESTED;
				//mEndGame = false;
				//mTetrisController.setState(State.END);
				//mTetrisController.clear();
				//mIM.clear();
				//restart();
				//break;
			}
		}

		//Update all objects
		super.update(context, deltaTS);
	}
}


text:
package st300

import (
	"bytes"
	"strconv"

	"github.com/larixsource/suntech/lexer"
	"github.com/larixsource/suntech/st"
)

type ST300CGF struct {
	DevID     string
	SwVer     string
	GeoID     int
	Active    bool
	Latitude  float32
	Longitude float32
	Radius    int
	In        bool
	Out       bool

	// Resp is true when this is a response
	Resp bool
}

func (gf *ST300CGF) Command() []byte {
	var buf bytes.Buffer
	buf.WriteString("ST300CGF;")
	buf.WriteString(gf.DevID)
	buf.WriteByte(';')
	buf.WriteString(gf.SwVer)
	buf.WriteByte(';')
	buf.WriteString(strconv.Itoa(gf.GeoID))
	buf.WriteByte(';')
	if gf.Active {
		buf.WriteString("1")
	} else {
		buf.WriteString("0")
	}
	buf.WriteByte(';')
	buf.WriteString(strconv.FormatFloat(float64(gf.Latitude), 'f', 6, 32))
	buf.WriteByte(';')
	buf.WriteString(strconv.FormatFloat(float64(gf.Longitude), 'f', 6, 32))
	buf.WriteByte(';')
	buf.WriteString(strconv.Itoa(gf.Radius))
	buf.WriteByte(';')
	if gf.In {
		buf.WriteString("1")
	} else {
		buf.WriteString("0")
	}
	buf.WriteByte(';')
	if gf.Out {
		buf.WriteString("1")
	} else {
		buf.WriteString("0")
	}
	return buf.Bytes()
}

func parseCGF(lex *lexer.Lexer, msg *Msg) {
	msg.Type = CGFCmd

	cgf := &ST300CGF{}
	msg.CGF = cgf

	// Res and DevID, or just DevID
	isDevID, devID, token, err := st.AsciiDevIDOrRes(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	if isDevID {
		cgf.DevID = devID
	} else {
		cgf.Resp = true

		// get devID
		devID, token, err := st.AsciiDevID(lex)
		msg.Frame = append(msg.Frame, token.Literal...)
		if err != nil {
			msg.ParsingError = err
			return
		}
		cgf.DevID = devID
	}

	swVer, token, err := st.AsciiSwVer2(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.SwVer = swVer

	geoID, token, err := st.AsciiGeoID(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.GeoID = geoID

	active, token, err := st.AsciiBit(lex, false)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.Active = active

	lat, token, err := st.AsciiLat(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.Latitude = lat

	lon, token, err := st.AsciiLon(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.Longitude = lon

	radius, token, err := st.AsciiRadius(lex)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.Radius = radius

	in, token, err := st.AsciiBit(lex, false)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.In = in

	out, token, err := st.AsciiBit(lex, true)
	msg.Frame = append(msg.Frame, token.Literal...)
	if err != nil {
		msg.ParsingError = err
		return
	}
	cgf.Out = out
}


text:
data_file_name = "test5_results_3.txt"
data_file = open(data_file_name)
file_content = data_file.readlines()
data_file.close()
result_file_name = data_file_name[:-4]+".csv"

result_content = "Frequency\n"
frequencies = sorted(map(lambda x: x[0], eval(file_content[0])[1][('Sum PSDA', ('P7', 'O1', 'O2', 'P8'))][1]))
for i, frequency in enumerate(frequencies):
    result_content += str(i+1) + " " + str(frequency) + "\n"
open(data_file_name[:-6] + "_freq" + data_file_name[-6:], "w").write(result_content)

psda_keys = ["Sum", 1, 2]

result_content = "PSDA_sum_f1 PSDA_sum_f2 PSDA_sum_f3 PSDA_h1_f1 PSDA_h1_f2 PSDA_h1_f3 PSDA_h2_f1 PSDA_h2_f2 PSDA_h2_f3 CCA_f1 CCA_f2 CCA_f3\n"
for i, line in enumerate(file_content):
    results_dict = eval(line)
    result_content += str(i+1) + " "
    for key in psda_keys:
        psda_results = results_dict[1][('Sum PSDA', ('P7', 'O1', 'O2', 'P8'))][key]
        psda_results_dict = dict(psda_results)
        for frequency in frequencies:
            result_content += str(psda_results_dict[frequency]) + " "
    cca_results_dict = dict(results_dict[2][('CCA', ('P7', 'O1', 'O2', 'P8'))])
    for frequency in frequencies:
        result_content += str(cca_results_dict[frequency]) + " "
    result_content = result_content[:-1] + "\n"

result_file = open(result_file_name, "w")
result_file.write(result_content)
result_file.close()


text:
<component name="libraryTable">
  <library name="exposed-instrumentation-api-publish-0.5">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/9f95ff56c140218076fe504608299176a4a2161f/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/9f95ff56c140218076fe504608299176a4a2161f/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://C:/Android/sdk/extras/android/m2repository/com/android/support/test/exposed-instrumentation-api-publish/0.5/exposed-instrumentation-api-publish-0.5-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<!DOCTYPE html>

  <title></title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
  <link rel="stylesheet" href="../assets/css/docs.min.css">
  <link rel="stylesheet" href="../assets/css/template.css?v=VERSION">
  <link rel="stylesheet" href="../assets/css/ads.css?v=VERSION">

      Via data attributes

      Via JavaScript


text:
<ion-tabs class="tabs-icon-top">

  <ion-tab title="About" icon="icon ion-information-circled" href="#/about">
    <ion-nav-view name="about"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Media Cloud" icon="icon ion-cloud" href="#/templates/menu">
    <ion-nav-view name="search"></ion-nav-view>
  </ion-tab>

</ion-tabs>


text:
#include "TclMolSelectionLoader.h"
#include "mmcore/param/FilePathParam.h"
#include "vislib/sys/ASCIIFileBuffer.h"
#include <deque>
#include <vector>

using namespace megamol;
using namespace megamol::moldyn;

io::TclMolSelectionLoader::TclMolSelectionLoader()
        : core::Module()
        , getDataSlot("getdata", "Access to the data")
        , filenameSlot("filename", "Path to the Tcl file to load")
        , hash(0)
        , cnt(0)
        , data() {

    getDataSlot.SetCallback(
        geocalls::ParticleRelistCall::ClassName(), "GetData", &TclMolSelectionLoader::getDataCallback);
    getDataSlot.SetCallback(
        geocalls::ParticleRelistCall::ClassName(), "GetExtent", &TclMolSelectionLoader::getDataCallback);
    MakeSlotAvailable(&getDataSlot);

    filenameSlot.SetParameter(new core::param::FilePathParam(""));
    MakeSlotAvailable(&filenameSlot);
}

io::TclMolSelectionLoader::~TclMolSelectionLoader() {
    Release();
}

bool io::TclMolSelectionLoader::create(void) {
    return true;
}

void io::TclMolSelectionLoader::release(void) {
    clear();
    hash = 0;
}

bool io::TclMolSelectionLoader::getDataCallback(core::Call& caller) {
    geocalls::ParticleRelistCall* prc = dynamic_cast<geocalls::ParticleRelistCall*>(&caller);
    if (prc == nullptr)
        return false;
    if (filenameSlot.IsDirty())
        load();

    prc->SetDataHash(hash);
    prc->Set(cnt, data.size(), data.data());
    prc->SetExtent(1, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f);
    prc->SetFrameID(0, true);
    prc->SetUnlocker(nullptr);

    return true;
}

void io::TclMolSelectionLoader::clear(void) {
    hash++;
    cnt = 0;
    data.clear();
}

void io::TclMolSelectionLoader::load(void) {
    typedef geocalls::ParticleRelistCall::ListIDType ListIDType;
    filenameSlot.ResetDirty();

    vislib::sys::ASCIIFileBuffer file;
    if (!file.LoadFile(filenameSlot.Param<core::param::FilePathParam>()->Value().native().c_str(),
            vislib::sys::ASCIIFileBuffer::PARSING_WORDS)) {
        megamol::core::utility::log::Log::DefaultLog.WriteError("Unable to read file \"%s\"",
            filenameSlot.Param<core::param::FilePathParam>()->Value().generic_u8string().c_str());
        return;
    }

    // count selection particles
    uint64_t partCnt = 0;
    uint64_t maxPart = 0;
    int actCol = -1;
    std::vector<int> cols;
    ListIDType selCnt = 0;

    SIZE_T lineCount = file.Count();
    for (SIZE_T li = 0; li < lineCount; ++li) {
        const auto& line = file.Line(li);
        SIZE_T wordCount = line.Count();
        if (wordCount < 4)
            continue;
        if ((vislib::StringA(line.Word(0)).Equals("mol", false) &&
                vislib::StringA(line.Word(1)).Equals("color", false) &&
                vislib::StringA(line.Word(2)).Equals("ColorID", false))) {
            try {
                int v = vislib::CharTraitsA::ParseInt(line.Word(3));
                if (actCol != v) {
                    auto ci = std::find(cols.begin(), cols.end(), v);
                    if (ci == cols.end()) {
                        cols.push_back(v);
                    }
                    actCol = v;
                }
            } catch (...) {}
        }
        if (!(vislib::StringA(line.Word(0)).Equals("mol", false) &&
                vislib::StringA(line.Word(1)).Equals("selection", false) &&
                vislib::StringA(line.Word(2)).Equals("serial", false)))
            continue;

        for (SIZE_T wi = 3; wi < wordCount; ++wi) {
            try {
                uint64_t v = vislib::CharTraitsA::ParseUInt64(line.Word(wi)); // these are 1-based
                partCnt++;
                if (maxPart < v)
                    maxPart = v;
            } catch (...) {}
        }
    }

    bool incompleteSelection = (partCnt != maxPart);
    if (incompleteSelection)
        cols.insert(cols.begin(), -1);
    // GetCoreInstance()->Log().WriteWarn("Particle selection", vislib::StringA(filenameSlot.Param<core::param::FilePathParam>()->Value()).PeekBuffer());

    hash++;
    data.resize(maxPart);
    ::memset(data.data(), 0, sizeof(ListIDType) * maxPart);
    selCnt = 0;
    for (SIZE_T li = 0; li < lineCount; ++li) {
        const auto& line = file.Line(li);
        SIZE_T wordCount = line.Count();
        if (wordCount < 4)
            continue;
        if ((vislib::StringA(line.Word(0)).Equals("mol", false) &&
                vislib::StringA(line.Word(1)).Equals("color", false) &&
                vislib::StringA(line.Word(2)).Equals("ColorID", false))) {
            try {
                int v = vislib::CharTraitsA::ParseInt(line.Word(3));
                if (actCol != v) {
                    auto ci = std::find(cols.begin(), cols.end(), v);
                    assert(ci != cols.end());
                    actCol = v;
                    selCnt = static_cast<ListIDType>(std::distance(cols.begin(), ci));
                }
            } catch (...) {}
        }
        if (!(vislib::StringA(line.Word(0)).Equals("mol", false) &&
                vislib::StringA(line.Word(1)).Equals("selection", false) &&
                vislib::StringA(line.Word(2)).Equals("serial", false)))
            continue;

        for (SIZE_T wi = 3; wi < wordCount; ++wi) {
            try {
                uint64_t v = vislib::CharTraitsA::ParseUInt64(line.Word(wi)); // these are 1-based
                data[v - 1] = selCnt;
            } catch (...) {}
        }
    }

    cnt = static_cast<ListIDType>(cols.size());
}


text:
package com.study.design.observer;

public class GraphObserver implements Observer {

    @Override
    public void update(NumberGenerator numberGenerator) {
        for(int i =0; i < numberGenerator.getNumber(); i++) {
            System.out.print("*");
        }
        System.out.println();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
import Node from '../Node.js';
import CompileError from '../../utils/CompileError.js';
import { loopStatement } from '../../utils/patterns.js';

export default class BreakStatement extends Node {
	initialise() {
		const loop = this.findNearest(loopStatement);
		const switchCase = this.findNearest('SwitchCase');

		if (loop && (!switchCase || loop.depth > switchCase.depth)) {
			loop.canBreak = true;
			this.loop = loop;
		}
	}

	transpile(code) {
		if (this.loop && this.loop.shouldRewriteAsFunction) {
			if (this.label)
				throw new CompileError(
					'Labels are not currently supported in a loop with locally-scoped variables',
					this
				);
			code.overwrite(this.start, this.start + 5, `return 'break'`);
		}
	}
}


text:
using System;

namespace pal.EventLogAnalyzer.ConsoleClient
{
    internal class CommandLineArgumentHandler
    {
        private readonly InputFilterArguments _inputFilterArguments;
        private readonly OutputFilterArguments _outputArguments;
        private readonly ProcessControlArguments _processControlArguments;

        public CommandLineArgumentHandler()
        {
            //TODO: Still to handle mandatory arguments
            _inputFilterArguments = new InputFilterArguments();
            _outputArguments = new OutputFilterArguments();
            _processControlArguments = new ProcessControlArguments();
        }

        public InputFilterArguments Filters
        {
            get { return _inputFilterArguments; }
        }

        public ProcessControlArguments ProcessArguments
        {
            get { return _processControlArguments; }
        }

        public OutputFilterArguments OutputArguments
        {
            get { return _outputArguments; }
        }

        public void PickArgument(string argumentSwitch, string argumentParameter)
        {
            if (!IsKnown(argumentSwitch))
                throw new Exception();

            //TODO: BaseArgumentType for all three types of arguments?

            if (_inputFilterArguments.IsKnown(argumentSwitch))
            {
                _inputFilterArguments.Add(argumentSwitch, argumentParameter);
            }

            if (_outputArguments.IsKnown(argumentSwitch))
            {
                _outputArguments.Add(argumentSwitch, argumentParameter);
                return;
            }

            if (_processControlArguments.IsKnown(argumentSwitch))
            {
                _processControlArguments.Add(argumentSwitch, argumentParameter);
            }
        }

        public bool IsKnown(string @switch)
        {
            return _inputFilterArguments.IsKnown(@switch)
                   || _outputArguments.IsKnown(@switch)
                   || _processControlArguments.IsKnown(@switch);
        }
    }
}


text:
/*
 *	gmkincludefile.cpp
 *	GMK Include File
 */

#include <gmkincludefile.hpp>

namespace Gmk
{
	IncludeFile::IncludeFile(GmkFile* gmk)
		: GmkResource(gmk),
		  filename(""),
		  filepath(""),
		  originalFile(false),
		  originalFileSize(0),
		  data(NULL),
		  exportKind(EkDont),
		  exportPath(""),
		  overwrite(false),
		  freeMemory(true),
		  removeAtEndOfGame(true)
	{
		exists = true;
	}

	IncludeFile::~IncludeFile()
	{
		if (data != NULL)
			delete data;
	}

	void IncludeFile::WriteVer81(Stream* stream)
	{
		Stream* includeFileStream = new Stream();

		includeFileStream->WriteTimestamp();
		includeFileStream->WriteDword(800);
		includeFileStream->WriteString(filename);
		includeFileStream->WriteString(filepath);
		includeFileStream->WriteBoolean(originalFile);
		includeFileStream->WriteDword(originalFileSize);

		if (data != NULL)
		{
			includeFileStream->WriteBoolean(true);
			includeFileStream->Serialize(data, false);
		}
		else
			includeFileStream->WriteBoolean(false);

		includeFileStream->WriteDword(exportKind);
		includeFileStream->WriteString(exportPath);
		includeFileStream->WriteBoolean(overwrite);
		includeFileStream->WriteBoolean(freeMemory);
		includeFileStream->WriteBoolean(removeAtEndOfGame);

		stream->Serialize(includeFileStream);
		delete includeFileStream;
	}

	void IncludeFile::ReadVer81(Stream* stream)
	{
		Stream* includeFileStream = stream->Deserialize();

		includeFileStream->ReadTimestamp();
		includeFileStream->ReadDword();
		filename				= includeFileStream->ReadString();
		filepath				= includeFileStream->ReadString();
		originalFile			= includeFileStream->ReadBoolean();
		originalFileSize		= includeFileStream->ReadDword();

		if (includeFileStream->ReadBoolean())
			data = includeFileStream->Deserialize(false);
		else
			data = NULL;

		exportKind				= includeFileStream->ReadDword();
		exportPath				= includeFileStream->ReadString();
		overwrite				= includeFileStream->ReadBoolean();
		freeMemory				= includeFileStream->ReadBoolean();
		removeAtEndOfGame		= includeFileStream->ReadBoolean();

		delete includeFileStream;
	}

	void IncludeFile::WriteVer7(Stream* stream)
	{

	}

	void IncludeFile::ReadVer7(Stream* stream)
	{

	}
}


text:
Cloud-native architectures are typically composed of multiple layers of distributed services. End-user requests may comprise multiple calls to these services, and if a lower-level service fails, the failure can cascade up to the end user and spread to other dependent services. Heavy traffic to a failing service can also make it difficult to repair. Using Circuit Breaker Dashboard, you can monitor a service for failure, prevent failures from cascading, and supply dependent services until the failing service is operable again.

The code to create a circuit breaker involved providing a fallback method. For example:

```java
  @HystrixCommand(fallbackMethod = "getCompaniesFallback")
	public List<CompanyInfo> getCompanies(String name) {
		logger.debug("Fetching companies with name or symbol matching: " + name);
		CompanyInfo[] infos = restTemplate.getForObject("http://quotes/company/{name}", CompanyInfo[].class, name);
		return Arrays.asList(infos);
	}

	private List<CompanyInfo> getCompaniesFallback(String name) {
		List<CompanyInfo> infos = new ArrayList<>();
		return infos;
	}
```
It is useful to know when the circuits are open as it may suggest a problem with the dependent services. [Spring Cloud Services for Pivotal Cloud Foundry](https://network.pivotal.io/products/p-spring-cloud-services) provides a centralised dashboard to collect all the statistics from circuit breakers and visualize them in one place.

Underneath the covers, this circuit breaker pattern is implemented using the [Spring Cloud Netflix - Hystrix](http://cloud.spring.io/spring-cloud-netflix/).

In order to make use of the dashboard, we need to create an instance of the service to bind it to our applications.
### Exercise

1. Log in to the Apps Manager through your browser. The URL will be: `https://console.<your_cloud_foundry_url>/`

Go the *Marketplace* and choose a *Circuit Breaker for Pivotal Cloud Foundry standard*.

When prompted for the name of the service, insert **"circuit-breaker-dashboard"** and bind it to the space you are using to deploy your applications.

> You can pick any name of the service, however, the service is already specified in the manifest files, so it is easier to re-use that name. If you do modify the name, ensure you modify it in the manifest files as well.

# Summary

The circuit breaker dashboard can be accessed on the link provided in the console UI. Find the circuit breaker service you created and click on **Manage**.

You can now move on to [pushing the quote service](lab_pushquote.md)


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: sw=4 ts=4 et :
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "DeadlockDetector.h"

namespace mozilla {
const CallStack CallStack::kNone((CallStack::callstack_id) -1);
}


text:
import { transform, TransformOptions } from 'buble'
import walkes from 'walkes'
import {
	EvaluableComponent,
	isCodeVueSfc,
	isVue3,
	compileTemplateForEval,
  transformOneImport
} from 'vue-inbrowser-compiler-utils'
import normalizeSfcComponent, {
	parseScriptCode,
	getRenderFunctionStart,
	insertCreateElementFunction,
	JSX_ADDON_LENGTH
} from './normalizeSfcComponent'
import getAst from './getAst'
import getTargetFromBrowser from './getTargetFromBrowser'

interface EvaluableComponentWithSource extends EvaluableComponent {
	raw: {
		script: string
		template?: string
	}
}

/**
 * Reads the code as a string, separates the javascript part from the template & style parts,
 * then replaces the imports with requires and returns the script code as the body of a function.
 *
 * - For Vue2 the function compiles the template into a render function and adds the new function to the evaluated code.
 * - For Vue3 you have to use the compileVue3Template function yourself to compile the template into a function.
 * @param code
 * @param config buble config to be used when transforming
 *
 */
export default function compileVueCodeForEvalFunction(
	code: string,
	config: TransformOptions = {}
): EvaluableComponentWithSource {
	const nonCompiledComponent = prepareVueCodeForEvalFunction(code, config)
	const target = typeof window !== 'undefined' ? getTargetFromBrowser() : {}

	const compiledComponent = {
		...nonCompiledComponent,
		script: transform(nonCompiledComponent.script, { target, ...config }).code
	}

	compileTemplateForEval(compiledComponent)

	return {
		...compiledComponent,
		raw: nonCompiledComponent
	}
}

function prepareVueCodeForEvalFunction(code: string, config: any): EvaluableComponent {
	let style
	let vsgMode = false
	let template

	// if the component is written as a Vue sfc,
	// transform it in to a "return"
	// even if jsx is used in an sfc we still use this use case
	if (isCodeVueSfc(code)) {
		return normalizeSfcComponent(code)
	}

	// if it's not a new Vue, it must be a simple template or a vsg format
	// lets separate the template from the script
	if (!/new Vue\(/.test(code)) {
		// this for jsx examples without the SFC shell
		// export default {render: (h) => <Button>}
		if (config.jsx) {
			const { preprocessing, component, postprocessing } = parseScriptCode(code)
			return {
				script: `${preprocessing};return {${component}};${postprocessing}`
			}
		}

		const findStartTemplateMatch = /^\W*</.test(code) ? { index: 0 } : code.match(/\n[\t ]*</)
		const limitScript =
			findStartTemplateMatch && findStartTemplateMatch.index !== undefined
				? findStartTemplateMatch.index
				: -1
		template = limitScript > -1 ? code.slice(limitScript) : undefined
		code = limitScript > -1 ? code.slice(0, limitScript) : code
		vsgMode = true
	}
	const ast = getAst(code)
	let offset = 0
	const varNames: string[] = []
	walkes(ast, {
		// replace `new Vue({data})` by `return {data}`
		ExpressionStatement(node: any) {
			if (node.expression.type === 'NewExpression' && node.expression.callee.name === 'Vue') {
				const before = code.slice(0, node.expression.start + offset)
				const optionsNode =
					node.expression.arguments && node.expression.arguments.length
						? node.expression.arguments[0]
						: undefined
				const renderIndex = getRenderFunctionStart(optionsNode)
				let endIndex = optionsNode.end
				if (renderIndex > 0 && !isVue3) {
					code = insertCreateElementFunction(
						code.slice(0, renderIndex + 1),
						code.slice(renderIndex + 1)
					)
					endIndex += JSX_ADDON_LENGTH
				}
				const after = optionsNode ? code.slice(optionsNode.start + offset, endIndex + offset) : ''
				code = before + ';return ' + after
			}
		},
		// transform all imports into require function calls
		ImportDeclaration(node: any) {
			const ret = transformOneImport(node, code, offset)
			offset = ret.offset
			code = ret.code
			if (vsgMode && node.specifiers) {
				node.specifiers.forEach((s: any) => varNames.push(s.local.name))
			}
		},
		...(vsgMode
			? {
					VariableDeclaration(node: any) {
						node.declarations.forEach((declaration: any) => {
							if (declaration.id.name) {
								// simple variable declaration
								varNames.push(declaration.id.name)
							} else if (declaration.id.properties) {
								// spread variable declaration
								// const { all:names } = {all: 'foo'}
								declaration.id.properties.forEach((p: any) => {
									varNames.push(p.value.name)
								})
							}
						})
					},
					FunctionDeclaration(node: any) {
						varNames.push(node.id.name)
					}
			  }
			: {})
	})
	if (vsgMode) {
		code += `;return {data:function(){return {${
			// add local vars in data
			// this is done through an object like {varName: varName}
			// since each varName is defined in compiledCode, it can be used to init
			// the data object here
			varNames.map(varName => `${varName}:${varName}`).join(',')
		}};}}`
	}
	return {
		script: code,
		style,
		template
	}
}


text:
namespace remoting {

namespace {

constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
    net::DefineNetworkTrafficAnnotation(
        "remoting_register_support_host_request",
        R"(
        semantics {
          sender: "Chrome Remote Desktop"
          description:
            "Request used by Chrome Remote Desktop to register a new remote "
            "support host."
          trigger:
            "User requests for remote assistance using Chrome Remote Desktop."
          data:
            "The user's OAuth token for Chrome Remote Desktop (CRD) and CRD "
            "host information such as CRD host public key, host version, and "
            "OS version."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This request cannot be stopped in settings, but will not be sent "
            "if the user does not use Chrome Remote Desktop."
          policy_exception_justification:
            "Not implemented."
        })");

constexpr char kRegisterSupportHostPath[] =
    "/v1/remotesupport:registersupporthost";

protocol::ErrorCode MapError(ProtobufHttpStatus::Code status_code) {
  switch (status_code) {
    case ProtobufHttpStatus::Code::OK:
      return protocol::ErrorCode::OK;
    case ProtobufHttpStatus::Code::DEADLINE_EXCEEDED:
      return protocol::ErrorCode::SIGNALING_TIMEOUT;
    case ProtobufHttpStatus::Code::PERMISSION_DENIED:
    case ProtobufHttpStatus::Code::UNAUTHENTICATED:
      return protocol::ErrorCode::AUTHENTICATION_FAILED;
    default:
      return protocol::ErrorCode::SIGNALING_ERROR;
  }
}

}  // namespace

class RemotingRegisterSupportHostRequest::RegisterSupportHostClientImpl final
    : public RegisterSupportHostClient {
 public:
  RegisterSupportHostClientImpl(
      OAuthTokenGetter* token_getter,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);

  RegisterSupportHostClientImpl(const RegisterSupportHostClientImpl&) = delete;
  RegisterSupportHostClientImpl& operator=(
      const RegisterSupportHostClientImpl&) = delete;

  ~RegisterSupportHostClientImpl() override;

  void RegisterSupportHost(
      std::unique_ptr<apis::v1::RegisterSupportHostRequest> request,
      RegisterSupportHostResponseCallback callback) override;
  void CancelPendingRequests() override;

 private:
  ProtobufHttpClient http_client_;
};

RemotingRegisterSupportHostRequest::RegisterSupportHostClientImpl::
    RegisterSupportHostClientImpl(
        OAuthTokenGetter* token_getter,
        scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : http_client_(ServiceUrls::GetInstance()->remoting_server_endpoint(),
                   token_getter,
                   url_loader_factory) {}

RemotingRegisterSupportHostRequest::RegisterSupportHostClientImpl::
    ~RegisterSupportHostClientImpl() = default;

void RemotingRegisterSupportHostRequest::RegisterSupportHostClientImpl::
    RegisterSupportHost(
        std::unique_ptr<apis::v1::RegisterSupportHostRequest> request,
        RegisterSupportHostResponseCallback callback) {
  auto request_config =
      std::make_unique<ProtobufHttpRequestConfig>(kTrafficAnnotation);
  request_config->path = kRegisterSupportHostPath;
  request_config->request_message = std::move(request);
  auto http_request =
      std::make_unique<ProtobufHttpRequest>(std::move(request_config));
  http_request->SetResponseCallback(std::move(callback));
  http_client_.ExecuteRequest(std::move(http_request));
}

void RemotingRegisterSupportHostRequest::RegisterSupportHostClientImpl::
    CancelPendingRequests() {
  http_client_.CancelPendingRequests();
}

// End of RegisterSupportHostClientImpl.

RemotingRegisterSupportHostRequest::RemotingRegisterSupportHostRequest(
    std::unique_ptr<OAuthTokenGetter> token_getter,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : token_getter_(std::move(token_getter)),
      register_host_client_(std::make_unique<RegisterSupportHostClientImpl>(
          token_getter_.get(),
          url_loader_factory)) {}

RemotingRegisterSupportHostRequest::~RemotingRegisterSupportHostRequest() {
  if (signal_strategy_) {
    signal_strategy_->RemoveListener(this);
  }
}

void RemotingRegisterSupportHostRequest::StartRequest(
    SignalStrategy* signal_strategy,
    scoped_refptr<RsaKeyPair> key_pair,
    RegisterCallback callback) {
  DCHECK_EQ(State::NOT_STARTED, state_);
  DCHECK(signal_strategy);
  DCHECK(key_pair);
  DCHECK(callback);
  signal_strategy_ = signal_strategy;
  key_pair_ = key_pair;
  callback_ = std::move(callback);

  signal_strategy_->AddListener(this);
}

void RemotingRegisterSupportHostRequest::OnSignalStrategyStateChange(
    SignalStrategy::State state) {
  switch (state) {
    case SignalStrategy::State::CONNECTED:
      RegisterHost();
      break;
    case SignalStrategy::State::DISCONNECTED:
      RunCallback({}, {}, protocol::ErrorCode::SIGNALING_ERROR);
      break;
    default:
      // Do nothing.
      break;
  }
}

bool RemotingRegisterSupportHostRequest::OnSignalStrategyIncomingStanza(
    const jingle_xmpp::XmlElement* stanza) {
  return false;
}

void RemotingRegisterSupportHostRequest::RegisterHost() {
  DCHECK_EQ(SignalStrategy::CONNECTED, signal_strategy_->GetState());
  if (state_ != State::NOT_STARTED) {
    return;
  }
  state_ = State::REGISTERING;

  auto request = std::make_unique<apis::v1::RegisterSupportHostRequest>();
  request->set_public_key(key_pair_->GetPublicKey());
  request->set_tachyon_id(signal_strategy_->GetLocalAddress().id());
  request->set_host_version(STRINGIZE(VERSION));
  request->set_host_os_name(GetHostOperatingSystemName());
  request->set_host_os_version(GetHostOperatingSystemVersion());

  register_host_client_->RegisterSupportHost(
      std::move(request),
      base::BindOnce(&RemotingRegisterSupportHostRequest::OnRegisterHostResult,
                     base::Unretained(this)));
}

void RemotingRegisterSupportHostRequest::OnRegisterHostResult(
    const ProtobufHttpStatus& status,
    std::unique_ptr<apis::v1::RegisterSupportHostResponse> response) {
  if (!status.ok()) {
    state_ = State::NOT_STARTED;
    RunCallback({}, {}, MapError(status.error_code()));
    return;
  }
  state_ = State::REGISTERED;
  base::TimeDelta lifetime =
      base::Seconds(response->support_id_lifetime_seconds());
  RunCallback(response->support_id(), lifetime, protocol::ErrorCode::OK);
}

void RemotingRegisterSupportHostRequest::RunCallback(
    const std::string& support_id,
    base::TimeDelta lifetime,
    protocol::ErrorCode error_code) {
  if (!callback_) {
    // Callback has already been run, so just return.
    return;
  }

  // Cleanup state before calling the callback.
  register_host_client_->CancelPendingRequests();
  signal_strategy_->RemoveListener(this);
  signal_strategy_ = nullptr;

  std::move(callback_).Run(support_id, lifetime, error_code);
}

}  // namespace remoting


text:
2 factor authentication plugin for Hapi

[![BuildStatus](https://img.shields.io/travis/nrotta/hapi-auth-2fa/master.svg?style=flat-square)](https://travis-ci.org/nrotta/hapi-auth-2fa)
[![NPM version](https://img.shields.io/npm/v/hapi-auth-2fa.svg?style=flat-square)](https://www.npmjs.com/package/hapi-auth-2fa)

This plugin provides 2 factor authentication to your hapi application.

Check out the code under `example` for a working example of form based email / password and 2 factor authentication

This library is heavily based on [hapi-authy] (https://github.com/mtharrison/hapi-authy)