text:
<?php

namespace Drupal\Tests\Component\Utility;

use Drupal\Component\Utility\Color;
use PHPUnit\Framework\TestCase;

/**
 * Tests Color utility class conversions.
 *
 * @group Utility
 */
class ColorTest extends TestCase {

  /**
   * Tests Color::hexToRgb().
   *
   * @param string $value
   *   The hex color value.
   * @param string $expected
   *   The expected rgb color value.
   * @param bool $invalid
   *   Whether this value is invalid and exception should be expected.
   *
   * @dataProvider providerTestHexToRgb
   */
  public function testHexToRgb($value, $expected, $invalid = FALSE) {
    if ($invalid) {
      if (method_exists($this, 'expectException')) {
        $this->expectException('InvalidArgumentException');
      }
      else {
        $this->setExpectedException('InvalidArgumentException');
      }
    }
    $this->assertSame($expected, Color::hexToRgb($value));
  }

  /**
   * Data provider for testHexToRgb().
   *
   * @see testHexToRgb()
   *
   * @return array
   *   An array of arrays containing:
   *     - The hex color value.
   *     - The rgb color array value.
   *     - (optional) Boolean indicating invalid status. Defaults to FALSE.
   */
  public function providerTestHexToRgb() {
    $invalid = [];
    // Any invalid arguments should throw an exception.
    foreach (['', '-1', '1', '12', '12345', '1234567', '123456789', '123456789a', 'foo'] as $value) {
      $invalid[] = [$value, '', TRUE];
    }
    // Duplicate all invalid value tests with additional '#' prefix.
    // The '#' prefix inherently turns the data type into a string.
    foreach ($invalid as $value) {
      $invalid[] = ['#' . $value[0], '', TRUE];
    }
    // Add invalid data types (hex value must be a string).
    foreach ([
      1, 12, 1234, 12345, 123456, 1234567, 12345678, 123456789, 123456789,
      -1, PHP_INT_MAX, PHP_INT_MAX + 1, -PHP_INT_MAX, 0x0, 0x010
    ] as $value) {
      $invalid[] = [$value, '', TRUE];
    }
    // And some valid values.
    $valid = [
      // Shorthands without alpha.
      ['hex' => '#000', 'rgb' => ['red' => 0, 'green' => 0, 'blue' => 0]],
      ['hex' => '#fff', 'rgb' => ['red' => 255, 'green' => 255, 'blue' => 255]],
      ['hex' => '#abc', 'rgb' => ['red' => 170, 'green' => 187, 'blue' => 204]],
      ['hex' => 'cba', 'rgb' => ['red' => 204, 'green' => 187, 'blue' => 170]],
      // Full without alpha.
      ['hex' => '#000000', 'rgb' => ['red' => 0, 'green' => 0, 'blue' => 0]],
      ['hex' => '#ffffff', 'rgb' => ['red' => 255, 'green' => 255, 'blue' => 255]],
      ['hex' => '#010203', 'rgb' => ['red' => 1, 'green' => 2, 'blue' => 3]],
    ];
    return array_merge($invalid, $valid);
  }

  /**
   * Tests Color::rgbToHex().
   *
   * @param string $value
   *   The rgb color value.
   * @param string $expected
   *   The expected hex color value.
   *
   * @dataProvider providerTestRbgToHex
   */
  public function testRgbToHex($value, $expected) {
    $this->assertSame($expected, Color::rgbToHex($value));
  }

  /**
   * Data provider for testRgbToHex().
   *
   * @see testRgbToHex()
   *
   * @return array
   *   An array of arrays containing:
   *     - The rgb color array value.
   *     - The hex color value.
   */
  public function providerTestRbgToHex() {
    // Input using named RGB array (e.g., as returned by Color::hexToRgb()).
    $tests = [
      [['red' => 0, 'green' => 0, 'blue' => 0], '#000000'],
      [['red' => 255, 'green' => 255, 'blue' => 255], '#ffffff'],
      [['red' => 119, 'green' => 119, 'blue' => 119], '#777777'],
      [['red' => 1, 'green' => 2, 'blue' => 3], '#010203'],
    ];
    // Input using indexed RGB array (e.g.: array(10, 10, 10)).
    foreach ($tests as $test) {
      $tests[] = [array_values($test[0]), $test[1]];
    }
    // Input using CSS RGB string notation (e.g.: 10, 10, 10).
    foreach ($tests as $test) {
      $tests[] = [implode(', ', $test[0]), $test[1]];
    }
    return $tests;
  }

  /**
   * Data provider for testNormalizeHexLength().
   *
   * @see testNormalizeHexLength()
   *
   * @return array
   *   An array of arrays containing:
   *     - The hex color value.
   *     - The 6 character length hex color value.
   */
  public function providerTestNormalizeHexLength() {
    $data = [
      ['#000', '#000000'],
      ['#FFF', '#FFFFFF'],
      ['#abc', '#aabbcc'],
      ['cba', '#ccbbaa'],
      ['#000000', '#000000'],
      ['ffffff', '#ffffff'],
      ['#010203', '#010203'],
    ];

    return $data;
  }

