text:
package io.skysail.server.app.todos.todos.resources.test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.restlet.data.Status;

import io.skysail.api.responses.SkysailResponse;
import io.skysail.server.app.todos.TodoApplication;
import io.skysail.server.app.todos.TodoList;
import io.skysail.server.app.todos.todos.Todo;

@Ignore

public class PostTodoResourceTest extends AbstractTodoResourceTest {

    private TodoList aList;

    @Before
    public void setUp() throws Exception {
        super.setUp();
        aList = createList();
        setAttributes(TodoApplication.LIST_ID, aList.getId());
    }

    @Test
    public void empty_html_form_yields_validation_failure() {
        form.add("title", "");
        form.add("list", aList.getId());
        SkysailResponse<Todo> post = postTodoResource.post(form, HTML_VARIANT);
        assertSingleValidationFailure(postTodoResource, post, "title", "size must be between");
    }

    @Test
    public void start_date_after_due_date_yields_validation_failure() {
        form.add("title", "title_" + randomString());
        form.add("list", aList.getId());
        form.add("due", "2099-12-01");
        form.add("startDate", "2100-12-30");

        SkysailResponse<Todo> post = postTodoResource.post(form, HTML_VARIANT);
        assertSingleValidationFailure(postTodoResource, post, "", "the start date must be before the due date");
    }

    @Test
    public void valid_form_data_yields_new_entity() {
        String title = "title_" + randomString();
        form.add("title", title);
        form.add("list", aList.getId());
        form.add("due", "2099-12-01");

        SkysailResponse<Todo> result = postTodoResource.post(form, HTML_VARIANT);

        assertTodoResult(postTodoResource, result, title);
    }

