text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.Data.Tables.Models;
using Azure.Data.Tables.Sas;
using Azure.Identity;
using NUnit.Framework;
using Parms = Azure.Data.Tables.TableConstants.Sas.Parameters;

namespace Azure.Data.Tables.Tests
{
    public class TableClientTests : ClientTestBase
    {
        public TableClientTests(bool isAsync) : base(isAsync)
        { }

        private const string TableName = "someTableName";
        private const string AccountName = "someaccount";
        private static readonly Uri _url = new Uri($"https://someaccount.table.core.windows.net");
        private readonly Uri _urlHttp = new Uri($"http://someaccount.table.core.windows.net");
        private MockTransport _transport;
        private TableClient client { get; set; }
        private const string Secret = "Kg==";
        private TableEntity entityWithoutPK = new TableEntity { { TableConstants.PropertyNames.RowKey, "row" } };
        private TableEntity entityWithoutRK = new TableEntity { { TableConstants.PropertyNames.PartitionKey, "partition" } };

        private TableEntity validEntity =
            new TableEntity { { TableConstants.PropertyNames.PartitionKey, "partition" }, { TableConstants.PropertyNames.RowKey, "row" } };

        private const string signature = "sv=2019-12-12&ss=t&srt=s&sp=rwdlacu&se=2020-08-28T23:45:30Z&st=2020-08-26T15:45:30Z&spr=https&sig=mySig&tn=someTableName";

        [SetUp]
        public void TestSetup()
        {
            _transport = new MockTransport(request => new MockResponse(204));
            var service_Instrumented = InstrumentClient(
                new TableServiceClient(
                    new Uri($"https://example.com?{signature}"),
                    new AzureSasCredential("sig"),
                    new TableClientOptions { Transport = _transport }));
            client = service_Instrumented.GetTableClient(TableName);
        }

        /// <summary>
        /// Validates the functionality of the TableServiceClient.
        /// </summary>
        [Test]
        public void ConstructorValidatesArguments()
        {
            Assert.Catch<ArgumentException>(
                () => new TableClient(_url, null, new TableSharedKeyCredential(AccountName, string.Empty)),
                "The constructor should validate the tableName.");

            Assert.That(
                () => new TableClient(null, TableName, new TableSharedKeyCredential(AccountName, string.Empty)),
                Throws.InstanceOf<ArgumentNullException>(),
                "The constructor should validate the url.");

            Assert.That(
                () => new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty), new TableClientOptions()),
                Throws.Nothing,
                "The constructor should accept valid arguments.");

            Assert.That(
                () => new TableClient(_url, TableName, null),
                Throws.InstanceOf<ArgumentNullException>(),
                "The constructor should validate the TablesSharedKeyCredential.");

            Assert.That(
                () => new TableClient(_urlHttp, new AzureSasCredential(signature)),
                Throws.InstanceOf<ArgumentException>(),
                "The constructor should validate the Uri is https when using a SAS token.");

            Assert.That(
                () => new TableClient(_urlHttp, TableName, null),
                Throws.InstanceOf<ArgumentException>(),
                "The constructor should not accept a null credential");

            Assert.That(
                () => new TableClient(_urlHttp, TableName, default(TokenCredential)),
                Throws.InstanceOf<ArgumentException>(),
                "The constructor should not accept a null credential");

