text:
from south.utils import datetime_utils as datetime
from south.db import dbs
import south.db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        db = dbs['stats']
        db.dry_run = south.db.db.dry_run

        # Renaming fields in 'HoudiniToolUsage'
        db.rename_column('houdini_stats_houdinitoolusage', 'tool_type',
                         'tool_name')

    def backwards(self, orm):
        db = dbs['stats']
        db.dry_run = south.db.db.dry_run

        # Renaming fields in 'HoudiniToolUsage'
        db.rename_column('houdini_stats_houdinitoolusage', 'tool_name', 'tool_type')

    models = {
        u'houdini_stats.event': {
            'Meta': {'ordering': "('date',)", 'object_name': 'Event'},
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'show': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '40'})
        },
        u'houdini_stats.houdinicrash': {
            'Meta': {'ordering': "('date',)", 'object_name': 'HoudiniCrash'},
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'machine_config': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['houdini_stats.MachineConfig']"}),
            'stack_trace': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
            'type': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '20'})
        },
        u'houdini_stats.houdinitoolusage': {
            'Meta': {'ordering': "('date',)", 'object_name': 'HoudiniToolUsage'},
            'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_asset': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_builtin': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'machine_config': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['houdini_stats.MachineConfig']"}),
            'tool_creation_mode': ('django.db.models.fields.IntegerField', [], {}),
            'tool_name': ('django.db.models.fields.CharField', [], {'max_length': '60'})
        },
        u'houdini_stats.machine': {
            'Meta': {'object_name': 'Machine'},
            'hardware_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'houdini_stats.machineconfig': {
            'Meta': {'ordering': "('creation_date',)", 'object_name': 'MachineConfig'},
            'config_hash': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
            'cpu_info': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'graphics_card': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
            'graphics_card_version': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
            'houdini_build_number': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '10'}),
            'houdini_major_version': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'houdini_minor_version': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'ip_address': ('django.db.models.fields.CharField', [], {'max_length': '25', 'blank': 'True'}),
            'is_apprentice': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'machine': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['houdini_stats.Machine']"}),
            'number_of_processors': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'}),
            'operating_system': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
            'product': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
            'raw_user_info': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
            'system_memory': ('django.db.models.fields.FloatField', [], {'default': '0', 'blank': 'True'}),
            'system_resolution': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'})
        },
        u'houdini_stats.uptime': {
            'Meta': {'ordering': "('date', 'number_of_seconds')", 'object_name': 'Uptime'},
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'machine_config': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['houdini_stats.MachineConfig']"}),
            'number_of_seconds': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
        }
    }

    complete_apps = ['houdini_stats']


text:
Astro.createValidator({
  name: 'unique',
  validate: function(fieldValue, fieldName) {
    var doc = this;
    var Class = doc.constructor;
    var Collection = Class.getCollection();

    // If a Class is not related with any collection then document is unique.
    if (!Collection) {
      return true;
    }

    // Prepare selector.
    var selector = {};
    selector[fieldName] = fieldValue;

    // If the "_id" fields is present, then object is being updated.
    // In this case, ignore the object itself.
    if (this._id) {
      selector._id = {
        $ne: this._id
      };
    }

    // Check if a record with the given field value exists.
    return _.isUndefined(Collection.findOne(selector));
  },
  events: {
    validationerror: function(e) {
      var fieldName = e.data.fieldName;

      e.setMessage(
        'The value of the "' + fieldName + '" field has to be unique'
      );
    }
  }
});

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe RepoViewModel do
  before (:each) do
    @metadata = PackageConfigurations.new
    @metadata.addConfiguration(PackageConfiguration.new("key1").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 1"))
    @metadata.addConfiguration(PackageConfiguration.new("key2").with(PackageConfiguration::REQUIRED, false).with(PackageConfiguration::SECURE, true).with(PackageConfiguration::DISPLAY_NAME, "Key 2"))
  end

  it "should create repo view model from metadata when repo is nil" do

    model = RepoViewModel.new @metadata, nil, "yum"
    model.properties.size.should == 2
    model.properties[0].name.should == "key1"
    model.properties[0].display_name.should == "Key 1"
    model.properties[0].value.should == nil
    model.properties[0].is_mandatory.should == true
    model.properties[0].is_secure.should == false
    model.properties[1].name.should == "key2"
    model.properties[1].display_name.should == "Key 2"
    model.properties[1].value.should == nil
    model.properties[1].is_mandatory.should == false
    model.properties[1].is_secure.should == true
    model.errors.isEmpty().should == true
    end

  it "should create repo view model from metadata when repo is provided" do
    secure_property = ConfigurationPropertyMother.create("key2", true, "v2")
    repo = PackageRepositoryMother.create("repo1", "repo1-name", "pluginid", "version1.0", Configuration.new([ConfigurationPropertyMother.create("key1", false, "v1"), secure_property].to_java(ConfigurationProperty)))
    model = RepoViewModel.new @metadata, repo, "yum"
    model.properties.size.should == 2
    model.properties[0].display_name.should == "Key 1"
    model.properties[0].value.should == "v1"
    model.properties[1].display_name.should == "Key 2"
    model.properties[1].value.should == secure_property.getEncryptedValue().getValue()
  end

  it "should create repo view model from metadata when repo doesn't have all configuration " do
    repo = PackageRepositoryMother.create("repo1", "repo1-name", "pluginid", "version1.0", Configuration.new([ConfigurationPropertyMother.create("key1", false, "v1")].to_java(ConfigurationProperty)))
    model = RepoViewModel.new @metadata, repo, "yum"
    model.properties.size.should == 2
    model.properties[0].display_name.should == "Key 1"
    model.properties[0].value.should == "v1"
    model.properties[1].display_name.should == "Key 2"
    model.properties[1].value.should == nil
  end

  it "should add error to model if plugin is missing" do
    repo = PackageRepositoryMother.create("repo1", "repo1-name", "pluginid", "version1.0", Configuration.new([ConfigurationPropertyMother.create("key1", false, "v1")].to_java(ConfigurationProperty)))
    model = RepoViewModel.new nil, repo, "yum"
    model.properties.size.should == 0
    model.errors.isEmpty().should == false
    model.errors.on("pluginId").should == "Associated plugin 'yum' not found. Please contact the Go admin to install the plugin."
  end
end


text:
import mimetypes

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.html import strip_tags
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from django.conf import settings

from bs4 import BeautifulSoup
from extended_choices import Choices

from geotrek.common.mixins import TimeStampedModelMixin, BasePublishableMixin

FLATPAGES_TARGETS = Choices(
    ('ALL', 'all', _('All')),
    ('MOBILE', 'mobile', _('Mobile')),
    ('HIDDEN', 'hidden', _('Hidden')),
    ('WEB', 'web', _('Web')),
)

class FlatPage(BasePublishableMixin, TimeStampedModelMixin):
    """
    Manage *Geotrek-rando* static pages from Geotrek admin.

    Historically, we started static pages as static HTML files within
    *Geotrek-rando* folders.
    """
    title = models.CharField(verbose_name=_(u'Title'), max_length=200,
                             db_column='titre')
    external_url = models.URLField(verbose_name=_(u'External URL'), blank=True,
                                   db_column='url_externe', default='',
                                   help_text=_('Link to external website instead of HTML content'))
    content = models.TextField(verbose_name=_(u'Content'), null=True, blank=True,
                               db_column='contenu',
                               help_text=_('HTML content'))
    target = models.CharField(verbose_name=_(u'Target'), max_length=12, choices=FLATPAGES_TARGETS,
                              db_column='cible', default=FLATPAGES_TARGETS.ALL)

    @property
    def slug(self):
        return slugify(self.title)

    class Meta:
        db_table = 'p_t_page'
        verbose_name = _(u'Flat page')
        verbose_name_plural = _(u'Flat pages')
        ordering = ['id']
        permissions = (
            ("read_flatpage", "Can read FlatPage"),
        )

    def __unicode__(self):
        return self.title

    def clean(self):
        html_content = ''
        for l in settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']:
            html_content += getattr(self, 'content_%s' % l[0], None) or ''

        # Test if HTML was filled
        # Use strip_tags() to catch empty tags (e.g. ``

``)
        if self.external_url and self.external_url.strip() and strip_tags(html_content):
            raise ValidationError(_('Choose between external URL and HTML content'))

    def parse_media(self):
        soup = BeautifulSoup(self.content or '')
        images = soup.findAll('img')
        results = []
        for image in images:
            url = image.get('src')
            if url is None:
                continue

            mt = mimetypes.guess_type(url, strict=True)[0]
            if mt is None:
                mt = 'application/octet-stream'

            results.append({
                'url': url,
                'title': image.get('title', ''),
                'alt': image.get('alt', ''),
                'mimetype': mt.split('/'),
            })

        return results

    @models.permalink
    def get_add_url(self):
        return ('admin:flatpages_flatpage_add', )

    @models.permalink
    def get_update_url(self):
        return ('admin:flatpages_flatpage_change', [self.pk])

    @models.permalink
    def get_delete_url(self):
        return ('admin:flatpages_flatpage_delete', [self.pk])