    @Test
    public void valid_json_data_yields_new_entity() {
        String title = "title_" + randomString();
        Todo todo = new Todo(title);
        //todo.setParent(aList.getId());
        todo.setDue(Date.from(LocalDate.now().plusMonths(1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
        SkysailResponse<Todo> result = postTodoResource.post(todo, HTML_VARIANT);

        assertTodoResult(postTodoResource, result, title);
    }

    @Test
    public void urgency_is_calculated() {
        //TodoList aList = createList();
        form.add("title", "title_" + randomString());
        form.add("list", aList.getId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        form.add("startDate", sdf.format(nowPlusWeeksAndDays(-1, -1)));
        form.add("due", sdf.format(nowPlusWeeks(1)));
        SkysailResponse<Todo> post = postTodoResource.post(form, HTML_VARIANT);
        assertThat(responses.get(postTodoResource.getClass().getName()).getStatus(), is(equalTo(Status.REDIRECTION_SEE_OTHER)));
        assertThat(post.getEntity().getUrgency(), greaterThan(0));
        assertThat(post.getEntity().getUrgency(), not(greaterThan(100)));
    }

    private Date nowPlusWeeks(int weeksOffset) {
        return Date.from(LocalDate.now().plusWeeks(weeksOffset).atStartOfDay().toInstant(ZoneOffset.MIN));
    }

    private Date nowPlusWeeksAndDays(int weeksOffset, int dayOffset) {
        return Date.from(LocalDate.now().plusWeeks(weeksOffset).plusDays(dayOffset).atStartOfDay()
                .toInstant(ZoneOffset.MIN));
    }

}


text:
async function fn() {
    await Promise.resolve();
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef DEVICE_CONTROL_H
#define DEVICE_CONTROL_H

#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

    int wrap_writer(char,FILE *);
    int wrap_reader(FILE *);

#ifdef __cplusplus
}
#endif

#endif /* DEVICE_CONTROL_H */


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/TagSpecification.h>
#include <utility>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /**
   */
  class AWS_EC2_API CreateLocalGatewayRouteTableVpcAssociationRequest : public EC2Request
  {
  public:
    CreateLocalGatewayRouteTableVpcAssociationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateLocalGatewayRouteTableVpcAssociation"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
The ID of the local gateway route table.

     */
    inline const Aws::String& GetLocalGatewayRouteTableId() const{ return m_localGatewayRouteTableId; }

    /**
     *
The ID of the local gateway route table.

     */
    inline bool LocalGatewayRouteTableIdHasBeenSet() const { return m_localGatewayRouteTableIdHasBeenSet; }

    /**
     *
The ID of the local gateway route table.

     */
    inline void SetLocalGatewayRouteTableId(const Aws::String& value) { m_localGatewayRouteTableIdHasBeenSet = true; m_localGatewayRouteTableId = value; }

    /**
     *
The ID of the local gateway route table.

     */
    inline void SetLocalGatewayRouteTableId(Aws::String&& value) { m_localGatewayRouteTableIdHasBeenSet = true; m_localGatewayRouteTableId = std::move(value); }

    /**
     *
The ID of the local gateway route table.

     */
    inline void SetLocalGatewayRouteTableId(const char* value) { m_localGatewayRouteTableIdHasBeenSet = true; m_localGatewayRouteTableId.assign(value); }

    /**
     *
The ID of the local gateway route table.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithLocalGatewayRouteTableId(const Aws::String& value) { SetLocalGatewayRouteTableId(value); return *this;}

    /**
     *
The ID of the local gateway route table.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithLocalGatewayRouteTableId(Aws::String&& value) { SetLocalGatewayRouteTableId(std::move(value)); return *this;}

    /**
     *
The ID of the local gateway route table.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithLocalGatewayRouteTableId(const char* value) { SetLocalGatewayRouteTableId(value); return *this;}

    /**
     *
The ID of the VPC.

     */
    inline const Aws::String& GetVpcId() const{ return m_vpcId; }

    /**
     *
The ID of the VPC.

     */
    inline bool VpcIdHasBeenSet() const { return m_vpcIdHasBeenSet; }

    /**
     *
The ID of the VPC.

     */
    inline void SetVpcId(const Aws::String& value) { m_vpcIdHasBeenSet = true; m_vpcId = value; }

    /**
     *
The ID of the VPC.

     */
    inline void SetVpcId(Aws::String&& value) { m_vpcIdHasBeenSet = true; m_vpcId = std::move(value); }

    /**
     *
The ID of the VPC.

     */
    inline void SetVpcId(const char* value) { m_vpcIdHasBeenSet = true; m_vpcId.assign(value); }

    /**
     *
The ID of the VPC.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithVpcId(const Aws::String& value) { SetVpcId(value); return *this;}

    /**
     *
The ID of the VPC.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithVpcId(Aws::String&& value) { SetVpcId(std::move(value)); return *this;}

    /**
     *
The ID of the VPC.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithVpcId(const char* value) { SetVpcId(value); return *this;}

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline const Aws::Vector<TagSpecification>& GetTagSpecifications() const{ return m_tagSpecifications; }

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline bool TagSpecificationsHasBeenSet() const { return m_tagSpecificationsHasBeenSet; }

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline void SetTagSpecifications(const Aws::Vector<TagSpecification>& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = value; }

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline void SetTagSpecifications(Aws::Vector<TagSpecification>&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = std::move(value); }

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithTagSpecifications(const Aws::Vector<TagSpecification>& value) { SetTagSpecifications(value); return *this;}

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithTagSpecifications(Aws::Vector<TagSpecification>&& value) { SetTagSpecifications(std::move(value)); return *this;}

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& AddTagSpecifications(const TagSpecification& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(value); return *this; }

    /**
     *
The tags to assign to the local gateway route table VPC association.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& AddTagSpecifications(TagSpecification&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(std::move(value)); return *this; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool GetDryRun() const{ return m_dryRun; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool DryRunHasBeenSet() const { return m_dryRunHasBeenSet; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline CreateLocalGatewayRouteTableVpcAssociationRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

  private:

    Aws::String m_localGatewayRouteTableId;
    bool m_localGatewayRouteTableIdHasBeenSet;

    Aws::String m_vpcId;
    bool m_vpcIdHasBeenSet;

    Aws::Vector<TagSpecification> m_tagSpecifications;
    bool m_tagSpecificationsHasBeenSet;

    bool m_dryRun;
    bool m_dryRunHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
backofficeApp.factory('cmsService', ['$resource', '$upload', '$q', function ($resource, $upload, $q) {

  var Connection = $resource('/cms/city_connections', null, {
    'update': {method: 'PUT'},
  });

  var Supplies = $resource('/cms/supplies', null, {
    'update': {method: 'PUT'},
  });

  var Stories = $resource('/cms/stories', null, {
    'update': {method: 'PUT'},
  });

  return {
    updateCity: function (city, cityImage, residentImage) {
      city.affiliates_attributes = city.affiliates ? city.affiliates : [];

      var promises = [];
      var uploadInfo = {
        method: 'PUT',
        url: '/cms/city/'+city.id,
        data: {city: city}
      }

      // This is for make two request only when 2 images are uploaded
      if (!_.isEmpty(cityImage)) {
        uploadInfo.file = cityImage;
        uploadInfo.fileFormDataName = "city_image";
        promises.push($upload.upload(uploadInfo));
        if (!_.isEmpty(residentImage)) {
          promises.push($upload.upload({
            method: 'PUT',
            url: '/cms/city/residents/'+city.id,
            file: residentImage,
            data: {city: city},
            fileFormDataName: "resident_image"
          }));
        }
      } else {
        if (!_.isEmpty(residentImage)) {
          uploadInfo.file = residentImage;
          uploadInfo.fileFormDataName = "resident_image";
        }
        promises.push($upload.upload(uploadInfo));
      }

      return $q.all(promises);
    },

    updateConnection: function (connection, callback, errorCallback) {
      connection.twitter_accounts_attributes = connection.twitter_accounts ? connection.twitter_accounts : [];
      connection.city_networks_attributes = connection.city_networks ? connection.city_networks : [];
      connection.city_resources_attributes = connection.city_resources ? connection.city_resources : [];
      connection = _(connection).omit('id', 'twitter_accounts', 'city_networks', 'city_resources');

      var uploadsNetwork = [];
      var uploadsResource = [];

      _(connection.city_networks_attributes).map(function (network, index) {
        network.index = index;

        uploadsNetwork.push(network.logo);
        delete network.logo;
        delete network.new_image;
        delete network.logo_url;
      });

      _(connection.city_resources_attributes).each(function (resource, index) {
        resource.index = index;
        uploadsResource.push(resource.logo);
        delete resource.logo;
        delete resource.new_image;
        delete resource.logo_url;
      });

      return $upload.upload({
        method: 'PUT',
        url: '/cms/city_connections',
        data: {city_connection: connection}
      }).then(function(data) {
        data = data.data;

        var promises = [];

        _(data.city_connection.city_networks).each(function(cnet, i) {
          var logo = uploadsNetwork[i];

          if(logo != null) {
            promises.push($upload.upload({
              method: 'PUT',
              url: '/cms/city_network/' + cnet.id,
              file: logo,
              fileFormDataName: "logo"
            }));
          }
        });

        _(data.city_connection.city_resources).each(function(crec, i) {
          var logo = uploadsResource[i];

          if(logo != null) {
            promises.push($upload.upload({
              method: 'PUT',
              url: '/cms/city_resource/' + crec.id,
              file: logo,
              fileFormDataName: "logo"
            }));
          }
        });

        return $q.all(promises).then(
          function(responses) {
            return $upload.upload({
              method: 'GET',
              url: '/cms/city_connections.json',
            }).then(callback, errorCallback);
          },
          errorCallback
        );
      }, errorCallback);

    },

    updateSupplies: function (essentials, usefuls, personals, kits) {
      var allSupplies = _(essentials).chain().union(usefuls).union(personals).value();
      var promises = [];

      _(allSupplies).map(function (supply, index) {
        supply.index = index;

        var uploadInfo = {
          method: 'PUT',
          url: '/cms/supplies/'+supply.id,
          data: {item: supply}
        };

        if(supply.image) {
          uploadInfo.file = supply.image
          uploadInfo.fileFormDataName = "image";
        }

        promises.push($upload.upload(uploadInfo));
      });

      _(kits).map(function (kit, index) {
        kit.index = index;

        var uploadInfo = {
          method: 'PUT',
          url: '/cms/supplies/kit/'+kit.id,
          data: {kit: kit}
        };

        if(kit.image) {
          uploadInfo.file = kit.image
          uploadInfo.fileFormDataName = "image";
        }

        promises.push($upload.upload(uploadInfo));
      });

      return $q.all(promises);
    },

    updateStories: function (stories, city) {
      var promises = [];
      _(stories).map(function (story, index) {
        story.index = index;

        var uploadInfo = {
          method: 'PUT',
          url: '/cms/stories/'+story.id,
          data: {story: story}
        };

        if(story.image) {
          uploadInfo.file = story.image
          uploadInfo.fileFormDataName = "image";
        }

        promises.push($upload.upload(uploadInfo));
      });

      promises.push($upload.upload({
        method: 'PUT',
        url: '/cms/stories/city/'+city.id,
        data: {city: city}
      }));

      return $q.all(promises);
    }
  }

}]);


text:
package org.eclipse.php.internal.ui.util;

import com.ibm.icu.text.MessageFormat;

/**
 * Helper class to format message strings.
 *
 */
public class Messages {

	public static String format(String message, Object object) {
		return MessageFormat.format(message, new Object[] { object });
	}

	public static String format(String message, Object[] objects) {
		return MessageFormat.format(message, objects);
	}

	private Messages() {
		// Not for instantiation
	}
}


text:
@interface FMReloadData : NSObject

typedef void (^OnReloadBlock)(FMReloadData *data);

@property (copy) NSString *nameToSelectOnList;

@end


text:
{% extends 'requestoid/base.html' %}
{% block content %}

{% for entry in content.available %}

{{ entry.label }}

{% endfor %}

{% endblock %}


text:
using System;

namespace Umbraco.Core.Persistence.Querying
{
    /// <summary>
    /// Represents the Sql Translator for translating a IQuery object to Sql
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal class SqlTranslator<T>
    {
        private readonly Sql _sql;

        public SqlTranslator(Sql sql, IQuery<T> query)
        {
            if (sql == null)
                throw new Exception("Sql cannot be null");

            var query1 = query as Query<T>;
            if (query1 == null)
                throw new Exception("Query cannot be null");

            _sql = sql;
            foreach (var clause in query1.WhereClauses())
            {
                _sql.Where(clause);
            }
        }

        public Sql Translate()
        {
            return _sql;
        }

        public override string ToString()
        {
            return _sql.SQL;
        }
    }
}


text:
package io.quarkus.scheduler.test;

import java.util.concurrent.CountDownLatch;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

import io.quarkus.scheduler.Scheduled;

public class RequestContextJobs {

    static final CountDownLatch LATCH = new CountDownLatch(1);

    @Inject
    RequestFoo foo;

    @Scheduled(every = "1s")
    void checkEverySecond() {
        foo.getName();
        LATCH.countDown();
    }

    @RequestScoped
    static class RequestFoo {

        private String name;

        @PostConstruct
        void init() {
            name = "oof";
        }

        public String getName() {
            return name;
        }

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/main_color"/>
            <stroke android:width="1dp" android:color="@color/main_color"/>
            <corners android:radius="30dp"/>
        </shape>
    </item>
    <!-- 默认 -->
    <item>
        <shape>
            <solid android:color="@color/main_color"/>
            <stroke android:width="1dp" android:color="@color/main_color"/>
            <corners android:radius="30dp"/>
        </shape>
    </item>

</selector>


text:
namespace MI.Code
{
    public class TreeGridModel
    {
        public string id { get; set; }
        public string parentId { get; set; }
        public string text { get; set; }
        public bool isLeaf { get; set; }
        public bool expanded { get; set; }
        public bool loaded { get; set; }
        public string entityJson { get; set; }
    }
}


text:
$( document ).bind( "mobileinit", function() {
	$.mobile.textinput.prototype.options.clearBtn = true;
});


text:
module ApplicationHelper
include KonoUtils::ApplicationHelper
end


text:
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>
#import <QuartzCore/CAEAGLLayer.h>
#import "glu.h"

#import "PLIRenderer.h"
#import "PLObjectBase.h"
#import "PLStructs.h"
#import "PLCamera.h"
#import "PLScene.h"
#import "PLSceneElement.h"

#import "PLVector3.h"
#import "PLIntersection.h"
#import "PLHotspot.h"

@interface PLRenderer : PLObjectBase <PLIRenderer>
{
    #pragma mark -
    #pragma mark member variables
@private
	BOOL isValid;

    EAGLContext *context;
    GLuint program;

	GLint backingWidth, backingHeight;

	GLuint defaultFramebuffer, colorRenderbuffer;

	UIView<PLIView> *view;
	NSObject<PLIScene> *scene;

	float aspect;

	float mvmatrix[16];
	float projmatrix[16];
	int viewport[4];

	PLVector3 *ray[2];
	PLVector3 *hitPoint;
	PLVector3 *points[4];
}

@end


text:
<?php

namespace ApplicationsTest\Form;

use PHPUnit\Framework\TestCase;

use Applications\Form\FactsFieldset;
use Core\Form\Element\DatePicker;
use Zend\Form\Factory;

/**
* @covers \Applications\Form\FactsFieldset
*/
class FactsFieldsetTest extends TestCase
{
    /**
     * @var $target FactsFieldset
     */
    protected $target;

    protected function setUp()
    {
        $this->target = new FactsFieldset();

        // Setup form factory.
        $factory = new Factory();
        $elements = $factory->getFormElementManager();
        $elements->setService('Core/Datepicker', new DatePicker());

        // inject form factory
        $this->target->setFormFactory($factory);
        $this->target->init();
    }

    public function testConstructor()
    {
        $this->assertInstanceOf('Applications\Form\FactsFieldset', $this->target);
    }
    public function testFormName()
    {
        $this->assertEquals($this->target->getName(), 'base');
    }

    public function testSetGetEmptySummaryText()
    {
        $input="Klick here";
        $this->target->setEmptySummaryNotice($input);
        $this->assertSame($this->target->getEmptySummaryNotice(), $input);
    }

    /**
     * @dataProvider providerDisableCapable
     */
    public function testSetGetIsDisableCapable($input, $expected)
    {
        $this->target->setIsDisableCapable($input);
        $this->assertSame($this->target->isDisableCapable(), $expected);
    }

    public function providerDisableCapable()
    {
        return [
            [true,true],
            [false,false],
            [null, true]
        ];
    }

    /**
     * @dataProvider providerDisableElementCapable
     */
    public function testSetGetIsDisableElementCapable($input, $expected)
    {
        $this->target->setIsDisableElementsCapable($input);
        $this->assertSame($this->target->isDisableElementsCapable(), $expected);
    }

    public function providerDisableElementCapable()
    {
        return [
            [true,true],
            [false,false],
            [null, true]
        ];
    }

    public function testIsSummaryEmptyDefaultTrue()
    {
        $this->assertSame($this->target->isSummaryEmpty(), true);
    }

    public function testIsSummaryEmptyDefaultFalse()
    {
        $expectedSalary = $this->target->get('expectedSalary');
        $expectedSalary->setValue(10000);
        $this->assertSame($this->target->isSummaryEmpty(), false);
    }

    public function testDisableElements()
    {
        $expectedSalary = $this->target->get('expectedSalary');
        $expectedSalary->setValue(10000);
        $this->target->disableElements(['expectedSalary', 'willingnessToTravel']);
        $this->assertSame($this->target->isSummaryEmpty(), true);
    }
}


text:
.. pymzml_regex_patterns:

.. default-domain:: py

Regex patterns
==============

This file hosts a centralized point for all regex patterns used in pymzML

.. NOTE::
    We need some comment lines for each regex, i.e. what does it catch ..
    maybe with examples and stuff ...

.. automodule:: pymzml.regex_patterns
    :members:


text:
Introduction
============
This quickstart demonstrates the usage of the Camel Component and it's binding feature, by binding
to a ftp server. When file is created on ftp server service will be invoked.

Running the quickstart
======================

EAP
----------
1. Ensure that connection parameters in src/main/resources/META-INF/switchyard.xml points to your server.
   The default parameters are:
```
    directory: .
    host: localhost
    port: 2222
    user: camel
    password: isMyFriend
```
2. Start EAP in standalone-full mode:

        ${AS}/bin/standalone.sh --server-config=standalone-full.xml

3. Build and deploy the quickstart

        mvn install -Pdeploy -DskipTests=true

    Tests should be skipped after parameter change because embedded server have hardcoded username and password.

4. From src/test/resources, copy ftpclient.jks, id_sftp_rsa, and known_hosts_sftp to ${EAP_HOME}/src/test/resources.

5. Create a file on the ftp server using a standalone FTP client.

6. Check the server console for output from the service.

7. Undeploy the quickstart:

        mvn clean -Pdeploy

Wildfly
----------
1. Ensure that connection parameters in src/main/resources/META-INF/switchyard.xml points to your server.
The default parameters are:
```
    directory: .
    host: localhost
    port: 2222
    user: camel
    password: isMyFriend
```
2. Start Wildfly in standalone-full mode:

${AS}/bin/standalone.sh --server-config=standalone-full.xml

3. Build and deploy the quickstart

mvn install -Pdeploy -Pwildfly -DskipTests=true

Tests should be skipped after parameter change because embedded server have hardcoded username and password.

4. From src/test/resources, copy ftpclient.jks, id_sftp_rsa, and known_hosts_sftp to ${WILDFLY_HOME}/src/test/resources.

5. Create file on ftp server using a standalone FTP client

6. Check the server console for output from the service.

7. Undeploy the quickstart:

mvn clean -Pdeploy -Pwildfly

Karaf
----------
1. Add these properties to the ${KARAF_HOME}/etc/system.properties

org.switchyard.component.camel.ftps.storefile=${karaf.home}/quickstarts/switchyard/camel-ftp-binding/src/test/resources/ftpclient.jks
org.switchyard.component.camel.sftp.knownhosts=${karaf.home}/quickstarts/switchyard/camel-ftp-binding/src/test/resources/known_hosts_sftp
org.switchyard.component.camel.sftp.keyfile=${karaf.home}/quickstarts/switchyard/camel-ftp-binding/src/test/resources/id_sftp_rsa

2. Start the Karaf server :

${KARAF_HOME}/bin/karaf

3. Add the features URL for the respective version of SwitchYard.   Replace {SWITCHYARD-VERSION}
with the version of SwitchYard that you are using (ex. 2.0.0):

karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features

4. From src/test/resources, copy ftpclient.jks, id_sftp_rsa, and known_hosts_sftp to ${KARAF_HOME}/etc.

5. Install the feature for the camel-ftp-binding quickstart :

karaf@root> features:install switchyard-quickstart-camel-ftp-binding

6. Create a file on the ftp server using a standalone FTP client.

7. Check the server console for output from the service.

8. Undeploy the quickstart:

karaf@root> features:uninstall switchyard-quickstart-camel-ftp-binding

9. Remove the added properties of the step 1 from the ${KARAF_HOME}/etc/system.properties file

## Further Reading

1. [FTP FTPS SFTP Binding Documentation](https://docs.jboss.org/author/display/SWITCHYARD/FTP+FTPS+SFTP)


text:
package agent

import (
	"io"
	"net"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"time"

	"go.etcd.io/etcd/pkg/fileutil"
)

// TODO: support separate WAL directory
func archive(baseDir, etcdLogPath, dataDir string) error {
	dir := filepath.Join(baseDir, "etcd-failure-archive", time.Now().Format(time.RFC3339))
	if existDir(dir) {
		dir = filepath.Join(baseDir, "etcd-failure-archive", time.Now().Add(time.Second).Format(time.RFC3339))
	}
	if err := fileutil.TouchDirAll(dir); err != nil {
		return err
	}

	dst := filepath.Join(dir, "etcd.log")
	if err := copyFile(etcdLogPath, dst); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	}
	if err := os.Rename(dataDir, filepath.Join(dir, filepath.Base(dataDir))); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	}

	return nil
}

func existDir(fpath string) bool {
	st, err := os.Stat(fpath)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	} else {
		return st.IsDir()
	}
	return false
}

func getURLAndPort(addr string) (urlAddr *url.URL, port int, err error) {
	urlAddr, err = url.Parse(addr)
	if err != nil {
		return nil, -1, err
	}
	var s string
	_, s, err = net.SplitHostPort(urlAddr.Host)
	if err != nil {
		return nil, -1, err
	}
	port, err = strconv.Atoi(s)
	if err != nil {
		return nil, -1, err
	}
	return urlAddr, port, err
}

func copyFile(src, dst string) error {
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()

	w, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer w.Close()

	if _, err = io.Copy(w, f); err != nil {
		return err
	}
	return w.Sync()
}

func cleanPageCache() error {
	// https://www.kernel.org/doc/Documentation/sysctl/vm.txt
	// https://github.com/torvalds/linux/blob/master/fs/drop_caches.c
	cmd := exec.Command("/bin/sh", "-c", `echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh`)
	return cmd.Run()
}


text:
package org.orekit.models.earth;

import org.apache.commons.math3.analysis.BivariateFunction;
import org.apache.commons.math3.analysis.interpolation.PiecewiseBicubicSplineInterpolator;
import org.orekit.data.DataProvidersManager;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.utils.Constants;
import org.orekit.utils.InterpolationTableLoader;

/** A static tropospheric model that interpolates the actual tropospheric delay
 * based on values read from a configuration file (tropospheric-delay.txt) via
 * the {@link DataProvidersManager}.
 * @author Thomas Neidhart
 */
public class FixedTroposphericDelay implements TroposphericDelayModel {

    /** Serializable UID. */
    private static final long serialVersionUID = -92320711761929077L;

    /** Singleton object for the default model. */
    private static FixedTroposphericDelay defaultModel;

    /** Abscissa grid for the bi-variate interpolation function read from the file. */
    private final double[] xArr;

    /** Ordinate grid for the bi-variate interpolation function read from the file. */
    private final double[] yArr;

    /** Values samples for the bi-variate interpolation function read from the file. */
    private final double[][] fArr;

    /** Interpolation function for the tropospheric delays. */
    private transient BivariateFunction delayFunction;

    /** Creates a new {@link FixedTroposphericDelay} instance.
     * @param xArr abscissa grid for the interpolation function
     * @param yArr ordinate grid for the interpolation function
     * @param fArr values samples for the interpolation function
     */
    public FixedTroposphericDelay(final double[] xArr, final double[] yArr, final double[][] fArr) {
        this.xArr = xArr.clone();
        this.yArr = yArr.clone();
        this.fArr = fArr.clone();
        delayFunction = new PiecewiseBicubicSplineInterpolator().interpolate(xArr, yArr, fArr);
    }

    /** Creates a new {@link FixedTroposphericDelay} instance, and loads the
     * delay values from the given resource via the {@link DataProvidersManager}.
     * @param supportedName a regular expression for supported resource names
     * @throws OrekitException if the resource could not be loaded
     */
    public FixedTroposphericDelay(final String supportedName) throws OrekitException {

        final InterpolationTableLoader loader = new InterpolationTableLoader();
        DataProvidersManager.getInstance().feed(supportedName, loader);

        if (!loader.stillAcceptsData()) {
            xArr = loader.getAbscissaGrid();
            yArr = loader.getOrdinateGrid();
            fArr = loader.getValuesSamples();
            delayFunction = new PiecewiseBicubicSplineInterpolator().interpolate(xArr, yArr, fArr);
        } else {
            throw new OrekitException(OrekitMessages.UNABLE_TO_FIND_RESOURCE, supportedName);
        }
    }

    /** Returns the default model, loading delay values from the file
     * "tropospheric-delay.txt".
     * @return the default model
     * @throws OrekitException if the file could not be loaded
     */
    public static FixedTroposphericDelay getDefaultModel() throws OrekitException {
        synchronized (FixedTroposphericDelay.class) {
            if (defaultModel == null) {
                defaultModel = new FixedTroposphericDelay("^tropospheric-delay\\.txt$");
            }
        }
        return defaultModel;
    }

    /** {@inheritDoc} */
    public double calculatePathDelay(final double elevation, final double height) {
        // limit the height to 5000 m
        final double h = Math.min(Math.max(0, height), 5000);
        // limit the elevation to 0 - 180 degree
        final double ele = Math.min(180d, Math.max(0d, elevation));
        // mirror elevation at the right angle of 90 degree
        final double e = ele > 90d ? 180d - ele : ele;

        return delayFunction.value(h, e);
    }

    /** {@inheritDoc} */
    public double calculateSignalDelay(final double elevation, final double height) {
        return calculatePathDelay(elevation, height) / Constants.SPEED_OF_LIGHT;
    }

    /** Make sure the unserializable bivariate interpolation function is properly rebuilt.
     * @return replacement object, with bivariate function properly set up
     */
    private Object readResolve() {
        return new FixedTroposphericDelay(xArr, yArr, fArr);
    }

}


text:
#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from azure.common import (
    AzureHttpError,
    AzureConflictHttpError,
    AzureMissingResourceHttpError,
)

_ERROR_CONFLICT = 'Conflict ({0})'
_ERROR_NOT_FOUND = 'Not found ({0})'
_ERROR_UNKNOWN = 'Unknown error ({0})'
_ERROR_VALUE_NONE = '{0} should not be None.'
_ERROR_MESSAGE_NOT_PEEK_LOCKED_ON_DELETE = \
    'Message is not peek locked and cannot be deleted.'
_ERROR_MESSAGE_NOT_PEEK_LOCKED_ON_UNLOCK = \
    'Message is not peek locked and cannot be unlocked.'
_ERROR_MESSAGE_NOT_PEEK_LOCKED_ON_RENEW_LOCK = \
    'Message is not peek locked and lock cannot be renewed.'
_ERROR_EVENT_HUB_NOT_FOUND = 'Event hub was not found'
_ERROR_QUEUE_NOT_FOUND = 'Queue was not found'
_ERROR_TOPIC_NOT_FOUND = 'Topic was not found'
_ERROR_SERVICEBUS_MISSING_INFO = \
    'You need to provide servicebus namespace, access key and Issuer'
_WARNING_VALUE_SHOULD_BE_BYTES = \
    'Warning: {0} must be bytes data type. It will be converted ' + \
    'automatically, with utf-8 text encoding.'
_ERROR_VALUE_SHOULD_BE_BYTES = '{0} should be of type bytes.'
_ERROR_VALUE_NEGATIVE = '{0} should not be negative.'

def _general_error_handler(http_error):
    ''' Simple error handler for azure.'''
    message = str(http_error)
    if http_error.respbody is not None:
        message += '\n' + http_error.respbody.decode('utf-8-sig')
    raise AzureHttpError(message, http_error.status)

def _dont_fail_on_exist(error):
    ''' don't throw exception if the resource exists.
    This is called by create_* APIs with fail_on_exist=False'''
    if isinstance(error, AzureConflictHttpError):
        return False
    else:
        raise error

def _dont_fail_not_exist(error):
    ''' don't throw exception if the resource doesn't exist.
    This is called by create_* APIs with fail_on_exist=False'''
    if isinstance(error, AzureMissingResourceHttpError):
        return False
    else:
        raise error

def _validate_type_bytes(param_name, param):
    if not isinstance(param, bytes):
        raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES.format(param_name))

def _validate_not_none(param_name, param):
    if param is None:
        raise ValueError(_ERROR_VALUE_NONE.format(param_name))


text:
<?php
require_once('connection.php');
require_once('functions.php');

validate_user();

if ($request[operation]=="delete") {
	$r=mysqli_query($link, "DELETE FROM countries WHERE country_id={$request[delete_country_id]}");
} elseif ($request[operation]=="add") {
	$r=mysqli_query($link, "INSERT INTO countries (country) VALUES ('{$request[new_country]}')");
} elseif ($request[operation]=="save") {
	foreach ($request as $key => $value) {
		if (substr($key,0,7)=="country") {
			$country_id=substr($key,8);
			mysqli_query($link, "UPDATE countries set country='$value' WHERE country_id=$country_id");
		}
	}
}
?>
<LINK href="css/netherhall.css" rel="stylesheet" type="text/css">

	<?php
	if ($request[op]=="e") {
		?>

List Countries

Save

		<?php
	} else {
		?>
Edit Countries
	<?php
	}
	?>

<form name="myform" method="post" action="admin.php">
<input type="hidden" name="pagetoload" value="countries_list.php">
<input type="hidden" name="operation">
<input type="hidden" name="delete_country_id">
<input type="hidden" name="op" value="e">

    Country
<?php
if ($request[op]=="e") {
	?>

	<?php
}
?>

<?php
$r=mysqli_query($link, "SELECT * FROM countries ORDER BY country");
while ($data=mysqli_fetch_assoc($r)) {
	?>

		<?php
		if ($request[op]=="e") {
			?><input type="text" name="country_<?=$data[country_id]?>" value="<?=$data[country]?>" size="20"><?php
		} else {
			echo $data[country];
		}
		?>

	<?php
	if ($request[op]=="e") {
		?>
		<div class="button_off" onMouseOver="this.className='button_on'" onMouseOut="this.className='button_off'" onClick="delete_country('<?=$data[country_id]?>','<?=$data[country]?>')">Delete

		<?php
	}
	?>

	<?php
}
?>

<?php
if ($request[op]=="e") {
	?>

	<input type="text" name="new_country" size="20">

Add

	<?php
}
?>
</form>


text: See https://github.com/joeferner/stm32-cc3000 for a working CC3000 driver.


text:
require 'nokogiri'
require 'open-uri'
require 'colorize'

require 'io/console'

require_relative 'what_a_world/version.rb'
require_relative 'what_a_world/print_fit.rb'
require_relative 'what_a_world/scraper.rb'
require_relative 'what_a_world/issues.rb'
require_relative 'what_a_world/country.rb'
require_relative 'what_a_world/cli.rb'


text:
title: "LightGBM Tracking"
meta_title: "LightGBM Tracking"
meta_description: "Polyaxon allows to schedule LightGBM experiments, and supports tracking metrics, outputs, and models natively."
custom_excerpt: "LightGBM, short for Light Gradient Boosting Machine, is a free and open source distributed gradient boosting framework for machine learning originally developed by Microsoft. It is based on decision tree algorithms and used for ranking, classification and other machine learning tasks."
image: "../../content/images/integrations/lightgbm.png"
author:
  name: "Polyaxon"
  slug: "Polyaxon"
  website: "https://polyaxon.com"
  twitter: "polyaxonAI"
  github: "polyaxon"
tags:
  - tracking
featured: false
popularity: 2
visibility: public
status: published
---

Polyaxon allows to schedule LightGBM experiments and supports tracking metrics, outputs, and models.

With Polyaxon you can:

 * log hyperparameters for every run
 * see learning curves for losses and metrics during training
 * see hardware consumption and stdout/stderr output during training
 * log images, charts, and other assets
 * log git commit information
 * log env information
 * log model
 * ...

## Tracking API

Polyaxon provides a [tracking API](/docs/experimentation/tracking/) to track experiment and report metrics, artifacts, logs, and results to the Polyaxon dashboard.

You can use the tracking API to create a custom tracking experience with LightGBM.

## Setup

In order to use Polyaxon tracking with LightGBM, you need to install Polyaxon library

```bash
pip install polyaxon
```

## Initialize your script with Polyaxon

This is an optional step if you need to perform some manual tracking or to track some information before passing the callback.

```python
from polyaxon import tracking

tracking.init(...)
```

## Polyaxon callback

Pass Polyaxon's callback to the `train` function

```python
from polyaxon.tracking.contrib.lightgbm import polyaxon_callback

gbm = lgb.train(
    params,
    lgb_train,
    num_boost_round=500,
    valid_sets=[lgb_train, lgb_eval],
    valid_names=['train','valid'],
    callbacks=[polyaxon_callback()],
)
```

## Customizing the callback

Creating the callback will use the current initialized run, but you can use a different run if you need to have more control:

```python
from polyaxon.tracking import Run
from polyaxon.tracking.contrib.lightgbm import polyaxon_callback

run = Run(...)

gbm = lgb.train(
    ...,
    callbacks = [polyaxon_callback(run)],
)
```

## Manual logging

If you want to have more control and use Polyaxon to log metrics in your scripts, you just need to add `tracking.log_...` anywhere needed:

 * log metrics

```python
tracking.log_mtrics(loss=loss)
```

 * log artifacts

```python
tracking.log_artifact_ref(asset_path)
```

## Example

In this example we will go through the process of logging a LightGBM model using Polyaxon's callback.

This example can be used with the offline mode `POLYAXON_OFFLINE=true` and it does not require a Polyaxon API to run locally.

To see how this can be turned to a declarative approach to be submitted to a Polyaxon cluster, please check this [example](https://github.com/polyaxon/polyaxon-examples/tree/master/in_cluster/lightgbm/wine)

```python
import argparse
import logging

import lightgbm as lgb

# Polyaxon
from polyaxon import tracking
from polyaxon.tracking.contrib.lightgbm import polyaxon_callback

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split

logger = logging.getLogger()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--boosting_type',
        type=str,
        default='gbdt'
    )
    parser.add_argument(
        '--objective',
        type=str,
        default='multiclass'
    )
    parser.add_argument(
        '--num_class',
        type=int,
        default=3
    )
    parser.add_argument(
        '--num_leaves',
        type=int,
        default=31
    )
    parser.add_argument(
        '--learning_rate',
        type=float,
        default=0.05,
    )
    parser.add_argument(
        '--feature_fraction',
        type=float,
        default=0.9
    )

    args = parser.parse_args()

    params = {
        'boosting_type': args.boosting_type,
        'objective': args.objective,
        'num_class': args.num_class,
        'num_leaves': args.num_leaves,
        'learning_rate': args.learning_rate,
        'feature_fraction': args.feature_fraction,
    }

    # Polyaxon
    tracking.init(is_offline=True)

    data = load_wine()
    X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.1)

    # Polyaxon
    tracking.log_data_ref(content=X_train, name='x_train', is_input=True)
    tracking.log_data_ref(content=y_train, name='y_train', is_input=True)
    tracking.log_data_ref(content=X_test, name='X_test', is_input=True)
    tracking.log_data_ref(content=y_test, name='y_train', is_input=True)

    lgb_train = lgb.Dataset(X_train, y_train)
    lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)

    gbm = lgb.train(
        params,
        lgb_train,
        num_boost_round=500,
        valid_sets=[lgb_train, lgb_eval],
        valid_names=['train', 'valid'],
        callbacks=[polyaxon_callback()],  # Polyaxon
    )

    y_test_pred = gbm.predict(X_test)

    # Polyaxon
    tracking.log_sklearn_roc_auc_curve("roc_c", y_test_pred, y_test, is_multi_class=True)

    model_path = tracking.get_outputs_path("model/lightgbm.pkl")
    gbm.save_model(model_path)

    # Polyaxon
    tracking.log_model_ref(model_path, framework="lightgbm")
```


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "customer".
 *
 * @property integer $id
 * @property string $last_name
 * @property string $first_name
 * @property string $patronymic
 * @property string $telephone
 * @property string $note
 *
 * @property Order[] $orders
 */
class Customer extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'customer';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['last_name', 'first_name', 'patronymic', 'telephone', ], 'required', 'message' => 'Поле обязательно для заполнения'],
            [['telephone'], 'string','max' => 200, 'message' => 'Указано слишком длинное значение'],
            [['last_name', 'first_name', 'patronymic', 'note'], 'string', 'max' => 200],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '№',
            'last_name' => 'Фамилия',
            'first_name' => 'Имя',
            'patronymic' => 'Отчество',
            'telephone' => 'Телефон',
            'note' => 'Заметка',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['id_customer' => 'id']);
    }
}


