text:
#include "stdafx.h"
#include "terraingenerator.h"

namespace geom
{

void TerrainGenerator::setTerrainGenerationInfo(const TerrainGenerationInfo& info)
{
	m_info = info;
}

Data TerrainGenerator::generate()
{
	Data data;
	DataWriter writer(&data);

	m_terrainWidth = (m_info.heightmapWidth % 2 == 0) ? m_info.heightmapWidth : m_info.heightmapWidth - 1;
	m_terrainHeight = (m_info.heightmapHeight % 2 == 0) ? m_info.heightmapHeight : m_info.heightmapHeight - 1;
	if (m_terrainWidth < 2 || m_terrainHeight < 2)
	{
		writer.getLastErrorRef() = "Heightmap size must be more than 2x2";
		return data;
	}

	int verticesCount = m_terrainWidth * m_terrainHeight;

	writer.getMeshesRef().resize(1);
	writer.getMeshesRef()[0].offsetInIB = 0;
	writer.getMeshesRef()[0].indicesCount = (m_terrainWidth - 1)* (m_terrainHeight - 1) * 6;

	writer.getVerticesCountRef() = verticesCount;
	writer.getAdditionalUVsCountRef() = 0;
	writer.getBoundingBoxRef().vmin = vector3(-0.5f * m_info.size.x, -0.5f * m_info.size.z, -0.5f * m_info.size.y);
	writer.getBoundingBoxRef().vmax = vector3(0.5f * m_info.size.x, 0.5f * m_info.size.z, 0.5f * m_info.size.y);

	writer.getVertexBufferRef().resize(verticesCount * sizeof(Data::Vertex));

	for (int y = 0; y < m_terrainHeight; y++)
	{
		for (int x = 0; x < m_terrainWidth; x++)
		{
			int i = y * m_terrainWidth + x;
			Data::Vertex* vertex = reinterpret_cast<Data::Vertex*>(writer.getVertexBufferRef().data() + i * sizeof(Data::Vertex));
			vertex->position = getPoint(x, y);
			calculateTangentSpace(x, y, vertex->normal, vertex->tangent, vertex->binormal);
			vertex->texCoord0 = vector2(float(x) * m_info.uvSize.x / float(m_terrainWidth - 1), float(y) * m_info.uvSize.y / float(m_terrainHeight - 1));
		}
	}

	writer.getIndexBufferRef().resize(writer.getMeshesRef()[0].indicesCount);
	unsigned int currentIndex = 0;
	for (int y = 0; y < m_terrainHeight - 1; y++)
	{
		unsigned int offset = (unsigned int)y * (unsigned int)m_terrainWidth;
		for (int x = 0; x < m_terrainWidth - 1; x++)
		{
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)x;
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)(x + m_terrainWidth);
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)(x + m_terrainWidth + 1);
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)(x + m_terrainWidth + 1);
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)(x + 1);
			writer.getIndexBufferRef()[currentIndex++] = offset + (unsigned int)x;
		}
	}

	return data;
}

vector3 TerrainGenerator::getPoint(int x, int y)
{
	vector3 pnt;
	pnt.x = m_info.size.x * (float(x) / float(m_terrainWidth - 1) - 0.5f);
	pnt.z = m_info.size.y * (float(y) / float(m_terrainHeight - 1) - 0.5f);

	int index = y * m_info.heightmapWidth + x;
	int h = m_info.heightmap[index];
	pnt.y = m_info.size.z * (float(h) / 255.0f - 0.5f);

	return pnt;
}

void TerrainGenerator::calculateTangentSpace(int x, int y, vector3& normal, vector3& tangent, vector3& binormal)
{
	vector3 center = getPoint(x, y);

	if (x + 1 < m_terrainWidth)
	{
		if (y + 1 < m_terrainHeight)
		{
			vector3 a = getPoint(x, y + 1) - center;
			a.norm();
			tangent += a;
			vector3 b = getPoint(x + 1, y) - center;
			b.norm();
			normal += (a * b);
		}
		if (y - 1 >= 0)
		{
			vector3 a = getPoint(x + 1, y) - center;
			a.norm();
			vector3 b = getPoint(x, y - 1) - center;
			b.norm();
			tangent -= b;
			normal += (a * b);
		}
	}
	if (x - 1 >= 0)
	{
		if (y + 1 < m_terrainHeight)
		{
			vector3 a = getPoint(x - 1, y) - center;
			a.norm();
			vector3 b = getPoint(x, y + 1) - center;
			b.norm();
			tangent += b;
			normal += (a * b);
		}
		if (y - 1 >= 0)
		{
			vector3 a = getPoint(x, y - 1) - center;
			a.norm();
			tangent -= a;
			vector3 b = getPoint(x - 1, y) - center;
			b.norm();
			normal += (a * b);
		}
	}

	normal.norm();
	tangent.norm();

	binormal = normal * tangent;
}

}


text:
package vn.tiki.noadapter2;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import java.util.List;

/**
 * Created by Giang Nguyen on 12/15/16.
 */

class DiffUtilCallback extends DiffUtil.Callback {

  private final List<?> oldItems;
  private final List<?> newItems;
  private final DiffCallback diffCallback;

  DiffUtilCallback(List<?> oldItems, List<?> newItems, @NonNull DiffCallback diffCallback) {
    this.oldItems = oldItems;
    this.newItems = newItems;
    this.diffCallback = diffCallback;
  }

  @Override public int getOldListSize() {
    return oldItems == null ? 0 : oldItems.size();
  }

  @Override public int getNewListSize() {
    return newItems == null ? 0 : newItems.size();
  }

  @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
    final Object oldItem = getOldItem(oldItemPosition);
    final Object newItem = getNewItem(newItemPosition);
    if (oldItem == null) {
      return newItem == null;
    } else {
      return newItem != null && diffCallback.areItemsTheSame(oldItem, newItem);
    }
  }

  @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
    final Object oldItem = getOldItem(oldItemPosition);
    final Object newItem = getNewItem(newItemPosition);
    if (oldItem == null) {
      return newItem == null;
    } else {
      return newItem != null && diffCallback.areContentsTheSame(oldItem, newItem);
    }
  }

  @Nullable private Object getNewItem(int newItemPosition) {
    return newItemPosition >= newItems.size() ? null : newItems.get(newItemPosition);
  }

  @Nullable private Object getOldItem(int oldItemPosition) {
    return oldItemPosition >= oldItems.size() ? null : oldItems.get(oldItemPosition);
  }

  @Override public int hashCode() {
    return diffCallback.hashCode();
  }

  @Override public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    DiffUtilCallback that = (DiffUtilCallback) o;

    return diffCallback.equals(that.diffCallback);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bronto.API.Tests
{
    public abstract class BrontoBaseTestWithLogin : BrontoBaseTestClass
    {
        LoginSession _login = null;

        public LoginSession Login
        {
            get { return _login ?? (_login = Bronto.API.LoginSession.Create(ApiToken)); }
            set { _login = value; }
        }
    }
}


text:
package custattr

import "github.com/corestoreio/csfw/eav"

var (
	_ eav.AttributeBackendModeller = (*todoABB)(nil)
)

type (
	// example for your own struct
	todoABB struct {
		*eav.AttributeBackend
	}
)

// CustomerBackendBilling handles billing address @todo
// @see magento2/site/app/code/Magento/Customer/Model/Customer/Attribute/Backend/Billing.php
func CustomerBackendBilling() *todoABB {
	return &todoABB{
		AttributeBackend: eav.NewAttributeBackend(),
	}
}

// CustomerBackendShipping handles shipping address @todo
// @see magento2/site/app/code/Magento/Customer/Model/Customer/Attribute/Backend/Shipping.php
func CustomerBackendShipping() *eav.AttributeBackend {
	return eav.NewAttributeBackend()
}

// CustomerBackendDataBoolean converts 1 or 0 to bool @todo
// @see magento2/site/app/code/Magento/Customer/Model/Attribute/Backend/Data/Boolean.php
func CustomerBackendDataBoolean() *eav.AttributeBackend {
	return eav.NewAttributeBackend()
}

// CustomerBackendPassword handles customer passwords @todo
// @see magento2/site/app/code/Magento/Customer/Model/Customer/Attribute/Backend/Password.php
func CustomerBackendPassword() *eav.AttributeBackend {
	return eav.NewAttributeBackend()
}

// CustomerBackendStore handles store
// @see magento2/site/app/code/Magento/Customer/Model/Customer/Attribute/Backend/Store.php
func CustomerBackendStore() *eav.AttributeBackend {
	return eav.NewAttributeBackend()
}

// CustomerBackendWebsite handles website
// @see magento2/site/app/code/Magento/Customer/Model/Customer/Attribute/Backend/Website.php
func CustomerBackendWebsite() *eav.AttributeBackend {
	return eav.NewAttributeBackend()
}


text:
using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.CommonServiceLocator;
using CommonServiceLocator;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;
using SampleProject.Application.Configuration;
using SampleProject.Application.Configuration.Emails;
using SampleProject.Infrastructure.Caching;
using SampleProject.Infrastructure.Database;
using SampleProject.Infrastructure.Domain;
using SampleProject.Infrastructure.Emails;
using SampleProject.Infrastructure.Logging;
using SampleProject.Infrastructure.Processing;
using SampleProject.Infrastructure.Processing.InternalCommands;
using SampleProject.Infrastructure.Processing.Outbox;
using SampleProject.Infrastructure.Quartz;
using SampleProject.Infrastructure.SeedWork;
using Serilog;

namespace SampleProject.Infrastructure
{
    public class ApplicationStartup
    {
        public static IServiceProvider Initialize(
            IServiceCollection services,
            string connectionString,
            ICacheStore cacheStore,
            IEmailSender emailSender,
            EmailsSettings emailsSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor,
            bool runQuartz = true)
        {
            if (runQuartz)
            {
                StartQuartz(connectionString, emailsSettings, logger, executionContextAccessor);
            }

            services.AddSingleton(cacheStore);

            var serviceProvider = CreateAutofacServiceProvider(
                services,
                connectionString,
                emailSender,
                emailsSettings,
                logger,
                executionContextAccessor);

            return serviceProvider;
        }

        private static IServiceProvider CreateAutofacServiceProvider(
            IServiceCollection services,
            string connectionString,
            IEmailSender emailSender,
            EmailsSettings emailsSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor)
        {
            var container = new ContainerBuilder();

            container.Populate(services);

            container.RegisterModule(new LoggingModule(logger));
            container.RegisterModule(new DataAccessModule(connectionString));
            container.RegisterModule(new MediatorModule());
            container.RegisterModule(new DomainModule());

            if (emailSender != null)
            {
                container.RegisterModule(new EmailModule(emailSender, emailsSettings));
            }
            else
            {
                container.RegisterModule(new EmailModule(emailsSettings));
            }

            container.RegisterModule(new ProcessingModule());

            container.RegisterInstance(executionContextAccessor);

            var buildContainer = container.Build();

            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(buildContainer));

            var serviceProvider = new AutofacServiceProvider(buildContainer);

            CompositionRoot.SetContainer(buildContainer);

            return serviceProvider;
        }