            Assert.That(
                () => new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty)),
                Throws.Nothing,
                "The constructor should accept valid arguments.");

            Assert.That(
                () => new TableClient(_urlHttp, TableName, new TableSharedKeyCredential(AccountName, string.Empty)),
                Throws.Nothing,
                "The constructor should accept an http url.");

            Assert.That(
                () => new TableClient(_urlHttp, TableName, new DefaultAzureCredential(), new TableClientOptions()),
                Throws.Nothing,
                "The constructor should accept valid arguments.");
        }

        public static IEnumerable<object[]> ValidConnStrings()
        {
            yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;", AccountName, TableName };
            yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.microsoft.scloud:443/;", AccountName, TableName };
            yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.microsoft.scloud:443/{TableName};", AccountName, TableName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;", AccountName, TableName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.microsoft.scloud:443/;", AccountName, TableName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.microsoft.scloud:443/;", AccountName, AccountName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.microsoft.scloud:443/{AccountName};", AccountName, AccountName };
            yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};EndpointSuffix=core.windows.net", AccountName, TableName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret};EndpointSuffix=core.windows.net", AccountName, TableName };
            yield return new object[] { $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret}", AccountName, TableName };
            yield return new object[] { $"AccountName={AccountName};AccountKey={Secret}", AccountName, TableName };
            yield return new object[] { $"UseDevelopmentStorage=true", TableConstants.ConnectionStrings.DevStoreAccountName, TableName };
        }

        [Test]
        [TestCaseSource(nameof(ValidConnStrings))]
        public void AccountNameAndNameForConnStringCtor(string connString, string expectedAccountName, string expectedTableName)
        {
            var client = new TableClient(connString, expectedTableName, new TableClientOptions());

            Assert.Multiple(
                () =>
                {
                    Assert.AreEqual(expectedAccountName, client.AccountName);
                    Assert.AreEqual(expectedTableName, client.Name);
                });
        }

        [Test]
        public void AccountNameAndNameForUriCtor()
        {
            var client = new TableClient(_url, TableName, new TableSharedKeyCredential(AccountName, string.Empty), new TableClientOptions());

            Assert.AreEqual(AccountName, client.AccountName);
            Assert.AreEqual(TableName, client.Name);
        }

        [Test]
        public void NoCredCtor()
        {
            var client = new TableClient(new Uri($"{_url}/{TableName}?{signature}"));

            Assert.AreEqual(AccountName, client.AccountName);
            Assert.AreEqual(TableName, client.Name);
        }

        /// <summary>
        /// Validates the functionality of the TableClient.
        /// </summary>
        [Test]
        public void ServiceMethodsValidateArguments()
        {
            Assert.That(
                async () => await client.AddEntityAsync<TableEntity>(null),
                Throws.InstanceOf<ArgumentNullException>(),
                "The method should validate the entity is not null.");

            Assert.That(
                async () => await client.UpsertEntityAsync<TableEntity>(null, TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentNullException>(),
                "The method should validate the entity is not null.");
            Assert.That(
                async () => await client.UpsertEntityAsync(new TableEntity { PartitionKey = null, RowKey = "row" }, TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentException>(),
                $"The method should validate the entity has a {TableConstants.PropertyNames.PartitionKey}.");

            Assert.That(
                async () => await client.UpsertEntityAsync(new TableEntity { PartitionKey = "partition", RowKey = null }, TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentException>(),
                $"The method should validate the entity has a {TableConstants.PropertyNames.RowKey}.");

            Assert.That(
                async () => await client.UpdateEntityAsync<TableEntity>(null, new ETag("etag"), TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentNullException>(),
                "The method should validate the entity is not null.");
            Assert.That(
                async () => await client.UpdateEntityAsync(validEntity, default, TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentException>(),
                "The method should validate the eTag is not null.");

            Assert.That(
                async () => await client.UpdateEntityAsync(entityWithoutPK, new ETag("etag"), TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentException>(),
                $"The method should validate the entity has a {TableConstants.PropertyNames.PartitionKey}.");

            Assert.That(
                async () => await client.UpdateEntityAsync(entityWithoutRK, new ETag("etag"), TableUpdateMode.Replace),
                Throws.InstanceOf<ArgumentException>(),
                $"The method should validate the entity has a {TableConstants.PropertyNames.RowKey}.");
        }

        [Test]
        public void GetSasBuilderPopulatesPermissionsAndExpiry()
        {
            var expiry = DateTimeOffset.Now.AddDays(1);
            var permissions = TableSasPermissions.All;

            var sas = client.GetSasBuilder(permissions, expiry);

            Assert.That(sas.Permissions, Is.EqualTo(permissions.ToPermissionsString()));
            Assert.That(sas.ExpiresOn, Is.EqualTo(expiry));
        }

        [Test]
        public void GetSasBuilderPopulatesRawPermissionsAndExpiry()
        {
            var expiry = DateTimeOffset.Now.AddDays(1);
            var permissions = TableSasPermissions.All;

            var sas = client.GetSasBuilder(permissions.ToPermissionsString(), expiry);

            Assert.That(sas.Permissions, Is.EqualTo(permissions.ToPermissionsString()));
            Assert.That(sas.ExpiresOn, Is.EqualTo(expiry));
        }

        [Test]
        public void GetSasBuilderGeneratesCorrectUri()
        {
            var expiry = new DateTimeOffset(2020, 1, 1, 1, 1, 1, TimeSpan.Zero);
            var permissions = TableSasPermissions.All;

            var sas = client.GetSasBuilder(permissions.ToPermissionsString(), expiry);

            const string startIP = "123.45.67.89";
            const string endIP = "123.65.43.21";
            sas.IPRange = new TableSasIPRange(IPAddress.Parse(startIP), IPAddress.Parse(endIP));
            sas.PartitionKeyEnd = "PKEND";
            sas.PartitionKeyStart = "PKSTART";
            sas.RowKeyEnd = "PKEND";
            sas.RowKeyStart = "RKSTART";
            sas.StartsOn = expiry.AddHours(-1);

            string token = sas.Sign(new TableSharedKeyCredential("foo", "Kg=="));

            Assert.That(
                token.StartsWith(
                    $"{Parms.TableName}={TableName.ToLowerInvariant()}&{Parms.StartPartitionKey}={sas.PartitionKeyStart}&{Parms.EndPartitionKey}={sas.PartitionKeyEnd}&{Parms.StartRowKey}={sas.RowKeyStart}&{Parms.EndRowKey}={sas.RowKeyEnd}&{Parms.Version}=2019-02-02&{Parms.StartTime}=2020-01-01T00%3A01%3A01Z&{Parms.ExpiryTime}=2020-01-01T01%3A01%3A01Z&{Parms.IPRange}=123.45.67.89-123.65.43.21&{Parms.Permissions}=raud&{Parms.Signature}="));
        }

        /// <summary>
        /// Validates the functionality of the TableClient.
        /// </summary>
        [Test]
        public void CreatedTableEntityEnumEntitiesThrowNotSupported()
        {
            var entityToCreate = new TableEntity { PartitionKey = "partitionKey", RowKey = "01" };
            entityToCreate["MyFoo"] = Foo.Two;

            // Create the new entities.
            Assert.ThrowsAsync<NotSupportedException>(async () => await client.AddEntityAsync(entityToCreate).ConfigureAwait(false));
        }

        [Test]
        public void CreatedTableEntityPropertiesAreSerializedProperly()
        {
            var entity = new TableEntity { PartitionKey = "partitionKey", RowKey = "01", Timestamp = DateTime.Now, ETag = ETag.All };
            entity["MyFoo"] = "Bar";

            var dictEntity = entity.ToOdataAnnotatedDictionary();

            Assert.That(dictEntity["PartitionKey"], Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
            Assert.That(dictEntity["RowKey"], Is.EqualTo(entity.RowKey), "The entities should be equivalent");
            Assert.That(dictEntity["MyFoo"], Is.EqualTo(entity["MyFoo"].ToString()), "The entities should be equivalent");
            Assert.That(dictEntity.Keys, Is.EquivalentTo(new[] { "PartitionKey", "RowKey", "MyFoo" }), "Only PK, RK, and user properties should be sent");
        }

        [Test]
        public void CreatedEnumPropertiesAreSerializedProperly()
        {
            var entity = new EnumEntity
            {
                PartitionKey = "partitionKey",
                RowKey = "01",
                Timestamp = DateTime.Now,
                MyFoo = Foo.Two,
                MyNullableFoo = null,
                ETag = ETag.All
            };

            // Create the new entities.
            var dictEntity = entity.ToOdataAnnotatedDictionary();

            Assert.That(dictEntity["PartitionKey"], Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
            Assert.That(dictEntity["RowKey"], Is.EqualTo(entity.RowKey), "The entities should be equivalent");
            Assert.That(dictEntity["MyFoo"], Is.EqualTo(entity.MyFoo.ToString()), "The entities should be equivalent");
            Assert.That(dictEntity["MyNullableFoo"], Is.EqualTo(entity.MyNullableFoo), "The entities should be equivalent");
            Assert.That(dictEntity.TryGetValue(TableConstants.PropertyNames.Timestamp, out var _), Is.False, "Only PK, RK, and user properties should be sent");
        }

        [Test]
        public void EnumPropertiesAreDeSerializedProperly()
        {
            var entity = new EnumEntity
            {
                PartitionKey = "partitionKey",
                RowKey = "01",
                Timestamp = DateTime.Now,
                MyFoo = Foo.Two,
                MyNullableFoo = null,
                MyNullableFoo2 = NullableFoo.Two,
                ETag = ETag.All
            };

            // Create the new entities.
            var dictEntity = entity.ToOdataAnnotatedDictionary();
            var deserializedEntity = dictEntity.ToTableEntity<EnumEntity>();
            Assert.That(deserializedEntity.PartitionKey, Is.EqualTo(entity.PartitionKey), "The entities should be equivalent");
            Assert.That(deserializedEntity.RowKey, Is.EqualTo(entity.RowKey), "The entities should be equivalent");
            Assert.That(deserializedEntity.MyFoo.ToString(), Is.EqualTo(entity.MyFoo.ToString()), "The entities should be equivalent");
            Assert.That(deserializedEntity.MyNullableFoo.ToString(), Is.EqualTo(entity.MyNullableFoo.ToString()), "The entities should be equivalent");
            Assert.That(deserializedEntity.MyNullableFoo2.ToString(), Is.EqualTo(entity.MyNullableFoo2.ToString()), "The entities should be equivalent");
            Assert.That(dictEntity.TryGetValue(TableConstants.PropertyNames.Timestamp, out var _), Is.False, "Only PK, RK, and user properties should be sent");
        }

        [Test]
        public void RoundTripContinuationTokenWithPartitionKeyAndRowKey()
        {
            var response = new MockResponse(200);
            (string NextPartitionKey, string NextRowKey) expected = ("next-pk", "next-rk");
            response.AddHeader(new HttpHeader("x-ms-continuation-NextPartitionKey", expected.NextPartitionKey));
            response.AddHeader(new HttpHeader("x-ms-continuation-NextRowKey", expected.NextRowKey));
            var headers = new TableQueryEntitiesHeaders(response);

            var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
            var actual = TableClient.ParseContinuationToken(continuationToken);

            Assert.That(continuationToken, Is.EqualTo("next-pk next-rk"));
            Assert.That(actual, Is.EqualTo(expected));
        }

        [Test]
        public void RoundTripContinuationTokenWithPartitionKeyAndNoRowKey()
        {
            var response = new MockResponse(200);
            (string NextPartitionKey, string NextRowKey) expected = ("next-pk", null);
            response.AddHeader(new HttpHeader("x-ms-continuation-NextPartitionKey", expected.NextPartitionKey));
            var headers = new TableQueryEntitiesHeaders(response);

            var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
            var actual = TableClient.ParseContinuationToken(continuationToken);

            Assert.That(continuationToken, Is.EqualTo("next-pk "));
            Assert.That(actual, Is.EqualTo(expected));
        }

        [Test]
        public void NullContinuationTokenReturnsWhenWithNoPartitionKeyAndNoRowKey()
        {
            var response = new MockResponse(200);
            (string NextPartitionKey, string NextRowKey) expected = (null, null);
            var headers = new TableQueryEntitiesHeaders(response);

            var continuationToken = TableClient.CreateContinuationTokenFromHeaders(headers);
            var actual = TableClient.ParseContinuationToken(continuationToken);

            Assert.That(continuationToken, Is.Null);
            Assert.That(actual, Is.EqualTo(expected));
        }

        [Test]
        public void HandlesEmptyStringContinuationToken()
        {
            (string NextPartitionKey, string NextRowKey) expected = (null, null);

            var actual = TableClient.ParseContinuationToken(" ");

            Assert.That(actual, Is.EqualTo(expected));
        }

        [Test]
        public async Task ValidateUri()
        {
            await client.UpdateEntityAsync(new TableEntity("pkā", "rk"), ETag.All).ConfigureAwait(false);
            Assert.AreEqual(
                $"https://example.com/someTableName(PartitionKey='{Uri.EscapeDataString("pkā")}',RowKey='rk')?{signature}&$format=application%2Fjson%3Bodata%3Dminimalmetadata",
                _transport.Requests[0].Uri.ToString());
        }

        [Test]
        public void CreateIfNotExistsThrowsWhenTableBeingDeleted()
        {
            _transport = new MockTransport(
                request => throw new RequestFailedException(
                    (int)HttpStatusCode.Conflict,
                    null,
                    TableErrorCode.TableBeingDeleted.ToString(),
                    null));
            var service_Instrumented = InstrumentClient(
                new TableServiceClient(
                    new Uri($"https://example.com?{signature}"),
                    new AzureSasCredential("sig"),
                    new TableClientOptions { Transport = _transport }));
            client = service_Instrumented.GetTableClient(TableName);

            Assert.ThrowsAsync<RequestFailedException>(() => client.CreateIfNotExistsAsync());
        }

        private static IEnumerable<object[]> TableClients()
        {
            var cred = new TableSharedKeyCredential(AccountName, Secret);
            var devCred = new TableSharedKeyCredential(TableConstants.ConnectionStrings.DevStoreAccountName, TableConstants.ConnectionStrings.DevStoreAccountKey);
            var sharedKeyClient = new TableClient(_url, TableName, cred);
            var connStringClient = new TableClient(
                $"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;",
                TableName);
            var devStorageClient = new TableClient("UseDevelopmentStorage=true", TableName);
            yield return new object[] { sharedKeyClient, cred };
            yield return new object[] { connStringClient, cred };
            yield return new object[] { devStorageClient, devCred };
        }

        [TestCaseSource(nameof(TableClients))]
        public void GenerateSasUri(TableClient client, TableSharedKeyCredential cred)
        {
            TableSasPermissions permissions = TableSasPermissions.Add;
            var expires = DateTime.Now.AddDays(1);
            var expectedSas = new TableSasBuilder(TableName, permissions, expires).Sign(cred);

            var actualSas = client.GenerateSasUri(permissions, expires);

            Assert.AreEqual("?" + expectedSas, actualSas.Query);
        }

        public class EnumEntity : ITableEntity
        {
            public string PartitionKey { get; set; }
            public string RowKey { get; set; }
            public DateTimeOffset? Timestamp { get; set; }
            public ETag ETag { get; set; }
            public Foo MyFoo { get; set; }
            public NullableFoo? MyNullableFoo { get; set; }
            public NullableFoo? MyNullableFoo2 { get; set; }
        }

        public enum Foo
        {
            One,
            Two
        }

        public enum NullableFoo
        {
            One,
            Two
        }
    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('user', '0013_subscription_site_name'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='site_name',
            field=models.CharField(db_index=True, default='somerville.cornerwise.org', help_text='The site where the user created his/her account', max_length=64),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
function exp(x) {
  return Math.exp(x);
}

var first_call_result = exp(Math.PI);
var second_call_result = exp(Math.PI);

function assertAlmostEquals(expected, actual, x) {
  if (expected == 0 && actual == 0) return;  // OK
  if (expected == Number.POSITIVE_INFINITY &&
      actual == Number.POSITIVE_INFINITY) {
    return;  // OK
  }
  relative_diff = Math.abs(expected/actual - 1);
  assertTrue(relative_diff < 1e-12, "relative difference of " + relative_diff +
                                    " for input " + x);
}

var increment = Math.PI / 35;  // Roughly 0.1, but we want to try many
                               // different mantissae.
for (var x = -708; x < 710; x += increment) {
  var ex = exp(x);
  var reference = Math.pow(Math.E, x);
  assertAlmostEquals(reference, ex, x);
  if (ex > 0 && isFinite(ex)) {
    var back = Math.log(ex);
    assertAlmostEquals(x, back, x + " (backwards)");
  }
}

// Make sure optimizing the function does not alter the result.
var last_call_result = exp(Math.PI);
assertEquals(first_call_result, second_call_result);
assertEquals(first_call_result, last_call_result);


text:
\hypertarget{related__8_8js}{}\section{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/related\+\_\+8.js File Reference}
\label{related__8_8js}\index{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/related\+\_\+8.\+js@{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/related\+\_\+8.\+js}}
\subsection*{Variables}
\begin{DoxyCompactItemize}
\item
var \hyperlink{related__8_8js_ad01a7523f103d6242ef9b0451861231e}{search\+Data}
\end{DoxyCompactItemize}

\subsection{Variable Documentation}
\index{related\+\_\+8.\+js@{related\+\_\+8.\+js}!search\+Data@{search\+Data}}
\index{search\+Data@{search\+Data}!related\+\_\+8.\+js@{related\+\_\+8.\+js}}
\subsubsection[{\texorpdfstring{search\+Data}{searchData}}]{\setlength{\rightskip}{0pt plus 5cm}var search\+Data}\hypertarget{related__8_8js_ad01a7523f103d6242ef9b0451861231e}{}\label{related__8_8js_ad01a7523f103d6242ef9b0451861231e}
{\bfseries Initial value\+:}
\begin{DoxyCode}
=
[
  [\textcolor{stringliteral}{'naggymock'},[\textcolor{stringliteral}{'NaggyMock'},[\textcolor{stringliteral}{'../classtesting\_1\_1\_mock.html#aee2e427ecb34e6662477add3bb5f8819'},1,\textcolor{stringliteral}{'
      testing::Mock'}]]],
  [\textcolor{stringliteral}{'nicemock'},[\textcolor{stringliteral}{'NiceMock'},[\textcolor{stringliteral}{'../classtesting\_1\_1\_mock.html#a9e796f79d4c876398f83aa7678dddc46'},1,\textcolor{stringliteral}{'
      testing::Mock'}]]]
]
\end{DoxyCode}

Definition at line 1 of file related\+\_\+8.\+js.


text:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"  type="text/css">
<link href="bootstrap/css/bootstrap-theme.css.no" rel="stylesheet"  type="text/css">
<script src="bootstrap/jquery-1.9.1.js"></script>
<script src="bootstrap/js/bootstrap.js.no"></script>
<script src="js/bootstrap-maxlength.js"></script>
<style type="text/css">
body { padding: 12px; }
</style>
<script type="text/javascript">
$(function(){
	 $('input#test').maxlength();
})
</script>
</head>
<body>
<input type="text" class="form-control" maxlength="25" name="test" id="test" />
</body>
</html>


text:
package org.hellojavaer.ddal.ddr.datasource.jdbc;

import org.hellojavaer.ddal.ddr.datasource.manager.DataSourceParam;
import org.hellojavaer.ddal.ddr.sqlparse.SQLParsedResult;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

/**
 *
 * @author Kaiming Zou,created on 11/12/2016.
 */
public interface DDRStatement extends Statement {

    SQLParsedResult parseSql(String sql, Map<Object, Object> jdbcParams) throws SQLException;

    StatementWrapper getStatement(DataSourceParam param, String sql) throws SQLException;

}


text:
from a10sdk.common.A10BaseClass import A10BaseClass

class Delete(A10BaseClass):

    """    :param private_key: {"description": "Private key file name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"}
    :param ca: {"description": "CA certificate file name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"}
    :param cert_name: {"description": "Certificate file name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"}
    :param crl: {"description": "CRL file name", "format": "string", "minLength": 1, "optional": true, "maxLength": 63, "type": "string"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

Class Description::
    Delete SSL cert.

    Class delete supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/pki/delete`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required=[]
        self.b_key = "delete"
        self.a10_url="/axapi/v3/pki/delete"
        self.DeviceProxy = ""
        self.private_key = ""
        self.ca = ""
        self.cert_name = ""
        self.crl = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)


text:
package com.sqb.designpattern.bridge;

public interface Sourceable {
    public void method();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nancy.KeyRockAuthenticationProvider
{
    public class AccessTokenResult
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
    }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<script>
Polymer({
  is: 'state-history-chart-timeline',

  properties: {
    data: {
      type: Object,
      observer: 'dataChanged',
    },

    isAttached: {
      type: Boolean,
      value: false,
      observer: 'dataChanged',
    },
  },

  created: function () {
    this.style.display = 'block';
  },

  attached: function () {
    this.isAttached = true;
  },

  dataChanged: function () {
    this.drawChart();
  },

  drawChart: function () {
    var root = Polymer.dom(this);
    var stateHistory = this.data;
    var chart;
    var dataTable;
    var startTime;
    var endTime;
    var numTimelines;

    if (!this.isAttached) {
      return;
    }

    while (root.node.lastChild) {
      root.node.removeChild(root.node.lastChild);
    }

    if (!stateHistory || stateHistory.length === 0) {
      return;
    }

    chart = new window.google.visualization.Timeline(this);
    dataTable = new window.google.visualization.DataTable();

    dataTable.addColumn({ type: 'string', id: 'Entity' });
    dataTable.addColumn({ type: 'string', id: 'State' });
    dataTable.addColumn({ type: 'date', id: 'Start' });
    dataTable.addColumn({ type: 'date', id: 'End' });

    function addRow(entityDisplay, stateStr, start, end) {
      var stateDisplay = stateStr.replace(/_/g, ' ');
      dataTable.addRow([entityDisplay, stateDisplay, start, end]);
    }

    startTime = new Date(
      stateHistory.reduce(
        function (minTime, stateInfo) {
          return Math.min(minTime, stateInfo[0].lastChangedAsDate);
        }, new Date()));

    // end time is Math.min(curTime, start time + 1 day)
    endTime = new Date(startTime);
    endTime.setDate(endTime.getDate() + 1);
    if (endTime > new Date()) {
      endTime = new Date();
    }

    numTimelines = 0;
    // stateHistory is a list of lists of sorted state objects
    stateHistory.forEach(function (stateInfo) {
      var entityDisplay;
      var newLastChanged;
      var prevState = null;
      var prevLastChanged = null;

      if (stateInfo.length === 0) return;

      entityDisplay = stateInfo[0].entityDisplay;

      stateInfo.forEach(function (state) {
        if (prevState !== null && state.state !== prevState) {
          newLastChanged = state.lastChangedAsDate;

          addRow(entityDisplay, prevState, prevLastChanged, newLastChanged);

          prevState = state.state;
          prevLastChanged = newLastChanged;
        } else if (prevState === null) {
          prevState = state.state;
          prevLastChanged = state.lastChangedAsDate;
        }
      });

      addRow(entityDisplay, prevState, prevLastChanged, endTime);
      numTimelines++;
    });

    chart.draw(dataTable, {
      height: 55 + (numTimelines * 42),

      timeline: {
        showRowLabels: stateHistory.length > 1,
      },

      hAxis: {
        format: 'H:mm',
      },
    });
  },
});
</script>


text:
<?php

namespace Concrete\Core\Workflow;

use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Entity\Package;
use Concrete\Core\Foundation\ConcreteObject;
use Concrete\Core\Package\PackageService;
use Concrete\Core\Permission\ObjectInterface;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\Workflow\Progress\Progress as WorkflowProgress;
use Concrete\Core\Workflow\Request\Request as WorkflowRequest;
use Punic\Comparer;

abstract class Workflow extends ConcreteObject implements ObjectInterface
{
    /**
     * The workflow ID.
     *
     * @var int
     */
    protected $wfID = 0;

    /**
     * The list of allowed tasks.
     *
     * @var string[]
     */
    protected $allowedTasks = ['cancel', 'approve'];

    /**
     * The list of permission key handles that this workflow can be attached to.
     *
     * @var string[]
     */
    protected $restrictedToPermissionKeyHandles = [];

    /**
     * Get the workflow ID.
     *
     * @return int
     */
    public function getWorkflowID()
    {
        return $this->wfID;
    }

    /**
     * Get the workflow (English) name.
     *
     * @return string
     */
    public function getWorkflowName()
    {
        return $this->wfName;
    }

    /**
     * Get the display name for this workflow (localized and escaped accordingly to $format).
     *
     * @param string $format = 'html'
     *    Escape the result in html format (if $format is 'html').
     *    If $format is 'text' or any other value, the display name won't be escaped.
     *
     * @return string
     */
    public function getWorkflowDisplayName($format = 'html')
    {
        $value = tc('WorkflowName', $this->getWorkflowName());
        switch ($format) {
            case 'html':
                return h($value);
            case 'text':
            default:
                return $value;
        }
    }

    /**
     * Get the list of allowed tasks.
     *
     * @return string[]
     */
    public function getAllowedTasks()
    {
        return $this->allowedTasks;
    }

    /**
     * Get the workflow type associated to this workflow.
     *
     * @return \Concrete\Core\Workflow\Type|null
     */
    public function getWorkflowTypeObject()
    {
        return empty($this->wftID) ? null : Type::getByID($this->wftID);
    }

    /**
     * Get the list of permission key handles that this workflow can be attached to.
     *
     * @var string[]
     */
    public function getRestrictedToPermissionKeyHandles()
    {
        return $this->restrictedToPermissionKeyHandles;
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Permission\ObjectInterface::getPermissionResponseClassName()
     */
    public function getPermissionResponseClassName()
    {
        return '\\Concrete\\Core\\Permission\\Response\\Workflow';
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Permission\ObjectInterface::getPermissionAssignmentClassName()
     */
    public function getPermissionAssignmentClassName()
    {
        return '\\Concrete\\Core\\Permission\\Assignment\\WorkflowAssignment';
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Permission\ObjectInterface::getPermissionObjectKeyCategoryHandle()
     */
    public function getPermissionObjectKeyCategoryHandle()
    {
        return 'basic_workflow';
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Permission\ObjectInterface::getPermissionObjectIdentifier()
     */
    public function getPermissionObjectIdentifier()
    {
        return $this->getWorkflowID();
    }

    /**
     * Delete this workflow and all its associated progresses.
     */
    public function delete()
    {
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $rows = $db->fetchAll('select wpID from WorkflowProgress where wfID = ?', [$this->getWorkflowID()]);
        foreach ($rows as $row) {
            $wfp = WorkflowProgress::getByID($row['wpID']);
            if ($wfp) {
                $wfp->delete();
            }
        }
        $db->delete('Workflows', ['wfID' => $this->getWorkflowID()]);
    }

    /**
     * By default the basic workflow just passes the status num from the request
     * we do this so that we can order things by most important, etc...
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return int|null
     */
    public function getWorkflowProgressCurrentStatusNum(WorkflowProgress $wp)
    {
        $req = $wp->getWorkflowRequestObject();
        if (is_object($req)) {
            return $req->getWorkflowRequestStatusNum();
        }
    }

    /**
     * Get the list of installed workflows, sorted by the workflow display name.
     *
     * @return \Concrete\Core\Workflow\Workflow[]
     */
    public static function getList()
    {
        $workflows = [];
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $rows = $db->fetchAll('select wfID from Workflows');
        foreach ($rows as $row) {
            $wf = static::getByID($row['wfID']);
            if ($wf) {
                $workflows[] = $wf;
            }
        }
        $cmp = new Comparer();
        usort($workflows, function (Workflow $a, Workflow $b) use ($cmp) {
            return $cmp->compare($a->getWorkflowDisplayName('text'), $b->getWorkflowDisplayName('text'));
        });

        return $workflows;
    }

    /**
     * Get the list of workflows installed by a package, sorted by the workflow display name.
     *
     * @param \Concrete\Core\Entity\Package $pkg
     *
     * @return \Concrete\Core\Workflow\Workflow[]
     */
    public static function getListByPackage(Package $pkg)
    {
        $workflows = [];
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $rows = $db->fetchAll('select wfID from Workflows where pkgID = ?', [$pkg->getPackageID()]);
        foreach ($rows as $row) {
            $wf = static::getByID($row['wfID']);
            if ($wf) {
                $workflows[] = $wf;
            }
        }
        $cmp = new Comparer();
        usort($workflows, function (Workflow $a, Workflow $b) use ($cmp) {
            return $cmp->compare($a->getWorkflowDisplayName('text'), $b->getWorkflowDisplayName('text'));
        });

        return $workflows;
    }

    /**
     * Create a new workflow.
     *
     * @param \Concrete\Core\Workflow\Type $wt The workflow type
     * @param string $name the (English) name of the workflow
     * @param \Concrete\Core\Entity\Package|null $pkg the package that's creating the new workflow
     *
     * @return \Concrete\Core\Workflow\Workflow
     */
    public static function add(Type $wt, $name, Package $pkg = null)
    {
        $wf = static::getByName($name);
        if ($wf !== null) {
            return $wf;
        }
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $db->insert(
            'Workflows',
            [
                'wftID' => $wt->getWorkflowTypeID(),
                'wfName' => (string) $name,
                'pkgID' => $pkg === null ? $wt->getPackageID() : $pkg->getPackageID(),
            ]
        );
        $wfID = $db->lastInsertId();

        return self::getByID($wfID);
    }

    /**
     * Get a workflow given its ID.
     *
     * @param int $wfID the ID of the workflow
     *
     * @return \Concrete\Core\Workflow\Workflow|null
     */
    public static function getByID($wfID)
    {
        $wfID = (int) $wfID;
        if ($wfID === 0) {
            return null;
        }
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $r = $db->fetchAssoc(<<<'EOT'
select
    WorkflowTypes.wftHandle,
    WorkflowTypes.pkgID
from
    Workflows
    inner join WorkflowTypes on Workflows.wftID = WorkflowTypes.wftID
where
    Workflows.wfID = ?
EOT
            ,
            [$wfID]
        );
        if (!$r) {
            return null;
        }
        $class = '\\Core\\Workflow\\' . camelcase($r['wftHandle']) . 'Workflow';
        if ($r['pkgID']) {
            $pkg = $app->make(PackageService::class)->getByID($r['pkgID']);
            $prefix = $pkg->getPackageHandle();
        } else {
            $prefix = null;
        }
        $class = core_class($class, $prefix);
        $obj = $app->make($class);
        /** @var \Concrete\Core\Workflow\Workflow $obj */
        $obj->load($wfID);
        if (!$obj->getWorkflowID()) {
            return null;
        }
        $obj->loadDetails();

        return $obj;
    }

    /**
     * Get a workflow given its (English) name.
     *
     * @param string $wfName
     *
     * @return \Concrete\Core\Workflow\Workflow|null
     */
    public static function getByName($wfName)
    {
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $wfID = $db->fetchColumn('SELECT wfID FROM Workflows WHERE wfName = ?', [(string) $wfName]);

        return $wfID ? static::getByID($wfID) : null;
    }

    /**
     * Change the (English) name of this workflow.
     *
     * @param string $wfName
     */
    public function updateName($wfName)
    {
        $wfName = (string) $wfName;
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $db->update(
            'Workflows',
            [
                'wfName' => $wfName,
            ],
            [
                'wfID' => $this->getWorkflowID(),
            ]
        );
        $this->wfName = $wfName;
    }

    /**
     * Start the workflow.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return \Concrete\Core\Workflow\Progress\Response|\Concrete\Core\Workflow\Progress\SkippedResponse|null
     */
    abstract public function start(WorkflowProgress $wp);

    /**
     * Check if the currently logged-in user can approve this workflow.
     *
     * @return bool
     */
    abstract public function canApproveWorkflow();

    /**
     * Get the list of users that can approve an operation.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return \Concrete\Core\User\UserInfo[]
     */
    abstract public function getWorkflowProgressApprovalUsers(WorkflowProgress $wp);

    /**
     * Get the list of actions that can be performed against an operation.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return \Concrete\Core\Workflow\Progress\Action\Action[]
     */
    abstract public function getWorkflowProgressActions(WorkflowProgress $wp);

    /**
     * Get the comments about an operation.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return string|false|null
     */
    abstract public function getWorkflowProgressCurrentComment(WorkflowProgress $wp);

    /**
     * Get the description of the status of an operation.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return string
     */
    abstract public function getWorkflowProgressStatusDescription(WorkflowProgress $wp);

    /**
     * Check if the currently logged-in user can approve an operation.
     *
     * @param \Concrete\Core\Workflow\Progress\Progress $wp
     *
     * @return bool
     */
    abstract public function canApproveWorkflowProgressObject(WorkflowProgress $wp);

    /**
     * Update the workflow details with data (usually received via POST).
     *
     * @param array $vars
     */
    abstract public function updateDetails($vars);

    /**
     * Load the details of this workflow (usually called right after this instance has been created).
     */
    abstract public function loadDetails();

    /**
     * @return bool
     */
    public function getPermissionAccessObject()
    {
        return false;
    }

    /**
     * Check if a workflow request is valid.
     *
     * @param \Concrete\Core\Workflow\Request\Request $req
     *
     * @return bool
     */
    public function validateTrigger(WorkflowRequest $req)
    {
        // Check if the current workflow request is not already deleted
        $wr = $req::getByID($req->getWorkflowRequestID());

        return is_object($wr);
    }

    /**
     * Load the workflow data from the database row.
     *
     * @param int $wfID
     */
    protected function load($wfID)
    {
        $app = Application::getFacadeApplication();
        $db = $app->make(Connection::class);
        $r = $db->fetchAssoc('select * from Workflows where wfID = ?', [(int) $wfID]);
        $r['wfID'] = (int) $r['wfID'];
        $r['wftID'] = (int) $r['wftID'];
        $r['pkgID'] = (int) $r['pkgID'];
        $this->setPropertiesFromArray($r);
    }
}


text:
@class CCSprite, CCSprite9Slice, NSMutableDictionary;

@interface CCSlider : CCControl
{
    NSMutableDictionary *_backgroundSpriteFrames;
    NSMutableDictionary *_handleSpriteFrames;
    BOOL _draggingHandle;
    struct CGPoint _handleStartPos;
    struct CGPoint _dragStartPos;
    float _dragStartValue;
    CCSprite9Slice *_background;
    CCSprite *_handle;
    float _sliderValue;
}

- (void).cxx_destruct;
@property(readonly, nonatomic) CCSprite9Slice *background; // @synthesize background=_background;
- (id)backgroundSpriteFrameForState:(unsigned int)arg1;
@property(readonly, nonatomic) CCSprite *handle; // @synthesize handle=_handle;
- (id)handleSpriteFrameForState:(unsigned int)arg1;
- (id)init;
- (id)initWithBackground:(id)arg1 andHandleImage:(id)arg2;
- (void)inputDraggedWithPos:(struct CGPoint)arg1;
- (void)inputEnteredWithWorlPos:(struct CGPoint)arg1;
- (void)inputUpInside;
- (void)inputUpOutside;
- (void)layout;
- (void)setBackgroundSpriteFrame:(id)arg1 forState:(unsigned int)arg2;
- (void)setHandleSpriteFrame:(id)arg1 forState:(unsigned int)arg2;
@property(nonatomic) float sliderValue; // @synthesize sliderValue=_sliderValue;
- (void)setValue:(id)arg1 forKey:(id)arg2 state:(unsigned int)arg3;
- (void)stateChanged;
- (void)touchEntered:(id)arg1 withEvent:(id)arg2;
- (void)touchMoved:(id)arg1 withEvent:(id)arg2;
- (void)touchUpInside:(id)arg1 withEvent:(id)arg2;
- (void)touchUpOutside:(id)arg1 withEvent:(id)arg2;
- (void)updatePropertiesForState:(unsigned int)arg1;
- (void)updateSliderPositionFromValue;
- (id)valueForKey:(id)arg1 state:(unsigned int)arg2;

@end


text:
package org.renjin.primitives.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 *
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Primitive {
  String value() default "";
}


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var chalk = require('chalk');
var vorpal = require('vorpal');
var MPlayer = require('mplayer');
var Spinner = require('./spinner').Spinner;
var LocalStorage = require('node-localstorage').LocalStorage;

var App = function () {
  function App() {
    var _this = this;

    _classCallCheck(this, App);

    this.localStorage = new LocalStorage((process.env.HOME || process.env.USERPROFILE) + '/.musicli');
    this.vorpal = vorpal();
    this.vorpal.delimiter('musicli>');

    this.player = new MPlayer();
    this.player.isPaused = false;
    this.player.on('status', function (data) {
      if (data.filename) {
        var re = /http:\/\/.*\/(.*)_.*.mp3/gi;
        var m = void 0;

        if ((m = re.exec(data.filename)) !== null) {
          if (m.index === re.lastIndex) {
            re.lastIndex++;
          }

          var song = decodeURI(m[1]);

          _this.vorpal.log(chalk.green('Now playing: ' + song));
        }
      }
    });
    this.player.on('stop', function () {
      var that = _this;

      _this.playlist.fetchRandomSong().then(function (songUri) {
        that.player.openFile(songUri);
      });
    });
    this.player.on('error', function (error) {
      _this.vorpal.log(chalk.red('Error: ' + error));
    });
    this.spinner = new Spinner(this.vorpal);

    require('./commands/artist/search')(this);

    require('./commands/playlist/all')(this);
    require('./commands/playlist/create')(this);
    require('./commands/playlist/load')(this);
    require('./commands/playlist/delete')(this);
    require('./commands/playlist/current')(this);
    require('./commands/playlist/leaves')(this);
    require('./commands/playlist/remove')(this);
    require('./commands/playlist/refresh')(this);

    require('./commands/player/play')(this);
    require('./commands/player/next')(this);
    require('./commands/player/pause')(this);
  }

  _createClass(App, [{
    key: 'run',
    value: function run() {
      this.vorpal.show();
    }
  }]);

  return App;
}();

module.exports.App = App;


text:
package com.hsdc.dp.intf.service.prototype;

import java.util.List;

import com.hsdc.dp.intf.domain.prototype.Prototype;
import com.hsdc.dp.intf.domain.prototype.PurchaseOrder;

public interface MaintainPurchaseUco {
	public List<PurchaseOrder> getPurchaseLists();
	public Prototype<PurchaseOrder> newPurchaseOrder();
	public List<PurchaseOrder> save(PurchaseOrder po);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WiimoteLib.DataTypes
{
    /// <summary>
	/// Current button state of the Guitar controller
	/// </summary>
	public struct GuitarButtonState
    {
        /// <summary>
        /// Strum bar
        /// </summary>
        public bool StrumUp, StrumDown;
        /// <summary>
        /// Other buttons
        /// </summary>
        public bool Minus, Plus;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>WebSocket Communication — Leap Motion C++ SDK v3.1 documentation</title>

    <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1471552333.css" type="text/css" />

    <link rel="top" title="Leap Motion C++ SDK v3.1 documentation" href="../index.html" />
    <link rel="up" title="Appendices" href="Leap_Supplements.html" />
    <link rel="next" title="Leap Motion Release Notes" href="SDK_Release_Notes.html" />
    <link rel="prev" title="Using the Diagnostic Visualizer" href="Leap_Visualizer.html" />

<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

            Developer Portal

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

      </button>

What's new

Getting Started

Documentation

 Examples

 Blog

 Community

      JavaScript

      Unity

      C#

      C++

      Java

      Python

      Objective-C

      Unreal

<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">

  <input type="search" results="5" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

WebSocket Communication¶

The Leap Motion software installed on any computer with a Leap Motion controller provides tracking data through a WebSocket server. The WebSocket server listens to port 6347 on the localhost domain (http://127.0.0.1:6437). Any client application, including Web clients, that can make a WebSocket connection can access the Leap Motion tracking data in the form of JSON-formatted messages. The WebSocket server is provided by the <tt class="docutils literal">leapd</tt> process, which runs as a service on Windows and a daemon on OS X and Linux.

In most cases, you should use an existing client library rather than implement this protocol directly in an application. This article is provided to help you if you are developing your own library. Existing libraries include:

<tt class="docutils literal">leap.js</tt> – A JavaScript client library for browsers and Nodejs. Available at https://github.com/leapmotion/leapjs.

<tt class="docutils literal">LeapMotionAS3</tt> – An ActionScript client library for Adobe Flash and AIR. Available at https://github.com/logotype/LeapMotionAS3.

Protocols¶

The communication between the WebSocket server and a client is mediated by a data exchange subprotocol. This subprotocol defines which messages can be sent between the client and the server and the format of the JSON data. The protocol version defines which feature set the server uses to communicate with a client.

You can request a specific version of the Leap Motion subprotocol by adding a string of the form <tt class="docutils literal">v6.json</tt> to the WebSocket URL, where the digit, in this case <tt class="docutils literal">6</tt> indicates which version to use. If you omit this part of the URL, you will get version 1. Note that the Leap Motion leap.js JavaScript library automatically selects the protocol version corresponding to the library version. When you successfully connect to the Leap Motion WebSocket server, it responds with a message reporting  the protocol version. If the client’s Leap Motion software is out-of-date, then this version could be less than the one you requested.

The current version of the protocol is <tt class="docutils literal">v6.json</tt>.

Client-Server Messages¶

The WebSocket server and a client can exchange the following messages:

Server to client

<tt class="docutils literal">version</tt>

Indicates the version numbers of the Leap Motion service and WebSocket subprotocol:

{"serviceVersion":"2.3.1+33747", "version":6}

<tt class="docutils literal">deviceEvent</tt>

Sent when the Leap Motion when the service/daemon is paused or resumed and when the controller hardware is plugged in or unplugged:

{
  "event": {
    "state": {
      "attached": false,
      "id": "NNNNNNNNNNN",
      "streaming": false,
      "type": "peripheral"
    },
    "type": "deviceEvent"
  }
}

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

<tt class="docutils literal">id</tt>
A string containing the ID of the Leap Mption device.

<tt class="docutils literal">attached</tt>
Whether the hardware device is plugged in or attached.

<tt class="docutils literal">streaming</tt>
Whether the service/daemon is sending tracking data. Always false if attached is false.

<tt class="docutils literal">type</tt>
The hardware form factor. One of: “peripheral”, “keyboard”, “laptop”

Tracking data

Contains a set of tracking data. See JSON tracking data format.

Client to server

<tt class="docutils literal">background</tt>

Specifies whether the client wants to receive frames when it is not the <tt class="docutils literal">focused</tt> application:

{"background": true}
{"background": false}

<tt class="docutils literal">focused</tt>

Specifies whether the application is active. Setting <tt class="docutils literal">focused</tt> to true, stops other WebSocket clients from getting data. Setting <tt class="docutils literal">focused</tt> to false stops your WebSocket client from getting data (and potentially unwanted input):

{"focused": true}
{"focused": false}

<tt class="docutils literal">optimizeHMD</tt>

Specifies whether the client application expects the Leap Motion hardware to be attached to a head-mounted display:

{"optimizeHMD": true}
{"optimizeHMD": false}

To send a message to the WebSocket server, first encode the desired message as a JSON string. In JavaScript, for example, you can use the JSON <tt class="docutils literal">stringify()</tt> function and then send the message using the WebSocket <tt class="docutils literal">send</tt> function:

//ws is a connected WebSocket object
var backgroundMessage = JSON.stringify({background: true});
ws.send(backgroundMessage);

JSON tracking data format¶

Each frame of data from the WebSocket server contains JSON defining a frame. The attributes of a frame in the JSON message are similar, but not identical to those of a |Frame|_ object obtained through the native library. They include:

"currentFrameRate": float
"id": float
"r": array of floats (Matrix)
"s": float
"t":  array of floats (vector)
"timestamp": integer
"devices": not implemented (always an empty array)

"gestures": array of Gesture objects
    (Attributes vary by gesture type)
    "center": array of floats (vector) -- circle only
    "direction": array of floats (vector) -- swipe, keyTap, screenTap only
    "duration": integer microseconds
    "handIds": array of integers
    "id": integer
    "normal": array of floats -- circle only
    "pointableIds": array
    "position": array of floats (vector) -- swipe, keyTap, screenTap only
    "progress": float -- circle, keyTap, screenTap only
    "radius": float -- circle only
    "speed": float -- swipe only
    "startPosition": array of float (vector) -- swipe only
    "state": string - one of "start", "update", "stop"
    "type": string - one of "circle", "swipe", "keyTap", "screenTap"

"hands": array of Hand objects
   "armBasis: the 3 basis vectors of the arm (array of vectors)
   "armWidth: float
   "confidence: float
   "direction": array of floats (vector)
   "elbow: array of floats (vector)
   "grabStrength: float
   "id": integer
   "palmNormal": array of floats (vector)
   "palmPosition": array of floats (vector)
   "palmVelocity": array of floats (vector)
   "pinchStrength: float
   "r": array of floats (Matrix)
   "s": float
   "sphereCenter": array of floats (vector)
   "sphereRadius": float
   "stabilizedPalmPosition": array of floats (vector)
   "t": array of floats (vector)
   "timeVisible": float
   "type": string - one of "right", "left"
   "wrist: array of floats (vector)

"interactionBox": object
   "center": array of floats (vector)
   "size": array of floats  (vector)

"pointables": array of Pointable objects
   "bases": the 3 basis vectors for each bone, in index order, wrist to tip, (array of vectors).
   "btipPosition": the position of the tip of the distal phalanx as an array of 3 floats.
   "carpPosition": the position of the base of metacarpal bone as an array of 3 floats.
   "dipPosition:" the position of the base of the distal phalanx as an array of 3 floats.
   "direction": array of floats (vector)
   "extended": boolean (true or false)
   "handId": integer
   "id": integer
   "length": float
   "mcpPosition": a position vector as an array of 3 floating point numbers
   "pipPosition": a position vector as an array of 3 floating point numbers
   "stabilizedTipPosition": array of floats (vector)
   "timeVisible": float
   "tipPosition":  array of floats (vector)
   "tipVelocity":  array of floats (vector)
   "tool": boolean (true or false)
   "touchDistance": float
   "touchZone": string - one of "none", "hovering", "touching"
   "type": integer - 0 is thumb; 4 is pinky
   "width": float

Notes:

Gesture data is only included in a frame of data if gesture recognition is enabled by sending the <tt class="docutils literal">enableGestures</tt> message to the WebSocket server.

Hand.basis is computed from the palmNormal and direction vectors. It is not included in the JSON data.

Motion factors¶

The motion factors, r, s, t, attached to Hand and Frame objects are snapshots of the motion occuring across frames. These factors must be combined with those of a previous frame to derive the relative motion.

r – a 3x3 rotation matrix

s – a scale factor

t – a 3-element translation vector

Rotation factor¶

The matrix expressing the relative rotation between two frames can be calculated by multiplying the r matrix from the current frame by the inverse of the r matrix of the starting frame.

\[\mathbf{rotation} = \mathbf{r_{current frame}} * \mathbf{r_{since frame}^{-1}}\]

Scale factor¶

The relative scale factor between two frames can be calculated by subtracting the s value from the starting frame from the current s value and computing the natural exponential function of the result.

\[scalefactor = e^{s_{current frame} - s_{sinceframe}}\]

Translation factor¶

The relative translation factor between two frames can be calculated by subtracting the t vector from the starting frame from the current t vector.

\[\mathbf{\overrightarrow{translation}} = \mathbf{\vec{t}}_{current frame} - \mathbf{\vec{t}}_{since frame}\]

Protocol Changes¶

This document describes the most recent version of the protocol.

Each version of the protocol corresponds to particular versions of the Leap Motion software installed on a client computer as well as a versions of the leap.js library which use the protocol:

<colgroup>
<col width="11%" />
<col width="39%" />
<col width="50%" />
</colgroup>

Protocol
Leap Motion Client Software
Leap.js

v1.json
prerelease
0.1.n

v2.json
prerelease
0.2.n

v3.json
1.0+
0.3.n

v4.json
1.0.9+
0.4.n

v5.json
1.2.0+
0.5.n

v6.json
2.0+
0.6.n

The following changes were made from previous versions of the protocol:

Version 6¶

Added additional data from the Leap Motion v2, skeletal tracking model:

Hand.confidence

Hand.grabStrength

Hand.pinchStrength

Hand.type

Pointable.dipPosition

Pointable.extended

Pointable.mcpPosition

Pointable.pipPosition

Pointable.type

Added Pointable.width for fingers

Added <tt class="docutils literal">optimizeHMD</tt> client-to-server message.

Version 5¶

Added deviceEvent messages.

Removed deviceConnected events in favore of deviceEvent messages.

Version 4¶

Added <tt class="docutils literal">focused</tt> and <tt class="docutils literal">background</tt> messages.

Removed <tt class="docutils literal">heartbeat</tt> messages. Servers supporting protocol version 4 or above ignore heartbeat messages, even when connecting to clients requesting protocol versions 2 or 3.

Version 3¶

Added <tt class="docutils literal">deviceConnected</tt> events.

Version 2¶

Added <tt class="docutils literal">heartbeat</tt> messages. If your application supports protocol version 2 or 3, you should send a heartbeat message every 100ms from clients connecting with version 2 or 3. If a heartbeat is not received by the server within this time period, it assumes the client is not active and stops sending data until it receives another heartbeat. Heartbeats were removed in version 4 in favor of <tt class="docutils literal">focused</tt> and <tt class="docutils literal">background</tt> messages.

C++ Docs (v3.1)

API Overview

Guidelines

Application Development

Using the Tracking API

API Reference

Appendices

Using the Leap Motion Control Panel

Using the Diagnostic Visualizer

WebSocket Communication

Protocols

Client-Server Messages

JSON tracking data format

Motion factors

Protocol Changes

Version 6

Version 5

Version 4

Version 3

Version 2

Leap Motion Release Notes

Acknowledgements


text:
package org.bouncycastle.pqc.crypto.lms;

import java.io.ByteArrayOutputStream;

import org.bouncycastle.util.encoders.Hex;

public class LMSVectorUtils
{
    public static final byte[] extract$PrefixedBytes(String vectorFromRFC)
        throws Exception
    {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for (String line : vectorFromRFC.split("\n"))
        {
            int start = line.indexOf("$");
            if (start > -1)
            {

                int end = line.indexOf("#");
                String hex;
                if (end < 0)
                {
                    hex = line.substring(start + 1).trim();
                }
                else
                {
                    hex = line.substring(start + 1, end).trim();
                }

                bos.write(Hex.decode(hex));
            }
        }
        return bos.toByteArray();

    }
}