text:
<?php
namespace FluxCtrl\App\Test\TestCase;

use Cake\Routing\Router;
use Cake\TestSuite\TestCase;

class RouteTest extends TestCase
{
    public function testAppFeedsRoutes()
    {
        $id = 'A3eRt';
        $route = ['plugin' => null, 'controller' => 'Feeds'];

        $expected = $route + ['action' => 'index', '_method' => 'GET'];
        $this->assertRoute('GET', '/feeds', $expected);

        $expected = $route + ['action' => 'add', '_method' => ['GET', 'POST']];
        $url = '/feeds/add';
        $this->assertRoute('GET', $url, $expected);
        $this->assertRoute('POST', $url, $expected);

        $route = $route + compact('id');

        $expected = $route + ['action' => 'delete', '_method' => 'DELETE'];
        $this->assertRoute('DELETE', '/feeds/' . $id, $expected);

        $expected = $route + ['action' => 'edit', '_method' => ['GET', 'PUT']];
        $url = '/feeds/' . $id . '/edit';
        $this->assertRoute('GET', $url, $expected);
        $this->assertRoute('PUT', $url, $expected);
    }

    public function testAppItemsRoutes()
    {
        $id = '4A';
        $feed_id = 'A3et';
        $route = ['plugin' => null, 'controller' => 'Items'];

        $expected = $route + ['action' => 'index', '_method' => 'GET'];
        $this->assertRoute('GET', '/items', $expected);

        $expected = $expected + ['id' => $feed_id, 'prefix' => 'feed'];
        $url = '/' . $feed_id . '/items';
        $this->assertRoute('GET', $url, $expected);

        $expected = ['action' => 'add', '_method' => ['GET', 'POST']] + $expected;
        $url .= '/add';
        $this->assertRoute('GET', $url, $expected);
        $this->assertRoute('POST', $url, $expected);

        $route += compact('id');
        $url = '/items/' . $id;

        $expected = $route + ['action' => 'view', '_method' => 'GET'];
        $this->assertRoute('GET', $url, $expected);

        $expected = $route + ['action' => 'delete', '_method' => 'DELETE'];
        $this->assertRoute('DELETE', $url, $expected);

        $expected = $route + ['action' => 'edit', '_method' => ['GET', 'PUT']];
        $url .= '/edit';
        $this->assertRoute('GET', $url, $expected);
        $this->assertRoute('PUT', $url, $expected);
    }

    /**
     * @expectedException \Cake\Routing\Exception\MissingRouteException
     */
    public function testAppFeedsViewThrowsException()
    {
        Router::parse('/feeds/A3eRt');
    }

    /**
     * @expectedException \Cake\Routing\Exception\MissingRouteException
     */
    public function testAppItemsAddWithoutFeedIdThrowsException()
    {
        Router::parse('/items/add');
    }

    public function assertRoute($method, $url, array $asserts)
    {
        $this->setHttpMethod($method);
        $result = Router::parse($url);
        foreach ($asserts as $k => $expected) {
            $this->assertEquals($expected, $result[$k], "$method: $url");
        }
    }

    public function setHttpMethod($method)
    {
        $_ENV['REQUEST_METHOD'] = $method;
    }
}


text:
import hearthbreaker.game_objects

class ProxyCharacter:
    def __init__(self, character_ref):
        if type(character_ref) is str:
            if character_ref.find(":") > -1:
                [self.player_ref, self.minion_ref] = character_ref.split(':')
                self.minion_ref = int(self.minion_ref)
            else:
                self.player_ref = character_ref
                self.minion_ref = None
        elif type(character_ref) is hearthbreaker.game_objects.Hero:
            if character_ref == character_ref.player.game.players[0].hero:
                self.player_ref = "p1"
            else:
                self.player_ref = "p2"
            self.minion_ref = None
        elif type(character_ref) is hearthbreaker.game_objects.Minion:
            if character_ref.player == character_ref.game.players[0]:
                self.player_ref = "p1"
            else:
                self.player_ref = "p2"
            self.minion_ref = character_ref.index

    def resolve(self, game):
        if self.player_ref == "p1":
            char = game.players[0].hero
        else:
            char = game.players[1].hero
        if self.minion_ref is not None:
            if self.minion_ref == -1:
                return None
            if self.player_ref == "p1":
                char = game.players[0].minions[self.minion_ref]
            else:
                char = game.players[1].minions[self.minion_ref]

        return char

    def __str__(self):
        if self.minion_ref is not None:
            return "{0}:{1}".format(self.player_ref, self.minion_ref)
        return self.player_ref

    def to_output(self):
        return str(self)

class TrackingProxyCharacter(ProxyCharacter):
    def __init__(self, character_ref, game):
        super().__init__(character_ref)
        if self.minion_ref is not None:
            if self.player_ref == "p1":
                player = game.players[0]
            else:
                player = game.players[1]
            player.bind("minion_played", self.__minion_added)
            player.bind("minion_removed", self.__minion_removed)

    def __minion_added(self, minion):
        if minion.index < self.minion_ref:
            self.minion_ref += 1

    def __minion_removed(self, minion):
        if minion.index == self.minion_ref:
            self.minion_ref = -1
            minion.player.unbind("minion_played", self.__minion_added)
            minion.player.unbind("minion_removed", self.__minion_removed)
        elif minion.index < self.minion_ref:
            self.minion_ref -= 1

class ProxyCard:
    def __init__(self, card_reference, game=None):
        self.card_ref = -1
        if isinstance(card_reference, str):
            self.card_ref = card_reference
        else:
            self.card_ref = str(card_reference)

        self.targetable = False

    def set_option(self, option):
        self.card_ref = ":" + str(option)

    def resolve(self, game):
        ref = self.card_ref.split(':')
        if len(ref) > 1:
            game.current_player.agent.next_option = int(ref[1])
        return game.current_player.hand[int(ref[0])]

    def __str__(self):
        return str(self.card_ref)

    def to_output(self):
        return str(self)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Deployment.Application;
using System.IO;

/// <summary>
/// This class represents an eData document per draft specification ASTM E55 workgroup WK51651.
/// </summary>
/// <remarks>Reference example code provided by Microsoft at https://msdn.microsoft.com/en-us/library/75wfb4f2(v=vs.110).aspx
/// See also explanatory example code at http://stackoverflow.com/questions/4271689/xml-selectnodes-with-default-namespace-via-xmlnamespacemanager-not-working-as-ex
/// </remarks>
public class eDataSig
{
    // XML content in opened eData document
    private XmlDocument _doc;

    // XML namespace manager used to resolve namespaces in XPath queries
    private XmlNamespaceManager _nsmgr;

    // Validation errors and warnings
    private string _validationErrors = string.Empty;
    private string _validationWarnings = string.Empty;
    public string ValidationErrors { get { return _validationErrors; } }
    public string ValidationWarnings { get { return _validationWarnings; } }

    /// <summary>
    /// Enumeration of various possibilities for digital signature that could be present in eData document.
    /// </summary>
    public enum SignatureTypes { None, HMACSHA1, DSA, Invalid };

    /// <summary>
    /// Returns the type of digital signature present in the eData document. No attempt
    /// is made to verify the signature.
    /// </summary>
    public SignatureTypes SignatureType
    {
        get
        {
            // Find all signatures present in the FileInformation element of the XML document
            XmlNodeList sigs = _doc.SelectNodes("/x:ASTMeDataXchange/x:FileInformation/y:Signature", _nsmgr);
            if (sigs.Count == 1)
            {
                try
                {
                    // Load the first signature, ignore all others
                    SignedXml signedXml = new SignedXml(_doc);
                    signedXml.LoadXml((XmlElement)sigs[0]);

                    // Handle the various signature methods
                    switch (signedXml.SignatureMethod)
                    {
                        case SignedXml.XmlDsigDSAUrl:
                            // Signature is DSA
                            return SignatureTypes.DSA;
                        case SignedXml.XmlDsigHMACSHA1Url:
                            // Signature is HMAC-SHA1
                            return SignatureTypes.HMACSHA1;
                        default:
                            // Signature is readable but algorithm is not supported
                            return SignatureTypes.Invalid;
                    }
                }
                catch (System.Exception x)
                {
                    // Signature cannot not be read for whatever reason
                    Debug.WriteLine(x);
                    return SignatureTypes.Invalid;
                }
            }
            else if (sigs.Count >1)
            {
                // More than one signature present, this is not supported
                return SignatureTypes.Invalid;
            }

            // There is no signature
            return SignatureTypes.None;
        }
    }

    /// <summary>
    /// Adds an enveloped digital signature of type DSA-SHA1 to the eData content and
    /// saves it to a new file.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="saveFile"></param>
    public void Sign(DSA key, string saveFile)
    {
        Sign(null, key, saveFile);
    }