  /**
   * Tests Color::normalizeHexLength().
   *
   * @param string $value
   *   The input hex color value.
   * @param string $expected
   *   The expected normalized hex color value.
   *
   * @dataProvider providerTestNormalizeHexLength
   */
  public function testNormalizeHexLength($value, $expected) {
    $this->assertSame($expected, Color::normalizeHexLength($value));
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

<title>Body Source</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta name="generator" content="Doc-O-Matic">
    <link rel="STYLESHEET" href="default.css" type="text/css">

SimMetrics library v 1.5 for .NET 2.0

Contents | Index | Reference

Body Source

BlockDistance.GetSimilarity

Body Source

public override double GetSimilarity(string firstWord, string secondWord) {
    Collection<string> firstTokens = tokeniser.Tokenize(firstWord);
    Collection<string> secondTokens = tokeniser.Tokenize(secondWord);
    int totalPossible = firstTokens.Count + secondTokens.Count;
    double totalDistance = GetActualSimilarity(firstTokens, secondTokens);
    return (totalPossible - totalDistance) / totalPossible;
}

Copyright (c) 2006. All rights reserved.

Contents | Index | Reference

redpajama_set_name: RedPajamaGithub


text:
[![Join the chat at https://gitter.im/iesen/rabbitmq-maven-plugin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iesen/rabbitmq-maven-plugin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

A maven plugin that downloads, install and configures a RabbitMQ instance within maven lifecycle

## Example Usage

Below is an example configuration for the plugin. You can add exchanges, queues and their binding in the configuration section.

```xml
<plugin>
    <groupId>com.github.iesen</groupId>
    <artifactId>rabbitmq-maven-plugin</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <configuration>
        <detached>true</detached>
        <exchanges>
            <exchange>
                <name>myexchange</name>
                <type>topic</type>
            </exchange>
            <queues>
                <queue>
                    <name>myqueue</name>
                    <bindings>
                        <binding>
                            <exchangeName>myexchange</exchangeName>
                            <routingKey>message.pingpong.*</routingKey>
                        </binding>
                    </bindings>
                </queue>
            </queues>
        </exchanges>
    </configuration>
</plugin>
```

##More Information

The plugin first checks if RabbitMQ is installed by this plugin before. If not, installs RabbitMQ to the home folder.
(also installs Erlang runtime if OS is Windows). Just after installation it enables the management plugin and applies
the settings specified in the plugin configuration.

##Supported Platforms

Windows and Mac OS is supported.

Linux is supported but withouth erlang support.


text:
@interface FNSettingMostCacheController : YJSettingBaseController

@end


text:
package edu.duke.cabig.c3pr.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

import edu.duke.cabig.c3pr.constants.C3PRUserGroupType;
import edu.duke.cabig.c3pr.constants.ContactMechanismType;
import edu.duke.cabig.c3pr.domain.ContactMechanism;
import edu.duke.cabig.c3pr.domain.ContactMechanismBasedRecipient;
import edu.duke.cabig.c3pr.domain.HealthcareSiteInvestigator;
import edu.duke.cabig.c3pr.domain.Investigator;
import edu.duke.cabig.c3pr.domain.PlannedNotification;
import edu.duke.cabig.c3pr.domain.PersonUser;
import edu.duke.cabig.c3pr.domain.RoleBasedRecipient;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyCoordinatingCenter;
import edu.duke.cabig.c3pr.domain.StudyOrganization;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.UserBasedRecipient;
import edu.duke.cabig.c3pr.exception.C3PRBaseException;
import edu.duke.cabig.c3pr.service.impl.PersonnelServiceImpl;

/**
 * Author: vGangoli Date: Nov 30, 2007
 */
public class StudyTargetAccrualNotificationEmail {

    private MailSender mailSender;

    private SimpleMailMessage accountCreatedTemplateMessage;

    PersonnelServiceImpl personnelServiceImpl;

    private Logger log = Logger.getLogger(StudyTargetAccrualNotificationEmail.class);

    public static final String STUDY_INVESTIGATOR = "SI";
    /**
     * This method is responsible for figuring out the email address from notifications and sending
     * out the notification email using Javamail.
     *
     * @param studySubject
     */
    public void sendEmail(StudySubject studySubject) {

        Study study = studySubject.getStudySite().getStudy();
        int totalAccrual = calculateTotalAccrual(study);
        List<String> emailList = null;

        for (PlannedNotification nf : study.getPlannedNotifications()) {
            if (totalAccrual >= nf.getStudyThreshold()) {
                emailList = generateEmailList(study, nf);
                for (String emailAddress : emailList) {
                    try {
                    	if(emailAddress != null){
                    		SimpleMailMessage msg = new SimpleMailMessage(
                                    this.accountCreatedTemplateMessage);
		                    msg.setSubject("Study Threshold Notification.");
		                    msg.setTo(emailAddress);
		                    msg.setText("This is to notify you that the study accrual for "
										+ study.getShortTitleText() + " has now reached " + totalAccrual + ".");
							log.debug("Trying to send study target accrual notification email to "+emailAddress);

		                    this.mailSender.send(msg);
                    	}
                    }
                    catch (MailException e) {
                        log.error("Could not send email due to  " + e.getMessage());
                        // just log it for now
                    }
                }
            }
        }

    }

    /**
     * This method generates a list of emails by getting the emailaddresses from all the email based
     * Recepients and Role based Recepients for a given Notification. The role based recepient only
     * has the role String...the corresponding personnel in that role for that study have to be
     * retrieved and their email addresses have to be addded to the finalList.
     */
    public List<String> generateEmailList(Study study, PlannedNotification nf) {

        List<String> finalList = new ArrayList<String>();
        for (ContactMechanismBasedRecipient cmbr : nf.getContactMechanismBasedRecipient()) {
        	for (ContactMechanism cm : cmbr.getContactMechanisms()) {
        		if(cm.getType().getCode().equalsIgnoreCase(ContactMechanismType.EMAIL.getCode())){
        			finalList.add(cm.getValue());
        		}
            }
        }
        for (UserBasedRecipient er : nf.getUserBasedRecipient()) {
            finalList.add(er.getEmailAddress());
        }
        for (RoleBasedRecipient rr : nf.getRoleBasedRecipient()) {
            finalList.addAll(getEmailsFromRoleBasedRecipient(study, rr));
        }

        return finalList;
    }

    public List<String> getEmailsFromRoleBasedRecipient(Study study, RoleBasedRecipient rr) {
        List<StudyOrganization> studyOrgList = study.getStudyOrganizations();
        List<String> returnList = new ArrayList<String>();
        List<C3PRUserGroupType> groupList = null;
        List<PersonUser> rStaffList = null;
        for (StudyOrganization so : studyOrgList) {
            if (so instanceof StudyCoordinatingCenter) {
                rStaffList = so.getHealthcareSite().getPersonUsers();

                for (PersonUser rs : rStaffList) {
                    try {
                        groupList = personnelServiceImpl.getGroups(rs);
                    }
                    catch (C3PRBaseException e) {
                        log
                                        .error("StudyTargetAccrualNotificationAspect - personnelServiceImpl.getGroups():FAILED");
                        log.error(e.getMessage());
                    }
                    /* Handle the investigator code seperately */
                    if (groupList != null) {
                        for (C3PRUserGroupType group : groupList) {
                            if (group.getCode().equalsIgnoreCase(rr.getRole())) {
                                returnList.addAll(getEmailAddressesFromResearchStaff(rs));
                            }
                            //Handling the investigators
							if(rr.getRole().equalsIgnoreCase(STUDY_INVESTIGATOR)){
								for(HealthcareSiteInvestigator hcsi: so.getHealthcareSite().getHealthcareSiteInvestigators()){
									returnList.addAll(getEmailAddressesFromInvestigator(hcsi.getInvestigator()));
								}
                            }
                        }
                    }
                }
            }

        }
        return returnList;
    }

    public List<String> getEmailAddressesFromResearchStaff(PersonUser rs) {

        List<String> returnList = new ArrayList<String>();
//        for (ContactMechanism cm : rs.getContactMechanisms()) {
//            if (cm.getType().equals(ContactMechanismType.EMAIL)) {
//                returnList.add(cm.getValue());
//            }
//        }
        returnList.add(rs.getEmail());
        return returnList;
    }

	public List<String> getEmailAddressesFromInvestigator(Investigator inv) {
		List<String> returnList = new ArrayList<String>();
//		for (ContactMechanism cm : inv.getContactMechanisms()) {
//			if (cm.getType().equals(ContactMechanismType.EMAIL)) {
//				returnList.add(cm.getValue());
//			}
//		}
		returnList.add(inv.getEmail());
		return returnList;
    }

    /**
     * This method calculates the total number of subjects assigned to a study by iterating through
     * all the sites that are in the study.
     */
    public int calculateTotalAccrual(Study study) {
        List<StudySite> studySitesList = study.getStudySites();
        int totalAccrual = 0;
        Iterator sslIter = studySitesList.iterator();
        StudySite studySite;
        while (sslIter.hasNext()) {
            studySite = (StudySite) sslIter.next();
            // replace this with a "count-calculating HQL method" call.
            totalAccrual += studySite.getStudySubjects().size();
        }
        return totalAccrual;
    }

    public MailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public SimpleMailMessage getAccountCreatedTemplateMessage() {
        return accountCreatedTemplateMessage;
    }

    public void setAccountCreatedTemplateMessage(SimpleMailMessage accountCreatedTemplateMessage) {
        this.accountCreatedTemplateMessage = accountCreatedTemplateMessage;
    }

    public PersonnelServiceImpl getPersonnelServiceImpl() {
        return personnelServiceImpl;
    }

    public void setPersonnelServiceImpl(PersonnelServiceImpl personnelServiceImpl) {
        this.personnelServiceImpl = personnelServiceImpl;
    }
}


text:
Running Parsl on Midway
=======================

This is a brief guide to running Parsl on UChicago RCC's midway cluster.

Requirements
============

Make sure you have python3.6 and Parsl installed with all it's dependencies.

Running IPP
===========

In order to run Parsl apps on Midway nodes, we need to first start an IPython controller on the login node.

>>> ipcontroller --port=5XXXX --ip=*

Once the ipcontroller is started in a separate terminal or in a screen session, we can now run parsl scripts.

Parsl Config:
=============

Here's a config for Midway that starts with a request for 2 nodes.

.. code:: python3

        USERNAME = <SET_YOUR_USERNAME>

        { "site" : "Midway_Remote_Westmere",
          "auth" : {
              "channel" : "ssh",
              "hostname" : "swift.rcc.uchicago.edu",
              "username" : USERNAME,
              "script_dir" : "/scratch/midway2/{0}/parsl_scripts".format(USERNAME)
          },
          "execution" : {
              "executor" : "ipp",
              "provider" : "slurm",
              "block" : { # Definition of a block
                  "nodes" : 1,            # of nodes in that block
                  "task_blocks" : 1,       # total tasks in a block
                  "init_blocks" : 1,
                  "max_blocks" : 1,
                  "options" : {
                      "partition" : "westmere",
                      "overrides" : """module load python/3.5.2+gcc-4.8; source /scratch/midway2/yadunand/parsl_env_3.5.2_gcc/bin/activate"""
                  }
              }
          }
        }


text:
package Univale.Tcc.RL.Pogamut.Bot;

import Univale.Tcc.RL.Pogamut.DecisionMaking.Agent.QLearningAgent;

/**
 * Created by winicius on 17/11/2014.
 */
public class QLearningBot extends LearnerBot {
    public QLearningBot()
    {
        super(new QLearningAgent());
    }
}


text:
namespace syncer {
namespace sessions {

SyncSessionSnapshot::SyncSessionSnapshot()
    : is_silenced_(false),
      num_encryption_conflicts_(0),
      num_hierarchy_conflicts_(0),
      num_server_conflicts_(0),
      notifications_enabled_(false),
      num_entries_(0),
      num_entries_by_type_(MODEL_TYPE_COUNT, 0),
      num_to_delete_entries_by_type_(MODEL_TYPE_COUNT, 0),
      is_initialized_(false) {}

SyncSessionSnapshot::SyncSessionSnapshot(
    const ModelNeutralState& model_neutral_state,
    const ProgressMarkerMap& download_progress_markers,
    bool is_silenced,
    int num_encryption_conflicts,
    int num_hierarchy_conflicts,
    int num_server_conflicts,
    bool notifications_enabled,
    size_t num_entries,
    base::Time sync_start_time,
    base::Time poll_finish_time,
    const std::vector<int>& num_entries_by_type,
    const std::vector<int>& num_to_delete_entries_by_type,
    sync_pb::GetUpdatesCallerInfo::GetUpdatesSource legacy_updates_source)
    : model_neutral_state_(model_neutral_state),
      download_progress_markers_(download_progress_markers),
      is_silenced_(is_silenced),
      num_encryption_conflicts_(num_encryption_conflicts),
      num_hierarchy_conflicts_(num_hierarchy_conflicts),
      num_server_conflicts_(num_server_conflicts),
      notifications_enabled_(notifications_enabled),
      num_entries_(num_entries),
      sync_start_time_(sync_start_time),
      poll_finish_time_(poll_finish_time),
      num_entries_by_type_(num_entries_by_type),
      num_to_delete_entries_by_type_(num_to_delete_entries_by_type),
      legacy_updates_source_(legacy_updates_source),
      is_initialized_(true) {}

SyncSessionSnapshot::SyncSessionSnapshot(const SyncSessionSnapshot& other) =
    default;

SyncSessionSnapshot::~SyncSessionSnapshot() {}

std::unique_ptr<base::DictionaryValue> SyncSessionSnapshot::ToValue() const {
  std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue());
  value->SetInteger("numSuccessfulCommits",
                    model_neutral_state_.num_successful_commits);
  value->SetInteger("numSuccessfulBookmarkCommits",
                    model_neutral_state_.num_successful_bookmark_commits);
  value->SetInteger("numUpdatesDownloadedTotal",
                    model_neutral_state_.num_updates_downloaded_total);
  value->SetInteger(
      "numTombstoneUpdatesDownloadedTotal",
      model_neutral_state_.num_tombstone_updates_downloaded_total);
  value->SetInteger(
      "numReflectedUpdatesDownloadedTotal",
      model_neutral_state_.num_reflected_updates_downloaded_total);
  value->SetInteger("numLocalOverwrites",
                    model_neutral_state_.num_local_overwrites);
  value->SetInteger("numServerOverwrites",
                    model_neutral_state_.num_server_overwrites);
  value->Set("downloadProgressMarkers",
             ProgressMarkerMapToValue(download_progress_markers_));
  value->SetBoolean("isSilenced", is_silenced_);
  // We don't care too much if we lose precision here, also.
  value->SetInteger("numEncryptionConflicts", num_encryption_conflicts_);
  value->SetInteger("numHierarchyConflicts", num_hierarchy_conflicts_);
  value->SetInteger("numServerConflicts", num_server_conflicts_);
  value->SetInteger("numEntries", num_entries_);
  value->SetString("legacySource",
                   GetUpdatesSourceString(legacy_updates_source_));
  value->SetBoolean("notificationsEnabled", notifications_enabled_);

  std::unique_ptr<base::DictionaryValue> counter_entries(
      new base::DictionaryValue());
  for (int i = FIRST_REAL_MODEL_TYPE; i < MODEL_TYPE_COUNT; i++) {
    std::unique_ptr<base::DictionaryValue> type_entries(
        new base::DictionaryValue());
    type_entries->SetInteger("numEntries", num_entries_by_type_[i]);
    type_entries->SetInteger("numToDeleteEntries",
                             num_to_delete_entries_by_type_[i]);

    const std::string model_type = ModelTypeToString(static_cast<ModelType>(i));
    counter_entries->Set(model_type, type_entries.release());
  }
  value->Set("counter_entries", std::move(counter_entries));
  return value;
}

std::string SyncSessionSnapshot::ToString() const {
  std::string json;
  base::JSONWriter::WriteWithOptions(
      *ToValue(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &json);
  return json;
}

const ProgressMarkerMap& SyncSessionSnapshot::download_progress_markers()
    const {
  return download_progress_markers_;
}

bool SyncSessionSnapshot::is_silenced() const {
  return is_silenced_;
}

int SyncSessionSnapshot::num_encryption_conflicts() const {
  return num_encryption_conflicts_;
}

int SyncSessionSnapshot::num_hierarchy_conflicts() const {
  return num_hierarchy_conflicts_;
}

int SyncSessionSnapshot::num_server_conflicts() const {
  return num_server_conflicts_;
}

bool SyncSessionSnapshot::notifications_enabled() const {
  return notifications_enabled_;
}

size_t SyncSessionSnapshot::num_entries() const {
  return num_entries_;
}

base::Time SyncSessionSnapshot::sync_start_time() const {
  return sync_start_time_;
}

base::Time SyncSessionSnapshot::poll_finish_time() const {
  return poll_finish_time_;
}

bool SyncSessionSnapshot::is_initialized() const {
  return is_initialized_;
}

const std::vector<int>& SyncSessionSnapshot::num_entries_by_type() const {
  return num_entries_by_type_;
}

const std::vector<int>& SyncSessionSnapshot::num_to_delete_entries_by_type()
    const {
  return num_to_delete_entries_by_type_;
}

sync_pb::GetUpdatesCallerInfo::GetUpdatesSource
SyncSessionSnapshot::legacy_updates_source() const {
  return legacy_updates_source_;
}

}  // namespace sessions
}  // namespace syncer


text:
module Rails
  module Decorators
    VERSION = '1.0.0.pre'
  end
end


text:
const path = require(`path`)

// Create a slug for each recipe and set it as a field on the node.
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `recipes`) {
    const slug = `/recipes/${node.internalId}/`
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

// Implement the Gatsby API "createPages". This is called once the
// data layer is bootstrapped to let plugins create pages from data.
exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

  const recipeTemplate = path.resolve(`src/templates/recipe.js`)
  // Query for recipe nodes to use in creating pages.
  return graphql(
    `
      {
        allRecipes {
          edges {
            node {
              internalId
              fields {
                slug
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create pages for each recipe.
    result.data.allRecipes.edges.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: recipeTemplate,
        context: {
          slug: node.fields.slug,
        },
      })
    })
  })
}


text:
import arcade

def on_draw(delta_time):
    arcade.start_render()

    # Appear in first column
    arcade.draw_circle_filled(100, 100, 50, arcade.color.YELLOW)

    # Appear in second column
    arcade.draw_small_filled_circle(300, 100, arcade.color.YELLOW)
    arcade.draw_medium_filled_circle(300, 300, arcade.color.YELLOW)
    arcade.draw_large_filled_circle(300, 500, arcade.color.YELLOW)

    # Appear in third column
    arcade.draw_standard_circle(500, 100,
                                arcade.color.YELLOW, "LARGE", "filled")
    arcade.draw_standard_circle(500, 300,
                                arcade.color.YELLOW, "m", "filled")
    arcade.draw_standard_circle(500, 500,
                                arcade.color.YELLOW, "small", "filled")

    # Appear in fourth column
    arcade.draw_circle_outline(700, 300, 50, arcade.color.YELLOW)

    arcade.draw_circle(700, 100, 50, arcade.color.YELLOW)

arcade.open_window("Test Circles", 800, 600)
arcade.set_background_color(arcade.color.RED)

arcade.schedule(on_draw, 1/80)

arcade.run()

arcade.close_window()


text:
package edu.ucdenver.ccp.datasource.identifiers.impl.ice;

import edu.ucdenver.ccp.datasource.fileparsers.CcpExtensionOntology;

import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.Identifier;
import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier;

@Identifier(ontClass=CcpExtensionOntology.WIKIPEDIA_IDENTIFIER)
public class WikipediaId extends StringDataSourceIdentifier {

	public WikipediaId(String resourceID) {
		super(resourceID, DataSource.WIKIPEDIA);
}

}


text:
/* C */
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

/* replicant */
#include <replicant.h>

#define REPLICANT_FINISH
#include "common.h"

int
main(int argc, char* argv[])
{
    int opt;
    const char* connect = "127.0.0.1:1982";
    struct replicant_client* repl = NULL;
    int64_t id;
    enum replicant_returncode rc;
    char* input = NULL;
    size_t input_sz = 0;
    uint64_t seqno = 0;

    while ((opt = getopt(argc, argv, "c:")) != -1)
    {
        switch (opt)
        {
            case 'c':
                connect = strdup(optarg);
                break;
            default:
                goto usage;
        }
    }

    if (optind + 2 != argc)
    {
        fprintf(stderr, "error: incorrect number of arguments\n\n");
        goto usage;
    }

    repl = replicant_client_create_conn_str(connect);

    if (!repl)
    {
        fprintf(stderr, "error: could not create replicant client\n");
        return EXIT_FAILURE;
    }

    seqno = atoi(argv[optind]);
    input_sz = sizeof(uint64_t) + strlen(argv[optind + 1]) + 1;
    input = malloc(input_sz);

    if (!input)
    {
        fprintf(stderr, "out of memory\n");
        return EXIT_FAILURE;
    }

    pack64be(seqno, input);
    strcpy(input + sizeof(uint64_t), argv[optind + 1]);
    id = replicant_client_call(repl, "lock", "unlock", input, input_sz,
                               REPLICANT_CALL_ROBUST, &rc, NULL, NULL);
    replicant_finish(repl, id, &rc);
    return EXIT_SUCCESS;

usage:
    fprintf(stderr, "usage: %s [-c connect-string] lock-holder-name\n", argv[0]);
    exit(EXIT_FAILURE);
}


text:
'use strict';

var getReturnUrl = function(req) {
  var returnUrl = req.user.defaultReturnUrl();
  if (req.session.returnUrl) {
    returnUrl = req.session.returnUrl;
    delete req.session.returnUrl;
  }
  return returnUrl;
};

exports.init = function(req, res){
  if (req.isAuthenticated()) {
    res.redirect(getReturnUrl(req));
  }
  else {
    res.render('login/index', {
      oauthMessage: ''/*,
      oauthTwitter: !!req.app.config.oauth.twitter.key,
      oauthGitHub: !!req.app.config.oauth.github.key,
      oauthFacebook: !!req.app.config.oauth.facebook.key,
      oauthGoogle: !!req.app.config.oauth.google.key,
      oauthTumblr: !!req.app.config.oauth.tumblr.key*/
    });
  }
};

exports.login = function(req, res){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.username) {
      workflow.outcome.errfor.username = 'required';
    }

    if (!req.body.password) {
      workflow.outcome.errfor.password = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('abuseFilter');
  });

  workflow.on('abuseFilter', function() {
    var getIpCount = function(done) {
      var conditions = { ip: req.ip };
      req.app.db.models.LoginAttempt.count(conditions, function(err, count) {
        if (err) {
          return done(err);
        }

        done(null, count);
      });
    };

    var getIpUserCount = function(done) {
      var conditions = { ip: req.ip, user: req.body.username };
      req.app.db.models.LoginAttempt.count(conditions, function(err, count) {
        if (err) {
          return done(err);
        }

        done(null, count);
      });
    };

    var asyncFinally = function(err, results) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (results.ip >= req.app.config.loginAttempts.forIp || results.ipUser >= req.app.config.loginAttempts.forIpAndUser) {
        workflow.outcome.errors.push('You\'ve reached the maximum number of login attempts. Please try again later.');
        return workflow.emit('response');
      }
      else {
        workflow.emit('attemptLogin');
      }
    };

    require('async').parallel({ ip: getIpCount, ipUser: getIpUserCount }, asyncFinally);
  });

  workflow.on('attemptLogin', function() {
    req._passport.instance.authenticate('local', function(err, user, info) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        var fieldsToSet = { ip: req.ip, user: req.body.username };
        req.app.db.models.LoginAttempt.create(fieldsToSet, function(err, doc) {
          if (err) {
            return workflow.emit('exception', err);
          }

          workflow.outcome.errors.push('Username and password combination not found or your account is inactive.');
          return workflow.emit('response');
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return workflow.emit('exception', err);
          }

          workflow.emit('response');
        });
      }
    })(req, res);
  });

  workflow.emit('validate');
};
/*
exports.loginTwitter = function(req, res, next){
  req._passport.instance.authenticate('twitter', function(err, user, info) {
    if (!info || !info.profile) {
      return res.redirect('/login/');
    }

    req.app.db.models.User.findOne({ 'twitter.id': info.profile.id }, function(err, user) {
      if (err) {
        return next(err);
      }

      if (!user) {
        res.render('login/index', {
          oauthMessage: 'No users found linked to your Twitter account. You may need to create an account first.',
          oauthTwitter: !!req.app.config.oauth.twitter.key,
          oauthGitHub: !!req.app.config.oauth.github.key,
          oauthFacebook: !!req.app.config.oauth.facebook.key,
          oauthGoogle: !!req.app.config.oauth.google.key,
          oauthTumblr: !!req.app.config.oauth.tumblr.key
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return next(err);
          }

          res.redirect(getReturnUrl(req));
        });
      }
    });
  })(req, res, next);
};

exports.loginGitHub = function(req, res, next){
  req._passport.instance.authenticate('github', function(err, user, info) {
    if (!info || !info.profile) {
      return res.redirect('/login/');
    }

    req.app.db.models.User.findOne({ 'github.id': info.profile.id }, function(err, user) {
      if (err) {
        return next(err);
      }

      if (!user) {
        res.render('login/index', {
          oauthMessage: 'No users found linked to your GitHub account. You may need to create an account first.',
          oauthTwitter: !!req.app.config.oauth.twitter.key,
          oauthGitHub: !!req.app.config.oauth.github.key,
          oauthFacebook: !!req.app.config.oauth.facebook.key,
          oauthGoogle: !!req.app.config.oauth.google.key,
          oauthTumblr: !!req.app.config.oauth.tumblr.key
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return next(err);
          }

          res.redirect(getReturnUrl(req));
        });
      }
    });
  })(req, res, next);
};

exports.loginFacebook = function(req, res, next){
  req._passport.instance.authenticate('facebook', { callbackURL: '/login/facebook/callback/' }, function(err, user, info) {
    if (!info || !info.profile) {
      return res.redirect('/login/');
    }

    req.app.db.models.User.findOne({ 'facebook.id': info.profile.id }, function(err, user) {
      if (err) {
        return next(err);
      }

      if (!user) {
        res.render('login/index', {
          oauthMessage: 'No users found linked to your Facebook account. You may need to create an account first.',
          oauthTwitter: !!req.app.config.oauth.twitter.key,
          oauthGitHub: !!req.app.config.oauth.github.key,
          oauthFacebook: !!req.app.config.oauth.facebook.key,
          oauthGoogle: !!req.app.config.oauth.google.key,
          oauthTumblr: !!req.app.config.oauth.tumblr.key
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return next(err);
          }

          res.redirect(getReturnUrl(req));
        });
      }
    });
  })(req, res, next);
};

exports.loginGoogle = function(req, res, next){
  req._passport.instance.authenticate('google', { callbackURL: '/login/google/callback/' }, function(err, user, info) {
    if (!info || !info.profile) {
      return res.redirect('/login/');
    }

    req.app.db.models.User.findOne({ 'google.id': info.profile.id }, function(err, user) {
      if (err) {
        return next(err);
      }

      if (!user) {
        res.render('login/index', {
          oauthMessage: 'No users found linked to your Google account. You may need to create an account first.',
          oauthTwitter: !!req.app.config.oauth.twitter.key,
          oauthGitHub: !!req.app.config.oauth.github.key,
          oauthFacebook: !!req.app.config.oauth.facebook.key,
          oauthGoogle: !!req.app.config.oauth.google.key,
          oauthTumblr: !!req.app.config.oauth.tumblr.key
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return next(err);
          }

          res.redirect(getReturnUrl(req));
        });
      }
    });
  })(req, res, next);
};

exports.loginTumblr = function(req, res, next){
  req._passport.instance.authenticate('tumblr', { callbackURL: '/login/tumblr/callback/' }, function(err, user, info) {
    if (!info || !info.profile) {
      return res.redirect('/login/');
    }

    if (!info.profile.hasOwnProperty('id')) {
      info.profile.id = info.profile.username;
    }

    req.app.db.models.User.findOne({ 'tumblr.id': info.profile.id }, function(err, user) {
      if (err) {
        return next(err);
      }

      if (!user) {
        res.render('login/index', {
          oauthMessage: 'No users found linked to your Tumblr account. You may need to create an account first.',
          oauthTwitter: !!req.app.config.oauth.twitter.key,
          oauthGitHub: !!req.app.config.oauth.github.key,
          oauthFacebook: !!req.app.config.oauth.facebook.key,
          oauthGoogle: !!req.app.config.oauth.google.key,
          oauthTumblr: !!req.app.config.oauth.tumblr.key
        });
      }
      else {
        req.login(user, function(err) {
          if (err) {
            return next(err);
          }

          res.redirect(getReturnUrl(req));
        });
      }
    });
  })(req, res, next);
};*/


text:
/*
 * radio-util
 * ----------
 * Utility methods for Backbone.Radio
 *
 */

var radioUtil = {

  // Generate a unique channel name from a collection or a model
  entityChannelName: function(entity) {
    return 'gistbook-' + entity.uniqueId;
  },

  // Get the channel from an entity
  entityChannel: function(entity) {
    return Radio.channel(radioUtil.entityChannelName(entity));
  }
};


text:
<?php

namespace Hal\Metrics\Mood\Abstractness;
use Hal\Component\Result\ExportableInterface;

/**
 * Represents abstractness
 *
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
 */
class Result implements ExportableInterface {

    /**
     * @var int
     */
    private $abstractness;

    /**
     * @inheritdoc
     */
    public function asArray()
    {
        return array(
            'abstractness' => $this->getAbstractness()
        );
    }

    /**
     * @param int $abstractness
     */
    public function setAbstractness($abstractness)
    {
        $this->abstractness = $abstractness;
    }

    /**
     * @return int
     */
    public function getAbstractness()
    {
        return $this->abstractness;
    }

}


text:
const logging = require('../../../../../shared/logging');
const config = require('../../../../../shared/config');
const {URL} = require('url');

module.exports.config = {
    transaction: true
};

// We've been incorrectly saving canonical_url fields without a subdirectory.
// We need this column to be consistent with all other relative URLs, so...

// if we have a configured url with a subdirectory
// find all posts that have a canonical_url starting with / but not //
// prefix the subdirectory to the canonical_url and save the post
module.exports.up = (options) => {
    // normalize config url to always have a trailing-slash
    let configUrl = config.get('url');
    if (!configUrl.endsWith('/')) {
        configUrl = `${configUrl}/`;
    }
    const url = new URL(configUrl);

    const localOptions = Object.assign({
        context: {internal: true}
    }, options);

    if (url.pathname === '/') {
        logging.info('Skipping posts.canonical_url subdirectory fix: no subdirectory configured');
        return Promise.resolve();
    }

    // perform a specific query for the type of canonical URLs we're looking for
    // so we're not fetching and manually looping over a ton of post models
    return localOptions
        .transacting('posts')
        .where('canonical_url', 'like', '/%')
        .whereNot('canonical_url', 'like', '//%')
        .select().then((posts) => {
            if (posts) {
                return Promise.mapSeries(posts, (post) => {
                    const canonicalUrl = post.canonical_url.replace('/', url.pathname);
                    return localOptions
                        .transacting('posts')
                        .where('id', '=', post.id)
                        .update({
                            canonical_url: canonicalUrl
                        });
                }).then(() => {
                    logging.info(`Added subdirectory prefix to canonical_url in ${posts.length} posts`);
                });
            }

            logging.info('Skipping posts.canonical_url subdirectory fix: no canonical_urls to fix');
            return Promise.resolve();
        });
};

// if we have a configured url with a subdirectory
// find all posts with a canonical_url starting with the subdirectory
// remove it and save the post
module.exports.down = (options) => {
    // normalize config url to always have a trailing-slash
    let configUrl = config.get('url');
    if (!configUrl.endsWith('/')) {
        configUrl = `${configUrl}/`;
    }
    const url = new URL(configUrl);

    const localOptions = Object.assign({
        context: {internal: true}
    }, options);

    if (url.pathname === '/') {
        logging.info('Skipping posts.canonical_url subdirectory fix: no subdirectory configured');
        return Promise.resolve();
    }

    return localOptions
        .transacting('posts')
        .where('canonical_url', 'like', `${url.pathname}%`)
        .select().then((posts) => {
            if (posts) {
                return Promise.mapSeries(posts, (post) => {
                    const canonicalUrl = post.canonical_url.replace(url.pathname, '/');
                    return localOptions
                        .transacting('posts')
                        .where('id', '=', post.id)
                        .update({
                            canonical_url: canonicalUrl
                        });
                }).then(() => {
                    logging.info(`Removed subdirectory prefix from canonical_url in ${posts.length} posts`);
                });
            }

            logging.info('Skipping posts.canonical_url subdirectory fix: no canonical_urls to fix');
            return Promise.resolve();
        });
};


text:
    <form ng-submit="setPage(currentPageView - 1)">
      <input type="text" class="paginate_input" ng-model="currentPageView">
      of {{goTos.length}}
    </form>


text:
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository\Exception;

class RedisConnectionException extends RuntimeException
{
}


text:
import { isPlainObject } from "lodash";
export = isPlainObject;


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using XDT.Domain.Repositories;
using XDT.Infrastructure;
using XDT.Model.Enums;
using Microsoft.Extensions.DependencyInjection;

namespace XDT.Domain.Model
{
    /// <summary>
    /// 商品
    /// </summary>
    public class WareItem : AggregateRoot
    {

        public WareItem(string url)
        {
            ListenUrl = url;
        }
        public WareItem() { }
        public BoxItem BoxItem { get; set; }
        /// <summary>
        /// 记录首次添加的人
        /// </summary>
        public User Operator { get; set; }
        public string ListenUrl { get; set; }
        public string ItemName { get; set; }
        public DateTime? FirstListenTime { get; set; }
        public DateTime? LastListenTime { get; set; }
        /// <summary>
        /// 商品类别
        /// </summary>
        public DictItemType ItemType { get; set; }
        public DictWareItemStatus Status { get; set; }
        public DictPriceTrend Trend { get; set; }
        /// <summary>
        /// 条目来源 比如:淘宝,天猫,京东自营,京东店铺,
        /// </summary>
        public DictWareItemSource ItemSource { get; set; }
        public string ItemImage { get; set; }
        public decimal CurrentPrice { get; set; }
        public DateTime CreateTime { get; set; }
        public string Description { get; set; }
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
                return true;
            if (obj == null)
                return false;
            WareItem other = obj as WareItem;
            if ((object)other == null)
                return false;
            return (this.ID == other.ID || this.ListenUrl == other.ListenUrl);
        }
        public override int GetHashCode()
        {
            return this.ID.GetHashCode();
        }
        public void Init()
        {
            //初始化数据
            var urlHost = XDT.Infrastructure.UrlHelper.GetDomainFromUrl(ListenUrl);
            var enumItemSource = Enum.Parse(typeof(DictWareItemSourcePy), urlHost, true);
            ItemSource = (urlHost == "" ? DictWareItemSource.未知 : (DictWareItemSource)((byte)enumItemSource));
            CreateTime = DateTime.Now;

        }
        public void InitItemType(string keyName = null)
        {
            if (!string.IsNullOrEmpty(keyName))
            {
                ItemType = GetItemTypeByName(keyName);
                return;
            }
            ItemType = GetItemTypeByName(this.ItemName);
        }
        /// <summary>
        ///     手机=0,
        //外设=1,
        //电脑=2,
        //外套=3,
        //裤子=4,
        //皮鞋=5,
        //运动鞋=6,
        //运动装=7
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        private DictItemType GetItemTypeByName(string keyName)
        {
            string regshouji = "手机";
            string regpixie = "皮鞋";
            string regwaishe = "(鼠标|键盘)";
            string regyundongxie = "运动鞋";
            string regkuzi = @"(运动|[\S]+)裤";
            string regyundongfu = "运动(服|装)";
            string regwaitao = "外套";
            if (Regex.IsMatch(keyName, regshouji))
            {
                return DictItemType.手机;
            }
            else if (Regex.IsMatch(keyName, regwaishe))
            {
                return DictItemType.外设;
            }
            else if (Regex.IsMatch(keyName, regpixie))
            {
                return DictItemType.皮鞋;
            }
            else if (Regex.IsMatch(keyName, regyundongxie))
            {
                return DictItemType.运动鞋;
            }
            else if (Regex.IsMatch(keyName, regkuzi))
            {
                return DictItemType.裤子;
            }
            else if (Regex.IsMatch(keyName, regyundongfu))
            {
                return DictItemType.运动装;
            }
            else if (Regex.IsMatch(keyName, regwaitao))
            {
                return DictItemType.外套;
            }
            else return DictItemType.其他;
        }
        public BoxItem CreateBoxItem(long userId)
        {
            var ppboxItem = new BoxItem();
            var _ppBoxRepository = ServiceLocator.Instance.GetService<IBoxRepository>();
            ppboxItem.Box = _ppBoxRepository.GetByExpression(x => x.User.ID == userId);
            ppboxItem.WareItem = this;
            ppboxItem.CreateTime = DateTime.Now;
            return ppboxItem;
        }
        public UrlHistoryItem CreateHistoryUrl()
        {
            var historyUrl = new UrlHistoryItem()
            {
                WareItem = this,
                UpdateTime = DateTime.Now,
                Url = this.ListenUrl
            };
            return historyUrl;
        }
    }
}


text:
<?php
namespace UNAH\SGOBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use UNAH\SGOBundle\Entity\Coordinacion;
use UNAH\SGOBundle\Entity\TipoSolicitud;

class LoadCoordinacionData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {

        $coordinaciones = array(
            1 => array(
                'nombre' => 'Coordinación de Gestión Académica',
                'solicitudes' => array(
                    'Agregados',
                    'Asunto  legal',
                    'Asuntos Administrativos',
                    'Cambio de Carrera',
                    'Cancelación Excepcional de Asignaturas',
                    'Casos Sujetos a Investigación',
                    'Certificación de Calificaciones',
                    'Equivalencias Automáticas',
                    'Errores de Programación y Cambios de Programación',
                    'Estudiantes  que no Logran Ingresar a la UNAH con la PAA',
                    'Examen Opcional de Suficiencia',
                    'Habilitación de  Cuenta',
                    'Ingreso a la UNAH',
                    'Inscripción de Asignaturas',
                    'Inscripción de Calificaciones',
                    'Matrícula Condicionada',
                    'Pago de Matrícula y/o Laboratorio',
                    'Problemas  para Entregar Título de Educación Media',
                    'Problemas en Historiales Académicos y Planes de Estudios',
                    'Problemas relacionados con la matrícula de asignaturas',
                    'Rectificación de Calificaciones',
                    'Segunda Carrera',
                    'Solicitud de Reingreso a la UNAH',
                    'Solicitudes Postgrados',
                    'Tramites Académicos',
                    'Trámites de Práctica Profesional, Graduación, y Títulos',
                    'Traslape de Clase con laboratorios',
                    'Varios',
                )
            )
        );

        $colores = ColorGenerator::generateUniqueHexColors(count($coordinaciones) + 1);

        foreach ($coordinaciones as $i => $coordinacion) {
            $entity = new Coordinacion();
            $entity->setNombre($coordinacion['nombre']);
            $entity->setColor($colores[$i]);
            $sol_color = ColorGenerator::generateUniqueHexColors(count($coordinacion['solicitudes']));
            $manager->persist($entity);
            foreach($coordinacion['solicitudes'] as $j => $nombre)
            {
                $solicitud = new TipoSolicitud();
                $solicitud->setNombre($nombre);
                $solicitud->setColor($sol_color[$j]);
                $manager->persist($solicitud);
            }
        }

        $manager->flush();
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 3; // the order in which fixtures will be loaded
    }
}


text:
import tensorflow as tf

# Start tf session
sess = tf.Session()

a = tf.constant(2)
b = tf.constant(3)

c = a + b

# Print out operation everything is operation
print(a)
print(b)
print(c)

print(a + b)

# Print out the result of operation
print(sess.run(a))
print(sess.run(b))
print(sess.run(c))
print(sess.run(a + b))


text:
var cdb = require('cartodb.js');
var TablesCollection = require('../../../../data/tables-collection');
var AnalysisSourceOptionsModel = require('../analyses-form-types/analysis-source-options-model');
var AnalysisFormTypeView = require('../analyses-form-types/analysis-form-type-view');
var AnalysisControlsView = require('./analysis-controls-view');

var ANALYSIS_FORM_MODELS = {
  buffer: require('../analyses-form-types/area-of-influence-form-model'),
  'trade-area': require('../analyses-form-types/area-of-influence-form-model'),
  'point-in-polygon': require('../analyses-form-types/analysis-point-in-polygon-form-model')
};

module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    if (!opts.layerDefinitionModel) throw new Error('Layer definition is required');
    if (!opts.viewModel) throw new Error('viewModel is required');

    this._layerDefinitionModel = opts.layerDefinitionModel;
    this._viewModel = opts.viewModel;

    this._analysisSourceOptionsModel = new AnalysisSourceOptionsModel(null, {
      analysisDefinitionNodesCollection: this._analysisDefinitionNodeModel().collection,
      layerDefinitionsCollection: opts.layerDefinitionModel.collection,
      tablesCollection: new TablesCollection(null, {
        configModel: opts.layerDefinitionModel._configModel
      })
    });

    this._viewModel.bind('change:selectedNode', this.render, this);
    this.add_related_model(this._viewModel);
  },

  render: function () {
    this.clearSubViews();

    var nodeDefModel = this._analysisDefinitionNodeModel();
    var FormModel = ANALYSIS_FORM_MODELS[nodeDefModel.get('type')];

    var formModel = new FormModel(nodeDefModel.attributes, {
      analysisSourceOptionsModel: this._analysisSourceOptionsModel,
      layerDefinitionModel: this._layerDefinitionModel,
      parse: true
    });
    this.add_related_model(formModel);

    this._renderFormTypeView(formModel);
    this._renderControlsView(formModel);

    return this;
  },

  _renderFormTypeView: function (formModel) {
    var formView = new AnalysisFormTypeView({
      formModel: formModel,
      layerDefinitionModel: this._layerDefinitionModel
    });

    this.addView(formView);
    this.$el.append(formView.render().el);
  },

  _renderControlsView: function (formModel) {
    var view = new AnalysisControlsView({
      formModel: formModel,
      analysisDefinitionNodeModel: this._analysisDefinitionNodeModel()
    });
    this.addView(view);
    this.$el.append(view.render().el);
  },

  _analysisDefinitionNodeModel: function () {
    return this._viewModel.get('selectedNode');
  }

});


text:
import jwt
import bcrypt

from gargantua.settings import SECRET_KEY

def generate_passwd(passwd):
    return bcrypt.hashpw(passwd.encode('utf8'), bcrypt.gensalt(len(passwd))).decode('utf8')

def validate_passwd(passwd, hashed):
    return bcrypt.hashpw(passwd.encode('utf8'), hashed.encode('utf8')) == hashed.encode('utf8')

def generate_token(json_, secret=SECRET_KEY):
    return jwt.encode(json_, secret, algorithm='HS512').decode()

def validate_token(token, secret=SECRET_KEY):
    return decode_token(token, secret=secret) is not None

def decode_token(token, secret=SECRET_KEY):
    """
    JWT is dangerous: https://paragonie.com/blog/2017/03/jwt-json-web-tokens-is-bad-standard-that-everyone-should-avoid
    """
    try:
        return jwt.decode(token, secret, algorithms=['HS512', 'HS256'])
    except (jwt.InvalidAlgorithmError, jwt.DecodeError):
        raise


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.WebJobs
{
    /// <summary>
    /// Defines an asynchronous collector (an insert-only collection).
    /// </summary>
    /// <typeparam name="T">The type of items to collect.</typeparam>
    public interface IAsyncCollector<in T>
    {
        /// <summary>
        /// Adds an item to the <see cref="IAsyncCollector{T}"/>.
        /// </summary>
        /// <param name="item">The item to be added.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task that will add the item to the collector.</returns>
        Task AddAsync(T item, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
var path            = require("path");
var express         = require("express");
var mongoose        = require("mongoose");
var bodyParser      = require("body-parser");
var sassMiddleware  = require('node-sass-middleware');

var oneDay = 86400000;

var CONFIG = require('./config/config');

var app = express();

app.use(bodyParser());

app.use(function(req, res, next) {
  res.setHeader("Cache-Control", "public, max-age=3600");
  return next();
});

app.use(express.static(__dirname + '/src'));

app.use(express.static(__dirname + '/public'));

app.get(/^(?!api).*/, function(req, res) {
  res.sendFile(path.join(__dirname, './src/index.html'));
});

app.listen(CONFIG.PORT, CONFIG.HOST, function(err, res) {
  if(err) {
    console.log("Problem while starting the server!!!")
    console.log(err);
  }

  console.log('\nListening at http://'+CONFIG.HOST+':'+CONFIG.PORT+'\n');
});


text:
'use strict'

/*!
 * imports.
 */

var test = require('tape-catch')

/*!
 * imports (local).
 */

var <%= S.camelize(package_name) %> = require('./')

/*!
 * parameters.
 */

var parameters = [
  { name: 'default-test', args: ['training'], expected: 'training' }
]

/*!
 * tests.
 */

test('<%= S.camelize(package_name) %>()', function (t) {
  t.plan(parameters.length)

  parameters.forEach(function (p) {
    var actual = <%= S.camelize(package_name) %>.apply(null, p.args)
    t.equal(actual, p.expected, p.name)
  })
})


text:
import expect from 'expect';
import deepFreeze from 'deep-freeze';
import selectedArticle from '../../reducers/selectedArticle';
import {
  SELECT_ARTICLE
} from '../../constants/actionTypes';

describe('selectedArticle reducer', () => {
  it('should handle initial state', () => {
    const oldState = undefined;
    const action = {
      type: undefined
    };
    deepFreeze(action);
    const newState = {
      id: null,
      headline: null,
      byline: null,
      leadParagraph: null,
      body: null
    };
    expect(
      selectedArticle(oldState, action)
    ).toEqual(newState);
  });

  it('should handle selecting an article', () => {
    const oldState = {
      id: null,
      headline: null,
      byline: null,
      leadParagraph: null,
      body: null
    };
    const action = {
      type: SELECT_ARTICLE,
      id: "1",
      headline: "Frontend ReactJS Blog Tutorial",
      byline: "Oliver Forral",
      leadParagraph: "Write a frontend blog client using ReactJS!",
      body: "Step 1: Write a frontend blog client using ReactJS.  Step 2: ???  Step 3: Profit!!!"
    };
    deepFreeze(oldState);
    deepFreeze(action);
    const newState = {
      id: "1",
      headline: "Frontend ReactJS Blog Tutorial",
      byline: "Oliver Forral",
      leadParagraph: "Write a frontend blog client using ReactJS!",
      body: "Step 1: Write a frontend blog client using ReactJS.  Step 2: ???  Step 3: Profit!!!"
    };
    expect(
      selectedArticle(oldState, action)
    ).toEqual(newState);
  });
});


text:
NSString *const kMyClassName = @"name";

@interface MyClass ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation MyClass

+ (MyClass *)modelWithDictionary:(NSDictionary *)dict {
    if (!dict) return nil;
    MyClass *instance = [[MyClass alloc] initWithDictionary:dict];
    return instance;
}

+ (MyClass *)modelWithString:(NSString *)json {
    if (!json) return nil;
    MyClass *instance = [[MyClass alloc] initWithString:json];
    return instance;
}

- (instancetype)initWithString:(NSString *)json {
    self = [super init];

    if (![[json stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] hasPrefix:@"{"])
        json = [NSString stringWithFormat:@"{ \"%@\" : %@ }", kMyClassName, json];

    NSError *jsonError = nil;
    NSData *objectData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&jsonError];
    if (!jsonError)
        self = [self initWithDictionary:dict];

    return self;
}

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    self = [super init];

    if (self && [dict isKindOfClass:[NSDictionary class]]) {
        self.name = [self objectOrNilForKey:kMyClassName fromDictionary:dict];
    }
    return self;
}

- (NSDictionary *)dictionaryRepresentation {
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];

    [mutableDict setValue:self.name forKey:kMyClassName];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict {
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];

    self.name = [aDecoder decodeObjectForKey:kMyClassName];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_name forKey:kMyClassName];
}

- (id)copyWithZone:(NSZone *)zone {
    MyClass *copy = [[MyClass alloc] init];
    if (copy) {
        copy.name = [self.name copyWithZone:zone];
    }

    return copy;
}

@end


text:
<?php namespace Exolnet\Foreigner;

use Config;
use Exception;
use Httpful\Request;
use Httpful\Response;
use Illuminate\Support\Str;

class Foreigner
{
	/**
	 * Foreigner constructor.
	 */
	public function __construct()
	{
		$this->shouldBeConfigured();
	}

	/**
	 * @return string
	 */
	public function getServiceUrl()
	{
		return rtrim(env('FOREIGNER_URL', 'https://foreigner.exolnet.com'), '/');
	}

	/**
	 * @return string|null
	 */
	public function getProjectName()
	{
		return Config::get('app.name');
	}

	/**
	 * @return string
	 */
	public function getProjectIdentifier()
	{
		return Str::slug($this->getProjectName());
	}

	/**
	 * @return array
	 */
	public function getSupportedLocales()
	{
		if (Config::has('app.supported_locales')) {
			return Config::get('app.supported_locales');
		}

		return [Config::get('app.locale')];
	}

	/**
	 * @param array $translations
	 * @return $this
	 * @throws \Exception
	 */
	public function push(array $translations)
	{
		$project = [
			'name'         => $this->getProjectName(),
			'identifier'   => $this->getProjectIdentifier(),
			'locales'      => $this->getSupportedLocales(),
			'translations' => $translations,
		];

		$data = json_encode($project);

		try {
			$response = Request::put($this->getServiceUrl() . '/projects/push', $data, 'application/json')
				->addHeader('User-Agent', 'eXolnet Laravel Foreigner/1.0')
				->expects('json')
				->send();

			if ($response->hasErrors()) {
				$this->responseToException($response);
			}
		} catch (Exception $e) {
			if ($e->getMessage() === 'Unable to parse response as JSON') {
				throw new ForeignerException('[Foreigner Service Error] '. $e->getMessage());
			}

			throw $e;
		}

		return $this;
	}

	/**
	 * @return array
	 */
	public function pull()
	{
		return [];
	}

	/**
	 * @param \Httpful\Response $response
	 */
	private function responseToException(Response $response)
	{
		if (is_array($response->body)) {
			$message = implode(PHP_EOL, '[Foreigner Service Error] '.$response->body);

			throw new ForeignerException($message);
		}

		if (is_string($response->body)) {
			throw new ForeignerException('[Foreigner Service Error] '.$response->body);
		}

		throw new ForeignerException('[Foreigner Service Error] Unknown error (code '. $response->code .')');
	}

	/**
	 * @return $this
	 * @throws \Exolnet\Foreigner\ForeignerException
	 */
	private function shouldBeConfigured()
	{
		if ( ! $this->getServiceUrl()) {
			throw new ForeignerException('Foreigner needs to be configured to be used. No service URL found.');
		}

		if ( ! $this->getProjectName()) {
			throw new ForeignerException('Foreigner needs to be configured to be used. No project name found.');
		}

		return $this;
	}
}


text:
import * as v1 from './v1';
import * as v1p1beta1 from './v1p1beta1';
import * as v1p2beta1 from './v1p2beta1';
import * as v1p3beta1 from './v1p3beta1';
import * as v1p4beta1 from './v1p4beta1';
import * as helpers from './helpers';
Object.assign(v1.ImageAnnotatorClient.prototype, helpers.call('v1'));
Object.assign(
  v1p1beta1.ImageAnnotatorClient.prototype,
  helpers.call('v1p1beta1')
);
Object.assign(
  v1p2beta1.ImageAnnotatorClient.prototype,
  helpers.call('v1p2beta1')
);
Object.assign(
  v1p3beta1.ImageAnnotatorClient.prototype,
  helpers.call('v1p3beta1')
);
Object.assign(
  v1p4beta1.ImageAnnotatorClient.prototype,
  helpers.call('v1p4beta1')
);
const ImageAnnotatorClient = v1.ImageAnnotatorClient;
type ImageAnnotatorClient = v1.ImageAnnotatorClient;
const ProductSearchClient = v1.ProductSearchClient;
type ProductSearchClient = v1.ProductSearchClient;
export {
  v1,
  v1p1beta1,
  v1p2beta1,
  v1p3beta1,
  v1p4beta1,
  ImageAnnotatorClient,
  ProductSearchClient,
};
// For compatibility with JavaScript libraries we need to provide this default export:
// tslint:disable-next-line no-default-export
export default {
  v1,
  v1p1beta1,
  v1p2beta1,
  v1p3beta1,
  v1p4beta1,
  ImageAnnotatorClient,
  ProductSearchClient,
};
import * as protos from '../protos/protos';
export {protos};


text:
package fr.acinq.eclair.channel

import fr.acinq.bitcoin.scalacompat.Crypto.PublicKey
import fr.acinq.bitcoin.scalacompat.{Block, ByteVector32, ByteVector64, DeterministicWallet, Satoshi, SatoshiLong, Transaction}
import fr.acinq.eclair.blockchain.fee._
import fr.acinq.eclair.channel.Commitments._
import fr.acinq.eclair.channel.Helpers.Funding
import fr.acinq.eclair.channel.states.ChannelStateTestsBase
import fr.acinq.eclair.crypto.ShaChain
import fr.acinq.eclair.crypto.keymanager.LocalChannelKeyManager
import fr.acinq.eclair.transactions.CommitmentSpec
import fr.acinq.eclair.transactions.Transactions.CommitTx
import fr.acinq.eclair.wire.protocol.{IncorrectOrUnknownPaymentDetails, UpdateAddHtlc}
import fr.acinq.eclair.{TestKitBaseClass, _}
import org.scalatest.funsuite.FixtureAnyFunSuiteLike
import org.scalatest.{Outcome, Tag}
import scodec.bits.ByteVector

import scala.concurrent.duration._
import scala.util.Random

class CommitmentsSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with ChannelStateTestsBase {

  type FixtureParam = SetupFixture

  implicit val log: akka.event.LoggingAdapter = akka.event.NoLogging

  val feeConfNoMismatch = OnChainFeeConf(
    FeeTargets(6, 2, 12, 2, 6, 1),
    new TestFeeEstimator(),
    spendAnchorWithoutHtlcs = true,
    closeOnOfflineMismatch = false,
    1.0,
    FeerateTolerance(0.00001, 100000.0, TestConstants.anchorOutputsFeeratePerKw, DustTolerance(100000 sat, closeOnUpdateFeeOverflow = false)),
    Map.empty
  )

  override def withFixture(test: OneArgTest): Outcome = {
    val setup = init()
    import setup._
    within(30 seconds) {
      reachNormal(setup, test.tags)
      awaitCond(alice.stateName == NORMAL)
      awaitCond(bob.stateName == NORMAL)
      withFixture(test.toNoArgTest(setup))
    }
  }

  test("correct values for availableForSend/availableForReceive (success case)") { f =>
    import f._

    val a = 758640000 msat // initial balance alice
    val b = 190000000 msat // initial balance bob
    val p = 42000000 msat // a->b payment
    val htlcOutputFee = 2 * 1720000 msat // fee due to the additional htlc output; we count it twice because we keep a reserve for a x2 feerate increase
    val maxDustExposure = 500000 sat

    val ac0 = alice.stateData.asInstanceOf[DATA_NORMAL].commitments
    val bc0 = bob.stateData.asInstanceOf[DATA_NORMAL].commitments

    assert(ac0.availableBalanceForSend > p) // alice can afford the payment
    assert(ac0.availableBalanceForSend == a)
    assert(ac0.availableBalanceForReceive == b)
    assert(bc0.availableBalanceForSend == b)
    assert(bc0.availableBalanceForReceive == a)

    val (payment_preimage, cmdAdd) = makeCmdAdd(p, bob.underlyingActor.nodeParams.nodeId, currentBlockHeight)
    val Right((ac1, add)) = sendAdd(ac0, cmdAdd, currentBlockHeight, alice.underlyingActor.nodeParams.onChainFeeConf)
    assert(ac1.availableBalanceForSend == a - p - htlcOutputFee) // as soon as htlc is sent, alice sees its balance decrease (more than the payment amount because of the commitment fees)
    assert(ac1.availableBalanceForReceive == b)

    val Right(bc1) = receiveAdd(bc0, add, bob.underlyingActor.nodeParams.onChainFeeConf)
    assert(bc1.availableBalanceForSend == b)
    assert(bc1.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac2, commit1)) = sendCommit(ac1, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac2.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac2.availableBalanceForReceive == b)

    val Right((bc2, revocation1)) = receiveCommit(bc1, commit1, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc2.availableBalanceForSend == b)
    assert(bc2.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac3, _)) = receiveRevocation(ac2, revocation1, maxDustExposure)
    assert(ac3.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac3.availableBalanceForReceive == b)

    val Right((bc3, commit2)) = sendCommit(bc2, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc3.availableBalanceForSend == b)
    assert(bc3.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac4, revocation2)) = receiveCommit(ac3, commit2, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac4.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac4.availableBalanceForReceive == b)

    val Right((bc4, _)) = receiveRevocation(bc3, revocation2, maxDustExposure)
    assert(bc4.availableBalanceForSend == b)
    assert(bc4.availableBalanceForReceive == a - p - htlcOutputFee)

    val cmdFulfill = CMD_FULFILL_HTLC(0, payment_preimage)
    val Right((bc5, fulfill)) = sendFulfill(bc4, cmdFulfill)
    assert(bc5.availableBalanceForSend == b + p) // as soon as we have the fulfill, the balance increases
    assert(bc5.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac5, _, _)) = receiveFulfill(ac4, fulfill)
    assert(ac5.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac5.availableBalanceForReceive == b + p)

    val Right((bc6, commit3)) = sendCommit(bc5, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc6.availableBalanceForSend == b + p)
    assert(bc6.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac6, revocation3)) = receiveCommit(ac5, commit3, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac6.availableBalanceForSend == a - p)
    assert(ac6.availableBalanceForReceive == b + p)

    val Right((bc7, _)) = receiveRevocation(bc6, revocation3, maxDustExposure)
    assert(bc7.availableBalanceForSend == b + p)
    assert(bc7.availableBalanceForReceive == a - p)

    val Right((ac7, commit4)) = sendCommit(ac6, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac7.availableBalanceForSend == a - p)
    assert(ac7.availableBalanceForReceive == b + p)

    val Right((bc8, revocation4)) = receiveCommit(bc7, commit4, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc8.availableBalanceForSend == b + p)
    assert(bc8.availableBalanceForReceive == a - p)

    val Right((ac8, _)) = receiveRevocation(ac7, revocation4, maxDustExposure)
    assert(ac8.availableBalanceForSend == a - p)
    assert(ac8.availableBalanceForReceive == b + p)
  }

  test("correct values for availableForSend/availableForReceive (failure case)") { f =>
    import f._

    val a = 758640000 msat // initial balance alice
    val b = 190000000 msat // initial balance bob
    val p = 42000000 msat // a->b payment
    val htlcOutputFee = 2 * 1720000 msat // fee due to the additional htlc output; we count it twice because we keep a reserve for a x2 feerate increase
    val maxDustExposure = 500000 sat

    val ac0 = alice.stateData.asInstanceOf[DATA_NORMAL].commitments
    val bc0 = bob.stateData.asInstanceOf[DATA_NORMAL].commitments

    assert(ac0.availableBalanceForSend > p) // alice can afford the payment
    assert(ac0.availableBalanceForSend == a)
    assert(ac0.availableBalanceForReceive == b)
    assert(bc0.availableBalanceForSend == b)
    assert(bc0.availableBalanceForReceive == a)

    val (_, cmdAdd) = makeCmdAdd(p, bob.underlyingActor.nodeParams.nodeId, currentBlockHeight)
    val Right((ac1, add)) = sendAdd(ac0, cmdAdd, currentBlockHeight, alice.underlyingActor.nodeParams.onChainFeeConf)
    assert(ac1.availableBalanceForSend == a - p - htlcOutputFee) // as soon as htlc is sent, alice sees its balance decrease (more than the payment amount because of the commitment fees)
    assert(ac1.availableBalanceForReceive == b)

    val Right(bc1) = receiveAdd(bc0, add, bob.underlyingActor.nodeParams.onChainFeeConf)
    assert(bc1.availableBalanceForSend == b)
    assert(bc1.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac2, commit1)) = sendCommit(ac1, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac2.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac2.availableBalanceForReceive == b)

    val Right((bc2, revocation1)) = receiveCommit(bc1, commit1, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc2.availableBalanceForSend == b)
    assert(bc2.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac3, _)) = receiveRevocation(ac2, revocation1, maxDustExposure)
    assert(ac3.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac3.availableBalanceForReceive == b)

    val Right((bc3, commit2)) = sendCommit(bc2, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc3.availableBalanceForSend == b)
    assert(bc3.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac4, revocation2)) = receiveCommit(ac3, commit2, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac4.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac4.availableBalanceForReceive == b)

    val Right((bc4, _)) = receiveRevocation(bc3, revocation2, maxDustExposure)
    assert(bc4.availableBalanceForSend == b)
    assert(bc4.availableBalanceForReceive == a - p - htlcOutputFee)

    val cmdFail = CMD_FAIL_HTLC(0, Right(IncorrectOrUnknownPaymentDetails(p, BlockHeight(42))))
    val Right((bc5, fail)) = sendFail(bc4, cmdFail, bob.underlyingActor.nodeParams.privateKey)
    assert(bc5.availableBalanceForSend == b)
    assert(bc5.availableBalanceForReceive == a - p - htlcOutputFee) // a's balance won't return to previous before she acknowledges the fail

    val Right((ac5, _, _)) = receiveFail(ac4, fail)
    assert(ac5.availableBalanceForSend == a - p - htlcOutputFee)
    assert(ac5.availableBalanceForReceive == b)

    val Right((bc6, commit3)) = sendCommit(bc5, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc6.availableBalanceForSend == b)
    assert(bc6.availableBalanceForReceive == a - p - htlcOutputFee)

    val Right((ac6, revocation3)) = receiveCommit(ac5, commit3, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac6.availableBalanceForSend == a)
    assert(ac6.availableBalanceForReceive == b)

    val Right((bc7, _)) = receiveRevocation(bc6, revocation3, maxDustExposure)
    assert(bc7.availableBalanceForSend == b)
    assert(bc7.availableBalanceForReceive == a)

    val Right((ac7, commit4)) = sendCommit(ac6, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac7.availableBalanceForSend == a)
    assert(ac7.availableBalanceForReceive == b)

    val Right((bc8, revocation4)) = receiveCommit(bc7, commit4, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc8.availableBalanceForSend == b)
    assert(bc8.availableBalanceForReceive == a)

    val Right((ac8, _)) = receiveRevocation(ac7, revocation4, maxDustExposure)
    assert(ac8.availableBalanceForSend == a)
    assert(ac8.availableBalanceForReceive == b)
  }

  test("correct values for availableForSend/availableForReceive (multiple htlcs)") { f =>
    import f._

    val a = 758640000 msat // initial balance alice
    val b = 190000000 msat // initial balance bob
    val p1 = 18000000 msat // a->b payment
    val p2 = 20000000 msat // a->b payment
    val p3 = 40000000 msat // b->a payment
    val htlcOutputFee = 2 * 1720000 msat // fee due to the additional htlc output; we count it twice because we keep a reserve for a x2 feerate increase
    val maxDustExposure = 500000 sat

    val ac0 = alice.stateData.asInstanceOf[DATA_NORMAL].commitments
    val bc0 = bob.stateData.asInstanceOf[DATA_NORMAL].commitments

    assert(ac0.availableBalanceForSend > (p1 + p2)) // alice can afford the payments
    assert(bc0.availableBalanceForSend > p3) // bob can afford the payment
    assert(ac0.availableBalanceForSend == a)
    assert(ac0.availableBalanceForReceive == b)
    assert(bc0.availableBalanceForSend == b)
    assert(bc0.availableBalanceForReceive == a)

    val (payment_preimage1, cmdAdd1) = makeCmdAdd(p1, bob.underlyingActor.nodeParams.nodeId, currentBlockHeight)
    val Right((ac1, add1)) = sendAdd(ac0, cmdAdd1, currentBlockHeight, alice.underlyingActor.nodeParams.onChainFeeConf)
    assert(ac1.availableBalanceForSend == a - p1 - htlcOutputFee) // as soon as htlc is sent, alice sees its balance decrease (more than the payment amount because of the commitment fees)
    assert(ac1.availableBalanceForReceive == b)

    val (_, cmdAdd2) = makeCmdAdd(p2, bob.underlyingActor.nodeParams.nodeId, currentBlockHeight)
    val Right((ac2, add2)) = sendAdd(ac1, cmdAdd2, currentBlockHeight, alice.underlyingActor.nodeParams.onChainFeeConf)
    assert(ac2.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee) // as soon as htlc is sent, alice sees its balance decrease (more than the payment amount because of the commitment fees)
    assert(ac2.availableBalanceForReceive == b)

    val (payment_preimage3, cmdAdd3) = makeCmdAdd(p3, alice.underlyingActor.nodeParams.nodeId, currentBlockHeight)
    val Right((bc1, add3)) = sendAdd(bc0, cmdAdd3, currentBlockHeight, bob.underlyingActor.nodeParams.onChainFeeConf)
    assert(bc1.availableBalanceForSend == b - p3) // bob doesn't pay the fee
    assert(bc1.availableBalanceForReceive == a)

    val Right(bc2) = receiveAdd(bc1, add1, bob.underlyingActor.nodeParams.onChainFeeConf)
    assert(bc2.availableBalanceForSend == b - p3)
    assert(bc2.availableBalanceForReceive == a - p1 - htlcOutputFee)

    val Right(bc3) = receiveAdd(bc2, add2, bob.underlyingActor.nodeParams.onChainFeeConf)
    assert(bc3.availableBalanceForSend == b - p3)
    assert(bc3.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee)

    val Right(ac3) = receiveAdd(ac2, add3, alice.underlyingActor.nodeParams.onChainFeeConf)
    assert(ac3.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee)
    assert(ac3.availableBalanceForReceive == b - p3)

    val Right((ac4, commit1)) = sendCommit(ac3, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac4.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee)
    assert(ac4.availableBalanceForReceive == b - p3)

    val Right((bc4, revocation1)) = receiveCommit(bc3, commit1, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc4.availableBalanceForSend == b - p3)
    assert(bc4.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee)

    val Right((ac5, _)) = receiveRevocation(ac4, revocation1, maxDustExposure)
    assert(ac5.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee)
    assert(ac5.availableBalanceForReceive == b - p3)

    val Right((bc5, commit2)) = sendCommit(bc4, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc5.availableBalanceForSend == b - p3)
    assert(bc5.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee)

    val Right((ac6, revocation2)) = receiveCommit(ac5, commit2, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac6.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee) // alice has acknowledged b's hltc so it needs to pay the fee for it
    assert(ac6.availableBalanceForReceive == b - p3)

    val Right((bc6, _)) = receiveRevocation(bc5, revocation2, maxDustExposure)
    assert(bc6.availableBalanceForSend == b - p3)
    assert(bc6.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee)

    val Right((ac7, commit3)) = sendCommit(ac6, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac7.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee)
    assert(ac7.availableBalanceForReceive == b - p3)

    val Right((bc7, revocation3)) = receiveCommit(bc6, commit3, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc7.availableBalanceForSend == b - p3)
    assert(bc7.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee)

    val Right((ac8, _)) = receiveRevocation(ac7, revocation3, maxDustExposure)
    assert(ac8.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee)
    assert(ac8.availableBalanceForReceive == b - p3)

    val cmdFulfill1 = CMD_FULFILL_HTLC(0, payment_preimage1)
    val Right((bc8, fulfill1)) = sendFulfill(bc7, cmdFulfill1)
    assert(bc8.availableBalanceForSend == b + p1 - p3) // as soon as we have the fulfill, the balance increases
    assert(bc8.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee)

    val cmdFail2 = CMD_FAIL_HTLC(1, Right(IncorrectOrUnknownPaymentDetails(p2, BlockHeight(42))))
    val Right((bc9, fail2)) = sendFail(bc8, cmdFail2, bob.underlyingActor.nodeParams.privateKey)
    assert(bc9.availableBalanceForSend == b + p1 - p3)
    assert(bc9.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee - htlcOutputFee) // a's balance won't return to previous before she acknowledges the fail

    val cmdFulfill3 = CMD_FULFILL_HTLC(0, payment_preimage3)
    val Right((ac9, fulfill3)) = sendFulfill(ac8, cmdFulfill3)
    assert(ac9.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3) // as soon as we have the fulfill, the balance increases
    assert(ac9.availableBalanceForReceive == b - p3)

    val Right((ac10, _, _)) = receiveFulfill(ac9, fulfill1)
    assert(ac10.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)
    assert(ac10.availableBalanceForReceive == b + p1 - p3)

    val Right((ac11, _, _)) = receiveFail(ac10, fail2)
    assert(ac11.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)
    assert(ac11.availableBalanceForReceive == b + p1 - p3)

    val Right((bc10, _, _)) = receiveFulfill(bc9, fulfill3)
    assert(bc10.availableBalanceForSend == b + p1 - p3)
    assert(bc10.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3) // the fee for p3 disappears

    val Right((ac12, commit4)) = sendCommit(ac11, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac12.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)
    assert(ac12.availableBalanceForReceive == b + p1 - p3)

    val Right((bc11, revocation4)) = receiveCommit(bc10, commit4, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc11.availableBalanceForSend == b + p1 - p3)
    assert(bc11.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)

    val Right((ac13, _)) = receiveRevocation(ac12, revocation4, maxDustExposure)
    assert(ac13.availableBalanceForSend == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)
    assert(ac13.availableBalanceForReceive == b + p1 - p3)

    val Right((bc12, commit5)) = sendCommit(bc11, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc12.availableBalanceForSend == b + p1 - p3)
    assert(bc12.availableBalanceForReceive == a - p1 - htlcOutputFee - p2 - htlcOutputFee + p3)

    val Right((ac14, revocation5)) = receiveCommit(ac13, commit5, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac14.availableBalanceForSend == a - p1 + p3)
    assert(ac14.availableBalanceForReceive == b + p1 - p3)

    val Right((bc13, _)) = receiveRevocation(bc12, revocation5, maxDustExposure)
    assert(bc13.availableBalanceForSend == b + p1 - p3)
    assert(bc13.availableBalanceForReceive == a - p1 + p3)

    val Right((ac15, commit6)) = sendCommit(ac14, alice.underlyingActor.nodeParams.channelKeyManager)
    assert(ac15.availableBalanceForSend == a - p1 + p3)
    assert(ac15.availableBalanceForReceive == b + p1 - p3)

    val Right((bc14, revocation6)) = receiveCommit(bc13, commit6, bob.underlyingActor.nodeParams.channelKeyManager)
    assert(bc14.availableBalanceForSend == b + p1 - p3)
    assert(bc14.availableBalanceForReceive == a - p1 + p3)

    val Right((ac16, _)) = receiveRevocation(ac15, revocation6, maxDustExposure)
    assert(ac16.availableBalanceForSend == a - p1 + p3)
    assert(ac16.availableBalanceForReceive == b + p1 - p3)
  }

  // See https://github.com/lightningnetwork/lightning-rfc/issues/728
  test("funder keeps additional reserve to avoid channel being stuck") { f =>
    val isInitiator = true
    val c = CommitmentsSpec.makeCommitments(100000000 msat, 50000000 msat, FeeratePerKw(2500 sat), 546 sat, isInitiator)
    val (_, cmdAdd) = makeCmdAdd(c.availableBalanceForSend, randomKey().publicKey, f.currentBlockHeight)
    val Right((c1, _)) = sendAdd(c, cmdAdd, f.currentBlockHeight, feeConfNoMismatch)
    assert(c1.availableBalanceForSend == 0.msat)

    // We should be able to handle a fee increase.
    val Right((c2, _)) = sendFee(c1, CMD_UPDATE_FEE(FeeratePerKw(3000 sat)), feeConfNoMismatch)

    // Now we shouldn't be able to send until we receive enough to handle the updated commit tx fee (even trimmed HTLCs shouldn't be sent).
    val (_, cmdAdd1) = makeCmdAdd(100 msat, randomKey().publicKey, f.currentBlockHeight)
    val Left(_: InsufficientFunds) = sendAdd(c2, cmdAdd1, f.currentBlockHeight, feeConfNoMismatch)
  }

  test("can send availableForSend") { f =>
    for (isInitiator <- Seq(true, false)) {
      val c = CommitmentsSpec.makeCommitments(702000000 msat, 52000000 msat, FeeratePerKw(2679 sat), 546 sat, isInitiator)
      val (_, cmdAdd) = makeCmdAdd(c.availableBalanceForSend, randomKey().publicKey, f.currentBlockHeight)
      val result = sendAdd(c, cmdAdd, f.currentBlockHeight, feeConfNoMismatch)
      assert(result.isRight, result)
    }
  }

  test("can receive availableForReceive") { f =>
    for (isInitiator <- Seq(true, false)) {
      val c = CommitmentsSpec.makeCommitments(31000000 msat, 702000000 msat, FeeratePerKw(2679 sat), 546 sat, isInitiator)
      val add = UpdateAddHtlc(randomBytes32(), c.remoteNextHtlcId, c.availableBalanceForReceive, randomBytes32(), CltvExpiry(f.currentBlockHeight), TestConstants.emptyOnionPacket, None)
      receiveAdd(c, add, feeConfNoMismatch)
    }
  }

  test("should always be able to send availableForSend", Tag("fuzzy")) { f =>
    val maxPendingHtlcAmount = 1000000.msat
    case class FuzzTest(isInitiator: Boolean, pendingHtlcs: Int, feeRatePerKw: FeeratePerKw, dustLimit: Satoshi, toLocal: MilliSatoshi, toRemote: MilliSatoshi)
    for (_ <- 1 to 100) {
      val t = FuzzTest(
        isInitiator = Random.nextInt(2) == 0,
        pendingHtlcs = Random.nextInt(10),
        feeRatePerKw = FeeratePerKw(Random.nextInt(10000).max(1).sat),
        dustLimit = Random.nextInt(1000).sat,
        // We make sure both sides have enough to send/receive at least the initial pending HTLCs.
        toLocal = maxPendingHtlcAmount * 2 * 10 + Random.nextInt(1000000000).msat,
        toRemote = maxPendingHtlcAmount * 2 * 10 + Random.nextInt(1000000000).msat)
      var c = CommitmentsSpec.makeCommitments(t.toLocal, t.toRemote, t.feeRatePerKw, t.dustLimit, t.isInitiator)
      // Add some initial HTLCs to the pending list (bigger commit tx).
      for (_ <- 1 to t.pendingHtlcs) {
        val amount = Random.nextInt(maxPendingHtlcAmount.toLong.toInt).msat.max(1 msat)
        val (_, cmdAdd) = makeCmdAdd(amount, randomKey().publicKey, f.currentBlockHeight)
        sendAdd(c, cmdAdd, f.currentBlockHeight, feeConfNoMismatch) match {
          case Right((cc, _)) => c = cc
          case Left(e) => ignore(s"$t -> could not setup initial htlcs: $e")
        }
      }
      if (c.availableBalanceForSend > 0.msat) {
        val (_, cmdAdd) = makeCmdAdd(c.availableBalanceForSend, randomKey().publicKey, f.currentBlockHeight)
        val result = sendAdd(c, cmdAdd, f.currentBlockHeight, feeConfNoMismatch)
        assert(result.isRight, s"$t -> $result")
      }
    }
  }

  test("should always be able to receive availableForReceive", Tag("fuzzy")) { f =>
    val maxPendingHtlcAmount = 1000000.msat
    case class FuzzTest(isInitiator: Boolean, pendingHtlcs: Int, feeRatePerKw: FeeratePerKw, dustLimit: Satoshi, toLocal: MilliSatoshi, toRemote: MilliSatoshi)
    for (_ <- 1 to 100) {
      val t = FuzzTest(
        isInitiator = Random.nextInt(2) == 0,
        pendingHtlcs = Random.nextInt(10),
        feeRatePerKw = FeeratePerKw(Random.nextInt(10000).max(1).sat),
        dustLimit = Random.nextInt(1000).sat,
        // We make sure both sides have enough to send/receive at least the initial pending HTLCs.
        toLocal = maxPendingHtlcAmount * 2 * 10 + Random.nextInt(1000000000).msat,
        toRemote = maxPendingHtlcAmount * 2 * 10 + Random.nextInt(1000000000).msat)
      var c = CommitmentsSpec.makeCommitments(t.toLocal, t.toRemote, t.feeRatePerKw, t.dustLimit, t.isInitiator)
      // Add some initial HTLCs to the pending list (bigger commit tx).
      for (_ <- 1 to t.pendingHtlcs) {
        val amount = Random.nextInt(maxPendingHtlcAmount.toLong.toInt).msat.max(1 msat)
        val add = UpdateAddHtlc(randomBytes32(), c.remoteNextHtlcId, amount, randomBytes32(), CltvExpiry(f.currentBlockHeight), TestConstants.emptyOnionPacket, None)
        receiveAdd(c, add, feeConfNoMismatch) match {
          case Right(cc) => c = cc
          case Left(e) => ignore(s"$t -> could not setup initial htlcs: $e")
        }
      }
      if (c.availableBalanceForReceive > 0.msat) {
        val add = UpdateAddHtlc(randomBytes32(), c.remoteNextHtlcId, c.availableBalanceForReceive, randomBytes32(), CltvExpiry(f.currentBlockHeight), TestConstants.emptyOnionPacket, None)
        receiveAdd(c, add, feeConfNoMismatch) match {
          case Right(_) => ()
          case Left(e) => fail(s"$t -> $e")
        }
      }
    }
  }

  test("check if channel seed has been modified") { f =>
    val commitments = f.alice.stateData.asInstanceOf[DATA_NORMAL].commitments
    assert(Commitments.validateSeed(commitments, TestConstants.Alice.channelKeyManager))
    assert(!Commitments.validateSeed(commitments, new LocalChannelKeyManager(ByteVector32.fromValidHex("42" * 32), Block.RegtestGenesisBlock.hash)))
  }
}

object CommitmentsSpec {

  def makeCommitments(toLocal: MilliSatoshi, toRemote: MilliSatoshi, feeRatePerKw: FeeratePerKw = FeeratePerKw(0 sat), dustLimit: Satoshi = 0 sat, isInitiator: Boolean = true, announceChannel: Boolean = true): Commitments = {
    val channelReserve = (toLocal + toRemote).truncateToSatoshi * 0.01
    val localParams = LocalParams(randomKey().publicKey, DeterministicWallet.KeyPath(Seq(42L)), dustLimit, UInt64.MaxValue, Some(channelReserve), 1 msat, CltvExpiryDelta(144), 50, isInitiator, ByteVector.empty, None, Features.empty)
    val remoteParams = RemoteParams(randomKey().publicKey, dustLimit, UInt64.MaxValue, Some(channelReserve), 1 msat, CltvExpiryDelta(144), 50, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, Features.empty, None)
    val commitmentInput = Funding.makeFundingInputInfo(randomBytes32(), 0, (toLocal + toRemote).truncateToSatoshi, randomKey().publicKey, remoteParams.fundingPubKey)
    Commitments(
      channelId = randomBytes32(),
      ChannelConfig.standard,
      ChannelFeatures(),
      localParams,
      remoteParams,
      channelFlags = ChannelFlags(announceChannel = announceChannel),
      LocalCommit(0, CommitmentSpec(Set.empty, feeRatePerKw, toLocal, toRemote), CommitTxAndRemoteSig(CommitTx(commitmentInput, Transaction(2, Nil, Nil, 0)), ByteVector64.Zeroes), Nil),
      RemoteCommit(0, CommitmentSpec(Set.empty, feeRatePerKw, toRemote, toLocal), randomBytes32(), randomKey().publicKey),
      LocalChanges(Nil, Nil, Nil),
      RemoteChanges(Nil, Nil, Nil),
      localNextHtlcId = 1,
      remoteNextHtlcId = 1,
      originChannels = Map.empty,
      remoteNextCommitInfo = Right(randomKey().publicKey),
      commitInput = commitmentInput,
      remotePerCommitmentSecrets = ShaChain.init)
  }

  def makeCommitments(toLocal: MilliSatoshi, toRemote: MilliSatoshi, localNodeId: PublicKey, remoteNodeId: PublicKey, announceChannel: Boolean): Commitments = {
    val channelReserve = (toLocal + toRemote).truncateToSatoshi * 0.01
    val localParams = LocalParams(localNodeId, DeterministicWallet.KeyPath(Seq(42L)), 0 sat, UInt64.MaxValue, Some(channelReserve), 1 msat, CltvExpiryDelta(144), 50, isInitiator = true, ByteVector.empty, None, Features.empty)
    val remoteParams = RemoteParams(remoteNodeId, 0 sat, UInt64.MaxValue, Some(channelReserve), 1 msat, CltvExpiryDelta(144), 50, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, randomKey().publicKey, Features.empty, None)
    val commitmentInput = Funding.makeFundingInputInfo(randomBytes32(), 0, (toLocal + toRemote).truncateToSatoshi, randomKey().publicKey, remoteParams.fundingPubKey)
    Commitments(
      channelId = randomBytes32(),
      ChannelConfig.standard,
      ChannelFeatures(),
      localParams,
      remoteParams,
      channelFlags = ChannelFlags(announceChannel = announceChannel),
      LocalCommit(0, CommitmentSpec(Set.empty, FeeratePerKw(0 sat), toLocal, toRemote), CommitTxAndRemoteSig(CommitTx(commitmentInput, Transaction(2, Nil, Nil, 0)), ByteVector64.Zeroes), Nil),
      RemoteCommit(0, CommitmentSpec(Set.empty, FeeratePerKw(0 sat), toRemote, toLocal), randomBytes32(), randomKey().publicKey),
      LocalChanges(Nil, Nil, Nil),
      RemoteChanges(Nil, Nil, Nil),
      localNextHtlcId = 1,
      remoteNextHtlcId = 1,
      originChannels = Map.empty,
      remoteNextCommitInfo = Right(randomKey().publicKey),
      commitInput = commitmentInput,
      remotePerCommitmentSecrets = ShaChain.init)
  }

}


text:
#include <v8.h>
#include <node.h>
#include "lame.h"

namespace nodelame {

/* enums used to set the type of the input PCM */
typedef enum {
  PCM_TYPE_SHORT_INT,
  PCM_TYPE_FLOAT,
  PCM_TYPE_DOUBLE
} pcm_type;

/* struct that's used for async encoding */
struct encode_req {
  uv_work_t req;
  lame_global_flags *gfp;
  unsigned char *input;
  pcm_type input_type;
  int channels;
  int num_samples;
  unsigned char *output;
  int output_size;
  int rtn;
  v8::Persistent<v8::Function> callback;
};

void node_lame_encode_buffer_async (uv_work_t *);
void node_lame_encode_buffer_after (uv_work_t *);

void node_lame_encode_flush_nogap_async (uv_work_t *);
#define node_lame_encode_flush_nogap_after node_lame_encode_buffer_after

} // nodelame namespace


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('courses', '0003_auto_20170429_1509'),
    ]

    operations = [
        migrations.AddField(
            model_name='course',
            name='students',
            field=models.ManyToManyField(blank=True, related_name='courses_joined', to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
namespace glpp
{
template<typename T>
class quad : public mesh
{
public:
    explicit quad( const common::dims_2<T>& dimensions,
                   bool                     flip_y = false )
        : _dimensions()
    {
        bind()
            .indices ( {
                0, 1, 3,
                1, 2, 3
            } )
            .template attribs<T>( {
                { "position", 3 },
                { "texcoord", 2 }
            } );

        this->dimensions ( dimensions, flip_y );
    }

    quad( quad&& move ) = default;

    quad( const quad& copy ) = delete;

    virtual ~quad() = default;

    quad& operator=( quad&& move ) = default;

    quad& operator=( const quad& copy ) = delete;

    static auto make_shared ( const common::dims_2<T>& dimensions,
                              bool                     flip_y = false ) {
        return std::make_shared<quad>( dimensions, flip_y );
    }

    static auto make_unique ( const common::dims_2<T>& dimensions ) {
        return std::make_unique<quad>( dimensions );
    }

    common::dims_2<T> dimensions() {
        return _dimensions;
    }

    quad& dimensions ( const common::dims_2<T>& dimensions,
                       bool                     flip_y = false ) {
        _dimensions = dimensions;

        T sign = flip_y ? -1 : 1;

        vertices<T>( {
                // Top Right
                _dimensions.width, sign * _dimensions.height, 0,
                1, 0,

                // Bottom Right
                _dimensions.width, sign * -_dimensions.height, 0,
                1, 1,

                // Bottom Left
                -_dimensions.width, sign * -_dimensions.height, 0,
                0, 1,

                // TOP Left
                -_dimensions.width, sign * _dimensions.height, 0,
                0, 0
            } );

        return *this;
    }

private:
    common::dims_2<T> _dimensions;
};
}

#endif // GLPP_QUAD_H


text:
return <<'END';
3400	4DB5	Unified_Ideograph
4E00	9FA5	Unified_Ideograph
FA0E	FA0F	Unified_Ideograph
FA11		Unified_Ideograph
FA13	FA14	Unified_Ideograph
FA1F		Unified_Ideograph
FA21		Unified_Ideograph
FA23	FA24	Unified_Ideograph
FA27	FA29	Unified_Ideograph
20000	2A6D6	Unified_Ideograph
END