text:
[![Build Status](https://travis-ci.org/rvl/hsoz.svg?branch=master)](https://travis-ci.org/rvl/hsoz) [![Hackage](https://img.shields.io/hackage/v/hsoz.svg)](http://hackage.haskell.org/package/hsoz)

*hsoz* is a Haskell implementation of the Iron, Hawk, and Oz web
authentication protocols. These protocols originate from the OAuth2
standardisation process, but are designed to be simpler to implement
for the common case of web applications.

## Introduction

In the words of their principal designer:

**Iron** is a cryptographic utility for sealing a JSON object using
symmetric key encryption with message integrity verification. Or in
other words, it lets you encrypt an object, send it around (in
cookies, authentication credentials, etc.), then receive it back and
decrypt it. The algorithm ensures that the message was not tampered
with, and also provides a simple mechanism for password rotation.

**Hawk** is an HTTP authentication scheme using a message
authentication code (MAC) algorithm to provide partial HTTP request
cryptographic verification.

**Oz** is a web authorization protocol based on industry best
practices. Oz combines the Hawk authentication protocol with the
Iron encryption protocol to provide a simple to use and secure
solution for granting and authenticating third-party access to an
API on behalf of a user or an application.

## Documentation

The Haddock documentation is on [Hackage](http://hackage.haskell.org/package/hsoz)
and at https://rodney.id.au/docs/hsoz/.

 * [Network.Iron](http://hackage.haskell.org/package/hsoz/docs/Network-Iron.html)
 * [Network.Hawk](http://hackage.haskell.org/package/hsoz/docs/Network-Hawk.html)
 * [Network.Oz](http://hackage.haskell.org/package/hsoz/docs/Network-Oz.html)

## Example Usage

See the [Network.Iron](http://hackage.haskell.org/package/hsoz/docs/Network-Iron.html)
documentation, and the [example](./example/) directory of this
repository.

## Status

This is an in-progress experiment in implementing the protocol in
Haskell.

 * **Iron**: complete
 * **Hawk**: complete
 * **Oz**: under construction.
 * **Example web application**: under construction.

*Please note*: until the example application is built, this library
cannot be considered "battle-tested".

There is also an `org-mode` file: [todo.org](./todo.org?raw=1).

## Development

I welcome collaborators, particularly anyone who would like to develop
authentication plugins for frameworks such as
[Snap](http://snapframework.com/) and
[Servant](https://haskell-servant.github.io/), or a manager for
[Wreq](http://www.serpentine.com/wreq/).

### Building with Stack

```
stack build
```

### Building with Nix

```
nix-shell -p cabal2nix --command "cabal2nix --shell . > default.nix"
nix-shell --command "cabal configure"
cabal build
```

## Credits

This module is based on the Javascript code and documentation by Eran
Hammer and others. A fair amount of Hammer's descriptive text has been
incorporated into this documentation, as well as the cool logos.


text:
<?php
/**
 * Simple product add to cart
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     2.1.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product;

if ( ! $product->is_purchasable() ) return;
?>

<?php
	// Availability
	$availability      = $product->get_availability();
	$availability_html = empty( $availability['availability'] ) ? '' : '
' . esc_html( $availability['availability'] ) . '
';

	echo apply_filters( 'woocommerce_stock_html', $availability_html, $availability['availability'], $product );
?>

<?php if ( $product->is_in_stock() ) : ?>

	<?php do_action( 'woocommerce_before_add_to_cart_form' ); ?>

	<form class="cart" method="post" enctype='multipart/form-data'>
	 	<?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>

	 	<?php
	 		if ( ! $product->is_sold_individually() )
	 			woocommerce_quantity_input_dd( array(
	 				'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ),
	 				'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product )
	 			) );
	 	?>

	 	<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" />

	 	<button type="submit" class="single_add_to_cart_button button alt"><?php echo $product->single_add_to_cart_text(); ?></button>

		<?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
	</form>

	<?php do_action( 'woocommerce_after_add_to_cart_form' ); ?>

<?php endif; ?>


text:
//
// Copyright 2022 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//

using Google.Solutions.Common.Diagnostics;
using Google.Solutions.Common.Threading;
using Google.Solutions.IapTunneling.Net;
using System;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Solutions.IapTunneling.Iap
{
    /// <summary>
    /// Factory for creating (Web Socket) connections to the tunneling
    /// endpoint (for ex, Cloud IAP).
    /// </summary>
    public interface ISshRelayEndpoint
    {
        Task<INetworkStream> ConnectAsync(CancellationToken token);

        Task<INetworkStream> ReconnectAsync(
            string sid,
            ulong lastByteConsumedByClient,
            CancellationToken token);
    }

    /// <summary>
    /// SSH Relay session. A session uses one WebSocket connection
    /// at a time. If that connection breaks, the session attempts
    /// to reconnect.
    /// </summary>
    internal sealed class SshRelaySession
    {
        private const uint MaxReconnects = 2;

        public ISshRelayEndpoint Endpoint { get; }

        //
        // Current connection, guarded by the a lock.
        //
        private INetworkStream connection = null;
        private readonly AsyncLock connectLock = new AsyncLock();

        internal SessionState State { get; } = new SessionState();

        /// <summary>
        /// Unique identifier of session. Available after initial
        /// connection has been established.
        /// </summary>
        public string Sid { get; private set; }

        private void TraceVerbose(string message)
        {
            if (IapTraceSources.Default.Switch.ShouldTrace(TraceEventType.Verbose))
            {
                IapTraceSources.Default.TraceVerbose($"{this}: {message}");
            }
        }

        private async Task<INetworkStream> GetConnectionAsync(
            Func<INetworkStream, CancellationToken, Task> resendUnacknoledgedDataAction,
            CancellationToken cancellationToken)
        {
            //
            // This method might be called concurrently by a
            // writer and a reader, so we have to synchronize.
            //
            using (await this.connectLock
                .AcquireAsync(cancellationToken)
                .ConfigureAwait(false))
            {
                if (this.connection != null)
                {
                    //
                    // We're still connected.
                    //
                    return this.connection;
                }
                else if (this.State.LastAckReceived == 0)
                {
                    //
                    // Initial connect.
                    //
                    TraceVerbose($"Establishing new connection");

                    var connection = await this.Endpoint
                        .ConnectAsync(cancellationToken)
                        .ConfigureAwait(false);

                    //
                    // To complete connection establishment, we have to receive
                    // a CONNECT_SUCCESS_SID message.
                    //
                    var message = new byte[SshRelayFormat.MaxMessageSize];
                    string connectionSid = null;

                    while (true)
                    {
                        var bytesRead = await connection
                            .ReadAsync(
                                message,
                                0,
                                message.Length,
                                cancellationToken)
                            .ConfigureAwait(false);

                        SshRelayFormat.Tag.Decode(message, out var tag);

                        if (bytesRead == 0)
                        {
                            throw new WebSocketStreamClosedByServerException(
                                WebSocketCloseStatus.NormalClosure,
                                "The connection was closed by the server");
                        }
                        else if (bytesRead < SshRelayFormat.Tag.Length)
                        {
                            throw new SshRelayProtocolViolationException(
                                "The server sent an incomplete message");
                        }

                        switch (tag)
                        {
                            case SshRelayMessageTag.CONNECT_SUCCESS_SID:
                                {
                                    var bytesDecoded = SshRelayFormat.ConnectSuccessSid.Decode(
                                        message,
                                        out var sid);
                                    connectionSid = sid;

                                    Debug.Assert(bytesDecoded == bytesRead);

                                    //
                                    // If the previous connection broke before we received
                                    // the first ACK, then there might be data to be resend.
                                    //

                                    await resendUnacknoledgedDataAction(
                                            connection,
                                            cancellationToken)
                                        .ConfigureAwait(false);

                                    this.Sid = connectionSid;
                                    this.connection = connection;

                                    TraceVerbose($"Received CONNECT_SUCCESS_SID, connected");

                                    return connection;
                                }

                            case SshRelayMessageTag.LONG_CLOSE:
                            default:
                                //
                                // Unknown tag, ignore.
                                //

                                TraceVerbose($"Received unknown message: {tag}");

                                break;
                        }
                    }
                }
                else
                {
                    //
                    // Reconnect + sync ack's + resend data.
                    //
                    Debug.Assert(this.Sid != null);
                    TraceVerbose($"Attempting reconnect with ack={this.State.LastAckReceived}");

                    var connection = await this.Endpoint
                        .ReconnectAsync(
                            this.Sid,
                            this.State.BytesReceived,
                            cancellationToken)
                        .ConfigureAwait(false);

                    //
                    // To complete connection establishment, we have to receive
                    // a RECONNECT_SUCCESS_ACK message.
                    //
                    var message = new byte[SshRelayFormat.MaxMessageSize];
                    while (true)
                    {
                        var bytesRead = await connection
                            .ReadAsync(
                                message,
                                0,
                                message.Length,
                                cancellationToken)
                            .ConfigureAwait(false);

                        SshRelayFormat.Tag.Decode(message, out var tag);

                        if (bytesRead == 0)
                        {
                            throw new WebSocketStreamClosedByServerException(
                                WebSocketCloseStatus.NormalClosure,
                                "The connection was closed by the server");
                        }
                        else if (bytesRead < SshRelayFormat.Tag.Length)
                        {
                            throw new SshRelayProtocolViolationException(
                                "The server sent an incomplete message");
                        }

                        switch (tag)
                        {
                            case SshRelayMessageTag.RECONNECT_SUCCESS_ACK:
                                {
                                    var bytesDecoded = SshRelayFormat.ReconnectAck.Decode(
                                        message,
                                        out var ack);
                                    this.State.LastAckReceived = ack;

                                    Debug.Assert(bytesDecoded == bytesRead);

                                    //
                                    // Resend all data since the ACK that we just received.
                                    //

                                    await resendUnacknoledgedDataAction(
                                            connection,
                                            cancellationToken)
                                        .ConfigureAwait(false);

                                    this.connection = connection;

                                    TraceVerbose("Received RECONNECT_SUCCESS_ACK, reconnected");

                                    return connection;
                                }
                            case SshRelayMessageTag.CONNECT_SUCCESS_SID:
                                {
                                    //
                                    // We shouldn't be receiving this message after
                                    // a reconnect.
                                    //
                                    throw new SshRelayProtocolViolationException(
                                        "The server sent an unexpected CONNECT_SUCCESS_SID " +
                                        "message in response to a reconect");
                                }

                            case SshRelayMessageTag.LONG_CLOSE:
                            default:
                                //
                                // Unknown tag, ignore.
                                //
                                TraceVerbose($"Received unknown message: {tag}");

                                break;
                        }
                    }
                }
            }
        }

        //---------------------------------------------------------------------
        // Publics.
        //---------------------------------------------------------------------

        public SshRelaySession(ISshRelayEndpoint endpoint)
        {
            this.Endpoint = endpoint;
        }

        internal async Task DisconnectAsync(CancellationToken cancellationToken)
        {
            using (await this.connectLock
                .AcquireAsync(cancellationToken)
                .ConfigureAwait(false))
            {
                //
                // Drop this connection.
                //
                if (this.connection != null)
                {
                    try
                    {
                        await this.connection
                            .CloseAsync(cancellationToken)
                            .ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        IapTraceSources.Default.TraceError(e);
                    }

                    try
                    {
                        this.connection.Dispose();
                    }
                    catch (Exception e)
                    {
                        IapTraceSources.Default.TraceError(e);
                    }

                    this.connection = null;
                }

                TraceVerbose("Disonnected");
            }
        }

        public async Task<uint> IoAsync(
            Func<INetworkStream, Task<uint>> ioAction,
            Func<INetworkStream, CancellationToken, Task> resendUnacknoledgedDataAction,
            bool treatNormalCloseAsError,
            CancellationToken cancellationToken)
        {
            var attempt = 0;
            while (true)
            {
                try
                {
                    var connection = await GetConnectionAsync(
                            resendUnacknoledgedDataAction,
                            cancellationToken)
                        .ConfigureAwait(false);

                    Debug.Assert(connection != null);
                    return await ioAction(connection).ConfigureAwait(false);
                }
                catch (WebSocketStreamClosedByClientException)
                {
                    throw;
                }
                catch (WebSocketStreamClosedByServerException e)
                {
                    IapTraceSources.Default.TraceError(e);

                    switch ((SshRelayCloseCode)e.CloseStatus)
                    {
                        case SshRelayCloseCode.NORMAL:
                        case SshRelayCloseCode.DESTINATION_READ_FAILED:
                        case SshRelayCloseCode.DESTINATION_WRITE_FAILED:
                            //
                            // NB. We get a DESTINATION_*_FAILED if the
                            // backend closed the connection (as opposed
                            // to the relay).
                            //
                            if (treatNormalCloseAsError)
                            {
                                throw;
                            }
                            else
                            {
                                //
                                // Server closed the connection normally.
                                //
                                return 0;
                            }

                        case SshRelayCloseCode.NOT_AUTHORIZED:
                            throw new SshRelayDeniedException(
                                $"The server denied access: " +
                                e.CloseStatusDescription);

                        case SshRelayCloseCode.FAILED_TO_REWIND:
                        case SshRelayCloseCode.SID_UNKNOWN:
                        case SshRelayCloseCode.SID_IN_USE:
                            throw new SshRelayReconnectException(
                                "The server closed the connection unexpectedly and " +
                                "reestablishing the connection failed: " +
                                e.CloseStatusDescription);

                        case SshRelayCloseCode.FAILED_TO_CONNECT_TO_BACKEND:
                            throw new SshRelayConnectException(
                                "The server could not connect to the backend: " +
                                e.CloseStatusDescription);

                        case SshRelayCloseCode.LOOKUP_FAILED:
                        case SshRelayCloseCode.LOOKUP_FAILED_RECONNECT:
                            throw new SshRelayBackendNotFoundException(
                                "The backend could not be found");

                        default:
                            {
                                if (attempt++ >= MaxReconnects)
                                {
                                    TraceVerbose($"Failed to reconnect after {attempt} attempts");
                                    throw;
                                }
                                else
                                {
                                    //
                                    // Try again.
                                    //
                                    await DisconnectAsync(cancellationToken)
                                        .ConfigureAwait(true);

                                    TraceVerbose("Attempting to reconnect");

                                    break;
                                }
                            }
                    }
                }
            }
        }

        public void Dispose()
        {
            this.connectLock.Dispose();
            this.connection?.Dispose();
        }

        public override string ToString()
        {
            var sidToken = this.Sid != null
                ? this.Sid.Substring(0, Math.Min(this.Sid.Length, 10))
                : "(unknown)";
            return $"[SshRelaySession {sidToken} {this.State}]";
        }

        //---------------------------------------------------------------------
        // Inner classes.
        //---------------------------------------------------------------------

        internal class SessionState
        {
            //
            // Counters for keeping track of the connection state.
            // The values can be read from any thread, but written
            // only by the current reader or writer thread.
            //

            private long lastAckReceived = 0;
            private long lastAckSent = 0;
            private long bytesReceived = 0;
            private long bytesSent = 0;

            public ulong LastAckReceived
            {
                get => (ulong)Thread.VolatileRead(ref this.lastAckReceived);
                set => this.lastAckReceived = (long)value;
            }

            public ulong LastAckSent
            {
                get => (ulong)Thread.VolatileRead(ref this.lastAckSent);
                set => this.lastAckSent = (long)value;
            }

            public ulong BytesReceived
            {
                get => (ulong)Thread.VolatileRead(ref this.bytesReceived);
            }

            public ulong BytesSent
            {
                get => (ulong)Thread.VolatileRead(ref this.bytesSent);
            }

            public void AddBytesReceived(uint delta)
            {
                Debug.Assert(delta > 0);
                Interlocked.Add(ref this.bytesReceived, delta);
            }

            public void AddBytesSent(uint delta)
            {
                Debug.Assert(delta > 0);
                Interlocked.Add(ref this.bytesSent, delta);
            }

            public override string ToString()
            {
                return $"AR: {this.LastAckReceived} AS: {this.LastAckSent} " +
                       $"TR: {this.BytesReceived} TX: {this.BytesSent}";
            }
        }
    }
}


text:
<?php

namespace alexion\yii\kit\enum;

class Scenario
{
    const CREATE = 'create';
    const LOGIN = 'login';
    const UPDATE = 'update';
    const UPDATE_PASSWORD = 'update_password';
    const UPDATE_STATUS = 'update_status';
}


text: require("@testing-library/jest-dom/extend-expect")


text:
#include <aws/chime/model/VoiceConnectorSettings.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Chime
{
namespace Model
{

VoiceConnectorSettings::VoiceConnectorSettings() :
    m_cdrBucketHasBeenSet(false)
{
}

VoiceConnectorSettings::VoiceConnectorSettings(JsonView jsonValue) :
    m_cdrBucketHasBeenSet(false)
{
  *this = jsonValue;
}

VoiceConnectorSettings& VoiceConnectorSettings::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("CdrBucket"))
  {
    m_cdrBucket = jsonValue.GetString("CdrBucket");

    m_cdrBucketHasBeenSet = true;
  }

  return *this;
}

JsonValue VoiceConnectorSettings::Jsonize() const
{
  JsonValue payload;

  if(m_cdrBucketHasBeenSet)
  {
   payload.WithString("CdrBucket", m_cdrBucket);

  }

  return payload;
}

} // namespace Model
} // namespace Chime
} // namespace Aws


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.pitest.coverage.export (pitest 1.0.1-SNAPSHOT API)</title>
<meta name="date" content="2015-09-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.pitest.coverage.export

Classes

DefaultCoverageExporter

NullCoverageExporter


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * User
 *
 * @property int    $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property int    $merchant_id
 * @property string $remember_token
 * @property        $created_at
 * @property        $updated_at
 * @property Collection $roles
 * @property Collection $locations
 *
 * @package App
 */
class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;
    use SoftDeletes;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'merchant_id', 'role_id', 'api_token'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'api_token', 'deleted_at'];

    /**
     * Get the merchant record associated with the user.
     * @author MS
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function merchant()
    {
        return $this->belongsTo(\App\Basket\Merchant::class);
    }

    /**
     * Get the role record associated with the user.
     *
     * TODO To remove! ~WN
     *
     * @deprecated
     * @author MS
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(\App\Role::class);
    }

    /**
     * @author EB
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function locations()
    {
        return $this->belongsToMany(\App\Basket\Location::class);
    }

    /**
     * @author EB
     * @return BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class)
            ->withPivot('user_id', 'role_id');
    }

    /**
     * @author EB
     * @return \Illuminate\Support\Collection
     */
    public function permissions()
    {
        return $this->roles()->with('permissions')
            ->get()
            ->pluck('permissions')
            ->flatten(1)
            ->unique('id');
    }
}


text:
namespace blink {

using Corner = ScrollAnchor::Corner;

ScrollAnchor::ScrollAnchor(ScrollableArea* scroller)
    : m_scroller(scroller)
    , m_anchorObject(nullptr)
    , m_corner(Corner::TopLeft)
{
    ASSERT(m_scroller);
    ASSERT(m_scroller->isFrameView() || m_scroller->isPaintLayerScrollableArea());
}

ScrollAnchor::~ScrollAnchor()
{
}

static LayoutBox* scrollerLayoutBox(const ScrollableArea* scroller)
{
    LayoutBox* box = scroller->isFrameView()
        ? toFrameView(scroller)->layoutView()
        : &toPaintLayerScrollableArea(scroller)->box();
    ASSERT(box);
    return box;
}

static Corner cornerFromCandidateRect(LayoutRect candidateRect, LayoutRect visibleRect)
{
    if (visibleRect.contains(candidateRect.minXMinYCorner()))
        return Corner::TopLeft;
    if (visibleRect.contains(candidateRect.maxXMinYCorner()))
        return Corner::TopRight;
    if (visibleRect.contains(candidateRect.minXMaxYCorner()))
        return Corner::BottomLeft;
    if (visibleRect.contains(candidateRect.maxXMaxYCorner()))
        return Corner::BottomRight;
    return Corner::TopLeft;
}

static LayoutPoint cornerPointOfRect(LayoutRect rect, Corner whichCorner)
{
    switch (whichCorner) {
    case Corner::TopLeft: return rect.minXMinYCorner();
    case Corner::TopRight: return rect.maxXMinYCorner();
    case Corner::BottomLeft: return rect.minXMaxYCorner();
    case Corner::BottomRight: return rect.maxXMaxYCorner();
    }
    ASSERT_NOT_REACHED();
    return LayoutPoint();
}

// Bounds of the LayoutObject relative to the scroller's visible content rect.
static LayoutRect relativeBounds(const LayoutObject* layoutObject, const ScrollableArea* scroller)
{
    LayoutRect localBounds;
    if (layoutObject->isBox()) {
        localBounds = toLayoutBox(layoutObject)->borderBoxRect();
    } else if (layoutObject->isText()) {
        // TODO(skobes): Use first and last InlineTextBox only?
        for (InlineTextBox* box = toLayoutText(layoutObject)->firstTextBox(); box; box = box->nextTextBox())
            localBounds.unite(box->calculateBoundaries());
    } else {
        // Only LayoutBox and LayoutText are supported.
        ASSERT_NOT_REACHED();
    }
    LayoutRect relativeBounds = LayoutRect(layoutObject->localToAncestorQuad(
        FloatRect(localBounds), scrollerLayoutBox(scroller)).boundingBox());
    if (scroller->isFrameView())
        relativeBounds.moveBy(-LayoutPoint(scroller->scrollPositionDouble()));
    return relativeBounds;
}

static LayoutPoint computeRelativeOffset(const LayoutObject* layoutObject, const ScrollableArea* scroller, Corner corner)
{
    return cornerPointOfRect(relativeBounds(layoutObject, scroller), corner);
}

static bool candidateMovesWithScroller(const LayoutObject* candidate, const ScrollableArea* scroller)
{
    if (candidate->style() && candidate->style()->hasViewportConstrainedPosition())
        return false;

    bool skippedByContainerLookup = false;
    candidate->container(scrollerLayoutBox(scroller), &skippedByContainerLookup);
    return !skippedByContainerLookup;
}

ScrollAnchor::ExamineResult ScrollAnchor::examine(const LayoutObject* candidate) const
{
    if (candidate->isLayoutInline())
        return ExamineResult(Continue);

    if (!candidate->isText() && !candidate->isBox())
        return ExamineResult(Skip);

    if (!candidateMovesWithScroller(candidate, m_scroller))
        return ExamineResult(Skip);

    LayoutRect candidateRect = relativeBounds(candidate, m_scroller);
    LayoutRect visibleRect = scrollerLayoutBox(m_scroller)->overflowClipRect(LayoutPoint());

    bool occupiesSpace = candidateRect.width() > 0 && candidateRect.height() > 0;
    if (occupiesSpace && visibleRect.intersects(candidateRect)) {
        return ExamineResult(
            visibleRect.contains(candidateRect) ? Return : Constrain,
            cornerFromCandidateRect(candidateRect, visibleRect));
    } else {
        return ExamineResult(Skip);
    }
}

void ScrollAnchor::findAnchor()
{
    LayoutObject* stayWithin = scrollerLayoutBox(m_scroller);
    LayoutObject* candidate = stayWithin->nextInPreOrder(stayWithin);
    while (candidate) {
        ExamineResult result = examine(candidate);
        if (result.viable) {
            m_anchorObject = candidate;
            m_corner = result.corner;
        }
        switch (result.status) {
        case Skip:
            candidate = candidate->nextInPreOrderAfterChildren(stayWithin);
            break;
        case Constrain:
            stayWithin = candidate;
            // fall through
        case Continue:
            candidate = candidate->nextInPreOrder(stayWithin);
            break;
        case Return:
            return;
        }
    }
}

void ScrollAnchor::save()
{
    if (m_scroller->scrollPosition() == IntPoint::zero()) {
        clear();
        return;
    }
    if (m_anchorObject)
        return;

    findAnchor();
    if (!m_anchorObject)
        return;

    m_anchorObject->setIsScrollAnchorObject();
    m_savedRelativeOffset = computeRelativeOffset(m_anchorObject, m_scroller, m_corner);
}

void ScrollAnchor::restore()
{
    if (!m_anchorObject)
        return;

    LayoutSize adjustment = computeRelativeOffset(m_anchorObject, m_scroller, m_corner) - m_savedRelativeOffset;
    if (!adjustment.isZero()) {
        m_scroller->setScrollPosition(
            m_scroller->scrollPositionDouble() + DoubleSize(adjustment),
            AnchoringScroll);
        // Update UMA metric.
        DEFINE_STATIC_LOCAL(EnumerationHistogram, adjustedOffsetHistogram,
            ("Layout.ScrollAnchor.AdjustedScrollOffset", 2));
        adjustedOffsetHistogram.count(1);
        UseCounter::count(scrollerLayoutBox(m_scroller)->document(), UseCounter::ScrollAnchored);
    }
}

void ScrollAnchor::clear()
{
    LayoutObject* anchorObject = m_anchorObject;
    m_anchorObject = nullptr;

    if (anchorObject)
        anchorObject->maybeClearIsScrollAnchorObject();
}

} // namespace blink


text:
package com.thingtrack.konekti.service.sensor.api;

import java.util.List;

import com.thingtrack.konekti.domain.sensor.CaptureTelemetry;

/**
 * @author Thingtrack S.L.
 *
 */
public interface CaptureTelemetryService {
	public List<CaptureTelemetry> getAll() throws Exception;
	public CaptureTelemetry get( Integer actionId ) throws Exception;
	public CaptureTelemetry save(CaptureTelemetry telemetryCapture) throws Exception;
	public void delete(CaptureTelemetry telemetryCapture) throws Exception;
}


text:
namespace DotNetNuke.Modules.Reports.Extensions
{
    using System.Collections.Generic;

    /// -----------------------------------------------------------------------------
    /// <summary>
    ///     The IReportsSettingsControl class provides an interface to a Reports Module Settings Control
    /// </summary>
    /// <history>
    ///     [anurse]     08/02/2007    Created
    /// </history>
    /// -----------------------------------------------------------------------------
    public interface IReportsSettingsControl : IReportsControl
    {
        /// -----------------------------------------------------------------------------
        /// <summary>
        ///     Loads settings from the specified settings dictionary into the
        ///     settings UI
        /// </summary>
        /// <param name="Settings">The settings dictionary to load into the UI</param>
        /// <history>
        ///     [anurse]     08/02/2007    Created
        /// </history>
        /// -----------------------------------------------------------------------------
        void LoadSettings(Dictionary<string, string> Settings);

        /// -----------------------------------------------------------------------------
        /// <summary>
        ///     Save settings to the specified settings dictionary from the
        ///     settings UI
        /// </summary>
        /// <param name="Settings">The settings dictionary to save from the UI</param>
        /// <history>
        ///     [anurse]     08/02/2007    Created
        /// </history>
        /// -----------------------------------------------------------------------------
        void SaveSettings(Dictionary<string, string> Settings);
    }
}


text:
This guide is intended for players with developer privileges in the game.

- Chapter 1. [Introduction and example](PROGRAMMING_TUT.md)
- Chapter 2. [Reference guide](PROGRAMMING_REF.md)
- Chapter 3. [Object serialization](PROGRAMMING_OBJ.md)


text:
WalletFrame::WalletFrame(const PlatformStyle *_platformStyle, BitcoinGUI *_gui) :
    QFrame(_gui),
    gui(_gui),
    platformStyle(_platformStyle)
{
    // Leave HBox hook for adding a list view later
    QHBoxLayout *walletFrameLayout = new QHBoxLayout(this);
    setContentsMargins(0,0,0,0);
    walletStack = new QStackedWidget(this);
    walletFrameLayout->setContentsMargins(0,0,0,0);
    walletFrameLayout->addWidget(walletStack);

    QLabel *noWallet = new QLabel(tr("No wallet has been loaded."));
    noWallet->setAlignment(Qt::AlignCenter);
    walletStack->addWidget(noWallet);
}

WalletFrame::~WalletFrame()
{
}

void WalletFrame::setClientModel(ClientModel *_clientModel)
{
    this->clientModel = _clientModel;
}

bool WalletFrame::addWallet(WalletModel *walletModel)
{
    if (!gui || !clientModel || !walletModel) {
        return false;
    }

    const QString name = walletModel->getWalletName();
    if (mapWalletViews.count(name) > 0) {
        return false;
    }

    WalletView *walletView = new WalletView(platformStyle, this);
    walletView->setBitcoinGUI(gui);
    walletView->setClientModel(clientModel);
    walletView->setWalletModel(walletModel);
    walletView->showOutOfSyncWarning(bOutOfSync);

    WalletView* current_wallet_view = currentWalletView();
    if (current_wallet_view) {
        walletView->setCurrentIndex(current_wallet_view->currentIndex());
    } else {
        walletView->gotoOverviewPage();
    }

    walletStack->addWidget(walletView);
    mapWalletViews[name] = walletView;

    // Ensure a walletView is able to show the main window
    connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized()));

    connect(walletView, SIGNAL(outOfSyncWarningClicked()), this, SLOT(outOfSyncWarningClicked()));

    return true;
}

bool WalletFrame::setCurrentWallet(const QString& name)
{
    if (mapWalletViews.count(name) == 0)
        return false;

    WalletView *walletView = mapWalletViews.value(name);
    walletStack->setCurrentWidget(walletView);
    assert(walletView);
    walletView->updateEncryptionStatus();
    return true;
}

bool WalletFrame::removeWallet(const QString &name)
{
    if (mapWalletViews.count(name) == 0)
        return false;

    WalletView *walletView = mapWalletViews.take(name);
    walletStack->removeWidget(walletView);
    delete walletView;
    return true;
}

void WalletFrame::removeAllWallets()
{
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        walletStack->removeWidget(i.value());
    mapWalletViews.clear();
}

bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient)
{
    WalletView *walletView = currentWalletView();
    if (!walletView)
        return false;

    return walletView->handlePaymentRequest(recipient);
}

void WalletFrame::showOutOfSyncWarning(bool fShow)
{
    bOutOfSync = fShow;
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        i.value()->showOutOfSyncWarning(fShow);
}

void WalletFrame::gotoOverviewPage()
{
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        i.value()->gotoOverviewPage();
}

void WalletFrame::gotoHistoryPage()
{
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        i.value()->gotoHistoryPage();
}

void WalletFrame::gotoReceiveCoinsPage()
{
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        i.value()->gotoReceiveCoinsPage();
}

void WalletFrame::gotoSendCoinsPage(QString addr)
{
    QMap<QString, WalletView*>::const_iterator i;
    for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
        i.value()->gotoSendCoinsPage(addr);
}

void WalletFrame::gotoSignMessageTab(QString addr)
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->gotoSignMessageTab(addr);
}

void WalletFrame::gotoVerifyMessageTab(QString addr)
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->gotoVerifyMessageTab(addr);
}

void WalletFrame::encryptWallet(bool status)
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->encryptWallet(status);
}

void WalletFrame::backupWallet()
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->backupWallet();
}

void WalletFrame::changePassphrase()
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->changePassphrase();
}