    /// <summary>
    /// Internal method used for signing by DSA-SHA1 or HMAC-SHA1
    /// </summary>
    /// <param name="secret"></param>
    /// <param name="key"></param>
    /// <param name="saveFile"></param>
    private void Sign(string secret, DSA key, string saveFile)
    {
        // Create a SignedXml object
        SignedXml signedXml = new SignedXml(_doc);

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = string.Empty;

        // Add an enveloped transformation to the reference
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXML object.
        signedXml.AddReference(reference);

        if (key != null)
        {
            // Specify the key
            signedXml.SigningKey = key;

            // Add optional information about public key
            KeyInfo ki = new KeyInfo();
            ki.AddClause(new DSAKeyValue(key));
            signedXml.KeyInfo = ki;

            // Compute the signature.
            signedXml.ComputeSignature();
        }
        else if (secret != null)
        {
            // Caution - this is not strictly secure
            KeyedHashAlgorithm hash = new HMACSHA1(Encoding.ASCII.GetBytes(secret));

            // Compute the signature.
            signedXml.ComputeSignature(hash);
        }

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        XmlNode fi = _doc.SelectSingleNode("/x:ASTMeDataXchange/x:FileInformation", _nsmgr);
        fi.AppendChild(_doc.ImportNode(xmlDigitalSignature, true));

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(saveFile, new UTF8Encoding(false));
        _doc.WriteTo(xmltw);
        xmltw.Close();
    }

    /// <summary>
    /// Adds an enveloped digital signature of type HMAC-SHA1 to the eData content and
    /// saves it to a new file.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="saveFile">Name of </param>
    public void Sign(string key, string saveFile)
    {
        Sign(key, null, saveFile);
    }

    /// <summary>
    /// Verifies an enveloped digital signature of type DSA-SHA1 in the eData content. This
    /// method does not verify the trust chain of the certificate.
    /// </summary>
    /// <param name="key">DSA key used for verification.</param>
    /// <returns>true if the digital signature is valid, otherwise false.</returns>
    public bool VerifySignature(DSA key)
    {
        try
        {
            SignedXml signedXml = getSignature();
            return signedXml.CheckSignature(key);
        }
        catch(Exception x)
        {
            Debug.WriteLine(x);
        }
        return false;
    }

    /// <summary>
    /// Verifies an enveloped digital signature of type HMAC-SHA1 in the eData content.
    /// </summary>
    /// <param name="key"></param>
    /// <returns>true if the digital signature is valid, otherwise false.</returns>
    public bool VerifySignature(string key)
    {
        try
        {
            // Caution - this is not strictly secure
            KeyedHashAlgorithm hash = new HMACSHA1(Encoding.ASCII.GetBytes(key));

            // Check the signature and return the result.
            SignedXml signedXml = getSignature();
            return signedXml.CheckSignature(hash);
        }
        catch(Exception x)
        {
            Debug.WriteLine(x);
        }
        return false;
    }

    /// <summary>
    /// Verifies an enveloped digital signature in the eData content using the public key embedded in
    /// the signature. This does not necessarily ensure data integrity since the public key could have been
    /// maliciously compromised.
    /// </summary>
    /// <returns>true if the digital signature is valid, otherwise false.</returns>
    public bool VerifySignature()
    {
        try
        {
            SignedXml signedXml = getSignature();
            return signedXml.CheckSignature();
        }
        catch(Exception x)
        {
            Debug.WriteLine(x);
        }
        return false;
    }

    // Private method to retrieve the first XMLDsig Signature element in the document
    private SignedXml getSignature()
    {
        // Create a new SignedXML object and pass it
        // the XMl document class.
        SignedXml signedXml = new SignedXml(_doc);

        // Find all signatures present in the FileInformation element of the XML document
        XmlNodeList sigs = _doc.SelectNodes("/x:ASTMeDataXchange/x:FileInformation/y:Signature", _nsmgr);

        // Load the signature node.
        signedXml.LoadXml((XmlElement)sigs[0]);

        return signedXml;
    }

    /// <summary>
    /// Validates the document content according to the eData XML Schema Definition (XSD)
    /// </summary>
    /// <returns>True if the format is OK, otherwise false</returns>
    public bool ValidateFormat()
    {
        string _xsdPath = "eData.xsd";
        // Need to check for ClickOnce deployment since XSD will be elsewhere in that case
        if (ApplicationDeployment.IsNetworkDeployed)
        {
            _xsdPath = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, _xsdPath);
        }
        _doc.Schemas.Add("http://www.astm.org/E55/03/eDataXchange", _xsdPath);
        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
        _validationErrors = string.Empty;
        _validationWarnings = string.Empty;
        _doc.Validate(eventHandler);
        return (_validationErrors == string.Empty);
    }

    /// <summary>
    /// Read only property specifying the number of MaterialData elements present in the document
    /// </summary>
    public int MaterialDataCount
    {
        get
        {
            // Find all MaterialData elements present in the MaterialDataGroup element of the XML document
            XmlNodeList mds = _doc.SelectNodes("/x:ASTMeDataXchange/x:MaterialDataGroup/x:MaterialData", _nsmgr);
            if (mds!=null)
            {
                return mds.Count;
            }
            return 0;
        }
    }

    // Private method handling XSD validation errors/warnings
    private void ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        switch (e.Severity)
        {
            case XmlSeverityType.Error:
                _validationErrors += e.Message;
                break;
            case XmlSeverityType.Warning:
                _validationWarnings += e.Message;
                break;
        }
    }

    // Private constructor
    private eDataSig() { }

    /// <summary>
    /// Public constructor
    /// </summary>
    /// <param name="xmlFile">Path to an eData XML file</param>
    public eDataSig(string xmlFile)
    {
        // Read the eData file into memory
        XmlReader reader = XmlReader.Create(xmlFile);
        _doc = new XmlDocument();
        _doc.PreserveWhitespace = true;
        _doc.Load(reader);
        reader.Close();

        // Prepare the namespace manager for XPath queries
        _nsmgr = new XmlNamespaceManager(_doc.NameTable);
        _nsmgr.AddNamespace("x", "http://www.astm.org/E55/03/eDataXchange");
        _nsmgr.AddNamespace("y", "http://www.w3.org/2000/09/xmldsig#");

    }

}


text:
#import <Foundation/Foundation.h>
#import <P2PKit/PPKPeer.h>
#import <P2PKit/PPKController.h>


text:
'use strict';
angular.module('cm.services')
  .factory('cmCache', function($cacheFactory) {
    return $cacheFactory('data');
  })

  .factory('dataFactory', function($http, $q, $filter, cmCache, state, config) {
    var getAllData = function() {
      var deferred       = $q.defer()
          ,currentSeason = state.getCurrentState('season');

      if (typeof currentSeason !== 'string')
        currentSeason = config.seasons[config.seasons.length - 1].id;

      $http.get('data/data.' + currentSeason + '.json', {cache: cmCache})
        .success(function(data) {
          deferred.resolve(data);
        }).error(function(){
          deferred.reject("Woops! Something wen't wrong.");
        });

      return deferred.promise;
    }

    var filterByDivision = function(teams, division) {
      var deferred = $q.defer();

      getAllData().then(function(data) {
        var filteredTeams = $filter('filter')(teams, function(team) {
          if (teams.indexOf(team.name) !== -1)
            return true;
          else
            return false;
        });

        // Filter out data
        deferred.resolve(filteredTeams);
      });

      return deferred.promise;
    }

    var filterByTeams = function(teams) {
      var deferred = $q.defer();

      getAllData().then(function(data) {
        var filteredTeams = $filter('filter')(data, function(team) {
          if (teams.indexOf(team.name) !== -1)
            return true;
          else
            return false;
        });

        // Filter out data
        deferred.resolve(filteredTeams);
      });

      return deferred.promise;
    }

    // @TODO: Find a way to not have to copy the original children array....
    var filterByPosition = function(filteredTeams, position) {
      var filteredPlayers = [];
      angular.forEach(filteredTeams, function(team, i) {
        var has_copy = team.hasOwnProperty('children_copy') ? true :false
            ,access_key = has_copy ? 'children_copy' : 'children';

        filteredPlayers = $filter('filter')(team[access_key], function(p) {
          if (position.value.indexOf(p.pos) !== -1)
            return true;
          else
            return false;
        });

        if (!has_copy)
          filteredTeams[i].children_copy = filteredTeams[i].children;

        filteredTeams[i].children = filteredPlayers;
      });

      return filteredTeams;
    }

    var getAllPlayers = function() {
      var deferred = $q.defer();

      getAllData().then(function(data) {
        // If data is already in cache, use that, else, filter it.
        var cached = cmCache.get('all_players')
            ,players = [];

        if (!cached) {
          data.forEach(function(team) {
            team['children'].forEach(function(player) {
              players.push(player);
            });
          });
        }
        else {
          players = cached;
        }

        deferred.resolve(players);
      });

      return deferred.promise;
    }

    var getPlayer = function(player) {
      var deferred = $q.defer();

      getAllData().then(function(data) {
        // Filter out data
        deferred.resolve(data);
      });

      return deferred.promise;
    }

    var getLeagueHighsLows = function(metrics) {
      var deferred = $q.defer();

      getAllData().then(function(data) {
        // If data is already in cache, use that, else, filter it.
        var cached     = cmCache.get('league_highs_lows')
            ,highsLows = {};

        if (!cached) {
          if (typeof metrics === 'undefined')
            deferred.reject('\'getLeagueHighsLows\' needs to be passed a metrics argument.');

          var val = .0;
          angular.forEach(metrics, function(metric, m) {
            highsLows[metric.name] = {
              title: metric.title
              ,high: -Number.MAX_VALUE
              ,low: Number.MAX_VALUE
            };

            angular.forEach(data, function(team, t) {
              angular.forEach(team.children, function(player, p) {
                val = parseInt(player[metric.name]);

                if (val < highsLows[metric.name].low) {
                  highsLows[metric.name].low = val;
                }

                if (val > highsLows[metric.name].high) {
                  highsLows[metric.name].high = val;
                }
              });
            });
          });

          cmCache.put('league_highs_lows', highsLows);
        }
        else {
          highsLows = cached;
        }

        deferred.resolve(highsLows);
      });

      return deferred.promise;
    }

    return {
       getAllData: getAllData
      ,filterByDivision: filterByDivision
      ,filterByPosition: filterByPosition
      ,filterByTeams: filterByTeams
      ,getAllPlayers: getAllPlayers
      ,getPlayer: getPlayer
      ,getLeagueHighsLows: getLeagueHighsLows
    }
  });