        private static void StartQuartz(
            string connectionString,
            EmailsSettings emailsSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor)
        {
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult();

            var container = new ContainerBuilder();

            container.RegisterModule(new LoggingModule(logger));
            container.RegisterModule(new QuartzModule());
            container.RegisterModule(new MediatorModule());
            container.RegisterModule(new DataAccessModule(connectionString));
            container.RegisterModule(new EmailModule(emailsSettings));
            container.RegisterModule(new ProcessingModule());

            container.RegisterInstance(executionContextAccessor);
            container.Register(c =>
            {
                var dbContextOptionsBuilder = new DbContextOptionsBuilder<OrdersContext>();
                dbContextOptionsBuilder.UseSqlServer(connectionString);

                dbContextOptionsBuilder
                    .ReplaceService<IValueConverterSelector, StronglyTypedIdValueConverterSelector>();

                return new OrdersContext(dbContextOptionsBuilder.Options);
            }).AsSelf().InstancePerLifetimeScope();

            scheduler.JobFactory = new JobFactory(container.Build());

            scheduler.Start().GetAwaiter().GetResult();

            var processOutboxJob = JobBuilder.Create<ProcessOutboxJob>().Build();
            var trigger =
                TriggerBuilder
                    .Create()
                    .StartNow()
                    .WithCronSchedule("0/15 * * ? * *")
                    .Build();

            scheduler.ScheduleJob(processOutboxJob, trigger).GetAwaiter().GetResult();

            var processInternalCommandsJob = JobBuilder.Create<ProcessInternalCommandsJob>().Build();
            var triggerCommandsProcessing =
                TriggerBuilder
                    .Create()
                    .StartNow()
                    .WithCronSchedule("0/15 * * ? * *")
                    .Build();
            scheduler.ScheduleJob(processInternalCommandsJob, triggerCommandsProcessing).GetAwaiter().GetResult();
        }
    }
}


text:
package org.opentosca.toscana.api.model;

import java.io.IOException;
import java.util.List;

import org.opentosca.toscana.api.PlatformController;
import org.opentosca.toscana.api.TransformationController;
import org.opentosca.toscana.api.docs.HiddenResourceSupport;
import org.opentosca.toscana.core.plugin.lifecycle.LifecyclePhase;
import org.opentosca.toscana.core.transformation.TransformationState;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.hateoas.core.Relation;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@ApiModel
@Relation(collectionRelation = "transformation")
public class TransformationResponse extends HiddenResourceSupport {
    private final List<? extends LifecyclePhase> phases;
    private final TransformationState state;
    private final String platform;

    public TransformationResponse(
        @JsonProperty("phases") List<? extends LifecyclePhase> phases,
        @JsonProperty("state") TransformationState state,
        @JsonProperty("platform") String platform,
        String csarName
    ) {
        this.phases = phases;
        this.state = state;
        this.platform = platform;
        this.add(ControllerLinkBuilder.linkTo(methodOn(TransformationController.class)
            .getCSARTransformation(csarName, platform))
            .withSelfRel().expand(csarName));
        this.add(linkTo(methodOn(TransformationController.class)
            .getTransformationLogs(csarName, platform, 0L))
            .withRel("logs").expand(csarName));
        this.add(ControllerLinkBuilder.linkTo(methodOn(PlatformController.class)
            .getPlatform(platform)).withRel("platform"));
        this.add(linkTo(methodOn(TransformationController.class)
            .getInputs(csarName, platform))
            .withRel("inputs").expand(csarName));
        this.add(linkTo(methodOn(TransformationController.class)
            .deleteTransformation(csarName, platform))
            .withRel("delete").expand(csarName));
        try {
            this.add(linkTo(methodOn(TransformationController.class)
                .getTransformationArtifact(csarName, platform, null))
                .withRel("artifact").expand(csarName));
        } catch (IOException e) {
            //Never happens because the call above is a dummy call
        }
    }

    @ApiModelProperty(
        required = true,
        notes = "The phases of the transformation"
    )
    @JsonProperty("phases")
    public List<? extends LifecyclePhase> getPhases() {
        return phases;
    }

    @ApiModelProperty(
        required = true,
        //Sadly Java does not allow Dynamic calls here, therefore this has to be updated manually
        notes = "The Current State of the transformation. Has to be one of the following: " +
            "\"READY\", \"INPUT_REQUIRED\", \"TRANSFORMING\", \"DONE\" or \"ERROR\"",
        example = "READY"
    )
    @JsonProperty("state")
    public TransformationState getState() {
        return state;
    }

    @ApiModelProperty(
        required = true,
        notes = "The platform identifier for this transformation",
        example = "kubernetes"
    )
    @JsonProperty("platform")
    public String getPlatform() {
        return platform;
    }
}


text:
<?php
// define the autoload function.
function glu_class_autoloader($c) {
    include dirname(__FILE__). DIRECTORY_SEPARATOR . strtolower($c) . '.php';
}

// register the autoload function.
spl_autoload_register("glu_class_autoloader");

// EOF


text:
revenue_vehicles_table = QueryAssetClass.find_or_create_by(
  table_name: 'revenue_vehicles',
  transam_assets_join: "LEFT JOIN transit_assets as rvta ON rvta.id = transam_assets.transam_assetible_id and transam_assets.transam_assetible_type = 'TransitAsset' LEFT JOIN service_vehicles sv ON sv.id = rvta.transit_assetible_id AND rvta.transit_assetible_type = 'ServiceVehicle' LEFT JOIN revenue_vehicles on revenue_vehicles.id = sv.service_vehiclible_id and sv.service_vehiclible_type = 'RevenueVehicle'"
)

category_fields = {
  "Characteristics": [
    {
      name: 'standing_capacity',
      label: 'Standing Capacity',
      filter_type: 'numeric'
    }
  ],
  "Funding": [
    {
      name: 'fta_funding_type_id',
      label: 'Funding Type',
      filter_type: 'multi_select',
      association: {
        table_name: 'fta_funding_types',
        display_field_name: 'name'
      }
    },
    {
      name: 'fta_ownership_type_id',
      label: 'Ownership Type',
      filter_type: 'multi_select',
      pairs_with: 'other_fta_ownership_type',
      association: {
        table_name: 'fta_ownership_types',
        display_field_name: 'name'
      }
    },
    {
      name: 'other_fta_ownership_type',
      label: 'Ownership Type (Other)',
      filter_type: 'text',
      hidden: true
    }
  ],
  "Operations": [
    {
      name: 'dedicated',
      label: 'Dedicated Asset',
      filter_type: 'boolean'
    }
  ]
}

category_fields.each do |category_name, fields|
  qc = QueryCategory.find_or_create_by(name: category_name)
  fields.each do |field|
    if field[:association]
      qac = QueryAssociationClass.find_or_create_by(field[:association])
    end
    qf = QueryField.find_or_create_by(
      name: field[:name],
      label: field[:label],
      query_category: qc,
      query_association_class_id: qac.try(:id),
      filter_type: field[:filter_type],
      auto_show: field[:auto_show],
      hidden: field[:hidden],
      pairs_with: field[:pairs_with]
    )
    qf.query_asset_classes << revenue_vehicles_table
  end
end


text:
class AppFeatureCompletionMigration
  include ActiveModel::Validations

  attr_reader :app, :feature_gate, :version_before_type_cast

  validate :feature_gate_must_exist

  delegate :version, to: :app_feature_completion

  def initialize(params)
    @app = params[:app] || raise("Must provide app")
    @feature_gate = params[:feature_gate]
    app_feature_completion.version = @version_before_type_cast = params[:version]
  end

  def valid?
    if destroy?
      super
    else
      app_feature_completion.valid?
    end
  end

  def errors
    if destroy?
      super
    else
      app_feature_completion.errors
    end
  end

  def save
    if destroy?
      valid? && app_feature_completion.destroy.destroyed?
    else
      app_feature_completion.save
    end
  end

  def destroy?
    version_before_type_cast.blank?
  end

  private

  def app_feature_completion
    @app_feature_completion ||= app.feature_completions.find_or_initialize_by(feature_gate: feature_gate_model)
  end

  def feature_gate_model
    Split.find_by(name: feature_gate)
  end

  def feature_gate_must_exist
    errors.add(:feature_gate, "must exist") unless feature_gate_model
  end
end