void WalletFrame::unlockWallet()
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->unlockWallet();
}

void WalletFrame::usedSendingAddresses()
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->usedSendingAddresses();
}

void WalletFrame::usedReceivingAddresses()
{
    WalletView *walletView = currentWalletView();
    if (walletView)
        walletView->usedReceivingAddresses();
}

WalletView *WalletFrame::currentWalletView()
{
    return qobject_cast<WalletView*>(walletStack->currentWidget());
}

void WalletFrame::outOfSyncWarningClicked()
{
    Q_EMIT requestedSyncWarningInfo();
}


text:
package instance_test

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-pez/haas-broker/handlers"
	. "github.com/pivotal-pez/haas-broker/handlers/instance"
	"github.com/pivotal-pez/pezdispenser/pdclient/fake"
	"github.com/unrolled/render"
)

var _ = Describe("Management Dashboard", func() {
	Describe("given GetDashboard() function", func() {
		Context("when the instance is not yet provisioned", func() {
			runGetDashboardHandlerContext("running", PendingResponse)
		})
		Context("when the instance is provisioned", func() {
			runGetDashboardHandlerContext("complete", "name")
			runGetDashboardHandlerContext("complete", "oob_ip")
			runGetDashboardHandlerContext("complete", "oob_pw")
			runGetDashboardHandlerContext("complete", "oob_user")
		})
		Context("when the instance has failed provisioning", func() {
			runGetDashboardHandlerContext("failed", FailureResponse)
		})
	})
})

