text:
Namespace Authentication

	'''
	''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
	''' <generator-date>01/02/2014 12:15:17</generator-date>
	''' <generator-functions>1</generator-functions>
	''' <generator-source>Hermes_\_Authentication\Generated\Request.tt</generator-source>
	''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
	''' <generator-version>1</generator-version>
	<System.CodeDom.Compiler.GeneratedCode("Hermes_\_Authentication\Generated\Request.tt", "1")> _
	Partial Public Class Request
		Inherits System.Object

		#Region " Public Constructors "

			''' Default Constructor
			Public Sub New()

				MyBase.New()

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (1 Parameters)
			Public Sub New( _
				ByVal _Username As System.String _
			)

				MyBase.New()

				Username = _Username

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (2 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String _
			)

				MyBase.New()

				Username = _Username
				Password = _Password

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (3 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (4 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String, _
				ByVal _Source As System.String _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain
				Source = _Source

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (5 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String, _
				ByVal _Source As System.String, _
				ByVal _Agent As System.String _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain
				Source = _Source
				Agent = _Agent

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (6 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String, _
				ByVal _Source As System.String, _
				ByVal _Agent As System.String, _
				ByVal _Persistant As System.Boolean _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain
				Source = _Source
				Agent = _Agent
				Persistant = _Persistant

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (7 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String, _
				ByVal _Source As System.String, _
				ByVal _Agent As System.String, _
				ByVal _Persistant As System.Boolean, _
				ByVal _Site As System.String _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain
				Source = _Source
				Agent = _Agent
				Persistant = _Persistant
				Site = _Site

				m_Created = DateTime.Now()
			End Sub

			''' Parametered Constructor (8 Parameters)
			Public Sub New( _
				ByVal _Username As System.String, _
				ByVal _Password As System.String, _
				ByVal _Domain As System.String, _
				ByVal _Source As System.String, _
				ByVal _Agent As System.String, _
				ByVal _Persistant As System.Boolean, _
				ByVal _Site As System.String, _
				ByVal _Created As System.DateTime _
			)

				MyBase.New()

				Username = _Username
				Password = _Password
				Domain = _Domain
				Source = _Source
				Agent = _Agent
				Persistant = _Persistant
				Site = _Site
				m_Created = _Created

			End Sub

		#End Region

		#Region " Public Constants "

			''' Public Shared Reference to the Name of the Property: Username
			''' <remarks></remarks>
			Public Const PROPERTY_USERNAME As String = "Username"

			''' Public Shared Reference to the Name of the Property: Password
			''' <remarks></remarks>
			Public Const PROPERTY_PASSWORD As String = "Password"

			''' Public Shared Reference to the Name of the Property: Domain
			''' <remarks></remarks>
			Public Const PROPERTY_DOMAIN As String = "Domain"

			''' Public Shared Reference to the Name of the Property: Source
			''' <remarks></remarks>
			Public Const PROPERTY_SOURCE As String = "Source"

			''' Public Shared Reference to the Name of the Property: Agent
			''' <remarks></remarks>
			Public Const PROPERTY_AGENT As String = "Agent"

			''' Public Shared Reference to the Name of the Property: Persistant
			''' <remarks></remarks>
			Public Const PROPERTY_PERSISTANT As String = "Persistant"

			''' Public Shared Reference to the Name of the Property: Site
			''' <remarks></remarks>
			Public Const PROPERTY_SITE As String = "Site"

			''' Public Shared Reference to the Name of the Property: Created
			''' <remarks></remarks>
			Public Const PROPERTY_CREATED As String = "Created"

		#End Region

		#Region " Private Variables "

			''' Private Data Storage Variable for Property: Username
			''' <remarks></remarks>
			Private m_Username As System.String

			''' Private Data Storage Variable for Property: Password
			''' <remarks></remarks>
			Private m_Password As System.String

			''' Private Data Storage Variable for Property: Domain
			''' <remarks></remarks>
			Private m_Domain As System.String

			''' Private Data Storage Variable for Property: Source
			''' <remarks></remarks>
			Private m_Source As System.String

			''' Private Data Storage Variable for Property: Agent
			''' <remarks></remarks>
			Private m_Agent As System.String

			''' Private Data Storage Variable for Property: Persistant
			''' <remarks></remarks>
			Private m_Persistant As System.Boolean

			''' Private Data Storage Variable for Property: Site
			''' <remarks></remarks>
			Private m_Site As System.String

			''' Private Data Storage Variable for Property: Created
			''' <remarks></remarks>
			Private m_Created As System.DateTime

		#End Region

		#Region " Public Properties "

			''' Provides Access to the Property: Username
			''' <remarks></remarks>
			Public Property Username() As System.String
				Get
					Return m_Username
				End Get
				Set(value As System.String)
					m_Username = value
				End Set
			End Property

			''' Provides Access to the Property: Password
			''' <remarks></remarks>
			Public Property Password() As System.String
				Get
					Return m_Password
				End Get
				Set(value As System.String)
					m_Password = value
				End Set
			End Property

			''' Provides Access to the Property: Domain
			''' <remarks></remarks>
			Public Property Domain() As System.String
				Get
					Return m_Domain
				End Get
				Set(value As System.String)
					m_Domain = value
				End Set
			End Property

			''' Provides Access to the Property: Source
			''' <remarks></remarks>
			Public Property Source() As System.String
				Get
					Return m_Source
				End Get
				Set(value As System.String)
					m_Source = value
				End Set
			End Property

			''' Provides Access to the Property: Agent
			''' <remarks></remarks>
			Public Property Agent() As System.String
				Get
					Return m_Agent
				End Get
				Set(value As System.String)
					m_Agent = value
				End Set
			End Property

			''' Provides Access to the Property: Persistant
			''' <remarks></remarks>
			Public Property Persistant() As System.Boolean
				Get
					Return m_Persistant
				End Get
				Set(value As System.Boolean)
					m_Persistant = value
				End Set
			End Property

			''' Provides Access to the Property: Site
			''' <remarks></remarks>
			Public Property Site() As System.String
				Get
					Return m_Site
				End Get
				Set(value As System.String)
					m_Site = value
				End Set
			End Property

			''' Provides Access to the Property: Created
			''' <remarks></remarks>
			Public ReadOnly Property Created() As System.DateTime
				Get
					Return m_Created
				End Get
			End Property

		#End Region

	End Class

End Namespace


text:
<?php
namespace WigeDev\SimpleMVC\Utility;

use WigeDev\SimpleMVC\Core;

/**
 * Class Configuration
 *
 * The configuration class manages the configuration settings for the application, providing parsing of the config files
 * in a specified directory or directories, and providing access to the configuration settings.
 *
 * All configuration files are expected to be in the form of nested arrays. At least one configuration file must have
 * an array called 'core' that has the overall settings for the application, and should at a minimum specify the log.
 *
 * If two configurations have overlapping settings, the system will attempt to merge them, with new settings replacing
 * old settings if they exist. For this reason, it is not recommended to parse an entire folder that has conflicting or
 * overlapping configurations, as the results may be unpredictable.
 */
class Configuration
{
    protected $parsed_files = array();
    protected $configuration = array();
    static $iteration = 0;

    public function __construct(?string $config_path = null)
    {
        if (is_dir($config_path)) {
            $this->parseFolder($config_path);
        } elseif (is_file($config_path)) {
            $this->parseFile($config_path);
        }
    }

    /**
     * Process the specified folder for log files, processing each file in turn. This is NOT recursive.
     *
     * @param string $path The path to the folder
     */
    public function parseFolder(string $path): void
    {
        //TODO: Implement me!
    }

    /**
     * Process a single file's configuration settings.
     *
     * @param string $path The path to the configuration file
     *
     * @return bool True if the file is parsed successfully or skipped because it has already been parsed
     */
    public function parseFile(string $path): bool
    {
        static::$iteration++;
        if (static::$iteration > 10) exit();
        if (in_array($path, $this->parsed_files)) {
            // The file has already been parsed, don't parse it again
            return true;
        }
        $this->parsed_files[] = $path;
        if (is_readable($path)) {
            $array = include($path);
        } else {
            if (isset(Core::i()->log)) {
                Core::i()->log->debug('Config path ' . $path . ' could not be read.');
            }
            return false;
        }
        if (!is_array($array)) {
            if (isset(Core::i()->log)) {
                Core::i()->log->debug('Config file ' . $path . ' is not an array.');
            }
            return false;
        }
        $this->parseArray($array);
        return true;
    }

    /**
     * Process an array of configuration settings
     *
     * @param array $array
     */
    public function parseArray(array $array): void
    {
        $this->configuration = array_merge_recursive($this->configuration, $array);
    }

    public function getConfiguration(string $category): array
    {
        $return = [];
        if (isset($this->configuration[$category])) {
            $return = $this->configuration[$category];
        }
        return $return;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Plantillas
==========

Estas son las plantillas comunes.

Plantillas de registro
----------------------

Plantillas de confirmación
--------------------------

Plantillas de recuperación
--------------------------


text:
<?php

/* GPIOfferBundle:Offer:details.html.twig */
class __TwigTemplate_a1abf74541fd19c05e9a41408832b623715cff7822aa08506735b36b61bad057 extends Sonata\CacheBundle\Twig\TwigTemplate14
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
";
        // line 2
        if ((isset($context["isDeactivated"]) ? $context["isDeactivated"] : $this->getContext($context, "isDeactivated"))) {
            // line 3
            echo "
Oferta została wyłączona przez administratora

            Powód: ";
            // line 5
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["disableReason"]) ? $context["disableReason"] : $this->getContext($context, "disableReason")), "content", array()), "html", null, true);
            echo "

";
        } elseif ( !(isset($context["isActive"]) ? $context["isActive"] : $this->getContext($context, "isActive"))) {
            // line 8
            echo "
Oferta jest nieaktywna.

";
        }
        // line 10
        echo "

";
        // line 13
        echo $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "content", array());
        echo "

Szczegóły

Aukcja:env, $this->env->getExtension('routing')->getPath("gpi_auction_details", array("id" => $this->getAttribute($this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "getAuction", array(), "method"), "id", array()))), "html", null, true);
        echo "\">";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "getAuction", array(), "method"), "getName", array(), "method"), "html", null, true);
        echo "

Dodano przez: ";
        // line 20
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "getCreatedBy", array(), "method"), "html", null, true);
        echo "

Cena minimalna: ";
        // line 21
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "actualPrice", array()), "html", null, true);
        echo "

            ";
        // line 22
        if (($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "security", array()), "getToken", array(), "method"), "getUser", array(), "method") == $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "createdBy", array(), "method"))) {
            // line 23
            echo "
Dolny limit ceny: ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "price", array()), "html", null, true);
            echo "

                ";
            // line 24
            if ( !(null === $this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "bidPercent", array()))) {
                // line 25
                echo "
Procent przebicia: ";
                echo twig_escape_filter($this->env, ($this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "bidPercent", array()) * 100), "html", null, true);
                echo "%

                ";
            } else {
                // line 27
                echo "
Procent przebicia: Nie ustalono

                ";
            }
            // line 29
            echo "            ";
        }
        // line 30
        echo "

            ";
        // line 38
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["offer"]) ? $context["offer"] : $this->getContext($context, "offer")), "documents", array()));
        foreach ($context['_seq'] as $context["_key"] => $context["document"]) {
            // line 39
            echo "

                    env, $this->env->getExtension('assets')->getAssetUrl($this->getAttribute($context["document"], "getWebPath", array(), "method")), "html", null, true);
            echo "\" target=\"_blank\" class=\"cbp-caption cbp-lightbox\">

                            env, $this->env->getExtension('liip_imagine')->filter($this->env->getExtension('assets')->getAssetUrl($this->getAttribute($context["document"], "getWebPath", array(), "method")), "details_thumb"), "html", null, true);
            echo "\" alt=\"\" width=\"100%\">

";
            // line 47
            echo twig_escape_filter($this->env, $this->getAttribute($context["document"], "description", array()), "html", null, true);
            echo "

            ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['document'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 54
        echo "

";
    }

    public function getTemplateName()
    {
        return "GPIOfferBundle:Offer:details.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  131 => 54,  118 => 47,  110 => 42,  105 => 40,  102 => 39,  98 => 38,  88 => 30,  85 => 29,  81 => 27,  75 => 25,  73 => 24,  68 => 23,  66 => 22,  62 => 21,  58 => 20,  52 => 19,  43 => 13,  38 => 10,  34 => 8,  28 => 5,  24 => 3,  22 => 2,  19 => 1,);
    }
}


text:
import json
import socket

SOCKET_ADDRESS = "/var/run/pdinstall.sock"

def sendCommand(command, data):
    """
    Send a command to the pdinstall service.

    Commands:
    install - Install snaps from a file path or http(s) URL.
        Required data fields:
        sources - List with at least one snap file path or URL.  The snaps
                  are installed in order until one succeeds or all fail.

    Returns True/False for success.  Currently, we cannot check whether the
    call succeeded, only whether it was delived.  A return value of False means
    we could not deliver the command to pdinstall.
    """
    data['command'] = command

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect(SOCKET_ADDRESS)
        sock.send(json.dumps(data))
        return True
    except:
        return False
    finally:
        sock.close()


text:
#!/usr/bin/env node

'use strict';

import url from 'url';
import minimist from 'minimist';
import chalk from 'chalk';
import Github from 'github';
import editor from 'editor';
import fs from 'fs';
import logUpdate from 'log-update';
import randomstring from 'randomstring';
import {spawnSync} from 'child_process';

const argv = minimist(process.argv.slice(2), {
  boolean: ['noprogress']
});
const [command = 'list'] = argv._;
const {noprogress} = argv;
const {host, user, repo} = getUserRepo();
const token = getAccessToken(host);
const githubOption = getGithubOption(host);
const github = new Github(githubOption);
github.authenticate({token, type: 'token'});

if (command === 'list') {
  status('requesting issues');
  repoIssuesPromise()
    .then(issues => {
      clearStatus();
      showIssues(issues);
    })
    .catch(error);
}
else if (command === 'create') {
  getIssueMessagePromise()
    .then(({title, body}) => createPromise(title, body))
    .then(res => {
      clearStatus();
      console.log(res.url);
    })
    .catch(error);
}
else {
  let [, number] = argv._;

  typeof number !== 'number' && error('$ gic show/comment/close [issue_number]');

  if (command === 'show') {
    status(`requesting #${number} issue and comment`);
    Promise.all([getRepoIssuePromise(number), getCommentsPromise(number)])
      .then(([issue, comments]) => {
        clearStatus();
        showIssue(issue);
        showComments(number, comments);
      })
      .catch(error);
  }
  else if (command === 'comment') {
    getIssueMessagePromise(true)
      .then(({body}) => createCommentPromise(number, body))
      .then(res => {
        clearStatus();
        console.log(res.url);
      })
      .catch(error);
  }
  else if (command === 'close') {
    getIssueMessagePromise(true)
      .then(({body}) => body ? createCommentPromise(number, body) : true)
      .then(() => closePromise(number))
      .then(res => {
        clearStatus();
        console.log(res.url);
      })
      .catch(error);
  }
}

function repoIssuesPromise () {
  return createGithubIssuesPromise('repoIssues');
}

function createPromise (title, body) {
  return createGithubIssuesPromise('create', {title, body});
}

function getRepoIssuePromise (number) {
  return createGithubIssuesPromise('getRepoIssue', {number});
}

function getCommentsPromise (number) {
  return createGithubIssuesPromise('getComments', {number});
}

function createCommentPromise (number, body) {
  return createGithubIssuesPromise('createComment', {number, body});
}

function closePromise (number) {
  return createGithubIssuesPromise('edit', {number, state: 'closed'});
}

function createGithubIssuesPromise (api, option = {}) {
  return new Promise((resolve, reject) => {
    github.issues[api]({user, repo, ...option}, (err, res) => {
      err ? reject(err) : resolve(res);
    });
  });
}

function status (message) {
  !noprogress && logUpdate(`[${chalk.green('gic')}]`, message);
}

function clearStatus () {
  logUpdate.clear();
  logUpdate.done();
}

function error (...messages) {
  clearStatus();
  messages.forEach(message => {
    console.error(chalk.red(message));
  });
  process.exit(0);
}

function getUserRepo () {
  status('getting user/repo');
  let origin = getOriginUrl();
  let {hostname, pathname} = url.parse(origin);
  let [, user, repo] = pathname.replace(/\.git$/, '').split('/');

  (!hostname || !user || !repo) && error(
    'Miss getting Github information(host, user, repo).',
    'Is not git repository here?.'
  );

  return {host: hostname, user, repo};
}

function getOriginUrl () {
  return getLocalOriginUrl() || getRemoteOriginUrl();
}

// $ git config --get remote.origin.url
function getLocalOriginUrl () {
  return spawnSync('git', ['config', '--get', 'remote.origin.url']).stdout.toString();
}

// $ git remote show origin
function getRemoteOriginUrl () {
  let remoteInformation = spawnSync('git', ['remote', 'show', 'origin']);
  return remoteInformation.stdout.toString().split('\n')
    .filter(line => /^Fetch URL/.test(line))
    .map(line => line.trim().replace(/^Fetch URL: /, ''))
    .pop();
}

// $ git config --get gic.github.com.token
// $ git config --get gic.github.enterprise.token
function getAccessToken (host = 'github.com') {
  status('getting access token');
  const token = spawnSync('git', ['config', '--get', `gic.${host}.token`]).stdout.toString();

  (!token || !token.length) && error(
    'gic want your access token.',
    '$ git config --global gic.github.com.token ${YOUR ACCESSTOKEN}',
    'if you use Github Enterprise, set below.',
    '$ git config --global gic.GITHUB.ENTERPRISE.HOST.token ${YOUR ACCESSTOKEN}'
  );

  return token;
}

function getGithubOption (host) {
  const githubOption = {
    version: '3.0.0',
    protocol: 'https',
    timeout: 5000
  };

  if (host !== 'github.com') {
    return {host, pathPrefix: '/api/v3', ...githubOption};
  }
  return githubOption;
}

function getIssueMessagePromise (isBody) {
  let filename = `.${randomstring.generate()}.gic`;
  fs.writeFileSync(filename, '', 'utf-8');

  return new Promise(resolve => {
    editor(filename, () => {
      let message = fs.readFileSync(filename, 'utf-8');
      let [title = '', ...bodyLine] = message.split('\n');
      let body = isBody ? message.trim() : bodyLine.join('\n').trim();
      fs.unlinkSync(filename);
      resolve({title, body});
    });
  });
}

function showIssues (issues) {
  console.log(chalk.yellow(`${user}/${repo} has ${issues.length} issues`));

  issues.sort(compareIssue).forEach(issue => {
    let {number, title/*, user, assignee, comments*/, pull_request} = issue;
    let numberLabel = `#${number}`;
    if (pull_request) {
      numberLabel = `[${numberLabel}]`;
    }
    console.log(
      chalk.green(`  ${numberLabel}`),
      chalk.bold(title)
    );
  });
}

function compareIssue (aIssue, bIssue) {
  if (aIssue.number > bIssue.number) {
    return 1;
  }
  if (aIssue.number < bIssue.number) {
    return -1;
  }
  return 0;
}

function showIssue (issue) {
  let {title, body, labels, milestone, assignee} = issue;

  labels.length && console.log(chalk.underline(`labels: ${labels.map(label => label.name).join(', ')}`));
  milestone && console.log(chalk.underline(`milestone: ${milestone.title}`));
  assignee && console.log(chalk.underline(`assignee: @${assignee.login}`));
  console.log(chalk.yellow.bold(`# ${title}`));
  body ? console.log(`${body}`) : console.log(chalk.gray.dim('No description provided.'));
}

function showComments (number, comments) {
  comments.forEach(comment => {
    let {body, user} = comment;

    console.log('\n ', chalk.blue(`> @${user.login}`));
    console.log(' ', `${body.replace(/\n/g, '\n  ')}`);
  });
}


text: require("style!css!less!./bootstrap-styles!./bootstrap.config.js");


text:
<footer class="organism-footer">
	<small class="atom-small">
		developed with love by microscope
	</small>
</footer>


text:
package com.helger.commons.text.display;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.util.Locale;

import org.junit.Test;

import com.helger.commons.mock.CommonsTestHelper;

/**
 * Test class for class {@link HasDisplayTextWithArgs}.
 *
 * @author Philip Helger
 */
public final class HasDisplayTextWithArgsTest
{
  private static final Locale L_DE = new Locale ("de");
  private static final Locale L_FR = new Locale ("fr");

  @Test
  public void testAll ()
  {
    final IHasDisplayText t = new MockHasDisplayText (L_DE, "Hallo {0}");
    final HasDisplayTextWithArgs x = new HasDisplayTextWithArgs (t, "Welt");
    assertEquals ("Hallo Welt", x.getDisplayText (L_DE));
    assertNull (x.getDisplayText (L_FR));
    CommonsTestHelper.testToStringImplementation (x);

    try
    {
      // null parent
      new HasDisplayTextWithArgs (null, "abc");
      fail ();
    }
    catch (final NullPointerException ex)
    {}

    try
    {
      // no arguments
      new HasDisplayTextWithArgs (new MockHasDisplayText (L_DE, "de"));
      fail ();
    }
    catch (final IllegalArgumentException ex)
    {}
  }
}


text:
package marketdata
import akka.actor.{Props, Actor}
import akka.actor.ActorSystem
import com.typesafe.config.{Config, ConfigFactory}
import scala.collection.JavaConverters._
import marketdata.MarketDataTypes.{MarketDataType,TickDataType,TradeDataType}

object MarketDataApp extends App {
    val sysName : String = "marketdata-usd"
    val config = ConfigFactory.load()
    val marketdataConfig = config.getConfig(sysName).withFallback(config)
    lazy val actorSystem: ActorSystem = ActorSystem(sysName, marketdataConfig)

    val actors : List[String] =  marketdataConfig.getStringList("actors").asScala.toList
    val instrument : String =  marketdataConfig.getString("instrument")
    actors.foreach { actorName => actorSystem.actorOf(Props(new MarketDataFeedPublisherActor(actorName, instrument, List[MarketDataType] (TickDataType,TradeDataType))), actorName) }
    actorSystem.awaitTermination();
}


text:
//
//  AttributedPlainText.h
//  Notation
//
//  Created by Zachary Schneirov on 1/16/06.

#import <Cocoa/Cocoa.h>

#define SEPARATE_ATTRS 0

extern NSString *NVHiddenDoneTagAttributeName;
extern NSString *NVHiddenBulletIndentAttributeName;

@interface NSMutableAttributedString (AttributedPlainText)

- (void)trimLeadingWhitespace;
- (void)indentTextLists;
- (void)removeAttachments;
- (NSString*)prefixWithSourceString:(NSString*)source;

- (NSString*)trimLeadingSyntheticTitle;

#if SEPARATE_ATTRS
+ (NSMutableAttributedString*)attributedStringWithString:(NSString*)text attributesByRange:(NSDictionary*)attributes font:(NSFont*)font;
#endif
- (void)santizeForeignStylesForImporting;
- (void)addLinkAttributesForRange:(NSRange)changedRange;
- (void)_addDoubleBracketedNVLinkAttributesForRange:(NSRange)changedRange;
- (void)addStrikethroughNearDoneTagsForRange:(NSRange)changedRange;
- (BOOL)restyleTextToFont:(NSFont*)currentFont usingBaseFont:(NSFont*)baseFont;

@end

@interface NSAttributedString (AttributedPlainText)

- (BOOL)attribute:(NSString*)anAttribute existsInRange:(NSRange)aRange;

- (NSArray*)allLinks;
- (id)findNextLinkAtIndex:(unsigned int)startIndex effectiveRange:(NSRange *)range;
#if SEPARATE_ATTRS
//extract the attributes using their ranges as keys
- (NSDictionary*)attributesByRange;
#endif

+ (NSAttributedString*)timeDelayStringWithNumberOfSeconds:(double)seconds;

@end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Rawr.Retribution
{
    public class CombatStats
    {

        public CombatStats(Character character, Stats stats)
        {
            _stats = stats;
            _character = character;
            _calcOpts = _character.CalculationOptions as CalculationOptionsRetribution;
            _talents = _character.PaladinTalents;
            UpdateCalcs();
        }

        protected Character _character = new Character();
        public Character Character { get { return _character; } }

        protected Stats _stats = new Stats();
        public Stats Stats { get { return _stats; } }

        protected CalculationOptionsRetribution _calcOpts = new CalculationOptionsRetribution();
        public CalculationOptionsRetribution CalcOpts { get { return _calcOpts; } }

        protected PaladinTalents _talents = new PaladinTalents();
        public PaladinTalents Talents { get { return _talents; } }

        public float WeaponDamage;
        public float BaseWeaponSpeed;
        public float AttackSpeed;
        public float NormalWeaponDamage;

        public float AvengingWrathMulti = 1f;
        public float ArmorReduction = 1f;
        public readonly float PartialResist = 0.94f;

        public float GetMeleeMissChance()    // Chance to miss a white/yellow
        {
            return (float)Math.Max(StatConversion.WHITE_MISS_CHANCE_CAP[_calcOpts.TargetLevel - 80] - _stats.PhysicalHit, 0f);
        }
        public float GetRangedMissChance()    // Chance to miss a ranged attack (HoW)
        {
            // Should be 'RangedHit' instead of PhysicalHit, pala's won't be gearing for specific ranged hit, and there's no RangedHit stat in Stats (only RangedHitRating).
            return (float)Math.Max(StatConversion.WHITE_MISS_CHANCE_CAP[_calcOpts.TargetLevel - 80] - _stats.PhysicalHit, 0f);
        }
        public float GetToBeParriedChance()
        {
            return (float)Math.Max(StatConversion.WHITE_PARRY_CHANCE_CAP[_calcOpts.TargetLevel - 80] - StatConversion.GetDodgeParryReducFromExpertise(_stats.Expertise, CharacterClass.Paladin), 0f);
        }
        public float GetToBeDodgedChance()
        {
            return (float)Math.Max(StatConversion.WHITE_DODGE_CHANCE_CAP[_calcOpts.TargetLevel - 80] - StatConversion.GetDodgeParryReducFromExpertise(_stats.Expertise, CharacterClass.Paladin), 0f);
        }
        public float GetSpellMissChance()
        {
            return StatConversion.GetSpellMiss(_calcOpts.TargetLevel - 80, false);
        }

        public void UpdateCalcs()
        {
            float fightLength = _calcOpts.FightLength * 60f;

            float bloodlustUptime = ((float)Math.Floor(fightLength / 600f) * 40f + (float)Math.Min(fightLength % 600f, 40f)) / fightLength;
            float bloodlustHaste = 1f + (CalcOpts.Bloodlust ? (bloodlustUptime * .3f) : 0f);

            float awUptime = (float)Math.Ceiling((fightLength - 20f) / (180f - _talents.SanctifiedWrath * 30f)) * 20f / fightLength;
            AvengingWrathMulti = 1f + awUptime * .2f;

            float targetArmor = StatConversion.NPC_ARMOR[CalcOpts.TargetLevel - 80];

            float dr = StatConversion.GetArmorDamageReduction(Character.Level, targetArmor, Stats.ArmorPenetration, 0f, Stats.ArmorPenetrationRating);
            float drAW = dr * ((1 - awUptime) + (1 - .25f * _talents.SanctifiedWrath) * awUptime);
            float drNoAW = dr;
            ArmorReduction = 1f - drAW;

            BaseWeaponSpeed = (_character.MainHand == null || _character.MainHand.Speed == 0.0f) ? 3.5f : _character.MainHand.Speed; // NOTE by Kavan: added a check against speed == 0, it can happen when item data is still being downloaded
            float baseWeaponDamage = _character.MainHand == null ? 371.5f : (_character.MainHand.MinDamage + _character.MainHand.MaxDamage) / 2f;
            AttackSpeed = BaseWeaponSpeed / ((1f + _stats.PhysicalHaste) * bloodlustHaste);
            WeaponDamage = baseWeaponDamage + _stats.AttackPower * BaseWeaponSpeed / 14f;
            NormalWeaponDamage = baseWeaponDamage + _stats.AttackPower * 3.3f / 14f;
        }
    }
}


text:
/// <reference no-default-lib="true"/>

declare namespace Intl {

    interface DateTimeFormatPartTypesRegistry {
        fractionalSecond: any
     }

    interface DateTimeFormatOptions {
        formatMatcher?: "basic" | "best fit" | "best fit" | undefined;
        dateStyle?: "full" | "long" | "medium" | "short" | undefined;
        timeStyle?: "full" | "long" | "medium" | "short" | undefined;
        dayPeriod?: "narrow" | "short" | "long" | undefined;
        fractionalSecondDigits?: 1 | 2 | 3 | undefined;
    }

    interface DateTimeRangeFormatPart extends DateTimeFormatPart {
        source: "startRange" | "endRange" | "shared"
    }

    interface DateTimeFormat {
        formatRange(startDate: Date | number | bigint, endDate: Date | number | bigint): string;
        formatRangeToParts(startDate: Date | number | bigint, endDate: Date | number | bigint): DateTimeRangeFormatPart[];
    }

    interface ResolvedDateTimeFormatOptions {
        formatMatcher?: "basic" | "best fit" | "best fit";
        dateStyle?: "full" | "long" | "medium" | "short";
        timeStyle?: "full" | "long" | "medium" | "short";
        hourCycle?: "h11" | "h12" | "h23" | "h24";
        dayPeriod?: "narrow" | "short" | "long";
        fractionalSecondDigits?: 1 | 2 | 3;
    }

    /**
     * The locale matching algorithm to use.
     *
     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
     */
    type ListFormatLocaleMatcher = "lookup" | "best fit";

    /**
     * The format of output message.
     *
     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
     */
    type ListFormatType = "conjunction" | "disjunction" | "unit";

    /**
     * The length of the formatted message.
     *
     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
     */
    type ListFormatStyle = "long" | "short" | "narrow";

    /**
     * An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter.
     *
     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
     */
    interface ListFormatOptions {
        /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
        localeMatcher?: ListFormatLocaleMatcher | undefined;
        /** The format of output message. */
        type?: ListFormatType | undefined;
        /** The length of the internationalized message. */
        style?: ListFormatStyle | undefined;
    }

    interface ListFormat {
        /**
         * Returns a string with a language-specific representation of the list.
         *
         * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
         *
         * @throws `TypeError` if `list` includes something other than the possible values.
         *
         * @returns {string} A language-specific formatted string representing the elements of the list.
         *
         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format).
         */
        format(list: Iterable<string>): string;

        /**
         * Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
         *
         * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale.
         *
         * @throws `TypeError` if `list` includes something other than the possible values.
         *
         * @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list.
         *
         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts).
         */
        formatToParts(list: Iterable<string>): { type: "element" | "literal", value: string; }[];
    }

    const ListFormat: {
        prototype: ListFormat;

        /**
         * Creates [Intl.ListFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that
         * enable language-sensitive list formatting.
         *
         * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
         *  For the general form and interpretation of the `locales` argument,
         *  see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
         *
         * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters)
         *  with some or all options of `ListFormatOptions`.
         *
         * @returns [Intl.ListFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object.
         *
         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat).
         */
        new(locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: ListFormatOptions): ListFormat;

        /**
         * Returns an array containing those of the provided locales that are
         * supported in list formatting without having to fall back to the runtime's default locale.
         *
         * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
         *  For the general form and interpretation of the `locales` argument,
         *  see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
         *
         * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters).
         *  with some or all possible options.
         *
         * @returns An array of strings representing a subset of the given locale tags that are supported in list
         *  formatting without having to fall back to the runtime's default locale.
         *
         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf).
         */
        supportedLocalesOf(locales: BCP47LanguageTag | BCP47LanguageTag[], options?: Pick<ListFormatOptions, "localeMatcher">): BCP47LanguageTag[];
    };
}


text:
package com.jcwhatever.nucleus.localizer;

import java.io.File;
import java.io.IOException;

public class Main {

    public static void main(String args[]) {

        if (args.length != 2) {
            printHelp();
            return;
        }

        String inputJarName = args[0];
        String version = args[1];

        File jarFile = new File(inputJarName);
        if (!jarFile.exists()) {
            System.out.println("File not found: " + inputJarName);
            return;
        }

        if (!inputJarName.endsWith(".jar") || !jarFile.isFile()) {
            System.out.println("jar file expected: " + inputJarName);
            return;
        }

        File outFile = new File("lang.keys.txt");

        LanguageGenerator generator = new LanguageGenerator(jarFile, outFile, version);

        try {
            generator.generate();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void printHelp() {

        System.out.println("Format expect:");
        System.out.println("jar -jar NucleusLocalizer.jar <jarFileName> <version>");
    }

}


text:
<?php
namespace TYPO3\CMS\Frontend\ContentObject;

use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Contains an abstract class for all tslib content class implementations.
 */
abstract class AbstractContentObject
{
    /**
     * @var ContentObjectRenderer
     */
    protected $cObj;

    /**
     * @var PageRenderer
     */
    protected $pageRenderer = null;

    /**
     * Default constructor.
     *
     * @param ContentObjectRenderer $cObj
     */
    public function __construct(ContentObjectRenderer $cObj)
    {
        $this->cObj = $cObj;
    }

    /**
     * Renders the content object.
     *
     * @param array $conf
     * @return string
     */
    abstract public function render($conf = []);

    /**
     * Getter for current cObj
     *
     * @return ContentObjectRenderer
     */
    public function getContentObject()
    {
        return $this->cObj;
    }

    /**
     * @return PageRenderer
     */
    protected function getPageRenderer()
    {
        if ($this->pageRenderer === null) {
            $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
        }

        return $this->pageRenderer;
    }
}


text:
Describe "Common parameters support for script cmdlets" -Tags "CI" {
    BeforeEach {
        $rs = [system.management.automation.runspaces.runspacefactory]::CreateRunspace()
        $rs.open()
        $ps = [System.Management.Automation.PowerShell]::Create()
        $ps.Runspace = $rs
    }

    AfterEach {
            $ps.Dispose()
            $rs.Dispose()
    }

    Context "Debug" {
        BeforeAll {
            $script = "
                function get-foo
                {
                    [CmdletBinding()]
                    param()

                    write-output 'output foo'
                    write-debug  'debug foo'
                }"
        }

        It "Debug get-foo" {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.Streams.Debug.Count | Should -Be 0
        }

        It 'get-foo -debug' {
            $command = 'get-foo -debug'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.Streams.Debug[0].Message | Should -BeExactly "debug foo"
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context "verbose" {
        BeforeAll {
            $script = "
                function get-foo
                {
                    [CmdletBinding()]
                    param()

                    write-output 'output foo'
                    write-verbose  'verbose foo'
                }"
        }

        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.streams.verbose.Count | Should -Be 0
        }

        It 'get-foo -verbose' {
            $command = 'get-foo -verbose'

            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.Streams.verbose[0].Message | Should -BeExactly "verbose foo"
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context "erroraction" {
        BeforeAll {
            $script = "
                function get-foo
                {
                    [CmdletBinding()]
                    param()

                    write-error  'error foo'
                    write-output 'output foo'
                }"
            }

        It 'erroraction' {

            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.Streams.error[0].ToString() | Should -Match "error foo"
        }

        It 'erroraction continue' {

            $command = 'get-foo -erroraction Continue'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.Streams.error[0].ToString() | Should -Match "error foo"
        }

        It 'erroraction SilentlyContinue' {

            $command = 'get-foo -erroraction SilentlyContinue'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly "output foo"
            $ps.streams.error.count | Should -Be 0
        }

        It 'erroraction Stop' {

            $command = 'get-foo -erroraction Stop'

            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()

            { $ps.EndInvoke($asyncResult) } | Should -Throw -ErrorId "ActionPreferenceStopException"
            # Exception: "Command execution stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: error foo"

            # BUG in runspace api.
            #$ps.error.count | Should Be 1

            $ps.InvocationStateInfo.State | Should -BeExactly 'Failed'
        }
    }

    Context "SupportShouldprocess" {
        $script = '
                function get-foo
                {
                    [CmdletBinding(SupportsShouldProcess=$true)]
                    param()

                    if($pscmdlet.shouldprocess("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'

        It 'SupportShouldprocess' {

            $command = 'get-foo'
            $ps = [system.management.automation.powershell]::Create()
            [void] $ps.AddScript($script + $command)
            $ps.RunspacePool = $rp
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly 'foo action'
        }

        It 'shouldprocess support -whatif' {

            $command = 'get-foo -whatif'
            $ps = [system.management.automation.powershell]::Create()
            [void] $ps.AddScript($script + $command)
            $ps.RunspacePool = $rp
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }

        It 'shouldprocess support -confirm under the non-interactive host' {

            $command = 'get-foo -confirm'
            [void] $ps.AddScript($script + $command)

            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1 # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context 'confirmimpact support: none' {
        BeforeAll {
            $script = '
                function get-foo
                {
                    [CmdletBinding(supportsshouldprocess=$true, ConfirmImpact="none")]
                    param()

                    if($pscmdlet.shouldprocess("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'
        }

        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly 'foo action'
        }

        It 'get-foo -confirm' {
            $command = 'get-foo -confirm'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly 'foo action'
        }
    }

    Context 'confirmimpact support: low under the non-interactive host' {
        BeforeAll {
            $script = '
                function get-foo
                {
                    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="low")]
                    param()

                    if($pscmdlet.shouldprocess("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'
        }
        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly 'foo action'
        }

        It 'get-foo -confirm' {
            $command = 'get-foo -confirm'

            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1  # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context 'confirmimpact support: Medium under the non-interactive host' {
        BeforeAll {
            $script = '
                function get-foo
                {
                    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="medium")]
                    param()

                    if($pscmdlet.shouldprocess("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'
        }

        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $output = $ps.EndInvoke($asyncResult)

            $output[0] | Should -BeExactly 'foo action'
        }

        It 'get-foo -confirm' {
            $command = 'get-foo -confirm'
            [void] $ps.AddScript($script + $command)

            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1  # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context 'confirmimpact support: High under the non-interactive host' {
        BeforeAll {
            $script = '
                function get-foo
                {
                    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
                    param()

                    if($pscmdlet.shouldprocess("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'
        }

        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1 # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }

        It 'get-foo -confirm' {
            $command = 'get-foo -confirm'
            [void] $ps.AddScript($script + $command)
            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1 # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }

    Context 'ShouldContinue Support under the non-interactive host' {
        BeforeAll {
            $script = '
                function get-foo
                {
                    [CmdletBinding()]
                    param()

                    if($pscmdlet.shouldcontinue("foo", "foo action"))
                    {
                        write-output "foo action"
                    }
                }'
        }

        It 'get-foo' {
            $command = 'get-foo'
            [void] $ps.AddScript($script + $command)

            $asyncResult = $ps.BeginInvoke()
            $ps.EndInvoke($asyncResult)

            $ps.Streams.Error.Count | Should -Be 1   # the host does not implement it.
            $ps.InvocationStateInfo.State | Should -BeExactly 'Completed'
        }
    }
}


text:
program GravityWave

use NumberKindsModule
use LoggerModule
use PlanarSWEModule
use ParticlesModule
use FieldModule
use MPISetupModule
use SWEPlaneSolverModule
use PSEDirectSumModule

implicit none

include 'mpif.h'

!
!	mesh variables
!
type(SWEMesh) :: plane
integer(kint) :: meshSeed
integer(kint) :: faceKind
integer(kint) :: initNest
integer(kint) :: maxNest
integer(kint) :: amrLimit
real(kreal), parameter :: meshRadius = 5.0_kreal
real(kreal) :: f0
real(kreal) :: beta
real(kreal), parameter :: g = 1.0_kreal
character(len=MAX_STRING_LENGTH) :: meshString

namelist /meshDefine/ faceKind, initNest, maxNest, amrLimit, f0, beta

!
!	timestepping
!
type(SWESolver) :: timekeeper
real(kreal) :: dt
real(kreal) :: tfinal
real(kreal) :: t
integer(kint) :: timeJ, nTimesteps
type(PSE) :: pseSetup

namelist /timestepping/ dt, tfinal

!
!	I/O variables
!
character(len=MAX_STRING_LENGTH) :: outputDir, outputRoot, vtkFile, matlabFile, vtkRoot
integer(kint) :: frameOut, frameCounter
namelist /fileIO/ outputDir, outputRoot, frameOut

!
!	computing environment
!
type(Logger) :: exeLog
character(len=MAX_STRING_LENGTH) :: logstring
character(len=15) :: logKey = "GravWave"
integer(kint), parameter :: logLevel = DEBUG_LOGGING_LEVEL
character(len=MAX_STRING_LENGTH) :: namelistFilename
integer(kint) :: mpiErrCode
real(kreal) :: programStart, programEnd

!--------------------------------
!	initialize : setup computing environment
!--------------------------------
call MPI_INIT(mpiErrCode)
call MPI_COMM_SIZE(MPI_COMM_WORLD, numProcs, mpiErrCode)
call MPI_COMM_RANK(MPI_COMM_WORLD, procRank, mpiErrCode)
programStart = MPI_WTIME()

call InitLogger(exeLog, procRank)

call ReadNamelistFile(procRank)

!--------------------------------
!	initialize : setup problem / build mesh
!--------------------------------

call New(plane, meshSeed, initNest, maxNest, amrLimit, meshRadius, f0, beta, g)
call SetInitialVorticityOnMesh( plane, initVorticity )
call SetInitialDivergenceOnMesh( plane, initDivergence)
call SetInitialVelocityOnMesh(plane, initVelocity )
call SetInitialHOnMesh( plane, initH )
call SetBottomHeightOnMesh( plane, bottomTopo)
call SetInitialPotVortOnMesh( plane )

call New(pseSetup, plane%mesh)
plane%pseEps = pseSetup%eps

call New(timekeeper, plane, bottomTopo)
nTimesteps = floor(tfinal/dt)
t = 0.0_kreal
frameCounter = 1

!
!	output initial mesh
!
if ( procRank == 0 ) then
	call LogStats(plane, exeLog)

	if ( meshSeed == TRI_HEX_SEED ) then
		write(meshString, '(A,I1,A)') '_triHex', initNest, '_'
	elseif ( meshSeed == QUAD_RECT_SEED ) then
		write(meshString, '(A,I1,A)') '_quadRect', initNest, '_'
	endif

	write(vtkRoot,'(4A)') trim(outputDir), '/vtkOut/', trim(outputRoot), trim(meshString)
	write(vtkFile,'(A,I0.4,A)') trim(vtkRoot), 0, '.vtk'

	call OutputToVTKFile(plane, vtkFile)
	call LogMessage(exelog, TRACE_LOGGING_LEVEL, trim(logkey)//" t = ", t)
endif

!--------------------------------
!	run : evolve the problem in time (currently no remeshing)
!--------------------------------
do timeJ = 0, nTimesteps - 1

	call Timestep( timekeeper, plane, dt, bottomTopo)

	t = real(timeJ+1,kreal) * dt
	plane%mesh%t = t

!	call LogStats(plane%divergence, exeLog)
!	call LogStats(plane%hBottom, exeLog)

	if ( procRank == 0 .AND. mod(timeJ+1, frameOut) == 0 ) then
		write(vtkFile,'(A,I0.4,A)') trim(vtkRoot), frameCounter, '.vtk'

		call OutputToVTKFile( plane, vtkFile )

		frameCounter = frameCounter + 1
		call LogMessage(exelog, TRACE_LOGGING_LEVEL, trim(logkey)//" t = ", plane%mesh%t)

	endif
enddo

!--------------------------------
!	finalize : clean up
!--------------------------------

programEnd = MPI_WTIME()

write(logstring,'(A,F12.2,A)') "PROGRAM COMPLETE : elapsed time ", programEnd - programStart, " seconds."
call LogMessage(exelog, TRACE_LOGGING_LEVEL, trim(logkey)//" ", logString)

call Delete(pseSetup)
call Delete(timekeeper)
call Delete(plane)

call MPI_FINALIZE(mpiErrCode)

contains

pure function initH(x, y)
	real(kreal) :: initH
	real(kreal), intent(in) :: x, y
	initH = 1.0_kreal - bottomTopo(x,y) + heightPertub(x,y)
end function

pure function heightPertub(x,y)
	real(kreal) :: heightPertub
	real(kreal), intent(in) :: x, y
!	if ( x >= -1.25_kreal .AND. x <= -1.0_kreal  ) then
!		heightPertub = 0.1_kreal * exp( -5.0_kreal * y * y)
!	else
!		heightPertub = 0.0_kreal
!	endif
	heightPertub = 0.1_kreal * exp( -20.0_kreal * ( x + 1.125_kreal )*(x + 1.125_kreal) - 5.0_kreal * y * y)
end function

pure function bottomTopo(x,y)
	real(kreal) :: bottomTopo
	real(kreal), intent(in) :: x, y
	!bottomTopo = 0.8_kreal * exp( -5.0_kreal * x * x - 5.0_kreal * y * y )
	bottomTopo = 0.8_kreal * exp( -5.0_kreal * x * x - 5.0_kreal * y * y)
end function

pure function initDivergence( x, y )
	real(kreal) :: initDivergence
	real(kreal), intent(in) :: x, y
	initDivergence = 0.0_kreal
end function

pure function initVorticity( x, y)
	real(kreal) :: initVorticity
	real(kreal), intent(in) :: x, y
	initVorticity = 0.0_kreal
end function

pure function initVelocity(x, y)
	real(kreal) :: initVelocity(2)
	real(kreal), intent(in) :: x, y
	initVelocity(1) = 0.0_kreal
	initVelocity(2) = 0.0_kreal
end function

subroutine InitLogger(log, rank)
	type(Logger), intent(inout) :: log
	integer(kint), intent(in) :: rank
	if ( rank == 0 ) then
		call New(log, logLevel)
	else
		call New(log, ERROR_LOGGING_LEVEL)
	endif
	write(logKey,'(A,I0.2,A)') trim(logKey)//"_", rank, ":"
end subroutine

subroutine ReadNamelistFile(rank)
	integer(kint), intent(in) :: rank
	!
	integer(kint), parameter :: initBCAST_intSize = 5
	integer(kint), parameter :: initBCAST_realSize = 4
	integer(kint) :: readStat
	integer(kint) :: bcastIntegers(initBCAST_intSize)
	real(kreal) :: bcastReals(initBCAST_realSize)
	integer(kint) :: mpiErrCode

	if ( COMMAND_ARGUMENT_COUNT() /= 1 ) then
		call LogMessage(exeLog,ERROR_LOGGING_LEVEL, trim(logKey), " expected namelist file name as 1st argument.")
		stop
	endif

	if ( rank == 0 ) then
		call GET_COMMAND_ARGUMENT(1, namelistFilename)

		open( unit=READ_UNIT, file=namelistFilename, status='OLD', action='READ', iostat=readStat)
			if (readStat /= 0 ) then
				call LogMessage(exeLog, ERROR_LOGGING_LEVEL, trim(logKey), " cannot read namelist file.")
				stop
			endif
			read(READ_UNIT, nml=meshDefine)
			rewind(READ_UNIT)
			read(READ_UNIT, nml=timestepping)
			rewind(READ_UNIT)
			read(READ_UNIT, nml=fileIO)
			! namelist /meshDefine/ faceKind, initNest, maxNest, amrLimit

			if ( faceKind == 3 ) then
				meshSeed = TRI_HEX_SEED
			elseif ( faceKind == 4 ) then
				meshSeed = QUAD_RECT_SEED
			else
				call LogMessage(exeLog, WARNING_LOGGING_LEVEL, trim(logKey)//" ReadNamelistFile WARNING :", &
					" invalid faceKind -- using triangles.")
				meshSeed = TRI_HEX_SEED
			endif

			if (amrLimit == 0) maxNest = initNest

			bcastIntegers(1) = meshSeed
			bcastIntegers(2) = initNest
			bcastIntegers(3) = maxNest
			bcastIntegers(4) = amrLimit
			bcastIntegers(5) = frameOut

			bcastReals(1) = dt
			bcastReals(2) = tfinal
			bcastReals(3) = f0
			bcastReals(4) = beta
		close(READ_UNIT)
	endif

	call MPI_BCAST(bcastIntegers, initBCAST_intSize, MPI_INTEGER, 0, MPI_COMM_WORLD, mpiErrCode)

	call MPI_BCAST(bcastReals, initBCAST_realSize, MPI_DOUBLE_PRECISION, 0, MPI_COMM_WORLD, mpiErrCode)

	meshSeed = bcastIntegers(1)
	initNest = bcastIntegers(2)
	maxNest = bcastIntegers(3)
	amrLimit = bcastIntegers(4)
	frameOut = bcastIntegers(5)

	dt = bcastReals(1)
	tfinal = bcastReals(2)
	f0 = bcastReals(3)
	beta = bcastReals(4)
end subroutine

end program


text:
package org.scalar.scholar

import java.net.URL

import org.jsoup.Jsoup
import org.jsoup.nodes.Document

/**
 * A detailed view of a publication.
 */
class DetailedPublication private (val content: Document)
{
   /**
    * A dictionary of informations that relate to the publication.
    * Keys may vary, depending on the type of publication (article,
    * book chapter, etc.).
    */
   lazy val metadata: Map[String, String] = {
      import scala.collection.JavaConversions._
      val keys = content.select("div.gsc_field").iterator.toList.map(_.text)
      val values = content.select("div.gsc_value").iterator.toList.map(_.text)
      // TODO: ignore div#gsc_graph_bars so that the history is not included in the value

      (keys zip values).toMap
   }

}

object DetailedPublication
{
   def apply(url: URL) = new DetailedPublication(Jsoup.connect(url.toString).get)
}


text:
module MiqReportResult::ResultSetOperations
  extend ActiveSupport::Concern

  module ClassMethods
    def apply_limit_and_offset(results, options)
      results.slice(options['offset'].to_i, options['limit'].to_i) || []
    end

    def result_set_for_reporting(report_result, options)
      report = report_result.report_or_miq_report
      sorting_columns = report.validate_sorting_columns(options[:sort_by])
      result_set = report_result.result_set

      count_of_full_result_set = result_set.count
      if result_set.present? && report
        if options.key?(:filter_column) && options.key?(:filter_string)
          result_set, count_of_full_result_set = report.filter_result_set(result_set, options)
          allowed_columns_to_format = report.col_order - [options[:filter_column]]
        end

        result_set.map! { |x| x.slice(*report.col_order) }
        result_set = result_set.stable_sort_by(sorting_columns, options[:sort_order])
        result_set = apply_limit_and_offset(result_set, options)
      end

      {:result_set => report.format_result_set(result_set, allowed_columns_to_format, options[:expand_value_format]), :count_of_full_result_set => count_of_full_result_set}
    end
  end
end


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.infobar;

import static junit.framework.Assert.assertEquals;

import androidx.test.filters.MediumTest;

import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabTestUtils;
import org.chromium.chrome.browser.test.ScreenShooter;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.batch.BlankCTATabInitialStateRule;
import org.chromium.chrome.test.util.InfoBarTestAnimationListener;
import org.chromium.components.infobars.InfoBar;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.content_public.browser.test.util.TestThreadUtils;

import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Tests for the appearance of InfoBars.
 */
// clang-format off
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
@Batch(Batch.PER_CLASS)
public class InfoBarAppearanceTest {
    // clang-format on

    @ClassRule
    public static ChromeTabbedActivityTestRule sActivityTestRule =
            new ChromeTabbedActivityTestRule();

    @ClassRule
    public static ScreenShooter sScreenShooter = new ScreenShooter();

    @Rule
    public BlankCTATabInitialStateRule mInitialStateRule =
            new BlankCTATabInitialStateRule(sActivityTestRule, true);

    private InfoBarTestAnimationListener mListener;
    private Tab mTab;

    @Before
    public void setUp() throws InterruptedException {
        mListener = new InfoBarTestAnimationListener();

        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mTab = sActivityTestRule.getActivity().getActivityTab();
            sActivityTestRule.getInfoBarContainer().addAnimationListener(mListener);
        });
    }

    @After
    public void tearDown() {
        InfoBarContainer container = sActivityTestRule.getInfoBarContainer();
        if (container != null) {
            TestThreadUtils.runOnUiThreadBlocking(() -> {
                container.removeAnimationListener(mListener);
                InfoBarContainer.removeInfoBarContainerForTesting(
                        sActivityTestRule.getActivity().getActivityTab());
            });
        }
    }

    @Test
    @MediumTest
    @Feature({"InfoBars", "UiCatalogue"})
    @DisabledTest(message = "https://crbug.com/1133772")
    public void testFramebustBlockInfoBar() throws Exception {
        FramebustBlockInfoBar infobar = new FramebustBlockInfoBar("http://very.evil.biz");
        captureMiniAndRegularInfobar(infobar);
    }

    @Test
    @MediumTest
    @Feature("InfoBars")
    public void testFramebustBlockInfoBarOverriding() {
        String url1 = "http://very.evil.biz/";
        String url2 = "http://other.evil.biz/";
        List<InfoBar> infobars;
        FramebustBlockInfoBar infoBar;

        TestThreadUtils.runOnUiThreadBlocking(
                () -> { TabTestUtils.showFramebustBlockInfobarForTesting(mTab, url1); });
        infobars = sActivityTestRule.getInfoBarContainer().getInfoBarsForTesting();
        assertEquals(1, infobars.size());
        infoBar = (FramebustBlockInfoBar) infobars.get(0);
        assertEquals(url1, infoBar.getBlockedUrl());

        TestThreadUtils.runOnUiThreadBlocking(
                () -> { TabTestUtils.showFramebustBlockInfobarForTesting(mTab, url2); });
        infobars = sActivityTestRule.getInfoBarContainer().getInfoBarsForTesting();
        assertEquals(1, infobars.size());
        infoBar = (FramebustBlockInfoBar) infobars.get(0);
        assertEquals(url2, infoBar.getBlockedUrl());
    }

    @Test
    @MediumTest
    @Feature("InfoBars")
    public void testFramebustBlockInfoBarUrlTapped() throws TimeoutException {
        String url = "http://very.evil.biz";

        CallbackHelper callbackHelper = new CallbackHelper();
        EmptyTabObserver navigationWaiter = new EmptyTabObserver() {
            @Override
            public void onDidStartNavigation(Tab tab, NavigationHandle navigation) {
                callbackHelper.notifyCalled();
            }
        };
        TestThreadUtils.runOnUiThreadBlocking(() -> mTab.addObserver(navigationWaiter));

        TestThreadUtils.runOnUiThreadBlocking(
                () -> { TabTestUtils.showFramebustBlockInfobarForTesting(mTab, url); });
        FramebustBlockInfoBar infoBar =
                (FramebustBlockInfoBar) sActivityTestRule.getInfoBarContainer()
                        .getInfoBarsForTesting()
                        .get(0);

        TestThreadUtils.runOnUiThreadBlocking(infoBar::onLinkClicked); // Once to expand the infobar
        assertEquals(0, callbackHelper.getCallCount());

        TestThreadUtils.runOnUiThreadBlocking(infoBar::onLinkClicked); // Now to navigate
        callbackHelper.waitForCallback(0);

        CriteriaHelper.pollUiThread(
                () -> InfoBarContainer.get(mTab).getInfoBarsForTesting().isEmpty());
    }

    @Test
    @MediumTest
    @Feature("InfoBars")
    public void testFramebustBlockInfoBarButtonTapped() {
        String url = "http://very.evil.biz";

        TestThreadUtils.runOnUiThreadBlocking(
                () -> { TabTestUtils.showFramebustBlockInfobarForTesting(mTab, url); });
        FramebustBlockInfoBar infoBar =
                (FramebustBlockInfoBar) sActivityTestRule.getInfoBarContainer()
                        .getInfoBarsForTesting()
                        .get(0);

        TestThreadUtils.runOnUiThreadBlocking(() -> infoBar.onButtonClicked(true));
        CriteriaHelper.pollUiThread(
                () -> InfoBarContainer.get(mTab).getInfoBarsForTesting().isEmpty());
    }

    @Test
    @MediumTest
    @Feature({"InfoBars", "UiCatalogue"})
    public void testFramebustBlockInfoBarWithLongMessages() throws Exception {
        FramebustBlockInfoBar infobar = new FramebustBlockInfoBar("https://someverylonglink"
                + "thatwilldefinitelynotfitevenwhenremovingthefilepath.com/somemorestuff");
        captureMiniAndRegularInfobar(infobar);
    }

    @Test
    @MediumTest
    @Feature({"InfoBars", "UiCatalogue"})
    public void testOomInfoBar() throws TimeoutException {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> InfoBarContainer.get(mTab).addInfoBarForTesting(new NearOomInfoBar()));
        mListener.addInfoBarAnimationFinished("InfoBar was not added.");
        sScreenShooter.shoot("oom_infobar");
    }

    private void captureMiniAndRegularInfobar(InfoBar infobar) throws TimeoutException {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> InfoBarContainer.get(mTab).addInfoBarForTesting(infobar));
        mListener.addInfoBarAnimationFinished("InfoBar was not added.");
        sScreenShooter.shoot("compact");

        TestThreadUtils.runOnUiThreadBlocking(infobar::onLinkClicked);
        mListener.swapInfoBarAnimationFinished("InfoBar did not expand.");
        sScreenShooter.shoot("expanded");
    }
}


text:
namespace em = enterprise_management;

using testing::AnyNumber;
using testing::AtLeast;
using testing::Mock;
using testing::_;

namespace policy {
namespace {

class TestHarness : public PolicyProviderTestHarness {
 public:
  explicit TestHarness(PolicyLevel level);
  virtual ~TestHarness();

  virtual void SetUp() OVERRIDE;

  virtual ConfigurationPolicyProvider* CreateProvider(
      const PolicyDefinitionList* policy_definition_list) OVERRIDE;

  virtual void InstallEmptyPolicy() OVERRIDE;
  virtual void InstallStringPolicy(const std::string& policy_name,
                                   const std::string& policy_value) OVERRIDE;
  virtual void InstallIntegerPolicy(const std::string& policy_name,
                                    int policy_value) OVERRIDE;
  virtual void InstallBooleanPolicy(const std::string& policy_name,
                                    bool policy_value) OVERRIDE;
  virtual void InstallStringListPolicy(
      const std::string& policy_name,
      const base::ListValue* policy_value) OVERRIDE;
  virtual void InstallDictionaryPolicy(
      const std::string& policy_name,
      const base::DictionaryValue* policy_value) OVERRIDE;

  // Creates harnesses for mandatory and recommended levels, respectively.
  static PolicyProviderTestHarness* CreateMandatory();
  static PolicyProviderTestHarness* CreateRecommended();

 private:
  MockCloudPolicyStore* store_;

  DISALLOW_COPY_AND_ASSIGN(TestHarness);
};

TestHarness::TestHarness(PolicyLevel level)
    : PolicyProviderTestHarness(level, POLICY_SCOPE_USER) {}

TestHarness::~TestHarness() {}

void TestHarness::SetUp() {}

ConfigurationPolicyProvider* TestHarness::CreateProvider(
    const PolicyDefinitionList* policy_definition_list) {
  // Create and initialize the store.
  store_ = new MockCloudPolicyStore();
  store_->NotifyStoreLoaded();
  EXPECT_CALL(*store_, Load());
  return new UserCloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_).Pass(),
                                    false);
}

void TestHarness::InstallEmptyPolicy() {}

void TestHarness::InstallStringPolicy(const std::string& policy_name,
                                      const std::string& policy_value) {
  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),
                          base::Value::CreateStringValue(policy_value));
}

void TestHarness::InstallIntegerPolicy(const std::string& policy_name,
                                       int policy_value) {
  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),
                          base::Value::CreateIntegerValue(policy_value));
}

void TestHarness::InstallBooleanPolicy(const std::string& policy_name,
                                       bool policy_value) {
  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),
                          base::Value::CreateBooleanValue(policy_value));
}

void TestHarness::InstallStringListPolicy(const std::string& policy_name,
                                          const base::ListValue* policy_value) {
  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),
                          policy_value->DeepCopy());
}

void TestHarness::InstallDictionaryPolicy(
    const std::string& policy_name,
    const base::DictionaryValue* policy_value) {
  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),
                          policy_value->DeepCopy());
}

// static
PolicyProviderTestHarness* TestHarness::CreateMandatory() {
  return new TestHarness(POLICY_LEVEL_MANDATORY);
}

// static
PolicyProviderTestHarness* TestHarness::CreateRecommended() {
  return new TestHarness(POLICY_LEVEL_RECOMMENDED);
}

// Instantiate abstract test case for basic policy reading tests.
INSTANTIATE_TEST_CASE_P(
    UserCloudPolicyManagerProviderTest,
    ConfigurationPolicyProviderTest,
    testing::Values(TestHarness::CreateMandatory,
                    TestHarness::CreateRecommended));

class UserCloudPolicyManagerTest : public testing::Test {
 protected:
  UserCloudPolicyManagerTest()
      : store_(NULL) {}

  virtual void SetUp() OVERRIDE {
    chrome::RegisterLocalState(&prefs_);

    // Set up a policy map for testing.
    policy_map_.Set("key", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
                    base::Value::CreateStringValue("value"));
    expected_bundle_.Get(POLICY_DOMAIN_CHROME, std::string()).CopyFrom(
        policy_map_);

    // Create a fake policy blob to deliver to the client.
    em::PolicyData policy_data;
    em::PolicyFetchResponse* policy_response =
        policy_blob_.mutable_policy_response()->add_response();
    ASSERT_TRUE(policy_data.SerializeToString(
        policy_response->mutable_policy_data()));

    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
        .Times(AnyNumber());
  }

  void CreateManager(bool wait_for_policy_fetch) {
    store_ = new MockCloudPolicyStore();
    EXPECT_CALL(*store_, Load());
    manager_.reset(
        new UserCloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_).Pass(),
                                   wait_for_policy_fetch));
    registrar_.Init(manager_.get(), &observer_);
  }

  void CreateManagerWithPendingFetch() {
    CreateManager(true);
    manager_->Initialize(&prefs_, &device_management_service_,
                         USER_AFFILIATION_NONE);
    EXPECT_FALSE(manager_->IsInitializationComplete());

    // Finishing the Load() operation shouldn't set the initialized flag.
    EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
    store_->NotifyStoreLoaded();
    EXPECT_FALSE(manager_->IsInitializationComplete());
    Mock::VerifyAndClearExpectations(&observer_);
  }

  // Required by the refresh scheduler that's created by the manager.
  MessageLoop loop_;

  // Convenience policy objects.
  em::DeviceManagementResponse policy_blob_;
  PolicyMap policy_map_;
  PolicyBundle expected_bundle_;

  // Policy infrastructure.
  TestingPrefService prefs_;
  MockConfigurationPolicyObserver observer_;
  MockDeviceManagementService device_management_service_;
  MockCloudPolicyStore* store_;
  scoped_ptr<UserCloudPolicyManager> manager_;
  ConfigurationPolicyObserverRegistrar registrar_;

 private:
  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerTest);
};

TEST_F(UserCloudPolicyManagerTest, Init) {
  CreateManager(false);
  PolicyBundle empty_bundle;
  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));
  EXPECT_FALSE(manager_->IsInitializationComplete());

  store_->policy_map_.CopyFrom(policy_map_);
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
  EXPECT_TRUE(manager_->IsInitializationComplete());
}

TEST_F(UserCloudPolicyManagerTest, Update) {
  CreateManager(false);
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  EXPECT_TRUE(manager_->IsInitializationComplete());
  PolicyBundle empty_bundle;
  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));

  store_->policy_map_.CopyFrom(policy_map_);
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
  EXPECT_TRUE(manager_->IsInitializationComplete());
}

TEST_F(UserCloudPolicyManagerTest, RefreshNotRegistered) {
  CreateManager(false);
  manager_->Initialize(&prefs_, &device_management_service_,
                       USER_AFFILIATION_NONE);

  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  Mock::VerifyAndClearExpectations(&observer_);

  // A refresh on a non-registered store should not block.
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  manager_->RefreshPolicies();
  Mock::VerifyAndClearExpectations(&observer_);
}

TEST_F(UserCloudPolicyManagerTest, RefreshSuccessful) {
  CreateManager(false);
  manager_->Initialize(&prefs_, &device_management_service_,
                       USER_AFFILIATION_NONE);
  manager_->cloud_policy_service()->client()->SetupRegistration("dm_token",
                                                                "client_id");

  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  Mock::VerifyAndClearExpectations(&observer_);

  // Start a refresh.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  MockDeviceManagementJob* request_job;
  EXPECT_CALL(device_management_service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(device_management_service_.CreateAsyncJob(&request_job));
  manager_->RefreshPolicies();
  ASSERT_TRUE(request_job);
  store_->policy_map_.CopyFrom(policy_map_);
  Mock::VerifyAndClearExpectations(&observer_);

  // A stray reload should be suppressed until the refresh completes.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  store_->NotifyStoreLoaded();
  Mock::VerifyAndClearExpectations(&observer_);

  // Respond to the policy fetch, which should trigger a write to |store_|.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  EXPECT_CALL(*store_, Store(_));
  request_job->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
  Mock::VerifyAndClearExpectations(&observer_);

  // The load notification from |store_| should trigger the policy update.
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
  Mock::VerifyAndClearExpectations(&observer_);
}

TEST_F(UserCloudPolicyManagerTest, WaitForPolicyFetch) {
  CreateManagerWithPendingFetch();

  // Setting the token should trigger the policy fetch.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  MockDeviceManagementJob* fetch_request = NULL;
  EXPECT_CALL(device_management_service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
  manager_->cloud_policy_service()->client()->SetupRegistration("dm_token",
                                                                "client_id");
  ASSERT_TRUE(fetch_request);
  EXPECT_FALSE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);

  // Respond to the policy fetch, which should trigger a write to |store_|.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  EXPECT_CALL(*store_, Store(_));
  fetch_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
  EXPECT_FALSE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);

  // The load notification from |store_| should trigger the policy update and
  // flip the initialized bit.
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  store_->NotifyStoreLoaded();
  EXPECT_TRUE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);
}

TEST_F(UserCloudPolicyManagerTest, WaitForPolicyFetchError) {
  CreateManagerWithPendingFetch();

  // Setting the token should trigger the policy fetch.
  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
  MockDeviceManagementJob* fetch_request = NULL;
  EXPECT_CALL(device_management_service_,
              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
      .WillOnce(device_management_service_.CreateAsyncJob(&fetch_request));
  manager_->cloud_policy_service()->client()->SetupRegistration("dm_token",
                                                                "client_id");
  ASSERT_TRUE(fetch_request);
  EXPECT_FALSE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);

  // Make the policy fetch fail, at which point the manager should bail out.
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
  fetch_request->SendResponse(DM_STATUS_REQUEST_FAILED, policy_blob_);
  EXPECT_TRUE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);
}

TEST_F(UserCloudPolicyManagerTest, WaitForPolicyFetchCancel) {
  CreateManagerWithPendingFetch();

  // Cancelling the initial fetch should flip the flag.
  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
  manager_->CancelWaitForPolicyFetch();
  EXPECT_TRUE(manager_->IsInitializationComplete());
  Mock::VerifyAndClearExpectations(&observer_);
}

}  // namespace
}  // namespace policy


text:
import json

class Element(object):
    """
    Abstract class for Cytoscape.js graph element with common properties for nodes and edges
    """

    def __init__(self, _id):
        self.__metaclass__ = Element
        self.group = 'nodes'  # 'nodes' for a node, 'edges' for an edge
        self.data = {  # element data (put json serializable dev data here)
            # define 'source' and 'target' for an edge
            'id': small_hash(self) if _id is None else _id
        }
        self.scratch = {}  # scratchpad data (usually temp or non-serializable data)
        self.selected = False  # whether the element is selected (default false)
        self.selectable = True  # whether the selection state is mutable (default true)
        self.classes = ''  # a space separated list of class names that the element has

    def add_class(self, cls):
        if self.classes.__len__() > 0:
            self.classes += ' '
        self.classes += cls

    def add_data(self, key, value):
        # self.data.update({key : value})
        self.data[key] = value

    def set_edge_data(self, source_el, target_el):
        self.group = 'edges'
        self.add_data('source', source_el.data['id'])
        self.add_data('target', target_el.data['id'])

    def to_json(self):
        return json.dumps(self, default=serialize_json)

class Node(Element):
    """
    Class which represents Cytoscape.js nodes with node specific properties
    """
    def __init__(self, _id=None):
        super().__init__(_id)
        self.group = 'nodes'
        self.position = {  # the model position of the node (optional on init, mandatory after)
            'x': 0,
            'y': 0
        }
        self.locked = False  # when locked a node's position is immutable (default false)
        self.grabbable = True  # whether the node can be grabbed and moved by the user

class Edge(Element):
    """
    Class which represents Cytoscape.js edges with edge specific properties
    """
    def __init__(self, source_el, target_el, _id=None):
        super().__init__(_id)
        self.set_edge_data(source_el, target_el)

class ViewStyle(object):
    """
    Class which represents Cytoscape.js style definition.

    Contains css styles and selector for elements for which those styles should be applied.
    """
    def __init__(self, selector):
        # self.selector = element.__class__.__name__.lower()
        # if element.classes.__len__() > 0:
        #     self.selector += '.' + element.classes.replace(' ', '.')
        self.selector = selector
        self.style = {}

    def to_json(self):
        return json.dumps(self, default=serialize_json)

def serialize_json(obj):
    """
    A helper method for serializing Cytoscape.js elements in desired json form.
    :param obj: Object to serialize
    :return: JSON string representation of obj
    """
    # handle concrete class serialization
    if hasattr(obj, '__metaclass__') and obj.__metaclass__.__name__ == 'Element':
        json = {}  # { '__classname__' : type(obj).__name__ }
        json.update(vars(obj))
        json.pop('__metaclass__', None)  # remove __metaclass__ from json
    # handle abstract class serialization
    elif obj.__class__.__name__ == 'type' and obj.__name__ == 'Element':
        json = obj.__name__
    elif obj.__class__.__name__ == 'ViewStyle':
        json = {}
        json.update(vars(obj))
    else:
        json = obj.__str__()
    return json

def deserialize_json(json):
    """
    A helper method for deserializing json into Cytoscape.js elements.
    :param json: json representation of Cytoscape.js element
    :return: Cytoscape.js element object if json is valid, else json
    """
    class_name = json.pop('__classname__', None)
    if class_name == 'Element':  # type(self).__name__:
        obj = Element.__new__(Element)   # Make instance without calling __init__
        for key, value in json.items():
            setattr(obj, key, value)
            return obj
    else:
        return json

def small_hash(instance, digits=9):
    """
    Cytoscape.js has trouble with dealing large or negative integers.

    Returns positive and n-digit hash of the passed instance.

    :param instance: for which it's positive 9-digit hash is returned

    :param digits: number of digits of the resulting hash. Default is 9.

    :return: positive 9-digit hash of the instance
    """
    # take positive value
    hash = instance.__hash__().__abs__()
    hash_str = str(hash)
    # reduce hash to n digit
    hash = int(hash_str[-digits:]) if hash_str.__len__() > digits else hash
    # if first digit iz 0 increase digits to n
    hash = hash * 10 if str(hash).__len__() < digits else hash
    return hash


text:
"""Implementation of base class for Grizzly errors handling.

Typical usage example:
  try:
    pass
  except:
    raise GrizzlyException('Unexpected error:', sys.exc_info()[1])
"""

class GrizzlyException(Exception):
  """Base class for all Grizzly errors."""


text:
<?php
global $title, $screen_layout_columns;
add_meta_box("wptabs_content", $title, "wptabs_meta_box", "wptabs_new", "normal", "core");
?>

		<?php do_meta_boxes('wptabs_new','normal', null); ?>

<?php
function wptabs_meta_box(){
global $wpdb;
?>

	<form name="frmwptabs" action="<?php echo admin_url('admin.php') .'?page=wptabs-new'; ?>" method="post">
		<input type="hidden" name="admin-action" value="create" />

				Title:
				<input type="text" name="tab_container_title" value="">

		<input type="submit" class="button-primary" value="Add tab container" />

	</form>

<?php } ?>


text:
package com.github.robozonky.internal.remote.entities;

import java.time.OffsetDateTime;
import java.util.Optional;
import java.util.StringJoiner;

import com.github.robozonky.api.Money;
import com.github.robozonky.api.Ratio;
import com.github.robozonky.api.remote.entities.BaseLoan;
import com.github.robozonky.api.remote.enums.MainIncomeIndustry;
import com.github.robozonky.api.remote.enums.MainIncomeType;
import com.github.robozonky.api.remote.enums.Purpose;
import com.github.robozonky.api.remote.enums.Region;
import com.github.robozonky.internal.test.DateUtil;

public abstract class BaseLoanImpl implements BaseLoan {

    protected boolean insuranceActive;
    protected int id;
    protected int termInMonths;
    protected String name;
    protected String story;
    protected MainIncomeType mainIncomeType;
    protected MainIncomeIndustry mainIncomeIndustry;
    protected Region region;
    protected Purpose purpose;

    // various ratios
    protected Ratio interestRate;
    protected Ratio revenueRate;

    // OffsetDateTime is expensive to parse, and Loans are on the hot path. Only do it when needed.
    protected String datePublished;
    protected String deadline;

    protected Money amount;
    protected Money remainingInvestment;
    protected Money reservedAmount;
    protected Money annuity;
    protected Money annuityWithInsurance;
    protected Money premium;
    protected Money zonkyPlusAmount;

    @Override
    public MainIncomeType getMainIncomeType() {
        return mainIncomeType;
    }

    public void setMainIncomeType(final MainIncomeType mainIncomeType) {
        this.mainIncomeType = mainIncomeType;
    }

    @Override
    public MainIncomeIndustry getMainIncomeIndustry() {
        return mainIncomeIndustry;
    }

    public void setMainIncomeIndustry(final MainIncomeIndustry mainIncomeIndustry) {
        this.mainIncomeIndustry = mainIncomeIndustry;
    }

    @Override
    public Region getRegion() {
        return region;
    }

    public void setRegion(final Region region) {
        this.region = region;
    }

    @Override
    public Purpose getPurpose() {
        return purpose;
    }

    public void setPurpose(final Purpose purpose) {
        this.purpose = purpose;
    }

    @Override
    public int getId() {
        return id;
    }

    public void setId(final int id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

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

    @Override
    public String getStory() {
        return story;
    }

    public void setStory(final String story) {
        this.story = story;
    }

    @Override
    public int getTermInMonths() {
        return termInMonths;
    }

    public void setTermInMonths(final int termInMonths) {
        this.termInMonths = termInMonths;
    }

    @Override
    public Ratio getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(final Ratio interestRate) {
        this.interestRate = interestRate;
    }

    @Override
    public boolean isInsuranceActive() {
        return insuranceActive;
    }

    public void setInsuranceActive(final boolean insuranceActive) {
        this.insuranceActive = insuranceActive;
    }

    @Override
    public Optional<Ratio> getRevenueRate() {
        return Optional.ofNullable(revenueRate);
    }

    public void setRevenueRate(final Ratio revenueRate) {
        this.revenueRate = revenueRate;
    }

    @Override
    public OffsetDateTime getDatePublished() {
        return OffsetDateTime.parse(datePublished);
    }

    public void setDatePublished(final OffsetDateTime datePublished) {
        this.datePublished = datePublished.toString();
    }

    @Override
    public OffsetDateTime getDeadline() {
        return OffsetDateTime.parse(deadline);
    }

    public void setDeadline(final OffsetDateTime deadline) {
        this.deadline = deadline.toString();
    }

    @Override
    public Money getAmount() {
        return amount;
    }

    public void setAmount(final Money amount) {
        this.amount = amount;
    }

    @Override
    public Money getRemainingInvestment() {
        return remainingInvestment;
    }

    public void setRemainingInvestment(final Money remainingInvestment) {
        this.remainingInvestment = remainingInvestment;
    }

    @Override
    public Money getNonReservedRemainingInvestment() {
        return getRemainingInvestment().subtract(reservedAmount);
    }

    @Override
    public Money getReservedAmount() {
        return reservedAmount;
    }

    public void setReservedAmount(final Money reservedAmount) {
        this.reservedAmount = reservedAmount;
    }

    @Override
    public Money getZonkyPlusAmount() {
        return zonkyPlusAmount;
    }

    public void setZonkyPlusAmount(final Money zonkyPlusAmount) {
        this.zonkyPlusAmount = zonkyPlusAmount;
    }

    @Override
    public Money getAnnuity() {
        return annuity;
    }

    public void setAnnuity(final Money annuity) {
        this.annuity = annuity;
    }

    @Override
    public Money getPremium() {
        return premium;
    }

    public void setPremium(final Money premium) {
        this.premium = premium;
    }

    @Override
    public Money getAnnuityWithInsurance() {
        return annuityWithInsurance;
    }

    public void setAnnuityWithInsurance(final Money annuityWithInsurance) {
        this.annuityWithInsurance = annuityWithInsurance;
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", BaseLoanImpl.class.getSimpleName() + "[", "]")
            .add("id=" + id)
            .add("amount='" + amount + "'")
            .add("annuity='" + annuity + "'")
            .add("annuityWithInsurance='" + annuityWithInsurance + "'")
            .add("datePublished='" + DateUtil.toString(getDatePublished()) + "'")
            .add("insuranceActive=" + insuranceActive)
            .add("interestRate=" + interestRate)
            .add("mainIncomeType=" + mainIncomeType)
            .add("mainIncomeIndustry=" + mainIncomeIndustry)
            .add("name='" + name + "'")
            .add("premium='" + premium + "'")
            .add("purpose=" + purpose)
            .add("region=" + region)
            .add("remainingInvestment='" + remainingInvestment + "'")
            .add("reservedAmount='" + reservedAmount + "'")
            .add("revenueRate=" + revenueRate)
            .add("termInMonths=" + termInMonths)
            .add("zonkyPlusAmount='" + zonkyPlusAmount + "'")
            .toString();
    }
}


text:
import nucleotide
import nucleotide.component
import nucleotide.component.function
import nucleotide.component._common

import nucleotide.translator
import nucleotide.config
import nucleotide.klass

atom_linux_shared_library = {
    'platform' : {
        'host'  : 'Linux',
        'guest' : 'Linux'
    },
    'cc' : {
        'vendor' : 'FSF',
        'name'   : 'gcc',
        'version': 'X'
    },
    'config' : {
        # Nothing. It is empty
    },
    'name' :'dll',
    'class':  [ 'executable:shared_object', 'linux:executable:shared_object' ]
}

atom_linux_shared_object = {
    'platform' : {
        'host'  : 'Linux',
        'guest' : 'Linux'
    },
    'cc' : {
        'vendor': 'FSF',
        'name': 'gcc',
        'version': 'X'
    },
     'config' : {
           'CPPDEFINES'  : ['_LIB' ],
    },
    'name' :'lib',
    'class': [  'shared:library' ]
}

def init( P_option ) :

   #nucleotide.component.function.extend( P_option, 'architecture',        atom_linux_architecture )

    nucleotide.component.function.extend( P_option, 'linux:shared_library',        atom_linux_shared_library)
    nucleotide.component.function.extend( P_option, 'linux:shared_object',         atom_linux_shared_object)
    #nucleotide.component.function.extend( P_option, 'linux:static_release',        atom_linux_static_release)

   #nucleotide.component.function.extend( P_option, 'linux:linker:warning',    atom_linux_linker_warning )
   #nucleotide.component.function.extend( P_option, 'linux:compiler:feature:for-scope',  atom_linux_compiler_warning )   -ffor-scope


text:
Trending Projects Calculation
=============================

- Get all projects that have had a "note" created in the last month
- AND where the "note" was created by a user (aka notes.system is false)
- AND where project is visible (aka projects.visibility_level = #{Gitlab::VisibilityLevel::PUBLIC})
- ORDER BY projects with the most notes created in the last month
- LIMIT to the first 100 projects


text:
class Chef::EncryptedDataBagItem
  class UnsupportedEncryptedDataBagItemFormat < StandardError
  end
end


text:
using System;

namespace WcfPeer
{
	public class ConnectionFactory
	{
		public AddressFactory  AddressFactory  {get;set;}
		public BehaviorFactory BehaviorFactory {get;set;}
		public BindingFactory  BindingFactory  {get;set;}

		public static ConnectionFactory Default = new ConnectionFactory{
			AddressFactory = AddressFactory.Default,
			BehaviorFactory = BehaviorFactory.Default,
			BindingFactory = BindingFactory.Default,
		};
	}
}


text:
#include <chipmunk/chipmunk.h>

extern void eachArbiter_body(cpBody *b, cpArbiter *a, void *p);
extern void eachConstraint_body(cpBody *b, cpConstraint *c, void *p);
extern void eachShape_body(cpBody *b, cpShape *s, void *p);
extern void updatePosition(cpBody *b, cpFloat dt);
extern void updateVelocity(cpBody *b, cpVect gravity, cpFloat damping, cpFloat dt);

inline void body_each_arbiter(cpBody *body, void *f) {
  cpBodyEachArbiter(body, eachArbiter_body, f);
}

inline void body_each_constraint(cpBody *body, void *f) {
  cpBodyEachConstraint(body, eachConstraint_body, f);
}

inline void body_each_shape(cpBody *body, void *f) {
  cpBodyEachShape(body, eachShape_body, f);
}

inline void body_set_position_func(cpBody *body, cpBool set) {
  body->position_func = set ? updatePosition : cpBodyUpdatePosition;
}

inline void body_set_velocity_func(cpBody *body, cpBool set) {
  body->velocity_func = set ? updateVelocity : cpBodyUpdateVelocity;
}

// Local Variables:
// indent-tabs-mode: nil
// c-basic-offset: 2
// End:
// ex: set tabstop=2 shiftwidth=2 expandtab: