text:
using System;
using System.Configuration;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Salesforce.Common;
using Salesforce.Common.Models.Json;
using Salesforce.Force.Tests.Models;
using System.Collections.Generic;
//using WadeWegner.Salesforce.SOAPHelpers;

namespace Salesforce.Force.Tests
{
  [TestFixture]
  public class ForceClientFunctionalTests
  {
    private static string _consumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
    private static string _consumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
    private static string _username = ConfigurationManager.AppSettings["Username"];
    private static string _password = ConfigurationManager.AppSettings["Password"];
    private static string _organizationId = ConfigurationManager.AppSettings["OrganizationId"];
    private static string _instanceUrl = ConfigurationManager.AppSettings["InstanceUrl"];

    private AuthenticationClient _auth;
    private ForceClient _client;

    [OneTimeSetUp]
    public void Init()
    {
      if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password) && string.IsNullOrEmpty(_organizationId))
      {
        _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
        _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
        _username = Environment.GetEnvironmentVariable("Username");
        _password = Environment.GetEnvironmentVariable("Password");
        _organizationId = Environment.GetEnvironmentVariable("OrganizationId");
        _instanceUrl = Environment.GetEnvironmentVariable("InstanceUrl");
      }

      // Use TLS 1.2 (instead of defaulting to 1.0)
      const int SecurityProtocolTypeTls11 = 768;
      const int SecurityProtocolTypeTls12 = 3072;
      ServicePointManager.SecurityProtocol |= (SecurityProtocolType)(SecurityProtocolTypeTls12 | SecurityProtocolTypeTls11);