func runGetDashboardHandlerContext(dispenserStatus string, brokerResponseEvaluator string) {
	var (
		responseWriter     *httptest.ResponseRecorder
		controlRequestBody        = "{}"
		dispenserResponse  string = fmt.Sprintf(`{
					"ID": "567471e1c19475001d000001","Timestamp": 1450471905595633562,"Expires": 0,
					"Status": "%s",
					"Profile": "agent_task_long_running","CallerName": "m1.small","MetaData": {
						"status": {
				      "data": {
				        "credentials": {
				          "name": "host-07-16",
				          "oob_ip": "10.65.70.116",
				          "oob_pw": "d3v0ps!",
				          "oob_user": "pezuser"
				        },
				        "status": "complete"
				      },
				      "message": "ok",
				      "status": "success"
						},
						"phinfo": {"data": [
								{
									"requestid": "2676f04e-a5c9-11e5-88f7-0050569b9b57"
								}],
							"message": "ok",
							"status": "success"
						}}}`, dispenserStatus)
	)
	BeforeEach(func() {
		responseWriter = httptest.NewRecorder()
		request := &http.Request{
			Body: ioutil.NopCloser(bytes.NewBufferString(controlRequestBody)),
		}
		fakeClientDoer := &fake.ClientDoer{
			Response: &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(bytes.NewBufferString(dispenserResponse)),
			},
		}
		BuildDashboardHandler(handlers.DispenserCreds{}, new(fakeCol), render.New(render.Options{
			Directory: "../../templates",
		}), fakeClientDoer)(responseWriter, request)
	})
	It(fmt.Sprintf("then it should return a %s message", brokerResponseEvaluator), func() {
		body, _ := ioutil.ReadAll(responseWriter.Body)
		Ω(body).Should(ContainSubstring(brokerResponseEvaluator))
	})
}