text:
function carregaCicloAscaris() {
  // Criando um aliase de scene[0].item
  var item = scene[0].item;

  // Adicionando o aluno
  item.estTomateNormal = new Game.Item("estHngrSdv.png");
  item.estTomateNormal.setPosition(940, 590);
  item.estTomateNormal.setZorder(11);
  item.estTomateNormal.setBrightness(220);
  item.estTomateNormal.onMouseOver = function() {
    item.estTomateNormal.setBrightness(255);
    scene[0].setSubtitle("Ascaridíase");
    item.popupFlores.disable();
    item.popupFloresTexto.disable();
  }
  item.estTomateNormal.onMouseOut = function() {
    item.estTomateNormal.setBrightness(220);
    scene[0].setSubtitle("");
  }
  item.estTomateNormal.onClick = function() {
    somClique();
    item.popupLivro.disable();
    item.popupLivroTexto.disable();

    var currentTime = 0;
    var animationInterval = 500; // Intervalo entre cada animacao

    item.popupFlores.disable();
    item.popupFloresTexto.disable();

    // Fadeout unrelated images
    scene[0].background.changeBrightness(100, 600);
    item.carteiras.changeBrightness(100, 600);
    item.mesaProfessor.changeBrightness(100, 600);
    item.caixaDeAreia.changeBrightness(100, 600);
    item.vasoDeFlores.changeBrightness(100, 600);
    item.livro.changeBrightness(100, 600);
    item.microscopio.changeBrightness(100, 600);

    item.estBananaNormal.changeBrightness(100, 600);
    item.estPernNormal.changeBrightness(100, 600);
    item.estGatoNormal.changeBrightness(100, 600);
    item.setaJanela.changeAlpha(0, 600);
    item.setaArmario.changeAlpha(0, 600);

    item.estBananaNormal.setInteractive(false);
    item.estPernNormal.setInteractive(false);
    item.estGatoNormal.setInteractive(false);
    item.estTomateNormal.setInteractive(false);
    item.setaJanela.setInteractive(false);
    item.setaArmario.setInteractive(false);
    item.caixaDeAreia.setInteractive(false);
    item.vasoDeFlores.setInteractive(false);
    item.livro.setInteractive(false);
    item.microscopio.setInteractive(false);
    item.bananaRegion.setInteractive(false);

    setTimeout(function() {
      scene[0].setSubtitle("");
      item.setaJanela.disable();
      item.setaArmario.disable();
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.estTomateNormal.changeAlpha(0, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.estTomateNormal.disable();
      item.estTomateCiclo.enable();
      item.estTomateCiclo.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateElem1.enable();
      item.tomateElem1.changeAlpha(1, 600);
      item.tomateNum1.enable();
      item.tomateNum1.changeAlpha(1, 600);
      item.tomateSetaElem1Est.enable();
      item.tomateSetaElem1Est.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateElem2.enable();
      item.tomateElem2.changeAlpha(1, 600);
      item.tomateNum2.enable();
      item.tomateNum2.changeAlpha(1, 600);
      item.tomateSetaElem2Est.enable();
      item.tomateSetaElem2Est.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateSetaEstElem3a.enable();
      item.tomateSetaEstElem3a.changeAlpha(1, 600);
      item.tomateElem3a.enable();
      item.tomateElem3a.changeAlpha(1, 600);
      item.tomateNum3.enable();
      item.tomateNum3.changeAlpha(1, 600);
      item.tomateSetaElem3aElem3b.enable();
      item.tomateSetaElem3aElem3b.changeAlpha(1, 600);
      item.tomateSetaElem3aElem3c.enable();
      item.tomateSetaElem3aElem3c.changeAlpha(1, 600);
      item.tomateSetaElem3aElem3d.enable();
      item.tomateSetaElem3aElem3d.changeAlpha(1, 600);
      item.tomateElem3b.enable();
      item.tomateElem3b.changeAlpha(1, 600);
      item.tomateElem3c.enable();
      item.tomateElem3c.changeAlpha(1, 600);
      item.tomateElem3d.enable();
      item.tomateElem3d.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateSetaElem4Est.enable();
      item.tomateSetaElem4Est.changeAlpha(1, 600);
      item.tomateNum4.enable();
      item.tomateNum4.changeAlpha(1, 600);
      item.tomateElem4.enable();
      item.tomateElem4.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateSetaEstElem5.enable();
      item.tomateSetaEstElem5.changeAlpha(1, 600);
      item.tomateNum5.enable();
      item.tomateNum5.changeAlpha(1, 600);
      item.tomateElem5.enable();
      item.tomateElem5.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateSetaElem5Elem6.enable();
      item.tomateSetaElem5Elem6.changeAlpha(1, 600);
      item.tomateElem6.enable();
      item.tomateElem6.changeAlpha(1, 600);
      item.tomateNum6.enable();
      item.tomateNum6.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.tomateFechar.enable();
      item.tomateFechar.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      enableInteractiveness();
    }, currentTime += animationInterval);
  }

  var itensTomateCiclo = [];

  // Imagens ciclo
  item.estTomateCiclo = new Game.Image("estHngrClo.png");
  item.estTomateCiclo.setPosition(900, 550);
  item.estTomateCiclo.setScale(0.5);
  item.estTomateCiclo.setZorder(9);
  item.estTomateCiclo.setAlpha(0);
  item.estTomateCiclo.disable();
  itensTomateCiclo.push(item.estTomateCiclo);

  item.tomateElem1 = new Game.Item("ovoAscaris.png");
  item.tomateElem1.setPosition(450, 250);
  item.tomateElem1.setScale(0.58);
  item.tomateElem1.setZorder(6);
  item.tomateElem1.setAlpha(0);
  item.tomateElem1.disable();
  item.tomateElem1.onMouseOver = function() {
    scene[0].setSubtitle("Ovo de Ascaris lumbricoides");
  }
  item.tomateElem1.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem1);

  item.tomateNum1 = new Game.Text("1", estiloNumeros);
  item.tomateNum1.setAnchor(0.5, 0.6);
  item.tomateNum1.setPosition(620, 120);
  item.tomateNum1.setAlpha(0);
  item.tomateNum1.disable();
  itensTomateCiclo.push(item.tomateNum1);

  item.tomateSetaElem1Est = new Game.Line(450, 250, 830, 440, 4);
  item.tomateSetaElem1Est.setColor(0, 0, 0);
  item.tomateSetaElem1Est.setZorder(7);
  item.tomateSetaElem1Est.setAlpha(0);
  item.tomateSetaElem1Est.disable();
  itensTomateCiclo.push(item.tomateSetaElem1Est);

  item.tomateElem2 = new Game.Item("ascarisFilhote.png");
  item.tomateElem2.setPosition(380, 550);
  item.tomateElem2.setScale(0.47);
  item.tomateElem2.setZorder(6);
  item.tomateElem2.setAlpha(0);
  item.tomateElem2.disable();
  item.tomateElem2.onMouseOver = function() {
    scene[0].setSubtitle("Verme jovem de Ascaris lumbricoides");
  }
  item.tomateElem2.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem2);

  item.tomateNum2 = new Game.Text("2", estiloNumeros);
  item.tomateNum2.setAnchor(0.5, 0.6);
  item.tomateNum2.setPosition(290, 420);
  item.tomateNum2.setAlpha(0);
  item.tomateNum2.disable();
  itensTomateCiclo.push(item.tomateNum2);

  item.tomateSetaElem2Est = new Game.Line(380, 550, 897, 721, 4);
  item.tomateSetaElem2Est.setColor(0, 0, 0);
  item.tomateSetaElem2Est.setZorder(7);
  item.tomateSetaElem2Est.setAlpha(0);
  item.tomateSetaElem2Est.disable();
  itensTomateCiclo.push(item.tomateSetaElem2Est);

  item.tomateSetaEstElem3a = new Game.Line(900, 600, 1300, 300, 4);
  item.tomateSetaEstElem3a.setColor(0, 0, 0);
  item.tomateSetaEstElem3a.setZorder(7);
  item.tomateSetaEstElem3a.setAlpha(0);
  item.tomateSetaEstElem3a.disable();
  itensTomateCiclo.push(item.tomateSetaEstElem3a);

  item.tomateElem3a = new Game.Item("circulacao.png");
  item.tomateElem3a.setPosition(1300, 300);
  item.tomateElem3a.setScale(0.57);
  item.tomateElem3a.setZorder(6);
  item.tomateElem3a.setAlpha(0);
  item.tomateElem3a.disable();
  item.tomateElem3a.onMouseOver = function() {
    scene[0].setSubtitle("Migração do verme para a circulação sanguínea");
  }
  item.tomateElem3a.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem3a);

  item.tomateNum3 = new Game.Text("3", estiloNumeros);
  item.tomateNum3.setAnchor(0.5, 0.6);
  item.tomateNum3.setPosition(1430, 180);
  item.tomateNum3.setAlpha(0);
  item.tomateNum3.disable();
  itensTomateCiclo.push(item.tomateNum3);

  item.tomateSetaElem3aElem3b = new Game.Line(1300, 300, 1520, 200, 4);
  item.tomateSetaElem3aElem3b.setColor(0, 0, 0);
  item.tomateSetaElem3aElem3b.addArrowAtEnd();
  item.tomateSetaElem3aElem3b.setZorder(7);
  item.tomateSetaElem3aElem3b.setAlpha(0);
  item.tomateSetaElem3aElem3b.disable();
  itensTomateCiclo.push(item.tomateSetaElem3aElem3b);

  item.tomateSetaElem3aElem3c = new Game.Line(1300, 300, 1570, 360, 4);
  item.tomateSetaElem3aElem3c.setColor(0, 0, 0);
  item.tomateSetaElem3aElem3c.addArrowAtEnd();
  item.tomateSetaElem3aElem3c.setZorder(7);
  item.tomateSetaElem3aElem3c.setAlpha(0);
  item.tomateSetaElem3aElem3c.disable();
  itensTomateCiclo.push(item.tomateSetaElem3aElem3c);

  item.tomateSetaElem3aElem3d = new Game.Line(1300, 300, 1470, 450, 4);
  item.tomateSetaElem3aElem3d.setColor(0, 0, 0);
  item.tomateSetaElem3aElem3d.addArrowAtEnd();
  item.tomateSetaElem3aElem3d.setZorder(7);
  item.tomateSetaElem3aElem3d.setAlpha(0);
  item.tomateSetaElem3aElem3d.disable();
  itensTomateCiclo.push(item.tomateSetaElem3aElem3d);

  item.tomateElem3b = new Game.Item("coracao.png");
  item.tomateElem3b.setPosition(1630, 170);
  item.tomateElem3b.setScale(0.35);
  item.tomateElem3b.setZorder(6);
  item.tomateElem3b.setAlpha(0);
  item.tomateElem3b.disable();
  item.tomateElem3b.onMouseOver = function() {
    scene[0].setSubtitle("Migração para o coração");
  }
  item.tomateElem3b.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem3b);

  item.tomateElem3c = new Game.Item("figado.png");
  item.tomateElem3c.setPosition(1670, 370);
  item.tomateElem3c.setScale(0.32);
  item.tomateElem3c.setZorder(6);
  item.tomateElem3c.setAlpha(0);
  item.tomateElem3c.disable();
  item.tomateElem3c.onMouseOver = function() {
    scene[0].setSubtitle("Migração para o fígado");
  }
  item.tomateElem3c.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem3c);

  item.tomateElem3d = new Game.Item("pulmao.png");
  item.tomateElem3d.setPosition(1550, 530);
  item.tomateElem3d.setScale(0.35);
  item.tomateElem3d.setZorder(6);
  item.tomateElem3d.setAlpha(0);
  item.tomateElem3d.disable();
  item.tomateElem3d.onMouseOver = function() {
    scene[0].setSubtitle("Migração para o pulmão");
  }
  item.tomateElem3d.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem3d);

  item.tomateSetaElem4Est = new Game.Line(420, 850, 886, 751, 4);
  item.tomateSetaElem4Est.setColor(0, 0, 0);
  item.tomateSetaElem4Est.setZorder(7);
  item.tomateSetaElem4Est.setAlpha(0);
  item.tomateSetaElem4Est.disable();
  itensTomateCiclo.push(item.tomateSetaElem4Est);

  item.tomateNum4 = new Game.Text("4", estiloNumeros);
  item.tomateNum4.setAnchor(0.5, 0.6);
  item.tomateNum4.setPosition(540, 720);
  item.tomateNum4.setAlpha(0);
  item.tomateNum4.disable();
  itensTomateCiclo.push(item.tomateNum4);

  item.tomateElem4 = new Game.Item("ascarisMF.png");
  item.tomateElem4.setPosition(420, 850);
  item.tomateElem4.setScale(0.51);
  item.tomateElem4.setZorder(6);
  item.tomateElem4.setAlpha(0);
  item.tomateElem4.disable();
  item.tomateElem4.onMouseOver = function() {
    scene[0].setSubtitle("Macho e fêmea de vermes adultos de A. lumbricoides");
  }
  item.tomateElem4.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem4);

  item.tomateSetaEstElem5 = new Game.Line(870, 815, 1165, 790, 4);
  item.tomateSetaEstElem5.setColor(0, 0, 0);
  item.tomateSetaEstElem5.addArrowAtEnd();
  item.tomateSetaEstElem5.setZorder(7);
  item.tomateSetaEstElem5.setAlpha(0);
  item.tomateSetaEstElem5.disable();
  itensTomateCiclo.push(item.tomateSetaEstElem5);

  item.tomateNum5 = new Game.Text("5", estiloNumeros);
  item.tomateNum5.setAnchor(0.5, 0.6);
  item.tomateNum5.setPosition(1400, 680);
  item.tomateNum5.setAlpha(0);
  item.tomateNum5.disable();
  itensTomateCiclo.push(item.tomateNum5);

  item.tomateElem5 = new Game.Item("fezesSemMosca.png");
  item.tomateElem5.setPosition(1300, 800);
  item.tomateElem5.setScale(0.44);
  item.tomateElem5.setZorder(6);
  item.tomateElem5.setAlpha(0);
  item.tomateElem5.disable();
  item.tomateElem5.onMouseOver = function() {
    scene[0].setSubtitle("Fezes contendo ovos de A. lumbricoides");
  }
  item.tomateElem5.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem5);

  item.tomateSetaElem5Elem6 = new Game.Line(1300, 800, 1700, 800, 4);
  item.tomateSetaElem5Elem6.setColor(0, 0, 0);
  item.tomateSetaElem5Elem6.setZorder(7);
  item.tomateSetaElem5Elem6.setAlpha(0);
  item.tomateSetaElem5Elem6.disable();
  itensTomateCiclo.push(item.tomateSetaElem5Elem6);

  item.tomateElem6 = new Game.Item("ovoAscaris.png");
  item.tomateElem6.setPosition(1700, 800);
  item.tomateElem6.setScale(0.5);
  item.tomateElem6.setZorder(6);
  item.tomateElem6.setAlpha(0);
  item.tomateElem6.disable();
  item.tomateElem6.onMouseOver = function() {
    scene[0].setSubtitle("Ovo de A. lumbricoides");
  }
  item.tomateElem6.onMouseOut = function() {
    scene[0].setSubtitle("");
  }
  itensTomateCiclo.push(item.tomateElem6);

  item.tomateNum6 = new Game.Text("6", estiloNumeros);
  item.tomateNum6.setAnchor(0.5, 0.6);
  item.tomateNum6.setPosition(1820, 680);
  item.tomateNum6.setAlpha(0);
  item.tomateNum6.disable();
  itensTomateCiclo.push(item.tomateNum6);

  item.tomateFechar = new Game.Item("botaoFechar.png");
  item.tomateFechar.setPosition(1840, 70);
  item.tomateFechar.setRotation(180);
  item.tomateFechar.setBrightness(200);
  item.tomateFechar.setScale(0.14);
  item.tomateFechar.setZorder(1);
  item.tomateFechar.setAlpha(0);
  item.tomateFechar.disable();
  item.tomateFechar.onMouseOver = function() {
    item.tomateFechar.setBrightness(255);
  }
  item.tomateFechar.onMouseOut = function() {
    item.tomateFechar.setBrightness(200);
  }
  item.tomateFechar.onClick = function(mouse) {
    disableInteractiveness();
    somClique();

    var currentTime = 0;
    var animationInterval = 750; // Intervalo entre cada animacao

    groupChangeAlpha(itensTomateCiclo, 0, 600);

    setTimeout(function() {
      groupDisable(itensTomateCiclo);
      scene[0].setSubtitle("");

      item.tomateFechar.setBrightness(200);
      item.estTomateDoente.enable();
      item.estTomateDoente.changeAlpha(1, 600);
    }, currentTime += animationInterval);

    setTimeout(function() {
      groupDisable(itensTomateCiclo);
      item.tomateBalaoSintoma.enable();
      item.tomateBalaoSintoma.changeAlpha(1, 600);
      item.tomateTextoSintomas.enable();
      item.tomateTextoSintomas.changeAlpha(1, 600);

      item.tomateAbaPrevencao.enable();
      item.tomateAbaPrevencao.changeAlpha(1, 600);
      item.tomateAbaTransmissao.enable();
      item.tomateAbaTransmissao.changeAlpha(1, 600);

      item.tomateBotaoOK.enable();
      item.tomateBotaoOK.changeAlpha(1, 600);

      item.tomateBalaoPrevencao.setAlpha(1);
      item.tomateBalaoTransmissao.setAlpha(1);
      item.tomateAbaSintomas.setAlpha(1);
      item.tomateBotaoOKhover.setAlpha(1);
      item.tomateTextoPrevencao.setAlpha(1);
      item.tomateTextoTransmissao.setAlpha(1);
    }, currentTime += animationInterval);

    setTimeout(function() {
      enableInteractiveness();
    }, currentTime += animationInterval);
  }
  itensTomateCiclo.push(item.tomateFechar);

  var itensTomateDoente = [];

  item.estTomateDoente = new Game.Image("estHngrDte.png");
  item.estTomateDoente.setPosition(960, 550);
  item.estTomateDoente.setZorder(11);
  item.estTomateDoente.setAlpha(0);
  item.estTomateDoente.disable();
  itensTomateDoente.push(item.estTomateDoente);

  item.tomateBalaoSintoma = new Game.Image("balSintEsq.png");
  item.tomateBalaoSintoma.setPosition(730-260, 300);
  item.tomateBalaoSintoma.setScale(0.25);
  item.tomateBalaoSintoma.setZorder(6);
  item.tomateBalaoSintoma.setAlpha(0);
  item.tomateBalaoSintoma.disable();
  itensTomateDoente.push(item.tomateBalaoSintoma);

  item.tomateBalaoPrevencao = new Game.Image("balPrevEsq.png");
  item.tomateBalaoPrevencao.setPosition(730-260, 300);
  item.tomateBalaoPrevencao.setScale(0.25);
  item.tomateBalaoPrevencao.setZorder(6);
  item.tomateBalaoPrevencao.disable();
  itensTomateDoente.push(item.tomateBalaoPrevencao);

  item.tomateBalaoTransmissao = new Game.Image("balTranEsq.png");
  item.tomateBalaoTransmissao.setPosition(730-260, 300);
  item.tomateBalaoTransmissao.setScale(0.25);
  item.tomateBalaoTransmissao.setZorder(6);
  item.tomateBalaoTransmissao.disable();
  itensTomateDoente.push(item.tomateBalaoTransmissao);

  item.tomateAbaSintomas = new Game.Item("abaSint.png");
  item.tomateAbaSintomas.setPosition(432-260, 71);
  item.tomateAbaSintomas.setScale(0.25);
  item.tomateAbaSintomas.setZorder(7);
  item.tomateAbaSintomas.disable();
  item.tomateAbaSintomas.onClick = function() {
    somClique();

    item.tomateBalaoSintoma.enable();
    item.tomateBalaoPrevencao.disable();
    item.tomateBalaoTransmissao.disable();

    item.tomateAbaSintomas.disable();
    item.tomateAbaPrevencao.enable();
    item.tomateAbaTransmissao.enable();

    item.tomateTextoSintomas.enable();
    item.tomateTextoPrevencao.disable();
    item.tomateTextoTransmissao.disable();
  }
  itensTomateDoente.push(item.tomateAbaSintomas);

  item.tomateTextoSintomas = new Game.Text(
    "- Ação espoliadora: subnutrição;\n" +
    "- Ação tóxica: edema, urticária e convulsões;\n" +
    "- Ação mecânica: irritação na pele, obstrução intestinal."
    , estiloInfoBalao);
  item.tomateTextoSintomas.setPosition(432-130-260, 58+20);
  item.tomateTextoSintomas.setAlpha(0);
  item.tomateTextoSintomas.disable();
  itensTomateDoente.push(item.tomateTextoSintomas);

  item.tomateAbaPrevencao = new Game.Item("abaPrev.png");
  item.tomateAbaPrevencao.setPosition(432+486-260, 71);
  item.tomateAbaPrevencao.setScale(0.25);
  item.tomateAbaPrevencao.setZorder(9);
  item.tomateAbaPrevencao.setAlpha(0);
  item.tomateAbaPrevencao.disable();
  item.tomateAbaPrevencao.onClick = function() {
    somClique();

    item.tomateBalaoSintoma.disable();
    item.tomateBalaoPrevencao.enable();
    item.tomateBalaoTransmissao.disable();

    item.tomateAbaSintomas.enable();
    item.tomateAbaPrevencao.disable();
    item.tomateAbaTransmissao.enable();

    item.tomateTextoSintomas.disable();
    item.tomateTextoPrevencao.enable();
    item.tomateTextoTransmissao.disable();
  }
  itensTomateDoente.push(item.tomateAbaPrevencao);

  item.tomateTextoPrevencao = new Game.Text(
    "- Ingerir água tratada;\n" +
    "- Lavar bem frutas e legumes;\n" +
    "- Não defecar em locais inapropriados;\n" +
    "- Saneamento básico."
    , estiloInfoBalao);
  item.tomateTextoPrevencao.setPosition(432-130-260, 58+20);
  item.tomateTextoPrevencao.disable();
  itensTomateDoente.push(item.tomateTextoPrevencao);

  item.tomateAbaTransmissao = new Game.Item("abaTran.png");
  item.tomateAbaTransmissao.setPosition(432+232-260, 71);
  item.tomateAbaTransmissao.setScale(0.25);
  item.tomateAbaTransmissao.setZorder(8);
  item.tomateAbaTransmissao.setAlpha(0);
  item.tomateAbaTransmissao.disable();
  item.tomateAbaTransmissao.onClick = function() {
    somClique();

    item.tomateBalaoSintoma.disable();
    item.tomateBalaoPrevencao.disable();
    item.tomateBalaoTransmissao.enable();

    item.tomateAbaSintomas.enable();
    item.tomateAbaPrevencao.enable();
    item.tomateAbaTransmissao.disable();

    item.tomateTextoSintomas.disable();
    item.tomateTextoPrevencao.disable();
    item.tomateTextoTransmissao.enable();
  }
  itensTomateDoente.push(item.tomateAbaTransmissao);

  item.tomateTextoTransmissao = new Game.Text(
    "- Ingestão de água e alimentos contaminados;\n" +
    "- Poeira, aves, insetos (moscas e baratas);\n" +
    "- Irrigação de hortas com água contaminada."
    , estiloInfoBalao);
  item.tomateTextoTransmissao.setPosition(432-130-260, 58+20);
  item.tomateTextoTransmissao.disable();
  itensTomateDoente.push(item.tomateTextoTransmissao);

  item.tomateBotaoOK = new Game.Item("okNormal.png");
  item.tomateBotaoOK.setScale(0.25);
  item.tomateBotaoOK.setPosition(432+450-260, 71+290);
  item.tomateBotaoOK.setAlpha(0);
  item.tomateBotaoOK.disable();
  item.tomateBotaoOK.onMouseOver = function() {
    item.tomateBotaoOK.disable();
    item.tomateBotaoOKhover.enable();
  }
  item.tomateBotaoOK.onClick = function() {
    item.tomateBotaoOKhover.onClick();
  }
  itensTomateDoente.push(item.tomateBotaoOK);

  item.tomateBotaoOKhover = new Game.Item("okHover.png");
  item.tomateBotaoOKhover.setScale(0.25);
  item.tomateBotaoOKhover.setPosition(432+450-260, 71+290);
  item.tomateBotaoOKhover.disable();
  item.tomateBotaoOKhover.onMouseOut = function() {
    item.tomateBotaoOKhover.disable();
    item.tomateBotaoOK.enable();
  }
  item.tomateBotaoOKhover.onClick = function() {
    disableInteractiveness();
    somClique();

    var currentTime = 0;
    var animationInterval = 750; // Intervalo entre cada animacao

    groupChangeAlpha(itensTomateDoente, 0, 600);

    setTimeout(function() {
      item.estTomateNormal.enable();
      item.estTomateNormal.setBrightness(220);
      item.estTomateNormal.changeAlpha(1, 600);

      scene[0].background.changeBrightness(210, 600);
      item.carteiras.changeBrightness(210, 600);
      item.mesaProfessor.changeBrightness(210, 600);
      item.caixaDeAreia.changeBrightness(210, 600);
      item.vasoDeFlores.changeBrightness(210, 600);
      item.livro.changeBrightness(210, 600);
      item.microscopio.changeBrightness(210, 600);

      item.estBananaNormal.changeBrightness(210, 600);
      item.estPernNormal.changeBrightness(210, 600);
      item.estGatoNormal.changeBrightness(210, 600);
      item.setaJanela.enable();
      item.setaArmario.enable();
      item.setaJanela.changeAlpha(1, 600);
      item.setaArmario.changeAlpha(1, 600);

      item.tomateBotaoOKhover.disable();
      item.tomateBalaoPrevencao.disable();
      item.tomateBalaoTransmissao.disable();
      item.tomateAbaSintomas.disable();
      item.tomateAbaPrevencao.disable();
      item.tomateAbaTransmissao.disable();
      item.tomateTextoPrevencao.disable();
      item.tomateTextoTransmissao.disable();
    }, currentTime += animationInterval);

    setTimeout(function() {
      item.estBananaNormal.setInteractive(true);
      item.estPernNormal.setInteractive(true);
      item.estGatoNormal.setInteractive(true);
      item.estTomateNormal.setInteractive(true);
      item.setaJanela.setInteractive(true);
      item.setaArmario.setInteractive(true);
      item.caixaDeAreia.setInteractive(true);
      item.vasoDeFlores.setInteractive(true);
      item.livro.setInteractive(true);
      item.microscopio.setInteractive(true);
      item.bananaRegion.setInteractive(true);

      enableInteractiveness();

    }, currentTime += animationInterval);

  }
  itensTomateDoente.push(item.tomateBotaoOKhover);

}