text:
// -*- c-basic-offset: 4; related-file-name: "../../lib/element.cc" -*-
#ifndef CLICK_ELEMENT_HH
#define CLICK_ELEMENT_HH
#include <click/glue.hh>
#include <click/vector.hh>
#include <click/string.hh>
#include <click/packet.hh>
#include <click/handler.hh>
CLICK_DECLS
class Router;
class Master;
class RouterThread;
class Task;
class Timer;
class NotifierSignal;
class Element;
class ErrorHandler;
class Bitvector;
class EtherAddress;

/** @file <click/element.hh>
 * @brief Click's Element class.
 */

#ifndef CLICK_ELEMENT_DEPRECATED
# define CLICK_ELEMENT_DEPRECATED CLICK_DEPRECATED
#endif

class Element { public:

    Element();
    virtual ~Element();
    static int nelements_allocated;

    // RUNTIME
    virtual void push(int port, Packet *p);
    virtual Packet *pull(int port) CLICK_WARN_UNUSED_RESULT;
    virtual Packet *simple_action(Packet *p);

    virtual bool run_task(Task *task);	// return true iff did useful work
    virtual void run_timer(Timer *timer);
#if CLICK_USERLEVEL
    enum { SELECT_READ = 1, SELECT_WRITE = 2 };
    virtual void selected(int fd, int mask);
    virtual void selected(int fd);
#endif

