text:
<?php

$ethoseo_gau_version = "1.0.1";
define( 'ETHOSEO_GAU_PATH', plugin_dir_path(__FILE__) );
define( 'ETHOSEO_GAU_FILE', __FILE__);

// PRINT SCRIPT
if((bool)get_option("ethoseo_gau_infooter")){
	add_action('wp_footer', 'ethoseo_gau_print_script');
}else{
	add_action('wp_head', 'ethoseo_gau_print_script');
}

// GET USER ROLE
function get_user_role($uid) {
	global $wpdb;
	$role = $wpdb->get_var("SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'wp_capabilities' AND user_id = {$uid}");
	  if(!$role) return 'non-user';
	$rarr = unserialize($role);
	$roles = is_array($rarr) ? array_keys($rarr) : array('non-user');
	return $roles[0];
}

function ethoseo_gau_print_script () {

	global $ethoseo_gau_version, $current_user;
	$debug = get_option("ethoseo_gau_debug");
	$console_debug = get_option("ethoseo_gau_consoledebug");

	echo "<script>";
	if(!$console_debug){
		echo "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');";
	}else{
		echo "ga = function() { return console.log.apply(console, arguments); };";
	}
	echo "\n\n";
	echo $debug ? "/* BEFORE GA() */\n" : "";
	echo get_option("ethoseo_gau_before");
	echo $debug ? "/* CREATE(S) */\n" : "";
	foreach(get_option("ethoseo_gau_properties") as $property){
		if(!$property['roles'][get_user_role($current_user->id)]){
			if($property['custom']){
				echo "ga('create', '" . $property['id'] . "', " . $property['custom'] . ");";
			}else{
				echo "ga('create', '" . $property['id'] . "');";
			}
		}
	}
	echo $debug ? "/* PAGE VIEW */\n" : "";
	if(get_option("ethoseo_gau_titleoverride") && get_the_title()){
		echo "ga('send', 'pageview', {'title' : '" . addslashes(get_the_title()) . "'});";
	}else{
		echo "ga('send', 'pageview');";
	}
	echo $debug ? "/* AFTER GA() */\n" : "";
	echo get_option("ethoseo_gau_after");
	echo "</script>";

}

// DEFAULTS

register_activation_hook( __FILE__, 'ethoseo_gau_activate' );
function ethoseo_gau_activate() {
	if(!get_option("ethoseo_gau_activated")){
		update_option("ethoseo_gau_activated", true);
		update_option("ethoseo_gau_properties", array());
		update_option("ethoseo_gau_titleoverride", false);
		update_option("ethoseo_gau_before", "");
		update_option("ethoseo_gau_after", "");
		update_option("ethoseo_gau_hidefor", array());
		update_option("ethoseo_gau_infooter", true);
		update_option("ethoseo_gau_debug", false);
		update_option("ethoseo_gau_consoledebug", false);
	}
}

// SETTINGS

add_action('admin_menu', 'ethoseo_gau_create_menu');
function ethoseo_gau_create_menu() {

	$ethoseo_gau_options_page = add_submenu_page('options-general.php', 'GA Universal', 'GA Universal', 'activate_plugins', 'ga-universal', 'ethoseo_gau_settings_page');
}

add_action( 'admin_enqueue_scripts', 'ethoseo_gau_admin_enqueue' );
function ethoseo_gau_admin_enqueue($hook) {
	global $ethoseo_gau_version;
	if($hook == "settings_page_ga-universal"){
    	wp_enqueue_script('jquery-form-repeater', plugins_url('js/admin.js', __FILE__), array(), "0.1.0", 'all');
    	wp_enqueue_style('ethoseo_gau_admin_css', plugins_url('css/admin.css', __FILE__), array(), $ethoseo_gau_version, 'all');
    }
    if($hook == "post-new.php" && $_GET['ethoseo-thanks-template'] == 1){
    	wp_enqueue_script('ethoseo-thanks', plugins_url('js/thanks.js', __FILE__), array(), "0.1.0", 'all');
    }
}

function ethoseo_gau_page ($pagename){

	if (!current_user_can('activate_plugins'))	{
		wp_die( __('You do not have sufficient permissions to access this page.') );
	}

	global $wpdb;

	include(ETHOSEO_GAU_PATH . "inc/screens/$pagename.php");

}

function ethoseo_gau_settings_page() {
	ethoseo_gau_page('settings');
}

?>


text:
from dpa.action import Action, ActionError
from dpa.action.registry import ActionRegistry
from dpa.location import current_location_code
from dpa.ptask import PTask, PTaskError
from dpa.ptask.area import PTaskAreaError
from dpa.ptask.cli import ParsePTaskSpecArg
from dpa.shell.output import Output, Style

# ----------------------------------------------------------------------------
# Classes:
# ----------------------------------------------------------------------------
class PTaskTransferAction(Action):

    name = 'transfer'
    target_type = 'ptask'

    # ----------------------------------------------------------------------------
    # Class methods:
    # ----------------------------------------------------------------------------
    @classmethod
    def setup_cl_args(cls, parser):

        parser.add_argument(
            "ptask",
            action=ParsePTaskSpecArg,
            nargs="?",
            help="The spec representing the ptask to transfer."
        )

    # ----------------------------------------------------------------------------
    # Instance methods:
    # ----------------------------------------------------------------------------
    def __init__(self, ptask):

        super(PTaskTransferAction, self).__init__(ptask)

        self._ptask = ptask
        self._ptask_latest_version = None

    # ----------------------------------------------------------------------------
    def execute(self):

        # sync the contents of the latest version to this location
        self._sync_latest_remote()

        # update the latest version and set it's location to this location
        try:
            self.ptask_latest_version.update(
                location=current_location_code(),
            )
        except PTaskVersionError as e:
            raise ActionError(
                "Failed to update the location of latest version of the " + \
                    "ptask: " + str(e)
            )

        print "\nTransfer successful!\n"

    # ----------------------------------------------------------------------------
    def validate(self):

        # make sure the ptask evaluates to a real ptask
        try:
            self._ptask = PTask.get(self.ptask)
        except PTaskError:
            raise ActionError(
                "Unable to determine ptask from: " + str(self.ptask)
            )

        # for efficiency
        self._ptask_latest_version = self.ptask.latest_version

        # make sure the latest version is not this location
        if self.ptask_latest_version.location_code == current_location_code():
            raise ActionError(
                "Latest version of {b}{p}{r} already owned by this location.".\
                    format(
                        b=Style.bright,
                        p=self.ptask.spec,
                        r=Style.reset,
                    )
            )

    # ----------------------------------------------------------------------------
    def verify(self):

        ptask_field = 'PTask'
        latest_version_field = 'Latest version'
        from_field = 'From'
        to_field = 'To'

        output = Output()
        output.header_names = [
            ptask_field,
            latest_version_field,
            from_field,
            to_field,
        ]

        output.add_item(
            {
                ptask_field: self.ptask.spec,
                latest_version_field: self.ptask_latest_version.number_padded,
                from_field: self.ptask_latest_version.location_code,
                to_field: current_location_code(),
            },
            color_all=Style.bright,
        )

        output.title = "Confirm transfer:"
        output.dump()

        if not Output.prompt_yes_no(Style.bright + "Transfer" + Style.reset):
            raise ActionAborted("User chose not to proceed.")

    # ----------------------------------------------------------------------------
    def undo(self):
        pass

    # ----------------------------------------------------------------------------
    # Properties:
    # ----------------------------------------------------------------------------
    @property
    def ptask(self):
        return self._ptask

    # ----------------------------------------------------------------------------
    @property
    def ptask_latest_version(self):
        return self._ptask_latest_version

    # ----------------------------------------------------------------------------
    # Private methods
    # ----------------------------------------------------------------------------
    def _sync_latest_remote(self):

        # sync the local work directory with the contents of the remote work
        # directory (excluding products and child directories)

        source_action_class = ActionRegistry().get_action('sync', 'ptask')
        if not source_action_class:
            raise ActionError("Could not find ptask source action.")

        try:
            source_action = source_action_class(
                ptask=self.ptask,
                version="latest",
                force=True,
            )
            source_action.interactive = False
            source_action()
        except ActionError as e:
            raise ActionError("Failed to sync the remote work directory.")

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Encore\Admin\Grid\Displayers;

use Encore\Admin\Admin;

class Checkbox extends AbstractDisplayer
{
    public function display($options = [])
    {
        $radios = '';
        $name = $this->column->getName();

        if (is_string($this->value)) {
            $this->value = explode(',', $this->value);
        }

        foreach ($options as $value => $label) {
            $checked = in_array($value, $this->value) ? 'checked' : '';
            $radios .= <<<EOT

        <input type="checkbox" name="grid-checkbox-{$name}[]" value="{$value}" $checked />{$label}

EOT;
        }

        Admin::script($this->script());

        return <<<EOT
<form class="form-group grid-checkbox-$name" style="text-align:left;" data-key="{$this->getKey()}">
    $radios
    <button type="submit" class="btn btn-info btn-xs pull-left">
         {$this->trans('save')}
    </button>
    <button type="reset" class="btn btn-warning btn-xs pull-left" style="margin-left:10px;">
         {$this->trans('reset')}
    </button>
</form>
EOT;
    }