text:
class Test {
  final String s = new StringBuilder().<caret>append("foo").append("bar").toString();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/list_viewpage_img"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <Button
        android:id="@+id/list_viewpage_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="40dip"
        android:text="开始体验"
        android:visibility="gone" />

</FrameLayout>


text:
using System;
using System.Windows.Input;

namespace BooksSample.Framework
{
    public class DelegateCommand : ICommand
    {
        private Action _execute;
        private Func<bool> _canExecute;

        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        public DelegateCommand(Action execute)
            : this(execute, null)
        { }

        public event EventHandler CanExecuteChanged;

        // TODO: 08 - Expression bodied member: method
        // TODO: 08 - null conditional operator
        public bool CanExecute(object parameter)
        {
            if (_canExecute == null) return true;
            return _canExecute.Invoke();
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        // TODO: 08 - null conditional operator
        public void RaiseCanExecuteChanged()
        {
            EventHandler handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

    }
}


text:
from PyQt4 import QtCore, QtGui
import sys

from Settings_win import SettingsWindow
from preferences import Preferences
from data_dumper import DataDumper

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

# GENERATE GUI
# ------------------------------------------------------------------------------------------
# This code creates the GUI and connects the actions to functions in other files and classes

class MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(613, 370)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout_6 = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.formLayout_2 = QtGui.QFormLayout()
        self.formLayout_2.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
        self.formLayout_2.setObjectName(_fromUtf8("formLayout_2"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.label)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.file_in_line = QtGui.QLineEdit(self.centralwidget)
        self.file_in_line.setObjectName(_fromUtf8("file_in_line"))
        self.horizontalLayout.addWidget(self.file_in_line)
        self.open_file_button = QtGui.QPushButton(self.centralwidget)
        self.open_file_button.setObjectName(_fromUtf8("open_file_button"))
        self.horizontalLayout.addWidget(self.open_file_button)
        self.formLayout_2.setLayout(0, QtGui.QFormLayout.FieldRole, self.horizontalLayout)
        self.label_10 = QtGui.QLabel(self.centralwidget)
        self.label_10.setObjectName(_fromUtf8("label_10"))
        self.formLayout_2.setWidget(1, QtGui.QFormLayout.LabelRole, self.label_10)
        self.file_out_line = QtGui.QLineEdit(self.centralwidget)
        self.file_out_line.setObjectName(_fromUtf8("file_out_line"))
        self.formLayout_2.setWidget(1, QtGui.QFormLayout.FieldRole, self.file_out_line)
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.formLayout_2.setWidget(2, QtGui.QFormLayout.LabelRole, self.label_2)
        self.schema_line = QtGui.QLineEdit(self.centralwidget)
        self.schema_line.setObjectName(_fromUtf8("schema_line"))
        self.formLayout_2.setWidget(2, QtGui.QFormLayout.FieldRole, self.schema_line)
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.formLayout_2.setWidget(3, QtGui.QFormLayout.LabelRole, self.label_3)
        self.table_line = QtGui.QLineEdit(self.centralwidget)
        self.table_line.setObjectName(_fromUtf8("table_line"))
        self.formLayout_2.setWidget(3, QtGui.QFormLayout.FieldRole, self.table_line)
        self.label_7 = QtGui.QLabel(self.centralwidget)
        self.label_7.setObjectName(_fromUtf8("label_7"))
        self.formLayout_2.setWidget(7, QtGui.QFormLayout.LabelRole, self.label_7)
        self.password_line = QtGui.QLineEdit(self.centralwidget)
        self.password_line.setObjectName(_fromUtf8("password_line"))
        self.password_line.setEchoMode (QtGui.QLineEdit.Password)
        self.formLayout_2.setWidget(7, QtGui.QFormLayout.FieldRole, self.password_line)
        self.verticalLayout_2.addLayout(self.formLayout_2)
        self.auto_read_checkbox = QtGui.QCheckBox(self.centralwidget)
        self.auto_read_checkbox.setObjectName(_fromUtf8("auto_read_checkbox"))
        self.verticalLayout_2.addWidget(self.auto_read_checkbox)
        self.label_8 = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.read_button = QtGui.QPushButton(self.centralwidget)
        self.read_button.setObjectName(_fromUtf8("read_button"))
        self.verticalLayout_2.addWidget(self.read_button)
        self.sanitize_button = QtGui.QPushButton(self.centralwidget)
        self.sanitize_button.setObjectName(_fromUtf8("sanitize_button"))
        self.verticalLayout_2.addWidget(self.sanitize_button)
        self.label_8.setFont(font)
        self.label_8.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.label_8.setObjectName(_fromUtf8("label_8"))
        self.verticalLayout_2.addWidget(self.label_8)
        self.horizontalLayout_6.addLayout(self.verticalLayout_2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 613, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        self.menuExport = QtGui.QMenu(self.menuFile)
        self.menuExport.setObjectName(_fromUtf8("menuExport"))
        MainWindow.setMenuBar(self.menubar)
        self.actionSet_Defaults = QtGui.QAction(MainWindow)
        self.actionSet_Defaults.setObjectName(_fromUtf8("actionSet_Defaults"))
        self.actionSave_current_preferences = QtGui.QAction(MainWindow)
        self.actionSave_current_preferences.setObjectName(_fromUtf8("actionSave_current_preferences"))
        self.actionLoad_Preferences = QtGui.QAction(MainWindow)
        self.actionLoad_Preferences.setObjectName(_fromUtf8("actionLoad_Preferences"))
        self.actionPreferences = QtGui.QAction(MainWindow)
        self.actionPreferences.setObjectName(_fromUtf8("actionPreferences"))
        self.actionSanitization = QtGui.QAction(MainWindow)
        self.actionSanitization.setObjectName(_fromUtf8("actionSanitization"))
        self.actionPostgreSQL = QtGui.QAction(MainWindow)
        self.actionPostgreSQL.setObjectName(_fromUtf8("actionPostgreSQL"))
        self.actionDjango_Model = QtGui.QAction(MainWindow)
        self.actionDjango_Model.setObjectName(_fromUtf8("actionDjango_Model"))
        self.actionSettings = QtGui.QAction(MainWindow)
        self.actionSettings.setObjectName(_fromUtf8("actionSettings"))
        self.menuExport.addAction(self.actionPostgreSQL)
        self.menuExport.addAction(self.actionDjango_Model)
        self.menuFile.addAction(self.actionSave_current_preferences)
        self.menuFile.addAction(self.actionLoad_Preferences)
        self.menuFile.addAction(self.actionSettings)
        self.menuFile.addAction(self.menuExport.menuAction())
        self.menubar.addAction(self.menuFile.menuAction())
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        self.preferences = Preferences("settings_default.yaml")
        self.file_in_line.setText(self.preferences.file_in)
        self.file_in_line.textChanged.connect(self.update_preferences)
        self.file_out_line.setText(self.preferences.file_in.replace(".csv", "_clean.csv"))
        self.file_out_line.textChanged.connect(self.update_preferences)
        self.password_line.textChanged.connect(self.update_preferences)
        self.schema_line.textChanged.connect(self.update_preferences)
        self.table_line.textChanged.connect(self.update_preferences)

        MainWindow.setWindowTitle(_translate("MainWindow", "THE DATA DUMPER!!!", None))
        self.dumper = DataDumper()
        self.actionDjango_Model.triggered.connect(self.press_django)
        self.actionPostgreSQL.triggered.connect(self.press_postgres)
        self.actionSettings.triggered.connect(self.show_settings)
        self.label.setText(_translate("MainWindow", "File Input", None))
        self.open_file_button.setText(_translate("MainWindow", "Open File", None))
        self.open_file_button.clicked.connect(self.selectFile)
        self.label_10.setText(_translate("MainWindow", "File Output", None))
        self.label_2.setText(_translate("MainWindow", "Schema", None))
        self.label_3.setText(_translate("MainWindow", "Table", None))
        self.label_7.setText(_translate("MainWindow", "Password", None))
        self.auto_read_checkbox.setText(_translate("MainWindow", "Create a mapping if it does not exist.", None))
        self.label_8.setText(_translate("MainWindow", "If there is an error, it will appear here.", None))
        self.sanitize_button.setText(_translate("MainWindow", "Sanitize .csv", None))
        self.sanitize_button.clicked.connect(self.press_sanitize)
        self.read_button.setText(_translate("MainWindow", "Map .csv / Overwrite Current Mapping", None))
        self.read_button.clicked.connect(self.press_csv_map)
        self.menuFile.setTitle(_translate("MainWindow", "File", None))
        self.menuExport.setTitle(_translate("MainWindow", "Export", None))
        self.actionSet_Defaults.setText(_translate("MainWindow", "Defaults", None))
        self.actionSave_current_preferences.setText(_translate("MainWindow", "Save Preferences", None))
        self.actionLoad_Preferences.setText(_translate("MainWindow", "Load Preferences", None))
        self.actionPreferences.setText(_translate("MainWindow", "Preferences", None))
        self.actionSanitization.setText(_translate("MainWindow", "Sanitization", None))
        self.actionPostgreSQL.setText(_translate("MainWindow", "PostgreSQL", None))
        self.actionDjango_Model.setText(_translate("MainWindow", "Django Model", None))
        self.actionSettings.setText(_translate("MainWindow", "Settings", None))

    # GUI FUNCTIONS
    # ---------------------------------------------------------------------------------------

    # Generates the settings window
    def show_settings(self):
        self.settings = SettingsWindow(self.dumper.preferences,self.dumper)
        self.settings.setupUi(self.settings)
        self.settings.show()

    # This is passed to all the methods in data_dumper, lets the functions change the status.
    def set_status(self, status_string):
        self.label_8.setText(status_string)

    # returns T/F if the checkbox is checked or not
    def checked_is_true(self):
        if self.auto_read_checkbox.isChecked():
            return True
        else:
            return False

    # All of the press_------- functions call the data dumper functions and pass functions to them
    def press_csv_map(self):
        self.dumper.csv_map(self.set_status, self.checked_is_true())

    def press_sanitize(self):
        self.dumper.csv_sanitize(self.set_status, self.checked_is_true())

    def press_django(self):
        self.dumper.create_django_model(self.set_status, self.checked_is_true())

    def press_postgres(self):
        self.dumper.create_postgres(self.set_status, self.checked_is_true())

    # Called every time a text field is changed.
    def update_preferences(self):
        self.dumper.preferences.check_fields(self.file_in_line.text(),
                                        self.file_out_line.text(),
                                        self.schema_line.text(),
                                        self.table_line.text(),
                                        self.password_line.text())

    # Adds functionality to the open button window
    def selectFile(self):
        string = QtGui.QFileDialog.getOpenFileName()
        if string != "":
            self.file_in_line.setText(string)
            self.file_out_line.setText(str(string).replace(".csv", "_clean.csv"))
        self.update_preferences()

'''
This is code that I had to add
from "file name" import "class name"
if it is a main window, change from QWidget to QMainWindow
'''
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QMainWindow()
    ui = MainWindow()
    ui.setupUi(Form)

    Form.show()
    sys.exit(app.exec_())


text:
#ifndef util_timer_h
#define util_timer_h

#include "log.h"
#include <memory>

namespace tl {
class Timer {
private:
  class Impl;
  std::unique_ptr<Impl> pimpl_;

public:
  ~Timer();
  Timer();

  void lap(std::string);
  void start();
  void stop();

  void print(std::ostream& os = ilog) const;
};

// ------------------------------------------------------------ //

/// Global timer.
extern Timer timer;
}

#endif /* util_timer_h */


text:
#ifndef __OPENCV_WORLD_HPP__
#define __OPENCV_WORLD_HPP__

#include "opencv2/core/core.hpp"

#ifdef __cplusplus
namespace cv
{

CV_EXPORTS_W bool initAll();

}

#endif

#endif


text:
import re
import poplib
import imaplib
testNum = 5  # retry time for fail login
timeout = 10

class emailError(Exception):

    def __init__(self, msg):
        super().__init__()
        self.msg = msg

class emailFormatError(emailError):

    def __init__(self, msg):
        super().__init__(msg)

class emailDomainNotFind(emailError):

    def __init__(self, msg):
        super().__init__(msg)

class EmailLogin(object):

    """domain,host,hostType are lists.
    When init the class, read the conf file to conf domain,host,hostType
    The checkImapMail/checkPopMail
    will find the suitable (domain,host) in these list to verify the password"""

    def __init__(self):
        super().__init__()
        # read conf file
        self.mailDomainList = []
        self.mailHostList = []
        self.mailType = []
        conf = open('conf', 'r')
        while True:
            line = conf.readline()
            if not line:
                conf.close()
                break
            content = line.split(' ')
            if len(content) == 3:
                self.mailType.append(content[0].strip())
                self.mailDomainList.append(content[1].strip())
                self.mailHostList.append(content[2].strip())

    def getMailDomain(self, email):
        emailparts = email.split('@')
        mailDomain = None
        if(len(emailparts) != 2):
            raise emailFormatError("Email format error:%s" % email)

        for i in self.mailDomainList:
            reDomain = re.compile(i)
            if reDomain.match(str(emailparts[1])):
                mailDomain = i
                break

        if mailDomain == None:
            raise emailDomainNotFind("Email Domain can't find:%s" % email)

        return mailDomain

    def checkImapMail(self, email, password, mailDomain):
        retR = re.compile('^\(\'OK')
        ret = None
        mailHost = None
        for i in range(len(self.mailDomainList)):
            # imap mail
            if mailDomain == self.mailDomainList[i] and self.mailType[i] == 'imap':
                mailHost = self.mailHostList[i]
                break
        if mailHost == None:
            return False

        for i in range(testNum):
            try:
                M = imaplib.IMAP4_SSL(mailHost)
                ret = M.login(email, password)
            except:
                pass
            if(retR.match(str(ret))):
                return True

        return False

    def checkPopMail(self, email, password, mailDomain):
        retR = re.compile('\(\d*,\s*\d*')
        mailHost = None
        for i in range(len(self.mailDomainList)):
            # pop3 mail
            if mailDomain == self.mailDomainList[i] and self.mailType[i] == 'pop':
                mailHost = self.mailHostList[i]
                break
        if mailHost == None:
            return False
        for i in range(testNum):
            try:
                mail = poplib.POP3(mailHost, timeout=timeout)
                mail.user(email)
                mail.pass_(password)
                ret = mail.stat()
                if(retR.match(str(ret))):
                    return True
            except:
                pass

        return False

    def login(self, email, password):
        domain = self.getMailDomain(email)
        if self.checkPopMail(email, password, domain):
            return True
        elif self.checkImapMail(email, password, domain):
            return True
        else:
            return False


text:
namespace Cassandra
{
    /// <summary>
    ///  A retry policy that wraps another policy, logging the decision made by its
    ///  sub-policy. <p> Note that this policy only log the Ignore and Retry decisions
    ///  (since Rethrow decisions just amount to propate the cassandra exception). The
    ///  logging is done at the Info level.</p>
    /// </summary>
    public class LoggingRetryPolicy : IRetryPolicy
    {
        private readonly Logger _logger = new Logger(typeof (LoggingRetryPolicy));
        private readonly IRetryPolicy _policy;

        /// <summary>
        ///  Creates a new <c>RetryPolicy</c> that logs the decision of
        ///  <c>policy</c>.
        /// </summary>
        /// <param name="policy"> the policy to wrap. The policy created by this
        ///  constructor will return the same decision than <c>policy</c> but will log them.</param>
        public LoggingRetryPolicy(IRetryPolicy policy)
        {
            _policy = policy;
        }

        public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved,
                                           int nbRetry)
        {
            RetryDecision decision = _policy.OnReadTimeout(query, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
            switch (decision.DecisionType)
            {
                case RetryDecision.RetryDecisionType.Ignore:
                    _logger.Info(
                        string.Format(
                            "Ignoring read timeout (initial consistency: {0}, required responses: {1}, received responses: {2}, data retrieved: {3}, retries: {4})",
                            cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry));
                    break;
                case RetryDecision.RetryDecisionType.Retry:
                    _logger.Info(
                        string.Format(
                            "Retrying on read timeout at consistency {0} (initial consistency: {1}, required responses: {2}, received responses: {3}, data retrieved: {4}, retries: {5})",
                            CL(cl, decision), cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry));
                    break;
            }
            return decision;
        }

        public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry)
        {
            RetryDecision decision = _policy.OnWriteTimeout(query, cl, writeType, requiredAcks, receivedAcks, nbRetry);
            switch (decision.DecisionType)
            {
                case RetryDecision.RetryDecisionType.Ignore:
                    _logger.Info(
                        string.Format(
                            "Ignoring write timeout (initial consistency: {0}, write type: {1} required acknowledgments: {2}, received acknowledgments: {3}, retries: {4})",
                            cl, writeType, requiredAcks, receivedAcks, nbRetry));
                    break;
                case RetryDecision.RetryDecisionType.Retry:
                    _logger.Info(
                        string.Format(
                            "Retrying on write timeout at consistency {0}(initial consistency: {1}, write type: {2}, required acknowledgments: {3}, received acknowledgments: {4}, retries: {5})",
                            CL(cl, decision), cl, writeType, requiredAcks, receivedAcks, nbRetry));
                    break;
            }
            return decision;
        }

        public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry)
        {
            RetryDecision decision = _policy.OnUnavailable(query, cl, requiredReplica, aliveReplica, nbRetry);
            switch (decision.DecisionType)
            {
                case RetryDecision.RetryDecisionType.Ignore:
                    _logger.Info(
                        string.Format(
                            "Ignoring unavailable exception (initial consistency: {0}, required replica: {1}, alive replica: {2}, retries: {3})", cl,
                            requiredReplica, aliveReplica, nbRetry));
                    break;
                case RetryDecision.RetryDecisionType.Retry:
                    _logger.Info(
                        string.Format(
                            "Retrying on unavailable exception at consistency {0} (initial consistency: {1}, required replica: {2}, alive replica: {3}, retries: {4})",
                            CL(cl, decision), cl, requiredReplica, aliveReplica, nbRetry));
                    break;
            }
            return decision;
        }

        private static ConsistencyLevel CL(ConsistencyLevel cl, RetryDecision decision)
        {
            return decision.RetryConsistencyLevel ?? cl;
        }
    }
}


text:
package freemarker.ext.beans;

public final class RationalNumber extends Number {