    inline void checked_output_push(int port, Packet *p) const;
    inline Packet* checked_input_pull(int port) const;

    // ELEMENT CHARACTERISTICS
    virtual const char *class_name() const = 0;

    virtual const char *port_count() const;
    static const char PORTS_0_0[];
    static const char PORTS_0_1[];
    static const char PORTS_1_0[];
    static const char PORTS_1_1[];
    static const char PORTS_1_1X2[];

    virtual const char *processing() const;
    static const char AGNOSTIC[];
    static const char PUSH[];
    static const char PULL[];
    static const char PUSH_TO_PULL[];
    static const char PULL_TO_PUSH[];
    static const char PROCESSING_A_AH[];

    virtual const char *flow_code() const;
    static const char COMPLETE_FLOW[];

    virtual const char *flags() const;
    int flag_value(int flag) const;

    virtual void *cast(const char *name);
    virtual void *port_cast(bool isoutput, int port, const char *name);

    // CONFIGURATION, INITIALIZATION, AND CLEANUP
    enum ConfigurePhase {
	CONFIGURE_PHASE_FIRST = 0,
	CONFIGURE_PHASE_INFO = 20,
	CONFIGURE_PHASE_PRIVILEGED = 90,
	CONFIGURE_PHASE_DEFAULT = 100,
	CONFIGURE_PHASE_LAST = 2000
    };
    virtual int configure_phase() const;