      _auth = new AuthenticationClient();
      _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password).Wait();

      _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
    }

    [Test]
    public async Task AsyncTaskCompletion_ExpandoObject()
    {
      dynamic account = new ExpandoObject();
      account.Name = "ExpandoName" + DateTime.Now.Ticks;
      account.Description = "ExpandoDescription" + DateTime.Now.Ticks;

      var result = await _client.CreateAsync("Account", account);

      Assert.IsNotNull(result);
    }

    [Test]
    public async Task UserInfo_IsNotNull()
    {
      var userInfo = await _client.UserInfo<UserInfo>(_auth.Id);

      Assert.IsNotNull(userInfo);
    }

    [Test]
    public async Task Query_Accounts_Continuation()
    {
      var accounts = await _client.QueryAsync<Account>("SELECT count() FROM Account");

      if (accounts.TotalSize < 1000)
      {
        await CreateLotsOfAccounts(_client);
      }

      var contacts = await _client.QueryAsync<dynamic>("SELECT Id, Name, Description FROM Account");

      var nextRecordsUrl = contacts.NextRecordsUrl;
      var nextContacts = await _client.QueryContinuationAsync<dynamic>(nextRecordsUrl);

      Assert.IsNotNull(nextContacts);
      Assert.AreNotEqual(contacts, nextContacts);
    }

    public async Task CreateLotsOfAccounts(ForceClient forceClient)
    {
      var account = new Account { Name = "Test Account", Description = "New Account Description" };

      for (var i = 0; i < 1000; i++)
      {
        account.Name = "Test Account (" + i + ")";
        await forceClient.CreateAsync("Account", account);
      }
    }

    [Test]
    public async Task Query_Count()
    {
      var accounts = await _client.QueryAsync<Account>("SELECT count() FROM Account");

      Assert.IsNotNull(accounts);
    }

    [Test]
    public async Task Query_Accounts_IsNotEmpty()
    {
      var accounts = await _client.QueryAsync<Account>("SELECT Id, name, description FROM Account");

      Assert.IsNotNull(accounts);
    }

    [Test]
    public async Task Query_ContactsWithAccountName_IsNotEmpty()
    {
      var queryResult = await _client.QueryAsync<Models.QueryTest.Contact>("SELECT AccountId, Account.Name, Email, Phone, Name, Title, MobilePhone FROM Contact Where Account.Name != null");

      Assert.IsNotNull(queryResult);
      Assert.IsNotNull(queryResult.Records);
      Assert.IsNotNull(queryResult.Records[0].Name);
      //Assert.IsNotNull(queryResult.Records[0].Account.Name); //BUG: This assertion sometimes causes the test run to fail (Not sure why, needs investigation)
    }

    [Test]
    public async Task Query_Accounts_BadObject()
    {
      try
      {
        await _client.QueryAsync<Account>("SELECT Id, name, description FROM BadObject");
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Create_Account_Typed()
    {
      var account = new Account { Name = "New Account", Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);

      Assert.That(successResponse.Id, Is.Not.Null.And.Not.Empty);
    }

    [Test]
    public async Task Create_Accounts_Typed()
    {
      var lstAccounts = new List<IAttributedObject>();

      lstAccounts.Add(new AtrributedAccount { Name = "New Account 1", Description = "New Account Description", Attributes = new ObjectAttributes()
        {
          Type = "Account",
          ReferenceId="ACC1",
        },
      });
      lstAccounts.Add(new AtrributedAccount { Name = "New Account 2", Description = "New Account Description", Attributes = new ObjectAttributes()
        {
          Type = "Account",
          ReferenceId = "ACC2",
        },
      });
      lstAccounts.Add(new AtrributedAccount { Name = "New Account 3", Description = "New Account Description", Attributes = new ObjectAttributes()
        {
          Type = "Account",
          ReferenceId = "ACC3",
        },
      });

      var theRequest = new CreateRequest()
      {
        Records = lstAccounts
      };

      var successResponse = await _client.CreateAsync("Account", theRequest);

      Assert.That(successResponse.Results, Is.Not.Null.And.Not.Empty);
    }

    [Test]
    public async Task QueryAll_Accounts_IsNotEmpty()
    {
      var accounts = await _client.QueryAllAsync<Account>("SELECT Id, name, description FROM Account");

      Assert.IsNotNull(accounts);
    }

    [Test]
    public async Task QueryAll_Accounts_Continuation()
    {
      var accounts = await _client.QueryAllAsync<Account>("SELECT count() FROM Account");

      if (accounts.TotalSize < 1000)
      {
        await CreateLotsOfAccounts(_client);
      }

      var contacts = await _client.QueryAllAsync<dynamic>("SELECT Id, Name, Description FROM Account");

      var nextRecordsUrl = contacts.NextRecordsUrl;
      var nextContacts = await _client.QueryContinuationAsync<dynamic>(nextRecordsUrl);

      Assert.IsNotNull(nextContacts);
      Assert.AreNotEqual(contacts, nextContacts);
    }

    [Test]
    public async Task Create_Contact_Typed_Annotations()
    {
      var contact = new Contact { Id = "Id", IsDeleted = false, AccountId = "AccountId", Name = "Name", FirstName = "FirstName", LastName = "LastName", Description = "Description" };
      var successResponse = await _client.CreateAsync("Contact", contact);

      Assert.That(successResponse.Id, Is.Not.Null.And.Not.Empty);
    }

    [Test]
    public async Task Create_Account_Untyped()
    {
      var account = new { Name = "New Account", Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);

      Assert.That(successResponse.Id, Is.Not.Null.And.Not.Empty);
    }

    [Test]
    public async Task Create_Account_Untyped_BadObject()
    {
      try
      {
        var account = new { Name = "New Account", Description = "New Account Description" };
        await _client.CreateAsync("BadAccount", account);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Create_Account_Untyped_BadFields()
    {
      try
      {
        var account = new { BadName = "New Account", BadDescription = "New Account Description" };
        await _client.CreateAsync("Account", account);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Update_Account_IsSuccess()
    {
      const string originalName = "New Account";
      const string newName = "New Account 2";

      var account = new Account { Name = originalName, Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);

      account.Name = newName;

      var success = await _client.UpdateAsync("Account", successResponse.Id, account);

      Assert.IsNotNull(success);
    }

    [Test]
    public async Task Update_Account_NullValues()
    {
      const string originalName = "New Account";
      const string newName = "New Account 2";

      var newAccount = new Account { Name = originalName, Description = "New Account Description" };
      var success1 = await _client.CreateAsync("Account", newAccount);
      Assert.IsNotNull(success1);

      var id = success1.Id;

      const string query = "SELECT AccountNumber,AccountSource,Active__c,AnnualRevenue,BillingAddress,BillingCity,BillingCountry,BillingGeocodeAccuracy,BillingLatitude,BillingLongitude,BillingPostalCode,BillingState,BillingStreet,CleanStatus,CreatedById,CreatedDate,CustomerPriority__c,DandbCompanyId,Description,DunsNumber,ExternalId__c,External_Id__c,Fax,Id,Industry,IsDeleted,Jigsaw,JigsawCompanyId,LastActivityDate,LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,MasterRecordId,MyCustomField__c,NaicsCode,NaicsDesc,Name,NumberOfEmployees,NumberofLocations__c,OwnerId,Ownership,ParentId,Phone,PhotoUrl,Rating,ShippingAddress,ShippingCity,ShippingCountry,ShippingGeocodeAccuracy,ShippingLatitude,ShippingLongitude,ShippingPostalCode,ShippingState,ShippingStreet,Sic,SicDesc,Site,SLAExpirationDate__c,SLASerialNumber__c,SLA__c,SystemModstamp,TickerSymbol,Tradestyle,Type,UpsellOpportunity__c,Website,YearStarted FROM Account WHERE Id = '{0}'";

      var account1 = await _client.QueryAsync<Account>(string.Format(query, id));
      var newAccount2 = new Account { Name = newName };

      var success2 = await _client.UpdateAsync("Account", id, newAccount2);
      Assert.IsNotNull(success2);

      var account2 = await _client.QueryAsync<Account>(string.Format(query, id));

      Assert.AreEqual(account1.Records[0].Description, account2.Records[0].Description);
    }

    [Test]
    public async Task Update_Account_BadObject()
    {
      try
      {
        const string originalName = "New Account";
        const string newName = "New Account 2";

        var account = new Account { Name = originalName, Description = "New Account Description" };
        var successResponse = await _client.CreateAsync("Account", account);

        account.Name = newName;

        await _client.UpdateAsync("BadAccount", successResponse.Id, account);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Update_Account_BadField()
    {
      try
      {
        const string originalName = "New Account";
        const string newName = "New Account 2";

        var account = new { Name = originalName, Description = "New Account Description" };
        var successResponse = await _client.CreateAsync("Account", account);

        var updatedAccount = new { BadName = newName, Description = "New Account Description" };

        await _client.UpdateAsync("Account", successResponse.Id, updatedAccount);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Update_Account_NameChanged()
    {
      const string originalName = "New Account";
      const string newName = "New Account 2";

      var account = new Account { Name = originalName, Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);
      account.Name = newName;
      await _client.UpdateAsync("Account", successResponse.Id, account);

      var result = await _client.QueryByIdAsync<Account>("Account", successResponse.Id);

      Assert.True(result.Name == newName);
    }

    [Test]
    public async Task Update_Account_ExternalIdChanged()
    {
      string originalExternalId = string.Concat(Guid.NewGuid().ToString("N").Take(16));
      string newExternalId = string.Concat(Guid.NewGuid().ToString("N").Take(16));

      dynamic account = new ExpandoObject();
      account.Name = "New Account";
      account.Description = "New Account Description";
      account.ExternalId__c = originalExternalId;
      var successResponse = await _client.CreateAsync("Account", account);

      account.ExternalId__c = newExternalId;
      await _client.UpdateAsync("Account", successResponse.Id, account);

      var result = await _client.QueryAllFieldsByIdAsync<Account>("Account", successResponse.Id);

      Assert.True(result.ExternalId__c.ToString() == newExternalId);
    }

    [Test]
    public async Task Delete_Account_IsSuccess()
    {
      var account = new Account { Name = "New Account", Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);
      var success = await _client.DeleteAsync("Account", successResponse.Id);

      Assert.IsTrue(success);
    }

    [Test]
    public async Task Delete_Account_ObjectDoesNotExist()
    {
      try
      {
        var account = new Account { Name = "New Account", Description = "New Account Description" };
        var successResponse = await _client.CreateAsync("Account", account);
        var success = await _client.DeleteAsync("BadAccount", successResponse.Id);

        Assert.IsTrue(success);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Delete_Account_IdDoesNotExist()
    {
      try
      {
        const string id = "asdfasdfasdf";
        await _client.DeleteAsync("Account", id);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Delete_Account_ValidateIsGone()
    {
      var account = new Account { Name = "New Account", Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);
      await _client.DeleteAsync("Account", successResponse.Id);

      var result = await _client.QueryByIdAsync<Account>("Account", successResponse.Id);

      Assert.IsNull(result);
    }

    //[Test]
    //public async Task Delete_External_ValidateIsGone()
    //{
    //    const string objectName = "Account";
    //    const string fieldName = "ExternalId__c";
    //    var fieldId = "123" + DateTime.Now.Ticks;

    //    await CreateExternalIdField(objectName, fieldName);

    //    var account = new Account { Name = "Upserted To Delete", Description = "Upserted Account Description to Delete" };
    //    var success = await _client.UpsertExternalAsync(objectName, fieldName, fieldId, account);

    //    var resultExists = await _client.QueryByIdAsync<Account>("Account", success.Id);

    //    Assert.IsNotNull(resultExists);

    //    await _client.DeleteExternalAsync("Account", fieldName, fieldId);

    //    var resultDoesNotExists = await _client.QueryByIdAsync<Account>("Account", success.Id);

    //    Assert.IsNull(resultDoesNotExists);
    //}

    [Test]
    public async Task Objects_GetAllObjects_IsNotNull()
    {
      var objects = await _client.GetObjectsAsync<object>();

      Assert.IsNotNull(objects);
    }

    [Test]
    public async Task Object_BasicInformation_IsNotNull()
    {
      var accounts = await _client.BasicInformationAsync<object>("Account");

      Assert.IsNotNull(accounts);
    }

    [Test]
    public async Task Object_Describe_IsNotNull()
    {
      var accounts = await _client.DescribeAsync<object>("Account");

      Assert.IsNotNull(accounts);
    }

    [Test]
    public async Task Object_GetDeleted_IsNotNull()
    {
      var account = new Account { Name = "New Account to Delete", Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);

      await _client.DeleteAsync("Account", successResponse.Id);
      var dateTime = DateTime.Now;

      await Task.Run(() => Thread.Sleep(5000));

      var sdt = dateTime.Subtract(new TimeSpan(0, 0, 2, 0));
      var edt = dateTime.Add(new TimeSpan(0, 0, 2, 0));
      var deleted = await _client.GetDeleted<DeletedRecordRootObject>("Account", sdt, edt);

      Assert.IsNotNull(deleted);
      Assert.IsNotNull(deleted.DeletedRecords);
      Assert.IsTrue(deleted.DeletedRecords.Count > 0);
    }

    [Test]
    public async Task Object_GetUpdated_IsNotNull()
    {
      const string originalName = "New Account";
      const string newName = "New Account 2";

      var account = new Account { Name = originalName, Description = "New Account Description" };
      var successResponse = await _client.CreateAsync("Account", account);

      account.Name = newName;
      var dateTime = DateTime.Now;

      await _client.UpdateAsync("Account", successResponse.Id, account);

      await Task.Run(() => Thread.Sleep(5000));

      var sdt = dateTime.Subtract(new TimeSpan(0, 0, 2, 0));
      var edt = dateTime.Add(new TimeSpan(0, 0, 2, 0));
      var updated = await _client.GetUpdated<UpdatedRecordRootObject>("Account", sdt, edt);

      Assert.IsNotNull(updated);
      Assert.IsTrue(updated.Ids.Count > 0);
    }

    [Test]
    public async Task Object_DescribeLayout_IsNotNull()
    {
      var accountsLayout = await _client.DescribeLayoutAsync<dynamic>("Account");

      Assert.IsNotNull(accountsLayout);

      string recordTypeId = accountsLayout.recordTypeMappings[0].recordTypeId;

      Assert.IsNotNull(recordTypeId);

      var accountsLayoutForRecordTypeId = await _client.DescribeLayoutAsync<dynamic>("Account", recordTypeId);

      Assert.IsNotNull(accountsLayoutForRecordTypeId);
    }

    [Test]
    public async Task Recent_IsNotNull()
    {
      var recent = await _client.RecentAsync<object>(5);

      Assert.IsNotNull(recent);
    }

    //[Test]
    //public async Task Upsert_Account_Update_IsSuccess()
    //{
    //    const string objectName = "Account";
    //    const string fieldName = "ExternalId__c";

    //    await CreateExternalIdField(objectName, fieldName);

    //    var account = new Account { Name = "Upserted Account", Description = "Upserted Account Description" };
    //    var success = await _client.UpsertExternalAsync(objectName, fieldName, "123", account);

    //    Assert.IsNotNull(success);
    //    Assert.IsEmpty(success.Id);
    //}

    //[Test]
    //public async Task Upsert_Account_Insert_IsSuccess()
    //{
    //    const string objectName = "Account";
    //    const string fieldName = "ExternalId__c";

    //    await CreateExternalIdField(objectName, fieldName);

    //    var account = new Account { Name = "Upserted Account" + DateTime.Now.Ticks, Description = "New Upserted Account Description" + DateTime.Now.Ticks };
    //    var success = await _client.UpsertExternalAsync(objectName, fieldName, "123" + DateTime.Now.Ticks, account);

    //    Assert.IsNotNull(success);
    //    Assert.IsNotNull(success.Id);
    //    Assert.That(success.Id, Is.Not.Null.And.Not.Empty);
    //}

    [Test]
    public async Task Upsert_Account_BadObject()
    {
      try
      {
        var account = new Account { Name = "New Account ExternalID", Description = "New Account Description" };
        await _client.UpsertExternalAsync("BadAccount", "ExternalID__c", "2", account);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    [Test]
    public async Task Upsert_Account_BadField()
    {
      try
      {
        var accountBadName = new { BadName = "New Account", Description = "New Account Description" };
        await _client.UpsertExternalAsync("Account", "ExternalID__c", "3", accountBadName);
      }
      catch (ForceException ex)
      {
        Assert.IsNotNull(ex);
        Assert.IsNotNull(ex.Message);
        Assert.IsNotNull(ex.Error);
      }
    }

    //[Test]
    //public async Task Upsert_Account_NameChanged()
    //{
    //    const string fieldName = "ExternalId__c";
    //    await CreateExternalIdField("Account", fieldName);

    //    const string originalName = "New Account External Upsert";
    //    const string newName = "New Account External Upsert 2";

    //    var account = new Account { Name = originalName, Description = "New Account Description" };
    //    await _client.UpsertExternalAsync("Account", fieldName, "4", account);

    //    account.Name = newName;
    //    await _client.UpsertExternalAsync("Account", fieldName, "4", account);

    //    var accountResult = await _client.QueryAsync<Account>(string.Format("SELECT Name FROM Account WHERE {0} = '4'", fieldName));
    //    var firstOrDefault = accountResult.Records.FirstOrDefault();

    //    Assert.True(firstOrDefault != null && firstOrDefault.Name == newName);
    //}

    //[Test]
    //public async Task UpdateExternalAsync_AccountSource()
    //{
    //    dynamic a = new ExpandoObject();
    //    a.AccountSource = "TestAccountSource";
    //    a.Name = "TestAccountName";

    //    const string objectName = "Account";
    //    const string fieldName = "External_Id__c";

    //    await CreateExternalIdField(objectName, fieldName);

    //    var externalId = Convert.ToString(DateTime.Now.Ticks);

    //    var success = await _client.UpsertExternalAsync(objectName, fieldName, externalId, a);
    //    Assert.IsNotNull(success.Id);
    //    Assert.IsNotNull(success);

    //    a.AccountSource = "TestAccountSource2";

    //    success = await _client.UpsertExternalAsync(objectName, fieldName, externalId, a);
    //    Assert.IsNotNull(success);
    //    Assert.IsEmpty(success.Id);
    //}

    [Test]
    public async Task QueryLeadWithUnescapedCharactersInEmail()
    {
      const string query = "SELECT Id FROM Lead WHERE email = 'forcetoolkit+issue@gmail.com'";
      var result = await _client.QueryAsync<dynamic>(query);

      Assert.IsNotNull(result);
      Assert.IsNotNull(result.Records);
      Assert.That(result.TotalSize, Is.Not.EqualTo(0));
    }

    [Test]
    public async Task QueryBlobContents()
    {
        var success = await _client.CreateAsync("Account", new Account { Name = "Test Account", Description = "New Account Description" });
        Assert.IsNotNull(success.Id);

        String accountId = success.Id;
        String input = "QueryBlobContents - Unit Test";
        var contents = System.Text.Encoding.UTF8.GetBytes(input);
        success = await _client.CreateAsync("Attachment", new { ParentId = accountId, Name = "BlobFunctionalTest.txt", Body = contents });

        String attachmentId = success.Id;
        var stream = await _client.GetBlobAsync("Attachment", attachmentId, "Body");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            var output = reader.ReadToEnd();
            Assert.AreEqual(input, output);
        }
    }

    [Test]
    public async Task SearchAsync()
    {
      var result = await _client.SearchAsync<dynamic>("FIND {test}");

      Assert.IsNotNull(result);

      result = await _client.SearchAsync<dynamic>("FIND {493*} in Phone FIELDS RETURNING Contact(Id, FirstName, Lastname, Email, Phone, MobilePhone)");

      Assert.IsNotNull(result);

      result = await _client.SearchAsync<dynamic>("FIND {493*} in Phone FIELDS RETURNING Lead(Id, FirstName, LastName, Phone, Company), Contact(Id, FirstName, LastName, Phone, MobilePhone)");

      Assert.IsNotNull(result);
    }

    [Test]
    public async Task Create_EventWithDate_IsSuccess()
    {
      // This test is to ensure we have proper date serialization and don't get the following error:
      // "Cannot deserialize instance of date from VALUE_STRING value 2015-08-25T11:49:53.0113029-07:00"

      var account = new Account { Name = "New Account", Description = "New Account Description" };
      var accountSuccessResponse = await _client.CreateAsync("Account", account);

      var newEvent = new Event
      {
        Description = "new Event",
        Subject = "new Event",
        WhatId = accountSuccessResponse.Id,
        ActivityDate = DateTime.Now,
        DurationInMinutes = 10,
        ActivityDateTime = DateTime.Now
      };

      var eventSuccessResponse = await _client.CreateAsync("Event", newEvent);

      Assert.IsTrue(eventSuccessResponse.Success);
    }

    [Test]
    public async Task ExecuteRestApiPost()
    {
      const string echo = "Thing to echo";

      var json = JObject.Parse(@"{'toecho':'" + echo + "'}");
      var response = await _client.ExecuteRestApiAsync<dynamic>("RestWSTest", json);

      Assert.IsNotNull(response);
      Assert.AreEqual(echo, response);
    }

    [Test]
    public async Task ExecuteRestApiGet()
    {
      const string echo = "stuff";

      var response = await _client.ExecuteRestApiAsync<dynamic>("RestWSTest");

      Assert.IsNotNull(response);
      Assert.AreEqual(echo, response);
    }

    [Test]
    public async Task ExecuteAnonymousAsync()
    {
      var response = await _client.ExecuteAnonymousAsync<AnonymousExecutionResponse>("System.debug('Test');");
      Assert.IsNotNull(response);
      Assert.IsTrue(response.Success);
    }

    //#region Private methods
    //private static async Task CreateExternalIdField(string objectName, string fieldName)
    //{
    //    var salesforceClient = new SalesforceClient();
    //    var loginResult = await salesforceClient.Login(_username, _password, _organizationId);

    //    await salesforceClient.CreateCustomField(objectName, fieldName, loginResult.SessionId,
    //            loginResult.MetadataServerUrl, true);
    //}
    //#endregion
  }
}


text:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace TwitterService.OAuth {

    /// <summary>
    /// Basic DelegatingHandler that creates an OAuth authorization header based on the OAuthBase
    /// class downloaded from http://oauth.net
    /// </summary>
    /// <remarks>
    /// Every time a request is submitted it hits the SendAsync method where we get the information from the request
    /// and update it with an appropriate OAuth authentication header before sending it on its way to the next handler.
    /// </remarks>
    public class OAuthMessageHandler : DelegatingHandler {

        // Obtain these values by creating a Twitter app at http://dev.twitter.com/
        // account: @BInowplaying
        // user: dev@bunnyinc.com
        // pass: dev22763404
        // consumer key (API Key): gEFEbGdkVTDfzVgyiiCbzUImi
        private static string _consumerKey = "gEFEbGdkVTDfzVgyiiCbzUImi";
        private static string _consumerSecret = "Q4yQ000AiJL110zoNEkBYL0ASl84SUcnaxkCJ01uZzeghqWeXX";
        private static string _token = "2834545563-3Gp2kIjsN5fFSiph2560NAJanr3WZ6S8pMjzPVU";
        private static string _tokenSecret = "iESkAmBbHXWaCHLrkXN89CUyigMMZ5QHboNYsczUDQLlg";

        private OAuthBase _oAuthBase = new OAuthBase();

        public OAuthMessageHandler(HttpMessageHandler innerHandler)
            : base(innerHandler) {
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            // Compute OAuth header
            string normalizedUri;
            string normalizedParameters;
            string authHeader;

            string signature = _oAuthBase.GenerateSignature(
                request.RequestUri,
                _consumerKey,
                _consumerSecret,
                _token,
                _tokenSecret,
                request.Method.Method,
                _oAuthBase.GenerateTimeStamp(),
                _oAuthBase.GenerateNonce(),
                out normalizedUri,
                out normalizedParameters,
                out authHeader);

            request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authHeader);
            return base.SendAsync(request, cancellationToken);
        }

    }//end class
}//end namespace

redpajama_set_name: RedPajamaGithub


text:
package app.ctrlyati.android.lazyquickreturn.listener;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import app.ctrlyati.android.lazyquickreturn.QuickReturnHelper;
import app.ctrlyati.android.lazyquickreturn.R;

/**
 * Created by Yati on 05/14/2015.
 */
public class SimpleTopElementQuickReturnListener extends SimpleQuickReturnListener {

    public static final float SCROLL_THRESHOLD = 100f;

    private View mTarget;

    private Animation mEnterAnimation;
    private Animation mExitAnimation;

    public SimpleTopElementQuickReturnListener(@NonNull final View target, Context context) {
        super(SCROLL_THRESHOLD, QuickReturnHelper.Direction.UP);

        mTarget = target;

        mExitAnimation = AnimationUtils.loadAnimation(context.getApplicationContext(), R.anim.abc_slide_out_top);
        mExitAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mTarget.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mEnterAnimation = AnimationUtils.loadAnimation(context.getApplicationContext(),
                R.anim.abc_slide_in_top);
        mEnterAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mTarget.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    @Override
    public void onShow() {
        mTarget.startAnimation(mEnterAnimation);
    }

    @Override
    public void onHide() {
        mTarget.startAnimation(mExitAnimation);
    }
}


text:
package com.amazonaws.services.healthlake.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The filters applied to Data Store query.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DatastoreFilter implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Allows the user to filter Data Store results by name.
     *

     */
    private String datastoreName;
    /**
     *

     * Allows the user to filter Data Store results by status.
     *

     */
    private String datastoreStatus;
    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date
     * will be included in the results.
     *

     */
    private java.util.Date createdBefore;
    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date
     * will be included in the results.
     *

     */
    private java.util.Date createdAfter;

    /**
     *

     * Allows the user to filter Data Store results by name.
     *

     *
     * @param datastoreName
     *        Allows the user to filter Data Store results by name.
     */

    public void setDatastoreName(String datastoreName) {
        this.datastoreName = datastoreName;
    }

    /**
     *

     * Allows the user to filter Data Store results by name.
     *

     *
     * @return Allows the user to filter Data Store results by name.
     */

    public String getDatastoreName() {
        return this.datastoreName;
    }

    /**
     *

     * Allows the user to filter Data Store results by name.
     *

     *
     * @param datastoreName
     *        Allows the user to filter Data Store results by name.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DatastoreFilter withDatastoreName(String datastoreName) {
        setDatastoreName(datastoreName);
        return this;
    }

    /**
     *

     * Allows the user to filter Data Store results by status.
     *

     *
     * @param datastoreStatus
     *        Allows the user to filter Data Store results by status.
     * @see DatastoreStatus
     */

    public void setDatastoreStatus(String datastoreStatus) {
        this.datastoreStatus = datastoreStatus;
    }

    /**
     *

     * Allows the user to filter Data Store results by status.
     *

     *
     * @return Allows the user to filter Data Store results by status.
     * @see DatastoreStatus
     */

    public String getDatastoreStatus() {
        return this.datastoreStatus;
    }

    /**
     *

     * Allows the user to filter Data Store results by status.
     *

     *
     * @param datastoreStatus
     *        Allows the user to filter Data Store results by status.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DatastoreStatus
     */

    public DatastoreFilter withDatastoreStatus(String datastoreStatus) {
        setDatastoreStatus(datastoreStatus);
        return this;
    }

    /**
     *

     * Allows the user to filter Data Store results by status.
     *

     *
     * @param datastoreStatus
     *        Allows the user to filter Data Store results by status.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DatastoreStatus
     */

    public DatastoreFilter withDatastoreStatus(DatastoreStatus datastoreStatus) {
        this.datastoreStatus = datastoreStatus.toString();
        return this;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date
     * will be included in the results.
     *

     *
     * @param createdBefore
     *        A filter that allows the user to set cutoff dates for records. All Data Stores created before the
     *        specified date will be included in the results.
     */

    public void setCreatedBefore(java.util.Date createdBefore) {
        this.createdBefore = createdBefore;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date
     * will be included in the results.
     *

     *
     * @return A filter that allows the user to set cutoff dates for records. All Data Stores created before the
     *         specified date will be included in the results.
     */

    public java.util.Date getCreatedBefore() {
        return this.createdBefore;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date
     * will be included in the results.
     *

     *
     * @param createdBefore
     *        A filter that allows the user to set cutoff dates for records. All Data Stores created before the
     *        specified date will be included in the results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DatastoreFilter withCreatedBefore(java.util.Date createdBefore) {
        setCreatedBefore(createdBefore);
        return this;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date
     * will be included in the results.
     *

     *
     * @param createdAfter
     *        A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified
     *        date will be included in the results.
     */

    public void setCreatedAfter(java.util.Date createdAfter) {
        this.createdAfter = createdAfter;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date
     * will be included in the results.
     *

     *
     * @return A filter that allows the user to set cutoff dates for records. All Data Stores created after the
     *         specified date will be included in the results.
     */

    public java.util.Date getCreatedAfter() {
        return this.createdAfter;
    }

    /**
     *

     * A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date
     * will be included in the results.
     *

     *
     * @param createdAfter
     *        A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified
     *        date will be included in the results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DatastoreFilter withCreatedAfter(java.util.Date createdAfter) {
        setCreatedAfter(createdAfter);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDatastoreName() != null)
            sb.append("DatastoreName: ").append(getDatastoreName()).append(",");
        if (getDatastoreStatus() != null)
            sb.append("DatastoreStatus: ").append(getDatastoreStatus()).append(",");
        if (getCreatedBefore() != null)
            sb.append("CreatedBefore: ").append(getCreatedBefore()).append(",");
        if (getCreatedAfter() != null)
            sb.append("CreatedAfter: ").append(getCreatedAfter());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DatastoreFilter == false)
            return false;
        DatastoreFilter other = (DatastoreFilter) obj;
        if (other.getDatastoreName() == null ^ this.getDatastoreName() == null)
            return false;
        if (other.getDatastoreName() != null && other.getDatastoreName().equals(this.getDatastoreName()) == false)
            return false;
        if (other.getDatastoreStatus() == null ^ this.getDatastoreStatus() == null)
            return false;
        if (other.getDatastoreStatus() != null && other.getDatastoreStatus().equals(this.getDatastoreStatus()) == false)
            return false;
        if (other.getCreatedBefore() == null ^ this.getCreatedBefore() == null)
            return false;
        if (other.getCreatedBefore() != null && other.getCreatedBefore().equals(this.getCreatedBefore()) == false)
            return false;
        if (other.getCreatedAfter() == null ^ this.getCreatedAfter() == null)
            return false;
        if (other.getCreatedAfter() != null && other.getCreatedAfter().equals(this.getCreatedAfter()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDatastoreName() == null) ? 0 : getDatastoreName().hashCode());
        hashCode = prime * hashCode + ((getDatastoreStatus() == null) ? 0 : getDatastoreStatus().hashCode());
        hashCode = prime * hashCode + ((getCreatedBefore() == null) ? 0 : getCreatedBefore().hashCode());
        hashCode = prime * hashCode + ((getCreatedAfter() == null) ? 0 : getCreatedAfter().hashCode());
        return hashCode;
    }

    @Override
    public DatastoreFilter clone() {
        try {
            return (DatastoreFilter) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.healthlake.model.transform.DatastoreFilterMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
A Reimagined Way to do Android bots

This system is divided into two parts: Reimagined and Enigma.

## Reimagined
This portion is the desktop and developer toolkit for Enigma clients, the Robot Controller (or just "Enigma") and the Driver Station ("Reimagined" or "Enigma Driver").

Reimagined allows for
- on-the-fly protocol inspection
- Robot Scripting
- Hardware functionality testing
- Custom testing
- Robot emulation (which platform is TBD)

## Engima
The Android system for robot control. Engima is the core for the robot controller. It allows for Android P2P communication, beside communciation with a Reimagined setup. This system relies heavily on Google Guava for the basic building blocks on the system.

### Robot Service
The Robot Service is the master controller for Enigma. It bootstraps and teardowns every other component, except the GUI.

## Simple Dag
This is the core dependency injection system for instation of any elements for when what constructor isn't known until runtime. This relies heavily on reflection, and is the only component that should be using reflection. The API is similar to Dagger, except for a few things.

### How to create instance of a class
```java
SimpleDag.create(klazz.class, this)
```
```this``` is used as a reference to the calling object in case that object knows that some components needed by the class are unknown by the predefined Providers. The requirement for any method in the reference is the same as in a provider.

### What happens if the instance can't be created?
A ```SimpleDagException``` is thrown as a unchecked exception. A JSON array containing information is included if the resolution of how to create the instance couldn't be determined.

# Contributing
I want to know of any improvements, usablity, or any other failures or ideas that you come across feel free to open an issue.
If there is anything you want to help with, open a pull request.

## Requests for opening a Pull Request
- Only add functionality or modify functionality of a certain component (unless you open an issue to describe the reasoning for doing both in your pull request, and enough people like the idea to continue)
- Follow Google Java Style Guidelines in your contributions
- If you add a method, class, interface, or anything of that nature, document it
- If you just refactor a method, document the change you made in the method (you don't have to document any pre-existing methods or classes, it is my fault for the lack of documentation)
- Keep the code you right readable (be descriptive in the names of anything you write; if you throw an exception, don't say it failed, tell why it failed, being as descriptive as possible, and never saying "a thing", "a module", "a instance", and so forth, tell what "a thing" is)
- Write unit tests (either test new functionality or prevent regression of old, bad functionality; Rule 1 doesn't apply to this)
- Write secure code, and fix any security issues found

# License
Apache 2, see LICENSE.md for more info


text:
import React from 'react';
import FontIcon from 'material-ui/FontIcon';
import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation';

const recentsIcon = <FontIcon className="material-icons">home</FontIcon>;
const favoritesIcon = <FontIcon className="material-icons">favorite</FontIcon>;

let selectedIndex = 0;
const select = (index) => {
  selectedIndex = index;
  console.log('selected', index);
};

const TodoFooter = () => (
  <BottomNavigation selectedIndex={selectedIndex}>
    <BottomNavigationItem
      label="Recents"
      icon={recentsIcon}
      onTouchTap={() => select(0)}
    />
    <BottomNavigationItem
      label="Favorites"
      icon={favoritesIcon}
      onTouchTap={() => select(1)}
    />
  </BottomNavigation>
);

export default TodoFooter;


text:
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>
            Brand

                     Shopping Cart

                            {{ Session::has('cart') ? Session::get('cart')->totalQty : '0' }}

                      @if(Auth::check()) [ {{ Auth::user()->email }} ] @else User Account @endif

                        @if(Auth::check())

Profile

Logout

                        @else

Sign Up

Sign In

                        @endif


text:
package org.apache.harmony.test.func.reg.vm.btest5789;

public class Btest5789_parent extends Btest5789_grandParent {
    private int privateField = 1;
    protected int protectedField = 1;
    public int publicField = 1;

    private int privateMethod() {
        System.out.println("Btest5789_parent::privateMethod()");
        return 1;
    }

    public int publicMethod() {
        System.out.println("Btest5789_parent::publicMethod()");
        return 1;
    }

    public int testMe() {
        if(super.testMe() == -1) return error();
        if (privateField != 1) return error();
        if (protectedField != 1) return error();
        if (publicField != 1) return error();

        if (privateMethod() != 1) return error();
        if (protectedMethod() != 2) return error();
        if (publicMethod() != 2) return error();
        return 1;
    }

    protected int error() {
        System.out.println("Error!!!!\n");
        return -1;
    }
};


text:
/**************************************************************************************************/
/* Copyright (C) mc2lab.com, SSE@USTC, 2014-2015                                                  */
/*                                                                                */
/*  FILE NAME             :  printui.C                                                            */
/*  PRINCIPAL AUTHOR      :  Florian Braun                                                        */
/*  SUBSYSTEM NAME        :  printu                                                               */
/*  MODULE NAME           :  printui                                                              */
/*  LANGUAGE              :  C                                                                    */
/*  TARGET ENVIRONMENT    :  ANY (C99)                                                            */
/*  DATE OF FIRST RELEASE :  2015/01/25                                                           */
/*  DESCRIPTION           :  Programm to print nice output in a window                            */
/**************************************************************************************************/

//INFOS----------------
//Default CMD size(Windows) : 80x25
//Default Terminal size(Unix) : 80x24
//INFOS----------------

//TODO Püfen ob ausgame nicht zu lang ist als es dürfte , was zu verschiebung der zeichen führt
//TODO /n löschen wenn win32 da dort /n einen character belegt und deswegen eine neue zeile beginnt.

//Code Begin

#include <stdbool.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "printui.h"
#include "../../src/utils.h"

#ifdef _WIN32
//vc=VerticalCaracter | hc = horizontalCharacter
static const char *hc = "-";
static const char *vc = "|";
//EDGES
static const char *lo = "|"; //links Oben
static const char *ro = "|"; //Rechts Oben

static const char *lu = "|"; //Links Unten
static const char *ru = "|"; //Rechts Unten

#else
//vc=VerticalCaracter | hc = horizontalCharacter
static const char *hc = "┅";
static const char *vc = "┋";
//EDGES
static const char *lo = "┏"; //links Oben
static const char *ro = "┓"; //Rechts Oben

static const char *lu = "┗"; //Links Unten
static const char *ru = "┛"; //Rechts Unten
#endif
//Terminal Breite , terminal wird auf win32 und unix systemen resized siehe src/ConsoleAdaption
static const int terminalWidth = 120;

//New Line Char , bei windows muss sie wieder gelöscht werden da sie ein zeichen verbraucht

#ifdef _WIN32
unsigned char *nlc = "\n";
#else
unsigned char *nlc = "\n";
#endif

//##############
//### Formatierungs Berechnung / Ausgabefalse
//##############

int getTerminalWidth(){
    return terminalWidth;
}

void center_print_row_segment(char *s, int width,bool isHeading,bool isLast)
{

    int length = CountUTF8String(s);
    int i;
    fputs(vc, stdout);
    for (i=1; i<((width-length)/2); i++) {
        if(isHeading){
            fputs(hc, stdout);
        }else{
            fputs(" ", stdout);
        }
    }

    fputs(s, stdout);
    i += length;
    for (; i<=width-2; i++) {
        if(isHeading){
            fputs(hc, stdout);
        }else{
            fputs(" ", stdout);
        }
    }
    fputs(vc, stdout);

    if(isLast) {
        fputs(nlc, stdout);
    }

}

//MODE 0=Header 1=Footer 2=Durchgehende Linie
void center_print_menu_header(char *s, int width,int Mode)
{

    int length = CountUTF8String(s);
    int i;

    if(Mode ==1){  fputs(lu,stdout);  }else if(Mode ==0){fputs(lo,stdout);}else{fputs(hc,stdout);}
    for (i=1; i<=(width-length)/2; i++) {
        fputs(hc, stdout);
    }
    fputs(s, stdout);
    i += length;
    for (; i<=width-2; i++) {

        fputs(hc, stdout);
    }

    if(Mode ==1){  fputs(ru,stdout);  }else if(Mode ==0){fputs(ro,stdout);}else{fputs(hc,stdout);}

    fputs(nlc,stdout);
}

void center_print_menu(char *s, int width)
{

    int length = CountUTF8String(s);
    int i;

    fputs(vc, stdout);
    for (i=1; i<=(width-length)/2; i++) {
        fputs(" ", stdout);
    }
    fputs(s, stdout);
    i += length;

    for (; i <= width - 2; i++) {
        fputs(" ", stdout);
    }

    fputs(vc, stdout);

    fputs(nlc,stdout);

}

//##############
//### Menu Aufbau
//##############

//Gibt die Menuüberschrift aus
void printMenuHeader(char *text){

    center_print_menu_header(text, terminalWidth,0);

}
void printMenuHeaderContinous(char *text){

    center_print_menu_header(text, terminalWidth,3);

}

//Gibt einen menueintrag aus
void printMenuItem(char *text){

    center_print_menu(text, terminalWidth);

}

//##############
//### Datenausgabe
//##############

//Gibt eine x Spaltige Tabelle Aus
void printTabelHeader(int numCols,...){

    va_list ap;
    int i;

    va_start(ap, numCols);
    for(i = 0; i < numCols-1; i++) {
        center_print_row_segment(va_arg(ap, char *), terminalWidth / numCols, true, false);
    }
        center_print_row_segment(va_arg(ap, char *),(terminalWidth-i*(terminalWidth / numCols)), true, true);

    va_end(ap);

}
void printTabelRow(char numCols,...){

    va_list ap;
    int i;

    va_start(ap, numCols);
    for(i = 0; i < numCols-1; i++) {
        center_print_row_segment(va_arg(ap, char *), terminalWidth / numCols, false, false);
    }
      center_print_row_segment(va_arg(ap, char *),(terminalWidth-i*(terminalWidth / numCols)), false, true);

    va_end(ap);

}

//Allgemeine schlusszeile

void printFooterContinous(){
    center_print_row_segment("", terminalWidth , true, true);
}

void printFooter(){
    center_print_menu_header("", terminalWidth,1);
}

void printFooterText(char *S){
    center_print_menu_header(S, terminalWidth,1);
}


text:
set -x

source ../configure.sh

git clone git://repo.or.cz/ppcg.git
cd ppcg
./get_submodules.sh
./autogen.sh
./configure --with-clang-prefix=${LLVM_PREFIX} --with-int=imath
make -j


text:
package org.kuali.rice.kew.rule;

import java.util.List;

import org.kuali.rice.kew.engine.RouteContext;

/**
 * An attribute which can be used to filter a List of rules prior to evaluation
 * by the rules engine.
 *
 * @see FlexRM
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface MassRuleAttribute {

    public List filterNonMatchingRules(RouteContext routeContext, List rules);

}


text:
TestCafe would not be possible without active support from the community. We certainly appreciate and would
encourage your contributions, no matter how large or small.

To that end, please review our contribution guidelines first.

* [Code of Conduct](#code-of-conduct)
* [General Discussion](#general-discussion)
* [Reporting a Problem](#reporting-a-problem)
* [Code Contribution](#code-contribution)

## Code of Conduct

TestCafe has adopted a [Contributor Code of Conduct](CODE_OF_CONDUCT.md), abide by its terms.

## General Discussion

If you have a question about TestCafe feel free to ask us on StackOverflow. We review and answer questions with the [TestCafe](https://stackoverflow.com/questions/tagged/testcafe) tag.

## Reporting a Problem

If you find a problem when using TestCafe, please file an issue in our [GitHub repository](https://github.com/DevExpress/testcafe/issues).
However, to save some time, please search through the existing issues to see if the problem has already been reported or addressed.

When you create a new issue, template text is automatically added to its body.
To help us understand the issue you're describing, be sure to fill in all sections in this template.

## Code Contribution

Please follow the steps below when submitting your code.

1. Search the [list of issues](https://github.com/DevExpress/testcafe/issues) to see if there
  is an issue for the bug or feature you are going to work on. If you do not find one, please create your own.

2. If you are going to address an existing issue, check the comment thread to make sure that nobody is working on it at the moment.

3. Leave a comment saying that you are willing to fix this issue, and if possible, provide details on how you are going to do this.

4. Core team members may need to discuss the details of the proposed fix with you. As soon as you get the green light from them,
  leave a comment saying that you are currently working on this issue.

5. Fork TestCafe and create a branch in your fork. Name this branch with an issue number, e.g. `gh852`, `gh853`.

    > If you are going to update the documentation, do this in a separate branch, e.g. `gh852-docs`.

6. Commit your changes into the branch.

7. Add regression tests to the appropriate sections if you are fixing a bug. You can find these sections by searching for `Regression` in the code.

    Add unit and/or functional tests if you are developing a new functionality.

8. Fetch upstream changes and rebase your branch onto `master`.

9. Run tests before submitting a pull request to ensure that everything works properly.

    ```sh
    gulp test-server
    gulp test-functional-local
    gulp test-client-local
    ```

10. Push changes to your fork.

11. Submit a pull request. If you are also updating the documentation, submit a separate pull request for these changes.

    The pull request name should describe what has been done and contain
    the [closes](https://github.com/blog/1506-closing-issues-via-pull-requests) directive
    with an appropriate issue number.

    Documentation pull requests should have the `[docs]` prefix in their title.
    This ensures that documentation tests are triggered against these pull requests.


text:
title:  Et pålitelig løfte for reisen
date:  30/06/2022
---

>

> «Bare godhet og miskunn skal følge meg alle mine dager, og jeg skal bo i Herrens hus gjennom alle tider» (Sal 23,6).

Når vi er i dalen eller omringet av fiender, kan det være fristende å tro vi er alene. Det føles ikke alltid som om Gud har gjort noe særlig. Vi tenker at hvis han hadde hjulpet oss, ville vi ikke ha kommet ut for dette. Men David ser det ikke slik.

`Hvilke to ting sier David at han er sikker på, til tross for prøvelsene? (Se også Ef 1,4; 2 Pet 1,10; Hebr 11,13–15.)`

Noen oversettelser sier at godhet og usvikelig kjærlighet (Guds paktsforpliktelse) vil «følge» meg alle mine dager. Det opprinnelige verbet er likevel mye sterkere, og verset bør leses som at godhet og usvikelig kjærlighet vil «forfølge» meg alle mine dager. (Det er det samme hebraiske verbet som brukes i slike vers som 1 Mos 14,14; Jos 10,19 og 1 Sam 25,29, der ideen om «å forfølge» er tydelig.)

`Hva ser du for deg hvis du forestiller deg at godhet og usvikelig kjærlighet «forfølger» deg? Hva tror du David ville si oss om Gud ved å skildre hans omsorg på denne måten?`

Samme hvor dyp dalen er eller hvor innbitte fiendene er, så kan vi være trygge på Guds godhet og usvikelige kjærlighet, og at han leder helt til reisens slutt. Hvis disse tankene kunne styrke Jesus på Golgata, burde også vi fatte nytt mot.

Men det hender at mennesker vi har omsorg for, er fulle av spørsmål. Som hos David er det sjelden best å ta opp disse bekymringene med teologiske tanker om hva Gud kan gjøre. Som David viser oss i Sal 23,6, er det bedre å vitne om vår personlige overbevisning om hvordan Gud er.

`Hva er det i din eget kjennskap til Gud som kan underbygge at hans godhet og usvikelige kjærlighet forfølger oss? Hvilke bevis kan du tilføye fra Bibelen? Hvordan kan du dele dette med dem som kanskje er usikre på Guds omsorg? Hvordan er korset det største eksemplet på denne «forfølgelsen».`


text:
package org.apache.olingo.odata2.jpa.processor.core.mock;

import org.apache.olingo.odata2.api.ODataService;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.api.uri.PathInfo;
import org.easymock.EasyMock;

public class ODataContextMock {

  private ODataService odataService;
  private PathInfo pathInfo;
  private boolean isInBatchMode;

  public void setODataService(final ODataService service) {
    odataService = service;
  }

  public void setPathInfo(final PathInfo pathInfo) {
    this.pathInfo = pathInfo;
  }

  public void isInBatchMode(final boolean isInBatchMode) {
    this.isInBatchMode = isInBatchMode;
  }

  public ODataContext mock() throws ODataException {
    ODataContext context = EasyMock.createMock(ODataContext.class);
    EasyMock.expect(context.getService()).andReturn(odataService).anyTimes();
    EasyMock.expect(context.getPathInfo()).andReturn(pathInfo).anyTimes();
    ODataJPAServiceFactoryMock mockServiceFactory = new ODataJPAServiceFactoryMock(context);
    mockServiceFactory.initializeODataJPAContext();
    EasyMock.expect(context.getServiceFactory()).andReturn(mockServiceFactory).anyTimes();
    EasyMock.expect(context.isInBatchMode()).andReturn(this.isInBatchMode).anyTimes();
    EasyMock.replay(context);
    return context;
  }

  public ODataContext mockWithoutOnJPAWriteContent() throws ODataException {
    ODataContext context = EasyMock.createMock(ODataContext.class);
    EasyMock.expect(context.getService()).andReturn(odataService).anyTimes();
    EasyMock.expect(context.getPathInfo()).andReturn(pathInfo).anyTimes();
    EasyMock.expect(context.isInBatchMode()).andReturn(this.isInBatchMode).anyTimes();
    ODataJPAServiceFactoryMock mockServiceFactory = new ODataJPAServiceFactoryMock(context);
    mockServiceFactory.initializeODataJPAContextX();
    EasyMock.expect(context.getServiceFactory()).andReturn(mockServiceFactory).anyTimes();
    EasyMock.replay(context);
    return context;
  }

}


text:
package org.deidentifier.arx.benchmark;

import java.io.File;
import java.io.IOException;

import org.deidentifier.arx.ARXCostBenefitConfiguration;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.benchmark.BenchmarkSetup.BenchmarkDataset;

import cern.colt.Arrays;
import de.linearbits.subframe.Benchmark;
import de.linearbits.subframe.analyzer.ValueBuffer;

/**
 * Benchmark of ARX's implementation of the game theoretic approach proposed in:

 * A Game Theoretic Framework for Analyzing Re-Identification Risk.

 * Zhiyu Wan, Yevgeniy Vorobeychik, Weiyi Xia, Ellen Wright Clayton,
 * Murat Kantarcioglu, Ranjit Ganta, Raymond Heatherly, Bradley A. Malin

 * PLOS|ONE. 2015.
 *
 * @author Fabian Prasser
 */
public abstract class BenchmarkExperiment7 extends BenchmarkExperiment {

    /** The benchmark instance */
    private static final Benchmark BENCHMARK           = new Benchmark(new String[] { "adversary gain = publisher loss" });
    /** MEASUREMENT PARAMETER */
    private static final int       PAYOUT_COST_BENEFIT = BENCHMARK.addMeasure("Cost/benefit");
    /** MEASUREMENT PARAMETER */
    private static final int       PAYOUT_SAFE_HARBOR  = BENCHMARK.addMeasure("HIPAA Safe Harbor");

    /**
     * Main
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        BenchmarkDataset dataset = BenchmarkDataset.ADULT_TN;
        BenchmarkDataset dataset_sh = BenchmarkDataset.ADULT_TN_SAFE_HARBOR;

        // Init
        BENCHMARK.addAnalyzer(PAYOUT_COST_BENEFIT, new ValueBuffer());
        BENCHMARK.addAnalyzer(PAYOUT_SAFE_HARBOR, new ValueBuffer());

        // Perform
        ARXCostBenefitConfiguration config = ARXCostBenefitConfiguration.create()
                                                                        .setAdversaryCost(BenchmarkSetup.getDefaultAdversaryCost())
                                                                        .setAdversaryGain(BenchmarkSetup.getDefaultAdversaryGain())
                                                                        .setPublisherLoss(BenchmarkSetup.getDefaultPublisherLoss())
                                                                        .setPublisherBenefit(BenchmarkSetup.getDefaultPublisherBenefit());

        double[] parameters = BenchmarkSetup.getParametersGainLoss();
        for (double parameter : parameters) {
            config.setAdversaryGain(parameter);
            config.setPublisherLoss(parameter);
            System.out.println(" - Adversary gain = publisher loss - " + parameter + " - " + Arrays.toString(parameters));
            BENCHMARK.addRun(config.getAdversaryGain());
            analyze(dataset, dataset_sh, config);
            BENCHMARK.getResults().write(new File("results/"+dataset.toString()+"-experiment7.csv"));
        }
    }

    /**
     * Run the benchmark
     * @param dataset
     * @param dataset_sh
     * @param config
     * @throws IOException
     */
    private static void analyze(BenchmarkDataset dataset, BenchmarkDataset dataset_sh, ARXCostBenefitConfiguration configuration) throws IOException {

        // Load data
        Data data = BenchmarkSetup.getData(dataset);
        Data data_sh = BenchmarkSetup.getData(dataset_sh);

        // Run benchmarks
        BENCHMARK.addValue(PAYOUT_COST_BENEFIT, getCostBenefitPayout(data, configuration));
        // Ugly hack
        BENCHMARK.addValue(PAYOUT_SAFE_HARBOR, getSafeHarborPayout(data_sh, configuration));
    }
}


text:
using MarkovChainLib;
using System;

namespace TestDriver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var testString = "The background generator is intended to remove the creative pressure that can sometimes frustrate players as they try to flesh out the murky details of their characters' backgrounds. This generator provides these details with either a simple roll of the die or the players deliberately selecting from options on the furnished tables and lists.";

            Console.WriteLine("Input String: {0}", testString);

            MarkovChain chain = new MarkovChain();

            chain.ParseText(testString, 3);

            Console.WriteLine(chain.GenerateChain(10));

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
}


text:
<?php

namespace Oro\Bundle\CalendarBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\CalendarBundle\Entity\CalendarConnection;

class CalendarConnectionRepository extends EntityRepository
{
    /**
     * Gets CalendarConnection object represents a connection between the given calendars
     *
     * @param $calendarId
     * @param $connectedCalendarId
     * @return CalendarConnection
     */
    public function findByRelation($calendarId, $connectedCalendarId)
    {
        return $this->findOneBy(array('calendar' => $calendarId, 'connectedCalendar' => $connectedCalendarId));
    }

    /**
     * Returns a query builder which can be used to get a list of connected calendars
     *
     * @param int $calendarId
     * @param int|null $userId
     * @return QueryBuilder
     */
    public function getConnectionListQueryBuilder($calendarId, $userId = null)
    {
        $qb = $this->createQueryBuilder('calendarConnection')
            ->select('calendarConnection, connectedCalendar, owner')
            ->innerJoin('calendarConnection.calendar', 'calendar')
            ->innerJoin('calendarConnection.connectedCalendar', 'connectedCalendar')
            ->innerJoin('connectedCalendar.owner', 'owner')
            ->where('calendar.id = :id')
            ->orderBy('calendarConnection.createdAt')
            ->setParameter('id', $calendarId);

        if (null !== $userId) {
            $qb->andWhere('owner.id = :userId')->setParameter('userId', $userId);
        }

        return $qb;
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getOperationAST = getOperationAST;

var _kinds = require("../language/kinds");

/**
 * Returns an operation AST given a document AST and optionally an operation
 * name. If a name is not provided, an operation is only returned if only one is
 * provided in the document.
 */
function getOperationAST(documentAST, operationName) {
  var operation = null;

  for (var i = 0; i < documentAST.definitions.length; i++) {
    var definition = documentAST.definitions[i];

    if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {
      if (!operationName) {
        // If no operation name was provided, only return an Operation if there
        // is one defined in the document. Upon encountering the second, return
        // null.
        if (operation) {
          return null;
        }

        operation = definition;
      } else if (definition.name && definition.name.value === operationName) {
        return definition;
      }
    }
  }

  return operation;
}


text:
goog.provide('modernPaste.universal.MenuController');

/**
 * This controller handles the left side-panel menu.
 *
 * @constructor
 */
modernPaste.universal.MenuController = function() {
    this.menuToggleButton = $('#header').find('.container .menu-button');
    this.menuPanel = $('#menu-panel');
    this.pageHeader = $('#header');
    this.pageFooter = $('#footer');
    this.mainPage = $('#main-page');
    this.userHeader = $('#header').find('.user-section .user-header');
    this.userHeaderDropdown = $('#user-header-dropdown');
    this.openSourceNote = this.menuPanel.find('.open-source-note');

    this.menuToggleButton.on('click', modernPaste.universal.MenuController.handleMenuToggleButtonClick.bind(this));
    $('html').on('click', modernPaste.universal.MenuController.handleWindowClick.bind(this));
    $(window).on('resize', modernPaste.universal.MenuController.toggleOpenSourceNoteVisibility.bind(this));
};

/**
 * Show or hide the menu panel's open source note depending on the available screen real estate.
 */
modernPaste.universal.MenuController.toggleOpenSourceNoteVisibility = function() {
    var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    height > 500 ? this.openSourceNote.show() : this.openSourceNote.hide();
};

/**
 * If the user clicks anywhere in the window, it should close the menu panel only if the menu panel is currently
 * expanded and the click lands outside the menu panel.
 */
modernPaste.universal.MenuController.handleWindowClick = function(evt) {
    if (modernPaste.universal.MenuController.isMenuPanelVisible.bind(this)() && this.menuPanel[0] !== $(evt.target)[0] && this.menuPanel.has($(evt.target)).length === 0) {
        // Panel is extended and visible, and the click location is outside of the menu
        modernPaste.universal.MenuController.hideMenuPanel.bind(this)();
    }
};

/**
 * Hide or show the menu panel when the user clicks on the menu button.
 */
modernPaste.universal.MenuController.handleMenuToggleButtonClick = function(evt) {
    evt.preventDefault();

    modernPaste.universal.MenuController.isMenuPanelVisible.bind(this)() ?
        modernPaste.universal.MenuController.hideMenuPanel.bind(this)() : modernPaste.universal.MenuController.showMenuPanel.bind(this)()
};

/**
 * Hide the menu panel.
 */
modernPaste.universal.MenuController.hideMenuPanel = function() {
    this.menuToggleButton.fadeOut(function() {
        $(this).attr('src', '/static/img/icons/menu.png');
        $(this).fadeIn();
    });
    this.menuPanel.css('margin-left', '-310px');
    this.pageHeader.css('margin-left', '0');
    this.mainPage.css('margin-left', '0');
    if (this.pageFooter.length > 0) {
        this.pageFooter.css('margin-left', '0');
    }
};

/**
 * Show the menu panel.
 */
modernPaste.universal.MenuController.showMenuPanel = function() {
    if (this.userHeaderDropdown.is(':visible')) {
        this.userHeader.click();
    }
    this.menuToggleButton.fadeOut(function() {
        $(this).attr('src', '/static/img/icons/cross.png');
        $(this).fadeIn();
    });
    this.menuPanel.css('margin-left', '0');
    this.pageHeader.css('margin-left', '310px');
    this.mainPage.css('margin-left', '310px');
    if (this.pageFooter.length > 0) {
        this.pageFooter.css('margin-left', '310px');
    }
};

/**
 * Determine if the menu panel is currently visible.
 *
 * @returns {boolean} true if the menu panel is extended and visible; false otherwise.
 */
modernPaste.universal.MenuController.isMenuPanelVisible = function() {
    return this.menuPanel.css('margin-left') === '0' || this.menuPanel.css('margin-left') === '0px';
};

$(document).ready(function() {
    new modernPaste.universal.MenuController();
});


text:
<resources>

  <!-- Base application theme. -->
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <!-- Main theme colors -->
    <!--   your app branding color for the app bar, also for button color-->
    <item name="android:colorPrimary">@color/primary</item>
    <!--   darker variant for the status bar and contextual app bars -->
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
    <!--   theme UI controls like checkboxes and text fields -->
    <item name="android:colorAccent">@color/accent</item>
    <item name="android:datePickerDialogTheme">@style/MyDialog</item>
    <item name="android:timePickerDialogTheme">@style/MyDialog</item>
    <!--progress bar theme-->
    <item name="android:progressBarStyle">@style/MyProgress</item>
    <!--switch button theme-->
    <item name="android:switchStyle">@style/MySwitch</item>
    <!--style editText-->
    <item name="android:editTextBackground">@color/primary_light</item>
    <item name="android:textColorHint">@color/divider</item>
    <item name="android:textCursorDrawable">@null</item>
  </style>

  <style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@color/accent</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">@color/primary_text</item>
    <!-- Used for the background -->
    <!--<item name="android:background">@color/primary_background</item>-->
  </style>

  <style name="MyProgress" parent="Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:background">@color/primary_light</item>
  </style>

  <style name="MySwitch" parent="Widget.AppCompat.CompoundButton.Switch"></style>

</resources>


text:
module RoleControl
  module Actor
    class DoChain
      attr_reader :scope, :action, :actor

      def initialize(actor, action)
        @actor = actor
        @action = action
      end

      def to(klass, context={}, add_active_scope: true)
        @scope = klass.scope_for(action, actor, context)
        if add_active_scope && klass.respond_to?(:active)
          @scope = @scope.merge(klass.active)
        end
        self
      end

      def with_ids(ids)
        @scope = scope.where(id: ids).order(:id) unless ids.blank?
        self
      end
    end

    def do(action, &block)
      DoChain.new(self, action, &block)
    end
  end
end


text:
#include "name.h"

#include <string.h>

#include "iterator.h"
#include "yajl.h"

/**
 * @brief Count number of levels in name of key
 *
 * @param cur the key to count levels
 *
 * @return number of levels in key name
 */
ssize_t elektraKeyCountLevel (const Key * cur)
{
	if (!cur)
	{
		return -1;
	}

	ssize_t curLevels = 0;
	keyNameReverseIterator curIt = elektraKeyNameGetReverseIterator (cur);
	while (elektraKeyNameReverseNext (&curIt))
	{
		++curLevels;
	}
	return curLevels;
}

/**
 * @brief Count how many levels are equal between cur and cmp
 * (starting from begin)
 *
 * @param cmp1 one key to compare
 * @param cmp2 the other key to compare
 *
 * @retval 0 on null pointers or nothing equal
 * @retval -1 when too many equal levels
 */
ssize_t elektraKeyCountEqualLevel (const Key * cmp1, const Key * cmp2)
{
	if (!cmp1)
	{
		return 0;
	}
	if (!cmp2)
	{
		return 0;
	}

	const char * pcmp1 = keyUnescapedName (cmp1);
	const char * pcmp2 = keyUnescapedName (cmp2);

	size_t size1 = keyGetUnescapedNameSize (cmp1);
	size_t size2 = keyGetUnescapedNameSize (cmp2);

	size_t counter = 0;
	const char * cur1 = pcmp1;
	const char * cur2 = pcmp2;
	while (strcmp (cur1, cur2) == 0)
	{
		const char * next1 = strchr (cur1, '\0');
		const char * next2 = strchr (cur2, '\0');

		++counter;

		cur1 = next1 + 1;
		cur2 = next2 + 1;

		if (pcmp1 + size1 <= cur1 || pcmp2 + size2 <= cur2)
		{
			break;
		}
	}

	return counter;
}


text:
{{var store.getFrontendName()}}

Het e-mailadres van Moneybooker : {{var email_addr}}

Het klant ID van Moneybooker: {{var customer_id}}

URL: {{var url}}

Taal: {{var language}}


text:
@class IDEBatchFindNamedScope;

@interface IDEFindNavigatorScopeNamedScopeOutlineItem : IDEFindNavigatorAbstractScopeOutlineItem
{
    IDEBatchFindNamedScope *_namedScope;
}

- (void).cxx_destruct;
@property(readonly) IDEBatchFindNamedScope *namedScope; // @synthesize namedScope=_namedScope;
- (id)filteredCloneWithChildren:(id)arg1 passedFilterLocally:(BOOL)arg2 descendantPassedFilter:(BOOL)arg3;
- (id)initWithNamedScope:(id)arg1 passedFilterLocally:(BOOL)arg2 descendantPassedFilter:(BOOL)arg3;

@end


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    tools:background="@android:color/black"
    android:layout_height="match_parent">

    <TextView
        tools:text="Tesco"
        android:layout_marginTop="@dimen/padding_small"
        android:textAppearance="@style/TextAppearance.AppCompat.Large.Inverse"
        android:layout_width="match_parent"
        android:gravity="center"
        android:maxLines="2"
        android:id="@+id/target_name"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_marginBottom="@dimen/padding_small"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium.Inverse"
        android:singleLine="true"
        android:layout_below="@id/target_name"
        android:id="@+id/distance"
        tools:text="500 meters away"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:layout_below="@id/distance"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ProgressBar
                android:layout_gravity="center"
                style="@style/Base.Widget.AppCompat.ProgressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_marginTop="@dimen/padding_small"
                android:layout_width="wrap_content"
                style="@style/TextAppearance.AppCompat.Inverse"
                android:text="@string/waiting_for_location"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <com.alexstyl.locationreminder.CompassView
            tools:visibility="visible"
            android:visibility="invisible"
            android:id="@+id/compass"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</RelativeLayout>


text:
package com.java.ui.componentc;

import com.java.ui.util.UIResourceManager;
import com.java.ui.util.UIUtil;

import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.plaf.basic.BasicTextUI;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CTextFieldUI extends BasicTextFieldUI {
    private static final Color DISABLED_BG = UIResourceManager.getColor("TextDisabledBackground");

    private static final Color NON_EDITABLE_BG = UIResourceManager.getColor("TextNonEditableBackground");

    public static ComponentUI createUI(JComponent c) {
        return new CTextFieldUI();
    }

    private Color getBackground(JCTextField field) {
        Color color = field.getBackground();

        if (!field.isEnabled()) {
            color = DISABLED_BG;
        } else if (!field.isEditable()) {
            color = NON_EDITABLE_BG;
        }

        return color;
    }

    protected void installDefaults() {
        try {
            Method updateCursorMethod = BasicTextUI.class.getDeclaredMethod("updateCursor", new Class[0]);
            updateCursorMethod.setAccessible(true);
            updateCursorMethod.invoke(this, new Object[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void paintBackground(Graphics g) {
        JTextComponent editor = getComponent();

        if ((editor instanceof JCTextField)) {
            JCTextField field = (JCTextField) editor;
            Color bg = getBackground(field);
            UIUtil.paintBackground(g, field, bg, bg, field.getImage(), field.isImageOnly(), field.getAlpha(), field.getVisibleInsets());
        } else {
            super.paintBackground(g);
        }
    }

    protected void paintSafely(Graphics g) {
        paintBackground(g);
        super.paintSafely(g);
    }

    protected void uninstallDefaults() {
        JTextComponent editor = getComponent();
        try {
            Field dragListenerField = BasicTextUI.class.getDeclaredField("dragListener");
            dragListenerField.setAccessible(true);
            MouseInputAdapter dragListener = (MouseInputAdapter) dragListenerField.get(this);
            editor.removeMouseListener(dragListener);
            editor.removeMouseMotionListener(dragListener);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ((editor.getCaret() instanceof UIResource)) {
            editor.setCaret(null);
        }

        if ((editor.getHighlighter() instanceof UIResource)) {
            editor.setHighlighter(null);
        }

        if ((editor.getTransferHandler() instanceof UIResource)) {
            editor.setTransferHandler(null);
        }

        if ((editor.getCursor() instanceof UIResource)) {
            editor.setCursor(null);
        }
    }
}


text:
package com.francetelecom.clara.cloud.presentation.designer.panels;

import com.francetelecom.clara.cloud.presentation.designer.pages.DesignerPage;
import com.francetelecom.clara.cloud.presentation.tools.BlockUIDecorator;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.panel.Panel;

/**
 * Created by IntelliJ IDEA.
 * User: Thomas Escalle - tawe8231
 * Entity : FT/OLNC/RD/MAPS/MEP/MSE
 * Date: 23/05/12
 */
public class DesignerSteppedButtonsPanel extends Panel {

    private int step;
    private DesignerPage parentPage;
    private boolean isArchitectureLocked;

    public DesignerSteppedButtonsPanel(String id, DesignerPage parentPage, boolean isArchitectureLocked) {
        super(id);
        setStep(0);
        this.parentPage = parentPage;
        this.isArchitectureLocked = isArchitectureLocked;
        initComponents();
    }

    @Override
    public boolean isVisible() {
        return !isArchitectureLocked;
    }

    private void initComponents() {
        initPreviousStepButton();
        initNextStepButton();
        setOutputMarkupId(true);
    }

    private void initPreviousStepButton() {

        AjaxLink previousButton = new AjaxLink("previousButton") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                step = parentPage.previousStepProcess();
                parentPage.managePageComponents(target, step, null);
            }

            @Override
            public boolean isVisible() {
                return step != 0;
            }
        };

        add(previousButton);

    }

    private void initNextStepButton() {

        AjaxLink nextButton = new AjaxLink("nextButton") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                step = parentPage.nextStepProcess();
                parentPage.managePageComponents(target, step, null);
            }

            @Override
            public boolean isVisible() {
                return step != 2;    //To change body of overridden methods use File | Settings | File Templates.
            }

            @Override
            protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
                if (step == 1) {
                    attributes.getAjaxCallListeners().add(new BlockUIDecorator(getString("portal.designer.architecture.validation")));
                }
            }

        };

        add(nextButton);

    }

    public void setStep(int step) {
        this.step = step;
    }

}


text:
require 'bundler/setup'
Bundler.setup

require 'grape-entity'
require 'grape-juice' # and any other gems you need

RSpec.configure do |config|
  # some (optional) config here
end


text:
class VrrpGroupDescriptor(object):
    def __init__(self, hello_interval=None, dead_interval=None, track_id=None, track_decrement=None,
                 priority_allocation_strategy=None):
        self.id = id
        self.hello_interval = hello_interval
        self.dead_interval = dead_interval
        self.track_id = track_id
        self.track_decrement = track_decrement
        self.priority_allocation_strategy = priority_allocation_strategy


text:
<form action="?page=postit" method="POST">
<input type="text" placeholder="pealkiri" name="title" value="<?php if (!empty($_POST['title'])) echo htmlspecialchars($_POST['title']);?>"/>

<textarea name="content" rows="10" cols="60"></textarea>

<input type="submit" value="postita"/>
</form>

<?php if(!empty($errors)):
	foreach($errors as $e):?>

<?php echo $e; ?>

<?php	endforeach;
endif;?>


text:
using System;

public class Puppy : Dog
{
    public void Weep()
    {
        Console.WriteLine("weeping...");
    }
}


text:
package io.anyway.galaxy.console.controller;

import io.anyway.galaxy.console.domain.BusinessTypeInfo;
import io.anyway.galaxy.console.service.BusinessTypeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by xiong.j on 2016/8/4.
 */

@Controller
@RequestMapping("businessType")
public class BusinessTypeController {

    @Autowired
    private BusinessTypeInfoService businessTypeInfoService;

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public int insertBusinessType(BusinessTypeInfo businessTypeInfo) {
        return businessTypeInfoService.update(businessTypeInfo);
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public int updateBusinessType(BusinessTypeInfo businessTypeInfo) {
        return businessTypeInfoService.update(businessTypeInfo);
    }

    @RequestMapping(value="{id}", method = RequestMethod.GET)
    @ResponseBody
    public BusinessTypeInfo getBusinessType(Model model, @PathVariable long id) {
        return businessTypeInfoService.get(id);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<BusinessTypeInfo> listBusinessType(BusinessTypeInfo businessTypeInfo) {
        return businessTypeInfoService.list(businessTypeInfo);
    }

    @RequestMapping(value="{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public BusinessTypeInfo delBusinessType(Model model, @PathVariable long id) {
        return businessTypeInfoService.get(id);
    }
}


text:
package es.bsc.compss.nio.listeners;

import es.bsc.comm.Connection;
import es.bsc.compss.data.MultiOperationFetchListener;
import es.bsc.compss.nio.NIOAgent;
import es.bsc.compss.nio.commands.CommandDataReceived;
import es.bsc.compss.nio.worker.NIOWorker;

public class FetchDataOperationListener extends MultiOperationFetchListener {

    private final int transferId;
    private final NIOWorker nw;

    /**
     * Creates a new Fetch Data operation listener.
     *
     * @param transferId Transfer data Id.
     * @param nw Associated NIO Worker.
     */
    public FetchDataOperationListener(int transferId, NIOWorker nw) {
        this.transferId = transferId;
        this.nw = nw;
    }

    @Override
    public void doCompleted() {
        CommandDataReceived cdr = new CommandDataReceived(this.transferId);
        Connection c = this.nw.startConnection();
        NIOAgent.registerOngoingCommand(c, cdr);
        c.sendCommand(cdr);
        c.finishConnection();
    }

    @Override
    public void doFailure(String failedDataId, Exception cause) {
        // Nothing to do
    }

}


text:
require 'valise/utils'
require 'file-sandbox'
require 'fileutils'

describe Valise::Unpath do
  let :module_host do
    Object.new.tap do |obj|
      obj.extend Valise::Unpath

      obj.instance_eval do
        class << self
          public :make_pathname
        end
      end
    end
  end

  describe "#make_pathname" do
    it '["", "etc", "configs"] => /etc/configs' do
      module_host.make_pathname(["", "etc", "configs"]).should == Pathname.new("/etc/configs")
    end
  end

  describe "#current_directory" do
    include FileSandbox

    before do
      sandbox.new :directory => "some/levels/deep"
      FileUtils.symlink("some/levels/deep", "shallow")
      Dir.chdir("shallow")
    end

    subject :path do
      Valise::Unpath.current_directory
    end

    it "should real working directory" do
      path.to_s.should =~ /deep$/
    end

    it "should return a Pathname" do
      path.should be_an_instance_of(Pathname)
    end
  end

  describe "#starting_directory" do
    it "should return a Pathname" do
      Valise::Unpath.start_dir.should be_an_instance_of(Pathname)
    end
  end

  describe Valise::Unpath::WorkspaceFinder do
    include FileSandbox
    before do
      sandbox.new :directory => "weird"
      sandbox.new :directory => "down/the/rabbit/hole"
      Dir.chdir "down/the/rabbit/hole"
    end

    subject :found do
      Valise::Unpath::containing_workspace do |finder|
        finder.search_from = "."
        finder.workspace_children = ["weird"]
        finder.description = "Weird test workspace"
      end
    end

    it "should find workspace" do
      found.to_s.should == @sandbox.root
    end

    it "should return a pathname" do
      found.should be_an_instance_of Pathname
    end
  end

  describe "#up_to" do
    it "should walk up paths" do
      Valise::Unpath.up_to("spec").to_s.should =~ /.*spec$/
    end

    it "should find a lib" do
      module_host.up_to("lib", "/a/b/c/lib/d/e/f").to_s.should == "/a/b/c/lib"
    end

    it "should raise if not available" do
      expect do
        module_host.up_to("surely/notpathsegment") #because / is the separator
      end.to raise_error(/not found/)
    end
  end

  describe "#from_here" do
    it "should manage relative paths" do
      module_host.from_here("../../thing", "/a/b/c/d/e").to_s.should == "/a/b/c/thing"
    end
  end

  describe "#file_from_backtrace" do
    it "should get filename properly" do
      module_host.file_from_backtrace(caller(0)[0]).should == __FILE__
    end
  end
end


text:
const fs = require('fs')
    , path = require('path')

const linkRe = /(?:\{([^\{]+)\})/g
    , termRe = /^:(.+):/
    , patternLineRe = /^\t([\.\*]+)$/
    , mainSectionDividerRe = /^(\-)+$/
    , periodRe = /\(p(\d+)\)/
    , emptyLineRe = /^\s*$/

const findSections = (dividerRe, keepDividerLine) => lines => {
  return lines
    .reduce((sections, line) => {
      if (dividerRe.test(line)) return sections.concat(newSection(line))
      last(sections).push(line)
      return sections
    }, [[ ]])
    .filter(nonEmptySection)

    function newSection(line) {
      return keepDividerLine ? [[ line ]] : [[ ]]
    }
}

const findMainSections = findSections(mainSectionDividerRe)
    , findContentSections = findSections(termRe, true)
    , findSimpleSections = findSections(emptyLineRe)

module.exports.parse = lines => {
  const [ introLines, termLines, biblioLines ] = findMainSections(lines)
      , terms = findTerms(termLines)

  return {
    terms: terms
  , patterns: terms.filter(isPattern)
  , introduction: findSimpleSections(introLines)
  , bibliography: findSimpleSections(biblioLines)
  }
}

function findTerms(lines) {
  return findContentSections(lines)
    .map(parseTerm)
    .filter(({ term }) => !!term )
}

function parseTerm(lines) {
  return lines.reduce((term, line) => {
    addTerm(term, line)
    addPeriod(term, line)
    addDescription(term, line)
    addLinks(term, line)
    addPatternLine(term, line)
    return term
  }, {})
}

function addTerm(term, line) {
  const matches = termRe.exec(line)
  if (!matches) return
  term.term = matches[1]
}

function addPeriod(term, line) {
  const matches = periodRe.exec(line)
  if (!matches) return
  term.period = parseInt(matches[1])
}

function addDescription(term, line) {
  const isEmptyLine = emptyLineRe.test(line)
      , isPatternLine = patternLineRe.test(line)
      , description = term.description || ''

  if (isEmptyLine || isPatternLine) return
  term.description = description + cleanDescriptionLine(line)
}

function cleanDescriptionLine(line) {
  return line
    .replace(/\{/g, '')
    .replace(/\}/g, '')
    .replace(periodRe, '')
    .replace(termRe, '')
    .replace(/  +/g, ' ')
    .replace(/^ /, '')
    .replace(/ $/, '')
    + ' '
}

function addLinks(term, line) {
  const links = findLinks(line)
  if (!links.length) return
  term.links = (term.links || []).concat(links)
}

function findLinks(line) {
  let matches
  const links = []
  while ((matches = linkRe.exec(line)) != null) links.push(matches[1])
  return links
}

function addPatternLine(term, line) {
  const matches = patternLineRe.exec(line)
  if (!matches) return
  term.pattern = (term.pattern || []).concat(toPatternLine(matches))
  term.width = term.pattern[0].length
  term.height = term.pattern.length
}

function toPatternLine(matches) {
  return [ matches[1].split('').map( toBinary ) ]
}

function toBinary(char) {
  return { '.': 0, '*': 1 }[char]
}

function last(array) {
  return array[array.length - 1]
}

function nonEmptySection(sectionLines) {
  return !!sectionLines.length
}

function isPattern(term) {
  return !!term.pattern
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>The One D Scorecard :: A Project of Data Driven Detroit</title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="assets/css/carousel.css" rel="stylesheet">

    <link href="assets/css/leaflet.css" rel="stylesheet">

    <link href="assets/css/crosslet.css" rel="stylesheet">

	<link href="css/style.css" type="text/css" rel="stylesheet" />

One D Scorecard Logo

Home

	  	                      Methodology

Priority Areas

One D Index

Geography

Data Download

	  	                      About

One D Scorecard

One Detroit Portal

Partners


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ZIPReader" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
	<brief_description>
		Allows reading the content of a zip file.
	</brief_description>
	<description>
		This class implements a reader that can extract the content of individual files inside a zip archive.
		[codeblock]
		func read_zip_file():
		    var reader := ZIPReader.new()
		    var err := reader.open("user://archive.zip")
		    if err == OK:
		        return PackedByteArray()
		    var res := reader.read_file("hello.txt")
		    reader.close()
		    return res
		[/codeblock]
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="close">
			<return type="int" enum="Error" />
			<description>
				Closes the underlying resources used by this instance.
			</description>
		</method>
		<method name="get_files">
			<return type="PackedStringArray" />
			<description>
				Returns the list of names of all files in the loaded archive.
				Must be called after [method open].
			</description>
		</method>
		<method name="open">
			<return type="int" enum="Error" />
			<param index="0" name="path" type="String" />
			<description>
				Opens the zip archive at the given [param path] and reads its file index.
			</description>
		</method>
		<method name="read_file">
			<return type="PackedByteArray" />
			<param index="0" name="path" type="String" />
			<param index="1" name="case_sensitive" type="bool" default="true" />
			<description>
				Loads the whole content of a file in the loaded zip archive into memory and returns it.
				Must be called after [method open].
			</description>
		</method>
	</methods>
</class>