    protected function script()
    {
        $name = $this->column->getName();

        return <<<EOT

$('form.grid-checkbox-$name').on('submit', function () {
    var values = $(this).find('input:checkbox:checked').map(function (_, el) {
        return $(el).val();
    }).get();

    $.ajax({
        url: "{$this->getResource()}/" + $(this).data('key'),
        type: "POST",
        data: {
            $name: values,
            _token: LA.token,
            _method: 'PUT'
        },
        success: function (data) {
            toastr.success(data.message);
        }
    });

    return false;
});

EOT;
    }
}


text:
<?php

/*
 * Imports sublocations from TSV file
 *
 * SYNTAX
 * php import_sublocations.php <file.tsv>
 * e.g.
 * php import_sublocations.php sublocations.tsv
 *
 * NOTES
 * Make *absolutely sure* that the country file is UTF-8-encoded.
 * Lines containing a '#' are ignored
 * Line format is:
 * <parent location label>   <location label>  <name>  [<locations name>]
 * e.g.
 * fr-hauts-de-seine    chatenay-malabry    Châtenay-Malabry
 */

require_once 'bootstrap.php' ;
require_once (ROOT.'/sys/config/config.inc.php') ; // initialises $config

use Sociable\Model\Location;

if ($argc < 2) {
    echo 'Syntax: ' . $argv[0] . ' <sublocations_file>';
    return;
}

$file = $argv[1];
$lines = file($file);

$dm = $config->getDocumentManager() ;

foreach ($lines as $line) {
    if (preg_match('/#/', $line)) {
        continue;
    }
    $components = explode("\t", trim($line));
    $location = $dm->getRepository('Sociable\Model\Location')->findOneByLabel($components[0]) ;
    if (is_null($location)) {
        throw new Exception ('Location ' . $components[0] . ' not found in database') ;
    }
    $location->setSublocationsName('ville') ;
    $sublocation = new Location() ;
    $sublocation->setLabel($components[1]) ;
    $sublocation->setName($components[2]) ;
    $sublocation->setParentLocation($location) ;
    if (isset($components[3])) {
        $sublocation->setSublocationsName($components[3]) ;
    }
    $sublocation->validate();
    echo $components[1] . "\n" ;
    $dm->persist($sublocation);
}

$dm->flush();

?>


text:
package org.bitstrings.maven.plugins.portallocator;

import static org.bitstrings.maven.plugins.portallocator.util.TestUtils.*;

import org.apache.maven.plugin.testing.MojoRule;
import org.apache.maven.plugin.testing.resources.TestResources;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.junit.Rule;

public class AbstractPortAllocatorTest
{
    @Rule
    public MojoRule rule = new MojoRule();

    @Rule
    public TestResources resources = new TestResources();

    protected PortAllocatorServiceMock portAllocatorServiceMock = new PortAllocatorServiceMock();

    public MavenProject createNewMavenProject()
        throws Exception
    {
        return rule.readMavenProject( resources.getBasedir( "base" ) );
    }

    public MavenProject executeMojo( String... params )
        throws Exception
    {
        return executeMojo( createNewMavenProject(), params );
    }

    public MavenProject executeMojo( MavenProject project, String... params )
        throws Exception
    {
        Xpp3Dom[] doms = new Xpp3Dom[ params.length ];

        for ( int i = 0; i < params.length; i++ )
        {
            doms[ i ] = domFromString( params[ i ] );
        }

        rule.executeMojo( project, "allocate", doms );

        return project;
    }
}