    virtual int configure(Vector<String> &conf, ErrorHandler *errh);

    virtual void add_handlers();

    virtual int initialize(ErrorHandler *errh);

    virtual void take_state(Element *old_element, ErrorHandler *errh);
    virtual Element *hotswap_element() const;

    enum CleanupStage {
	CLEANUP_NO_ROUTER,
	CLEANUP_BEFORE_CONFIGURE = CLEANUP_NO_ROUTER,
	CLEANUP_CONFIGURE_FAILED,
	CLEANUP_CONFIGURED,
	CLEANUP_INITIALIZE_FAILED,
	CLEANUP_INITIALIZED,
	CLEANUP_ROUTER_INITIALIZED,
	CLEANUP_MANUAL
    };
    virtual void cleanup(CleanupStage stage);

    static inline void static_initialize();
    static inline void static_cleanup();

    // ELEMENT ROUTER CONNECTIONS
    String name() const;
    virtual String declaration() const;

    inline Router *router() const;
    inline int eindex() const;
    inline int eindex(Router *r) const;

    /** @brief Return the element's master. */
    inline Master *master() const;

    inline void attach_router(Router *r, int eindex) {
	assert(!_router);
	_router = r;
	_eindex = eindex;
    }

    // INPUTS AND OUTPUTS
    inline int nports(bool isoutput) const;
    inline int ninputs() const;
    inline int noutputs() const;

    class Port;
    inline const Port &port(bool isoutput, int port) const;
    inline const Port &input(int port) const;
    inline const Port &output(int port) const;

    inline bool port_active(bool isoutput, int port) const;
    inline bool input_is_push(int port) const;
    inline bool input_is_pull(int port) const;
    inline bool output_is_push(int port) const;
    inline bool output_is_pull(int port) const;
    void port_flow(bool isoutput, int port, Bitvector*) const;

    // LIVE RECONFIGURATION
    String configuration() const;

    virtual bool can_live_reconfigure() const;
    virtual int live_reconfigure(Vector<String>&, ErrorHandler*);

    RouterThread *home_thread() const;

#if CLICK_USERLEVEL
    // SELECT
    int add_select(int fd, int mask);
    int remove_select(int fd, int mask);
#endif

    // HANDLERS
    void add_read_handler(const String &name, ReadHandlerCallback read_callback, const void *user_data = 0, uint32_t flags = 0);
    void add_read_handler(const String &name, ReadHandlerCallback read_callback, int user_data, uint32_t flags = 0);
    void add_read_handler(const char *name, ReadHandlerCallback read_callback, int user_data = 0, uint32_t flags = 0);
    void add_write_handler(const String &name, WriteHandlerCallback write_callback, const void *user_data = 0, uint32_t flags = 0);
    void add_write_handler(const String &name, WriteHandlerCallback write_callback, int user_data, uint32_t flags = 0);
    void add_write_handler(const char *name, WriteHandlerCallback write_callback, int user_data = 0, uint32_t flags = 0);
    void set_handler(const String &name, int flags, HandlerCallback callback, const void *read_user_data = 0, const void *write_user_data = 0);
    void set_handler(const String &name, int flags, HandlerCallback callback, int read_user_data, int write_user_data = 0);
    void set_handler(const char *name, int flags, HandlerCallback callback, int read_user_data = 0, int write_user_data = 0);
    int set_handler_flags(const String &name, int set_flags, int clear_flags = 0);
    enum { TASKHANDLER_WRITE_SCHEDULED = 1,
	   TASKHANDLER_WRITE_TICKETS = 2,
	   TASKHANDLER_WRITE_HOME_THREAD = 4,
	   TASKHANDLER_WRITE_ALL = 7,
	   TASKHANDLER_DEFAULT = 6 };
    void add_task_handlers(Task *task, NotifierSignal *signal, int flags, const String &prefix = String());
    inline void add_task_handlers(Task *task, NotifierSignal *signal, const String &prefix = String()) {
	add_task_handlers(task, signal, TASKHANDLER_DEFAULT, prefix);
    }
    inline void add_task_handlers(Task *task, const String &prefix = String()) {
	add_task_handlers(task, 0, TASKHANDLER_DEFAULT, prefix);
    }

    void add_data_handlers(const char *name, int flags, uint8_t *data);
    void add_data_handlers(const char *name, int flags, bool *data);
    void add_data_handlers(const char *name, int flags, uint16_t *data);
    void add_data_handlers(const char *name, int flags, int *data);
    void add_data_handlers(const char *name, int flags, unsigned *data);
    void add_data_handlers(const char *name, int flags, atomic_uint32_t *data);
    void add_data_handlers(const char *name, int flags, long *data);
    void add_data_handlers(const char *name, int flags, unsigned long *data);
#if HAVE_LONG_LONG
    void add_data_handlers(const char *name, int flags, long long *data);
    void add_data_handlers(const char *name, int flags, unsigned long long *data);
#endif
    void add_net_order_data_handlers(const char *name, int flags, uint16_t *data);
    void add_net_order_data_handlers(const char *name, int flags, uint32_t *data);
#if HAVE_FLOAT_TYPES
    void add_data_handlers(const char *name, int flags, double *data);
#endif
    void add_data_handlers(const char *name, int flags, String *data);
    void add_data_handlers(const char *name, int flags, IPAddress *data);
    void add_data_handlers(const char *name, int flags, EtherAddress *data);
    void add_data_handlers(const char *name, int flags, Timestamp *data, bool is_interval = false);

    static String read_positional_handler(Element*, void*);
    static String read_keyword_handler(Element*, void*);
    static int reconfigure_positional_handler(const String&, Element*, void*, ErrorHandler*);
    static int reconfigure_keyword_handler(const String&, Element*, void*, ErrorHandler*);

    virtual int llrpc(unsigned command, void* arg);
    int local_llrpc(unsigned command, void* arg);

    class Port { public:

	inline bool active() const;
	inline Element* element() const;
	inline int port() const;

	inline void push(Packet* p) const;
	inline Packet* pull() const;

#if CLICK_STATS >= 1
	unsigned npackets() const	{ return _packets; }
#endif

	inline void assign(bool isoutput, Element *e, int port);

      private:

	Element* _e;
	int _port;
#if HAVE_BOUND_PORT_TRANSFER
	union {
	    void (*push)(Element *e, int port, Packet *p);
	    Packet *(*pull)(Element *e, int port);
	} _bound;
#endif

#if CLICK_STATS >= 1
	mutable unsigned _packets;	// How many packets have we moved?
#endif
#if CLICK_STATS >= 2
	Element* _owner;		// Whose input or output are we?
#endif

	inline Port();
	inline void assign(bool isoutput, Element *owner, Element *e, int port);

	friend class Element;

    };

    // DEPRECATED
    /** @cond never */
    String id() const CLICK_DEPRECATED;
    String landmark() const CLICK_DEPRECATED;
    /** @endcond never */

  private:

    enum { INLINE_PORTS = 4 };

    Port* _ports[2];
    Port _inline_ports[INLINE_PORTS];

    int _nports[2];

    Router* _router;
    int _eindex;

#if CLICK_STATS >= 2
    // STATISTICS
    unsigned _xfer_calls;	// Push and pull calls into this element.
    click_cycles_t _xfer_own_cycles;	// Cycles spent in self from push and pull.
    click_cycles_t _child_cycles;	// Cycles spent in children.

    unsigned _task_calls;	// Calls to tasks owned by this element.
    click_cycles_t _task_own_cycles;	// Cycles spent in self from tasks.

    unsigned _timer_calls;	// Calls to timers owned by this element.
    click_cycles_t _timer_own_cycles;	// Cycles spent in self from timers.

    inline void reset_cycles() {
	_xfer_calls = _task_calls = _timer_calls = 0;
	_xfer_own_cycles = _task_own_cycles = _timer_own_cycles = _child_cycles = 0;
    }
    static String read_cycles_handler(Element *, void *);
    static int write_cycles_handler(const String &, Element *, void *, ErrorHandler *);
#endif

