text:
package org.apache.cassandra.db;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;

import org.apache.commons.lang.StringUtils;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.io.IColumnSerializer;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.FastByteArrayInputStream;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessageProducer;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.Deletion;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;

public class RowMutation implements IMutation, MessageProducer
{
    private static RowMutationSerializer serializer_ = new RowMutationSerializer();
    public static final String FORWARD_HEADER = "FORWARD";

    public static RowMutationSerializer serializer()
    {
        return serializer_;
    }

    private String table_;
    private ByteBuffer key_;
    // map of column family id to mutations for that column family.
    protected Map<Integer, ColumnFamily> modifications_ = new HashMap<Integer, ColumnFamily>();

    private Map<Integer, byte[]> preserializedBuffers = new HashMap<Integer, byte[]>();

    public RowMutation(String table, ByteBuffer key)
    {
        table_ = table;
        key_ = key;
    }

    public RowMutation(String table, Row row)
    {
        table_ = table;
        key_ = row.key.key;
        add(row.cf);
    }

    protected RowMutation(String table, ByteBuffer key, Map<Integer, ColumnFamily> modifications)
    {
        table_ = table;
        key_ = key;
        modifications_ = modifications;
    }

    public String getTable()
    {
        return table_;
    }

    public Collection<Integer> getColumnFamilyIds()
    {
        return modifications_.keySet();
    }

    public ByteBuffer key()
    {
        return key_;
    }

    public Collection<ColumnFamily> getColumnFamilies()
    {
        return modifications_.values();
    }

    public ColumnFamily getColumnFamily(Integer cfId)
    {
        return modifications_.get(cfId);
    }

    /**
     * Returns mutation representing a Hints to be sent to address
     * as soon as it becomes available.
     * The format is the following:
     *
     * HintsColumnFamily: {        // cf
     *   <dest token>: {           // key
     *     <uuid>: {               // super-column
     *       table:
        // columns
     *       key: <key>
     *       mutation: <mutation>
     *       version: <version>
     *     }
     *   }
     * }
     *
     */
    public static RowMutation hintFor(RowMutation mutation, ByteBuffer token) throws IOException
    {
        RowMutation rm = new RowMutation(Table.SYSTEM_TABLE, token);
        ByteBuffer hintId = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());

        // determine the TTL for the RowMutation
        // this is set at the smallest GCGraceSeconds for any of the CFs in the RM
        // this ensures that deletes aren't "undone" by delivery of an old hint
        int ttl = Integer.MAX_VALUE;
        for (ColumnFamily cf : mutation.getColumnFamilies())
            ttl = Math.min(ttl, cf.metadata().getGcGraceSeconds());

        // serialized RowMutation
        QueryPath path = new QueryPath(HintedHandOffManager.HINTS_CF, hintId, ByteBufferUtil.bytes("mutation"));
        rm.add(path, ByteBuffer.wrap(mutation.getSerializedBuffer(MessagingService.version_)), System.currentTimeMillis(), ttl);

        // serialization version
        path = new QueryPath(HintedHandOffManager.HINTS_CF, hintId, ByteBufferUtil.bytes("version"));
        rm.add(path, ByteBufferUtil.bytes(MessagingService.version_), System.currentTimeMillis(), ttl);

        // table
        path = new QueryPath(HintedHandOffManager.HINTS_CF, hintId, ByteBufferUtil.bytes("table"));
        rm.add(path, ByteBufferUtil.bytes(mutation.getTable()), System.currentTimeMillis(), ttl);

        // key
        path = new QueryPath(HintedHandOffManager.HINTS_CF, hintId, ByteBufferUtil.bytes("key"));
        rm.add(path, mutation.key(), System.currentTimeMillis(), ttl);

        return rm;
    }

    /*
     * Specify a column family name and the corresponding column
     * family object.
     * param @ cf - column family name
     * param @ columnFamily - the column family.
     */
    public void add(ColumnFamily columnFamily)
    {
        assert columnFamily != null;
        ColumnFamily prev = modifications_.put(columnFamily.id(), columnFamily);
        if (prev != null)
            // developer error
            throw new IllegalArgumentException("ColumnFamily " + columnFamily + " already has modifications in this mutation: " + prev);
    }

    public boolean isEmpty()
    {
        return modifications_.isEmpty();
    }

    /*
     * Specify a column name and a corresponding value for
     * the column. Column name is specified as <column family>:column.
     * This will result in a ColumnFamily associated with
     * <column family> as name and a Column with <column>
     * as name. The column can be further broken up
     * as super column name : columnname  in case of super columns
     *
     * param @ cf - column name as <column family>:<column>
     * param @ value - value associated with the column
     * param @ timestamp - timestamp associated with this data.
     * param @ timeToLive - ttl for the column, 0 for standard (non expiring) columns
     */
    public void add(QueryPath path, ByteBuffer value, long timestamp, int timeToLive)
    {
        Integer id = Schema.instance.getId(table_, path.columnFamilyName);
        ColumnFamily columnFamily = modifications_.get(id);
        if (columnFamily == null)
        {
            columnFamily = ColumnFamily.create(table_, path.columnFamilyName);
            modifications_.put(id, columnFamily);
        }
        columnFamily.addColumn(path, value, timestamp, timeToLive);
    }

    public void addCounter(QueryPath path, long value)
    {
        Integer id = Schema.instance.getId(table_, path.columnFamilyName);
        ColumnFamily columnFamily = modifications_.get(id);
        if (columnFamily == null)
        {
            columnFamily = ColumnFamily.create(table_, path.columnFamilyName);
            modifications_.put(id, columnFamily);
        }
        columnFamily.addCounter(path, value);
    }

    public void add(QueryPath path, ByteBuffer value, long timestamp)
    {
        add(path, value, timestamp, 0);
    }

    public void delete(QueryPath path, long timestamp)
    {
        Integer id = Schema.instance.getId(table_, path.columnFamilyName);

        int localDeleteTime = (int) (System.currentTimeMillis() / 1000);

        ColumnFamily columnFamily = modifications_.get(id);
        if (columnFamily == null)
        {
            columnFamily = ColumnFamily.create(table_, path.columnFamilyName);
            modifications_.put(id, columnFamily);
        }

        if (path.superColumnName == null && path.columnName == null)
        {
            columnFamily.delete(localDeleteTime, timestamp);
        }
        else if (path.columnName == null)
        {
            SuperColumn sc = new SuperColumn(path.superColumnName, columnFamily.getSubComparator());
            sc.delete(localDeleteTime, timestamp);
            columnFamily.addColumn(sc);
        }
        else
        {
            columnFamily.addTombstone(path, localDeleteTime, timestamp);
        }
    }

    /*
     * This is equivalent to calling commit. Applies the changes to
     * to the table that is obtained by calling Table.open().
     */
    public void apply() throws IOException
    {
        KSMetaData ksm = Schema.instance.getTableDefinition(getTable());

        Table.open(table_).apply(this, ksm.durableWrites);
    }

    public void applyUnsafe() throws IOException
    {
        Table.open(table_).apply(this, false);
    }

    public Message getMessage(Integer version) throws IOException
    {
        return getMessage(StorageService.Verb.MUTATION, version);
    }

    public Message getMessage(StorageService.Verb verb, int version) throws IOException
    {
        return new Message(FBUtilities.getBroadcastAddress(), verb, getSerializedBuffer(version), version);
    }

    public synchronized byte[] getSerializedBuffer(int version) throws IOException
    {
        byte[] bytes = preserializedBuffers.get(version);
        if (bytes == null)
        {
            bytes = FBUtilities.serialize(this, serializer(), version);
            preserializedBuffers.put(version, bytes);
        }
        return bytes;
    }

    public String toString()
    {
        return toString(false);
    }

    public String toString(boolean shallow)
    {
        StringBuilder buff = new StringBuilder("RowMutation(");
        buff.append("keyspace='").append(table_).append('\'');
        buff.append(", key='").append(ByteBufferUtil.bytesToHex(key_)).append('\'');
        buff.append(", modifications=[");
        if (shallow)
        {
            List<String> cfnames = new ArrayList<String>();
            for (Integer cfid : modifications_.keySet())
            {
                CFMetaData cfm = Schema.instance.getCFMetaData(cfid);
                cfnames.add(cfm == null ? "-dropped-" : cfm.cfName);
            }
            buff.append(StringUtils.join(cfnames, ", "));
        }
        else
            buff.append(StringUtils.join(modifications_.values(), ", "));
        return buff.append("])").toString();
    }

    public void addColumnOrSuperColumn(String cfName, ColumnOrSuperColumn cosc)
    {
        if (cosc.super_column != null)
        {
            for (org.apache.cassandra.thrift.Column column : cosc.super_column.columns)
            {
                add(new QueryPath(cfName, cosc.super_column.name, column.name), column.value, column.timestamp, column.ttl);
            }
        }
        else if (cosc.column != null)
        {
            add(new QueryPath(cfName, null, cosc.column.name), cosc.column.value, cosc.column.timestamp, cosc.column.ttl);
        }
        else if (cosc.counter_super_column != null)
        {
            for (org.apache.cassandra.thrift.CounterColumn column : cosc.counter_super_column.columns)
            {
                addCounter(new QueryPath(cfName, cosc.counter_super_column.name, column.name), column.value);
            }
        }
        else // cosc.counter_column != null
        {
            addCounter(new QueryPath(cfName, null, cosc.counter_column.name), cosc.counter_column.value);
        }
    }

    public void deleteColumnOrSuperColumn(String cfName, Deletion del)
    {
        if (del.predicate != null && del.predicate.column_names != null)
        {
            for(ByteBuffer c : del.predicate.column_names)
            {
                if (del.super_column == null && Schema.instance.getColumnFamilyType(table_, cfName) == ColumnFamilyType.Super)
                    delete(new QueryPath(cfName, c), del.timestamp);
                else
                    delete(new QueryPath(cfName, del.super_column, c), del.timestamp);
            }
        }
        else
        {
            delete(new QueryPath(cfName, del.super_column), del.timestamp);
        }
    }

    public static RowMutation fromBytes(byte[] raw, int version) throws IOException
    {
        RowMutation rm = serializer_.deserialize(new DataInputStream(new FastByteArrayInputStream(raw)), version);
        boolean hasCounters = false;
        for (Map.Entry<Integer, ColumnFamily> entry : rm.modifications_.entrySet())
        {
            if (entry.getValue().metadata().getDefaultValidator().isCommutative())
            {
                hasCounters = true;
                break;
            }
        }

        // We need to deserialize at least once for counters to cleanup the delta
        if (!hasCounters && version == MessagingService.version_)
            rm.preserializedBuffers.put(version, raw);
        return rm;
    }

    public static class RowMutationSerializer implements IVersionedSerializer<RowMutation>
    {
        public void serialize(RowMutation rm, DataOutput dos, int version) throws IOException
        {
            dos.writeUTF(rm.getTable());
            ByteBufferUtil.writeWithShortLength(rm.key(), dos);

            /* serialize the modifications_ in the mutation */
            int size = rm.modifications_.size();
            dos.writeInt(size);
            assert size >= 0;
            for (Map.Entry<Integer,ColumnFamily> entry : rm.modifications_.entrySet())
            {
                dos.writeInt(entry.getKey());
                ColumnFamily.serializer().serialize(entry.getValue(), dos);
            }
        }

        public RowMutation deserialize(DataInput dis, int version, IColumnSerializer.Flag flag) throws IOException
        {
            String table = dis.readUTF();
            ByteBuffer key = ByteBufferUtil.readWithShortLength(dis);
            Map<Integer, ColumnFamily> modifications = new HashMap<Integer, ColumnFamily>();
            int size = dis.readInt();
            for (int i = 0; i < size; ++i)
            {
                Integer cfid = Integer.valueOf(dis.readInt());
                ColumnFamily cf = ColumnFamily.serializer().deserialize(dis, flag, TreeMapBackedSortedColumns.factory());
                modifications.put(cfid, cf);
            }
            return new RowMutation(table, key, modifications);
        }

        public RowMutation deserialize(DataInput dis, int version) throws IOException
        {
            return deserialize(dis, version, IColumnSerializer.Flag.FROM_REMOTE);
        }

        public long serializedSize(RowMutation rm, int version)
        {
            int size = DBConstants.shortSize + FBUtilities.encodedUTF8Length(rm.getTable());
            size += DBConstants.shortSize + rm.key().remaining();

            size += DBConstants.intSize;
            for (Map.Entry<Integer,ColumnFamily> entry : rm.modifications_.entrySet())
            {
                size += DBConstants.intSize;
                size += entry.getValue().serializedSize();
            }

            return size;
        }
    }
}