    final int divident;
    final int divisor;

    public RationalNumber(int divident, int divisor) {
        this.divident = divident;
        this.divisor = divisor;
    }

    @Override
    public int intValue() {
        return divident / divisor;
    }

    @Override
    public long longValue() {
        return divident / (long) divisor;
    }

    @Override
    public float floatValue() {
        return (float) (divident / (double) divisor);
    }

    @Override
    public double doubleValue() {
        return divident / (double) divisor;
    }

    public int getDivident() {
        return divident;
    }

    public int getDivisor() {
        return divisor;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + divident;
        result = prime * result + divisor;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RationalNumber other = (RationalNumber) obj;
        if (divident != other.divident)
            return false;
        if (divisor != other.divisor)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return divident + "/" + divisor;
    }

}


text:
Tell
====

This is a Google Glass app, which adds a new voice command to the "ok glass"
main menu: "please tell".

Never again will have you have to talk to the people around you directly! Want
a sandwich? No problem, just say: "ok glass, please tell Bob to make me a
sandwich" and Glass will say "make him a sandwich, Bob"

## Functionality

This app doesn't understand English grammar, but it will try to do some helpful
rewriting to change the viewpoint of the speaker from the user to Glass itself.

Here are some examples of what you can say:

`ok glass, please tell Patrick not to brag all the time`

↳ *"hey Patrick, don't brag all the time"*

`ok glass, please tell John that his code is unreadable`

↳ *"your code is unreadable, John"*

`ok glass, please tell Christine to make me a sandwich`

↳ *"make him a sandwich, Christine"*

## Limitations

There are too many to list - this app is only intended for the humor of it
existing. However, here are some particularly notable problems:

* **Tell won't understand names consisting of more than one word**