    Element(const Element &);
    Element &operator=(const Element &);

    // METHODS USED BY ROUTER
    int set_nports(int, int);
    int notify_nports(int, int, ErrorHandler *);
    enum Processing { VAGNOSTIC, VPUSH, VPULL };
    static int next_processing_code(const char*& p, ErrorHandler* errh);
    void processing_vector(int* input_codes, int* output_codes, ErrorHandler*) const;

    void initialize_ports(const int* input_codes, const int* output_codes);
    int connect_port(bool isoutput, int port, Element*, int);

    static String read_handlers_handler(Element *e, void *user_data);
    void add_default_handlers(bool writable_config);
    inline void add_data_handlers(const char *name, int flags, HandlerCallback callback, void *data);

    friend class Router;
#if CLICK_STATS >= 2
    friend class Task;
    friend class Master;
    friend class TimerSet;
# if CLICK_USERLEVEL
    friend class SelectSet;
# endif
#endif

};

/** @brief Initialize static data for this element class.
 *
 * Place initialization code for an element class's shared global state in the
 * static_initialize() static member function.  (For example, the IPFilter
 * element class uses static_initialize() to set up various parsing tables.)
 * Click drivers will call this function when the element code is loaded,
 * before any elements of the class are created.
 *
 * static_initialize functions are called in an arbitrary and unpredictable
 * order (not, for example, the configure_phase() order).  Element authors are
 * responsible for handling static initialization dependencies.
 *
 * For Click to find a static_initialize declaration, it must appear inside
 * the element class's class declaration on its own line and have the
 * following prototype:
 *
 * @code
 * static void static_initialize();
 * @endcode
 *
 * It must also have public accessibility.
 *
 * @note In most cases you should also define a static_cleanup() function to
 * clean up state initialized by static_initialize().
 *
 * @sa Element::static_cleanup
 */
inline void
Element::static_initialize()
{
}

/** @brief Clean up static data for this element class.
 *
 * Place cleanup code for an element class's shared global state in the
 * static_cleanup() static member function.  Click drivers will call this
 * function before unloading the element code.
 *
 * static_cleanup functions are called in an arbitrary and unpredictable order
 * (not, for example, the configure_phase() order, and not the reverse of the
 * static_initialize order).  Element authors are responsible for handling
 * static cleanup dependencies.
 *
 * For Click to find a static_cleanup declaration, it must appear inside the
 * element class's class declaration on its own line and have the following
 * prototype:
 *
 * @code
 * static void static_cleanup();
 * @endcode
 *
 * It must also have public accessibility.
 *
 * @sa Element::static_initialize
 */
inline void
Element::static_cleanup()
{
}

/** @brief Return the element's router. */
inline Router*
Element::router() const
{
    return _router;
}

/** @brief Return the element's index within its router.
 * @invariant this == router()->element(eindex())
 */
inline int
Element::eindex() const
{
    return _eindex;
}

/** @brief Return the element's index within router @a r.
 *
 * Returns -1 if @a r != router(). */
inline int
Element::eindex(Router* r) const
{
    return (router() == r ? _eindex : -1);
}

/** @brief Return the number of input or output ports.
 * @param isoutput false for input ports, true for output ports */
inline int
Element::nports(bool isoutput) const
{
    return _nports[isoutput];
}

/** @brief Return the number of input ports. */
inline int
Element::ninputs() const
{
    return _nports[0];
}

/** @brief Return the number of output ports. */
inline int
Element::noutputs() const
{
    return _nports[1];
}

/** @brief Return one of the element's ports.
 * @param isoutput false for input ports, true for output ports
 * @param port port number
 *
 * An assertion fails if @a p is out of range. */
inline const Element::Port&
Element::port(bool isoutput, int port) const
{
    assert((unsigned) port < (unsigned) _nports[isoutput]);
    return _ports[isoutput][port];
}

/** @brief Return one of the element's input ports.
 * @param port port number
 *
 * An assertion fails if @a port is out of range.
 *
 * @sa Port, port */
inline const Element::Port&
Element::input(int port) const
{
    return Element::port(false, port);
}

/** @brief Return one of the element's output ports.
 * @param port port number
 *
 * An assertion fails if @a port is out of range.
 *
 * @sa Port, port */
inline const Element::Port&
Element::output(int port) const
{
    return Element::port(true, port);
}

/** @brief Check whether a port is active.
 * @param isoutput false for input ports, true for output ports
 * @param port port number
 *
 * Returns true iff @a port is in range and @a port is active.  Push outputs
 * and pull inputs are active; pull outputs and push inputs are not.
 *
 * @sa Element::Port::active */
inline bool
Element::port_active(bool isoutput, int port) const
{
    return (unsigned) port < (unsigned) nports(isoutput)
	&& _ports[isoutput][port].active();
}

/** @brief Check whether output @a port is push.
 *
 * Returns true iff output @a port exists and is push.  @sa port_active */
inline bool
Element::output_is_push(int port) const
{
    return port_active(true, port);
}

/** @brief Check whether output @a port is pull.
 *
 * Returns true iff output @a port exists and is pull. */
inline bool
Element::output_is_pull(int port) const
{
    return (unsigned) port < (unsigned) nports(true)
	&& !_ports[1][port].active();
}

/** @brief Check whether input @a port is pull.
 *
 * Returns true iff input @a port exists and is pull.  @sa port_active */
inline bool
Element::input_is_pull(int port) const
{
    return port_active(false, port);
}

/** @brief Check whether input @a port is push.
 *
 * Returns true iff input @a port exists and is push. */
inline bool
Element::input_is_push(int port) const
{
    return (unsigned) port < (unsigned) nports(false)
	&& !_ports[0][port].active();
}

#if CLICK_STATS >= 2
# define PORT_ASSIGN(o) _packets = 0; _owner = (o)
#elif CLICK_STATS >= 1
# define PORT_ASSIGN(o) _packets = 0; (void) (o)
#else
# define PORT_ASSIGN(o) (void) (o)
#endif

inline
Element::Port::Port()
    : _e(0), _port(-2)
{
    PORT_ASSIGN(0);
}

inline void
Element::Port::assign(bool isoutput, Element *e, int port)
{
    _e = e;
    _port = port;
    (void) isoutput;
#if HAVE_BOUND_PORT_TRANSFER
    if (e) {
	if (isoutput) {
	    void (Element::*pusher)(int, Packet *) = &Element::push;
	    _bound.push = (void (*)(Element *, int, Packet *)) (e->*pusher);
	} else {
	    Packet *(Element::*puller)(int) = &Element::pull;
	    _bound.pull = (Packet *(*)(Element *, int)) (e->*puller);
	}
    }
#endif
}

inline void
Element::Port::assign(bool isoutput, Element *owner, Element *e, int port)
{
    PORT_ASSIGN(owner);
    assign(isoutput, e, port);
}

/** @brief Returns whether this port is active (a push output or a pull input).
 *
 * @sa Element::port_active
 */
inline bool
Element::Port::active() const
{
    return _port >= 0;
}

/** @brief Returns the element connected to this active port.
 *
 * Returns 0 if this port is not active(). */
inline Element*
Element::Port::element() const
{
    return _e;
}

/** @brief Returns the port number of the port connected to this active port.
 *
 * Returns < 0 if this port is not active(). */
inline int
Element::Port::port() const
{
    return _port;
}

/** @brief Push packet @a p over this port.
 *
 * Pushes packet @a p downstream through the router configuration by passing
 * it to the next element's @link Element::push() push() @endlink function.
 * Returns when the rest of the router finishes processing @a p.
 *
 * This port must be an active() push output port.  Usually called from
 * element code like @link Element::output output(i) @endlink .push(p).
 *
 * When element code calls Element::Port::push(@a p), it relinquishes control
 * of packet @a p.  When push() returns, @a p may have been altered or even
 * freed by downstream elements.  Thus, you must not use @a p after pushing it
 * downstream.  To push a copy and keep a copy, see Packet::clone().
 *
 * output(i).push(p) basically behaves like the following code, although it
 * maintains additional statistics depending on how CLICK_STATS is defined:
 *
 * @code
 * output(i).element()->push(output(i).port(), p);
 * @endcode
 */
inline void
Element::Port::push(Packet* p) const
{
    assert(_e && p);
#if CLICK_STATS >= 1
    ++_packets;
#endif
#if CLICK_STATS >= 2
    ++_e->input(_port)._packets;
    click_cycles_t start_cycles = click_get_cycles(),
	start_child_cycles = _e->_child_cycles;
# if HAVE_BOUND_PORT_TRANSFER
    _bound.push(_e, _port, p);
# else
    _e->push(_port, p);
# endif
    click_cycles_t all_delta = click_get_cycles() - start_cycles,
	own_delta = all_delta - (_e->_child_cycles - start_child_cycles);
    _e->_xfer_calls += 1;
    _e->_xfer_own_cycles += own_delta;
    _owner->_child_cycles += all_delta;
#else
# if HAVE_BOUND_PORT_TRANSFER
    _bound.push(_e, _port, p);
# else
    _e->push(_port, p);
# endif
#endif
}

/** @brief Pull a packet over this port and return it.
 *
 * Pulls a packet from upstream in the router configuration by calling the
 * previous element's @link Element::pull() pull() @endlink function.  When
 * the router finishes processing, returns the result.
 *
 * This port must be an active() pull input port.  Usually called from element
 * code like @link Element::input input(i) @endlink .pull().
 *
 * input(i).pull() basically behaves like the following code, although it
 * maintains additional statistics depending on how CLICK_STATS is defined:
 *
 * @code
 * input(i).element()->pull(input(i).port())
 * @endcode
 */