text:
@interface CRFoursquare : NSObject <CRPointsOfInterestProtocol, CRAdvancedRequestSupporterProtocol>
@property (weak, nonatomic) id target;

-(instancetype)initWithClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret;

-(void)useAdvancedAuthentication;
-(NSString *) saveAsString;
-(void) loadAsString:(NSString*) savedState;

@end

redpajama_set_name: RedPajamaGithub


text: initSidebarItems({"fn":[["kill",""]]});


text:
Situ Design Brief
=================

General Idea
------------

An autogenerator for toponymy (place-names) on the basis of (fantasy) inputs
corresponding to sets of place-name elements. E.g., in English 'Hampton'
consists of 'ham' and '-ton', but 'Southampton' out of 'south', 'ham' and 'ton',
and so forth. The idea is that there are lists of all the common elements of
this type, and that the user can fill in what conlang words they want to
correspond to such elements, and that the program subsequently autogenerates as
many new toponyms as required.

Structure
---------

* A list of common place name elements. Ideally, these should be
  categorized/tagged/otherwise selectable according to geographical context, i.e.
  mountain-relevant ones, generic ones, coastal/island ones, etc. Keep in mind
  that there should also be room for proper names in this, as 'Swansea' is 'Sven's
  island' etc.

* A table corresponding to these where conlang elements can be filled in.
  Consider that in real life toponymy, there will be multiple words corresponding
  to the same geographical element, such as in English '-shaw', '-weald/wold' and
  '-frith' all refer to a wood, '-don', '-howe', and '-hirst/hurst' all refer to a
  hill, etc. (Moreover, in English as in some other languages toponymy has a lot
  of redundancy due to the use of an Anglo-Saxon, a Celtic, and a Norse word
  for the same geographical thing, etc.) So one should ideally be able to fill
  out multiple words per geographical referent.

* Some kind of rule or set of rules, to be determined by the user, for the
  syntactic structure of how the toponymy is derived. In English, Dutch, German
  etc. the name is usually just a compound of the elements, so
  'Southfarmenclosedhomestead' for Southampton. But in French (and via that, in
  some English places too: Chapel-en-le-Frith) this is not necessarily so: e.g.
  Noisy-le-Sec, Aix-la-Chapelle. So some kind of linguistic rule for how to
  construct the names from the table needs to be determinable.

* Finally, ideally, some kind of effect that with a probability distribution
  will 'smoothen' names (if possible): both compressing them or just making small
  variations in the vowels, consonants, or simply the elements as such. It may be
  easiest to set a rule for permitted variations, so you could e.g. set that
  '-ton' could also show up as '-tun', 'ham' as 'hamp-' before a consonant, or
  whatever, in addition to some kind of compression mechanism (?)


text:
require 'serverspec'

set :backend, :exec

# marathon service
describe file('/usr/local/lib/libmesos.so') do
  it { should be_file }
end

describe file('/usr/lib/libmesos.so') do
  it { should be_file }
end

describe file('/etc/marathon/marathon.conf') do
  it { should be_file }
end

describe service('marathon') do
  it { should be_running }
end


text:
import { setupRenderingTest } from 'ember-qunit';
import { module, test } from 'qunit';
import { hbs } from 'ember-cli-htmlbars';
import { click, render, settled } from '@ember/test-helpers';

module('Integration | Component | bs-alert', (hooks) => {
  setupRenderingTest(hooks);

  test('check has button', async function(assert) {
    this.set('dismissible', true);

    await render(hbs`<Bs::Alert @dismissible={{this.dismissible}}/>`);
    assert.equal(this.element.querySelector('a') !== null, true, 'no close button');
    assert.equal(this.element.querySelector('div.alert.in') !== null, true, 'alert is showing');

    this.set('dismissible', false);
    assert.equal(this.element.querySelector('a') , null, 'dismiss is false and close button is not displayed');
  });

  test('trigger close action', async function(assert) {
    this.set('dismissed', (actual) => {
      assert.ok(true, 'external Action was called!');
    });

    await render(hbs`<Bs::Alert @dismissible={{true}} @onDismiss={{fn this.dismissed}} />`);
    await click('a.close');

    assert.equal(this.element.querySelector('div.alert.in'), null, 'alert should not show');
  });

  test('auto dismiss', async function(assert) {

    await render(hbs`<Bs::Alert @dismissAfter={{0.1}} />`);

    assert.ok(this.element.querySelector('div.alert.in') === null, 'alert should not show');
  });
});


text:
require_relative '../../../automated_init'

context "Message" do
  context "Metadata" do
    context "Local Properties" do
      context "Set" do
        context do
          metadata = Messaging::Message::Metadata.new

          name = :some_local_property
          control_value = 'some local_property value'

          metadata.set_local_property(name, control_value)

          value = metadata.local_properties[name]

          test "Value is in the local_properties hash" do
            assert(value == control_value)
          end
        end

        context "Name Is Not a Symbol" do
          metadata = Messaging::Message::Metadata.new

          name = 'some_local_property'
          value = 'some local_property value'

          test "Is an error" do
            assert_raises Message::Metadata::Error do
              metadata.set_local_property(name, value)
            end
          end
        end
      end
    end
  end
end


text:
ActiveRecord::Base.class_eval do
  alias_method :save, :valid?
  def self.columns() @columns ||= []; end

  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type, null)
  end
end

class MockModel < ActiveRecord::Base

  validates_captcha

end


text:
from unittest import expectedFailure

from django.utils.safestring import mark_safe
from django.test import SimpleTestCase

from corehq.apps.reports.generic import GenericTabularReport

from ..generic import _sanitize_rows

class GenericTabularReportTests(SimpleTestCase):

    def test_strip_tags_html_bytestring(self):
        """
        _strip_tags should strip HTML tags
        """
        value = '<blink>182</blink>'
        value = GenericTabularReport._strip_tags(value)
        self.assertEqual(value, '182')

    def test_strip_tags_html_unicode(self):
        """
        _strip_tags should strip HTML tags from Unicode
        """
        value = '<blink>182</blink>'
        value = GenericTabularReport._strip_tags(value)
        self.assertEqual(value, '182')

    def test_strip_tags_passthru(self):
        """
        _strip_tags should allow non-basestring values to pass through
        """
        value = {'blink': 182}
        value = GenericTabularReport._strip_tags(value)
        self.assertEqual(value, {'blink': 182})

    @expectedFailure
    def test_strip_tags_expected_fail(self):
        """
        _strip_tags should not strip strings inside angle brackets, but does
        """
        value = '1 < 8 > 2'
        value = GenericTabularReport._strip_tags(value)
        self.assertEqual(value, '1 < 8 > 2')