  `ok glass, please tell John Smith to get off my case`

  ↳ *"John Smith to get off his case"*

* **Tell won't be able to change verb conjugation**

  `ok glass, please tell Will that he sucks`

  ↳ *"you sucks, Will"*

## Running this on Glass

You can use your IDE to compile and install this app or use
[`adb`](https://developer.android.com/tools/help/adb.html)
on the command line:

    $ adb install -r Tell.apk

To start the app, say "ok glass, please tell Bob to make me a
sandwich" from the Glass clock screen.


text:
package ch.becompany.social.twitter

import java.io.IOException
import java.time.Instant

import akka.http.scaladsl.model._
import akka.pattern.after
import akka.stream.{ActorAttributes, Supervision}
import akka.stream.scaladsl.{Flow, Framing, Source}
import akka.util.ByteString
import ch.becompany.http.{HttpClient, HttpHandler}
import ch.becompany.social.Status
import com.typesafe.scalalogging.LazyLogging
import spray.json._

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

class TwitterStream(filter: Map[String, String], url: String, userUpdateInterval: FiniteDuration = 1 minute)
                   (implicit ec: ExecutionContext)
  extends HttpClient
    with TwitterOAuthSupport
    with TwitterJsonSupport
    with LazyLogging {

  import ActorAttributes._

  private lazy val source = Uri(url)

  private lazy val resumingDecider: Supervision.Decider = {
    case e: Exception =>
      logger.info(s"Encountered ${e.getClass}, resuming stream")
      Supervision.Resume
    case _ =>
      Supervision.Stop
  }

  // Twitter defines a limitation of 15 request per user. Resets every 15 minutes. => 1 req/m
  private val minUpdateInterval: FiniteDuration = 1 minute
  private val updateInterval = minUpdateInterval.max(userUpdateInterval)

  private lazy val httpRequest: HttpRequest = HttpRequest(
    method = HttpMethods.POST,
    uri = source,
    headers = List(headers.Accept(MediaRanges.`*/*`)),
    entity = FormData(filter).toEntity
  )

  private def streamResponse(response: HttpResponse): Source[(Instant, Try[Status]), Any] =
    response.entity.dataBytes
      .via(Framing.delimiter(ByteString("\r\n"), maximumFrameLength = Int.MaxValue, allowTruncation = true))
      .map(_.utf8String)
      .filter(_.length > 0)
      .map { json =>
        val (date, status) = TweetJsonFormat.read(json.parseJson)
        (date, Try(status))
      }

  private def message(response: HttpResponse): Future[String] =
    response.entity.toStrict(5 seconds)
      .map(_.data.utf8String)
      .map(msg => s"Response ${response.status}: $msg")

  private object handler extends HttpHandler[Source[(Instant, Try[Status]), Any]] {
    override def handle(request: HttpRequest, response: HttpResponse)
                       (implicit ec: ExecutionContext): Future[Source[(Instant, Try[Status]), Any]] =
      response.status match {
        case StatusCodes.OK => Future.successful(streamResponse(response))
        case _ => message(response).flatMap(msg => Future.failed(new IOException(msg)))
      }
  }

  private lazy val sendRequest =
    req(httpRequest)(handler, ec) recover {
      case e => logger.error("Error requesting the Twitter stream: ", e); Source.empty
    }

  lazy val stream: Source[(Instant, Try[Status]), Any] = {
    logger.debug(s"Streaming tweets with filter $filter")
    Source
      .unfold(true)(previous => Some((false, previous)))
      .via(
        Flow[Boolean]
          .mapAsync(1)(first =>
            if (first) sendRequest else after(updateInterval, using = system.scheduler)(sendRequest)
          )
          .withAttributes(supervisionStrategy(resumingDecider))
      )
      .flatMapConcat(identity)
  }

}

object TwitterStream {

  private val streamUrl = "https://stream.twitter.com/1.1/statuses/filter.json"

  def apply(filter: (String, String)*)(implicit ec: ExecutionContext): TwitterStream =
    new TwitterStream(filter.toMap, streamUrl)

  def apply(restartInterval: FiniteDuration, filter: (String, String)*)(implicit ec: ExecutionContext): TwitterStream =
    new TwitterStream(filter.toMap, streamUrl, restartInterval)

}


text:
require 'sinatra/base'
require 'json'
require 'pp'
require 'rubygems'
require 'chef/rest'
require 'chef/search/query'
require 'date'

class ChefInfo

  def self.get_nodes
    Chef::Config.node_name=               ENV['CHEF_CLIENT_NAME']
    Chef::Config.client_key=              "/etc/chef/#{ENV['CHEF_CLIENT_KEY']}"
    Chef::Config.validation_client_name=  ENV['CHEF_VALIDATOR_NAME']
    Chef::Config.validation_key =         "/etc/chef/#{ENV['CHEF_VALIDATION_KEY']}"
    Chef::Config.chef_server_url =        ENV['CHEF_URL']

    query = Chef::Search::Query.new
    nodes = query.search('node', query = '*:*').first rescue []

    node_list =[]
    nodes.each do |n|
      # make each instance its own individual hash so we can access later
      node_hash = Hash.new
      time_now = Time.now.to_i

      node_hash[:name]              = n.name #rescue 'unknown'
      node_hash[:ipaddress]         = n.ipaddress rescue nil
      node_hash[:chef_environment]  = n.chef_environment
      node_hash[:primary_runlist]   = n.primary_runlist
      node_hash[:uptime]            = n.uptime rescue 'unknown'
      node_hash[:chef_version]      = n.chef_packages.chef.version rescue 'unknown'
      node_hash[:platform]          = "#{n.platform} #{n.platform_version}" rescue "unknown"
      node_hash[:ohai_time]         = n.ohai_time rescue nil

      # append our hash of server attrs and return the server_list

      node_list << node_hash
    end

    node_list
  end

  def self.update_nodes

    # Purpose of this function: map chef data onto the Node table

    begin
      chef_node_data=ChefInfo.get_nodes
    rescue
      return false
    end

    chef_node_data.each do |chef_node|
      if chef_node[:ipaddress].nil?
        puts "chef node with no IP should not get added to the database"
      else
        node_data = Node.find_by(iso_client_ip: chef_node[:ipaddress])

        if node_data.nil?
          # We only want chef to update nodes, not create them.
          # Could put logic here to capture orphans
        else
          node_data.update_attributes(
            chef_name:          chef_node[:name],
            iso_client_ip:      chef_node[:ipaddress].to_s,
            chef_env:           chef_node[:chef_environment].to_s,
            chef_runlist:       chef_node[:primary_runlist].to_s,
            chef_uptime:        chef_node[:uptime].to_s,
            chef_version:       chef_node[:chef_version].to_s,
            chef_platform:      chef_node[:platform].to_s,
            chef_last_ohai:     chef_node[:ohai_time].to_i,
          )

          node_data.save
        end
      end
    end

    return nil #success

  end
end


text:
Implementing a POST endpoint
=============================

# Setup

This assumes you have a Rails app with a model `Cheese` defined, mapping to a database (e.g. SQLite).
It should have one required column, `name`.

You should also have [curl](https://curl.se/) installed.

# Implementation

Add a route to your **'config/routes.rb'** :
```
  resources :cheeses
```

Create a controller in **'controllers/cheeses_controller'**:
```ruby
class CheesesController < ApplicationController

  skip_before_action :verify_authenticity_token

  def create
    Flappi.build_and_respond(self, :create)
  end
end
```

Note that we don't need an authenticity token as this is an API (you may do this in a superclass, something like: `ApiController`)

The second parameter to `Flappi.build_and_respond` sets the action - this causes a definition `Cheeses` + `Create` => `CheesesCreate` to be used.

Now, create your `CheesesCreate` definition class in **'app/controllers/api_definitions/cheeses_create.rb'**.

```ruby
module ApiDefinitions
  module CheesesCreate

    include Flappi::Definition

    def endpoint
      title 'Create a cheeses'
      http_method 'POST'
      path '/cheeses'
      check_params true
      param :name, doc: 'The name of the cheese'
    end

    # Post data to the model's create! method
    def respond
      build type: Cheese, as: :create! do
        field :name, doc: 'The name of the cheese'
      end
    end
  end
end
```

This implements a POST method `/cheeses`. It takes one parameter `name` which will be written into the created record.
Setting `check_params true` is needed for Rails permitted parameters.
The `build` statement results in a call to the `Cheese.create!` method with a hash of the params, creating a record.
The body of `build` defines the response, returning a hash with the `name`.

# Testing

Running the command:

`curl -X POST -d name=Gruyere 'http://localhost:3000/cheeses.json'`

should now create an entry in the database.


text:
import { API, asyncAction } from '../middlewares/apiMiddleware';
import { QUOTATIONS } from './pagination';

export const GET_QUOTATIONS = asyncAction('GET_QUOTATIONS');
export const GET_QUOTATION = asyncAction('GET_QUOTATION');
export const POST_QUOTATION = asyncAction('POST_QUOTATION');
export const SEARCH_QUOTATIONS = asyncAction('SEARCH_QUOTATIONS');

export const getQuotationsCreator = ({ customerId, page = 1 } = {}) => ({
	type: API,
	payload: {
		url: `/api/quotations?customer_id=${customerId}&page=${page}`,
		method: 'GET',
		types: [GET_QUOTATIONS.PENDING, GET_QUOTATIONS.SUCCESS, GET_QUOTATIONS.ERROR]
	},
	meta: { page, resource: QUOTATIONS },
});

export const getQuotationCreator = (id) => ({
	type: API,
	payload: {
		url: `/api/quotations/${id}`,
		method: 'GET',
		types: [GET_QUOTATION.PENDING, GET_QUOTATION.SUCCESS, GET_QUOTATION.ERROR],
	},
});

export const postQuotationCreator = ({ customerId, meta = {}} = {}) => ({
	type: API,
	payload: {
		url: '/api/quotations',
		method: 'POST',
		types: [POST_QUOTATION.PENDING, POST_QUOTATION.SUCCESS, POST_QUOTATION.ERROR],
		body: { quotation: { customer_id: customerId }},
	},
	meta
});

const searchQuotationsCreator = ({ customerId = null, term = '', page = 1 } = {}) => ({
	type: API,
	payload: {
		url: `/api/quotations/search/${term}?customer_id=${customerId}&page=${page}`,
		method: 'GET',
		types: [SEARCH_QUOTATIONS.PENDING, SEARCH_QUOTATIONS.SUCCESS, SEARCH_QUOTATIONS.ERROR],
	},
	meta: { page, resource: QUOTATIONS },
});

/*
 * Determines whether or not GET_CUSTOMERS request should be initiated.
 * @param state {} - Redux application state
 * @param params {} - The params object passed to getQuotations action
 * @returns true if quotations pagination sub-state for the params.page passed is not defined or
 * if the array of ids for that specific page is empty (look at src/reducers/pagination to
 * better understand the sub-state structure) or if quotations.byId object does not have an
 * quotation object whose customer_id is equals to params.customerId
*/
const shouldGetQuotationsRequest = (state, params) => {
	const { customerId, page } = params;
	const quotationsPagination = state.pagination.quotations;
	const { quotations } = state;
	return !quotationsPagination.pages[page] ||
		quotationsPagination.pages[page].ids === [] ||
		quotationsPagination.pages[page].ids.find(id => quotations.byId[id].customer_id === customerId);
};

const shouldGetQuotationRequest = (state, id) => state.quotations.byId[id] === undefined;

export const getQuotations = (params = {}) => {
	return (dispatch, getState) => {
		if (shouldGetQuotationsRequest(getState(), params)) {
			return dispatch(getQuotationsCreator(params));
		}
		return Promise.resolve();
	};
};

export const getQuotation = (id) => {
	return (dispatch, getState) => {
		if (shouldGetQuotationRequest(getState(), id)) {
			return dispatch(getQuotationCreator(id));
		}
		return Promise.resolve();
	};
};

export const postQuotation = (params) => {
	return (dispatch) => {
		return dispatch(postQuotationCreator(params));
	};
};

export const searchQuotations = (params = {}) => {
	return (dispatch) => {
		return dispatch(searchQuotationsCreator(params));
	};
}


text:
var Sequence = Group.extend({
  initialize: function(line, direction, options) {
    Group.prototype.initialize.call(this);

    this.line = line;
    this.direction = direction;
    this.gridSpace = options.gridSpace;
    this.interval = this.gridSpace[this.direction] / this.line.subdivisions;
  },

  resize: function(size) {
    this.height = size.height;
    this.width = size.width;
    this.drawLines(size);
  },

  drawLines: function(size) {
    var count = this.linesWithin(size[this.direction]);

    this.clear();

    for (var i=0; i <= count; i++) {
      var line = this.drawLine(i);
      this.insertChild(i, line);
    };
  },

  drawLine: function(i) {
    var position = i * this.interval;
    return this.makeLine(position, new Size(this.width, this.height), i);
  },

  makeLine: function(position, size, i) {
    var klass = this.line;
    return new klass(position, size, i);
  },

  linesWithin: function(l) {
    return Math.floor(l / this.interval);
  }
});

module.exports = Sequence;


text:
import { Lazy } from "lazy-val";
export declare function getLinuxToolsPath(): Promise<string>;
export declare function getAppImage(): Promise<string>;
export declare const fpmPath: Lazy<string>;
export declare function prefetchBuildTools(): Promise<[string, string]>;
export declare function getZstd(): Promise<string>;
export declare function getAria(): Promise<string>;


text:
using System;
using System.Net;
using System.Threading;
using OpenMetaverse.StructuredData;

namespace OpenMetaverse.Http
{
    public class EventQueueClient
    {
        /// =
        public const int REQUEST_TIMEOUT = 1000 * 120;

        public delegate void ConnectedCallback();
        public delegate void EventCallback(string eventName, OSDMap body);

        public ConnectedCallback OnConnected;
        public EventCallback OnEvent;

        public bool Running { get { return _Running; } }

        protected Uri _Address;
        protected bool _Dead;
        protected bool _Running;
        protected HttpWebRequest _Request;

        /// Number of times we've received an unknown CAPS exception in series.
        private int _errorCount;
        /// For exponential backoff on error.
        private static Random _random = new Random();

        public EventQueueClient(Uri eventQueueLocation)
        {
            _Address = eventQueueLocation;
        }

        public void Start()
        {
            _Dead = false;

            // Create an EventQueueGet request
            OSDMap request = new OSDMap();
            request["ack"] = new OSD();
            request["done"] = OSD.FromBoolean(false);

            byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

            _Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
        }

        public void Stop(bool immediate)
        {
            _Dead = true;

            if (immediate)
                _Running = false;

            if (_Request != null)
                _Request.Abort();
        }

        void OpenWriteHandler(HttpWebRequest request)
        {
            _Running = true;
            _Request = request;

            Logger.DebugLog("Capabilities event queue connected");

            // The event queue is starting up for the first time
            if (OnConnected != null)
            {
                try { OnConnected(); }
                catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
            }
        }

        void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
        {
            // We don't care about this request now that it has completed
            _Request = null;

            OSDArray events = null;
            int ack = 0;

            if (responseData != null)
            {
                _errorCount = 0;
                // Got a response
                OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap;

                if (result != null)
                {
                    events = result["events"] as OSDArray;
                    ack = result["id"].AsInteger();
                }
                else
                {
                    Logger.Log("Got an unparseable response from the event queue: \"" +
                        System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
                }
            }
            else if (error != null)
            {
                #region Error handling

                HttpStatusCode code = HttpStatusCode.OK;

                if (error is WebException)
                {
                    WebException webException = (WebException)error;

                    if (webException.Response != null)
                        code = ((HttpWebResponse)webException.Response).StatusCode;
                    else if (webException.Status == WebExceptionStatus.RequestCanceled)
                        goto HandlingDone;
                }

                if (error is WebException && ((WebException)error).Response != null)
                    code = ((HttpWebResponse)((WebException)error).Response).StatusCode;

                if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
                {
                    Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead = true;
                }
                else if (code == HttpStatusCode.BadGateway)
                {
                    // This is not good (server) protocol design, but it's normal.
                    // The EventQueue server is a proxy that connects to a Squid
                    // cache which will time out periodically. The EventQueue server
                    // interprets this as a generic error and returns a 502 to us
                    // that we ignore
                }
                else
                {
                    ++_errorCount;

                    // Try to log a meaningful error message
                    if (code != HttpStatusCode.OK)
                    {
                        Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}",
                            _Address, code), Helpers.LogLevel.Warning);
                    }
                    else if (error.InnerException != null)
                    {
                        Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}",
                            _Address, error.InnerException.Message), Helpers.LogLevel.Warning);
                    }
                    else
                    {
                        Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
                            _Address, error.Message), Helpers.LogLevel.Warning);
                    }
                }