inline Packet*
Element::Port::pull() const
{
    assert(_e);
#if CLICK_STATS >= 2
    click_cycles_t start_cycles = click_get_cycles(),
	old_child_cycles = _e->_child_cycles;
# if HAVE_BOUND_PORT_TRANSFER
    Packet *p = _bound.pull(_e, _port);
# else
    Packet *p = _e->pull(_port);
# endif
    if (p)
	_e->output(_port)._packets += 1;
    click_cycles_t all_delta = click_get_cycles() - start_cycles,
	own_delta = all_delta - (_e->_child_cycles - old_child_cycles);
    _e->_xfer_calls += 1;
    _e->_xfer_own_cycles += own_delta;
    _owner->_child_cycles += all_delta;
#else
# if HAVE_BOUND_PORT_TRANSFER
    Packet *p = _bound.pull(_e, _port);
# else
    Packet *p = _e->pull(_port);
# endif
#endif
#if CLICK_STATS >= 1
    if (p)
	++_packets;
#endif
    return p;
}

/** @brief Push packet @a p to output @a port, or kill it if @a port is out of
 * range.
 *
 * @param port output port number
 * @param p packet to push
 *
 * If @a port is in range (>= 0 and < noutputs()), then push packet @a p
 * forward using output(@a port).push(@a p).  Otherwise, kill @a p with @a p
 * ->kill().
 *
 * @note It is invalid to call checked_output_push() on a pull output @a port.
 */
inline void
Element::checked_output_push(int port, Packet* p) const
{
    if ((unsigned) port < (unsigned) noutputs())
	_ports[1][port].push(p);
    else
	p->kill();
}

/** @brief Pull a packet from input @a port, or return 0 if @a port is out of
 * range.
 *
 * @param port input port number
 *
 * If @a port is in range (>= 0 and < ninputs()), then return the result
 * of input(@a port).pull().  Otherwise, return null.
 *
 * @note It is invalid to call checked_input_pull() on a push input @a port.
 */
inline Packet*
Element::checked_input_pull(int port) const
{
    if ((unsigned) port < (unsigned) ninputs())
	return _ports[0][port].pull();
    else
	return 0;
}

#undef PORT_ASSIGN
CLICK_ENDDECLS
#endif


text:
/**TestStack
  *
  *@author Justin Ely
  */

import java.util.EmptyStackException;
import java.nio.BufferOverflowException;

/**Test the stack interface
  *
  *
This module provides pseudo-unit tests
  *    against the stack class. All core functions
  *    are excercised to test
  *    their stated function, along with the cases
  *    and errors that should be thrown.
  *

  *
Tests are performed with the assert
  *    statement, such that a failing test will halt the
  *    execuation at the failing statement.  This behavior
  *    is deliberate, as a failure is critical and should not
  *    be missed amongst the standard output
  *

  */
public class TestStack{

  /**Main test driver
    *
    *@param args[]   Holds command line arguments: Not used
    */
  public static void main(String[]args){
    System.out.println("###################################");
    System.out.println("# Testing the stack functionality #");
    System.out.println("#                                 #");
    System.out.println("# STDOUT is OK, Errors will be    #");
    System.out.println("# raised for failing tests        #");
    System.out.println("###################################");

    //Test push, pop, peek, isEmpty, size
    coreFunctionality();

    //Test the failure cases
    peekErrorHandling();
    popErrorHandling();
    pushErrorHandling();

    System.out.println("###################################");
    System.out.println("#     Finished Stack Testing      #");
    System.out.println("###################################");
  }

  /**Test the core functions of the stack
    *
    *
A list of strings will be sequentially pushed
    *   onto the stack, and subsequently peeked and popped
    *   off.  Before and after, the size and empty state will
    *   be checked.
    *

    *
Testing is done through assert statements,
    *   with additional output to visualize testing.  As such,
    *   output does not indicate a positive or negative test,
    *   but execution is a positive test and halting execution
    *   is a failure.
    *

    */
  public static void coreFunctionality(){
    Stack tester = new Stack();
    String[] alpha = new String[]{"a", "b", "c", "d", "e", "f", "g"};
    int length = 7;

    assert tester.isEmpty() : "New stack doesn't appear empty";
    assert tester.size() == 0 : "New stack size isn't 0";
    System.out.println("Testing empty() and size(): ok");

    System.out.println("Running push tests");
    for (int i=0; i<7; i++){
      tester.push(alpha[i]);
      assert tester.size() == i+1: "Size mismatch on iter: " + (i+1);
      System.out.println(tester.peek() + " push ok");
    }

    System.out.println("Running pop tests");
    int i = length - 1;
    while (tester.isEmpty() == false){
      System.out.println(tester.peek() + " == " + alpha[i]);
      assert tester.size() == i+1: "Size mismatch on iter: " + (i);
      assert alpha[i] == tester.pop() : i + "ith pop didn't match";
      i--;
    }

    assert tester.isEmpty() : "Final stack doesn't appear empty";
    assert tester.size() == 0 : "Final stack size isn't 0";
    System.out.println("Running final empty tests: ok");
  }

  /**Verify peek function error
    */
  public static void peekErrorHandling(){
    Stack tester = new Stack();
    boolean thrownCorrect = false;

    try {
      tester.peek();
    } catch (EmptyStackException e) {
      thrownCorrect = true;
    }

    assert thrownCorrect : "Peek doesn't throw right";
  }

  /**Verify pop function error
    */
  public static void popErrorHandling(){
    Stack tester = new Stack();
    boolean thrownCorrect = false;

    try {
      tester.pop();
    } catch (EmptyStackException e) {
      thrownCorrect = true;
    }

    assert thrownCorrect : "Pop doesn't throw right";
  }

  /**Verify push function error
    */
  public static void pushErrorHandling(){
    Stack tester = new Stack();
    boolean thrownCorrect = false;

    try {
      for (int i=0; i<500; i++){
        tester.push("a");
      }
    } catch (BufferOverflowException e) {
      thrownCorrect = true;
    }

    assert thrownCorrect : "Peek doesn't throw right";
  }
}


text:
var extend = require('../lib/util/extend')
var createContext = require('./util/create-context')
var createREGL = require('../regl')
var tape = require('tape')

tape('sample', function (t) {
  var gl = createContext(16, 16)
  var regl = createREGL(gl)

  function testFlags (prefix, flags) {
    function same (pname, value, str) {
      t.equals(gl.getParameter(pname), value, prefix + ' ' + str)
    }

    // getParameter doesn't support these values :(
    // same(gl.SAMPLE_COVERAGE, flags.enable, 'enable')
    // same(gl.SAMPLE_ALPHA_TO_COVERAGE, flags.alpha, 'alpha')
    same(gl.SAMPLE_COVERAGE_VALUE, flags.coverage.value, 'coverage.value')
    same(gl.SAMPLE_COVERAGE_INVERT, flags.coverage.invert, 'coverage.invert')
  }

  var permutations = [
    {
      enable: true,
      alpha: true,
      coverage: {
        value: 0.5,
        invert: true
      }
    },
    {
      enable: false,
      alpha: false,
      coverage: {
        value: 0,
        invert: false
      }
    }
  ]

  var staticOptions = {
    frag: [
      'precision mediump float;',
      'uniform vec4 color;',
      'void main() {',
      '  gl_FragColor = vec4(1, 0, 0, 1);',
      '}'
    ].join('\n'),

    vert: [
      'precision mediump float;',
      'attribute vec2 position;',
      'void main() {',
      '  gl_Position = vec4(position, 0, 1);',
      '}'
    ].join('\n'),

    attributes: {
      position: regl.buffer([
        [0, 0],
        [1, 0],
        [1, 1],
        [0, 1],
        [1, 0],
        [1, 1]
      ])
    },

    count: 6
  }

  var dynamicDraw = regl(extend({
    sample: {
      enable: regl.prop('enable'),
      alpha: regl.prop('alpha'),
      coverage: regl.prop('coverage')
    }
  }, staticOptions))

  permutations.forEach(function (params, i) {
    dynamicDraw(params)
    testFlags('dynamic 1-shot #' + i + ' - ', params)
  })

  permutations.forEach(function (params, i) {
    dynamicDraw([params])
    testFlags('batch #' + i + ' - ', params)
  })

  permutations.forEach(function (params, i) {
    var staticDraw = regl(extend({
      sample: params
    }, staticOptions))
    staticDraw()
    testFlags('static #' + i + ' - ', params)
  })

  // test nested dynamic properties.

  var nestedDynamicDraw = regl(extend({
    sample: {
      enable: regl.prop('enable'),
      alpha: regl.prop('alpha'),
      coverage: {
        value: regl.prop('coverage.value'),
        invert: regl.prop('coverage.invert')
      }
    }
  }, staticOptions))

  permutations.forEach(function (params, i) {
    nestedDynamicDraw(params)
    testFlags('dynamic 1-shot #' + i + ' - ', params)
  })

  permutations.forEach(function (params, i) {
    nestedDynamicDraw([params])
    testFlags('batch #' + i + ' - ', params)
  })

  regl.destroy()
  t.equals(gl.getError(), 0, 'error ok')
  createContext.destroy(gl)
  t.end()
})


text:
package io.infinicast;

public class Endpoint2ServerNetSettings implements IEndpoint2ServerNetSettings {
    InfinicastServerAddress address;
    IEndpoint2ServerNetLayerHandler handler;

    @Override
    public InfinicastServerAddress getServerAddress() {
        return address;
    }

    public void setServerAddress(InfinicastServerAddress address) {
        this.address = address;
    }

    @Override
    public IEndpoint2ServerNetLayerHandler getHandler() {
        return handler;
    }

    public void setHandler(IEndpoint2ServerNetLayerHandler handler) {
        this.handler = handler;
    }
}