class SanitizeRowTests(SimpleTestCase):
    def test_normal_output(self):
        rows = [['One']]

        result = _sanitize_rows(rows)
        self.assertEqual(result[0], ['One'])

    def test_escapes_rows(self):
        rows = [['']]

        result = _sanitize_rows(rows)
        self.assertEqual(result[0], ['<script>Hello</script>'])

    def test_does_not_escape_safe_text(self):
        rows = [[mark_safe('
Safe!
')]]  # nosec: test data

        result = _sanitize_rows(rows)
        self.assertEqual(result[0], ['
Safe!
'])

    def test_handles_rows(self):
        rows = [
            ['One', 'Two'],
            ['Three', 'Four'],
            ['Five', 'Six']
        ]

        result = _sanitize_rows(rows)
        self.assertEqual(result[0], ['One', 'Two'])
        self.assertEqual(result[1], ['Three', 'Four'])
        self.assertEqual(result[2], ['Five', 'Six'])


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/duo_view_menu_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:id="@+id/duo_view_menu_header_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/duo_view_menu_footer_layout"
        android:layout_below="@+id/duo_view_menu_header_layout"
        android:layout_centerVertical="true">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true">

            <LinearLayout
                android:id="@+id/duo_view_menu_options_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>
        </ScrollView>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/duo_view_menu_footer_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>


text:
var BuildScreenViewModel = function () {
    var self = this;

    function getNewDataModel() {
        var buildTypes = (function () {
            var isResultUpdate = false;
            var buildTypesFromApi = ko.observable({ isLoadingPlaceholder: true });

            var returnValue = ko.computed({
                read: function () {
                    if (!isResultUpdate) {
                        $.ajax({
                            dataType: "json",
                            url: Settings.buildTypesUrl,
                            xhrFields: { withCredentials: true }
                        }).always(function (data, textStatus, xhr) {
                            try {
                                isResultUpdate = true;
                                buildTypesFromApi(Utils.getErrorFromAjaxAlways.apply(this, arguments) || xhr.responseJSON.buildType);
                            } finally {
                                isResultUpdate = false;
                            }
                        })
                        ;
                    }

                    return buildTypesFromApi().isLoadingPlaceholder || buildTypesFromApi().isError ? buildTypesFromApi() : _(buildTypesFromApi()).map(function (buildTypeFromApi) {
                        buildTypeFromApi.branches = getBranchesForBuildTypeObservable(buildTypeFromApi);
                        return buildTypeFromApi;
                    });
                },
                deferEvaluation: true
            });

            returnValue.update = function() {
                buildTypesFromApi([]);
            };

            return returnValue;
        })();

        function getBranchesForBuildTypeObservable(buildType) {
            var branchesFromApi = ko.observable({ isLoadingPlaceholder: true });

            var isResultUpdate = false;
            var branchesUnfiltered = ko.computed({
                read: function () {
                    if (!isResultUpdate) {
                        $.ajax({
                            dataType: "json",
                            url: Settings.buildTypesUrl + '/id:(' + buildType.id + ')' + '/branches?' + Utils.getTsQSParam(),
                            xhrFields: { withCredentials: true }
                        }).always(function (data) {
                            try {
                                isResultUpdate = true;
                                var branches = [];
                                // Sadly, we don't get information from '/branches?' whether there are any 'no-branch' builds on this config (such builds can only be queried by branched:false, since they don't have a name). So, we add a fake entry here. Perhaps in future we could query the configuration.
                                if (data.branch && data.branch.length === 1) // The entry needs to be conditional, because otherwise we will show very old builds for the jobs that only at some point started using the 'Branch specification'. This is because 'Branch specification' respects the expiry of 'Active branch' (see https://confluence.jetbrains.com/display/TCD9/Working+with+Feature+Branches#WorkingwithFeatureBranches-Activebranches ) and old 'no-branch' builds don't, so they would stay visible forever, despite being dead. If we queried the configuration we'd know for sure, but for now, we know that when the call to '/branches?' returns more than one branch, it's a sign of using the 'Branch specification' which seems to cover all our cases.
                                    branches.push({ isNoBranchPlaceHolder: true });
                                branches = branches.concat(data.branch);
                                branchesFromApi(Utils.getErrorFromAjaxAlways.apply(this, arguments) || branches);
                            } finally {
                                isResultUpdate = false;
                            }
                        });
                    }

                    return branchesFromApi().isLoadingPlaceholder || branchesFromApi().isError ? branchesFromApi() : branchesFromApi().map(function (branchFromApi) {
                            branchFromApi.buildType = buildType;
                            return branchFromApi;
                        })
                        .map(function (branchFromApi) {
                            branchFromApi.builds = getBuildsForBranchObservable(branchFromApi);
                            return branchFromApi;
                        })
                    ;
                }
            });
            return ko.computed({
                read: function() {
                    return branchesUnfiltered().isLoadingPlaceholder || branchesUnfiltered().isError ? branchesUnfiltered() : branchesUnfiltered()
                        .filter(Settings.branchFilter || function () { return true; })
                        .filter(function(branch) {
                            return _(thisClientBranchFilterExcludeFunctions()).any(function(shouldExclude) { return shouldExclude(branch); }) === false;
                        })
;
                },
                deferEvaluation: true,
            });
        }

        function getBuildsForBranchObservable(branch) {
            var buildsFromApi = ko.observable({ isLoadingPlaceholder: true });

            var isResultUpdate = false;
            var builds = ko.computed({
                read: function () {
                    function ajaxLastBuild(nonRunningOnly) {
                        return $.ajax({
                            dataType: "json",
                            url: Settings.restApiBaseUrl + '/builds?locator=running:'+(nonRunningOnly ? 'false' : 'any')+',buildType:(id:(' + branch.buildType.id + ')),branch(' + (branch.isNoBranchPlaceHolder ? 'branched:false' : ('name:(' + branch.name + ')')) + '),count:1&fields=build(id,buildTypeId,number,status,state,running,percentageComplete,branchName,href,webUrl,startDate,finishDate)' + Utils.getTsQSParam(),
                            xhrFields: { withCredentials: true }
                        });
                    }
                    if (!isResultUpdate) {
                        ajaxLastBuild().always(function (responseDataWhereRunningIsAny) {
                            var error = Utils.getErrorFromAjaxAlways.apply(this, arguments);
                            var buildsWhereRunningIsAny = responseDataWhereRunningIsAny.build || [];
                            if (error || !responseDataWhereRunningIsAny.build || !responseDataWhereRunningIsAny.build[0] || !responseDataWhereRunningIsAny.build[0].running) {
                                try {
                                    isResultUpdate = true;
                                    buildsFromApi(error || buildsWhereRunningIsAny);
                                } finally {
                                    isResultUpdate = false;
                                }
                            } else { // Build is running. Don't triumph yet. Look for the previous one, it could be red.
                                ajaxLastBuild(/*nonRunningOnly:*/true).always(function (buildsWhereRunningIsFalse) {
                                    try {
                                        isResultUpdate = true;
                                        buildsFromApi(Utils.getErrorFromAjaxAlways.apply(this, arguments) || (buildsWhereRunningIsFalse.build || []).concat(buildsWhereRunningIsAny));
                                    } finally {
                                        isResultUpdate = false;
                                    }
                                });
                            }
                        });
                    }

                    return buildsFromApi().isLoadingPlaceholder || buildsFromApi().isError ? buildsFromApi() : ko.utils.arrayMap(buildsFromApi(), function (build) {
                        // this is just a trick to prevent ko.mapping from evaluating the investigations observable. TODO get rid of ko.mapping (used underneath this._super() in the SingleBuildViewModel), which evaluates our computeds immediately, creating a cyclic dependency on the build object, and causing an infinite loop when request for investigations comes back, by triggering uptade of builds.
                        var investigationsComputed;
                        build.investigations = function() {
                                return (investigationsComputed || (investigationsComputed = build.status === 'SUCCESS' ? ko.observable([]) : getInvestigationsForBuildType(build.buildTypeId)))();
                            };
                        build.investigations.isInvestigated = function () { return investigationsComputed && investigationsComputed.isInvestigated && investigationsComputed.isInvestigated(); };
                        return new SingleBuildViewModel(build, buildTypes());
                    });
                },
                deferEvaluation: true
            });
            return builds;
        }

        var projects;

        var allBuildsOfAllProjectsOrPlaceholders = ko.computed({
            read: function () {
                return projects().isLoadingPlaceholder || projects().isError ? [projects()] : (_(projects()).chain()
                    .map(function (project) {
                        return project.buildTypes.isLoadingPlaceholder ? project.buildTypes : _(project.buildTypes).map(function (buildType) {
                            return buildType.branches().isLoadingPlaceholder || buildType.branches().isError ? buildType.branches() : _(buildType.branches()).map(function (branch) {
                                return branch.builds().isLoadingPlaceholder || branch.builds().isError ? branch.builds() : _(branch.builds()).map(function (build) { return (build.investigations && build.investigations().isLoadingPlaceholder || build.investigations().isError ? build.investigations() : build); });
                            });
                        });
                    })
                    .flatten()
                    .sortBy(function (build) { return (build.isLoadingPlaceholder || build.isError) ? 6 : (build.status() !== 'SUCCESS' ? (build.isRunning() ? 5 : ((build.investigations && build.investigations.isInvestigated && build.investigations.isInvestigated()) === false ? 4 : 3)) : (build.isRunning() ? 2 : 1)) + '_' + build.startDate(); })
                    .reverse()
                    .value());
            },
            deferEvaluation: true
        });
        return {
            projects: projects = ko.computed({
                read: function () {
                    return buildTypes().isLoadingPlaceholder || buildTypes().isError ? buildTypes() : _(buildTypes()).chain().groupBy(function (buildType) {
                        return buildType.projectId;
                    }).mapObject(function (buildTypes, projectId) {
                        return {
                            projectId: projectId,
                            projectName: buildTypes[0].projectName,
                            buildTypes: buildTypes
                        };
                    })
                        .value()
                    ;
                },
                deferEvaluation: true
            }),
            allBuildsOfAllProjectsOrPlaceholders: allBuildsOfAllProjectsOrPlaceholders,
            allLoadedBuildsOfAllProjects: ko.computed({
                    read: function () {
                        return allBuildsOfAllProjectsOrPlaceholders().filter(function (build) { return !build.isLoadingPlaceholder && !build.isError; });
                    },
                    deferEvaluation: true
                }),
            isInitializing: ko.computed({
                read: function () {
                    return !!_(allBuildsOfAllProjectsOrPlaceholders()).findWhere({ isLoadingPlaceholder: true });
                },
                deferEvaluation: true
            }),
            errorsInfo: ko.computed({
                read: function () {
                    var allErrors = _(allBuildsOfAllProjectsOrPlaceholders()).where({ isError: true });
                    if (allErrors.length === 0)
                        return null;
                    if (_(allErrors).any(function (error) { return error.errorText === "" || error.textStatus === 'timeout' || (error.xhr && (error.xhr.status === 401 || error.xhr.status === 403 || error.xhr.status >= 500)); }))
                        return { code: 'CONNECTION_ERROR' };
                    else
                        return { allErrors: allErrors };
                },
                deferEvaluation: true
            })
        };
    };

    var currentViewDataModel = ko.observable(getNewDataModel());

    self.isFirstLoad = ko.computed(function() {
        return currentViewDataModel().isInitializing();
    });
    self.hasConnectionWorked = ko.observable(false);

    var thisClientBranchFilterExcludeProperties = Utils.getObservableArrayBackedByStorage(/*storage:*/ window.localStorage, /*storageKey:*/ getAppStorageKey('buildFilterExcludeProperties'));
    var thisClientBranchFilterExcludeFunctions = ko.computed(function () {
        return _(thisClientBranchFilterExcludeProperties()).map(function(branchToExcludeProps) {
            return function(branchToTest) {
                return ((!branchToExcludeProps.branchName && !branchToTest.name) || (branchToTest.name === branchToExcludeProps.branchName)) && branchToTest.buildType.id === branchToExcludeProps.buildTypeId;
            };
        });

    });

    self.excludedBuilds = {
        get length() { return thisClientBranchFilterExcludeProperties().length },
        push: function (build) {
            thisClientBranchFilterExcludeProperties.push({
                branchName: build.branchName && build.branchName(),
                buildTypeId: build.buildTypeId()
            });
        },
        removeAll: function () {
            thisClientBranchFilterExcludeProperties.removeAll();
        }
    };

    self.builds = ko.computed({
        read: function () {
            return currentViewDataModel().allLoadedBuildsOfAllProjects();
        },
        deferEvaluation: true
    });

    self.mainBuild = (function () {
        var isResultUpdate = false;
        var lastMainBuild = undefined;

        var mainBuildFromApi = ko.observable();

        var timeOfLastNotifyOfMainBuild = Utils.getObservableBackedByStorage(
            /*storage:*/ window.sessionStorage, // So that refreshing the same tab doesn't makes us notify again (e.g. play the sound), but if we restart the browser or use a new tab, we get fresh notifications.
            /*storageKey:*/ 'timeOfLastNotifyOfMainBuild'
            );

        var mainBuildUrl = ko.computed({
            read: function() {
                var url = null;
                if (Settings.mainBranch)
                    url = getBuildStatusUrlForBranch(Settings.mainBranch);
                else if (!currentViewDataModel().isInitializing()) {
                    var build = currentViewDataModel().allBuildsOfAllProjectsOrPlaceholders()[0];
                    if (build && !build.isError)
                        url = getBuildStatusUrlForBuildId(build.id());
                }
                return url;
            },
            deferEvaluation: true,
        });

        ko.computed({
            read: function () {
                if (mainBuildUrl() && !isResultUpdate) {
                    $.ajax({
                        dataType: "json",
                        url: mainBuildUrl() + '?' + Utils.getTsQSParam(),
                        xhrFields: { withCredentials: true }
                    }).always(function (build, status, xhr) {
                        try {
                            isResultUpdate = true;

                            var error = Utils.getErrorFromAjaxAlways.apply(this, arguments);
                            if (error) {
                                mainBuildFromApi(undefined); // TODO show the error
                                return;
                            }

                            if (lastMainBuild === xhr.responseText)
                                return;
                            lastMainBuild = xhr.responseText;

                            build.isNew = !timeOfLastNotifyOfMainBuild() || (build.startDate > timeOfLastNotifyOfMainBuild());

                            timeOfLastNotifyOfMainBuild(build.startDate);

                            var mainBuildModel = ko.mapping.fromJS(build, {
                                create: function (options) {
                                    return new MainBuildViewModel(options.data);
                                }
                            });

                            mainBuildModel.investigations = getInvestigationsForBuildType(build.buildTypeId);

                            mainBuildModel.changes = (function () {
                                var changesFromApi = ko.observable([]);
                                var isResultUpdate = false;

                                return ko.computed({
                                    read: function () {
                                        if (!isResultUpdate) {
                                            $.ajax({
                                                dataType: "json",
                                                url: Settings.teamCityBaseUrl + build.changes.href + Utils.getTsQSParam(),
                                                xhrFields: { withCredentials: true }
                                            }).always(function (changesResult) {
                                                try {
                                                    var error = Utils.getErrorFromAjaxAlways.apply(this, arguments);
                                                    if (error) {
                                                        mainBuildFromApi(undefined); // TODO show the error
                                                        return;
                                                    }

                                                    isResultUpdate = true;
                                                    changesFromApi(changesResult.change || []);
                                                } finally {
                                                    isResultUpdate = false;
                                                }
                                            })
                                            ;
                                        }
                                        return changesFromApi();
                                    },
                                    deferEvaluation: true
                                });
                            })();

                            mainBuildFromApi(mainBuildModel);
                        } finally {
                            isResultUpdate = false;
                        }
                    });
                }

                return mainBuildFromApi();
            },
        });

        return mainBuildFromApi;
    })();

    function getInvestigationsForBuildType(buildTypeId) {
        var refreshTrigger = ko.observable();
        var investigationsFromApi = ko.observable({ isLoadingPlaceholder: true });
        var isResultUpdate = false;
        var observableInvestigations = ko.computed({
            read: function () {
                refreshTrigger(); // This add dependency on the refresh trigger, so that we recompute again when it fires.
                if (!isResultUpdate) {
                    $.ajax({
                        dataType: "json",
                        url: Settings.restApiBaseUrl + '/investigations?locator=buildType:(id:(' + buildTypeId + '))' + Utils.getTsQSParam(),
                        xhrFields: { withCredentials: true },
                    }).always(function (data) {
                        try {
                            isResultUpdate = true;
                            investigationsFromApi(Utils.getErrorFromAjaxAlways.apply(this, arguments) || data.investigation || []);
                        } finally {
                            isResultUpdate = false;
                        }
                    });
                }

                return investigationsFromApi();
            },
            deferEvaluation: true
        });
        observableInvestigations.isInvestigated = ko.computed({
            read: function() {
                return !!_(observableInvestigations()).filter(function (investigation) { return investigation.state !== 'GIVEN_UP'; }).length;
            },
            deferEvaluation: true,
        });
        observableInvestigations.refresh = function () { refreshTrigger.notifySubscribers(); };
        return observableInvestigations;
    }

    self.audio = {
        volume: Utils.getObservableBackedByStorage(window.localStorage, 'audio.volume', 1),
        isMuted: Utils.getObservableBackedByStorage(window.localStorage, 'audio.isMuted', false)
    };

    var imageUpdateTickSource = ko.observable();

    self.getImageForStatus = function(status) {
        return ko.computed(function() {
            imageUpdateTickSource();
            return Images[status].getRandom();
        });
    }

    function updateData() {
        var newDataModel = getNewDataModel();
        newDataModel.isInitializing.subscribe(function (isInitializing) {
            if (!isInitializing) {
                currentViewDataModel(newDataModel);
                self.mainBuild() && self.mainBuild().investigations.refresh();
                ensureDataAutoUpdate();
            }
        });
    }

    function ensureDataAutoUpdate() {
        if (Settings.enableAutoUpdate)
            setTimeout(updateData, Settings.dataUpdateIntervalMs);
    }

    self.errorsInfo = ko.computed({
        read: function() {
            return currentViewDataModel().errorsInfo();
        },
        deferEvaluation: true
    });

    self.init = function () {
        setInterval(function () { imageUpdateTickSource(!imageUpdateTickSource()); }, Settings.buildImageIntervalMs);
        ensureDataAutoUpdate();
        if (Settings.enableAutoUpdate && Settings.appUpdateIntervalMs)
            setTimeout(function() { location.reload(/*withoutCache*/ true); }, Settings.appUpdateIntervalMs);
    };

    self.init();
};


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Patterson, R. T. 1990. New and renamed species of benthic foraminifera from the Pleistocene Santa Barbara Formation of California. Journal of Paleontology, 64(5): 681-691.

#### Original name
null

### Remarks
null


text:
/***************************************************************************
 *
 * This file is part of the 'dxpath mule module' project at
 * https://github.com/skjolber/mule-module-dxpath
 *
 * 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.mule.module.dxpath;

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

import javax.xml.namespace.QName;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.mule.api.MuleMessage;
import org.mule.api.expression.ExpressionRuntimeException;
import org.mule.api.lifecycle.InitialisationException;
import org.mule.api.registry.RegistrationException;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.CoreMessages;
import org.mule.config.i18n.MessageFactory;
import org.mule.module.xml.stax.MapNamespaceContext;
import org.mule.module.xml.util.NamespaceManager;
import org.mule.transformer.AbstractMessageTransformer;
import org.mule.transformer.types.DataTypeFactory;
import org.mule.transport.NullPayload;
import org.xml.sax.InputSource;

public class DxTransformer extends AbstractMessageTransformer {
	/**
	 * Result type.
	 */
	public enum ResultType {
		NODESET, NODE, STRING, BOOLEAN, NUMBER
	}

    // keep at least 1 XSLT Transformer ready by default
    private static final int MIN_IDLE_TRANSFORMERS = 1;
    // keep max. 32 XSLT Transformers around by default
    private static final int MAX_IDLE_TRANSFORMERS = 32;
    // MAX_IDLE is also the total limit
    private static final int MAX_ACTIVE_TRANSFORMERS = MAX_IDLE_TRANSFORMERS;

    protected final GenericObjectPool transformerPool;

	private volatile String expression;
	private volatile QName resultType;

	private volatile Map<String, Object> contextProperties;

	private volatile String[] keys;
	private volatile Object[] values;

	public DxTransformer() {
		super();

		transformerPool = new GenericObjectPool(new PooledDxTransformerFactory());
        transformerPool.setMinIdle(MIN_IDLE_TRANSFORMERS);
        transformerPool.setMaxIdle(MAX_IDLE_TRANSFORMERS);
        transformerPool.setMaxActive(MAX_ACTIVE_TRANSFORMERS);

		registerSourceType(DataTypeFactory.create(org.w3c.dom.Node.class));
		registerSourceType(DataTypeFactory.create(InputSource.class));
		registerSourceType(DataTypeFactory.create(NullPayload.class));

		contextProperties = new HashMap<String, Object>();
	}

	@Override
	public void initialise() throws InitialisationException {
		super.initialise();

		if (expression == null) {
			throw new InitialisationException(MessageFactory.createStaticMessage("An expression must be supplied to the Dynamic XPath Transformer"), this);
		}

        try {
        	transformerPool.addObject();
        } catch (Throwable te) {
        	throw new InitialisationException(te, this);
        }

        // transform context properties to thread safe alternative
        List<String> keys = new ArrayList<String>();
        List<Object> values = new ArrayList<Object>();

		for (Entry<String, Object> entryParameter : contextProperties.entrySet()) {
			keys.add(entryParameter.getKey());
			values.add(entryParameter.getValue());
		}

		this.keys = keys.toArray(new String[keys.size()]);
		this.values = values.toArray(new String[values.size()]);
	}

	/**
	 * @return Returns the expression.
	 */
	public String getExpression() {
		return expression;
	}

	/**
	 * @param expression
	 *            The expression to set.
	 */
	public void setExpression(String expression) {
		this.expression = expression;
	}

	/**
	 * Result type from this transformer.
	 *
	 * @param resultType
	 *            Result type from this transformer.
	 */
	public void setResultType(ResultType resultTypeType) {
		QName resultType;
		switch (resultTypeType) {
		case BOOLEAN:
			resultType = XPathConstants.BOOLEAN;
			break;
		case NODE:
			resultType = XPathConstants.NODE;
			break;
		case NODESET:
			resultType = XPathConstants.NODESET;
			break;
		case NUMBER:
			resultType = XPathConstants.NUMBER;
			break;
		default:
			resultType = XPathConstants.STRING;
			break;
		}
		this.resultType = resultType;
	}

	/**
	 * Gets the parameters to be used when applying the transformation
	 *
	 * @return a map of the parameter names and associated values
	 * @see javax.xml.transform.Transformer#setParameter(java.lang.String,
	 *      java.lang.Object)
	 */
	public Map<String, Object> getContextProperties() {
		return contextProperties;
	}

	/**
	 * Sets the parameters to be used when applying the transformation
	 *
	 * @param contextProperties
	 *            a map of the parameter names and associated values
	 * @see javax.xml.transform.Transformer#setParameter(java.lang.String,
	 *      java.lang.Object)
	 */
	public void setContextProperties(Map<String, Object> contextProperties) {
		this.contextProperties = contextProperties;
	}

	protected Object evaluateTransformParameter(String key, Object value, MuleMessage message) throws TransformerException {
		if (value instanceof String) {
			return muleContext.getExpressionManager().parse(value.toString(), message);
		}

		return value;
	}

	@Override
	public Object transformMessage(MuleMessage message, String putputEncoding) throws TransformerException {

		try {
			DxOperator operator = null;
			try {
				operator = (DxOperator) transformerPool.borrowObject();
				bindParameters(operator, message);

				Object src = message.getPayload();
				try {
					if (src instanceof InputSource) {
						return operator.evaluate((InputSource) src, expression, resultType);
					} else if (src instanceof NullPayload) {
						return operator.evaluateNull(expression, resultType);
					} else {
						return operator.evaluate(src, expression, resultType);
					}
				} catch (Exception e) {
					throw new TransformerException(this, e);
				}
			} finally {
				if(operator != null) {
					unbindParameters(operator);
					transformerPool.returnObject(operator);
				}
			}
		} catch (Exception e) {
			throw new TransformerException(this, e);
        }
	}

	protected void bindParameters(DxOperator operator, MuleMessage message) throws TransformerException, XPathExpressionException {
		operator.compile(expression);

		DxVariableResolver variableResolver = operator.getVariableResolver();
		if (contextProperties != null) {
			// resolve parameters dynamically
			for(int i = 0; i < keys.length; i++) {
				Object value = evaluateTransformParameter(keys[i], values[i], message);

				variableResolver.newVariable(keys[i], value);
			}
		}
	}

	/**
     * Removes any parameter bindings
     *
     * @param transformer the transformer to remove properties from
     */
    protected void unbindParameters(DxOperator operator)  {
		DxVariableResolver variableResolver = operator.getVariableResolver();
		variableResolver.clear();
    }

	/**
     * @return The current maximum number of allowable active transformer objects in
     *         the pool
     */
    public int getMaxActiveTransformers()
    {
        return transformerPool.getMaxActive();
    }

    /**
     * Sets the the current maximum number of active transformer objects allowed in the
     * pool
     *
     * @param maxActiveTransformers New maximum size to set
     */
    public void setMaxActiveTransformers(int maxActiveTransformers)
    {
        transformerPool.setMaxActive(maxActiveTransformers);
    }

    /**
     * @return The current maximum number of allowable idle transformer objects in the
     *         pool
     */
    public int getMaxIdleTransformers()
    {
        return transformerPool.getMaxIdle();
    }

    /**
     * Sets the the current maximum number of idle transformer objects allowed in the pool
     *
     * @param maxIdleTransformers New maximum size to set
     */
    public void setMaxIdleTransformers(int maxIdleTransformers)
    {
        transformerPool.setMaxIdle(maxIdleTransformers);
    }

	protected class PooledDxTransformerFactory extends BasePoolableObjectFactory
    {
        @Override
        public Object makeObject() throws Exception
        {
    		NamespaceManager namespaceManager = null;
    		try {
    			namespaceManager = muleContext.getRegistry().lookupObject(NamespaceManager.class);
    		} catch (RegistrationException e) {
    			throw new ExpressionRuntimeException(CoreMessages.failedToLoad("NamespaceManager"), e);
    		}

    		HashMap<String, String> prefixToNamespaceMap = new HashMap<String, String>();
    		if (namespaceManager != null) {
    			prefixToNamespaceMap.putAll(namespaceManager.getNamespaces());
    		}

    		MapNamespaceContext namespaceContext = new MapNamespaceContext(prefixToNamespaceMap);

    		DxVariableResolver variableResolver = new DxVariableResolver();

			DxOperator operator = new DxOperator(namespaceContext, variableResolver);

			return operator;
        }
    }

}


text:
require 'test/test_helper'

class App
  include Rack::RespondTo
end

class TestRespondTo < MiniTest::Unit::TestCase

  def setup
    Rack::RespondTo.selected_media_type = nil
    Rack::RespondTo.media_types = nil
    Rack::RespondTo.env = nil
  end

  ## api

  test "env accessor" do
    env = {'HTTP_ACCEPT' => 'text/html,application/xml'}
    Rack::RespondTo.env = env
    assert_equal env, Rack::RespondTo.env
  end

  test "media types accessor" do
    Rack::RespondTo.media_types = %w( application/xml )
    assert_equal %w( application/xml ), Rack::RespondTo.media_types
    assert_equal %w( application/xml ), Rack::RespondTo.mime_types  #alias
  end

  test "selected media type reader" do
    Rack::RespondTo.media_types = %w( application/xml )
    body = App.respond_to do |format|
      format.xml { 'xml' }
    end
    assert_equal 'application/xml', Rack::RespondTo.selected_media_type
    assert_equal 'application/xml', Rack::RespondTo.selected_mime_type  #alias
  end

  test "mixin injects respond_to class method" do
    assert App.respond_to?(:respond_to)
  end

  test "mixin injects respond_to instance method" do
    assert App.new.respond_to?(:respond_to)
  end

  ## requested media types

  test "explicitly specified media types take precedence over header's" do
    Rack::RespondTo.env = {'HTTP_ACCEPT' => 'text/html'}
    Rack::RespondTo.media_types = %w( text/plain )
    assert_equal %w( text/plain ), Rack::RespondTo.media_types
  end

  ## respond_to

  test "respond_to returns block for highest ranking format" do
    Rack::RespondTo.env = {'HTTP_ACCEPT' => 'application/xml;q=0.8,text/plain;q=0.9'}
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal 'txt', body
  end

  test "cascades down the Accept header's list to find suitable type" do
    Rack::RespondTo.env = {'HTTP_ACCEPT' => 'text/html,text/plain;q=0.9'}
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal 'txt', body
  end

  test "respond_to with no matching format" do
    Rack::RespondTo.media_types = %w( text/html )
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal nil, body
  end

  test "respond_to with empty type list" do
    Rack::RespondTo.media_types = []
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal nil, body
  end

  test "respond_to with nil type list" do
    Rack::RespondTo.media_types = nil
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal nil, body
  end

  test "respond_to handles synonymous formats" do
    Rack::RespondTo.media_types = %w( text/html )

    body = App.respond_to do |format|
      format.htm { 'htm' } # htm/html
      format.xml { 'xml' }
    end
    assert_equal 'htm', body

    body = App.respond_to do |format|
      format.html { 'html' } # htm/html
      format.json { 'json' }
    end
    assert_equal 'html', body
  end

  test "respond_to handles types with special chars" do
    Rack::RespondTo.media_types = %w( application/rss+xml )
    body = App.respond_to do |format|
      format.rss { 'rss' }
    end
    assert_equal 'rss', body

    Rack::RespondTo.media_types = %w( video/x-msvideo )
    body = App.respond_to do |format|
      format.avi { 'avi' }
    end
    assert_equal 'avi', body

    Rack::RespondTo.media_types = %w( application/x-bzip2 )
    body = App.respond_to do |format|
      format.bz2 { 'bz2' }
    end
    assert_equal 'bz2', body
  end

  test "repond_to sets selected media type" do
    Rack::RespondTo.media_types = %w( text/html text/plain )
    assert_equal nil, Rack::RespondTo.selected_media_type
    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal 'txt', body
    assert_equal 'text/plain', Rack::RespondTo.selected_media_type
  end

  ## wildcard media types

  test "wildcard type matches first handler" do
    Rack::RespondTo.media_types = %w( */* )

    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
    end
    assert_equal 'xml', body

    body = App.respond_to do |format|
      format.txt { 'txt' }
      format.xml { 'xml' }
    end
    assert_equal 'txt', body
  end

  test "wildcard subtype matches first handler for type" do
    Rack::RespondTo.media_types = %w( text/* )

    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.txt { 'txt' }
      format.htm { 'htm' }
    end
    assert_equal 'txt', body

    body = App.respond_to do |format|
      format.xml { 'xml' }
      format.htm { 'htm' }
      format.txt { 'txt' }
    end
    assert_equal 'htm', body

    body = App.respond_to do |format|
      format.xml { 'xml' }
    end
    assert_equal nil, body
  end

  ## catch-all format

  test "catch-all format" do
    Rack::RespondTo.media_types = %w( text/html application/xml )

    body = App.respond_to do |format|
      format.txt { 'txt' }
      format.avi { 'avi' }
      format.any { 'any' }
    end
    assert_equal 'any', body
    assert_equal 'text/html', Rack::RespondTo.selected_media_type

    body = App.respond_to do |format|
      format.htm { 'htm' }
      format.xml { 'xml' }
      format.any { 'any' }
    end
    assert_equal 'htm', body
    assert_equal 'text/html', Rack::RespondTo.selected_media_type
  end
end


text:
package org.accela.cellmatrix;

public interface StrategyFactory {

}


text:
import { IncomingMessage, ServerResponse } from "http";
import { check } from "./helpers";
import connect from "connect";
import supertest from "supertest";

import * as helmet from "..";

import contentSecurityPolicy from "../middlewares/content-security-policy";
import crossOriginEmbedderPolicy from "../middlewares/cross-origin-embedder-policy";
import crossOriginOpenerPolicy from "../middlewares/cross-origin-opener-policy";
import crossOriginResourcePolicy from "../middlewares/cross-origin-resource-policy";
import expectCt from "../middlewares/expect-ct";
import referrerPolicy from "../middlewares/referrer-policy";
import originAgentCluster from "../middlewares/origin-agent-cluster";
import strictTransportSecurity from "../middlewares/strict-transport-security";
import xContentTypeOptions from "../middlewares/x-content-type-options";
import xDnsPrefetchControl from "../middlewares/x-dns-prefetch-control";
import xDownloadOptions from "../middlewares/x-download-options";
import xFrameOptions from "../middlewares/x-frame-options";
import xPermittedCrossDomainPolicies from "../middlewares/x-permitted-cross-domain-policies";
import xPoweredBy from "../middlewares/x-powered-by";
import xXssProtection from "../middlewares/x-xss-protection";

describe("helmet", () => {
  const topLevel = helmet.default;

  it("includes all middleware, except Expect-CT, with their default options", async () => {
    // NOTE: This test relies on the CSP object being ordered a certain way,
    // which could change (and be non-breaking). If that becomes a problem,
    // we should update this test to be more robust.
    const expectedHeaders = {
      "content-security-policy":
        "default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests",
      "cross-origin-embedder-policy": "require-corp",
      "cross-origin-opener-policy": "same-origin",
      "cross-origin-resource-policy": "same-origin",
      // In Helmet 7, we can remove this Expect-CT assertion.
      "expect-ct": null,
      "origin-agent-cluster": "?1",
      "referrer-policy": "no-referrer",
      "strict-transport-security": "max-age=15552000; includeSubDomains",
      "x-content-type-options": "nosniff",
      "x-dns-prefetch-control": "off",
      "x-download-options": "noopen",
      "x-frame-options": "SAMEORIGIN",
      "x-permitted-cross-domain-policies": "none",
      "x-powered-by": null,
      "x-xss-protection": "0",
    };

    await check(topLevel(), expectedHeaders);
    await check(topLevel({}), expectedHeaders);
    await check(topLevel(Object.create(null)), expectedHeaders);
  });

  it("allows individual middlewares to be disabled", async () => {
    await check(topLevel({ contentSecurityPolicy: false }), {
      "content-security-policy": null,
    });
    await check(topLevel({ dnsPrefetchControl: false }), {
      "x-dns-prefetch-control": null,
    });
  });

  // In Helmet 7, this test should be removed.
  it("allows Expect-CT to be enabled", async () => {
    await check(topLevel({ expectCt: true }), {
      "expect-ct": "max-age=0",
    });
    await check(topLevel({ expectCt: { maxAge: 123 } }), {
      "expect-ct": "max-age=123",
    });
  });

  it("works with all default middlewares disabled", async () => {
    await check(
      topLevel({
        contentSecurityPolicy: false,
        dnsPrefetchControl: false,
        expectCt: false,
        frameguard: false,
        hidePoweredBy: false,
        hsts: false,
        ieNoOpen: false,
        noSniff: false,
        originAgentCluster: false,
        permittedCrossDomainPolicies: false,
        referrerPolicy: false,
        xssFilter: false,
        crossOriginEmbedderPolicy: false,
      }),
      {
        "content-security-policy": null,
        "x-frame-options": null,
      }
    );
  });

  it("errors when `use`d directly", () => {
    const fakeRequest = {
      constructor: {
        name: "IncomingMessage",
      },
    };

    expect(() => {
      topLevel(fakeRequest as any);
    }).toThrow();
  });

  it("allows default middleware to be explicitly enabled (a no-op)", async () => {
    await check(topLevel({ frameguard: true }), {
      "x-frame-options": "SAMEORIGIN",
    });
  });

  it("allows Cross-Origin-Embedder-Policy middleware to be enabled", async () => {
    await check(topLevel({ crossOriginEmbedderPolicy: true }), {
      "cross-origin-embedder-policy": "require-corp",
    });
  });

  it("allows Cross-Origin-Embedder-Policy middleware to be explicitly disabled", async () => {
    await check(topLevel({ crossOriginEmbedderPolicy: false }), {
      "cross-origin-embedder-policy": null,
    });
  });

  it("allows Cross-Origin-Opener-Policy middleware to be enabled with its default", async () => {
    await check(topLevel({ crossOriginOpenerPolicy: true }), {
      "cross-origin-opener-policy": "same-origin",
    });
  });

  it("allows Cross-Origin-Opener-Policy middleware to be enabled with custom arguments", async () => {
    await check(
      topLevel({
        crossOriginOpenerPolicy: { policy: "same-origin-allow-popups" },
      }),
      {
        "cross-origin-opener-policy": "same-origin-allow-popups",
      }
    );
  });

  it("allows Cross-Origin-Opener-Policy middleware to be explicitly disabled", async () => {
    await check(topLevel({ crossOriginOpenerPolicy: false }), {
      "cross-origin-opener-policy": null,
    });
  });

  it("allows Cross-Origin-Resource-Policy middleware to be enabled with its default", async () => {
    await check(topLevel({ crossOriginResourcePolicy: true }), {
      "cross-origin-resource-policy": "same-origin",
    });
  });

  it("allows Cross-Origin-Resource-Policy middleware to be enabled with custom arguments", async () => {
    await check(
      topLevel({ crossOriginResourcePolicy: { policy: "same-site" } }),
      {
        "cross-origin-resource-policy": "same-site",
      }
    );
  });

  it("allows Cross-Origin-Resource-Policy middleware to be explicitly disabled", async () => {
    await check(topLevel({ crossOriginResourcePolicy: false }), {
      "cross-origin-resource-policy": null,
    });
  });

  it("allows Origin-Agent-Cluster middleware to be enabled", async () => {
    await check(topLevel({ originAgentCluster: true }), {
      "origin-agent-cluster": "?1",
    });
  });

  it("allows Origin-Agent-Cluster middleware to be explicitly disabled", async () => {
    await check(topLevel({ originAgentCluster: false }), {
      "origin-agent-cluster": null,
    });
  });

  it("properly handles a middleware calling `next()` with an error", async () => {
    const app = connect()
      .use(
        topLevel({
          contentSecurityPolicy: {
            directives: {
              defaultSrc: ["'self'", () => "bad;value"],
            },
          },
        })
      )
      .use(
        (
          err: Error,
          _req: IncomingMessage,
          res: ServerResponse,
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          _next: () => void
        ) => {
          res.statusCode = 500;
          res.setHeader("Content-Type", "application/json");
          res.end(JSON.stringify({ message: err.message }));
        }
      );

    await supertest(app).get("/").expect(500, {
      message:
        'Content-Security-Policy received an invalid directive value for "default-src"',
    });
  });

  describe("warnings", () => {
    beforeEach(() => {
      jest.spyOn(console, "warn").mockImplementation(() => {});
    });

    it("logs a warning when passing options to crossOriginEmbedderPolicy", () => {
      topLevel({ crossOriginEmbedderPolicy: { option: "foo" } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "crossOriginEmbedderPolicy does not take options. Remove the property to silence this warning."
      );
    });

    it("logs a warning when passing options to hidePoweredBy", () => {
      topLevel({ hidePoweredBy: { setTo: "deprecated option" } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "hidePoweredBy does not take options. Remove the property to silence this warning."
      );
    });

    it("logs a warning when passing options to ieNoOpen", () => {
      topLevel({ ieNoOpen: { option: "foo" } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "ieNoOpen does not take options. Remove the property to silence this warning."
      );
    });

    it("logs a warning when passing options to originAgentCluster", () => {
      topLevel({ originAgentCluster: { option: "foo" } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "originAgentCluster does not take options. Remove the property to silence this warning."
      );
    });

    it("logs a warning when passing options to noSniff", () => {
      topLevel({ noSniff: { option: "foo" } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "noSniff does not take options. Remove the property to silence this warning."
      );
    });

    it("logs a warning when passing options to xssFilter", () => {
      topLevel({ xssFilter: { setOnOldIe: true } as any });

      expect(console.warn).toHaveBeenCalledTimes(1);
      expect(console.warn).toHaveBeenCalledWith(
        "xssFilter does not take options. Remove the property to silence this warning."
      );
    });
  });

  describe("module aliases", () => {
    it("aliases the X-DNS-Prefetch-Control middleware to helmet.dnsPrefetchControl", () => {
      expect(helmet.dnsPrefetchControl.name).toBe(xDnsPrefetchControl.name);
      expect(helmet.dnsPrefetchControl.name).toBe("xDnsPrefetchControl");
    });

    it("aliases the Cross-Origin-Embedder-Policy middleware to helmet.crossOriginEmbedderPolicy", () => {
      expect(helmet.crossOriginEmbedderPolicy.name).toBe(
        crossOriginEmbedderPolicy.name
      );
      expect(helmet.crossOriginEmbedderPolicy.name).toBe(
        "crossOriginEmbedderPolicy"
      );
    });

    it("aliases the Cross-Origin-Opener-Policy middleware to helmet.crossOriginOpenerPolicy", () => {
      expect(helmet.crossOriginOpenerPolicy.name).toBe(
        crossOriginOpenerPolicy.name
      );
      expect(helmet.crossOriginOpenerPolicy.name).toBe(
        "crossOriginOpenerPolicy"
      );
    });

    it("aliases the Cross-Origin-Resource-Policy middleware to helmet.crossOriginResourcePolicy", () => {
      expect(helmet.crossOriginResourcePolicy.name).toBe(
        crossOriginResourcePolicy.name
      );
      expect(helmet.crossOriginResourcePolicy.name).toBe(
        "crossOriginResourcePolicy"
      );
    });

    it("aliases the X-Content-Type-Options middleware to helmet.noSniff", () => {
      expect(helmet.noSniff.name).toBe(xContentTypeOptions.name);
      expect(helmet.noSniff.name).toBe("xContentTypeOptions");
    });

    it("aliases the Expect-CT middleware to helmet.expectCt", () => {
      expect(helmet.expectCt.name).toBe(expectCt.name);
      expect(helmet.expectCt.name).toBe("expectCt");
    });

    it("aliases the X-Permitted-Cross-Domain-Policies middleware to helmet.crossdomain", () => {
      expect(helmet.permittedCrossDomainPolicies.name).toBe(
        xPermittedCrossDomainPolicies.name
      );
      expect(helmet.permittedCrossDomainPolicies.name).toBe(
        "xPermittedCrossDomainPolicies"
      );
    });

    it("aliases the X-Frame-Options middleware to helmet.frameguard", () => {
      expect(helmet.frameguard.name).toBe(xFrameOptions.name);
      expect(helmet.frameguard.name).toBe("xFrameOptions");
    });

    it("aliases the Content-Security-Policy middleware to helmet.contentSecurityPolicy", () => {
      expect(helmet.contentSecurityPolicy.name).toBe(
        contentSecurityPolicy.name
      );
      expect(helmet.contentSecurityPolicy.name).toBe("contentSecurityPolicy");
    });

    it("aliases the X-Powered-By middleware to helmet.hidePoweredBy", () => {
      expect(helmet.hidePoweredBy.name).toBe(xPoweredBy.name);
      expect(helmet.hidePoweredBy.name).toBe("xPoweredBy");
    });

    it("aliases the Strict-Transport-Security middleware to helmet.hsts", () => {
      expect(helmet.hsts.name).toBe(strictTransportSecurity.name);
      expect(helmet.hsts.name).toBe("strictTransportSecurity");
    });

    it("aliases the X-Download-Options middleware to helmet.ieNoOpen", () => {
      expect(helmet.ieNoOpen.name).toBe(xDownloadOptions.name);
      expect(helmet.ieNoOpen.name).toBe("xDownloadOptions");
    });

    it("aliases the Referrer-Policy middleware to helmet.referrerPolicy", () => {
      expect(helmet.referrerPolicy.name).toBe(referrerPolicy.name);
      expect(helmet.referrerPolicy.name).toBe("referrerPolicy");
    });

    it("aliases the Origin-Agent-Cluster middleware to helmet.originAgentCluster", () => {
      expect(helmet.originAgentCluster.name).toBe(originAgentCluster.name);
      expect(helmet.originAgentCluster.name).toBe("originAgentCluster");
    });

    it("aliases the X-XSS-Protection middleware to helmet.xssFilter", () => {
      expect(helmet.xssFilter.name).toBe(xXssProtection.name);
      expect(helmet.xssFilter.name).toBe("xXssProtection");
    });
  });
});


text:
use simple_redis;

fn main() {
    match simple_redis::create("redis://127.0.0.1:6379/") {
        Ok(mut client) => {
            println!("Created Redis Client");

            match client.set("my_key", "my_value") {
                Err(error) => println!("Unable to set value in Redis: {}", error),
                _ => println!("Value set in Redis"),
            };

            match client.quit() {
                Err(error) => println!("Error: {}", error),
                _ => println!("Connection Closed."),
            }
        }
        Err(error) => println!("Unable to create Redis client: {}", error),
    }
}


text:
print("Creating mongodb user " + DB_USER)
db.createUser({user: DB_USER, pwd: DB_PASSWORD, roles:[{role:"root", db:"admin"}]})
print("OK")


text:
'use strict';

moduloEspecialidad.controller('EspecialidadNewController', ['$scope', '$routeParams', '$location', 'serverService', 'especialidadService', 'sharedSpaceService', '$filter', '$uibModal',
    function ($scope, $routeParams, $location, serverService, especialidadService, sharedSpaceService, $filter, $uibModal) {
        $scope.fields = especialidadService.getFields();
        $scope.obtitle = especialidadService.getObTitle();
        $scope.icon = especialidadService.getIcon();
        $scope.ob = especialidadService.getTitle();
        $scope.title = "Creando una nueva " + $scope.obtitle;
        $scope.op = "plist";
        $scope.status = null;
        $scope.debugging = serverService.debugging();
        $scope.bean = {id: 0};
        $scope.save = function () {
            $scope.bean.creation = $filter('date')($scope.bean.creation, "dd/MM/yyyy");
            $scope.bean.modification = $filter('date')($scope.bean.modification, "dd/MM/yyyy");
            var jsonToSend = {json: JSON.stringify(serverService.array_identificarArray($scope.bean))};
            serverService.promise_setOne($scope.ob, jsonToSend).then(function (response) {
                if (response.status == 200) {
                    if (response.data.status == 200) {
                        $scope.response = response;
                        $scope.status = "El registro " + $scope.obtitle + " se ha creado con id = " + response.data.message;
                        $scope.bean.id = response.data.message;
                    } else {
                        $scope.status = "Error en la recepción de datos del servidor";
                    }
                } else {
                    $scope.status = "Error en la recepción de datos del servidor";
                }
            }).catch(function (data) {
                $scope.status = "Error en la recepción de datos del servidor";
            });
            ;
        };
        $scope.back = function () {
            window.history.back();
        };
        $scope.close = function () {
            $location.path('/home');
        };
        $scope.plist = function () {
            $location.path('/' + $scope.ob + '/plist');
        };
        $scope.chooseOne = function (nameForeign, foreignObjectName, contollerName) {
            var modalInstance = $uibModal.open({
                templateUrl: 'js/' + foreignObjectName + '/selection.html',
                controller: contollerName,
                size: 'lg'
            }).result.then(function (modalResult) {
                $scope.bean[nameForeign].id = modalResult;
            });
        };
    }]);


text:
import pygame

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)

# This is a simple class that will help us print to the screen
# It has nothing to do with the joysticks, just outputting the
# information.
class TextPrint:
    def __init__(self):
        self.reset()
        self.font = pygame.font.Font(None, 20)

    def print(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, [self.x, self.y])
        self.y += self.line_height

    def reset(self):
        self.x = 10
        self.y = 10
        self.line_height = 15

    def indent(self):
        self.x += 10

    def unindent(self):
        self.x -= 10

pygame.init()

# Set the width and height of the screen [width,height]
size = [500, 700]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Initialize the joysticks
pygame.joystick.init()

# Get ready to print
textPrint = TextPrint()

# -------- Main Program Loop -----------
while done==False:
    # EVENT PROCESSING STEP
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop

    # DRAWING STEP
    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)
    textPrint.reset()

    # Get count of joysticks
    textPrint.print(screen, "Hello")
    textPrint.print(screen, "World")

    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 20 frames per second
    clock.tick(20)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit ()


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>Oscilloscope (v. 1.0)</title>
	<link rel="stylesheet" href="css/style.css">
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">

Oscilloscope 1.0

							Type

							<select name="type" id="type">
								<option value="sine">Sine</option>
								<option value="square">Square</option>
								<option value="sawtooth">Sawtooth</option>
								<option value="triangle">Triangle</option>
							</select>

							Frequency (Hz)

							<input name="frequency" id="frequency" type="range" value="200" step="10" min="0" max="1000" />

							Detune (cents)

							<input name="detune" id="detune" type="range" value="0" step="5" min="-100" max="100" />

							Start after (s)

							<input name="startAfter" id="startAfter" type="text" placeholder="0 s (Default)" />

							<input type="submit" id="play" value="PLAY" onclick="writeSummary();"/>

						Type

						Frequency (Hz)

						Detune (cents)

						Start after (s)

							<input type="submit" id="stop" value="STOP" />

To see the documentation, click here.

Oscilloscope 1.0 is a Web Audio experiment by Mattia Salvi.

Documentation

			Back

Introduction

Keyboard Shortcuts

Introduction

What's Web Audio API?

The Web Audio API is a high-level JavaScript Application Programming Interface (API) that can be used for processing and synthesizing audio in web applications.

			The audio processing is actually handled by Assembly/C/C++ code within the browser, but the API allows us to control it with JavaScript.

What's Oscilloscope 1.0?

Oscilloscope 1.0 is a web application that allow you to generate sounds with the Web Audio API in your browser.

			This is based on Web Audio API Oscillators which will attempt to cover what oscillators are, how to create them, changing waveforms, setting frequency, and layering multiple oscillators together to create rich.

			An oscillator is a circuit that produces a repetitive, oscillating signal.

			Along with audio filters and audio controllers, audio oscillators are one of the basic elements required for modern analog subtractive synthesizers.

Type: is the shape and form of the signal that we are going to create.

Frequency: is the number of occurrences of a repeating event per unit time. (Hz).

Detune: it defines the standard frequency tuning. (Hz).

Start after: it indicates how many seconds later the sound must play

Oscilloscope (v. 1.0) is a Web Audio experiment by Mattia Salvi.

Documentation

			Back

Introduction

Keyboard Shortcuts

Keyboard Shortcuts

Shortcut Key for Start & Stop

Press [SPACE] to start/stop the oscilloscope.

Shortcut Keys for Type are S, Q, W and T

Press [S] to set the type to "Sine" (default)

Press [Q] to set the type to "Square"

Press [W] to set the type to "Sawtooth"

Press [T] to set the type to "Triangle"

Shortcut Keys for Frequency are 1, 2, and 3

Press [1] to set the frequency to 200 (default)

Press [2] to set the frequency to 500

Press [3] to set the frequency to 800

Shortcut Keys for Detune are 6, 7, and 8

Press [4] to set the detune to -30

Press [5] to set the detune to 0 (default)

Press [6] to set the detune to 50

Oscilloscope 1.0 is a Web Audio experiment by Mattia Salvi.


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Net.Security;
using System.ServiceModel.Description;
using Xunit;

public static class ContractDescriptionTest
{
    [Fact]
    public static void Ctor_Taking_Name_Initializes()
    {
        const string expectedName = "testName";
        ContractDescription cd = new ContractDescription(expectedName);
        Assert.Equal<string>(expectedName, cd.Name);
        Assert.Equal<string>("http://tempuri.org/", cd.Namespace);
        Assert.Null(cd.ContractType);
        Assert.Null(cd.CallbackContractType);
        Assert.NotNull(cd.Operations);
        Assert.Equal<int>(0, cd.Operations.Count);
        Assert.NotNull(cd.Behaviors);
        Assert.Equal<int>(0, cd.Behaviors.Count);
        Assert.NotNull(cd.ContractBehaviors);
        Assert.Equal<int>(0, cd.ContractBehaviors.Count);
    }

    [Fact]
    public static void Ctor_Taking_Name_With_Null_Throws()
    {
        Assert.Throws<ArgumentNullException>(() => new ContractDescription(null));
    }

    [Fact]
    public static void Ctor_Taking_Name_With_Empty_String_Throws()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContractDescription(string.Empty));
    }

    [Theory]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("testNamespace")]
    [InlineData("http://localhost")]
    public static void Ctor_Taking_Name_And_Namespace_Initializes(string nameSpace)
    {
        const string expectedName = "testName";
        ContractDescription cd = new ContractDescription(expectedName, nameSpace);
        Assert.Equal<string>(expectedName, cd.Name);
        string expectedNamespace = nameSpace == null ? "http://tempuri.org/" : nameSpace;
        Assert.Equal<string>(expectedNamespace, cd.Namespace);
        Assert.Null(cd.ContractType);
        Assert.Null(cd.CallbackContractType);
        Assert.NotNull(cd.Operations);
        Assert.Equal<int>(0, cd.Operations.Count);
        Assert.NotNull(cd.Behaviors);
        Assert.Equal<int>(0, cd.Behaviors.Count);
        Assert.NotNull(cd.ContractBehaviors);
        Assert.Equal<int>(0, cd.ContractBehaviors.Count);
    }

    [Theory]
    [InlineData(typeof(IWcfService))]
    [InlineData(null)]
    public static void ContractType_Property_Sets(Type contractType)
    {
        ContractDescription cd = new ContractDescription("test");
        cd.ContractType = contractType;
        Assert.Equal(contractType, cd.ContractType);
    }

    [Theory]
    [InlineData(typeof(IWcfService))]
    [InlineData(null)]
    public static void CallbackContractType_Property_Sets(Type contractType)
    {
        ContractDescription cd = new ContractDescription("test");
        cd.CallbackContractType = contractType;
        Assert.Equal<Type>(contractType, cd.CallbackContractType);
    }

    [Theory]
    [InlineData("name1")]
    public static void Name_Property_Sets(string name)
    {
        ContractDescription cd = new ContractDescription("test");
        cd.Name = name;
        Assert.Equal<string>(name, cd.Name);
    }

    [Fact]
    public static void Name_Property_With_Null_Throws()
    {
        ContractDescription cd = new ContractDescription("test");
        Assert.Throws<ArgumentNullException>(() => cd.Name = null);
    }

    [Fact]
    public static void Name_Property_With_Empty_String_Throws()
    {
        ContractDescription cd = new ContractDescription("test");
        Assert.Throws<ArgumentOutOfRangeException>(() => cd.Name = String.Empty);
    }

    [Theory]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("testNamespace")]
    [InlineData("http://localhost")]
    public static void Namespace_Property_Sets(string nameSpace)
    {
        ContractDescription cd = new ContractDescription("test");
        cd.Namespace = nameSpace;
        Assert.Equal<string>(nameSpace, cd.Namespace);
    }

    [Theory]
    [InlineData("http://invalid<>")]
    [InlineData("http://badencode%")]
    public static void Namespace_Property_Set_With_Invalid_Value_Throws(string nameSpace)
    {
        ContractDescription cd = new ContractDescription("test");
        Assert.Throws<ArgumentException>(() => cd.Namespace = nameSpace);
    }

    [Theory]
    [InlineData(ProtectionLevel.None)]
    [InlineData(ProtectionLevel.Sign)]
    [InlineData(ProtectionLevel.EncryptAndSign)]
    public static void ProtectionLevel_Property_Sets(ProtectionLevel level)
    {
        ContractDescription cd = new ContractDescription("test");
        cd.ProtectionLevel = level;
        Assert.Equal<ProtectionLevel>(level, cd.ProtectionLevel);
    }

    [Fact]
    public static void ProtectionLevel_Property_Set_With_Invalid_Value_Throws()
    {
        ContractDescription cd = new ContractDescription("test");
        Assert.Throws<ArgumentOutOfRangeException>(() => cd.ProtectionLevel = (ProtectionLevel)99);
    }
}


text:
package org.usfirst.frc4453.unitTest;

import org.usfirst.frc4453.commands.DriveSetDirection;

public class DriveSetDirectionSub extends DriveSetDirection {

	public void execute() {
		super.execute();
	}
}


text:
package net.floodlightcontroller.benchmarkcontroller;

import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.IFloodlightService;

public interface IQueueCreaterService extends IFloodlightService {

	/**
	 * Get queue configurations from one switch
	 * @param sw
	 */
    public void getAllQueueConfigs(IOFSwitch sw);

    /**
     * Create a queue on a switch
     * @param sw
     * @param portNumber
     * @param queueId
     * @param rate
     */
    public void createQueue(IOFSwitch sw, short portNumber, int queueId, short rate);

    /**
     * Delete a queue on a switch
     * @param sw
     * @param portNumber
     * @param queueId
     */
    public void deleteQueue(IOFSwitch sw, short portNumber, int queueId);

}


text:
""" Cog code generation tool.
    http://nedbatchelder.com/code/cog

    Copyright 2004-2005, Ned Batchelder.
"""

import time
start = time.clock()

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    mydir = path.dirname(path.dirname(path.abspath(__file__)))
    #print mydir
    sys.path.append(mydir)

import sys
from cogapp import Cog

ret = Cog().main(sys.argv)

#print "Time: %.2f sec" % (time.clock() - start)
sys.exit(ret)