text:
[//]: <> (# Inheritance)

- pubdate: 2016-10-05
- issue: 2

------

> 原文链接:http://dailyjs.com/post/js101-prototype-chains

## 继承链和构造函数
[//]: <> (## Inheritance Chains and Constructors)

如之前所见,JavaScript 对象拥有一个 `prototype` 属性,它被设计用来实现继承。一个对象的 `prototype` 属性可以被设置为另一个对象的实例,以此创建一个继承链:
[//]: <> (As we saw last week, JavaScript objects have a `prototype` property, which is designed to facilitate inheritance. An object's `prototype` property can be set to an instance of another object to create an inheritance chain:)

```javascript
function Shape(name) {
  this.x = 0;
  this.y = 0;
  this.name = name;
  console.log('Shape constructor called');
}

Shape.prototype = {
  move: function(x, y) {
    this.x += x;
    this.y += y;
  },

  toString: function() {
    return 'name: ' + this.name + ', at x: ' + this.x + ', y:' + this.y;
  }
};

// Rectangle
function Rectangle(name) {
  this.name = name;
  console.log('Rectangle constructor called');
}

Rectangle.prototype = new Shape();

var rect = new Rectangle('Player 1');
rect.move(1, 1);
console.log(rect.toString());
console.log(rect instanceof Rectangle);
```

运行会显示下面的输出:
[//]: <> (Running this will display the following output:)

```javascript
Shape constructor called
Rectangle constructor called
name: Player 1, at x: 1, y:1
true
```

注意无论 `Shape` 还是 `Rectangle` 构造函数都被调用了。这是因为这一行 `Rectangle.prototype = new Shape();`。
[//]: <> (Notice that both the `Shape` and `Rectangle` constructors are called. This is because of the line `Rectangle.prototype = new Shape();` -- the parent object's constructor isn't actually automatically called as a result of `new Rectangle()`. This is why I've duplicated the `this.name = name` line in both constructors.)

另外需要注意到 `rect.move` 和 `rect.toString` 会从 `Shape.prototype` 中调用方法。当解释器检查一个属性,首先会在当前对象中查找。如果没有找到属性,则会在对象的原型中查找,并以此类推。这就是原型链:
[//]: <> (Also notice that `rect.move` and `rect.toString` call the methods from `Shape.prototype`. When the interpreter checks for a property, it will examine the current object for it. If no such property is found, the prototype for the object is checked, and so on. This is the prototype chain:)

> 首先在被涉及的对象中直接查找属性,如果对象包含该命名属性,则引用此命名属性;如果对象不包含该命名属性,对象的原型会被检查;以此类推。
[//]: <> (> First the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.)

-- [Annotated ECMAScript 5.1](http://es5.github.io/#x4.2.1)

## 调用父级方法
[//]: <> (## Calling Parent Methods)

如果 `Rectangle` 想要一个不同的 `move` 方法,但想重用 `Shape` 中初始的方法,那么完全可以使用 `Function.prototype.apply` 来实现:
[//]: <> (If we wanted `Rectangle` to have a different `move` method, but reuse the original in `Shape`, then it's entirely possible to do so using `Function.prototype.apply`:)

```javascript
Rectangle.prototype.move = function(x, y) {
  console.log('Super method called');
  Shape.prototype.move.apply(this, arguments);
};
```

尽管 `Shape.prototype.move.apply` 看起来很复杂,但如果我们把它分解,实际上很简单:
[//]: <> (Even though `Shape.prototype.move.apply` looks complicated, it's actually very simple if we break it down:)

1. 我们想要调用来自 `Shape` 的 `move` 方法
2. 此方法保存在 `Shape.prototype.move`
3. 因为它是一个 `Function`,所以有一些我们可用的方法(函数是对象!)
4. [apply](https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/Function/apply) 特别的允许我们调用函数,而无需创建一个新实例
5. 它还允许我们提供一个 `this` 值,以及一个参数数组

[//]: <> (1. We want to call the `move` method from `Shape`)
[//]: <> (2. This method is stored in `Shape.prototype.move`)
[//]: <> (3. Since this is a `Function`, there are several methods available to us (functions are objects!))
[//]: <> (4. The [apply](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply) method in particular allows us to call the function without creating a new instance)
[//]: <> (5. It also allows us to provide our own value for `this`, and an array of arguments))

当一个函数执行时,[参数](http://es5.github.io/#x10.6)对象由解释器创建。`this` 对象是另外一个故事了 -- 到目前为止我假设你已经直观的理解它是什么了,但我们会在接下来的部分更详细的看看它。
[//]: <> (The [arguments](http://es5.github.io/#x10.6) object is created by the interpreter when a function is executed. The `this` object is a whole other story -- so far I've been assuming you have intuitively understood what it is, but we'll look at it in more detail in the next part.)

引用
[//]: <> (References)
- [Annotated ECMAScript 5.1](http://es5.github.io)
- [MDN documentation for apply](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply)


text:
/**
 * @file   NngSocket.hpp
 * @brief  NngSocket class prototype.
 * @author zer0
 * @date   2019-05-29
 */

#ifndef __INCLUDE_LIBTBAG__LIBTBAG_MQ_NNGSOCKET_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_MQ_NNGSOCKET_HPP__

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <libtbag/mq/NngBypass.hpp>

#include <string>
#include <vector>
#include <memory>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace mq {

/**
 * NngSocket class prototype.
 *
 * @author zer0
 * @date   2019-05-29
 */
class TBAG_API NngSocket
{
public:
    enum class SocketType
    {
        ST_NONE = 0,
        ST_BUS0,
        ST_PAIR0,
        ST_PAIR1,
        ST_PULL0,
        ST_PUSH0,
        ST_PUB0,
        ST_SUB0,
        ST_REP0,
        ST_REQ0,
        ST_RESPONDENT0,
        ST_SURVEYOR0,
    };

public:
    static char const * const getSocketTypeName(SocketType type) TBAG_NOEXCEPT;

public:
    TBAG_CONSTEXPR static const nng_duration DURATION_INFINITE = NNG_DURATION_INFINITE;
    TBAG_CONSTEXPR static const nng_duration DURATION_DEFAULT  = NNG_DURATION_DEFAULT;
    TBAG_CONSTEXPR static const nng_duration DURATION_ZERO     = NNG_DURATION_ZERO;

    TBAG_CONSTEXPR static int const SOCKNAME_MAX_LENGTH = 64; // including the terminating NULL byte.

public:
    struct Impl;
    using SharedImpl = std::shared_ptr<Impl>;

private:
    SharedImpl _impl;

public:
    NngSocket();
    NngSocket(NngSocket const & obj) TBAG_NOEXCEPT;
    NngSocket(NngSocket && obj) TBAG_NOEXCEPT;
    ~NngSocket();

public:
    NngSocket & operator =(NngSocket const & obj) TBAG_NOEXCEPT;
    NngSocket & operator =(NngSocket && obj) TBAG_NOEXCEPT;

public:
    void copy(NngSocket const & obj) TBAG_NOEXCEPT;
    void swap(NngSocket & obj) TBAG_NOEXCEPT;

public:
    inline friend void swap(NngSocket & lh, NngSocket & rh) TBAG_NOEXCEPT
    { lh.swap(rh); }

public:
    inline bool exists() const TBAG_NOEXCEPT
    { return static_cast<bool>(_impl); }

    inline operator bool() const TBAG_NOEXCEPT
    { return exists(); }

public:
    inline Impl       * get()       TBAG_NOEXCEPT { return _impl.get(); }
    inline Impl const * get() const TBAG_NOEXCEPT { return _impl.get(); }

    inline Impl       * operator ->()       TBAG_NOEXCEPT { return get(); }
    inline Impl const * operator ->() const TBAG_NOEXCEPT { return get(); }

    inline Impl       & ref()       TBAG_NOEXCEPT { return *get(); }
    inline Impl const & ref() const TBAG_NOEXCEPT { return *get(); }

    inline Impl       & operator *()       TBAG_NOEXCEPT { return ref(); }
    inline Impl const & operator *() const TBAG_NOEXCEPT { return ref(); }

public:
    void reset();

public:
    Err open(SocketType type, bool raw = false);
    Err close();

public:
    SocketType getType() const;
    char const * const getTypeName() const;

public:
    bool isOpened() const;

public:
    nng_socket getSocket() const;

public:
    Err listen(std::string const & url, nng_listener * lp = nullptr, int flags = 0);
    Err dial(std::string const & url, nng_dialer * lp = nullptr, int flags = 0);

public:
    Err send(void * data, size_t size, int flags = 0);
    Err recv(void * data, size_t * size, int flags = 0);

public:
    Err setopt(std::string const & key, bool value);
    Err setopt(std::string const & key, int value);
    Err setopt(std::string const & key, size_t value);
    Err setopt(std::string const & key, std::string const & value);
    Err setopt(std::string const & key, void * value);

    Err getopt(std::string const & key, bool * value) const;
    Err getopt(std::string const & key, int * value) const;
    Err getopt(std::string const & key, size_t * value) const;
    Err getopt(std::string const & key, std::string & value) const;
    Err getopt(std::string const & key, void ** value) const;

    Err setopt_uint64(std::string const & key, uint64_t value);
    Err getopt_uint64(std::string const & key, uint64_t * value) const;

    Err setopt_duration(std::string const & key, nng_duration value = DURATION_DEFAULT);
    Err getopt_duration(std::string const & key, nng_duration * value) const;

public:
    // Socket options:
    // https://nanomsg.github.io/nng/man/tip/nng_options.5.html

    /**
     * This is the socket receive timeout in milliseconds.
     * When no message is available for receiving at the socket for this period of time,
     * receive operations will fail with a return value of NNG_ETIMEDOUT.
     */
    Err setRecvTimeout(nng_duration ms);
    Err getRecvTimeout(nng_duration * ms) const;

    /**
     * This is the socket send timeout in milliseconds.
     * When a message cannot be queued for delivery by the socket for this period of time
     * (such as if send buffers are full),
     * the operation will fail with a return value of NNG_ETIMEDOUT.
     */
    Err setSendTimeout(nng_duration ms);
    Err getSendTimeout(nng_duration * ms) const;

    /**
     * This is the depth of the socket's receive buffer as a number of messages.
     * Messages received by a transport may be buffered until the application has accepted them for delivery.
     */
    Err setRecvNumberOfMessages(int size);
    Err getRecvNumberOfMessages(int * size) const;

    /**
     * This is the depth of the socket send buffer as a number of messages.
     * Messages sent by an application may be buffered by the socket
     * until a transport is ready to accept them for delivery.
     * This value must be an integer between 0 and 8192, inclusive.
     */
    Err setSendNumberOfMessages(int size);
    Err getSendNumberOfMessages(int * size) const;

    /**
     * This is the maximum message size that the will be accepted from a remote peer.
     * If a peer attempts to send a message larger than this, then the message will be discarded.
     * If the value of this is zero, then no limit on message sizes is enforced.
     * This option exists to prevent certain kinds of denial-of-service attacks,
     * where a malicious agent can claim to want to send an extraordinarily large message,
     * without sending any data. This option can be set for the socket,
     * but may be overridden for on a per-dialer or per-listener basis.
     */
    Err setRecvMaxSize(std::size_t size);
    Err getRecvMaxSize(std::size_t * size) const;
    Err setUnlimitedRecvMaxSize();

    /**
     * This is the minimum amount of time (milliseconds) to wait before attempting to establish
     * a connection after a previous attempt has failed.
     * This can be set on a socket, but it can also be overridden on an individual dialer.
     * The option is irrelevant for listeners.
     */
    Err setReconnectTimeMin(nng_duration ms);
    Err getReconnectTimeMin(nng_duration * ms) const;

    /**
     * This is the maximum amount of time (milliseconds) to wait before attempting to establish
     * a connection after a previous attempt has failed.
     * If this is non-zero, then the time between successive connection attempts will start at
     * the value of NNG_OPT_RECONNMINT, and grow exponentially, until it reaches this value.
     * If this value is zero, then no exponential back-off between connection attempts is done,
     * and each attempt will wait the time specified by NNG_OPT_RECONNMINT.
     * This can be set on a socket, but it can also be overridden on an individual dialer.
     * The option is irrelevant for listeners.
     */
    Err setReconnectTimeMax(nng_duration ms);
    Err getReconnectTimeMax(nng_duration * ms) const;

    /**
     * This the socket name.
     * By default this is a string corresponding to the value of the socket.
     * The string must fit within 64-bytes, including the terminating NUL byte.
     * The value is intended for application use, and is not used for anything in the library itself.
     */
    Err setSocketName(std::string const & name);
    Err getSocketName(std::string & name) const;

    /**
     * This is the maximum number of "hops" a message may traverse across a nng_device() forwarders.
     * The intention here is to prevent forwarding loops in device chains.
     * When this is supported, it can have a value between 1 and 255, inclusive.
     */
    Err setMaxTTL(int size);
    Err getMaxTTL(int * size) const;

    /**
     * This read-only option indicates whether the socket is in "raw" mode.
     * If true, the socket is in "raw" mode, and if false the socket is in "cooked" mode.
     *
     * Raw mode sockets generally do not have any protocol-specific semantics applied to them;
     * instead the application is expected to perform such semantics itself.
     *
     * (For example, in "cooked" mode a rep socket would automatically copy message headers
     * from a received message to the corresponding reply, whereas in "raw" mode this is not done.)
     *
     * @see <https://nanomsg.github.io/nng/man/tip/nng.7#raw_mode>
     */
    Err getRaw(bool * mode) const;

    /**
     * This read-only option is used to obtain the URL with which a listener or dialer was configured.
     * Accordingly it can only be used with dialers, listeners, and pipes.
     */
    Err getUrl(std::string & url) const;

    /**
     * This read-only option is used to obtain the 16-bit number for the socket's protocol.
     */
    Err getProtocolNumber(int * number) const;

    /**
     * This read-only option is used to obtain the 16-bit number of the peer protocol for the socket.
     */
    Err getPeerProtocolNumber(int * number) const;

    /**
     * This read-only option is used to obtain the name of the socket's protocol.
     */
    Err getProtocolName(std::string & name) const;

    /**
     * This read-only option is used to obtain the name of the peer protocol for the socket.
     */
    Err getPeerProtocolName(std::string & name) const;

public:
    std::string getPrintableInformationText() const;

public:
    struct State
    {
        std::string name;
        std::string desc;
    };

    static std::vector<State> getState();
    static void dumpState();
};

} // namespace mq

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

#endif // __INCLUDE_LIBTBAG__LIBTBAG_MQ_NNGSOCKET_HPP__


text:
Possible user states:

 - passive
 - pending
 - active
 - suspended
 - disabled

----------

State: passive
Description: This is the first state a user is in when first created.
             It is a Devise-only state as it is immediately reset to 'pending' through code.
Set when: A new user is created.

State: pending
Description: Indicates has not yet activated the account using the activation link sent via email.
Set when: A new user is created.

State: active
Description: Indicates the user is active and can log into the portal.
Set when: Either set directly (for users like students) or via activation links (for teachers).

State: suspended
Description: Indicates the user has been suspended by the portal admin.
Set when: The admin suspends the user via the admin pages.

State: disabled
Description: Indicates the user has been soft-deleted.
Set when: The user is deleted.


text:
class CampaignPresenter < BasePresenter
  presents :campaign

  delegate :name, to: :campaign

  def tags
    campaign.tags.map{|t| "##{t.name}"}.to_sentence
  end

  def number_of_users
    [
      h.pluralize(campaign.participating_users.count, "user"),
      (campaign.ended? ? "participated" : "is".pluralize(campaign.participating_users.count)),
      "in this competition"
    ].join(" ")
  end

end


text:
package org.teavm.model.instructions;

import org.teavm.model.Instruction;

public class EmptyInstruction extends Instruction {
    @Override
    public void acceptVisitor(InstructionVisitor visitor) {
        visitor.visit(this);
    }
}


text:
package org.scalatest.examples.funspec.oneinstancepertest

import org.scalatest._
import collection.mutable.ListBuffer

class ExampleSpec extends FunSpec with OneInstancePerTest {

  val builder = new StringBuilder("ScalaTest is ")
  val buffer = new ListBuffer[String]

  describe("Testing") {
    it("should be easy") {
      builder.append("easy!")
      assert(builder.toString === "ScalaTest is easy!")
      assert(buffer.isEmpty)
      buffer += "sweet"
    }

    it("should be fun") {
      builder.append("fun!")
      assert(builder.toString === "ScalaTest is fun!")
      assert(buffer.isEmpty)
    }
  }

  //SCALATESTJS,NATIVE-ONLY def newInstance: Suite with OneInstancePerTest = new ExampleSpec
}


text:
package networkmachine

import (
	"hps"
)

func Cast(machines []hps.IMachine) ([]*Machine, bool) {
	list := []*Machine{}
	for _, m := range machines {
		if nm, ok := m.(*Machine); ok {
			list = append(list, nm)
		} else {
			return nil, false
		}
	}
	return list, true
}


text:
package org.mifos.application.accounts.struts.actionforms;

import java.util.ResourceBundle;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.mifos.application.accounts.util.helpers.AccountConstants;
import org.mifos.application.customer.center.util.helpers.ValidateMethods;
import org.mifos.application.util.helpers.Methods;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.framework.struts.actionforms.BaseActionForm;
import org.mifos.framework.util.helpers.FilePaths;

public class NotesActionForm extends BaseActionForm {

    private String accountId;

    private String accountTypeId;

    private String prdOfferingName;

    private String comment;

    private String globalAccountNum;

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public String getPrdOfferingName() {
        return prdOfferingName;
    }

    public void setPrdOfferingName(String prdOfferingName) {
        this.prdOfferingName = prdOfferingName;
    }

    public String getAccountTypeId() {
        return accountTypeId;
    }

    public void setAccountTypeId(String accountTypeId) {
        this.accountTypeId = accountTypeId;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getGlobalAccountNum() {
        return globalAccountNum;
    }

    public void setGlobalAccountNum(String globalAccountNum) {
        this.globalAccountNum = globalAccountNum;
    }

    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        String methodCalled = request.getParameter(Methods.method.toString());
        ActionErrors errors = null;
        if (null != methodCalled) {
            if (Methods.cancel.toString().equals(methodCalled) || Methods.searchNext.toString().equals(methodCalled)
                    || Methods.search.toString().equals(methodCalled)
                    || Methods.searchPrev.toString().equals(methodCalled)
                    || Methods.load.toString().equals(methodCalled) || Methods.create.toString().equals(methodCalled)) {
                request.setAttribute(Constants.SKIPVALIDATION, Boolean.valueOf(true));
            } else if (Methods.preview.toString().equals(methodCalled)) {
                errors = handlePreviewValidations(request, errors);
            }
        }
        if (null != errors && !errors.isEmpty()) {
            request.setAttribute(Globals.ERROR_KEY, errors);
            request.setAttribute("methodCalled", methodCalled);
        }
        return errors;
    }

    private ActionErrors handlePreviewValidations(HttpServletRequest request, ActionErrors errors) {
        Locale locale = getUserContext(request).getPreferredLocale();
        ResourceBundle resources = ResourceBundle.getBundle(FilePaths.ACCOUNTS_UI_RESOURCE_PROPERTYFILE, locale);
        String notes = resources.getString("Account.Notes");
        if (ValidateMethods.isNullOrBlank(getComment())) {
            if (null == errors) {
                errors = new ActionErrors();
            }
            errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, notes));
        } else if (getComment().length() > AccountConstants.COMMENT_LENGTH) {
            // status length is more than 500, throw an exception
            if (null == errors) {
                errors = new ActionErrors();
            }
            errors.add(AccountConstants.MAX_LENGTH, new ActionMessage(AccountConstants.MAX_LENGTH, notes,
                    AccountConstants.COMMENT_LENGTH));
        }
        return errors;
    }
}


text:
* Bugfix: make sure stripeLive is used for customer creation
* Implement CloudCode function replyTo and add Reply button to Incoming
  Messages list.
* Bugfix subscription Stripe API key ; add error handling to sendReply.

# [1.8.4](https://github.com/evias/TwilioTreeBot/compare/1.8.3...1.8.4)

* Handle drop off: number at twilio should only be purchased upon successfull
  Stripe registration.

# [1.8.3](https://github.com/evias/TwilioTreeBot/compare/1.8.2...1.8.3)

* Improve logs for requestFeedback Job
* Implement FeedbackService.sendRequests to avoid synchronous loop
* Bugfix bitly call, make sure request scheme is included

# [1.8.0](https://github.com/evias/TwilioTreeBot/compare/1.7...1.8)

* Implement bit.ly API call for shortening office URL
* Remove Subscribe Now button: deprecated
* Implement Job requestFeedback ; implement Function listCancelledAccounts
* /subscription POST handler now also calls createNumber CloudCode function if
  user has cancelled subscription before.
* Implement CloudCode cancelSubscription function, also delete number using
  Twilio API.
* /subscription now auto-submits form after Stripe checkout

# [1.7.0](https://github.com/evias/TwilioTreeBot/compare/1.6...1.7)

* Bugfix subscription stripePlans being empty.
* Add Parse.Config 'whichStripeKey' to be 'stripeTest' or 'stripeLive'
* Refactor /my-account ; typo change on /subscription
* Implement Stripe /plans API call for /subscription & /my-account pages

# [1.6.0](https://github.com/evias/TwilioTreeBot/compare/1.5...1.6)

* Implement /cancel-subscription to cancel subscription at Stripe.
* Add feedback list to homepage ; redirect to homepage with error instead of
  rendering in /sendRequest
* Add plan subscription details to /my-account
* Add automatic redirection to /subscription for unsubscribed users ; add some
  visual feedback to /subscription
* Implement /subscription using Stripe REST API and Parse.Cloud.httpRequest
* Add .parse.local with empty values


text:
<?php
/*
 * Plugin Name: Facebook Likebox widget
 * Plugin URI: http://gazpo.com
 * Description: A widget to display facebook like box.
 * Version: 1.0
 * Author: Sami Ch.
 * Author URI: http://gazpo.com
 */

add_action( 'widgets_init', 'max_magazine_facebook_widgets' );

function max_magazine_facebook_widgets() {
	register_widget( 'max_magazine_facebook_widget' );
}

class max_magazine_facebook_widget extends WP_Widget {

function max_magazine_facebook_widget() {

		/* Widget settings */
		$widget_ops = array( 'classname' => 'widget_facebook', 'description' => __('A widget to display your facebook like box.', 'max-magazine') );

		/* Create the widget */
		$this->WP_Widget( 'max_magazine_facebook_widget', __('Max: Facebook Likebox', 'max-magazine'), $widget_ops );
	}

function widget( $args, $instance ) {
		extract( $args );
		/* Our variables from the widget settings. */
		$title = apply_filters('widget_title', $instance['title'] );
		$fburl = $instance['fburl'];

		echo $before_widget;

		if ( $title )
			echo $before_title . $title . $after_title;
	?>
		<iframe src="http://www.facebook.com/plugins/likebox.php?href=<?php echo $fburl; ?>&width=270&colorscheme=light&show_faces=true&border_color=white&stream=false&header=false&height=330" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:270px; height:330px;">
        <?php
		echo $after_widget;
	}

function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['fburl'] = $new_instance['fburl'];
		return $instance;
	}

	function form( $instance ) {

		/* default widget settings. */
		$defaults = array(
		'title' => '',
		'fburl' => "http://www.facebook.com/pages/Gazpocom/182192741803165"
		);
		$instance = wp_parse_args( (array) $instance, $defaults ); ?>

			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'max-magazine') ?>
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" />

			<label for="<?php echo $this->get_field_id( 'fburl' ); ?>"><?php _e('Facebook URL:', 'max-mag') ?>
			<input class="widefat" id="<?php echo $this->get_field_id( 'fburl' ); ?>" name="<?php echo $this->get_field_name( 'fburl' ); ?>" value="<?php echo $instance['fburl']; ?>" />

	<?php
	}
}

?>


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Transitions - jQuery Mobile Demos</title>
	<link rel="stylesheet"  href="../../css/themes/default/jquery.mobile-1.3.2.min.css">
	<link rel="stylesheet" href="../../_assets/css/jqm-demos.css">
	<link rel="shortcut icon" href="../../favicon.ico">
	<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">

Dialog

That was an animated page transition effect to a dialog that we added with a data-transition attribute on the link.

Since it uses CSS animations, this should be hardware accelerated on many devices. To see transitions, 3D transform support is required so if you only saw a fade transition that's the reason.

			Take me back


text:
package org.jbox2d.dynamics.joints;

import org.jbox2d.common.Mat22;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.SolverData;
import org.jbox2d.pooling.IWorldPool;

//Point-to-point constraint
//Cdot = v2 - v1
//   = v2 + cross(w2, r2) - v1 - cross(w1, r1)
//J = [-I -r1_skew I r2_skew ]
//Identity used:
//w k % (rx i + ry j) = w * (-ry i + rx j)

//Angle constraint
//Cdot = w2 - w1
//J = [0 0 -1 0 0 1]
//K = invI1 + invI2

/** A motor joint is used to control the relative motion between two bodies. A typical usage is to control the movement of a
 * dynamic body with respect to the ground.
 *
 * @author dmurph */
public class MotorJoint extends Joint {

	// Solver shared
	private final Vec2 m_linearOffset = new Vec2();
	private float m_angularOffset;
	private final Vec2 m_linearImpulse = new Vec2();
	private float m_angularImpulse;
	private float m_maxForce;
	private float m_maxTorque;
	private float m_correctionFactor;

	// Solver temp
	private int m_indexA;
	private int m_indexB;
	private final Vec2 m_rA = new Vec2();
	private final Vec2 m_rB = new Vec2();
	private final Vec2 m_localCenterA = new Vec2();
	private final Vec2 m_localCenterB = new Vec2();
	private final Vec2 m_linearError = new Vec2();
	private float m_angularError;
	private float m_invMassA;
	private float m_invMassB;
	private float m_invIA;
	private float m_invIB;
	private final Mat22 m_linearMass = new Mat22();
	private float m_angularMass;

	public MotorJoint (IWorldPool pool, MotorJointDef def) {
		super(pool, def);
		m_linearOffset.set(def.linearOffset);
		m_angularOffset = def.angularOffset;

		m_angularImpulse = 0.0f;

		m_maxForce = def.maxForce;
		m_maxTorque = def.maxTorque;
		m_correctionFactor = def.correctionFactor;
	}

	@Override
	public void getAnchorA (Vec2 out) {
		out.set(m_bodyA.getPosition());
	}

	@Override
	public void getAnchorB (Vec2 out) {
		out.set(m_bodyB.getPosition());
	}

	public void getReactionForce (float inv_dt, Vec2 out) {
		out.set(m_linearImpulse).mulLocal(inv_dt);
	}

	public float getReactionTorque (float inv_dt) {
		return m_angularImpulse * inv_dt;
	}

	public float getCorrectionFactor () {
		return m_correctionFactor;
	}

	public void setCorrectionFactor (float correctionFactor) {
		this.m_correctionFactor = correctionFactor;
	}

	/** Set the target linear offset, in frame A, in meters. */
	public void setLinearOffset (Vec2 linearOffset) {
		if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) {
			m_bodyA.setAwake(true);
			m_bodyB.setAwake(true);
			m_linearOffset.set(linearOffset);
		}
	}

	/** Get the target linear offset, in frame A, in meters. */
	public void getLinearOffset (Vec2 out) {
		out.set(m_linearOffset);
	}

	/** Get the target linear offset, in frame A, in meters. Do not modify. */
	public Vec2 getLinearOffset () {
		return m_linearOffset;
	}

	/** Set the target angular offset, in radians.
	 *
	 * @param angularOffset */
	public void setAngularOffset (float angularOffset) {
		if (angularOffset != m_angularOffset) {
			m_bodyA.setAwake(true);
			m_bodyB.setAwake(true);
			m_angularOffset = angularOffset;
		}
	}

	public float getAngularOffset () {
		return m_angularOffset;
	}

	/** Set the maximum friction force in N.
	 *
	 * @param force */
	public void setMaxForce (float force) {
		assert (force >= 0.0f);
		m_maxForce = force;
	}

	/** Get the maximum friction force in N. */
	public float getMaxForce () {
		return m_maxForce;
	}

	/** Set the maximum friction torque in N*m. */
	public void setMaxTorque (float torque) {
		assert (torque >= 0.0f);
		m_maxTorque = torque;
	}

	/** Get the maximum friction torque in N*m. */
	public float getMaxTorque () {
		return m_maxTorque;
	}

	@Override
	public void initVelocityConstraints (SolverData data) {
		m_indexA = m_bodyA.m_islandIndex;
		m_indexB = m_bodyB.m_islandIndex;
		m_localCenterA.set(m_bodyA.m_sweep.localCenter);
		m_localCenterB.set(m_bodyB.m_sweep.localCenter);
		m_invMassA = m_bodyA.m_invMass;
		m_invMassB = m_bodyB.m_invMass;
		m_invIA = m_bodyA.m_invI;
		m_invIB = m_bodyB.m_invI;

		final Vec2 cA = data.positions[m_indexA].c;
		float aA = data.positions[m_indexA].a;
		final Vec2 vA = data.velocities[m_indexA].v;
		float wA = data.velocities[m_indexA].w;

		final Vec2 cB = data.positions[m_indexB].c;
		float aB = data.positions[m_indexB].a;
		final Vec2 vB = data.velocities[m_indexB].v;
		float wB = data.velocities[m_indexB].w;

		final Rot qA = pool.popRot();
		final Rot qB = pool.popRot();
		final Vec2 temp = pool.popVec2();
		Mat22 K = pool.popMat22();

		qA.set(aA);
		qB.set(aB);

		// Compute the effective mass matrix.
		// m_rA = b2Mul(qA, -m_localCenterA);
		// m_rB = b2Mul(qB, -m_localCenterB);
		m_rA.x = qA.c * -m_localCenterA.x - qA.s * -m_localCenterA.y;
		m_rA.y = qA.s * -m_localCenterA.x + qA.c * -m_localCenterA.y;
		m_rB.x = qB.c * -m_localCenterB.x - qB.s * -m_localCenterB.y;
		m_rB.y = qB.s * -m_localCenterB.x + qB.c * -m_localCenterB.y;

		// J = [-I -r1_skew I r2_skew]
		// [ 0 -1 0 1]
		// r_skew = [-ry; rx]

		// Matlab
		// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
		// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
		// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
		float mA = m_invMassA, mB = m_invMassB;
		float iA = m_invIA, iB = m_invIB;

		K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
		K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
		K.ey.x = K.ex.y;
		K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;

		K.invertToOut(m_linearMass);

		m_angularMass = iA + iB;
		if (m_angularMass > 0.0f) {
			m_angularMass = 1.0f / m_angularMass;
		}

		// m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset);
		Rot.mulToOutUnsafe(qA, m_linearOffset, temp);
		m_linearError.x = cB.x + m_rB.x - cA.x - m_rA.x - temp.x;
		m_linearError.y = cB.y + m_rB.y - cA.y - m_rA.y - temp.y;
		m_angularError = aB - aA - m_angularOffset;

		if (data.step.warmStarting) {
			// Scale impulses to support a variable time step.
			m_linearImpulse.x *= data.step.dtRatio;
			m_linearImpulse.y *= data.step.dtRatio;
			m_angularImpulse *= data.step.dtRatio;

			final Vec2 P = m_linearImpulse;
			vA.x -= mA * P.x;
			vA.y -= mA * P.y;
			wA -= iA * (m_rA.x * P.y - m_rA.y * P.x + m_angularImpulse);
			vB.x += mB * P.x;
			vB.y += mB * P.y;
			wB += iB * (m_rB.x * P.y - m_rB.y * P.x + m_angularImpulse);
		} else {
			m_linearImpulse.setZero();
			m_angularImpulse = 0.0f;
		}

		pool.pushVec2(1);
		pool.pushMat22(1);
		pool.pushRot(2);

		// data.velocities[m_indexA].v = vA;
		data.velocities[m_indexA].w = wA;
		// data.velocities[m_indexB].v = vB;
		data.velocities[m_indexB].w = wB;
	}

	@Override
	public void solveVelocityConstraints (SolverData data) {
		final Vec2 vA = data.velocities[m_indexA].v;
		float wA = data.velocities[m_indexA].w;
		final Vec2 vB = data.velocities[m_indexB].v;
		float wB = data.velocities[m_indexB].w;

		float mA = m_invMassA, mB = m_invMassB;
		float iA = m_invIA, iB = m_invIB;

		float h = data.step.dt;
		float inv_h = data.step.inv_dt;

		final Vec2 temp = pool.popVec2();

		// Solve angular friction
		{
			float Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
			float impulse = -m_angularMass * Cdot;

			float oldImpulse = m_angularImpulse;
			float maxImpulse = h * m_maxTorque;
			m_angularImpulse = MathUtils.clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
			impulse = m_angularImpulse - oldImpulse;

			wA -= iA * impulse;
			wB += iB * impulse;
		}

		final Vec2 Cdot = pool.popVec2();

		// Solve linear friction
		{
			// Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor *
			// m_linearError;
			Cdot.x = vB.x + -wB * m_rB.y - vA.x - -wA * m_rA.y + inv_h * m_correctionFactor * m_linearError.x;
			Cdot.y = vB.y + wB * m_rB.x - vA.y - wA * m_rA.x + inv_h * m_correctionFactor * m_linearError.y;

			final Vec2 impulse = temp;
			Mat22.mulToOutUnsafe(m_linearMass, Cdot, impulse);
			impulse.negateLocal();
			final Vec2 oldImpulse = pool.popVec2();
			oldImpulse.set(m_linearImpulse);
			m_linearImpulse.addLocal(impulse);

			float maxImpulse = h * m_maxForce;

			if (m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) {
				m_linearImpulse.normalize();
				m_linearImpulse.mulLocal(maxImpulse);
			}

			impulse.x = m_linearImpulse.x - oldImpulse.x;
			impulse.y = m_linearImpulse.y - oldImpulse.y;

			vA.x -= mA * impulse.x;
			vA.y -= mA * impulse.y;
			wA -= iA * (m_rA.x * impulse.y - m_rA.y * impulse.x);

			vB.x += mB * impulse.x;
			vB.y += mB * impulse.y;
			wB += iB * (m_rB.x * impulse.y - m_rB.y * impulse.x);
		}

		pool.pushVec2(3);

		// data.velocities[m_indexA].v.set(vA);
		data.velocities[m_indexA].w = wA;
		// data.velocities[m_indexB].v.set(vB);
		data.velocities[m_indexB].w = wB;
	}

	@Override
	public boolean solvePositionConstraints (SolverData data) {
		return true;
	}
}


text:
{% load i18n %}

{% if notification_restriction %}

    {% if key %}
        {% trans "Pour les notifications de type" %} {{key}}:
    {% else %}
        {% trans "Pour toutes les notificaitons:" %}
    {% endif %}

{% trans "Désactiver les mails" %}

            <input type="checkbox" class="onoffswitch-checkbox" id="notifications_mail" {% if notification_restriction.no_email %}checked{% endif %}>

{% trans "Ignorer automatiquement" %}

            <input type="checkbox" class="onoffswitch-checkbox" id="notifications_mute" {% if notification_restriction.autoread %}checked{% endif %}>

{% trans "Ne jamais grouper les mails" %}

            <input type="checkbox" class="onoffswitch-checkbox" id="notifications_no_group" {% if notification_restriction.no_email_group %}checked{% endif %}>

    {% if not key and notification_restriction.no_email %}

        {% trans "Désactiver toutes les notifications est une mauvaise idée !" %}

    {% endif %}
{% else %}
    {% trans "Tu ne peux pas mettre de restriction sur le groupes de clé" %}
{% endif %}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DatasetTools (Java Machine Learning Library 0.1.7)</title>
<meta name="date" content="2012-07-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.javaml.tools

Class DatasetTools

java.lang.Object

net.sf.javaml.tools.DatasetTools

public final class DatasetTools
extends java.lang.Object

This class provides utility methods on data sets.

Version:

0.1.7

Author:

Thomas Abeel (thomas@abeel.be)

See Also:

Dataset,
DefaultDataset

Constructor Summary

Constructors

Constructor and Description

DatasetTools()

Method Summary

Methods

Modifier and Type
Method and Description

static Instance
average(Dataset data)

Creates an instance that contains the average values for the attributes.

static Dataset
bootstrap(Dataset data,
         int size,
         java.util.Random rg)

Deprecated.

static Instance
createInstanceFromAttribute(Dataset data,
                           int i)

Creates an Instance from the values of one particular attribute over all
 Instances in a data set.

static Instance
createInstanceFromClass(Dataset data)

Creates an Instance from the class labels over all Instances in a data
 set.

static double[]
getRandomInstance(Dataset data,
                 java.util.Random r)

Creates a random instance using the
 getMinMax(Dataset) method.

static Instance
maxAttributes(Dataset data)

Create an instance that contains all the maximum values for the
 attributes.

static void
merge(Dataset... datasets)

All data will be merged together in the first supplied data set.

static Instance
minAttributes(Dataset data)

Create an instance that contains all the minimum values for the
 attributes.

static Instance
percentile(Dataset data,
          double perc)

Calculates the percentile hinge for a given percentile.

static Instance
standardDeviation(Dataset data,
                 Instance avg)

Creates an instance that contains the standard deviation of the values
 for each attribute.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DatasetTools

public DatasetTools()

Method Detail

merge

public static void merge(Dataset... datasets)

All data will be merged together in the first supplied data set.

Parameters:

datasets - a number of data sets

bootstrap

@Deprecated
public static Dataset bootstrap(Dataset data,
                           int size,
                           java.util.Random rg)

Deprecated.

Generate a bootstrap sample from the data set with a particular size,
 using the given random generator.

 This is done by sampling with replacement.

Parameters:

data - data set to bootstrap from

size - number of instances in the output data

rg - random generator to use for the bootstrapping

Returns:

bootstrap of the supplied data

maxAttributes

public static Instance maxAttributes(Dataset data)

Create an instance that contains all the maximum values for the
 attributes.

Parameters:

data - data set to find minimum attribute values for

Returns:

Instance representing the minimum values for each attribute

minAttributes

public static Instance minAttributes(Dataset data)

Create an instance that contains all the minimum values for the
 attributes.

Parameters:

data - data set to calculate minimum attribute values for

Returns:

Instance representing all minimum attribute values

standardDeviation

public static Instance standardDeviation(Dataset data,
                         Instance avg)

Creates an instance that contains the standard deviation of the values
 for each attribute.

Parameters:

data - data set to calculate attribute value standard deviations for

avg - the average instance for the data set

Returns:

Instance representing the standard deviation of the values for
         each attribute

average

public static Instance average(Dataset data)

Creates an instance that contains the average values for the attributes.

Parameters:

data - data set to calculate average attribute values for

Returns:

Instance representing the average attribute values

percentile

public static Instance percentile(Dataset data,
                  double perc)

Calculates the percentile hinge for a given percentile.

Parameters:

data - data set to calculate percentile for

perc - percentile to calculate, Q1=25, Q2=median=50,Q3=75

Returns:

createInstanceFromClass

public static Instance createInstanceFromClass(Dataset data)

Creates an Instance from the class labels over all Instances in a data
 set.

 The indices of the class labels are used because the class labels can be
 any Object.

Parameters:

data - data set to create class label instance for

Returns:

instance with class label indices as values.

createInstanceFromAttribute

public static Instance createInstanceFromAttribute(Dataset data,
                                   int i)

Creates an Instance from the values of one particular attribute over all
 Instances in a data set.

Parameters:

data -

i -

Returns:

getRandomInstance

public static double[] getRandomInstance(Dataset data,
                         java.util.Random r)

Creates a random instance using the
 getMinMax(Dataset) method. The random instance is
 created by choosing a random value for each attribute (which is between
 the min and max value of the attribute).

Parameters:

data - the data set

Returns:

a random instance

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

			Copyright © 2006-2012 - Thomas Abeel - All Rights Reserved.


text:
package tests

import (
	"fmt"
	"github.com/pubnub/go/messaging"
	"testing"
)

// TestTimeStart prints a message on the screen to mark the beginning of
// time tests.
// PrintTestMessage is defined in the common.go file.
func TestTimeStart(t *testing.T) {
	PrintTestMessage("==========Time tests start==========")
}

// TestServerTime calls the GetTime method of the messaging to test the time
func TestServerTime(t *testing.T) {
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")

	returnTimeChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	responseChannel := make(chan string)
	waitChannel := make(chan string)

	go pubnubInstance.GetTime(returnTimeChannel, errorChannel)
	go ParseTimeResponse(returnTimeChannel, responseChannel)
	go ParseErrorResponse(errorChannel, responseChannel)
	go WaitForCompletion(responseChannel, waitChannel)
	ParseWaitResponse(waitChannel, t, "Time")
}

// ParseTimeResponse parses the time response from the pubnub api.
// On error the test fails.
func ParseTimeResponse(returnChannel chan []byte, responseChannel chan string) {
	for {
		value, ok := <-returnChannel
		if !ok {
			break
		}
		if string(value) != "[]" {
			response := fmt.Sprintf("%s", value)
			if response != "" {
				responseChannel <- "Server time: passed."
				break
			} else {
				responseChannel <- "Server time: failed."
				break
			}
		}
	}
}

// TestTimeEnd prints a message on the screen to mark the end of
// time tests.
// PrintTestMessage is defined in the common.go file.
func TestTimeEnd(t *testing.T) {
	PrintTestMessage("==========Time tests end==========")
}


text:
from setuptools import setup, find_packages

with open('README.md') as f:
    long_description = f.read()

setup(
    name='windy',
    version='0.9.9',
    packages = find_packages(),
    entry_points={
        "console_scripts": ['windy = windy.gui.application:main'],
        'gui_scripts': ['windy = windy.gui.application:main', ]
        },
    description='windy is Windows GUI application for managing user/system environment variables.',
    long_description=long_description,
    url='http://github.com/zeljko-m-gavrilovic/windy',
    author='bigNumbers',
    author_email='zeljko.m.gavrilovic@gmail.com',
    license='MIT',
    classifiers=[
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: System Administrators",
        "Operating System :: Microsoft :: Windows",
        "Topic :: Desktop Environment",
        "License :: Freeware",
        "Topic :: Utilities"
      ],
    keywords=["windows", "environment", "variables", "path", "developer"],
    zip_safe=False
    )


text:
'use strict';

angular.module('av001App').controller('AddressDialogController',
    ['$scope', '$stateParams', '$modalInstance', 'entity', 'Address', 'Client',
        function($scope, $stateParams, $modalInstance, entity, Address, Client) {

        $scope.address = entity;
        $scope.clients = Client.query();
        $scope.load = function(id) {
            Address.get({id : id}, function(result) {
                $scope.address = result;
            });
        };

        var onSaveFinished = function (result) {
            $scope.$emit('av001App:addressUpdate', result);
            $modalInstance.close(result);
        };

        $scope.save = function () {
            if ($scope.address.id != null) {
                Address.update($scope.address, onSaveFinished);
            } else {
                Address.save($scope.address, onSaveFinished);
            }
        };

        $scope.clear = function() {
            $modalInstance.dismiss('cancel');
        };
}]);


text:
import { Component, DebugElement } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By, DOCUMENT } from '@angular/platform-browser';

import { TocComponent } from './toc.component';
import { TocItem, TocService } from 'app/shared/toc.service';

describe('TocComponent', () => {
  let tocComponentDe: DebugElement;
  let tocComponent: TocComponent;
  let tocService: TestTocService;

  let page: {
    listItems: DebugElement[];
    tocHeading: DebugElement;
    tocHeadingButton: DebugElement;
    tocMoreButton: DebugElement;
  };

  function setPage(): typeof page {
    return {
      listItems: tocComponentDe.queryAll(By.css('ul.toc-list>li')),
      tocHeading: tocComponentDe.query(By.css('.toc-heading')),
      tocHeadingButton: tocComponentDe.query(By.css('.toc-heading button')),
      tocMoreButton: tocComponentDe.query(By.css('button.toc-more-items')),
    };
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HostEmbeddedTocComponent, HostNotEmbeddedTocComponent, TocComponent ],
      providers: [
        { provide: TocService, useClass: TestTocService }
      ]
    })
    .compileComponents();
  }));

  describe('when embedded in doc body', () => {
    let fixture: ComponentFixture<HostEmbeddedTocComponent>;

    beforeEach(() => {
      fixture = TestBed.createComponent(HostEmbeddedTocComponent);
      tocComponentDe = fixture.debugElement.children[0];
      tocComponent = tocComponentDe.componentInstance;
      tocService = TestBed.get(TocService);
    });

    it('should create tocComponent', () => {
      expect(tocComponent).toBeTruthy();
    });

    it('should be in embedded state', () => {
      expect(tocComponent.isEmbedded).toEqual(true);
    });

    it('should not display anything when no TocItems', () => {
      tocService.tocList = [];
      fixture.detectChanges();
      expect(tocComponentDe.children.length).toEqual(0);
    });

    describe('when four TocItems', () => {

      beforeEach(() => {
        tocService.tocList.length = 4;
        fixture.detectChanges();
        page = setPage();
      });

      it('should have four displayed items', () => {
        expect(page.listItems.length).toEqual(4);
      });

      it('should not have secondary items', () => {
        expect(tocComponent.hasSecondary).toEqual(false, 'hasSecondary flag');
        const aSecond = page.listItems.find(item => item.classes.secondary);
        expect(aSecond).toBeFalsy('should not find a secondary');
      });

      it('should not display expando buttons', () => {
        expect(page.tocHeadingButton).toBeFalsy('top expand/collapse button');
        expect(page.tocMoreButton).toBeFalsy('bottom more button');
      });
    });

    describe('when many TocItems', () => {

      beforeEach(() => {
        fixture.detectChanges();
        page = setPage();
      });

      it('should have more than 4 displayed items', () => {
        expect(page.listItems.length).toBeGreaterThan(4);
        expect(page.listItems.length).toEqual(tocService.tocList.length);
      });

      it('should be in "closed" (not expanded) state at the start', () => {
        expect(tocComponent.isClosed).toBeTruthy();
      });

      it('should have "closed" class at the start', () => {
        expect(tocComponentDe.children[0].classes.closed).toEqual(true);
      });

      it('should display expando buttons', () => {
        expect(page.tocHeadingButton).toBeTruthy('top expand/collapse button');
        expect(page.tocMoreButton).toBeTruthy('bottom more button');
      });

      it('should have secondary items', () => {
        expect(tocComponent.hasSecondary).toEqual(true, 'hasSecondary flag');
      });

      // CSS should hide items with the secondary class when closed
      it('should have secondary item with a secondary class', () => {
        const aSecondary = page.listItems.find(item => item.classes.secondary);
        expect(aSecondary).toBeTruthy('should find a secondary');
        expect(aSecondary.classes.secondary).toEqual(true, 'has secondary class');
      });

      describe('after click expando button', () => {

        beforeEach(() => {
          page.tocHeadingButton.nativeElement.click();
          fixture.detectChanges();
        });

        it('should not be "closed"', () => {
          expect(tocComponent.isClosed).toEqual(false);
        });

        it('should not have "closed" class', () => {
          expect(tocComponentDe.children[0].classes.closed).toBeFalsy();
        });
      });
    });
  });

  describe('when in side panel (not embedded))', () => {
    let fixture: ComponentFixture<HostNotEmbeddedTocComponent>;

    beforeEach(() => {
      fixture = TestBed.createComponent(HostNotEmbeddedTocComponent);
      tocComponentDe = fixture.debugElement.children[0];
      tocComponent = tocComponentDe.componentInstance;
      fixture.detectChanges();
      page = setPage();
    });

    it('should not be in embedded state', () => {
      expect(tocComponent.isEmbedded).toEqual(false);
    });

    it('should display all items', () => {
      expect(page.listItems.length).toEqual(tocService.tocList.length);
    });

    it('should not have secondary items', () => {
      expect(tocComponent.hasSecondary).toEqual(false, 'hasSecondary flag');
      const aSecond = page.listItems.find(item => item.classes.secondary);
      expect(aSecond).toBeFalsy('should not find a secondary');
    });

    it('should not display expando buttons', () => {
      expect(page.tocHeadingButton).toBeFalsy('top expand/collapse button');
      expect(page.tocMoreButton).toBeFalsy('bottom more button');
    });
  });

});

//// helpers ////
@Component({
  selector: 'aio-embedded-host',
  template: '<aio-toc class="embedded"></aio-toc>'
})
class HostEmbeddedTocComponent {}

@Component({
  selector: 'aio-not-embedded-host',
  template: '<aio-toc></aio-toc>'
})
class HostNotEmbeddedTocComponent {}

class TestTocService {
  tocList: TocItem[] = getTestTocList();
}

// tslint:disable:quotemark

function getTestTocList() {
  return [
    {
      "content": "Heading one",
      "href": "fizz/buzz#heading-one-special-id",
      "level": "h2",
      "title": "Heading one"
    },
    {
      "content": "H2 Two",
      "href": "fizz/buzz#h2-two",
      "level": "h2",
      "title": "H2 Two"
    },
    {
      "content": "H2 Three",
      "href": "fizz/buzz#h2-three",
      "level": "h2",
      "title": "H2 Three"
    },
    {
      "content": "H3 3a",
      "href": "fizz/buzz#h3-3a",
      "level": "h3",
      "title": "H3 3a"
    },
    {
      "content": "H3 3b",
      "href": "fizz/buzz#h3-3b",
      "level": "h3",
      "title": "H3 3b"
    },
    {
      "content": "H2 four",
      "href": "fizz/buzz#h2-four",
      "level": "h2",
      "title": "H2 4"
    }
  ];
}


text:
function(get_system_libs return_var)
  # Returns in `return_var' a list of system libraries used by LLVM.
  if( NOT MSVC )
    if( MINGW )
      set(system_libs ${system_libs} imagehlp psapi)
    elseif( CMAKE_HOST_UNIX )
      if( HAVE_LIBDL )
	set(system_libs ${system_libs} ${CMAKE_DL_LIBS})
      endif()
      if( LLVM_ENABLE_THREADS AND HAVE_LIBPTHREAD )
	set(system_libs ${system_libs} pthread)
      endif()
    endif( MINGW )
  endif( NOT MSVC )
  set(${return_var} ${system_libs} PARENT_SCOPE)
endfunction(get_system_libs)

function(link_system_libs target)
  get_system_libs(llvm_system_libs)
  target_link_libraries(${target} ${llvm_system_libs})
endfunction(link_system_libs)

function(is_llvm_target_library library return_var)
  # Sets variable `return_var' to ON if `library' corresponds to a
  # LLVM supported target. To OFF if it doesn't.
  set(${return_var} OFF PARENT_SCOPE)
  string(TOUPPER "${library}" capitalized_lib)
  string(TOUPPER "${LLVM_ALL_TARGETS}" targets)
  foreach(t ${targets})
    if( capitalized_lib STREQUAL t OR
	capitalized_lib STREQUAL "LLVM${t}" OR
	capitalized_lib STREQUAL "LLVM${t}CODEGEN" OR
	capitalized_lib STREQUAL "LLVM${t}ASMPARSER" OR
	capitalized_lib STREQUAL "LLVM${t}ASMPRINTER" OR
	capitalized_lib STREQUAL "LLVM${t}DISASSEMBLER" OR
	capitalized_lib STREQUAL "LLVM${t}INFO" )
      set(${return_var} ON PARENT_SCOPE)
      break()
    endif()
  endforeach()
endfunction(is_llvm_target_library)

macro(llvm_config executable)
  explicit_llvm_config(${executable} ${ARGN})
endmacro(llvm_config)

function(explicit_llvm_config executable)
  set( link_components ${ARGN} )

  explicit_map_components_to_libraries(LIBRARIES ${link_components})
  target_link_libraries(${executable} ${LIBRARIES})
endfunction(explicit_llvm_config)

# This is a variant intended for the final user:
function(llvm_map_components_to_libraries OUT_VAR)
  explicit_map_components_to_libraries(result ${ARGN})
  get_system_libs(sys_result)
  set( ${OUT_VAR} ${result} ${sys_result} PARENT_SCOPE )
endfunction(llvm_map_components_to_libraries)

function(explicit_map_components_to_libraries out_libs)
  set( link_components ${ARGN} )
  get_property(llvm_libs GLOBAL PROPERTY LLVM_LIBS)
  string(TOUPPER "${llvm_libs}" capitalized_libs)

  # Expand some keywords:
  list(FIND LLVM_TARGETS_TO_BUILD "${LLVM_NATIVE_ARCH}" have_native_backend)
  list(FIND link_components "engine" engine_required)
  if( NOT engine_required EQUAL -1 )
    list(FIND LLVM_TARGETS_WITH_JIT "${LLVM_NATIVE_ARCH}" have_jit)
    if( NOT have_native_backend EQUAL -1 AND NOT have_jit EQUAL -1 )
      list(APPEND link_components "jit")
      list(APPEND link_components "native")
    else()
      list(APPEND link_components "interpreter")
    endif()
  endif()
  list(FIND link_components "native" native_required)
  if( NOT native_required EQUAL -1 )
    if( NOT have_native_backend EQUAL -1 )
      list(APPEND link_components ${LLVM_NATIVE_ARCH})
    endif()
  endif()

  # Translate symbolic component names to real libraries:
  foreach(c ${link_components})
    # add codegen, asmprinter, asmparser, disassembler
    list(FIND LLVM_TARGETS_TO_BUILD ${c} idx)
    if( NOT idx LESS 0 )
      list(FIND llvm_libs "LLVM${c}CodeGen" idx)
      if( NOT idx LESS 0 )
	list(APPEND expanded_components "LLVM${c}CodeGen")
      else()
	list(FIND llvm_libs "LLVM${c}" idx)
	if( NOT idx LESS 0 )
	  list(APPEND expanded_components "LLVM${c}")
	else()
	  message(FATAL_ERROR "Target ${c} is not in the set of libraries.")
	endif()
      endif()
      list(FIND llvm_libs "LLVM${c}AsmPrinter" asmidx)
      if( NOT asmidx LESS 0 )
        list(APPEND expanded_components "LLVM${c}AsmPrinter")
      endif()
      list(FIND llvm_libs "LLVM${c}AsmParser" asmidx)
      if( NOT asmidx LESS 0 )
        list(APPEND expanded_components "LLVM${c}AsmParser")
      endif()
      list(FIND llvm_libs "LLVM${c}Info" asmidx)
      if( NOT asmidx LESS 0 )
        list(APPEND expanded_components "LLVM${c}Info")
      endif()
      list(FIND llvm_libs "LLVM${c}Disassembler" asmidx)
      if( NOT asmidx LESS 0 )
        list(APPEND expanded_components "LLVM${c}Disassembler")
      endif()
    elseif( c STREQUAL "native" )
      # already processed
    elseif( c STREQUAL "nativecodegen" )
      list(APPEND expanded_components "LLVM${LLVM_NATIVE_ARCH}CodeGen")
    elseif( c STREQUAL "backend" )
      # same case as in `native'.
    elseif( c STREQUAL "engine" )
      # already processed
    elseif( c STREQUAL "all" )
      list(APPEND expanded_components ${llvm_libs})
    else( NOT idx LESS 0 )
      # Canonize the component name:
      string(TOUPPER "${c}" capitalized)
      list(FIND capitalized_libs LLVM${capitalized} lib_idx)
      if( lib_idx LESS 0 )
        # The component is unknown. Maybe is an omitted target?
        is_llvm_target_library(${c} iltl_result)
        if( NOT iltl_result )
          message(FATAL_ERROR "Library `${c}' not found in list of llvm libraries.")
        endif()
      else( lib_idx LESS 0 )
        list(GET llvm_libs ${lib_idx} canonical_lib)
        list(APPEND expanded_components ${canonical_lib})
      endif( lib_idx LESS 0 )
    endif( NOT idx LESS 0 )
  endforeach(c)
  # Expand dependencies while topologically sorting the list of libraries:
  list(LENGTH expanded_components lst_size)
  set(cursor 0)
  set(processed)
  while( cursor LESS lst_size )
    list(GET expanded_components ${cursor} lib)
    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib})
    list(APPEND expanded_components ${lib_deps})
    # Remove duplicates at the front:
    list(REVERSE expanded_components)
    list(REMOVE_DUPLICATES expanded_components)
    list(REVERSE expanded_components)
    list(APPEND processed ${lib})
    # Find the maximum index that doesn't have to be re-processed:
    while(NOT "${expanded_components}" MATCHES "^${processed}.*" )
      list(REMOVE_AT processed -1)
    endwhile()
    list(LENGTH processed cursor)
    list(LENGTH expanded_components lst_size)
  endwhile( cursor LESS lst_size )
  # Return just the libraries included in this build:
  set(result)
  foreach(c ${expanded_components})
    list(FIND llvm_libs ${c} lib_idx)
    if( NOT lib_idx LESS 0 )
      set(result ${result} ${c})
    endif()
  endforeach(c)
  set(${out_libs} ${result} PARENT_SCOPE)
endfunction(explicit_map_components_to_libraries)


text:
%
% Generic function for writing ODL (LBL/CAT) files using a "struct string lists" (SSL) on the same format as returned
% from read_ODL_from_struct. Does some basic "beautification" (indentation, added whitespace to make equal signs and
% value left-aligned).
%
% NOTE: Overwrites destination file if pre-existing.
% NOTE: Multiline values are not indented (except the key itself).
% NOTE: Does not quote any value strings. They have to be "pre-quoted".
%
%
% ARGUMENTS
% =========
% Ssl                 : SSL data struct. See EJ_library.PDS_utils.convert_ODL_to_structs.
% endRowsList         : Cell array of strings, one for every line after the final "END" statement (without CR, LF).
% contentRowMaxLength : Max row length, excluding line break.
%                       NOTE: This is not a rigorous line breaking for everything; only some things. In particular does
%                       not even try to line break contents of endRowsList.
%
%
% Initially created 2016-07-07 by Erik P G Johansson, IRF Uppsala, Sweden.
%
function write_ODL_file(filePath, Ssl, endRowsList, indentationLength, contentRowMaxLength)
%
% PROPOSAL: Implement additional empty rows before/after OBJECT/END_OBJECT.
%    NOTE: Only one row between END_OBJECT and OBJECT. ==> Non-trivial.
%
% PROPOSAL: Add assertion check for (dis)allowed characters (superscripted hyphen disallowed in particular).
% PROPOSAL: Also accept data on the format of non-hierarchical list of key-value pairs?!
% PROPOSAL: Insert line-breaks (CR+LF) to limit row length.
%   NOTE: DVAL indicates that row length (including CR+LF) should be max 72 for .CAT files and 80 for .LBL files.
%   PROPOSAL: Line-break (quoted) string values.
%       CON: Could potentially mess up, long manually line-broken string values.
%
% PROPOSAL: Change into function producing list of strings instead of writing to file.
%   PRO: Good for testing.
% PROPOSAL: ROW_MAX_LENGTH som argument.
%   PROPOSAL: Optional argument with default value?
% PROPOSAL: Change name: write_ODL_file

    LINE_BREAK = sprintf('\r\n');

    % ASSERTION
    if ~isnumeric(indentationLength) || (numel(indentationLength) ~= 1)
        error('Illegal indentationLength argument.')
    end

    [fileId, errorMsg] = fopen(filePath, 'w');
    if fileId == -1
        error('Failed to open file "%s": "%s"', filePath, errorMsg)
    end

    fileStr = EJ_library.PDS_utils.convert_struct_to_ODL(Ssl, endRowsList, indentationLength, contentRowMaxLength, LINE_BREAK);
    fwrite(fileId, fileStr);

    %for i=1:length(endRowsList)
    %    fwrite(fileId, [endRowsList{i}, LINE_BREAK]);
    %end

    fclose(fileId);
end


text:
int main()
{
    // currentVal is the number we are counting; we'll read new values into val
    int currentVal = 0, val = 0;
    int count = 0;
    if (std::cin >> val)
        currentVal = val;
    // when encountering EOF(^+d in macOS), loop terminates
    while (std::cin >> val)
    {
        // if currentVal equals val, increment count by one
        if (currentVal == val)
            count += 1;
    }
    std::cout << currentVal << " occurs " << count << " times" << std::endl;
    return 0;
}