                #endregion Error handling
            }
            else
            {
                ++_errorCount;

                Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
            }

        HandlingDone:

            #region Resume the connection

            if (_Running)
            {
                OSDMap osdRequest = new OSDMap();
                if (ack != 0) osdRequest["ack"] = OSD.FromInteger(ack);
                else osdRequest["ack"] = new OSD();
                osdRequest["done"] = OSD.FromBoolean(_Dead);

                byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);

                if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
                    Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount)));

                // Resume the connection. The event handler for the connection opening
                // just sets class _Request variable to the current HttpWebRequest
                CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT,
                    delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    Logger.DebugLog("Sent event queue shutdown message");
                }
            }

            #endregion Resume the connection

            #region Handle incoming events

            if (OnEvent != null && events != null && events.Count > 0)
            {
                // Fire callbacks for each event received
                foreach (OSDMap evt in events)
                {
                    string msg = evt["message"].AsString();
                    OSDMap body = (OSDMap)evt["body"];

                    try { OnEvent(msg, body); }
                    catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
                }
            }

            #endregion Handle incoming events
        }
    }
}


text:
package me.panavtec.wizard;

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

public class ActionBarActivityResolver implements ActionBarResolver {
  private final ActionBarActivity actionBarActivity;

  public ActionBarActivityResolver(ActionBarActivity actionBarActivity) {
    this.actionBarActivity = actionBarActivity;
  }