text:
namespace base
{
PProf::PProf(std::string const & path)
{
#if defined(USE_PPROF)
  ProfilerStart(path.c_str());
#endif
}

PProf::~PProf()
{
  CHECK(m_checker.CalledOnOriginalThread(), ());

#if defined(USE_PPROF)
  ProfilerStop();
#endif
}
}  // namespace base


text:
package btrfs

import (
	"fmt"
	"path"
	"syscall"
	"time"

	log "github.com/Sirupsen/logrus"
	graph "github.com/docker/docker/daemon/graphdriver"
	"github.com/docker/docker/daemon/graphdriver/btrfs"
	"github.com/pborman/uuid"

	"github.com/portworx/kvdb"

	"github.com/libopenstorage/openstorage/api"
	"github.com/libopenstorage/openstorage/pkg/chaos"
	"github.com/libopenstorage/openstorage/volume"
)

const (
	Name      = "btrfs"
	Type      = volume.File
	RootParam = "home"
	Volumes   = "volumes"
)

var (
	koStrayCreate chaos.ID
	koStrayDelete chaos.ID
)

type driver struct {
	*volume.DefaultBlockDriver
	*volume.DefaultEnumerator
	btrfs graph.Driver
	root  string
}

func Init(params volume.DriverParams) (volume.VolumeDriver, error) {
	root, ok := params[RootParam]
	if !ok {
		return nil, fmt.Errorf("Root directory should be specified with key %q", RootParam)
	}
	home := path.Join(root, Volumes)
	d, err := btrfs.Init(home, nil)
	if err != nil {
		return nil, err
	}
	s := volume.NewDefaultEnumerator(Name, kvdb.Instance())
	return &driver{btrfs: d, root: root, DefaultEnumerator: s}, nil
}

func (d *driver) String() string {
	return Name
}

// Status diagnostic information
func (d *driver) Status() [][2]string {
	return d.btrfs.Status()
}

func (d *driver) Type() volume.DriverType {
	return Type
}

// Create a new subvolume. The volume spec is not taken into account.
func (d *driver) Create(locator api.VolumeLocator,
	options *api.CreateOptions,
	spec *api.VolumeSpec) (api.VolumeID, error) {

	if spec.Format != "btrfs" && spec.Format != "" {
		return api.BadVolumeID, fmt.Errorf("Filesystem format (%v) must be %v",
			spec.Format, "btrfs")
	}

	volumeID := uuid.New()

	v := &api.Volume{
		ID:       api.VolumeID(volumeID),
		Locator:  locator,
		Ctime:    time.Now(),
		Spec:     spec,
		LastScan: time.Now(),
		Format:   "btrfs",
		State:    api.VolumeAvailable,
		Status:   api.Up,
	}
	err := d.CreateVol(v)
	if err != nil {
		return api.BadVolumeID, err
	}
	err = d.btrfs.Create(volumeID, "")
	if err != nil {
		return api.BadVolumeID, err
	}
	v.DevicePath, err = d.btrfs.Get(volumeID, "")
	if err != nil {
		return v.ID, err
	}
	err = d.UpdateVol(v)
	return v.ID, err
}

// Delete subvolume
func (d *driver) Delete(volumeID api.VolumeID) error {
	err := d.DeleteVol(volumeID)
	if err != nil {
		log.Println(err)
		return err
	}

	chaos.Now(koStrayDelete)
	if err == nil {
		err = d.btrfs.Remove(string(volumeID))
	}
	return err
}

// Mount bind mount btrfs subvolume
func (d *driver) Mount(volumeID api.VolumeID, mountpath string) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		log.Println(err)
		return err
	}
	err = syscall.Mount(v.DevicePath,
		mountpath,
		string(v.Format),
		syscall.MS_BIND, "")
	if err != nil {
		return fmt.Errorf("Faield to mount %v at %v: %v", v.DevicePath, mountpath, err)
	}
	v.AttachPath = mountpath
	err = d.UpdateVol(v)
	return err
}

// Unmount btrfs subvolume
func (d *driver) Unmount(volumeID api.VolumeID, mountpath string) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		return err
	}
	if v.AttachPath == "" {
		return fmt.Errorf("Device %v not mounted", volumeID)
	}
	err = syscall.Unmount(v.AttachPath, 0)
	if err != nil {
		return err
	}
	v.AttachPath = ""
	err = d.UpdateVol(v)
	return err
}

// Snapshot create new subvolume from volume
func (d *driver) Snapshot(volumeID api.VolumeID, readonly bool, locator api.VolumeLocator) (api.VolumeID, error) {
	vols, err := d.Inspect([]api.VolumeID{volumeID})
	if err != nil {
		return api.BadVolumeID, err
	}
	if len(vols) != 1 {
		return api.BadVolumeID, fmt.Errorf("Failed to inspect %v len %v", volumeID, len(vols))
	}
	snapID := uuid.New()
	vols[0].ID = api.VolumeID(snapID)
	vols[0].Parent = volumeID
	vols[0].Locator = locator
	vols[0].Ctime = time.Now()

	err = d.CreateVol(&vols[0])
	if err != nil {
		return api.BadVolumeID, err
	}
	chaos.Now(koStrayCreate)
	err = d.btrfs.Create(snapID, string(volumeID))
	if err != nil {
		return api.BadVolumeID, err
	}
	return vols[0].ID, nil
}

// Stats for specified volume.
func (d *driver) Stats(volumeID api.VolumeID) (api.Stats, error) {
	return api.Stats{}, nil
}

// Alerts on this volume.
func (d *driver) Alerts(volumeID api.VolumeID) (api.Alerts, error) {
	return api.Alerts{}, nil
}

// Shutdown and cleanup.
func (d *driver) Shutdown() {
}

func init() {
	volume.Register(Name, Init)
}


text:
class ApiKeyPolicy < ApplicationPolicy
  class Scope < Struct.new(:user, :scope)
    def resolve
      scope
    end
  end
end


text:
{% extends 'messages/base_messages.html' %}
{% load i18n %}
{% load static %}

{% block title %}{% trans 'New message' %}{% endblock %}

{% block page_header %}{% trans 'New message' %}{% endblock %}

{% block container %}
  <form class="form-horizontal" role="form" method="post">
    {% csrf_token %}

      {% trans 'Send To' %}

        <input class="form-control typeahead" type="text" id="to" name="to">

      {% trans 'Message' %}

        <textarea class="form-control" id="message" name="message" placeholder="{% trans 'Write a message' %}" rows="4"></textarea>

        <button type="submit" class="btn btn-primary">{% trans 'Send' %}</button>

  </form>

{% endblock container %}