text:
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';

function transform(contents: string, libSource: string, compilerOptions: ts.CompilerOptions = {}) {
    // Generated outputs
    let outputs = [];
    // Create a compilerHost object to allow the compiler to read and write files
    let compilerHost: ts.CompilerHost = {
        getSourceFile: function (filename, languageVersion) {
            if (filename === 'file.ts')
                return ts.createSourceFile(filename, contents, compilerOptions.target, false);
            if (filename === 'lib.d.ts')
                return ts.createSourceFile(filename, libSource, compilerOptions.target, false);
            return undefined;
        },
        writeFile: function (name, text, writeByteOrderMark) {
            outputs.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
        },
        getDefaultLibFileName: () => { return 'lib.d.ts'; },
        getDirectories: () => { return ['']; },
        useCaseSensitiveFileNames: () => { return false; },
        getCanonicalFileName: filename => { return filename; },
        getCurrentDirectory: () => { return ''; },
        getNewLine: () => { return '\n'; },
        fileExists: () => { return true; },
        readFile: () => { return ''; },
    };
    // Create a program from inputs
    let program: ts.Program = ts.createProgram(['file.ts'], compilerOptions, compilerHost);

    return {
        outputs: outputs,
        errors: {
            semantic: program.getSemanticDiagnostics(),
            syntactic: program.getSyntacticDiagnostics(),
            declaration: program.getDeclarationDiagnostics()
        }
    };
}

class CompilerService {
    // Probably have to refactor that but by the time...
    private readonly importer = 'import {lib} from \'lib\';';
    private readonly precode = '/* code start */';
    private readonly declarations = 'let lib: any = {};';
    private readonly removers = 'var lib = {};'

    private compilerOptions: ts.CompilerOptions = {
        target: ts.ScriptTarget.ES5,
        experimentalDecorators: true,
        strictNullChecks: true
    }

    private options: ts.TranspileOptions = {
        compilerOptions: this.compilerOptions,
        reportDiagnostics: true,
    }

    private addMethods(code) {
        // Yes could be better =)
        let methods = `
            var promise = {
                then: function() {},
                catch: function() {}
            }
            var lib = {
                create: function() {},
                ajax: function() { return promise},
                move: function(direction) {this.direction = direction},
                direction: -1,
                show: function() {},
                configure: function() {},
                sound: function() {this.isSound = true},
                isSound: false,
                setName: function() {}
            };

            exports.promise = promise;
            exports.lib = lib;
        `;
        let splitted = code.split(this.precode);
        return splitted[0] + methods + splitted[1].replace(this.removers, '');
    }

    public process(jscode) {
        let code = this.precode + this.declarations + jscode.replace(this.importer, '');
        let transpiled = ts.transpileModule(code, this.options);
        let finalCode = transpiled.outputText.split(this.precode)[1];
        finalCode = finalCode.replace(this.removers, '// var lib = {...}');
        let libSource = fs.readFileSync(path.join(path.dirname(require.resolve('typescript')), 'lib.d.ts')).toString();
        let checkErrors = transform(code, libSource, this.options.compilerOptions);
        let errorsFound = false;

        if (checkErrors.errors.semantic.length > 0 || checkErrors.errors.syntactic.length > 0 || checkErrors.errors.declaration.length > 0) {
            finalCode = '';
            errorsFound = true;
        }

        if (checkErrors.errors.semantic.length > 0) {
            let text: any = checkErrors.errors.semantic[0].messageText;
            finalCode += 'Stopped by Semantic Error: \n' + (text.messageText || text) + '\n';
        }

        if (checkErrors.errors.syntactic.length > 0) {
            let text: any = checkErrors.errors.syntactic[0].messageText;
            finalCode += 'Stopped by Syntactic Error: \n' + (text.messageText || text) + '\n';
        }

        if (checkErrors.errors.declaration.length > 0) {
            let text: any = checkErrors.errors.declaration[0].messageText;
            finalCode += 'Stopped by Declaration Error: \n' + (text.messageText || text) + '\n';
        }

        return {failed: errorsFound, code: finalCode, realCode: this.addMethods(transpiled.outputText)};
    }

}