  @Override public ActionBar getActionBar() {
    return actionBarActivity.getSupportActionBar();
  }
}


text:
import argparse

from ray.rllib import train
from ray.rllib import rollout

EXAMPLE_USAGE = """
Example usage for training:
    rllib train --run DQN --env CartPole-v0

Example usage for rollout:
    rllib rollout /trial_dir/checkpoint_000001/checkpoint-1 --run DQN
"""

def cli():
    parser = argparse.ArgumentParser(
        description="Train or Run an RLlib Trainer.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=EXAMPLE_USAGE)
    subcommand_group = parser.add_subparsers(
        help="Commands to train or run an RLlib agent.", dest="command")

    # see _SubParsersAction.add_parser in
    # https://github.com/python/cpython/blob/master/Lib/argparse.py
    train_parser = train.create_parser(
        lambda **kwargs: subcommand_group.add_parser("train", **kwargs))
    rollout_parser = rollout.create_parser(
        lambda **kwargs: subcommand_group.add_parser("rollout", **kwargs))
    options = parser.parse_args()

    if options.command == "train":
        train.run(options, train_parser)
    elif options.command == "rollout":
        rollout.run(options, rollout_parser)
    else:
        parser.print_help()


text:
#import "BTPaymentRequest.h"
#import "BTUIThemedView.h"
#import <UIKit/UIKit.h>

@protocol BTAppSwitchDelegate, BTViewControllerPresentingDelegate;
@class BTAPIClient, BTPaymentMethodNonce;

NS_ASSUME_NONNULL_BEGIN

@interface BTPaymentButton : BTUIThemedView

/*!
 @brief Initialize a BTPaymentButton.

 @param apiClient A `BTAPIClient` used for communicating with Braintree servers. Required.
 @param completion A completion block. Required.

 @return A new BTPaymentButton.
*/
- (instancetype)initWithAPIClient:(BTAPIClient *)apiClient
                       completion:(void(^)(BTPaymentMethodNonce * _Nullable paymentMethodNonce, NSError * _Nullable error))completion;

/*!
 @brief The `BTAPIClient` used for communicating with Braintree servers.

 @discussion This property is exposed to enable the use of other UIView initializers, e.g.
 when using Storyboards.
*/
@property (nonatomic, strong, nullable) BTAPIClient *apiClient;

/*!
 @brief The `BTPaymentRequest` that customizes the payment experience.
*/
@property (nonatomic, strong, nullable) BTPaymentRequest *paymentRequest;

/*!
 @brief The completion block to handle the result of a payment authorization flow.

 @discussion This property is exposed to enable the use of other `UIView` initializers, e.g.
 when using Storyboards.
*/
@property (nonatomic, copy) void(^completion)(BTPaymentMethodNonce * _Nullable paymentMethodNonce, NSError * _Nullable error);

/*!
 @brief Set of payment options as strings.
 @discussion e.g. `@"PayPal"`, `@"Venmo"`. By default, this is configured
 to the set of payment options that have been included in the client-side app integration,
 e.g. via frameworks.

 Setting this property will force the button to reload and display the specified payment options,
 even if the payment option is disabled in the Control Panel.
*/
@property (nonatomic, strong) NSOrderedSet <NSString *> *enabledPaymentOptions;

/*!
 @brief The configuration from a `BTAPIClient`.
 @discussion This is automatically fetched when the payment button
 is initialized with a `BTAPIClient`, but it can be `nil` if the `BTAPIClient` has not yet been
 set or if the configuration fetch fails.

 Setting this property will force the button to reload using the new configuration.
*/
@property (nonatomic, strong, nullable) BTConfiguration *configuration;

/*!
 @brief Optional delegate for receiving payment lifecycle messages from a payment option that may initiate an app or browser switch to authorize payments.
*/
@property (nonatomic, weak, nullable) id <BTAppSwitchDelegate> appSwitchDelegate;

/*!
 @brief Optional delegate for receiving payment lifecycle messages from a payment driverthat requires presentation of a view controller to authorize a payment.

 @note Required by PayPal.
*/
@property (nonatomic, weak, nullable) id <BTViewControllerPresentingDelegate> viewControllerPresentingDelegate;

/*!
 @brief Indicates whether any payment options available.
*/
@property (nonatomic, readonly) BOOL hasAvailablePaymentMethod;

@end

NS_ASSUME_NONNULL_END


text:
package apiGatewayConfDeploy

import "github.com/apid/apid-core"

var pluginData = apid.PluginData{
	Name:    "apidGatewayConfDeploy",
	Version: "0.0.2",
	ExtraData: map[string]interface{}{
		"schemaVersion": "0.0.1",
	},
}


text:
package com.oxidedevelopment.noeron;

import com.badlogic.gdx.Application;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.oxidedevelopment.noeron.screens.MainMenu;

public class Noeron extends Game {

	static Noeron instance;
	SpriteBatch batch;

	@Override
	public void create() {
		batch = new SpriteBatch();
		System.out.println("\n"); // Gradle build info is right on top of the debug info..
		Gdx.app.setLogLevel(Application.LOG_DEBUG);

		instance = this;
		setScreen(new MainMenu());
	}

	public static void changeScreen(Screen screen) {
		if(instance != null)
			instance.setScreen(screen);
		else
			Gdx.app.error("Noeron", "Change screen was called when the instance was not set.");
	}

	public static SpriteBatch getBatch() {
		if(instance != null)
			return instance.batch;
		else
			Gdx.app.error("Noeron", "getBatch() was called when the instance was not set.");

		return null;
	}
}


text:
typedef struct Function {
	char* returnType;
	char* name;
	Parameter* parameters;
	unsigned numParameters;
	unsigned outArraySize;
} Function;

char** getFunctionSignatures(Function*, unsigned);
char* getFunctionSignature(Function);

static int calculateSignatureLengthForFunction(Function);
static void buildSignatureForFunction(char*, Function);

void sortFunctions(Function*, unsigned);

bool allFunctionsEqual(Function*, Function*, const unsigned);
bool functionsEqual(Function, Function);

int compareFunctionPointers(const void*, const void*);
int compareFunctions(const Function, const Function);

char** getFunctionNames(Function*, unsigned);
char* getFunctionName(Function);

void removePrefixFromFunctions(Function*, const unsigned, const char*);
void removeFunctionsWithPrefix(Function**, unsigned*, const char*);
static bool functionIsPrefixed(Function, const char*);

#endif


text:
<?php

namespace AveCqrs\Domain;

/**
 * Interface Identifier
 *
 * @package AveCqrs\Domain
 * @author Averor <averor.dev@gmail.com>
 * @created 07.04.17
 */
interface Identifier
{
    /**
     * @return string
     */
    public function __toString();

    /**
     * @return string
     */
    public function toString();

    /**
     * @return Identifier
     */
    public static function create();

    /**
     * @param string $string
     * @return Identifier
     */
    public static function fromString($string);
}