text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using MensaPortable;
using System.Threading;
using System.Net.Http;

namespace MensaAppWin
{
    class MensaAdapter
    {

        public async static Task<bool> CatchMensaDataAsync()
        {
            AppLoadStoreMenuDB sl = new AppLoadStoreMenuDB();
#if DEBUG
            // Debugging? Reset the internal storage
            MenuDB.Instance.Reset(sl);
#endif
            // First, Load the Data from persistent storage
            MenuDB.Instance.LoadDB(sl);

            // Check the latest Day of the data
            if (!MenuDB.Instance.isOutdated())
                return true;

            // The data is Outdated! Try getting the new data
            try
            {
                // Reset the whole Database to prevent too much Data on the Device
                MenuDB.Instance.Reset(sl);

                Dictionary<string, string> dict = await getSourcesAsync(Mensen);
                var res =  MenuDB.Instance.ImportFromSources(dict);
                MenuDB.Instance.StoreDB(sl);
                return res;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// All known canteens and the corrsponding URL
        /// </summary>
        public static Dictionary<string, Uri> Mensen = new Dictionary<string, Uri>()
        {
			{ "Academica", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/academica-w.html")},
			{ "Ahornstrasse", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/ahornstrasse-w.html")},
			{ "Bistro", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/templergraben-w.html")},
			{ "Bayernallee", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/bayernallee-w.html")},
			{ "Eupener Straße", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/eupenerstrasse-w.html")},
			{ "Gastro Goethe", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/goethestrasse-w.html")},
			{ "Mensa Vita", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/vita-w.html")},
			/*{ "Forum Cafete", new Uri("http://www.studierendenwerk-aachen.de/speiseplaene/forum-w.html")},*/
        };

        /// <summary>
        /// Gets the next Mensa (sorted by the dictionary) of the provided one.
        ///     Checks for enabled canteens
        /// </summary>
        public static string getNextMensaName(string name)
        {
            // Idea: iterate thhrough the dict and get the first item, that is after the name-mensa
            bool flag = false;
            string newMensa = null;
            foreach (var mens in Mensen.Keys)
            {
                if (flag)
                {
                    // add config-cehck here
                    if (!App.MensaActive(mens))
                        continue;
                    newMensa = mens;
                    break;
                }
                if (mens == name)
                    flag = true;
            }

            if (newMensa != null)
                return newMensa;

            foreach (var mens in Mensen.Keys)
            {
                // add config-Check here
                if (App.MensaActive(mens))
                    return mens;
            }

            // every Mensa is deactivated...
            return name;
        }

        /// <summary>
        /// Gets the previous Mensa (sorted by the dictionary) of the provided one.
        ///     Checks for enabled canteens
        /// </summary>
        public static string getPreviousMensaName(string name)
        {
            // Idea: iterate thhrough the dict and get the first item, that is before the name-mensa
            string newMensa = null;
            foreach (var mens in Mensen.Keys)
            {
                if (mens == name)
                    break;

                // Add config-check here
                if (!App.MensaActive(mens))
                    continue;
                newMensa = mens;
            }

            if (newMensa != null)
                return newMensa;

            newMensa = name;

            foreach (var mens in Mensen.Keys)
            {
                // add config-Check here
                if (App.MensaActive(mens))
                    newMensa = mens;
            }

            // every Mensa is deactivated...
            return newMensa;
        }

        public static bool DownloadError = false;

        /// <summary>
        /// creates a dictionary of the web source text and the MensaName
        /// </summary>
        private async static Task<Dictionary<string, string>> getSourcesAsync(Dictionary<string, Uri> urls)
        {
            // Policy (input): urls.keys == MensaName, urls.Value == Uri of the plan
            // Policy (output): key==source, Value == MensaName
            DownloadError = false;
            int downloads = 0;
            Dictionary<string, string> dict = new Dictionary<string, string>();

            Mutex mutex = new Mutex();

            foreach (KeyValuePair<string, Uri> tuple in urls)
            {
                HttpClient client = new HttpClient();
                var answer = await client.GetAsync(tuple.Value);

                /*WebClient client = new WebClient();
				client.Encoding = Encoding.UTF8;
                //client.DownloadStringCompleted += client_DownloadStringCompleted;
                client.DownloadStringCompleted += ((object sender, DownloadStringCompletedEventArgs e) =>
                    {*/
                        try
                        {
                            // Error occured?
                            if (!answer.IsSuccessStatusCode)
                            {
                                DownloadError = true;
                            }
                            else
                            {
                        // No error -> Add to dict.
                                string result = await answer.Content.ReadAsStringAsync();
                                mutex.WaitOne();
                                dict.Add(result, tuple.Key);
                                mutex.ReleaseMutex();
                            }

                        }
                        catch (Exception)
                        {
                            // Error while getting data. Set flag!
                            DownloadError = true;
                        }
                        finally
                        {
                            // In every case, count this for a finished task
                            mutex.WaitOne();
                            downloads++;
                            mutex.ReleaseMutex();
                        }
                    /*});
                client.DownloadStringAsync(tuple.Value);*/
            }

            // Wait for the actions to complete
			while (downloads != urls.Count)
			{
				await Task.Delay (200);
				//Thread.Sleep(200);
			}

            string message = Localization.Localize("DownloadFail");

            if (DownloadError)
            {
                // Check for errors, inform user!
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    App.Current.MainPage.DisplayAlert("Error", message, "OK");
                });
            }

            return dict;

        }

    }

}


text:
import React, {Component, PropTypes} from 'react';

export default class ListProducts extends Component {
  static propTypes = {
    title: PropTypes.string.isRequired,
    children: PropTypes.node
  }

  render() {
    return (

{this.props.title}

{this.props.children}

    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
module Stripe
  # Configurable options:
  #
  # =ca_bundle_path=
  # The location of a file containing a bundle of CA certificates. By default
  # the library will use an included bundle that can successfully validate
  # Stripe certificates.
  #
  # =log_level=
  # When set prompts the library to log some extra information to $stdout and
  # $stderr about what it's doing. For example, it'll produce information about
  # requests, responses, and errors that are received. Valid log levels are
  # `debug` and `info`, with `debug` being a little more verbose in places.
  #
  # Use of this configuration is only useful when `.logger` is _not_ set. When
  # it is, the decision what levels to print is entirely deferred to the logger.
  #
  # =logger=
  # The logger should support the same interface as the `Logger` class that's
  # part of Ruby's standard library (hint, anything in `Rails.logger` will
  # likely be suitable).
  #
  # If `.logger` is set, the value of `.log_level` is ignored. The decision on
  # what levels to print is entirely deferred to the logger.
  class StripeConfiguration
    attr_accessor :api_key
    attr_accessor :api_version
    attr_accessor :client_id
    attr_accessor :enable_telemetry
    attr_accessor :logger
    attr_accessor :stripe_account

    attr_reader :api_base
    attr_reader :uploads_base
    attr_reader :connect_base
    attr_reader :ca_bundle_path
    attr_reader :log_level
    attr_reader :initial_network_retry_delay
    attr_reader :max_network_retries
    attr_reader :max_network_retry_delay
    attr_reader :open_timeout
    attr_reader :read_timeout
    attr_reader :write_timeout
    attr_reader :proxy
    attr_reader :verify_ssl_certs

    def self.setup
      new.tap do |instance|
        yield(instance) if block_given?
      end
    end

    # Create a new config based off an existing one. This is useful when the
    # caller wants to override the global configuration
    def reverse_duplicate_merge(hash)
      dup.tap do |instance|
        hash.each do |option, value|
          instance.public_send("#{option}=", value)
        end
      end
    end

    def initialize
      @ca_bundle_path = Stripe::DEFAULT_CA_BUNDLE_PATH
      @enable_telemetry = true
      @verify_ssl_certs = true

      @max_network_retries = 0
      @initial_network_retry_delay = 0.5
      @max_network_retry_delay = 2

      @open_timeout = 30
      @read_timeout = 80
      @write_timeout = 30

      @api_base = "https://api.stripe.com"
      @connect_base = "https://connect.stripe.com"
      @uploads_base = "https://files.stripe.com"
    end

    def log_level=(val)
      # Backwards compatibility for values that we briefly allowed
      if val == "debug"
        val = Stripe::LEVEL_DEBUG
      elsif val == "info"
        val = Stripe::LEVEL_INFO
      end

      levels = [Stripe::LEVEL_INFO, Stripe::LEVEL_DEBUG, Stripe::LEVEL_ERROR]

      if !val.nil? && !levels.include?(val)
        raise ArgumentError,
              "log_level should only be set to `nil`, `debug` or `info`"
      end
      @log_level = val
    end

    def max_network_retries=(val)
      @max_network_retries = val.to_i
    end

    def max_network_retry_delay=(val)
      @max_network_retry_delay = val.to_i
    end

    def initial_network_retry_delay=(val)
      @initial_network_retry_delay = val.to_i
    end

    def open_timeout=(open_timeout)
      @open_timeout = open_timeout
      StripeClient.clear_all_connection_managers(config: self)
    end

    def read_timeout=(read_timeout)
      @read_timeout = read_timeout
      StripeClient.clear_all_connection_managers(config: self)
    end

    def write_timeout=(write_timeout)
      unless Net::HTTP.instance_methods.include?(:write_timeout=)
        raise NotImplementedError
      end

      @write_timeout = write_timeout
      StripeClient.clear_all_connection_managers(config: self)
    end

    def proxy=(proxy)
      @proxy = proxy
      StripeClient.clear_all_connection_managers(config: self)
    end

    def verify_ssl_certs=(verify_ssl_certs)
      @verify_ssl_certs = verify_ssl_certs
      StripeClient.clear_all_connection_managers(config: self)
    end

    def uploads_base=(uploads_base)
      @uploads_base = uploads_base
      StripeClient.clear_all_connection_managers(config: self)
    end

    def connect_base=(connect_base)
      @connect_base = connect_base
      StripeClient.clear_all_connection_managers(config: self)
    end

    def api_base=(api_base)
      @api_base = api_base
      StripeClient.clear_all_connection_managers(config: self)
    end

    def ca_bundle_path=(path)
      @ca_bundle_path = path

      # empty this field so a new store is initialized
      @ca_store = nil

      StripeClient.clear_all_connection_managers(config: self)
    end

    # A certificate store initialized from the the bundle in #ca_bundle_path and
    # which is used to validate TLS on every request.
    #
    # This was added to the give the gem "pseudo thread safety" in that it seems
    # when initiating many parallel requests marshaling the certificate store is
    # the most likely point of failure (see issue #382). Any program attempting
    # to leverage this pseudo safety should make a call to this method (i.e.
    # `Stripe.ca_store`) in their initialization code because it marshals lazily
    # and is itself not thread safe.
    def ca_store
      @ca_store ||= begin
                      store = OpenSSL::X509::Store.new
                      store.add_file(ca_bundle_path)
                      store
                    end
    end

    def enable_telemetry?
      enable_telemetry
    end

    # Generates a deterministic key to identify configuration objects with
    # identical configuration values.
    def key
      instance_variables
        .collect { |variable| instance_variable_get(variable) }
        .join
    end
  end
end


text:
var password = require('../../../lib/password');
var assert = require('assert');
var should = require('should');
var sprintf = require('sprintf').sprintf;
describe('password module', function () {
  describe('when making salted hash with password only', function () {

    var saltedHash = password.makeSaltedHash('password');

    it("should have three parts split by '$'", function () {
      saltedHash.split('$').should.have.length(3);
    });

    it("should have no part is undefined", function () {
      var parts = saltedHash.split('$');
      parts[0].should.not.equal("undefined");
      parts[1].should.not.equal("undefined");
      parts[2].should.not.equal("undefined");
    });

    it("should have algorithm sha1", function () {
      var parts = saltedHash.split('$');
      parts[0].should.equal("sha1");
    });

    describe('when using matchesSaltedHash', function () {
      it("should match password to the saltedHash", function () {
        password.matchesSaltedHash('password',saltedHash).should.be.true;
      })
    });
  });

  describe('when making salted hash with password and salt', function () {
    var saltedHash = password.makeSaltedHash('password','123');

    it("should have correct salt", function () {
      saltedHash.split('$')[1].should.equal("123");
    });

    it("should have three parts split by '$'", function () {
      saltedHash.split('$').should.have.length(3);
    });

    it("should have no part undefined", function () {
      var parts = saltedHash.split('$');
      parts[0].should.not.equal("undefined");
      parts[1].should.not.equal("undefined");
      parts[2].should.not.equal("undefined");
    });

    it("should have algorithm sha1", function () {
      var parts = saltedHash.split('$');
      parts[0].should.equal("sha1");
    });

    it("should match password with matchesSaltedHash", function () {
      password.matchesSaltedHash('password',saltedHash).should.be.ok;
    });
  });

  describe('when making salted hash with password, salt and algorithm=md5', function () {
    var saltedHash =  password.makeSaltedHash('password','123','md5');
    var parts = saltedHash.split('$');

    it("should have three parts split by '$'", function () {
      saltedHash.split('$').should.have.length(3);
    });

    it("should use the alternate algorithm", function () {
      var defaultDigest = password.makeSaltedHash('password','123').split('$')[2]
      defaultDigest.should.not.equal(parts[2]);
    });

    it("should have no part undefined", function () {
      parts[0].should.not.equal("undefined");
      parts[1].should.not.equal("undefined");
      parts[2].should.not.equal("undefined");
    });

    it("should have algorithm md5", function () {
      var parts = saltedHash.split('$');
      parts[0].should.equal("md5");
    });

    it("should match password with matchesSaltedHash", function () {
      password.matchesSaltedHash('password',saltedHash).should.be.ok;
    });
  });

  describe('when using base64Encode,', function() {
    it('should be reversed with base64Decode', function () {
      var str = 'abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()`~-_=+[{]}\|;:\'"';
      str.should.equal(password.base64Decode(password.base64Encode(str)));
    })
  });

  describe('randomString is random', function () {
    it('should not equal another call to randomString',function () {
      password.randomString(1000).should.not.equal(password.randomString(1000));
    });
  });
});


text:
package n0deploy

import (
	"context"
	"fmt"
	"io"
	"os/exec"
	"strings"
)

func NewLocalParser() *Parser {
	return &Parser{
		NewCopyInstruction: NewLocalCopyInstruction,
		NewRunInstruction:  NewLocalRunInstruction,
	}
}

type LocalRunInstruction struct {
	command string
}

func NewLocalRunInstruction(line string) (Instruction, error) {
	return &LocalRunInstruction{
		command: strings.TrimPrefix(line, "RUN "),
	}, nil
}

func (i LocalRunInstruction) Do(ctx context.Context, out io.Writer) error {
	cmd := exec.CommandContext(ctx, "sh", "-c", i.command)
	cmd.Stdout = out
	cmd.Stderr = out

	if err := cmd.Run(); err != nil {
		return err
	}

	return nil
}

func (i LocalRunInstruction) String() string {
	return fmt.Sprintf("RUN %s", i.command)
}

type LocalCopyInstruction struct {
	src string
	dst string
}

func NewLocalCopyInstruction(src, dst string) (Instruction, error) {
	return &LocalCopyInstruction{
		src: src,
		dst: dst,
	}, nil
}

func (i LocalCopyInstruction) Do(ctx context.Context, out io.Writer) error {
	cmd := exec.CommandContext(ctx, "cp", i.src, i.dst)
	cmd.Stdout = out
	cmd.Stderr = out

	if err := cmd.Run(); err != nil {
		return err
	}

	return nil
}

func (i LocalCopyInstruction) String() string {
	return fmt.Sprintf("COPY %s %s", i.src, i.dst)
}


text:
flakeID
=======

flakeID is a small library to generate 64-bit IDs which could be roughly-sorted.

Inspired by following articles and libraries

* [Announcing Snowflake | Twitter Blogs](https://blog.twitter.com/2010/announcing-snowflake)
* [Sharding & IDs at Instagram - Instagram Engineering](http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram)
* [SawdustSoftware/simpleflake: Distributed ID generation in python for the lazy.](https://github.com/SawdustSoftware/simpleflake)

License
-------

flakeID is available under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).

### Build status
[![Build Status](https://travis-ci.org/artemdevel/flakeID.svg)](https://travis-ci.org/artemdevel/flakeID)


text:
package controllers.grs

import _root_.models._
import featureswitch.core.config.FeatureSwitching
import fixtures.VatRegistrationFixture
import models.api.{CharitableOrg, GovOrg, RegSociety, UkCompany}
import models.external.incorporatedentityid.{IncorpIdJourneyConfig, JourneyLabels, TranslationLabels}
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.FakeRequest
import services.mocks.{MockApplicantDetailsService, MockEntityService, MockVatRegistrationService, TimeServiceMock}
import testHelpers.{ControllerSpec, FutureAssertions}
import uk.gov.hmrc.http.InternalServerException

import scala.concurrent.Future

class IncorpIdControllerSpec extends ControllerSpec
  with VatRegistrationFixture
  with TimeServiceMock
  with FutureAssertions
  with MockApplicantDetailsService
  with MockVatRegistrationService
  with FeatureSwitching
  with MockEntityService {

  val testJourneyId = "testJourneyId"

  class Setup(cp: Option[CurrentProfile] = Some(currentProfile)) {
    val testController: IncorpIdController = new IncorpIdController(
      mockAuthClientConnector,
      mockSessionService,
      mockIncorpIdService,
      mockApplicantDetailsService,
      vatRegistrationServiceMock
    )

    mockAuthenticated()
    mockWithCurrentProfile(cp)
  }

  implicit val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest()

  val testJourneyConfig: IncorpIdJourneyConfig = IncorpIdJourneyConfig(
    continueUrl = appConfig.incorpIdCallbackUrl,
    deskProServiceId = "vrs",
    signOutUrl = appConfig.feedbackUrl,
    accessibilityUrl = appConfig.accessibilityStatementUrl,
    regime = appConfig.regime,
    businessVerificationCheck = true,
    labels = Some(JourneyLabels(
      en = TranslationLabels(
        optServiceName = Some("Register for VAT")
      ),
      cy = TranslationLabels(
        optServiceName = Some("Cofrestru ar gyfer TAW")
      )
    ))
  )

  "startJourney" should {
    List(UkCompany, RegSociety, CharitableOrg).foreach { partyType =>
      s"redirect to the journeyStartUrl for $partyType" in new Setup {
        lazy val testJourneyStartUrl = "/test"
        mockCreateJourney(testJourneyConfig, partyType)(Future.successful(testJourneyStartUrl))
        mockPartyType(Future.successful(partyType))

        lazy val res: Future[Result] = testController.startJourney(fakeRequest)

        status(res) mustBe SEE_OTHER
        redirectLocation(res) mustBe Some(testJourneyStartUrl)
      }
    }

    "return INTERNAL_SERVER_ERROR for invalid partyType" in new Setup {
      lazy val testJourneyStartUrl = "/test"
      mockCreateJourney(testJourneyConfig, GovOrg)(Future.successful(testJourneyStartUrl))
      mockPartyType(Future.successful(GovOrg))

      val ex = intercept[InternalServerException] {
        await(testController.startJourney(fakeRequest))
      }
      ex.getMessage mustBe "[IncorpIdController][startJourney] attempted to start journey with invalid partyType: GovOrg"
    }
  }

  "incorpIdCallback" when {
    "store the incorporation details and redirect to IndividualIdentification when the response is valid" in new Setup {
      mockGetDetails(testJourneyId)(Future.successful(testLimitedCompany))
      mockSaveApplicantDetails(testLimitedCompany)(completeApplicantDetails)
      mockIsTransactor(Future(true))

      val res = testController.incorpIdCallback(testJourneyId)(fakeRequest)

      status(res) mustBe SEE_OTHER
      redirectLocation(res) must contain(controllers.routes.TaskListController.show.url)
    }
  }

}


text:
/* global inject, describe, it, beforeEach, expect, module, spyOn*/

import angular from 'angular';
import Tester from 'tester';

import '../';

describe('avPollingService', () => {

  let avPollingService;
  let AV_POLLING;
  let asyncResponse;

  const tester = new Tester();

  const responseAsync = require('./response-async.json');
  const responseResolved = require('./response-resolved.json');

  beforeEach(angular.mock.module('availity'));

  tester.service();

  beforeEach(inject((_avPollingService_, _AvApiResource_, _AV_POLLING_) => {

    avPollingService = _avPollingService_;
    AV_POLLING = _AV_POLLING_;

    // Add a fake headers function that simulates real Angular function
    asyncResponse = angular.extend({}, responseAsync, {
      headers: Tester.headers({
        'location': '/api/v1/dummy/123456789'
      })
    });

  }));

  it('should calculate polling interval', () => {
    const config = {
      pollingInterval: 1000,
      pollingDecay: 1.2
    };

    const timeout = avPollingService.getPollingTimeout(config);
    expect(timeout).toBe(1200);
  });

  it('should override polling defaults', () => {

    const config = avPollingService.setDefaults({
      pollingInterval: 2,
      pollingDecay: 1,
      pollingMaxInterval: 4000
    });

    // ...ensure the overrides are honored...
    expect(config.pollingInterval).toBe(2);
    expect(config.pollingDecay).toBe(1);
    expect(config.pollingMaxInterval).toBe(4000);

    // ...and just for giggles
    expect(config.pollingRetryCount).toBe(0);
  });

  it('should ignore non-api request', () => {

    const spyAsyncResponse = spyOn(avPollingService, 'onAsyncReponse');

    tester.$httpBackend.expectGET('/ok').respond(200);

    tester.$http.get('/ok').then(response => {
      avPollingService.response(response);
      expect(spyAsyncResponse).not.toHaveBeenCalled();
    });
    tester.$httpBackend.flush();

  });

  it('isAsyncResponse() should respond TRUE for async response', () => {

    expect(avPollingService.isAsyncResponse(asyncResponse)).toBeTruthy();

    // try and blow up the function with bad values
    expect(avPollingService.isAsyncResponse({})).toBeFalsy();
    expect(avPollingService.isAsyncResponse(null)).toBeFalsy();
    expect(avPollingService.isAsyncResponse({data: null})).toBeFalsy();
    expect(avPollingService.isAsyncResponse('Hello World')).toBeFalsy();

  });

  it('asynchronous api response should return a promise and emit original response in the deferred object', () => {

    // Setup our callbacks
    spyOn(avPollingService, 'queueRequest');

    const promise = avPollingService.response(asyncResponse);
    promise.then(null, null, notification => {
      expect(notification).toEqual(asyncResponse);
    });
    tester.$timeout.flush();
    tester.$scope.$digest();

    expect(avPollingService.queueRequest).toHaveBeenCalled();

  });

  it('should convert async response to a request and put into queue', () => {

    spyOn(avPollingService, 'pushRequest').and.callThrough();
    const deferred = tester.$q.defer();

    avPollingService.queueRequest(deferred, asyncResponse);

    expect(avPollingService.pushRequest).toHaveBeenCalled();
    expect(avPollingService.pendingRequests.length).toBe(1);

    const request = avPollingService.pendingRequests[0];

    // ensure the queued request has the necessary attributes
    expect(request.id).toBeDefined();
    expect(request.config).toBeDefined();
    expect(request.config.headers).toBeDefined();
    expect(request.config.api).toBeTruthy();
    expect(request.deferred).toBeDefined();
    expect(request.timer).toBeDefined();

    // just for giggles test clearing all requests and the timers
    avPollingService.clearRequests();
    expect(avPollingService.pendingRequests.length).toBe(0);

  });

  it('should retry aysnc request until non-async response', () => {

    spyOn(avPollingService, 'retryRequest').and.callThrough();

    const promise = avPollingService.onAsyncReponse(asyncResponse);
    promise.then(successfulResponse => {
      expect(successfulResponse.data).toEqual(responseResolved);
      // at this point we retried the original request twice and simulated
      // two server responses...one of them being async response and the other
      // the real response so the call count should be 2
      expect(avPollingService.retryRequest.calls.count()).toBe(2);
    });

    tester.$httpBackend.expectGET('/api/v1/dummy/123456789').respond(202, asyncResponse, {'location': '/api/v1/dummy/123456789'});
    // flush will retry the original queued request
    // and backend will response with async response that the polling service should requeue
    // and retry
    tester.flush();
    tester.$scope.$digest();
    tester.$httpBackend.flush();

    // reset ajax expectation but this time return a good response that will resolve successfully
    tester.$httpBackend.expectGET('/api/v1/dummy/123456789').respond(200, responseResolved);
    // this will cause the request that is queued on a timer to fire the ajax request
    tester.flush();
    tester.$scope.$digest();
    tester.$httpBackend.flush();

  });

  it('should timeout after default number of attempts', () => {

    const promise = avPollingService.onAsyncReponse(asyncResponse);
    promise.then(null, errorResponse => {
      expect(errorResponse.config.pollingRetryCount).toBe(AV_POLLING.MAX_RETRY);
    });

    tester.$httpBackend.expectGET('/api/v1/dummy/123456789').respond(202, responseAsync, {'location': '/api/v1/dummy/123456789'});

    // flush will retry the original queued request
    // and backend will response with async response that the polling service should requeue
    // and retry
    tester.flush();
    tester.$scope.$digest();
    tester.$httpBackend.flush();

    const pendingRequest = avPollingService.pendingRequests[0];
    expect(pendingRequest.config.pollingRetryCount).toBe(1);

    pendingRequest.config.pollingRetryCount = AV_POLLING.MAX_RETRY;

    // reset ajax expectation but and return another async response to test the max retry
    // tester.$httpBackend.expectGET('/api/v1/dummy/123456789').respond(200, responseAsync);
    // this will cause the request that is queued on a timer to fire the ajax request
    tester.flush();
    tester.$scope.$digest();
    // tester.$httpBackend.flush();

  });

  it('should resolve successful asynchronous response', () => {

    spyOn(avPollingService, 'retryRequest').and.callThrough();

    tester.$httpBackend.expectGET('/api/v1/dummy/123456789').respond(200, responseResolved);

    const promise = avPollingService.onAsyncReponse(asyncResponse);
    promise.then(response => {
      expect(avPollingService.retryRequest).toHaveBeenCalled();
      expect(response.data).toEqual(responseResolved);
    });

    tester.flush();
    tester.$scope.$digest();
    tester.$httpBackend.flush();

    avPollingService.clearRequests();
  });

  it('should return relative url from API aysnc response href attribute', () => {

    let url = avPollingService.getUrl('https://aaa.api.availity.com/v1/dummy');
    expect(url).toBe('/api/v1/dummy');

    url = avPollingService.getUrl('/api/v1/dummy');
    expect(url).toBe('/api/v1/dummy');
  });

});


text:
/*
 * Scene - Intro
 */

define(function(require, exports) {
    var util = require('../util');

    var Framework = require('../model/framework');
    var Info = require('../model/info');

    var Intro = require('../proto/scene').sub({

        el: $('#intro'),

        title: 'INTRO',

        template: 'tpl-intro',

        getData: function(params, callback) {

            util.finish([

                Framework.fetch(params).bind(Framework),
                Info.fetch(params).bind(Info)

            ], function(framework, infos){

                callback(null, {
                    framework: framework,
                    infos: infos
                });

            });

        }
    });

    return Intro;
});


text:
using tin::network::websocket::events::NewServerConnection;

NewServerConnection::NewServerConnection(
    const unsigned int& serverConnectionID
):
serverConnectionID(serverConnectionID)
{}

void NewServerConnection::accept(tin::network::websocket::ManagerVisitor& visitor)
{
    visitor.visit(*this);
}


text:
namespace base {

class MessagePump;

namespace sequence_manager {
class SequenceManager;
class TaskQueue;
}  // namespace sequence_manager

// A simple single thread TaskExecutor intended for non-test usage. Tests should
// generally use TaskEnvironment or BrowserTaskEnvironment instead.
// TODO(alexclarke): Inherit from TaskExecutor to support base::Here().
class BASE_EXPORT SingleThreadTaskExecutor {
 public:
  // For MessagePumpType::CUSTOM use the constructor that takes a pump.
  explicit SingleThreadTaskExecutor(
      MessagePumpType type = MessagePumpType::DEFAULT);

  // Creates a SingleThreadTaskExecutor pumping from a custom |pump|.
  // The above constructor using MessagePumpType is generally preferred.
  explicit SingleThreadTaskExecutor(std::unique_ptr<MessagePump> pump);

  SingleThreadTaskExecutor(const SingleThreadTaskExecutor&) = delete;
  SingleThreadTaskExecutor& operator=(const SingleThreadTaskExecutor&) = delete;

  // Shuts down the SingleThreadTaskExecutor, after this no tasks can be
  // executed and the base::TaskExecutor APIs are non-functional but won't crash
  // if called.
  ~SingleThreadTaskExecutor();

  const scoped_refptr<SingleThreadTaskRunner>& task_runner() const;

  MessagePumpType type() const { return type_; }

  // Sets the number of application tasks executed every time the MessagePump
  // asks its delegate to DoWork(). Defaults to 1. Can be increased in some
  // scenarios where the native pump (i.e. not MessagePumpType::DEFAULT) has
  // high overhead and yielding to native isn't critical.
  void SetWorkBatchSize(int work_batch_size);

 private:
  explicit SingleThreadTaskExecutor(MessagePumpType type,
                                    std::unique_ptr<MessagePump> pump);

  std::unique_ptr<sequence_manager::SequenceManager> sequence_manager_;
  scoped_refptr<sequence_manager::TaskQueue> default_task_queue_;
  MessagePumpType type_;
  SimpleTaskExecutor simple_task_executor_;
};

}  // namespace base

#endif  // BASE_TASK_SINGLE_THREAD_TASK_EXECUTOR_H_


text:
<?php

/**
 * Swaggy Jenkins
 * PHP version 7.4
 *
 * @package OpenAPIServer
 * @author  OpenAPI Generator team
 * @link    https://github.com/openapitools/openapi-generator
 */

/**
 * Jenkins API clients generated from Swagger / Open API specification
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 * Generated by: https://github.com/openapitools/openapi-generator.git
 */

/**
 * NOTE: This class is auto generated by the openapi generator program.
 * https://github.com/openapitools/openapi-generator
 * Please update the test case below to test the model.
 */
namespace OpenAPIServer\Model;

use PHPUnit\Framework\TestCase;
use OpenAPIServer\Model\QueueItemImpl;

/**
 * QueueItemImplTest Class Doc Comment
 *
 * @package OpenAPIServer\Model
 * @author  OpenAPI Generator team
 * @link    https://github.com/openapitools/openapi-generator
 *
 * @coversDefaultClass \OpenAPIServer\Model\QueueItemImpl
 */
class QueueItemImplTest extends TestCase
{

    /**
     * Setup before running any test cases
     */
    public static function setUpBeforeClass(): void
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp(): void
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown(): void
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass(): void
    {
    }

    /**
     * Test "QueueItemImpl"
     */
    public function testQueueItemImpl()
    {
        $testQueueItemImpl = new QueueItemImpl();
        $namespacedClassname = QueueItemImpl::getModelsNamespace() . '\\QueueItemImpl';
        $this->assertSame('\\' . QueueItemImpl::class, $namespacedClassname);
        $this->assertTrue(
            class_exists($namespacedClassname),
            sprintf('Assertion failed that "%s" class exists', $namespacedClassname)
        );
        $this->markTestIncomplete(
            'Test of "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "class"
     */
    public function testPropertyClass()
    {
        $this->markTestIncomplete(
            'Test of "class" property in "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "expectedBuildNumber"
     */
    public function testPropertyExpectedBuildNumber()
    {
        $this->markTestIncomplete(
            'Test of "expectedBuildNumber" property in "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "id"
     */
    public function testPropertyId()
    {
        $this->markTestIncomplete(
            'Test of "id" property in "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "pipeline"
     */
    public function testPropertyPipeline()
    {
        $this->markTestIncomplete(
            'Test of "pipeline" property in "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "queuedTime"
     */
    public function testPropertyQueuedTime()
    {
        $this->markTestIncomplete(
            'Test of "queuedTime" property in "QueueItemImpl" model has not been implemented yet.'
        );
    }

    /**
     * Test getOpenApiSchema static method
     * @covers ::getOpenApiSchema
     */
    public function testGetOpenApiSchema()
    {
        $schemaArr = QueueItemImpl::getOpenApiSchema();
        $this->assertIsArray($schemaArr);
    }
}


text:
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CLIST_PQ_Time
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CLIST_PQ_Time

#include "type_iso.CANY.h"

namespace AIMXML
{

namespace iso
{

class CLIST_PQ_Time : public ::AIMXML::iso::CANY
{
public:
	AIMXML_EXPORT CLIST_PQ_Time(xercesc::DOMNode* const& init);
	AIMXML_EXPORT CLIST_PQ_Time(CLIST_PQ_Time const& init);
	void operator=(CLIST_PQ_Time const& other) { m_node = other.m_node; }
	static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_iso_altova_CLIST_PQ_Time); }
	MemberElement<iso::CPQ_Time, _altova_mi_iso_altova_CLIST_PQ_Time_altova_item> item;
	struct item { typedef Iterator<iso::CPQ_Time> iterator; };
	AIMXML_EXPORT void SetXsiType();
};

} // namespace iso

}	// namespace AIMXML

#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CLIST_PQ_Time


text:
%Source: https://sites.google.com/site/prologsite/prolog-problems
%query:my_length(g,f).
% 1.04 (*): Find the number of elements of a list.

% my_length(L,N) :- the list L contains N elements
%    (list,integer) (+,?)

% Note: length(?List, ?Int) is predefined

my_length([],0).
my_length([_|L],N) :- my_length(L,N1), N is N1 + 1.


text:
<?php

namespace Magento\Catalog\Test\Constraint;

use Magento\Catalog\Test\Page\Product\CatalogProductView;
use Magento\ConfigurableProduct\Test\Fixture\ConfigurableProduct;
use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\Constraint\AbstractAssertForm;
use Magento\Mtf\Fixture\FixtureInterface;

/**
 * Class AssertProductPage
 * Assert that displayed product data on product page(front-end) equals passed from fixture.
 */
class AssertProductPage extends AbstractAssertForm
{
    /**
     * Product view block on frontend page
     *
     * @var \Magento\ConfigurableProduct\Test\Block\Product\View
     */
    protected $productView;

    /**
     * Product fixture
     *
     * @var ConfigurableProduct
     */
    protected $product;

    /**
     * Assert that displayed product data on product page(front-end) equals passed from fixture:
     * 1. Product Name
     * 2. Price
     * 3. Special price
     * 4. SKU
     * 5. Description
     * 6. Short Description
     *
     * @param BrowserInterface $browser
     * @param CatalogProductView $catalogProductView
     * @param FixtureInterface $product
     * @return void
     */
    public function processAssert(
        BrowserInterface $browser,
        CatalogProductView $catalogProductView,
        FixtureInterface $product
    ) {
        $browser->open($_ENV['app_frontend_url'] . $product->getUrlKey() . '.html');

        $this->product = $product;
        $this->productView = $catalogProductView->getViewBlock();

        $errors = $this->verify();
        \PHPUnit_Framework_Assert::assertEmpty(
            $errors,
            "\nFound the following errors:\n" . implode(" \n", $errors)
        );
    }

    /**
     * Verify displayed product data on product page(front-end) equals passed from fixture
     *
     * @return array
     */
    protected function verify()
    {
        $errors = [];

        $errors[] = $this->verifyName();
        $errors[] = $this->verifyPrice();
        $errors[] = $this->verifySpecialPrice();
        $errors[] = $this->verifySku();
        $errors[] = $this->verifyDescription();
        $errors[] = $this->verifyShortDescription();

        return array_filter($errors);
    }

    /**
     * Verify displayed product name on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifyName()
    {
        $fixtureProductName = $this->product->getName();
        $formProductName = $this->productView->getProductName();

        if ($fixtureProductName == $formProductName) {
            return null;
        }
        return "Displayed product name on product page(front-end) not equals passed from fixture. "
        . "Actual: {$formProductName}, expected: {$fixtureProductName}.";
    }

    /**
     * Verify displayed product price on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifyPrice()
    {
        if ($this->product->hasData('price') == false) {
            return null;
        }

        $priceBlock = $this->productView->getPriceBlock();
        $formPrice = $priceBlock->isOldPriceVisible() ? $priceBlock->getOldPrice() : $priceBlock->getPrice();
        $fixturePrice = number_format($this->product->getPrice(), 2, '.', '');

        if ($fixturePrice != $formPrice) {
            return "Displayed product price on product page(front-end) not equals passed from fixture. "
                . "Actual: {$fixturePrice}, expected: {$formPrice}.";
        }
        return null;
    }

    /**
     * Verify displayed product special price on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifySpecialPrice()
    {
        if (!$this->product->hasData('special_price')) {
            return null;
        }
        $fixtureProductSpecialPrice = $this->product->getSpecialPrice();
        $fixtureProductSpecialPrice = number_format($fixtureProductSpecialPrice, 2);
        $formProductSpecialPrice = $this->productView->getPriceBlock()->getSpecialPrice();
        if ($fixtureProductSpecialPrice == $formProductSpecialPrice) {
            return null;
        }
        return "Displayed product special price on product page(front-end) not equals passed from fixture. "
            . "Actual: {$formProductSpecialPrice}, expected: {$fixtureProductSpecialPrice}.";
    }

    /**
     * Verify displayed product sku on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifySku()
    {
        $fixtureProductSku = $this->product->getSku();
        $formProductSku = $this->productView->getProductSku();

        if ($fixtureProductSku === null || $fixtureProductSku == $formProductSku) {
            return null;
        }
        return "Displayed product sku on product page(front-end) not equals passed from fixture. "
            . "Actual: {$formProductSku}, expected: {$fixtureProductSku}.";
    }

    /**
     * Verify displayed product description on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifyDescription()
    {
        $fixtureProductDescription = $this->product->getDescription();
        $formProductDescription = $this->productView->getProductDescription();

        if ($fixtureProductDescription == $formProductDescription) {
            return null;
        }
        return "Displayed product description on product page(front-end) not equals passed from fixture. "
            . "Actual: {$formProductDescription}, expected: {$fixtureProductDescription}.";
    }

    /**
     * Verify displayed product short description on product page(front-end) equals passed from fixture
     *
     * @return string|null
     */
    protected function verifyShortDescription()
    {
        $fixtureProductShortDescription = $this->product->getShortDescription();
        $formProductShortDescription = $this->productView->getProductShortDescription();

        if ($fixtureProductShortDescription == $formProductShortDescription) {
            return null;
        }
        return "Displayed product short description on product page(front-end) not equals passed from fixture. "
            . "Actual: {$formProductShortDescription}, expected: {$fixtureProductShortDescription}.";
    }

    /**
     * Returns a string representation of the object
     *
     * @return string
     */
    public function toString()
    {
        return 'Product on product view page is correct.';
    }
}


text:
package ca.antonious.habittracker.todayshabitlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import ca.antonious.habittracker.BaseFragment;
import ca.antonious.habittracker.Constants;
import ca.antonious.habittracker.R;
import ca.antonious.habittracker.habitdetails.HabitDetailsActivity;
import ca.antonious.habittracker.models.Habit;
import ca.antonious.habittracker.viewcells.EmptyViewCell;
import ca.antonious.habittracker.viewcells.HabitViewCell;
import ca.antonious.viewcelladapter.ViewCellAdapter;
import ca.antonious.viewcelladapter.construction.SectionBuilder;
import ca.antonious.viewcelladapter.sections.HomogeneousSection;

/**
 * Created by George on 2016-09-30.
 */

public class TodaysHabitsFragment extends BaseFragment implements ITodaysHabitsView {
    private RecyclerView habitRecyclerView;

    private HomogeneousSection<Habit, HabitViewCell> habitsSection;
    private TodaysHabitsController controller;

    public static TodaysHabitsFragment newInstance() {
        return new TodaysHabitsFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_todays_habits, container, false);

        bindViews(view);
        resolveDependencies();

        habitRecyclerView.setAdapter(getViewCellAdapter());
        habitRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return view;
    }

    private void bindViews(View view) {
        habitRecyclerView = (RecyclerView) view.findViewById(R.id.habit_recycler_view);
    }

    private void resolveDependencies() {
        controller = getHabitTrackerApplication().getTodaysHabitsController();
    }

    private ViewCellAdapter getViewCellAdapter() {
        habitsSection = new HomogeneousSection<>(Habit.class, HabitViewCell.class);

        return ViewCellAdapter.create()
            .section(
                SectionBuilder.wrap(habitsSection)
                    .showIfEmpty(new EmptyViewCell("Seems like you have no habits for today"))
                    .build()
            )
            .listener(new HabitViewCell.OnHabitClickedListener() {
                @Override
                public void onHabitClicked(Habit habit, int position) {
                    navigateToDetails(habit.getId());
                }
            })
            .listener(new HabitViewCell.OnCompleteClickedListener() {
                @Override
                public void onComplete(Habit habit, int position) {
                    controller.markHabitAsCompleted(habit.getId());
                }
            })
            .build();
    }

    private void navigateToDetails(String habitID) {
        Intent intent = new Intent(getActivity(), HabitDetailsActivity.class);
        intent.putExtra(Constants.EXTRA_HABIT_ID, habitID);

        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        controller.attachView(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        controller.detachView();
    }

    @Override
    public void displayTodaysHabits(List<Habit> habits) {
        habitsSection.setAll(habits);
    }
}


text:
var _curry2 = require('./internal/_curry2');

/**
 * See if an object (`val`) is an instance of the supplied constructor. This
 * function will check up the inheritance chain, if any.
 *
 * @func
 * @memberOf R
 * @since v0.3.0
 * @category Type
 * @sig (* -> {*}) -> a -> Boolean
 * @param {Object} ctor A constructor
 * @param {*} val The value to test
 * @return {Boolean}
 * @example
 *
 *      R.is(Object, {}); //=> true
 *      R.is(Number, 1); //=> true
 *      R.is(Object, 1); //=> false
 *      R.is(String, 's'); //=> true
 *      R.is(String, new String('')); //=> true
 *      R.is(Object, new String('')); //=> true
 *      R.is(Object, 's'); //=> false
 *      R.is(Number, {}); //=> false
 */
module.exports = _curry2(function is(Ctor, val) {
  return val != null && val.constructor === Ctor || val instanceof Ctor;
});


text:
@interface FlutterEngine () <FlutterViewEngineDelegate>

- (flutter::Shell&)shell;

- (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics;
- (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet;

- (fml::RefPtr<fml::TaskRunner>)platformTaskRunner;
- (fml::RefPtr<fml::TaskRunner>)RasterTaskRunner;

- (fml::WeakPtr<flutter::PlatformView>)platformView;

- (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type
                                 base64Encode:(bool)base64Encode;

- (FlutterPlatformPlugin*)platformPlugin;
- (flutter::FlutterPlatformViewsController*)platformViewsController;
- (FlutterTextInputPlugin*)textInputPlugin;
- (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil;
- (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil;
- (void)attachView;

@end

#endif  // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_


text:
#ifndef STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP
#define STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP

#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/promote_scalar_type.hpp>
#include <stan/math/prim/meta/ref_type.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <stdexcept>

namespace stan {
namespace math {
namespace internal {

template <typename T>
class broadcast_array {
 private:
  T& prim_;

 public:
  explicit broadcast_array(T& prim) : prim_(prim) {}

  T& operator[](int /*i*/) { return prim_; }

  /** \ingroup type_trait
   * Broadcast array can be assigned a scalar or a vector. If assigned a scalar,
   * it will be used directly. If assigned a vector, the argument will be summed
   * first.
   */
  template <typename Y>
  void operator=(const Y& m) {
    prim_ = sum(m);
  }
};

template <typename T, typename S, typename Enable = void>
class empty_broadcast_array {
 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& operator[](int /*i*/);

  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  template <typename Y>
  void operator=(const Y& /*A*/);
  template <typename Y>
  void add_write_event(Y&& /* event */);
};

template <typename ViewElt, typename T>
class empty_broadcast_array<ViewElt, T, require_eigen_t<T>> {
  enum { R = T::RowsAtCompileTime, C = T::ColsAtCompileTime };
  using T_arg = promote_scalar_t<ViewElt, T>;

 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator[](int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator()(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator=(const T_arg& /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator+=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator-=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& row(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& col(int /*i*/);
};
}  // namespace internal
}  // namespace math
}  // namespace stan
#endif


text:
import sys
import radtrack.rbcbt as rbcbt
from PyQt4 import QtGui
import radtrack.beamlines.RbOpticalElements as module

class RbLaserTransport(rbcbt.RbCbt):
    defaultTitle = 'Laser Transport'
    acceptsFileTypes = [module.fileExtension]
    task = 'Design a laser beam line'
    category = 'beam lines'

    def __init__(self, parent = None):
        super(RbLaserTransport, self).__init__(module, parent)

def main():
    app = QtGui.QApplication(sys.argv)
    myapp = RbLaserTransport()
    myapp.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
package sample.jsqlparser;

public class Main {
    public static void main(String[] args) throws Exception {

    }
}


text:
package org.kataetos.calendar;

import java.util.List;

import org.kataetos.calendar.theme.DisplayFormat;
import org.kataetos.event.EventType;

public interface ThemeBuilder {

  public ThemeBuilder withEventDisplayFormat(EventType type, DisplayFormat format);

  public ThemeBuilder withPrecedence(List<EventType> precedence);

  public ThemeBuilder withTitleDisplayFormat(DisplayFormat format);

  public Theme build();
}


text:
import './app.scss';

import angular from 'angular';

// Import base modules
import appConstants from 'appConstants';

// Components.
import PlayerComponent from './components/player/player.component';
import PlayerController from './components/player/player.controller';
import AudioControlsComponent from './components/audioControls/audioControls.component';
import AudioControlsController from './components/audioControls/audioControls.controller';
import TrackStatusComponent from './components/trackStatus/trackStatus.component';
import TrackStatusController from './components/trackStatus/trackStatus.controller';
import AlbumArtComponent from './components/albumArt/albumArt.component';
import AlbumArtController from './components/albumArt/albumArt.controller';

// Services.
import FreeMusicArchiveService from './services/FreeMusicArchive.service';
import PlayerService from './components/player/player.service';

export default angular.module('fundbox-test', [])
  .constant("AppConstants", appConstants)

  // Player component.
  .controller(PlayerController.UID, PlayerController)
  .component('player', PlayerComponent)

  // Audio controls component.
  .controller(AudioControlsController.UID, AudioControlsController)
  .component('audioControls', AudioControlsComponent)

  // Track status component.
  .controller(TrackStatusController.UID, TrackStatusController)
  .component('trackStatus', TrackStatusComponent)

  // Track status component.
  .controller(AlbumArtController.UID, AlbumArtController)
  .component('albumArt', AlbumArtComponent)

  .service('FreeMusicArchiveService', FreeMusicArchiveService)
  .service('PlayerService', PlayerService)

  .name;


text:
const emptyConfig = {
  pillows: {
    small: {},
    medium: {},
    big: {}
  },
  pictures: {
    example: ""
  }
}

export default (state = emptyConfig, action) => {
  switch (action.type) {
    case 'CONFIG_READY':
      return { ...state, ...action.config, status: 'READY' };
    default:
      return state;
  }
};