export let compilerService = new CompilerService();


text:
import {
  OPEN_EDIT_MEDIA_DIALOG, CLOSE_EDIT_MEDIA_DIALOG,
  OPEN_PREVIEW_MEDIA_DIALOG, CLOSE_PREVIEW_MEDIA_DIALOG,
  OPEN_LOGIN_DIALOG, CLOSE_LOGIN_DIALOG,
} from '../constants/ActionTypes';

const initialState = {
  editMedia: {
    open: false,
    payload: {},
  },
  previewMedia: {
    open: false,
    payload: {},
  },
  login: {
    open: false,
    payload: {},
  },
};

const openDialog = (state, name, payload, open = true) => ({
  ...state,
  [name]: {
    open,
    payload,
  },
});
const closeDialog = (state, name) => ({
  ...state,
  [name]: {
    open: false,
    payload: state[name].payload,
  },
});

export default function reduce(state = initialState, action = {}) {
  const { type, payload } = action;
  switch (type) {
    case OPEN_EDIT_MEDIA_DIALOG:
      return openDialog(state, 'editMedia', payload);
    case CLOSE_EDIT_MEDIA_DIALOG:
      return closeDialog(state, 'editMedia');
    case OPEN_PREVIEW_MEDIA_DIALOG:
      return openDialog(state, 'previewMedia', payload);
    case CLOSE_PREVIEW_MEDIA_DIALOG:
      return closeDialog(state, 'previewMedia');
    case OPEN_LOGIN_DIALOG:
      return openDialog(state, 'login', payload);
    case CLOSE_LOGIN_DIALOG:
      return closeDialog(state, 'login');
    default:
      return state;
  }
}


text:
import { appActionTypes } from '../actions/appActions';
import { EditorState } from 'draft-js';

const editorState = EditorState.createEmpty();
console.log(editorState)
const INITIAL_STATE = {
  init: false
}

function setState(state, newState) {
    console.log(JSON.stringify({ ...state, ...newState }));
    return { ...state, ...newState };
}

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case appActionTypes.INIT:
          return setState(state, action.state);
        case appActionTypes.CHANGE_STATE:
          return setState(state, action.state);
    }
    return state;
};


text:
<!-- default base.html template -->
<!DOCTYPE html>
<head>
        <title>{% block title %}cage{% end %}</title>
        <link href='/media/{{ handler.cfg.template }}/css/basic.css' rel='stylesheet'
                type='text/css'>
{% block extrahead %}
{% end %}
</head>
<body>
{% block header %}

{% end %}
  {% block mainnav %}
    {% module PageNav() %}
  {% end %}
{% block content %}{% end %}
{% block footer %}
{% end %}
{% block extrajs %}
{% end %}
</body>
</html>


text:
#ifndef PARAMETER_NAME_H
#define PARAMETER_NAME_H

#include <cassert>
#include <sstream>
#include <string>
#include <vector>

/**
 * Parameter name string supporting deferred formatting for array subscripts.
 *
 * Custom parameter name class with support for deferred formatting of names containing array subscripts.  The class stores
 * a format string and a vector of index values, and performs string formatting when an accessor function is called to
 * retrieve the name string.  This class was primarily designed to be used with validation functions that receive a parameter name
 * string and value as arguments, and print an error message that includes the parameter name when the value fails a validation
 * test.  Using standard strings with these validation functions requires that parameter names containing array subscripts be
 * formatted before each validation function is called, performing the string formatting even when the value passes validation
 * and the string is not used:
 *         sprintf(name, "pCreateInfo[%d].sType", i);
 *         validate_stype(name, pCreateInfo[i].sType);
 *
 * With the ParameterName class, a format string and a vector of format values are stored by the ParameterName object that is
 * provided to the validation function.  String formatting is then performed only when the validation function retrieves the
 * name string from the ParameterName object:
 *         validate_stype(ParameterName("pCreateInfo[%i].sType", IndexVector{ i }), pCreateInfo[i].sType);
 */
class ParameterName {
   public:
    /// Container for index values to be used with parameter name string formatting.
    typedef std::vector<size_t> IndexVector;

    /// Format specifier for the parameter name string, to be replaced by an index value.  The parameter name string must contain
    /// one format specifier for each index value specified.
    const std::string IndexFormatSpecifier = "%i";

   public:
    /**
     * Construct a ParameterName object from a string literal, without formatting.
     *
     * @param source Paramater name string without format specifiers.
     *
     * @pre The source string must not contain the %i format specifier.
     */
    ParameterName(const char *source) : source_(source) { assert(IsValid()); }

    /**
     * Construct a ParameterName object from a std::string object, without formatting.
     *
     * @param source Paramater name string without format specifiers.
     *
     * @pre The source string must not contain the %i format specifier.
     */
    ParameterName(const std::string &source) : source_(source) { assert(IsValid()); }

    /**
     * Construct a ParameterName object from a std::string object, without formatting.
     *
     * @param source Paramater name string without format specifiers.
     *
     * @pre The source string must not contain the %i format specifier.
     */
    ParameterName(const std::string &&source) : source_(std::move(source)) { assert(IsValid()); }

    /**
     * Construct a ParameterName object from a std::string object, with formatting.
     *
     * @param source Paramater name string with format specifiers.
     * @param args Array index values to be used for formatting.
     *
     * @pre The number of %i format specifiers contained by the source string must match the number of elements contained
     *      by the index vector.
     */
    ParameterName(const std::string &source, const IndexVector &args) : source_(source), args_(args) { assert(IsValid()); }

    /**
     * Construct a ParameterName object from a std::string object, with formatting.
     *
     * @param source Paramater name string with format specifiers.
     * @param args Array index values to be used for formatting.
     *
     * @pre The number of %i format specifiers contained by the source string must match the number of elements contained
     *      by the index vector.
     */
    ParameterName(const std::string &&source, const IndexVector &&args) : source_(std::move(source)), args_(std::move(args)) {
        assert(IsValid());
    }

    /// Retrive the formatted name string.
    std::string get_name() const { return (args_.empty()) ? source_ : Format(); }

   private:
    /// Replace the %i format specifiers in the source string with the values from the index vector.
    std::string Format() const {
        std::string::size_type current = 0;
        std::string::size_type last = 0;
        std::stringstream format;

        for (size_t index : args_) {
            current = source_.find(IndexFormatSpecifier, last);
            if (current == std::string::npos) {
                break;
            }
            format << source_.substr(last, (current - last)) << index;
            last = current + IndexFormatSpecifier.length();
        }

        format << source_.substr(last, std::string::npos);

        return format.str();
    }

    /// Check that the number of %i format specifiers in the source string matches the number of elements in the index vector.
    bool IsValid() {
        // Count the number of occurances of the format specifier
        uint32_t count = 0;
        std::string::size_type pos = source_.find(IndexFormatSpecifier);

        while (pos != std::string::npos) {
            ++count;
            pos = source_.find(IndexFormatSpecifier, pos + 1);
        }

        return (count == args_.size());
    }

   private:
    std::string source_;  ///< Format string.
    IndexVector args_;    ///< Array index values for formatting.
};

#endif  // PARAMETER_NAME_H


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/john.francis/Projects/MyRepo/SignatureSample/ReactNativeSignatureExample/android/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-xlarge-land/values-xlarge-land.xml -->
    <eat-comment/>
    <dimen name="abc_search_view_text_min_width">256dip</dimen>
</resources>


text:
angular.
  module('Home').
  factory('ApiHome', ['$resource',
    function($resource) {
      return $resource('/api/Disciplina/Mostrar', {}, {
        Mostrar: {},
      });
    }
  ]);