text:
"""video_utils test."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.data_generators import video_utils
from tensor2tensor.utils import decoding

import tensorflow as tf

class VideoUtilsTest(tf.test.TestCase):

  def testConvertPredictionsToVideoSummaries(self):
    # Initialize predictions.
    rng = np.random.RandomState(0)
    inputs = rng.randint(0, 255, (2, 32, 32, 3))
    outputs = rng.randint(0, 255, (5, 32, 32, 3))
    targets = rng.randint(0, 255, (5, 32, 32, 3))

    # batch it up.
    prediction = [{"outputs": outputs, "inputs": inputs, "targets": targets}]*50
    predictions = [prediction]
    decode_hparams = decoding.decode_hparams()

    decode_hooks = decoding.DecodeHookArgs(
        estimator=None, problem=None, output_dirs=None,
        hparams=decode_hparams, decode_hparams=decode_hparams,
        predictions=predictions)
    summaries = video_utils.display_video_hooks(decode_hooks)
    # ground_truth + output.
    self.assertEqual(len(summaries), 20)
    for summary in summaries:
      self.assertTrue(isinstance(summary, tf.Summary.Value))

if __name__ == "__main__":
  tf.test.main()


text:
#ifndef __CCCONSOLE_H__
#define __CCCONSOLE_H__

#if defined(_MSC_VER) || defined(__MINGW32__)
#include <BaseTsd.h>
#include <WinSock2.h>
//typedef SSIZE_T ssize_t;
// ssize_t was redefined as int in libwebsockets.h.
// Therefore, to avoid conflict, we needs the same definition.
typedef int ssize_t;
#else
#include <sys/select.h>
#endif

#include <thread>
#include <vector>
#include <functional>
#include <string>
#include <mutex>

#include <stdarg.h>

#include "ccMacros.h"
#include "CCPlatformMacros.h"

NS_CC_BEGIN

/// The max length of CCLog message.
static const int MAX_LOG_LENGTH = 16*1024;

/**
 @brief Output Debug message.
 */
void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2);

/** Console is helper class that lets the developer control the game from TCP connection.
 Console will spawn a new thread that will listen to a specified TCP port.
 Console has a basic token parser. Each token is associated with an std::function<void(int)>.
 If the std::function<> needs to use the cocos2d API, it needs to call

 ```
 scheduler->performFunctionInCocosThread( ... );
 ```
 */
class CC_DLL Console
{
public:
    struct Command {
        const char *name;
        std::function<void(int, const char*)> callback;
    };

    /** Constructor */
    Console();

    /** Destructor */
    virtual ~Console();

    /** starts listening to specifed TCP port */
    bool listenOnTCP(int port);

    /** starts listening to specifed file descriptor */
    bool listenOnFileDescriptor(int fd);

    /** stops the Console. 'stop' will be called at destruction time as well */
    void stop();

    /** sets user tokens */
    void setUserCommands( Command* commands, int numberOfCommands);

    /** log something in the console */
    void log(const char *buf);

protected:
    void loop();
    ssize_t readline(int fd);
    bool parseCommand(int fd);
    void sendPrompt(int fd);
    void addClient();

    // Add commands here
    void commandHelp(int fd, const char *command);
    void commandExit(int fd, const char *command);
    void commandSceneGraph(int fd, const char *command);
    void commandFileUtilsDump(int fd, const char *command);
    void commandConfig(int fd, const char *command);
    void commandTextures(int fd, const char *command);

    // file descriptor: socket, console, etc.
    int _listenfd;
    int _maxfd;
    std::vector<int> _fds;
    std::thread _thread;

    fd_set _read_set;

    bool _running;
    bool _endThread;

    char _buffer[512];

    struct Command _commands[64];
    int _maxCommands;
    struct Command *_userCommands;
    int _maxUserCommands;

    // strings generated by cocos2d sent to the remote console
    bool _sendDebugStrings;
    std::mutex _DebugStringsMutex;
    std::vector<std::string> _DebugStrings;

private:
    CC_DISALLOW_COPY_AND_ASSIGN(Console);
};

NS_CC_END

#endif /* defined(__CCCONSOLE_H__) */


text:
/** @module Set */

/**
 * This Set constructor exists mainly to unify the interface with Sample and Inc. The value is not
 * limited to numbers.
 *
 * @param val Simply sets the internal state to val.
 * @param {Number} timeStamp A unix time stamp (in ms).
 * @param {Object} persistObj The object that this set belongs to. This is not used, but the
 *                            argument must be here for consistency.
 * @constructor
 * @alias module:Set
 */

function Set(val, timeStamp, persistObj) {
	this.value = val;
	this.timeStamp = timeStamp;

	if (persistObj) {
		var that = this;

		persistObj.on('reset', function (timeStamp) {
			that.reset(timeStamp);
		});
	}
}

/**
 * Simply replace the existing value contained in a set object.
 *
 * @param val Reset the internal state to val.
 * @param {Number} timeStamp A unix time stamp (in ms).
 */

Set.prototype.update = function (val, timeStamp) {
	this.value = val;
	this.timeStamp = timeStamp;
};

/**
 * Simply return the value in the value contained in a set object.
 *
 * @return Returns the stored value, with optional type information.
 */

Set.prototype.toJSON = function () {
	return {
		type: 'set',
		value: { val: this.value, timeStamp: this.timeStamp}
	};
};

/**
 * If we are persisting, set the time stamp.
 *
 * @param {Number} timeStamp A unix time stamp (in ms).
 */

Set.prototype.reset = function (timeStamp) {
	this.timeStamp = timeStamp;
};

module.exports = Set;


text:
/*
 * UserDataPicker.java
 *
 * Created on 20 août 2012, 22:09:04
 */
package com.jme3.gde.core.sceneexplorer.nodes.actions;

import com.jme3.gde.core.assets.ProjectAssetManager;
import com.jme3.gde.core.properties.ParticleInfluencerPropertyEditor;
import com.jme3.gde.core.sceneexplorer.nodes.JmeParticleEmitter;
import java.awt.EventQueue;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.swing.DefaultListModel;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.source.ClassIndex;
import org.netbeans.api.java.source.ClassIndex.NameKind;
import org.netbeans.api.java.source.ClassIndex.SearchScope;
import org.netbeans.api.java.source.ClasspathInfo;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.JavaSource.Phase;
import org.netbeans.api.java.source.Task;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.openide.util.Exceptions;

/**
 *
 * @author Nehon
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public class ParticleInfluencerPicker extends javax.swing.JDialog {

    JmeParticleEmitter jmePE;
    ParticleInfluencerPropertyEditor editor;
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);

    /**
     * Creates new form UserDataPicker
     */
    public ParticleInfluencerPicker(java.awt.Frame parent, boolean modal, ParticleInfluencerPropertyEditor editor, JmeParticleEmitter spat) {
        super(parent, modal);
        this.jmePE = spat;
        initComponents();
        this.editor = editor;

        setLocationRelativeTo(null);

        jList1.setEnabled(false);
        //loading savable list in a new Thread
        exec.execute(new Runnable() {
            public void run() {
                final DefaultListModel model = getSources();

                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        jList1.setModel(model);
                        jList1.setEnabled(true);
                    }
                });

            }
        });

    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        exec.shutdown();
    }

    private DefaultListModel getSources() {
        final DefaultListModel model = new DefaultListModel();
        model.addElement("com.jme3.effect.influencers.DefaultParticleInfluencer");
        model.addElement("com.jme3.effect.influencers.NewtonianParticleInfluencer");
        model.addElement("com.jme3.effect.influencers.RadialParticleInfluencer");
        model.addElement("com.jme3.effect.influencers.EmptyParticleInfluencer");
        Sources sources = jmePE.getLookup().lookup(ProjectAssetManager.class).getProject().getLookup().lookup(Sources.class);
        if (sources != null) {
            SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
            if (groups != null) {
                for (SourceGroup sourceGroup : groups) {
                    ClasspathInfo cpInfo = ClasspathInfo.create(ClassPath.getClassPath(sourceGroup.getRootFolder(), ClassPath.BOOT),
                            ClassPath.getClassPath(sourceGroup.getRootFolder(), ClassPath.COMPILE),
                            ClassPath.getClassPath(sourceGroup.getRootFolder(), ClassPath.SOURCE));

                    HashSet<SearchScope> set = new HashSet<SearchScope>();
                    set.add(ClassIndex.SearchScope.SOURCE);

                    Set<ElementHandle<TypeElement>> types = cpInfo.getClassIndex().getDeclaredTypes("", NameKind.PREFIX, set);
                    for (Iterator<ElementHandle<TypeElement>> it = types.iterator(); it.hasNext();) {
                        final ElementHandle<TypeElement> elementHandle = it.next();
                        JavaSource js = JavaSource.create(cpInfo);
                        try {
                            js.runUserActionTask(new Task<CompilationController>() {
                                public void run(CompilationController control)
                                        throws Exception {
                                    control.toPhase(Phase.RESOLVED);
                                    //TODO: check with proper casting check.. gotta get TypeMirror of Control interface..
//                                    TypeUtilities util = control.getTypeUtilities();//.isCastable(Types., null)
//                                    util.isCastable(null, null);
                                    TypeElement elem = elementHandle.resolve(control);
                                    List<? extends TypeMirror> interfaces = elem.getInterfaces();
                                    for (TypeMirror typeMirror : interfaces) {
                                        String interfaceName = typeMirror.toString();
                                        if ("com.jme3.effect.influencers.ParticleInfluencer".equals(interfaceName)) {
                                            model.addElement(elem.getQualifiedName().toString());
                                        }
                                    }
                                    TypeMirror superClass = elem.getSuperclass();
                                    String superClassName = superClass.toString();
                                    if ("com.jme3.effect.influencers.DefaultParticleInfluencer".equals(superClassName)) {
                                        model.addElement(elem.getQualifiedName().toString());
                                    }

                                }
                            }, false);
                        } catch (Exception ioe) {
                            Exceptions.printStackTrace(ioe);
                        }
                    }

                }
            }
        }
        return model;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ParticleInfluencerPicker.class, "ParticleInfluencerPicker.jPanel1.border.title"))); // NOI18N

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Loading Savable types..." };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jTextField1.setText(org.openide.util.NbBundle.getMessage(ParticleInfluencerPicker.class, "ParticleInfluencerPicker.jTextField1.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setText(org.openide.util.NbBundle.getMessage(ParticleInfluencerPicker.class, "ParticleInfluencerPicker.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(org.openide.util.NbBundle.getMessage(ParticleInfluencerPicker.class, "ParticleInfluencerPicker.jButton2.text")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 225, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    setVisible(false);
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    editor.setAsText(jTextField1.getText());
    setVisible(false);

}//GEN-LAST:event_jButton1ActionPerformed

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
    jTextField1.setText(jList1.getSelectedValue().toString());
}//GEN-LAST:event_jList1ValueChanged

private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
    if (evt.getClickCount() == 2) {
        jButton1ActionPerformed(null);
    }
}//GEN-LAST:event_jList1MouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}