text:
<template name="subjectSourceIdsList">
  {{#if has_sources_and_subjects}}
    {{#if submitting}}
      {{> subjectSourceIdSubmit}}
    {{/if}}

      {{#each subject_source_ids}}
        {{#if item_is_edited}}
          {{> subjectSourceIdEdit}}
        {{else}}
          {{> subjectSourceIdItem}}
        {{/if}}
      {{/each}}

  {{else}}

{{_ "You need to add sources and subjects before you can add subject source ids"}}.

  {{/if}}
</template>


text:
var https = require('https');
var http = require('http');
var request = require('request');
var FormData = require('form-data');
var path = require('path');
var fs = require('fs');

// misc
var noop = function(){};

// generic HTTP request
var restRequest = function(options, callback){
    callback = callback || noop;
    options = options || {};

    // set protocol to HTTP or HTTPS
    options.protocol = options.protocol || "http";
    options.protocol = (options.protocol.toLowerCase() == "http") ? "http" : "https";
    var protocol = (options.protocol == "http") ? http : https;

    // automatically manage body submit & set content length if not specified
    if((typeof options.body != "undefined") && (!options.headers["Content-Length"])){
        options.headers["Content-Length"] = Buffer.byteLength( options.body, 'utf8' );
    }

    // if we still don't have have content length, set to zero
    if(typeof options.headers["Content-Length"] == "undefined") options.headers["Content-Length"] = 0;

    var submitBody = options.body;

    // cleanup options from custom vars
    delete options.protocol;
    delete options.body;

    var req = protocol.request(options, function(res) {

        var body = "";
        res.on('data', function(d) {
            body += d;
        });
        res.on('end', function() {
            // parse JSON response
            if(res.headers["content-type"]) {
                if (res.headers["content-type"].toLowerCase().indexOf("application/json") !== -1) {
                    body = JSON.parse(body);
                }
            }

            if(res.statusCode >= 400) {
                callback(res.statusCode, body);
            } else {
                callback(null, body);
            }
        });
    });

    req.on('error', function(e) {
        callback(e);
    });

    if(submitBody) req.write(submitBody);
    req.end();
};

var edsFileUploadRequest = function(options, callback){
    callback = callback || noop;

    var objData = {
        targetFileProperty: {
            id: options.edsMultipartData.objId,
            objectType: options.edsMultipartData.objType,
            propertyName: options.edsMultipartData.fieldName
        }
    };

    var filePath = options.edsMultipartData.filePath;
    var address = options.protocol + "://" + options.hostname + options.path;

    // create multipart/form data
    var form = new FormData();
    form.append('object', JSON.stringify(objData));
    form.append('filename', path.basename(filePath));
    form.append('file', fs.createReadStream(filePath));
    form.getLength(function(err, theLength){

        options.headers['Content-Length'] = theLength;

        var req = request.post(address, {
            headers: options.headers
        }, function(e, r, body) {
            // TODO: fix the statusCode. Should be 200?
            if(!e && (r.statusCode == 201)){
                body = JSON.parse(body);
                callback(null, body);
            } else {
                callback(r.statusCode, body);
            }
        });
        req._form = form
    });
};

var edsFileDownloadRequest = function(options, callback){
    callback = callback || noop;

    request({
        method: "GET",
        url: options.address,
        headers: options.headers
    }, function(e, r, body) {
        if(!e && (r.statusCode == 200)){
            callback(null, body);
        } else {
            callback(r.statusCode);
        }
    }).pipe(fs.createWriteStream(options.filePath));
};

module.exports = {
    restRequest: restRequest,
    edsFileUploadRequest: edsFileUploadRequest,
    edsFileDownloadRequest: edsFileDownloadRequest
};


text:
import os
import sys

# Third Party
from django.core.management import execute_from_command_line
from dotenv import load_dotenv

if __name__ == "__main__":
    # Read .env file and set key/value inside it as environment variables
    load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.development")

    execute_from_command_line(sys.argv)


text:
VBA modules designed to improve productivity in Excel.

The first module, MatchArrays, has similar functionality to the VLOOKUP or MATCH functions.

Benefits to include:

  Faster than VLOOKUP or MATCH on thousands of rows (done)

  Simpler user experience (halfway there, work-in-progress)

  Simpler usage in VBA than writing new functions (work-in-progress)

  Quick-Access Toolbar button to run (may be programmatically added or packaged with instructions)

Requirements:

  Microsoft Excel 2010 or greater (Untested in older version)

  Microsoft Scripting Runtime reference (instructions to be included in package)


text:
@protocol CDColumnCellDelegate<NSObject>
- (void)CDColumnCellOpenClick:(StudentDetail_Column_M *)mode;
@end
@interface CDColumnCell : UITableViewCell
@property (nonatomic, strong) UILabel *titleLabel,*majorName,*schoolName,*start,*end,*startLabel,*endLabel;
@property (nonatomic, strong) UIView *bottomView,*lineView;
@property (nonatomic, assign) id<CDColumnCellDelegate> delegate;
- (void)setMode:(StudentDetail_Column_M *)mode;
+ (CGFloat )getHeight:(StudentDetail_Column_M *)mode;
@end


text:
package com.jrestless.aws.security;

import java.security.Principal;

import javax.annotation.Nonnull;

/**
 * User authenticated by a custom authorizer.
 *

 * See
 * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
 *
 * @author Bjoern Bilger
 *
 */
public interface CustomAuthorizerPrincipal extends Principal {
	/**
	 * Returns the user's claims.
	 * @return the user's claims
	 */
	@Nonnull
	CustomAuthorizerClaims getClaims();

	/**
	 * Returns the principalId.
	 *
	 * @return the principalId
	 */
	@Nonnull
	@Override
	default String getName() {
		return getClaims().getPrincipalId();
	}
}


text:
package org.wso2.carbon.device.mgt.mobile.windows.api.operations.util;

import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.AddTag;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.ItemTag;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.MetaTag;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.TargetTag;

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

/**
 * Contains utility methods which are used while creating Syncml Messages.
 */
public class TagUtil {
    /**
     * Build syncml AddTag for Device response message.
     *
     * @param operation Policy operation
     * @param data      Configuration service provider(CSP) data value 1/0
     * @return Syncml AddTag type object.
     */
    public static AddTag buildAddTag(Operation operation, String data) {
        TargetTag target = new TargetTag();
        MetaTag meta = new MetaTag();
        AddTag add = new AddTag();

        List<ItemTag> itemTags = new ArrayList<>();
        ItemTag itemTag = new ItemTag();
        itemTag.setTarget(target);
        itemTag.setMeta(meta);
        itemTag.setData(data);
        itemTags.add(itemTag);
        add.setCommandId(operation.getId());
        add.setItems(itemTags);
        return add;
    }
}


text:
package org.cloudname.flags;

/**
 * Class containing enum for testing.
 *
 * @author acidmoose
 *
 */
public class FlagsEnum {

    public enum SimpleEnum {OPTION1, OPTION2};

    @Flag(name="option", options=SimpleEnum.class)
    public static SimpleEnum option = SimpleEnum.OPTION1;
}


text:
require 'spec_helper'

describe EventsController do
  login_user

  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.code.should eq "200"
    end
  end

  describe "GET 'events_table'" do
    it "returns http success" do
      get 'events_table', {:client => 1}
      response.code.should eq "406"
    end
  end

  describe "GET 'modal_data'" do
    it "returns http success" do
      get 'modal_data', {:client => 1}
      response.code.should eq "200"
    end
  end

  describe "GET 'resolve'" do
    it "returns http success" do
      # todo
      # get 'resolve', {:client => 1, :check => 1}
      # response.code.should eq "200"
    end
  end

  describe "GET 'silence_client'" do
    it "returns http success" do
      # todo
      # get 'silence_client', {:client =>1}
      # response.code.should eq "200"
    end
  end

  describe "GET 'silence_check'" do
    it "returns http success" do
      # todo
      # get 'silence_check', {:client => 1, :check => 1, :description => "this is a test description", :user => User.first}
      # response.code.should eq "200"
    end
  end

  describe "GET 'unsilence_check'" do
    it "returns http success" do
      # todo
      # get 'unsilence_check', {:client => 1, :check => 1}
      # response.code.should eq "200"
    end
  end

  describe "GET 'unslience_client'" do
    it "returns http success" do
      # todo
      # get 'unslience_client', {:client => 1}
      # response.code.should eq "200"
    end
  end

end


text:
namespace Tournamentz.DAL.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class AddedTestTodoEntries : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.TodoEntries",
                c => new
                {
                    Id = c.Guid(nullable: false),
                    Name = c.String(),
                    Difficulty = c.Int(nullable: false),
                    CreatedById = c.Guid(nullable: false),
                    CreatedDate = c.DateTime(nullable: false),
                    LastUpdatedById = c.Guid(),
                    LastUpdatedDate = c.DateTime(),
                })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.ApplicationUsers", t => t.CreatedById, cascadeDelete: true)
                .ForeignKey("dbo.ApplicationUsers", t => t.LastUpdatedById)
                .Index(t => t.CreatedById)
                .Index(t => t.LastUpdatedById);
        }

        public override void Down()
        {
            DropForeignKey("dbo.TodoEntries", "LastUpdatedById", "dbo.ApplicationUsers");
            DropForeignKey("dbo.TodoEntries", "CreatedById", "dbo.ApplicationUsers");
            DropIndex("dbo.TodoEntries", new[] { "LastUpdatedById" });
            DropIndex("dbo.TodoEntries", new[] { "CreatedById" });
            DropTable("dbo.TodoEntries");
        }
    }
}


text:
<!DOCTYPE html>

    <base href=""/>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Kepler planet discoveries</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/theme.css">

    <link rel="stylesheet" href="planets.css"/>

            This is a comparison of mass, radius and average density of other worlds in relation to earth. The planets were discovered by NASA's kepler probe since 2011.

            You can download the .csv data here containing all planets scraped from NASA's site.

                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                    Radius
                </button>

Radius

Mass

Density

Eccentricity

Planet

Earth

With thanks to NASA! http://kepler.nasa.gov/Mission/discoveries/

https://github.com/korve/

https://korve.github.io/


text:
package com.javarush.task.task36.task3609;

/*
Рефакторинг MVC

Перемести некоторые методы в нужные классы, что бы получить паттерн MVC.
Если необходимо — внеси изменения в метод main, которые отражают внесенные тобой изменения.
Поведение программы при этом не должно измениться.
НЕ изменяй названия классов, методов и полей.

Требования:
1. Вывод программы должен остаться без изменений.
2. Необходимо переместить метод void speedUp(int) из класса CarModel в класс CarController.
3. Необходимо переместить метод void speedDown(int) из класса CarModel в класс CarController.
4. В методе main класса Solution метод speedUp необходимо вызывать у контроллера, а не у модели.
5. В методе main класса Solution метод speedDown необходимо вызывать у контроллера, а не у модели.
*/

public class Solution {
    public static void main(String[] args) {
        //Fetch car record from the database
        CarModel model = retrieveCarFromDatabase();

        //Create a view : to show car's speed on speedometer(console)
        SpeedometerView view = new SpeedometerView();

        CarController controller = new CarController(model, view);
        controller.updateView();

        //Update model data
        controller.speedUp(15);
        controller.updateView();

        //Update model data
        controller.speedUp(50);
        controller.updateView();

        //Update model data
        controller.speedDown(7);
        controller.updateView();
    }

    private static CarModel retrieveCarFromDatabase() {
        CarModel currentCar = new CarModel();
        currentCar.setBrand("Nissan");
        currentCar.setModel("Almera classic");
        currentCar.setSpeed(0);
        currentCar.setMaxSpeed(200);
        return currentCar;
    }
}


text:
package com.intel.analytics.bigdl.integration.torch

import com.intel.analytics.bigdl.nn.MulConstant
import com.intel.analytics.bigdl.tensor.Tensor

import scala.util.Random

@com.intel.analytics.bigdl.tags.Serial
class MulConstantSpec extends TorchSpec {
    "A MulConstant Module " should "generate correct output and grad" in {
    torchCheck()
    val module = new MulConstant[Double](10)
    val input = Tensor[Double](1, 5).apply1(e => Random.nextDouble())
    val gradOutput = Tensor[Double](1, 5).apply1(e => Random.nextDouble())

    val code = "module = nn.MulConstant(10)\n" +
      "output = module:forward(input)\n" +
      "gradInput = module:backward(input, gradOutput)\n"

    val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
      Array("output", "gradInput"))

    val luaOutput1 = torchResult("output").asInstanceOf[Tensor[Double]]
    val luaOutput2 = torchResult("gradInput").asInstanceOf[Tensor[Double]]

    val start = System.nanoTime()
    val output = module.forward(input)
    val gradInput = module.backward(input, gradOutput)
    val end = System.nanoTime()
    val scalaTime = end - start

    luaOutput1 should be(output)
    luaOutput2 should be(gradInput)

    println("Test case : MulConstant, Torch : " + luaTime +
      " s, Scala : " + scalaTime / 1e9 + " s")
  }
}


text:
package scrupal.store.reactivemongo

import reactivemongo.api.commands.bson._

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random

import reactivemongo.api.indexes.Index
import reactivemongo.api._
import reactivemongo.bson._
import reactivemongo.api.commands._

import play.api.libs.iteratee.Iteratee

/** An Abstraction For Easier Access to MongoDB Collections
  * Provides a variety of useful methods assuming that the collection holds instances of `Model` and those instances
  * are indexed by `Id`.
 * A DAO defines how to work with a specific collection.
 *
 * @tparam Model The representation of a document in the collection, typically a case class that extends Storable[Id]
 * @tparam Id The type of the _id field in the document which must guarantee uniqueness.
 */
abstract class DataAccessObject[Model <: Storable[Id],Id] extends DataAccessInterface[Model,Id]
{
  import BSONValueBuilder._

  type Reader = BSONDocumentReader[Model]
  type Writer = BSONDocumentWriter[Model]

  implicit val reader : Reader
  implicit val writer : Writer
  implicit val converter : Converter

  /**
   * Returns the number of documents in this collection matching the given selector.
   *
   * @param selector Selector document which may be empty.
   */
  def count(selector: BSONDocument, limit: Int = 0)(implicit ec: ExecutionContext): Future[Int] = {
    import BSONCountCommandImplicits._
    val command = BSONCountCommand.Count(doc=selector, limit)
    collection.runCommand(command).map(_.value)
  }

  /** Retrieves at most one model matching the given selector. */
  def findOne(selector: BSONDocument)
             (implicit ec: ExecutionContext): Future[Option[Model]] = {
    collection.find(selector).one[Model]
  }

  /** Find all matching instances of Model for the given selector and return them.
   * Note that you should only do this for smallish collection. For larger connections,
    * page through them with the [[findByPage]] method.
   *
   * @param selector Document for selecting the instances
   * @param sort Document for sorting the instances, if any.
   */
  def findAll(selector: BSONDocument, sort: BSONDocument = $empty)
             (implicit ec: ExecutionContext): Future[Seq[Model]] = {
    collection.find(selector).sort(sort).cursor[Model].collect[Seq]()
  }

  /** Find matching instances of Model for the given selector and return a sorted page of them
   * This allows you to constrain the size of the result set so you don't unload too many instances into memory.
   *
   * @param selector Document for selecting the instances.
   * @param page The page number to retrieve (0-based).
   * @param pageSize Maximum number of elements in each page.
    * @param sort Document for sorting the instances, if any.
   */
  def findByPage(selector: BSONDocument, page: Int, pageSize: Int, sort: BSONDocument = $empty)
          (implicit ec: ExecutionContext): Future[Seq[Model]] = {

    collection.find(selector).sort(sort)
      .options(QueryOpts(skipN = (page-1)*pageSize, batchSizeN = pageSize))
      .cursor[Model].collect[Seq](pageSize)
  }
  /**
   * Updates and returns a single model. It returns the old document by default.
   *
   * @param selector The selection criteria for the update.
   * @param update Performs an update of the selected model.
   * @param sort Determines which model the operation updates if the query selects multiple models.
   *             findAndUpdate() updates the first model in the sort order specified by this argument.
   * @param fetchNewObject When true, returns the updated model rather than the original.
   * @param upsert When true, findAndUpdate() creates a new model if no model matches the query.
   */
  def findAndUpdate(selector: BSONDocument, update: BSONDocument, sort: BSONDocument,fetchNewObject: Boolean = true,
                    upsert: Boolean = false)
                   (implicit ec: ExecutionContext): Future[Option[Model]]= {

    import BSONFindAndModifyImplicits._
    val command = BSONFindAndModifyCommand.FindAndModify (
      query = selector, modify = BSONFindAndModifyCommand.Update(update, fetchNewObject), upsert,
      if (sort == BSONDocument.empty) None else Some(sort)
    )

    collection.runCommand(command).map( _.result[Model] )
  }

  /** Find an object, remove it, and return it.
    *
    * @param selector
    * @param sort
    * @param ec
    * @return
    */

   def findAndRemove(selector: BSONDocument, sort: BSONDocument = BSONDocument.empty)
                    (implicit ec: ExecutionContext): Future[Option[Model]] = {

    import BSONFindAndModifyImplicits._
    val command = BSONFindAndModifyCommand.FindAndModify (
      query = selector,
      modify = BSONFindAndModifyCommand.Remove,
      sort = if (sort == BSONDocument.empty) None else Some(sort)
    )
    collection.runCommand(command).map(_.result[Model])
  }

  /** Find a random instance matching the selector provided.
    * This method obtains the size of the collection and then attempts to find a random document within it
    * @param selector Document for selecting the instances
    * @param ec execution context to run in
    * @return A future to an option of the instance of the Model
    */
  def findRandom(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[Model]] = {
    for {
      count <- count(selector)
      index = if (count == 0) 0 else Random.nextInt(count)
      random <- collection.find(selector).options(QueryOpts(skipN = index, batchSizeN = 1)).one[Model]
    } yield random
  }

  /** Inserts the given model. */
  def insert(obj: Model, writeConcern: GetLastError = defaultWriteConcern)
            (implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.insert(obj, writeConcern)
  }

  /**
   * Bulk inserts multiple models.
   *
   * @param objs A collection of model objects (any traversable collection type)
   * @param bulkSize The size of the bulk insert
   * @param bulkByteSize The size in bytes of the bulk insert
   * @return The number of successful insertions.
   */
  def bulkInsert(objs: TraversableOnce[Model],
                  bulkSize: Int /*= bulk.MaxDocs*/, bulkByteSize: Int /*= bulk.MaxBulkSize*/)
                (implicit ec: ExecutionContext): Future[Int] = {
    /*
    val enumerator = Enumerator.enumerate(objs)
    collection.bulkInsert(enumerator, bulkSize, bulkByteSize) map { result ⇒
      mappedDocuments.map(lifeCycle.postPersist)
      result
    }
    */
    Future { 0 }
    ???
  }

  /**
   * Updates the documents matching the given selector.
   *
   * @param selector Selector query.
   * @param update Update query.
   * @param writeConcern Write concern which defaults to defaultWriteConcern.
   * @param upsert Create the document if it does not exist.
   * @param multi Update multiple documents.
   * @tparam U Type of the update query.
   */
  def update[U <: BSONDocumentWriter[Model]]
    (selector: Model, update: U, writeConcern: GetLastError = defaultWriteConcern,
     upsert: Boolean = false, multi: Boolean = false)
    (implicit ec: ExecutionContext, u: BSONDocumentWriter[U]): Future[WriteResult] = {
      collection.update(writer.write(selector), u.write(update), writeConcern, upsert, multi)
  }

  /**
   * Updates the document with the given `id`.
   *
   * @param id ID of the document that will be updated.
   * @param update Update query.
   * @param writeConcern Write concern which defaults to defaultWriteConcern.
   * @tparam U Type of the update query.
   */
  def updateById[U <: BSONDocumentWriter[Model]]
    (id: Id, update: U,writeConcern: GetLastError = defaultWriteConcern)
    (implicit ec: ExecutionContext, updateWriter: BSONDocumentWriter[U]): Future[WriteResult] = {
      collection.update($id(id), updateWriter.write(update), writeConcern)
  }

  /**
   * Removes model(s) matching the given selector.
   *
   * In order to remove multiple documents `firstMatchOnly` has to be `false`.
   *
   * @param selector Selector document.
   * @param writeConcern Write concern defaults to `defaultWriteConcern`.
   * @param firstMatchOnly Remove only the first matching document.
   */
  def remove(selector: BSONDocument, firstMatchOnly: Boolean = false, writeConcern: GetLastError = defaultWriteConcern)
            (implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove(selector, writeConcern, firstMatchOnly)
  }

  /** Removes the document with the given ID. */
  def removeById(id: Id, writeConcern: GetLastError = defaultWriteConcern)
                (implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove($id(id), writeConcern)
  }

  /** Removes all documents in this collection. */
  def removeAll(writeConcern: GetLastError = defaultWriteConcern)
               (implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove(query = BSONDocument.empty, writeConcern = writeConcern, firstMatchOnly = false)
  }

  def drop(implicit ec: ExecutionContext): Future[Unit] = {
    collection.drop()
  }

  /**
   * Folds the documents matching the given selector by applying the function `f`.
   *
   * @param selector Selector document.
   * @param sort Sorting document.
   * @param state Initial state for the fold operation.
   * @param f Folding function.
   * @tparam A Type of fold result.
   */
  def fold[A](selector: BSONDocument, sort: BSONDocument, state: A)(f: (A, Model) ⇒ A)
             (implicit ec: ExecutionContext): Future[A] = {
    collection.find(selector).sort(sort).cursor[Model]
      .enumerate()
      .apply(Iteratee.fold(state)(f))
      .flatMap(i ⇒ i.run)

  }

  /**
   * Iterates over the documents matching the given selector and applies the function `f`.
   *
   * @param selector Selector document.
   * @param sort Sorting document.
   * @param f function to be applied.
   */
  def foreach(selector: BSONDocument, sort: BSONDocument)(f: (Model) ⇒ Unit)
             (implicit ec: ExecutionContext): Future[Unit] = {
    collection.find(selector).sort(sort).cursor[Model]
      .enumerate()
      .apply(Iteratee.foreach(f))
      .flatMap(i ⇒ i.run)
  }

  /**
   * Lists indexes that are currently ensured in this collection.
   *
   * This list may not be equal to `autoIndexes` in case of index creation failure.
   */
  def listIndices()(implicit ec: ExecutionContext): Future[List[Index]] = {
    collection.indexesManager.list()
  }

  /**
   * The list of indexes to be ensured on DAO load.
   *
   * Because of Scala initialization order there are exactly 2 ways
   * of defining auto indexes.
   *
   * First way is to use an '''early definition''':
   *
   * {{{
   * object PersonDao extends {
   *   override val autoIndexes = Seq(
   *     Index(Seq("name" -> IndexType.Ascending), unique = true, background = true),
   *     Index(Seq("age" -> IndexType.Ascending), background = true))
   * } with BsonDao[Person, BSONObjectID](MongoContext.db, "persons")
   * }}}
   *
   * Second way is to '''override def'''. Be careful __not to change declaration to `val` instead of `def`__.
   *
   * {{{
   * object PersonDao extends BsonDao[Person, BSONObjectID](MongoContext.db, "persons") {
   *
   *   override def autoIndexes = Seq(
   *     Index(Seq("name" -> IndexType.Ascending), unique = true, background = true),
   *     Index(Seq("age" -> IndexType.Ascending), background = true))
   * }
   * }}}
   */

  /** Ensures indexes defined by `autoIndexes`. */
  def ensureIndices(implicit ec: ExecutionContext): Future[Traversable[Boolean]] = {
    Future sequence {
      indices map { index ⇒
        collection.indexesManager.ensure(index)
      }
    }
  }
}

abstract class IdentifierDAO[Model <: Storable[Symbol]] extends DataAccessObject[Model,Symbol] {
  implicit val converter = (id: Symbol) ⇒ BSONString(id.name)
}


text:
var common = require('../casper_lib/common.js').common;

common.start_and_log_in();
casper.verbonse = true;

casper.waitForSelector('#new_message_content', function () {
    casper.test.info('compose box visible');
    casper.page.sendEvent('keypress', "c"); // brings up the compose box
});

casper.then(function () {
    casper.fill('form[action^="/json/messages"]', {
        stream:  'Verona',
        subject: 'Test mention all'
    });
});
common.select_item_via_typeahead('#new_message_content', '@all', 'all');

casper.waitForText("Are you sure you want to message all", function () {
    casper.test.info('Warning message appears when mentioning @all');
    casper.test.assertSelectorHasText('.compose-all-everyone', 'Are you sure you want to message all');
});

casper.then( function () {
    common.turn_off_press_enter_to_send();
    casper.test.info('Click Send Button');
    casper.click('#compose-send-button');
});
casper.waitForText("Please remove @all", function () {
    casper.test.info('Error message appears when attempting to send a message without acknowledging the @all mention warning');
    casper.test.assertSelectorHasText('#error-msg', "Please remove @all / @everyone or acknowledge that you will be spamming everyone!");
});

casper.waitForSelector('.compose-all-everyone-confirm', function () {
    casper.click('.compose-all-everyone-confirm');
}, function () {
    casper.test.error('Could not click confirm button.');
});

casper.waitWhileVisible('.compose-all-everyone-confirm', function () {
    casper.test.info('Check that error messages are gone.');
    casper.test.assertNotVisible('.compose-all-everyone-msg');
    casper.test.assertNotVisible('#send-status');
});

casper.then( function () {
    casper.test.info('Click Send Button');
    casper.click('#compose-send-button');
});

casper.then( function () {
    common.expected_messages('zhome', ['Verona > Test mention all'],
     ["
@all
"]
    );
});

common.then_log_out();

casper.run(function () {
    casper.test.done();
});


text:
<?xml version="1.0" encoding="utf-8"?>

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        style="@style/InLayoutPadding"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@drawable/view_separator"
        android:showDividers="end"
        android:orientation="vertical">

        <TextView
            style="@style/InLayoutPadding"
            android:id="@+id/trailer_head"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/trailer_heading"
            android:textStyle="bold"
            android:textSize="@dimen/info_textSize"
            android:textColor="@color/primary_dark"
            android:gravity="bottom"/>

        <LinearLayout
            style="@style/InLayoutPadding"
            android:id="@+id/trailer_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="0dp"
            android:paddingBottom="0dp"
            android:visibility="visible"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/InLayoutPadding">

            <TextView
                android:id="@+id/review_head"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/reviews_heading"
                android:textStyle="bold"
                android:textSize="@dimen/info_textSize"
                android:textColor="@color/primary_dark"
                android:gravity="bottom"/>

        </RelativeLayout>

        <!--<include layout="@layout/review_list_layout" />-->
        <LinearLayout
            style="@style/InLayoutPadding"
            android:id="@+id/review_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="0dp"
            android:paddingBottom="@dimen/margin_default"
            android:paddingEnd="@dimen/margin_large"
            android:paddingStart="@dimen/margin_large"
            android:visibility="visible"/>

    </LinearLayout>
</androidx.core.widget.NestedScrollView>


text:
import { Component, Inject } from "@angular/core";
import { MD_DIALOG_DATA } from '@angular/material';

@Component({
	templateUrl: "confirm-dialog.component.html"
})
export class ConfirmDialogComponent {

	private modelTitle: string;

	constructor(@Inject(MD_DIALOG_DATA) modelTitle: string) {
		this.modelTitle = modelTitle;
	}
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.identitylink.service.impl.persistence.entity.data.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.engine.common.impl.db.AbstractDataManager;
import org.flowable.engine.common.impl.db.CachedEntityMatcher;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityImpl;
import org.flowable.identitylink.service.impl.persistence.entity.data.IdentityLinkDataManager;
import org.flowable.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByProcInstMatcher;

/**
 * @author Joram Barrez
 */
public class MybatisIdentityLinkDataManager extends AbstractDataManager<IdentityLinkEntity> implements IdentityLinkDataManager {

    protected CachedEntityMatcher<IdentityLinkEntity> identityLinkByProcessInstanceMatcher = new IdentityLinksByProcInstMatcher();

    @Override
    public Class<? extends IdentityLinkEntity> getManagedEntityClass() {
        return IdentityLinkEntityImpl.class;
    }

    @Override
    public IdentityLinkEntity create() {
        return new IdentityLinkEntityImpl();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinksByTaskId(String taskId) {
        return getDbSqlSession().selectList("selectIdentityLinksByTask", taskId);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinksByProcessInstanceId(String processInstanceId) {
        return getList("selectIdentityLinksByProcessInstance", processInstanceId, identityLinkByProcessInstanceMatcher, true);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinksByProcessDefinitionId(String processDefinitionId) {
        return getDbSqlSession().selectList("selectIdentityLinksByProcessDefinition", processDefinitionId);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinkByTaskUserGroupAndType(String taskId, String userId, String groupId, String type) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("taskId", taskId);
        parameters.put("userId", userId);
        parameters.put("groupId", groupId);
        parameters.put("type", type);
        return getDbSqlSession().selectList("selectIdentityLinkByTaskUserGroupAndType", parameters);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinkByProcessInstanceUserGroupAndType(String processInstanceId, String userId, String groupId, String type) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("processInstanceId", processInstanceId);
        parameters.put("userId", userId);
        parameters.put("groupId", groupId);
        parameters.put("type", type);
        return getDbSqlSession().selectList("selectIdentityLinkByProcessInstanceUserGroupAndType", parameters);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<IdentityLinkEntity> findIdentityLinkByProcessDefinitionUserAndGroup(String processDefinitionId, String userId, String groupId) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("processDefinitionId", processDefinitionId);
        parameters.put("userId", userId);
        parameters.put("groupId", groupId);
        return getDbSqlSession().selectList("selectIdentityLinkByProcessDefinitionUserAndGroup", parameters);
    }

    @Override
    public void deleteIdentityLinksByProcDef(String processDefId) {
        getDbSqlSession().delete("deleteIdentityLinkByProcDef", processDefId, IdentityLinkEntityImpl.class);
    }

}


text:
require File.dirname(__FILE__) + '/payflow/payflow_common_api'
require File.dirname(__FILE__) + '/payflow/payflow_express_response'
require File.dirname(__FILE__) + '/paypal_express_common'

module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class PayflowExpressGateway < Gateway
      include PayflowCommonAPI
      include PaypalExpressCommon

      self.test_redirect_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'
      self.homepage_url = 'https://www.paypal.com/cgi-bin/webscr?cmd=xpt/merchant/ExpressCheckoutIntro-outside'
      self.display_name = 'PayPal Express Checkout'

      def authorize(money, options = {})
        requires!(options, :token, :payer_id)
        request = build_sale_or_authorization_request('Authorization', money, options)
        commit(request)
      end

      def purchase(money, options = {})
        requires!(options, :token, :payer_id)
        request = build_sale_or_authorization_request('Sale', money, options)
        commit(request)
      end

      def credit(money, identification, options = {})
        request = build_reference_request(:credit, money, identification, options)
        commit(request)
      end

      def setup_authorization(money, options = {})
        requires!(options, :return_url, :cancel_return_url)

        request = build_setup_express_sale_or_authorization_request('Authorization', money, options)
        commit(request)
      end

      def setup_purchase(money, options = {})
        requires!(options, :return_url, :cancel_return_url)

        request = build_setup_express_sale_or_authorization_request('Sale', money, options)
        commit(request)
      end

      def details_for(token)
        request = build_get_express_details_request(token)
        commit(request)
      end

      private
      def build_get_express_details_request(token)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag! 'GetExpressCheckout' do
          xml.tag! 'Authorization' do
            xml.tag! 'PayData' do
              xml.tag! 'Tender' do
                xml.tag! 'PayPal' do
                  xml.tag! 'Token', token
                end
              end
            end
          end
        end
        xml.target!
      end

      def build_setup_express_sale_or_authorization_request(action, money, options = {})
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag! 'SetExpressCheckout' do
          xml.tag! action do
            xml.tag! 'PayData' do
              xml.tag! 'Invoice' do
                xml.tag! 'CustIP', options[:ip] unless options[:ip].blank?
                xml.tag! 'InvNum', options[:order_id] unless options[:order_id].blank?
                xml.tag! 'Description', options[:description] unless options[:description].blank?

                billing_address = options[:billing_address] || options[:address]
                add_address(xml, 'BillTo', billing_address, options) if billing_address
                add_address(xml, 'ShipTo', options[:shipping_address], options) if options[:shipping_address]

                xml.tag! 'TotalAmt', amount(money), 'Currency' => options[:currency] || currency(money)
              end

              xml.tag! 'Tender' do
                add_paypal_details(xml, options)
              end
            end
          end
        end
        xml.target!
      end

      def build_sale_or_authorization_request(action, money, options)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag! 'DoExpressCheckout' do
          xml.tag! action do
            xml.tag! 'PayData' do
              xml.tag! 'Invoice' do
                xml.tag! 'TotalAmt', amount(money), 'Currency' => options[:currency] || currency(money)
              end
              xml.tag! 'Tender' do
                add_paypal_details xml, options
              end
            end
          end
        end
        xml.target!
      end

      def add_paypal_details(xml, options)
         xml.tag! 'PayPal' do
          xml.tag! 'EMail', options[:email] unless options[:email].blank?
          xml.tag! 'ReturnURL', options[:return_url] unless options[:return_url].blank?
          xml.tag! 'CancelURL', options[:cancel_return_url] unless options[:cancel_return_url].blank?
          xml.tag! 'NotifyURL', options[:notify_url] unless options[:notify_url].blank?
          xml.tag! 'PayerID', options[:payer_id] unless options[:payer_id].blank?
          xml.tag! 'Token', options[:token] unless options[:token].blank?
          xml.tag! 'NoShipping', options[:no_shipping] ? '1' : '0'
          xml.tag! 'AddressOverride', options[:address_override] ? '1' : '0'
          xml.tag! 'ButtonSource', application_id.to_s.slice(0,32) unless application_id.blank?

          # Customization of the payment page
          xml.tag! 'PageStyle', options[:page_style] unless options[:page_style].blank?
          xml.tag! 'HeaderImage', options[:header_image] unless options[:header_image].blank?
          xml.tag! 'HeaderBackColor', options[:header_background_color] unless options[:header_background_color].blank?
          xml.tag! 'HeaderBorderColor', options[:header_border_color] unless options[:header_border_color].blank?
          xml.tag! 'PayflowColor', options[:background_color] unless options[:background_color].blank?
        end
      end

      def build_response(success, message, response, options = {})
        PayflowExpressResponse.new(success, message, response, options)
      end
    end
  end
end


text:
#ifndef PCL_FILTERS_SAMPLING_SURFACE_NORMAL_H_
#define PCL_FILTERS_SAMPLING_SURFACE_NORMAL_H_

#include <pcl/filters/filter_indices.h>
#include <time.h>
#include <limits.h>

namespace pcl
{
  /** \brief @b SamplingSurfaceNormal divides the input space into grids until each grid contains a maximum of N points,
    * and samples points randomly within each grid. Normal is computed using the N points of each grid. All points
    * sampled within a grid are assigned the same normal.
    *
    * \author Aravindhan K Krishnan. This code is ported from libpointmatcher (https://github.com/ethz-asl/libpointmatcher)
    * \ingroup filters
    */
  template<typename PointT>
  class SamplingSurfaceNormal: public FilterIndices<PointT>
  {
    using FilterIndices<PointT>::filter_name_;
    using FilterIndices<PointT>::getClassName;
    using FilterIndices<PointT>::indices_;
    using FilterIndices<PointT>::input_;

    typedef typename FilterIndices<PointT>::PointCloud PointCloud;
    typedef typename PointCloud::Ptr PointCloudPtr;
    typedef typename PointCloud::ConstPtr PointCloudConstPtr;

    typedef typename Eigen::Matrix<float, Eigen::Dynamic, 1> Vector;

    public:
      /** \brief Empty constructor. */
      SamplingSurfaceNormal () :
        sample_ (10), seed_ (static_cast<unsigned int> (time (NULL))), ratio_ ()
      {
        filter_name_ = "SamplingSurfaceNormal";
        srand (seed_);
      }

      /** \brief Set maximum number of samples in each grid
        * \param[in] sample maximum number of samples in each grid
        */
      inline void
      setSample (unsigned int sample)
      {
        sample_ = sample;
      }

      /** \brief Get the value of the internal \a sample parameter. */
      inline unsigned int
      getSample () const
      {
        return (sample_);
      }

      /** \brief Set seed of random function.
        * \param[in] seed the input seed
        */
      inline void
      setSeed (unsigned int seed)
      {
        seed_ = seed;
        srand (seed_);
      }

      /** \brief Get the value of the internal \a seed parameter. */
      inline unsigned int
      getSeed () const
      {
        return (seed_);
      }

      /** \brief Set ratio of points to be sampled in each grid
        * \param[in] ratio sample the ratio of points to be sampled in each grid
        */
      inline void
      setRatio (float ratio)
      {
        ratio_ = ratio;
      }

      /** \brief Get the value of the internal \a ratio parameter. */
      inline float
      getRatio () const
      {
        return ratio_;
      }

    protected:

      /** \brief Maximum number of samples in each grid. */
      unsigned int sample_;
      /** \brief Random number seed. */
      unsigned int seed_;
      /** \brief Ratio of points to be sampled in each grid */
      float ratio_;

      /** \brief Sample of point indices into a separate PointCloud
        * \param[out] output the resultant point cloud
        */
      void
      applyFilter (PointCloud &output);

      /** \brief Sample of point indices
        * \param indices the resultant point cloud indices
        */
      void
      applyFilter (std::vector<int>&)
      {
      }

    private:

      /** \brief @b CompareDim is a comparator object for sorting across a specific dimenstion (i,.e X, Y or Z)
       */
      struct CompareDim
      {
        /** \brief The dimension to sort */
        const int dim;
        /** \brief The input point cloud to sort */
        const pcl::PointCloud <PointT>& cloud;

        /** \brief Constructor. */
        CompareDim (const int dim, const pcl::PointCloud <PointT>& cloud) : dim (dim), cloud (cloud)
        {
        }

        /** \brief The operator function for sorting. */
        bool
        operator () (const int& p0, const int& p1)
        {
          if (dim == 0)
            return (cloud.points[p0].x < cloud.points[p1].x);
          else if (dim == 1)
            return (cloud.points[p0].y < cloud.points[p1].y);
          else if (dim == 2)
            return (cloud.points[p0].z < cloud.points[p1].z);
          return (false);
        }
      };

      /** \brief Finds the max and min values in each dimension
        * \param[in] cloud the input cloud
        * \param[out] max_vec the max value vector
        * \param[out] min_vec the min value vector
        */
      void
      findXYZMaxMin (const PointCloud& cloud, Vector& max_vec, Vector& min_vec);

      /** \brief Recursively partition the point cloud, stopping when each grid contains less than sample_ points
        *  Points are randomly sampled when a grid is found
        * \param cloud
        * \param first
        * \param last
        * \param min_values
        * \param max_values
        * \param indices
        * \param[out] outcloud output the resultant point cloud
        */
      void
      partition (const PointCloud& cloud, const int first, const int last,
                 const Vector min_values, const Vector max_values,
                 std::vector<int>& indices, PointCloud& outcloud);

      /** \brief Randomly sample the points in each grid.
        * \param[in] data
        * \param[in] first
        * \param[in] last
        * \param[out] indices
        * \param[out] output the resultant point cloud
        */
      void
      samplePartition (const PointCloud& data, const int first, const int last,
                       std::vector<int>& indices, PointCloud& outcloud);

      /** \brief Returns the threshold for splitting in a given dimension.
        * \param[in] cloud the input cloud
        * \param[in] cut_dim the input dimension (0=x, 1=y, 2=z)
        * \param[in] cut_index the input index in the cloud
        */
      float
      findCutVal (const PointCloud& cloud, const int cut_dim, const int cut_index);

      /** \brief Computes the normal for points in a grid. This is a port from features to avoid features dependency for
        * filters
        * \param[in] cloud The input cloud
        * \param[out] normal the computed normal
        * \param[out] curvature the computed curvature
        */
      void
      computeNormal (const PointCloud& cloud, Eigen::Vector4f &normal, float& curvature);

      /** \brief Computes the covariance matrix for points in the cloud. This is a port from features to avoid features dependency for
        * filters
        * \param[in] cloud The input cloud
        * \param[out] covariance_matrix the covariance matrix
        * \param[out] centroid the centroid
        */
      unsigned int
      computeMeanAndCovarianceMatrix (const pcl::PointCloud<PointT> &cloud,
                                      Eigen::Matrix3f &covariance_matrix,
                                      Eigen::Vector4f &centroid);

      /** \brief Solve the eigenvalues and eigenvectors of a given 3x3 covariance matrix, and estimate the least-squares
        * plane normal and surface curvature.
        * \param[in] covariance_matrix the 3x3 covariance matrix
        * \param[out] (nx ny nz) plane_parameters the resultant plane parameters as: a, b, c, d (ax + by + cz + d = 0)
        * \param[out] curvature the estimated surface curvature as a measure of
        */
      void
      solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,
                            float &nx, float &ny, float &nz, float &curvature);
  };
}
#endif  //#ifndef PCL_FILTERS_SAMPLING_SURFACE_NORMAL_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270"
        android:endColor="#00000000"
        android:startColor="#30000000"
        android:type="linear" />

</shape>


text:
import Errors from "./Errors";

export default class Form {
    /**
     * Create a new Form instance.
     *
     * @param data
     */
    constructor(data) {
        this.original = JSON.parse(JSON.stringify(data));
        this.data = data;
        this.hasChanges = false;
        this.isSubmitting = false;

        this.errors = new Errors();
    }

    /**
     * Send a POST request to the given URL.
     *
     * @param {string} url
     */
    post(url) {
        this.data["_method"] = "POST";

        return this.submit("post", url);
    }

    /**
     * Send a PUT request to the given URL.
     * .
     * @param {string} url
     */
    put(url) {
        this.data["_method"] = "PUT";

        return this.submit("post", url);
    }

    /**
     * Send a PATCH request to the given URL.
     * .
     * @param {string} url
     */
    patch(url) {
        this.data["_method"] = "PATCH";

        return this.submit("post", url);
    }

    /**
     * Send a DELETE request to the given URL.
     *
     * @param {string} url
     */
    delete(url) {
        this.data["_method"] = "DELETE";

        return this.submit("post", url);
    }

    /**
     * Mark this form as having been changed.
     */
    markAsChanged() {
        this.hasChanges = true;
    }

    /**
     * Submit the form.
     *
     * @param type
     * @param url
     * @returns {Promise}
     */
    submit(type, url) {
        this.isSubmitting = true;

        return new Promise((resolve, reject) => {
            axios({
                method: type,
                url: url,
                data: this.generateFormData(),
            })
                .then(response => {
                    this.isSubmitting = false;
                    this.hasChanges = false;

                    this.errors.clear();

                    resolve(response.data);
                })
                .catch(error => {
                    this.isSubmitting = false;

                    this.onFail(error);

                    reject(error.response.data);
                });
        });
    }

    /**
     * Handle a failed form submission.
     *
     * @param error
     */
    onFail(error) {
        if (error.response) {
            switch (error.response.status) {
            case 401:
                toastr.error("You need to be logged in before you can do that!", "Not logged in");

                break;
            case 403:
                toastr.error("You weren't allowed to do that.", "Unauthorized");

                if (typeof error.response.data.redirect != "undefined") {
                    window.location.href = error.response.data.redirect;
                }

                break;
            case 422:
                if (typeof error.response.data == "string") {
                    toastr.error(error.response.data, "Whoops!");

                    break;
                }

                toastr.error("Some issues were found with your submission that you need to fix.", "Whoops!");

                this.errors.record(error.response.data);

                break;
            default:
                toastr.error("Some unrecognized response came back from the server.", "Whoops!");
            }
        }
        else {
            toastr.error("For some reason, there was no response back from the server.  Did your internet go out?", "Whoops!");
        }
    }

    /**
     * Generate a FormData object from the given data.
     *
     * @returns {FormData}
     */
    generateFormData() {
        let formData = new FormData();

        _.forOwn(this.data, (value, key) => {
            this.formatFormData(formData, value, key);
        });

        return formData;
    }

    /**
     * Appends to FormData in a way based on the type of data presented in value.
     *
     * @param formData
     * @param value
     * @param key
     */
    formatFormData(formData, value, key) {
        if (Array.isArray(value)) {
            // PHP requires each array field key to be concatenated with an "[]".
            for (let i = 0; i < value.length; i++)
                this.formatFormData(formData, value[i], key + `[${i}]`);
        }
        else if (value === null) {
            formData.append(key, "");
        }
        else if (typeof value === "boolean") {
            if (value)
                formData.append(key, 1);
            else
                formData.append(key, 0);
        }
        else if (typeof value === "object" && !(value instanceof File)) {
            _.forOwn(value, (innerObjectValue, innerObjectKey) => {
                this.formatFormData(formData, innerObjectValue, `${key}[${innerObjectKey}]`);
            });
        }
        else {
            formData.append(key, value);
        }
    }
}


text:
from platformio import util
from platformio.exception import PlatformioException, UserSideException

class PackageException(PlatformioException):
    pass

class ManifestException(PackageException):
    pass

class UnknownManifestError(ManifestException):
    pass

class ManifestParserError(ManifestException):
    pass

class ManifestValidationError(ManifestException):
    def __init__(self, messages, data, valid_data):
        super().__init__()
        self.messages = messages
        self.data = data
        self.valid_data = valid_data

    def __str__(self):
        return (
            "Invalid manifest fields: %s. \nPlease check specification -> "
            "https://docs.platformio.org/page/librarymanager/config.html"
            % self.messages
        )

class MissingPackageManifestError(ManifestException):

    MESSAGE = "Could not find one of '{0}' manifest files in the package"

class UnknownPackageError(UserSideException):

    MESSAGE = (
        "Could not find the package with '{0}' requirements for your system '%s'"
        % util.get_systype()
    )

class NotGlobalLibDir(UserSideException):

    MESSAGE = (
        "The `{0}` is not a PlatformIO project.\n\n"
        "To manage libraries in global storage `{1}`,\n"
        "please use `platformio lib --global {2}` or specify custom storage "
        "`platformio lib --storage-dir /path/to/storage/ {2}`.\n"
        "Check `platformio lib --help` for details."
    )


text:
import * as windows1251 from 'windows-1251';

var text:string = "some text", byteString:string, decodedText:string;

var version:string = windows1251.version;

var labels:string[] = windows1251.labels;

byteString = windows1251.encode(text);
byteString = windows1251.encode(text, { mode: 'html' });
byteString = windows1251.encode(text, { mode: 'fatal' });

decodedText = windows1251.decode(byteString);
decodedText = windows1251.decode(byteString, { mode: 'fatal' });
decodedText = windows1251.decode(byteString, { mode: 'replacement' });