text:
/*
 * s3verify (C) 2016 Minio, Inc.
 *
 * 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 cmd

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"time"
)

// newRemoveBucketReq - Fill in the dynamic fields of a DELETE request here.
func newRemoveBucketReq(bucketName string) (Request, error) {
	// removeBucketReq is a new DELETE bucket request.
	var removeBucketReq = Request{
		customHeader: http.Header{},
	}

	// Set the bucketName.
	removeBucketReq.bucketName = bucketName

	reader := bytes.NewReader([]byte{}) // Compute hash using empty body because DELETE requests do not send a body.
	_, sha256Sum, _, err := computeHash(reader)
	if err != nil {
		return Request{}, err
	}

	// Set the headers.
	removeBucketReq.customHeader.Set("User-Agent", appUserAgent)
	removeBucketReq.customHeader.Set("X-Amz-Content-Sha256", hex.EncodeToString(sha256Sum))

	return removeBucketReq, nil
}

// removeBucketVerify - Check a Response's Status, Headers, and Body for AWS S3 compliance.
func removeBucketVerify(res *http.Response, expectedStatusCode int, errorResponse ErrorResponse) error {
	if err := verifyHeaderRemoveBucket(res.Header); err != nil {
		return err
	}
	if err := verifyStatusRemoveBucket(res.StatusCode, expectedStatusCode); err != nil {
		return err
	}
	if err := verifyBodyRemoveBucket(res.Body, errorResponse); err != nil {
		return err
	}
	return nil
}

// TODO: right now only checks for correctly deleted buckets...need to add in checks for 'failed' tests.

// verifyHeaderRemoveBucket - Check that the responses headers match the expected headers for a given DELETE Bucket request.
func verifyHeaderRemoveBucket(header http.Header) error {
	if err := verifyStandardHeaders(header); err != nil {
		return err
	}
	return nil
}

// verifyBodyRemoveBucket - Check that the body of the response matches the expected body for a given DELETE Bucket request.
func verifyBodyRemoveBucket(resBody io.Reader, expectedError ErrorResponse) error {
	if expectedError.Message != "" { // Error is expected.
		errResponse := ErrorResponse{}
		err := xmlDecoder(resBody, &errResponse)
		if err != nil {
			return err
		}
		if errResponse.Message != expectedError.Message {
			err := fmt.Errorf("Unexpected Error Message: wanted %v, got %v", expectedError.Message, errResponse.Message)
			return err
		}
	}
	return nil
}

// verifyStatusRemoveBucket - Check that the status of the response matches the expected status for a given DELETE Bucket request.
func verifyStatusRemoveBucket(respStatusCode, expectedStatusCode int) error {
	if respStatusCode != expectedStatusCode { // Successful DELETE request will result in 204 No Content.
		err := fmt.Errorf("Unexpected Status: wanted %d, got %d", expectedStatusCode, respStatusCode)
		return err
	}
	return nil
}

// mainRemoveBucketExists - test the removebucket API.
func mainRemoveBucketExists(config ServerConfig, curTest int) bool {
	message := fmt.Sprintf("[%02d/%d] RemoveBucket (Bucket Exists):", curTest, globalTotalNumTest)
	// Only remove s3verify created buckets.
	for _, bucket := range s3verifyBuckets {
		// Spin the scanBar
		scanBar(message)
		// Generate the new DELETE bucket request.
		req, err := newRemoveBucketReq(bucket.Name)
		if err != nil {
			printMessage(message, err)
			return false
		}
		// Spin the scanBar
		scanBar(message)
		// Perform the request.
		res, err := config.execRequest("DELETE", req)
		if err != nil {
			printMessage(message, err)
			return false
		}
		defer closeResponse(res)
		// Spin the scanBar
		scanBar(message)
		if err := removeBucketVerify(res, 204, ErrorResponse{}); err != nil {
			printMessage(message, err)
			return false
		}
		// Spin the scanBar
		scanBar(message)
	}
	printMessage(message, nil)
	return true
}

// Test the RemoveBucket API when the bucket does not exist.
func mainRemoveBucketDNE(config ServerConfig, curTest int) bool {
	message := fmt.Sprintf("[%02d/%d] RemoveBucket (Bucket DNE):", curTest, globalTotalNumTest)
	// Generate a random bucketName.
	bucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "")
	// Hardcode the expected error response.
	errResponse := ErrorResponse{
		Code:       "NoSuchBucket",
		Message:    "The specified bucket does not exist",
		BucketName: bucketName,
		Key:        "",
	}
	// Spin scanBar
	scanBar(message)
	// Generate a new DELETE bucket request for a bucket that does not exist.
	req, err := newRemoveBucketReq(bucketName)
	if err != nil {
		printMessage(message, err)
		return false
	}
	// spin scanBar
	scanBar(message)
	// Perform the request.
	res, err := config.execRequest("DELETE", req)
	if err != nil {
		printMessage(message, err)
		return false
	}
	defer closeResponse(res)
	// Spin scanBar
	scanBar(message)
	if err := removeBucketVerify(res, http.StatusNotFound, errResponse); err != nil {
		printMessage(message, err)
		return false
	}
	// Spin scanBar
	scanBar(message)
	printMessage(message, nil)
	return true
}

// Test the RemoveBucket API when the bucket is not empty.
func mainRemoveBucketNotEmpty(config ServerConfig, curTest int) bool {
	message := fmt.Sprintf("[%02d/%d] RemoveBucket (Bucket Not Empty):", curTest, globalTotalNumTest)
	// Spin scanBar
	scanBar(message)
	// Attempt to remove a s3verify created bucket before the objects inside have been removed.
	bucketName := s3verifyBuckets[0].Name

	// Expected error response.
	errResponse := ErrorResponse{
		Code:    "BucketNotEmpty",
		Message: "The bucket you tried to delete is not empty",
	}

	// Spin scanBar
	scanBar(message)
	// Create a new DELETE request for a bucket that is not yet empty.
	req, err := newRemoveBucketReq(bucketName)
	if err != nil {
		printMessage(message, err)
		return false
	}
	// Spin scanBar
	scanBar(message)

	// Execute the request.
	res, err := config.execRequest("DELETE", req)
	if err != nil {
		printMessage(message, err)
		return false
	}
	defer closeResponse(res)
	// Spin scanBar
	scanBar(message)

	// Verify that the request failed.
	if err := removeBucketVerify(res, http.StatusConflict, errResponse); err != nil {
		printMessage(message, err)
		return false
	}
	// Spin scanBar
	scanBar(message)
	// Test passed.
	printMessage(message, nil)
	return true
}


text:
Please read [this introduction](./doc/introduction.md) to understand the fundamentals of Geeo.

Or consult our [website geeo.io](https://geeo.io/) to learn more about Geeo and how to use it in your apps.

# Javascript SDK

`geeo-javascript` is the open source Javascript Client for Geeo.io, usable from node.js or an HTML5 browser.

You can get it with npm:

```
$ npm install geeo-javascript
```

or clone this repository.

## Files

`geeo-javascript` is written with ES6 in the `src` folder, babelified to ES5 in `lib` and webpacked and minified in `dist`.

The node.js module can be used with

```
const {GeeoWS, GeeoHTTP} = require("geeo-javascript")
```

If you're writing for browsers, include `./dist/geeo.js` or `./dist/geeo.min.js` to your webpage. See [example.html](./example.html) for a working example.

## API

You can find the API docs in [the doc folder](./doc/api.md).

## the API at a glance

_Note: functions I'm not allowed to use with my token are just ignored by the server._

```
var wsURL = "wss://demo.geeo.io"
var httpURL = "https://demo.geeo.io"

var geeo = new GeeoWS(wsURL)
var geeoHttp = new GeeoHTTP(httpURL)

geeoHttp.getGuestToken({name: 'chris', age: 45})
.then( function(token) {
	geeo.connect(token)
}).catch(function(error) {
	console.log("Server doesn't allow guest tokens)
})

geeo.on('error', function (error) {
	geeo.close()
})

geeo.on('connect', function() {
	geeo.view.move(0,0,1,1) // lon1 lat1 lon2 lat2 (point1 is SW, point2 is NE)
	geeo.move(0.5, 0.5) // lon lat

	geeo.view.getPosition() // null if not set, [lon1, lat1, lon2, lat2] otherwise
	geeo.getPosition() // null if not set [lon, lat] otherwise
})

geeo.on('viewUpdated', function() {
	geeo.view.pois() // pois in the view
	geeo.view.agents() // agents in the view

	geeo.addPOI({id, [lon, lat], publicData})
	geeo.addAirBeacon({id, [lon1, lat1, lon2, lat2], publicData})
	geeo.removePOI(poi)
	geeo.removeAirBeacon(ab)
})

geeo.view.on('agentEntered', function(agent){})
geeo.view.on('agentMoved', function(agent){})
geeo.view.on('agentLeft', function(agent){})

geeo.view.on('poiEntered', function(poi){})
geeo.view.on('poiMoved', function(poi){})
geeo.view.on('poiLeft', function(poi){})
```

Not implemented yet in Geeo REST api, coming soon:
```
geeoHttp.setToken(token) // necessary to use the following features
geeoHttp.createPOI(poi)
geeoHTTP.removePOI(poi)
geeoHttp.createAirBeacon(ab)
geeoHttp.removeAirBeacon(ab)
geeoHttp.view([0,0,1,1]) // returns agents + POIs
```


text:
//Describe the difference between C# and .NET Framework in 2-3 sentences.
//Write your description in a text file called "csharp-and-dot-net-framework.txt". Use English.

//The answer is in csharp-and-dot-net-framework.txt file


text:
var _ = require('underscore')
  , filter = require('../lib/ansi')
  , expect = require('chai').expect
  , fs = require('fs')
  , path = require('path')
  ;

function loadFix(name) {
  return fs.readFileSync(path.join(__dirname, 'fixtures', 'ansi-' + name)).toString('utf8');
}

describe('ansi filtering', function () {
  it('should work w/ mocha output', function () {
    expect(filter(loadFix('1.in'))).to.equal(loadFix('1.out'))
  })
  describe('with plaintext option', function () {
    it('should strip correctly', function () {
      expect(filter(loadFix('2.in'), true)).to.equal(loadFix('2.out'))
    })
  })
  it('should preserve leading CR', function () {
    expect(filter('somethen\relse')).to.equal('\relse')
  })
  it("should not add leading cr when it's CRLF", function () {
    expect(filter('something\r\nelse')).to.equal('something\r\nelse')
  })
})


text:
namespace Svit
{
	class Rectangle
	{
		public:
			Point2i start;
			Vector2i size;

			Rectangle ();

			Rectangle (Point2i _start, Vector2i _size);

			int
			get_area () const;

			float
			get_aspect_ratio () const;

			void
			dump (const char* _name, unsigned int _level = 0) const;
	};
}

#endif


text:
var express = require('express');
var router = express.Router();

/*
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  console.log("/"+req.method);
  next();
});
*/

/* GET home page. */
router.get('/', function(req, res) {
	res.render('./pages/index', function(err, html) {
		res.send(html);
	});
});

module.exports = router;


text:
{-# LANGUAGE BangPatterns #-}
module Tests.SlowFunctions
    (
      indices
    , splitOn
    ) where

import qualified Data.Text as T
import Data.Text.Internal (Text(..))
import Data.Text.Unsafe (iter_, unsafeHead, unsafeTail)

indices :: T.Text              -- ^ Substring to search for (@needle@)
        -> T.Text              -- ^ Text to search in (@haystack@)
        -> [Int]
indices needle@(Text _narr _noff nlen) haystack@(Text harr hoff hlen)
    | T.null needle = []
    | otherwise     = scan 0
  where
    scan i | i >= hlen = []
           | needle `T.isPrefixOf` t = i : scan (i+nlen)
           | otherwise = scan (i+d)
           where t = Text harr (hoff+i) (hlen-i)
                 d = iter_ haystack i

splitOn :: T.Text               -- ^ Text to split on
        -> T.Text               -- ^ Input text
        -> [T.Text]
splitOn pat src0
    | T.null pat  = error "splitOn: empty"
    | l == 1      = T.split (== (unsafeHead pat)) src0
    | otherwise   = go src0
  where
    l      = T.length pat
    go src = search 0 src
      where
        search !n !s
            | T.null s             = [src]      -- not found
            | pat `T.isPrefixOf` s = T.take n src : go (T.drop l s)
            | otherwise            = search (n+1) (unsafeTail s)


text:
#include <fstream>

namespace engine
{
	FontRenderer::FontRenderer(std::wstring font,float red,float green,float blue)
	{
		LoadCharInfos(font);
		LoadTexture(font);

		if(char_infos['.'])
			ppp_length = (int)(char_infos['.']->xadvance*3);
		else ppp_length = 0;

		HRESULT hresult;
		ID3D10Device *d3d10_device = engine.GetDevice();

		char *vs_buffer, *ps_buffer;
		unsigned int vs_size, ps_size;
		render_state.vertex_shader = CreateVertexShaderFromFile("FontVS", vs_buffer, vs_size);
		render_state.pixel_shader = CreatePixelShaderFromFile("FontPS", ps_buffer, ps_size);

		D3D10_INPUT_ELEMENT_DESC font_input_element_desc[] =
		{
			{ "SV_POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
			{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D10_INPUT_PER_VERTEX_DATA, 0 }
		};

		if((hresult = d3d10_device->CreateInputLayout(font_input_element_desc,2,vs_buffer,vs_size,&render_state.input_layout)) != S_OK)
			throw Exception(L"FontRenderer: CreateInputLayout failed: " + GetD3D10Error(hresult));

		delete[] vs_buffer;
		delete[] ps_buffer;

		float constant_data[4] = { red, green, blue, 0.0f };
		constant_buffer = new StaticConstantBuffer(&constant_data,4*sizeof(float));
		render_state.ps_constant_buffers.push_back(constant_buffer->GetConstantBuffer());

		// Initialize render states
		RenderStateManager &render_state_manager = engine.GetRenderStateManager();

		render_state.vertex_buffers.resize(1);
		render_state.vertex_buffer_offsets.resize(1);
		render_state.vertex_buffer_strides.push_back(sizeof(CharacterVertex));

		render_state.index_buffer_format = DXGI_FORMAT_R16_UINT;

		render_state.topology = D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST;

		d3d10_device->CreateRasterizerState(&render_state_manager.GetDefaultRasterizerDesc(),&global_render_state.rasterizer_state);

		D3D10_DEPTH_STENCIL_DESC depth_stencil_desc = render_state_manager.GetDefaultDepthStencilDesc();
		depth_stencil_desc.DepthEnable = false;
		d3d10_device->CreateDepthStencilState(&depth_stencil_desc,&render_state.depth_stencil_state);

		d3d10_device->CreateBlendState(&render_state_manager.GetDefaultBlendDesc(),&render_state.blend_state);

		ID3D10SamplerState *sampler_state;
		D3D10_SAMPLER_DESC sampler_desc = render_state_manager.GetDefaultSamplerDesc();
		sampler_desc.Filter = D3D10_FILTER_MIN_MAG_MIP_POINT;
		d3d10_device->CreateSamplerState(&sampler_desc,&sampler_state);
		render_state.ps_sampler_states.push_back(sampler_state);

		render_state.ps_resources.push_back(texture->GetResourceView());
	}

	FontRenderer::~FontRenderer()
	{
		SafeRelease(render_state.vertex_shader);
		SafeRelease(render_state.pixel_shader);
		SafeRelease(render_state.ps_sampler_states[0]);
		SafeRelease(render_state.blend_state);
		SafeRelease(render_state.depth_stencil_state);
		SafeRelease(global_render_state.rasterizer_state);

		delete constant_buffer;
		delete texture;

		for(unsigned int i=0;i<256;++i)
			delete char_infos[i];
	}

	void FontRenderer::Render(int x,int y,std::string text,int max_length)
	{
		float current_x = (float)x, current_y = (float)y;
		int length = 0;
		int current_advance = 0;
		int ppp_left = 3;

		ID3D10Device *d3d10_device = engine.GetDevice();

		DynamicBatchManager &dynamic_batch_manager = engine.GetDynamicBatchManager();
		DynamicVertexBatch &dyn_vertex_batch = dynamic_batch_manager.NextDynamicVertexBatch((int)text.length()*4*sizeof(CharacterVertex));
		DynamicIndexBatch &dyn_index_batch = dynamic_batch_manager.NextDynamicIndexBatch((int)text.length()*6*sizeof(unsigned __int16));

		CharacterVertex *vertices = (CharacterVertex*)dyn_vertex_batch.Map();
		unsigned __int16* indices = (unsigned __int16*)dyn_index_batch.Map();

		for(unsigned int i=0;i<text.length();++i) {
			CharacterInfo *char_info = char_infos[text[i]];

			if(max_length) {
				if(!ppp_left) break;
				if(current_advance > max_length-ppp_length) {
					char_info = char_infos['.'];
					--ppp_left;
				}
			}

			if(!char_info) continue;

			unsigned int index_offset = i*6, vertex_offset = i*4;

			float left = current_x + char_info->xoffset;
			float top = current_y + char_info->yoffset;
			float right = left + char_info->width;
			float bottom = top + char_info->height;
			float tex_left = char_info->x;
			float tex_top = char_info->y;
			float tex_right = tex_left+char_info->tex_width;
			float tex_bottom = tex_top+char_info->tex_height;

			CharacterVertex new_vertices[4];
			new_vertices[0].position[0] = new_vertices[2].position[0] = left;
			new_vertices[0].position[1] = new_vertices[1].position[1] = top;
			new_vertices[1].position[0] = new_vertices[3].position[0] = right;
			new_vertices[2].position[1] = new_vertices[3].position[1] = bottom;
			new_vertices[0].texcoords[0] = new_vertices[2].texcoords[0] = tex_left;
			new_vertices[0].texcoords[1] = new_vertices[1].texcoords[1] = tex_top;
			new_vertices[1].texcoords[0] = new_vertices[3].texcoords[0] = tex_right;
			new_vertices[2].texcoords[1] = new_vertices[3].texcoords[1] = tex_bottom;

			vertices[vertex_offset] = new_vertices[0]; vertices[vertex_offset+1] = new_vertices[1];
			vertices[vertex_offset+2] = new_vertices[2]; vertices[vertex_offset+3] = new_vertices[3];
			indices[index_offset] = vertex_offset; indices[index_offset+1] = vertex_offset+1; indices[index_offset+2] = vertex_offset+2;
			indices[index_offset+3] = vertex_offset+1; indices[index_offset+4] = vertex_offset+3; indices[index_offset+5] = vertex_offset+2;

			current_x += char_info->xadvance;
			current_advance += (int)char_info->xadvance;

			++length;
		}

		dyn_index_batch.Unmap();
		dyn_vertex_batch.Unmap();

		render_state.vertex_buffers[0] = dyn_vertex_batch.GetVertexBuffer(render_state.vertex_buffer_offsets[0]);
		render_state.index_buffer = dyn_index_batch.GetIndexBuffer(render_state.index_buffer_offset);

		engine.GetRenderStateManager().SetGlobalRenderState(global_render_state);
		engine.GetRenderStateManager().SetRenderState(render_state);

		d3d10_device->DrawIndexed((unsigned int)text.length()*6,0,0);
	}

	void FontRenderer::LoadCharInfos(std::wstring &font)
	{
		std::ifstream filestream(font + L".fnt");

		char buffer[128];
		filestream.getline(buffer,128);

		unsigned int scale_w,scale_h,line_height,base;
		sscanf_s(buffer,"common lineHeight=%d base=%d scaleW=%d scaleH=%d",&line_height,&base,&scale_w,&scale_h);

		memset(char_infos,0,256*sizeof(CharacterInfo*));

		while(!filestream.eof()) {
			CharacterInfo char_info;

			unsigned int id;
			int x,y;
			int width,height;
			int xoffset,yoffset;
			int xadvance;

			filestream.getline(buffer,128);
			int test = sscanf_s(buffer,"char id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d",
				&id,&x,&y,&width,&height,&xoffset,&yoffset,&xadvance);

			if(id>255 || test!=8) continue;

			char_info.x = (float)x/(float)scale_w;
			char_info.y = (float)y/(float)scale_h;
			char_info.width = (float)width;
			char_info.height = (float)height;
			char_info.tex_width = (float)width/(float)scale_w;
			char_info.tex_height = (float)height/(float)scale_h;
			char_info.xoffset = (float)xoffset;
			char_info.yoffset = (float)yoffset;
			char_info.xadvance = (float)xadvance;

			if(!char_infos[id]) {
				char_infos[id] = new CharacterInfo;
				*char_infos[id] = char_info;
			}
		}

		filestream.close();
	}

	void FontRenderer::LoadTexture(std::wstring &font)
	{
		texture = new Texture(font + L".dds", false);

		if(!texture) throw Exception(L"Could not load font resources");
	}
}