text:
const templateUrl = require('@components/form/form.partial.html');

function atFormLink (scope, el, attrs, controllers) {
    let formController = controllers[0];
    let form = el[0];

    scope.ns = 'form';
    scope[scope.ns] = { modal: {} };

    formController.init(scope, form);
}

function AtFormController (eventService, strings) {
    let vm = this || {};

    let scope;
    let modal;
    let form;

    vm.components = [];
    vm.state = {
        isValid: false,
        disabled: false,
        value: {},
    };

    vm.init = (_scope_, _form_) => {
        scope = _scope_;
        form = _form_;
        modal = scope[scope.ns].modal;

        vm.state.disabled = scope.state.disabled;

        vm.setListeners();
    };

    vm.register = (category, component, el) => {
        component.category = category;
        component.form = vm.state;

        vm.components.push(component)
    };

    vm.setListeners = () => {
        let listeners = eventService.addListeners([
            [form, 'keypress', vm.submitOnEnter]
        ]);

        scope.$on('$destroy', () => eventService.remove(listeners));
    };

    vm.submitOnEnter = event => {
        if (event.key !== 'Enter' || event.srcElement.type === 'textarea') {
            return;
        }

        event.preventDefault();
        scope.$apply(vm.submit);
    };

    vm.submit = event => {
        if (!vm.state.isValid) {
            return;
        }

        vm.state.disabled = true;

        let data = vm.components
            .filter(component => component.category === 'input')
            .reduce((values, component) => {
                if (!component.state._value) {
                    return values;
                }

                if (component.state._key && typeof component.state._value === 'object') {
                    values[component.state.id] = component.state._value[component.state._key];
                } else if (component.state._group) {
                    values[component.state._key] = values[component.state._key] || {};
                    values[component.state._key][component.state.id] = component.state._value;
                } else {
                    values[component.state.id] = component.state._value;
                }

                return values;
            }, {});

        scope.state.save(data)
            .then(scope.state.onSaveSuccess)
            .catch(err => vm.onSaveError(err))
            .finally(() => vm.state.disabled = false);
    };

    vm.onSaveError = err => {
        let handled;

        if (err.status === 400) {
            handled = vm.handleValidationError(err.data);
        }

        if (err.status === 500) {
            handled = vm.handleUnexpectedError(err);
        }

        if (!handled) {
            let message;
            let title = strings.get('form.SUBMISSION_ERROR_TITLE');
            let preface = strings.get('form.SUBMISSION_ERROR_PREFACE');

            if (typeof err.data === 'object') {
                message = JSON.stringify(err.data);
            } else {
                message = err.data;
            }

            modal.show(title, `${preface}: ${message}`)
        }
    };

    vm.handleUnexpectedError = err => {
        let title = strings.get('form.SUBMISSION_ERROR_TITLE');
        let message = strings.get('form.SUBMISSION_ERROR_MESSAGE');

        modal.show(title, message);

        return true;
    };

    vm.handleValidationError = errors => {
        let errorMessageSet = vm.setValidationMessages(errors);

        if (errorMessageSet) {
            vm.check();
        }

        return errorMessageSet;
    };

    vm.setValidationMessages = (errors, errorSet) => {
        let errorMessageSet = errorSet || false;

        for (let id in errors) {
            if (!Array.isArray(errors[id]) && typeof errors[id] === 'object') {
                errorMessageSet = vm.setValidationMessages(errors[id], errorMessageSet);
                continue;
            }

            vm.components
                .filter(component => component.category === 'input')
                .filter(component => errors[component.state.id])
                .forEach(component => {
                    errorMessageSet = true;

                    component.state._rejected = true;
                    component.state._message = errors[component.state.id].join(' ');
                });
        }

        return errorMessageSet;
    };

    vm.validate = () => {
        let isValid = true;

        for (let i = 0; i < vm.components.length; i++) {
            if (vm.components[i].category !== 'input') {
                continue;
            }

            if (!vm.components[i].state._isValid) {
                isValid = false;
                break;
            }
        }

        return isValid;
    };

    vm.check = () => {
        let isValid = vm.validate();

        if (isValid !== vm.state.isValid) {
            vm.state.isValid = isValid;
        }
    };

    vm.deregisterInputGroup = components => {
        for (let i = 0; i < components.length; i++) {
            for (let j = 0; j < vm.components.length; j++) {
                if (components[i] === vm.components[j].state) {
                    vm.components.splice(j, 1);
                    break;
                }
            }
        }
    };
}

AtFormController.$inject = ['EventService', 'ComponentsStrings'];

function atForm () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        require: ['atForm'],
        templateUrl,
        controller: AtFormController,
        controllerAs: 'vm',
        link: atFormLink,
        scope: {
            state: '='
        }
    };
}

export default atForm;


text: <!DOCTYPE html>

redpajama_set_name: RedPajamaGithub


text:
class PopulateProjectIdInTickets < ActiveRecord::Migration
  class Ticket < ActiveRecord::Base
    belongs_to :survey_response
  end

  def up
    reset_column_information

    Ticket.find_each do |t|
      t.update(project_id: t.survey_response.project_id)
    end
  end

  def down
    reset_column_information

    Ticket.update_all(project_id: nil)
  end

  private

  def reset_column_information
    Ticket.reset_column_information
  end
end


text:
declare module "debug" {

    function d(namespace: string): d.Debugger;

    module d {
        export var log: Function;

        function enable(namespaces: string): void;
        function disable(): void;

        function enabled(namespace: string): boolean;

        export interface Debugger {
            (formatter: any, ...args: any[]): void;

            enabled:   boolean;
            log:       Function;
            namespace: string;
        }
    }

    export = d;

}


text:
package io.undertow.util;

import io.undertow.testutils.category.UnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * @author David M. Lloyd
 */
@Category(UnitTest.class)
public final class HeaderMapTestCase {

    private static final List<HttpString> HTTP_STRING_LIST = Arrays.asList(Headers.CONNECTION, Headers.HOST, Headers.UPGRADE, Headers.CONTENT_MD5, Headers.KEEP_ALIVE, Headers.RESPONSE_AUTH, Headers.CONTENT_DISPOSITION, Headers.DEFLATE, Headers.NEGOTIATE, Headers.USER_AGENT, Headers.REFERER, Headers.TRANSFER_ENCODING, Headers.FROM);

    @Test
    public void testInitial() {
        final HeaderMap headerMap = new HeaderMap();
        assertEquals(0, headerMap.size());
        assertEquals(-1L, headerMap.fastIterate());
        assertFalse(headerMap.iterator().hasNext());
    }

    @Test
    public void testSimple() {
        final HeaderMap headerMap = new HeaderMap();
        headerMap.add(Headers.HOST, "yay.undertow.io");
        assertTrue(headerMap.contains(Headers.HOST));
        assertTrue(headerMap.contains("host"));
        assertEquals(1, headerMap.size());
        assertNotEquals(-1L, headerMap.fastIterate());
        assertEquals(-1L, headerMap.fiNext(headerMap.fastIterate()));
        assertEquals(Headers.HOST, headerMap.fiCurrent(headerMap.fastIterate()).getHeaderName());
        assertEquals("yay.undertow.io", headerMap.getFirst(Headers.HOST));
        assertEquals("yay.undertow.io", headerMap.getLast(Headers.HOST));
        assertEquals("yay.undertow.io", headerMap.get(Headers.HOST, 0));
        headerMap.remove("host");
        assertEquals(0, headerMap.size());
    }

    @Test
    public void testGrowing() {
        final HeaderMap headerMap = new HeaderMap();
        for (HttpString item : HTTP_STRING_LIST) {
            for (int i = 0; i < (item.hashCode() & 7) + 1; i ++)
                headerMap.add(item, "Test value");
        }
        for (HttpString item : HTTP_STRING_LIST) {
            assertTrue(String.format("Missing %s (hash %08x)", item, Integer.valueOf(item.hashCode())), headerMap.contains(item));
            assertNotNull(headerMap.get(item));
            assertEquals((item.hashCode() & 7) + 1, headerMap.get(item).size());
            assertEquals("Test value", headerMap.getFirst(item));
            assertEquals("Test value", headerMap.getLast(item));
        }
        assertEquals(HTTP_STRING_LIST.size(), headerMap.size());
        for (HttpString item : HTTP_STRING_LIST) {
            assertTrue(headerMap.contains(item));
            assertNotNull(headerMap.remove(item));
            assertFalse(headerMap.contains(item));
        }
        assertEquals(0, headerMap.size());
    }

    @Test
    public void testCollision() {
        HeaderMap headerMap = new HeaderMap();
        headerMap.put(new HttpString("Link"), "a");
        headerMap.put(new HttpString("Rest"), "b");
        assertEquals("a", headerMap.getFirst(new HttpString("Link")));
        assertEquals("b", headerMap.getFirst(new HttpString("Rest")));
        assertEquals("a", headerMap.getFirst("Link"));
        assertEquals("b", headerMap.getFirst("Rest"));
    }
}


text:
import timeInWords from 'travis/utils/time-in-words';
import { module, test } from 'qunit';

module('Unit | Utility | time in words', function () {
  test('it translates durations in seconds to abbreviated words', function (assert) {
    assert.equal(timeInWords(59), '59 sec');
    assert.equal(timeInWords(60), '1 min');
    assert.equal(timeInWords(61), '1 min 1 sec');

    assert.equal(timeInWords(3600), '1 hr');
    assert.equal(timeInWords(3660), '1 hr 1 min');
    assert.equal(timeInWords(3661), '1 hr 1 min 1 sec');

    assert.equal(timeInWords(7200), '2 hrs');

    assert.equal(timeInWords(86400 + 1), 'more than 24 hrs', 'expected a duration longer than a day to be truncated');

    assert.equal(timeInWords(-1), '-', 'expected an invalid duration to return just a hyphen');
  });
});


text:
#ifndef JPET_FRAME_H
#define JPET_FRAME_H

#include <TRef.h>
#include "TNamed.h"

/**
 * @brief Parametric class representing database information on a whole mechanical structure frame of the PET setup.
 *
 * The frame consists of one or more layers represented by JPetLayer objects.
 */
class JPetFrame: public TNamed
{
 protected:
  const int fId;
  bool fIsActive;
  std::string fStatus;
  std::string fDescription;
  const int fVersion;
  const int fCreator_id;

 public:

  /// The default constructor sets fId, fVersion, fCreator_id to -1.
  JPetFrame();
  JPetFrame(int id, bool isActive, std::string status, std::string description, int version, int creator_id);

  inline bool operator==(const JPetFrame& frame) { return getId() == frame.getId(); }
  inline bool operator!=(const JPetFrame& frame) { return getId() != frame.getId(); }
  int getId() const { return fId; }
  bool getIsActive() const { return fIsActive; }
  std::string getStatus() const { return fStatus; }
  std::string getDescription() const { return fDescription; }
  int getVersion() const { return fVersion; }
  int getCreator() const { return fCreator_id; }

 private:
  ClassDef(JPetFrame, 1);
};

#endif // JPET_FRAME_H


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <aws/ec2/model/BundleTask.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
  /**
   *
Contains the output of DescribeBundleTasks.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API DescribeBundleTasksResponse
  {
  public:
    DescribeBundleTasksResponse();
    DescribeBundleTasksResponse(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DescribeBundleTasksResponse& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
Information about one or more bundle tasks.

     */
    inline const Aws::Vector<BundleTask>& GetBundleTasks() const{ return m_bundleTasks; }

    /**
     *
Information about one or more bundle tasks.

     */
    inline void SetBundleTasks(const Aws::Vector<BundleTask>& value) { m_bundleTasks = value; }

    /**
     *
Information about one or more bundle tasks.

     */
    inline void SetBundleTasks(Aws::Vector<BundleTask>&& value) { m_bundleTasks = std::move(value); }

    /**
     *
Information about one or more bundle tasks.

     */
    inline DescribeBundleTasksResponse& WithBundleTasks(const Aws::Vector<BundleTask>& value) { SetBundleTasks(value); return *this;}

    /**
     *
Information about one or more bundle tasks.

     */
    inline DescribeBundleTasksResponse& WithBundleTasks(Aws::Vector<BundleTask>&& value) { SetBundleTasks(std::move(value)); return *this;}

    /**
     *
Information about one or more bundle tasks.

     */
    inline DescribeBundleTasksResponse& AddBundleTasks(const BundleTask& value) { m_bundleTasks.push_back(value); return *this; }

    /**
     *
Information about one or more bundle tasks.

     */
    inline DescribeBundleTasksResponse& AddBundleTasks(BundleTask&& value) { m_bundleTasks.push_back(std::move(value)); return *this; }

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DescribeBundleTasksResponse& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DescribeBundleTasksResponse& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:
    Aws::Vector<BundleTask> m_bundleTasks;
    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
.clearfix:after {content: "\0020"; display: block; height: 0;clear: both; visibility: hidden; }
.clearfix {zoom: 1;}
.clear{clear:both;}

/*首页*/
.index{background-color: #10ADA2;color: white;}
.recolor{color: #FE3333;}

/*选择城市*/
.checkadd_choose
.checkadd_choose dl dt{color: #A4A4A4;border-bottom: 1px solid #E3E3E3;line-height: 60px;}
.checkadd_choose dl dd{border-bottom: 1px solid #E3E3E3; line-height: 40px;padding-left: 10px;}

/*网众验房*/
/*免费验房*/
.yanfang_nav ul{margin: 0px;padding: 0px;}
.yanfang_nav ul li{list-style: none;float: left;line-height: 50px;width: 100px;text-align: center;}
.yanfang_nav ul li:nth-child(2){margin-left: 25px;}
 .yanfang_form .yanfang_input{margin: 10px 0px;}
 .yanfang_form .yanfang_input input{height: 40px;width: 100%;border: none;border-bottom: 1px solid #E8E8E8;}


text:
class Wypozyczenie;
class Lista_Wypozyczen
{
public:
	Lista_Wypozyczen();
	virtual ~Lista_Wypozyczen();

	std::vector<Wypozyczenie *> wypozyczenia;
protected:

private:
};

#endif // LISTA_WYPOZYCZEN_H


text:
package org.miszkiewicz.model.smtpapi

sealed trait Filter {
  def name: String
}

case class BCC(enable: Boolean, email: String) extends Filter {
  override val name: String = "bcc"
}

case class BypassListManagement(enable: Boolean) extends Filter {
  override val name: String = "bypass_list_management"
}

case class ClickTrack(enable: Boolean) extends Filter {
  override val name: String = "clicktrack"
}

case class Gravatar(enable: Boolean) extends Filter {
  override val name: String = "gravatar"
}

//case class dkim(use_from: Boolean, domain: String) extends Filter {
case class DKIM(useFrom: Boolean, domain: String) extends Filter {
  override val name: String = "dkim"
}

case class OpenTrack(enable: Boolean, replace: String) extends Filter {
  override val name: String = "opentrack"
}

//case class footer(enable: Boolean, `text/html`: String, `text/plain`: String) extends Filter {
case class Footer(enable: Boolean, textHtml: Option[String] = None, textPlain: Option[String] = None) extends Filter {
  override val name: String = "footer"
}

//case class subscriptiontrack(enable: Boolean, `text/html`: String, `text/plain`: String, replace: String) extends Filter {
case class SubscriptionTrack(enable: Boolean, textHtml: String, textPlain: String, replace: String) extends Filter {
  override val name: String = "subscriptiontrack"
}

//case class templates(enable: Boolean, template_id: String) extends Filter{
case class Templates(enable: Boolean, templateId: String) extends Filter {
  override val name: String = "templates"
}

//case class template(enable: Boolean, `text/html`: String) extends Filter{
case class Template(enable: Boolean, textHtml: String) extends Filter {
  override val name: String = "template"
}

/*case class ganalytics(enable: Boolean,
                      utm_source: String,
                      utm_medium: String,
                      utm_term: String,
                      utm_content: String,
                      utm_campaign: String) extends Filter {*/

case class Ganalytics(enable: Boolean,
                      utmSource: String,
                      utmMedium: String,
                      utmTerm: String,
                      utmContent: String,
                      utmCampaign: String) extends Filter {
  override val name: String = "ganalytics"
}

case class SpamCheck(enable: Boolean, maxScore: Double, url: String) extends Filter {
  override val name: String = "spamcheck"
}


text:
"""
Python Enhancement Proposal (PEP) Reader.
"""

__docformat__ = 'reStructuredText'

from docutils.readers import standalone
from docutils.transforms import peps, references, misc, frontmatter
from docutils.parsers import rst

class Reader(standalone.Reader):

    supported = ('pep',)
    """Contexts this reader supports."""

    settings_spec = (
        'PEP Reader Option Defaults',
        'The --pep-references and --rfc-references options (for the '
        'reStructuredText parser) are on by default.',
        ())

    config_section = 'pep reader'
    config_section_dependencies = ('readers', 'standalone reader')

    def get_transforms(self):
        transforms = standalone.Reader.get_transforms(self)
        # We have PEP-specific frontmatter handling.
        transforms.remove(frontmatter.DocTitle)
        transforms.remove(frontmatter.SectionSubTitle)
        transforms.remove(frontmatter.DocInfo)
        transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes])
        return transforms

    settings_default_overrides = {'pep_references': 1, 'rfc_references': 1}

    inliner_class = rst.states.Inliner

    def __init__(self, parser=None, parser_name=None):
        """`parser` should be ``None``."""
        if parser is None:
            parser = rst.Parser(rfc2822=True, inliner=self.inliner_class())
        standalone.Reader.__init__(self, parser, '')


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="common_google_play_services_install_title" msgid="26645092511305524">"Google Play-Dienste
        installieren"
    </string>
    <string name="common_google_play_services_install_text_phone" msgid="8685301130651051380">"Zur Nutzung dieser App
        sind Google Play-Dienste erforderlich, die auf Ihrem Telefon nicht installiert sind."
    </string>
    <string name="common_google_play_services_install_text_tablet" msgid="1589957570365247855">"Zur Nutzung dieser App
        sind Google Play-Dienste erforderlich, die auf Ihrem Tablet nicht installiert sind."
    </string>
    <string name="common_google_play_services_install_button" msgid="8515591849428043265">"Google Play-Dienste
        installieren"
    </string>
    <string name="common_google_play_services_enable_title" msgid="529078775174559253">"Google Play-Dienste
        aktivieren"
    </string>
    <string name="common_google_play_services_enable_text" msgid="7627896071867667758">"Diese App funktioniert nur, wenn
        Sie die Google Play-Dienste aktivieren."
    </string>
    <string name="common_google_play_services_enable_button" msgid="4181637455539816337">"Google Play-Dienste
        aktivieren"
    </string>
    <string name="common_google_play_services_update_title" msgid="6006316683626838685">"Google Play-Dienste
        aktualisieren"
    </string>
    <string name="common_google_play_services_update_text" msgid="448354684997260580">"Diese App wird nur ausgeführt,
        wenn Sie die Google Play-Dienste aktualisieren."
    </string>
    <string name="common_google_play_services_unknown_issue" msgid="4762332809710093730">"Unbekanntes Problem mit Google
        Play-Diensten"
    </string>
    <string name="common_google_play_services_unsupported_title" msgid="6334768798839376943">"Google Play-Dienste"
    </string>
    <string name="common_google_play_services_unsupported_text" msgid="3542578567569488671">"Google Play-Dienste, auf
        denen einige Ihrer Apps basieren, werden von diesem Gerät nicht unterstützt. Wenden Sie sich für weitere
        Informationen an den Hersteller."
    </string>
    <string name="common_google_play_services_update_button" msgid="8932944190611227642">"Aktualisieren"</string>
    <string name="common_signin_button_text" msgid="9071884888741449141">"Anmelden"</string>
    <string name="common_signin_button_text_long" msgid="2429381841831957106">"Über Google anmelden"</string>
</resources>


text:
package com.pfm.libro;

import java.io.IOException;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.EntityBackground;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.text.TickerText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool;
import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.HorizontalAlign;

import android.content.Intent;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef;
import com.pfm.cuento.R;
import com.pfm.menu.Indice;

public class Page2  extends BaseGameActivity implements IAccelerometerListener {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 800;
	private Camera mCamera;
	private Texture backTex;
	private TextureRegion backTexR;
	private Texture mLetraMeievalTextureM;
	private Font mLetraMeievalFontM;
	private Scene scene;
	private PhysicsWorld mPhysicsWorld;
	private Sound mLecturaSound;
	private Texture mBotonesTex;
	private TextureRegion mBtnDTexR;
	private int centerRX;
	private int centerRY;
	private boolean playingSound;
	private Sprite nextSprite;
	private Sprite previousSprite;
	private int tiempoCrono = 12;
	private Texture mTierraTex;
	private TextureRegion mTierraTexR;
	private Texture mTextureBox;
	private TiledTextureRegion mBoxFaceTextureRegion;
	private Vector2 p1;
	private Vector2 p2;
	private Vector2 d;
	private Body m_bodies[] = new Body[4];
	private Joint m_joints[] = new Joint[8];

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public Engine onLoadEngine() {
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT,new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),this.mCamera);
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);
		engineOptions.setNeedsMusic(true);
	    engineOptions.setNeedsSound(true);
		return new Engine(engineOptions);
	}

	@Override
	public void onLoadResources() {
		Log.v("#PFM#", "Entramos en  onLoadResources()");

		// TEXTURAS
		backTex = new Texture(512, 512,	TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		backTexR = TextureRegionFactory.createFromAsset(this.backTex, this,"gfx/fondolibro.png", 0, 0);

		FontFactory.setAssetBasePath("font/");
		this.mLetraMeievalTextureM = new Texture(256, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mLetraMeievalFontM = FontFactory.createFromAsset(this.mLetraMeievalTextureM,this, "medievalsharp.ttf", 30, true, Color.DKGRAY);

		this.mBotonesTex = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBtnDTexR = TextureRegionFactory.createFromAsset(this.mBotonesTex, this, "gfx/btndere.png", 0, 0);

		this.mTierraTex = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mTierraTexR = TextureRegionFactory.createFromAsset(this.mTierraTex, this, "gfx/tierrasonriendo.png", 0, 0);

		this.mTextureBox = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBoxFaceTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTextureBox, this, "gfx/face_box_tiled.png", 0, 0, 2, 1); // 64x32

		this.mEngine.getTextureManager().loadTextures(backTex, mLetraMeievalTextureM, mBotonesTex, mTierraTex, mTextureBox);
		this.mEngine.getFontManager().loadFonts(this.mLetraMeievalFontM);

		this.enableAccelerometerSensor(this);

		// Carga de música y sonido.
		SoundFactory.setAssetBasePath("mfx/");
		try {
//			this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "mfx/street.mid");
//			this.mMusic.setLooping(true);

			this.mLecturaSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "audiolibro2.ogg");

		} catch (IOException ioe) {
			// No se ha podido cargar el fichero. Realizar las operaciones
			// oportunas.
//			Debug.e(ioe);
		}
	}

	@Override
	public Scene onLoadScene() {
		Log.v("#PFM#", "Entramos en  onLoadScene()");

		this.mEngine.registerUpdateHandler(new FPSLogger());

		scene = new Scene(2);
		scene.setBackground(new EntityBackground(new Sprite(0, 0, CAMERA_WIDTH,CAMERA_HEIGHT, backTexR)));

		nextSprite = new Sprite(CAMERA_WIDTH - 20 - this.mBtnDTexR.getWidth(), CAMERA_HEIGHT - 20 - this.mBtnDTexR.getHeight(), this.mBtnDTexR){
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(pSceneTouchEvent.isActionDown()) {
					next();
				}
				return true;
			}
		};

		previousSprite = new Sprite(20, CAMERA_HEIGHT - 20 - this.mBtnDTexR.getHeight(), this.mBtnDTexR.clone()){
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(pSceneTouchEvent.isActionDown()) {
					previous();
				}
				return true;
			};
		};
		previousSprite.getTextureRegion().setFlippedHorizontal(true);

		final Text text = new TickerText(10, 10, this.mLetraMeievalFontM, "El amuleto conocido como "LA\n" +
																		  "TRIPLE R" fue guardado con \n" +
																		  "cuidado a lo largo de cada una\n" +
																		  "de las civilizaciones por unos \n" +
																		  "pocos privilegiados que lo\n" +
																		  "mantenían en secreto. \n\n" +
																		  "Tierra se sentía alegre, feliz \n" +
																		  "y fuerte gracias a su amuleto \n" +
																		  "y los hombres que la cuidaban.", HorizontalAlign.LEFT, 15);

		text.registerEntityModifier(
				new SequenceEntityModifier(
						new ParallelEntityModifier(
								new AlphaModifier(5, 0.0f, 1.0f),
								new ScaleModifier(10, 0.5f, 1.0f)
						)
				)
		);
		text.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		scene.getLastChild().attachChild(text);

		scene.getLastChild().attachChild(nextSprite);
		scene.getLastChild().attachChild(previousSprite);

		scene.registerTouchArea(nextSprite);
		scene.registerTouchArea(previousSprite);

		this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);

		final Shape right = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
		final Shape left = new Rectangle(0, 0, CAMERA_WIDTH, 2);
		final Shape roof = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
		final Shape ground = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);

		final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

		scene.getFirstChild().attachChild(ground);
		scene.getFirstChild().attachChild(roof);
		scene.getFirstChild().attachChild(left);
		scene.getFirstChild().attachChild(right);

		scene.registerUpdateHandler(this.mPhysicsWorld);

		scene.registerUpdateHandler(new TimerHandler(1.0f, true,new ITimerCallback() {
			@Override
			public void onTimePassed(final TimerHandler pTimerHandler) {
//				Log.v("#PFM#", "Entramos en  onLoadScene() - registerUpdateHandler()");
				actualizarEstados();
			}
		}));

		//Añadimos las físicas
		this.initJoints(scene);

		return scene;
	}

	private void initJoints(final Scene pScene) {
         m_joints = new Joint[8];

		final int centerY = CAMERA_HEIGHT / 2;

		final int spriteWidth = this.mBoxFaceTextureRegion.getTileWidth();
		final int spriteHeight = this.mBoxFaceTextureRegion.getTileHeight();

		final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1.0f, 0.2f, 0.5f);

		centerRX = (CAMERA_WIDTH - this.mBtnDTexR.getWidth()) / 2;
		centerRY = (CAMERA_HEIGHT - this.mBtnDTexR.getHeight())* 2 / 3;

		final Sprite tierraFace = new Sprite(centerRX, centerRY + 50, this.mTierraTexR){
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				return true;
				}
			};

		final Body tierra = PhysicsFactory.createCircleBody(this.mPhysicsWorld, tierraFace, BodyType.DynamicBody, objectFixtureDef);
//		movingFace.setScale(4.0f);
		pScene.getLastChild().attachChild(tierraFace);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(tierraFace, tierra, true, true));

		//****************************************************************
		//CONECTOR 1
		//****************************************************************
		final float anchorFaceX = CAMERA_WIDTH -100;
		final float anchorFaceY = centerY - spriteHeight + 200;

		final AnimatedSprite b1Face = new AnimatedSprite(anchorFaceX, anchorFaceY, this.mBoxFaceTextureRegion);
		final Body b1 = PhysicsFactory.createBoxBody(this.mPhysicsWorld, b1Face, BodyType.StaticBody, objectFixtureDef);
//		b1Face.setVisible(false);
		pScene.getLastChild().attachChild(b1Face);

//        bd.position.set(-5.0f, 5.0f);
//        m_bodies[0] = m_world.createBody(bd);
//        m_bodies[0].createFixture(shape, 5.0f);

		final Line connectionLine = new Line(anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2, anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2);
		pScene.getFirstChild().attachChild(connectionLine);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(b1Face, b1, true, true){
			@Override
			public void onUpdate(final float pSecondsElapsed) {
				super.onUpdate(pSecondsElapsed);
				final Vector2 movingBodyWorldCenter = tierra.getWorldCenter();
				connectionLine.setPosition(connectionLine.getX1(), connectionLine.getY1(), movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
			}
		});
		//****************************************************************

		//****************************************************************
		//CONECTOR 2
		//****************************************************************
		final float anchorFaceX2 = 100;
		final float anchorFaceY2 =  centerY - spriteHeight + 200;

		final AnimatedSprite b2Face = new AnimatedSprite(anchorFaceX2, anchorFaceY2, this.mBoxFaceTextureRegion);
		final Body b2 = PhysicsFactory.createBoxBody(this.mPhysicsWorld, b2Face, BodyType.StaticBody, objectFixtureDef);
//		b2Face.setVisible(false);
		pScene.getLastChild().attachChild(b2Face);

		final Line connectionLine2 = new Line(anchorFaceX2 + spriteWidth / 2, anchorFaceY2 + spriteHeight / 2, anchorFaceX2 + spriteWidth / 2, anchorFaceY2 + spriteHeight / 2);
		pScene.getFirstChild().attachChild(connectionLine2);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(b2Face, b2, true, true){
			@Override
			public void onUpdate(final float pSecondsElapsed) {
				super.onUpdate(pSecondsElapsed);
				final Vector2 movingBodyWorldCenter2 = tierra.getWorldCenter();
				connectionLine2.setPosition(connectionLine2.getX1(), connectionLine2.getY1(), movingBodyWorldCenter2.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter2.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
			}
		});
		//****************************************************************

		//****************************************************************
		//CONECTOR 3
		//****************************************************************
		final float anchorFaceX3 = CAMERA_WIDTH -100;
		final float anchorFaceY3 =  centerY - spriteHeight + 300;

		final AnimatedSprite b3Face = new AnimatedSprite(anchorFaceX3, anchorFaceY3, this.mBoxFaceTextureRegion);
		final Body b3 = PhysicsFactory.createBoxBody(this.mPhysicsWorld, b3Face, BodyType.DynamicBody, objectFixtureDef);
//		b3Face.setVisible(false);
		pScene.getLastChild().attachChild(b3Face);

		final Line connectionLine3 = new Line(anchorFaceX3 + spriteWidth / 2, anchorFaceY3 + spriteHeight / 2, anchorFaceX3 + spriteWidth / 2, anchorFaceY3 + spriteHeight / 2);
		pScene.getFirstChild().attachChild(connectionLine3);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(b3Face, b3, true, true){
			@Override
			public void onUpdate(final float pSecondsElapsed) {
				super.onUpdate(pSecondsElapsed);
				final Vector2 movingBodyWorldCenter3 = tierra.getWorldCenter();
				connectionLine3.setPosition(connectionLine3.getX1(), connectionLine3.getY1(), movingBodyWorldCenter3.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter3.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
			}
		});
		//****************************************************************

		//****************************************************************
		//CONECTOR 4
		//****************************************************************
		final float anchorFaceX4 = 100;
		final float anchorFaceY4 =  centerY - spriteHeight + 300;

		final AnimatedSprite b4Face = new AnimatedSprite(anchorFaceX4, anchorFaceY4, this.mBoxFaceTextureRegion);
		final Body b4 = PhysicsFactory.createBoxBody(this.mPhysicsWorld, b4Face, BodyType.DynamicBody, objectFixtureDef);
//		b4Face.setVisible(false);
		pScene.getLastChild().attachChild(b4Face);

		final Line connectionLine4 = new Line(anchorFaceX4 + spriteWidth / 2, anchorFaceY4 + spriteHeight / 2, anchorFaceX4 + spriteWidth / 2, anchorFaceY4 + spriteHeight / 2);
		pScene.getFirstChild().attachChild(connectionLine4);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(b4Face, b4, true, true){
			@Override
			public void onUpdate(final float pSecondsElapsed) {
				super.onUpdate(pSecondsElapsed);
				final Vector2 movingBodyWorldCenter4 = tierra.getWorldCenter();
				connectionLine4.setPosition(connectionLine4.getX1(), connectionLine4.getY1(), movingBodyWorldCenter4.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter4.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
			}
		});
		//****************************************************************

		//****************************************************************
		//DISTANCE JOINT
		//****************************************************************
		final DistanceJointDef distanceJointDef = new DistanceJointDef();
		//The mass-spring-damper frequency in Hertz.
		distanceJointDef.frequencyHz = 4.0f;
		//AMORTIGUACIÓN: The damping ratio. 0 = no damping, 1 = critical damping.
		distanceJointDef.dampingRatio = 0.5f;
        // La longitud de equilibrio entre los puntos de anclaje.
		distanceJointDef.length = 1.0f;

		distanceJointDef.bodyA = tierra;
		distanceJointDef.bodyB = b1;
		distanceJointDef.localAnchorA.set(-10.0f, 0.0f);
		distanceJointDef.localAnchorB.set(-0.5f, -0.5f);
//		distanceJointDef.localAnchorA.set(tierra.getWorldCenter());
//		distanceJointDef.localAnchorB.set(b1.getWorldCenter().add(-2.0f, -2.0f));
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[0] = mPhysicsWorld.createJoint(distanceJointDef);

		distanceJointDef.bodyA = tierra;
		distanceJointDef.bodyB = b2;
		distanceJointDef.localAnchorA.set(10.0f, 0.0f);
		distanceJointDef.localAnchorB.set(0.5f, -0.5f);
//		distanceJointDef.localAnchorA.set(tierra.getWorldCenter());
//		distanceJointDef.localAnchorB.set(b2.getWorldCenter().add(-2.0f, -2.0f));
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[1] = mPhysicsWorld.createJoint(distanceJointDef);

		distanceJointDef.bodyA = tierra;
		distanceJointDef.bodyB = b3;
		distanceJointDef.localAnchorA.set(10.0f, 20.0f);
		distanceJointDef.localAnchorB.set(0.5f, 0.5f);
//		distanceJointDef.localAnchorA.set(tierra.getWorldCenter());
//		distanceJointDef.localAnchorB.set(b3.getWorldCenter().add(-2.0f, -2.0f));
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[2] = mPhysicsWorld.createJoint(distanceJointDef);

		distanceJointDef.bodyA = tierra;
		distanceJointDef.bodyB = b4;
		distanceJointDef.localAnchorA.set(-10.0f, 20.0f);
		distanceJointDef.localAnchorB.set(-0.5f, 0.5f);
//		distanceJointDef.localAnchorA.set(tierra.getWorldCenter());
//		distanceJointDef.localAnchorB.set(b4.getWorldCenter().add(-2.0f, -2.0f));
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[3] = mPhysicsWorld.createJoint(distanceJointDef);

        //=================================================
        distanceJointDef.bodyA = b1;
		distanceJointDef.bodyB = b2;
		distanceJointDef.localAnchorA.set(0.5f, 0.0f);
		distanceJointDef.localAnchorB.set(-0.5f, 0.0f);
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[4] = mPhysicsWorld.createJoint(distanceJointDef);

        distanceJointDef.bodyA = b2;
		distanceJointDef.bodyB = b3;
		distanceJointDef.localAnchorA.set(0.0f, 0.5f);
		distanceJointDef.localAnchorB.set(0.0f, -0.5f);
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[5] = mPhysicsWorld.createJoint(distanceJointDef);

        distanceJointDef.bodyA = b3;
		distanceJointDef.bodyB = b4;
		distanceJointDef.localAnchorA.set(-0.5f, 0.0f);
		distanceJointDef.localAnchorB.set(0.5f, 0.0f);
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[6] = mPhysicsWorld.createJoint(distanceJointDef);

        distanceJointDef.bodyA = b4;
		distanceJointDef.bodyB = b1;
		distanceJointDef.localAnchorA.set(0.0f, -0.5f);
		distanceJointDef.localAnchorB.set(0.0f, 0.5f);
        p1 = distanceJointDef.bodyA.getWorldPoint(distanceJointDef.localAnchorA);
        p2 = distanceJointDef.bodyB.getWorldPoint(distanceJointDef.localAnchorB);
        d = p2.sub(p1);
        distanceJointDef.length = d.len();
        m_joints[7] = mPhysicsWorld.createJoint(distanceJointDef);

		//****************************************************************

//		mPhysicsWorld.setContactListener(new ContactListener(){
//
//			@Override
//			public void beginContact(Contact contact) {
//				if(contact.getFixtureB().getBody() == movingBody)
//					maza1Sound.play();
//
//				if(contact.getFixtureB().getBody() == movingBody2)
//					maza2Sound.play();
//			}
//
//			@Override
//			public void endContact(Contact contact) {
//				maza1Sound.stop();
//			}
//
//			});
	}

	protected void saltoTierra() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLoadComplete() {

	}

	@Override
	public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) {
		final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX()* -1, pAccelerometerData.getY());
		this.mPhysicsWorld.setGravity(gravity);
		Vector2Pool.recycle(gravity);
	}

	// ===========================================================
	// Methods
	// ===========================================================

	public void next() {
		Log.v("#PFM#", "Entramos en  next()");
		mLecturaSound.stop();
        startActivity(new Intent(Page2.this, Page3.class));
        // Supply a custom animation.  This one will just fade the new
        // activity on top.  Note that we need to also supply an animation
        // (here just doing nothing for the same amount of time) for the
        // old activity to prevent it from going away too soon.
        overridePendingTransition(R.anim.fade, R.anim.hold);
        this.finish();
	}

	public void previous() {
		Log.v("#PFM#", "Entramos en  previous()");
		mLecturaSound.stop();

        // Request the next activity transition (here starting a new one).
		Intent i = new Intent(getBaseContext(), Page1.class);
	    startActivity(i);

        // Supply a custom animation.  This one will just fade the new
        // activity on top.  Note that we need to also supply an animation
        // (here just doing nothing for the same amount of time) for the
        // old activity to prevent it from going away too soon.
        overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
	    this.finish();
	}

	//Método que comprueba si el juego esta cargando, si esta en cuenta atras o si es el finla del juego actualizando los objetos
	public void actualizarEstados(){
		int seg = tiempoCrono -((int) Page2.this.mEngine.getSecondsElapsedTotal()-5);

		if (!isPlayingSound()){
			mLecturaSound.play();
			setPlayingSound(true);
		}else{
			Log.v("#PFM#", "seg:"+seg);

//			if(seg<0&&!nextSprite.isVisible()){
//				nextSprite.setVisible(true);
//				previousSprite.setVisible(true);
//			}
		}
	}

	//Método que lanza un thread con los milisegundos indicados haciendo esperar el flujo de la aplicación
	public void dormir(int miliSeg) {
		try {
			Thread.sleep(miliSeg);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.indice:
			Intent settings = new Intent(getBaseContext(),Indice.class);
			startActivity(settings);
			finish();
			return false;
		case R.id.acercade:
			  Toast.makeText(Page2.this, getString(R.string.TituloAlumno) + "\n" + getString(R.string.nombreAlumno)+ "\n" + getString(R.string.universidadAlumno) , Toast.LENGTH_SHORT).show();
			  return true;
		case R.id.salir:
			this.finish();
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
	public void setPlayingSound(boolean playingSound) {
		this.playingSound = playingSound;
	}

	public boolean isPlayingSound() {
		return playingSound;
	}
}


text:
import os
import traceback

from telemetry import story
from telemetry.internal.results import base_test_results_unittest
from telemetry.internal.results import gtest_progress_reporter
from telemetry.internal.results import page_test_results
from telemetry import page as page_module
from telemetry.testing import fakes
from telemetry.testing import stream
from telemetry.value import failure
from telemetry.value import skip

_GROUPING_KEY_DEFAULT = {'1': '2'}

def _MakeStorySet():
  story_set = story.StorySet(base_dir=os.path.dirname(__file__))
  story_set.AddStory(
      page_module.Page('http://www.foo.com/', story_set, story_set.base_dir,
                       name='http://www.foo.com/'))
  story_set.AddStory(
      page_module.Page('http://www.bar.com/', story_set, story_set.base_dir,
                       name='http://www.bar.com/'))
  story_set.AddStory(
      page_module.Page('http://www.baz.com/', story_set, story_set.base_dir,
                       name='http://www.baz.com/'))
  story_set.AddStory(
      page_module.Page('http://www.roz.com/', story_set, story_set.base_dir,
                       name='http://www.roz.com/'))
  story_set.AddStory(
      page_module.Page('http://www.fus.com/', story_set, story_set.base_dir,
                       grouping_keys=_GROUPING_KEY_DEFAULT,
                       name='http://www.fus.com/'))
  story_set.AddStory(
      page_module.Page('http://www.ro.com/', story_set, story_set.base_dir,
                       grouping_keys=_GROUPING_KEY_DEFAULT,
                       name='http://www.ro.com/'))
  return story_set

class GTestProgressReporterTest(
    base_test_results_unittest.BaseTestResultsUnittest):

  def setUp(self):
    super(GTestProgressReporterTest, self).setUp()
    self._fake_timer = fakes.FakeTimer(gtest_progress_reporter)

    self._output_stream = stream.TestOutputStream()
    self._reporter = gtest_progress_reporter.GTestProgressReporter(
        self._output_stream)

  def tearDown(self):
    self._fake_timer.Restore()

  def testSingleSuccessPage(self):
    test_story_set = _MakeStorySet()

    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[0])
    self._fake_timer.SetTime(0.007)
    results.DidRunPage(test_story_set.stories[0])

    results.PrintSummary()
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '[       OK ] http://www.foo.com/ (7 ms)\n'
                '[  PASSED  ] 1 test.\n\n')
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testSingleSuccessPageWithGroupingKeys(self):
    test_story_set = _MakeStorySet()

    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[4])
    self._fake_timer.SetTime(0.007)
    results.DidRunPage(test_story_set.stories[4])

    results.PrintSummary()
    expected = ("[ RUN      ] http://www.fus.com/@{'1': '2'}\n"
                "[       OK ] http://www.fus.com/@{'1': '2'} (7 ms)\n"
                "[  PASSED  ] 1 test.\n\n")
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testSingleFailedPage(self):
    test_story_set = _MakeStorySet()

    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[0])
    exc_info = self.CreateException()
    results.AddValue(failure.FailureValue(test_story_set.stories[0], exc_info))
    results.DidRunPage(test_story_set.stories[0])

    results.PrintSummary()
    exception_trace = ''.join(traceback.format_exception(*exc_info))
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '%s\n'
                '[  FAILED  ] http://www.foo.com/ (0 ms)\n'
                '[  PASSED  ] 0 tests.\n'
                '[  FAILED  ] 1 test, listed below:\n'
                '[  FAILED  ]  http://www.foo.com/\n\n'
                '1 FAILED TEST\n\n' % exception_trace)
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testSingleFailedPageWithGroupingKeys(self):
    test_story_set = _MakeStorySet()

    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[4])
    exc_info = self.CreateException()
    results.AddValue(failure.FailureValue(test_story_set.stories[4], exc_info))
    results.DidRunPage(test_story_set.stories[4])

    results.PrintSummary()
    exception_trace = ''.join(traceback.format_exception(*exc_info))
    expected = ("[ RUN      ] http://www.fus.com/@{'1': '2'}\n"
                "%s\n"
                "[  FAILED  ] http://www.fus.com/@{'1': '2'} (0 ms)\n"
                "[  PASSED  ] 0 tests.\n"
                "[  FAILED  ] 1 test, listed below:\n"
                "[  FAILED  ]  http://www.fus.com/@{'1': '2'}\n\n"
                "1 FAILED TEST\n\n" % exception_trace)
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testSingleSkippedPage(self):
    test_story_set = _MakeStorySet()
    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[0])
    self._fake_timer.SetTime(0.007)
    results.AddValue(skip.SkipValue(test_story_set.stories[0],
        'Page skipped for testing reason'))
    results.DidRunPage(test_story_set.stories[0])

    results.PrintSummary()
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '===== SKIPPING TEST http://www.foo.com/:'
                ' Page skipped for testing reason =====\n'
                '[       OK ] http://www.foo.com/ (7 ms)\n'
                '[  PASSED  ] 1 test.\n\n')
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testPassAndFailedPages(self):
    test_story_set = _MakeStorySet()
    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    exc_info = self.CreateException()

    results.WillRunPage(test_story_set.stories[0])
    self._fake_timer.SetTime(0.007)
    results.DidRunPage(test_story_set.stories[0])

    results.WillRunPage(test_story_set.stories[1])
    self._fake_timer.SetTime(0.009)
    results.AddValue(failure.FailureValue(test_story_set.stories[1], exc_info))
    results.DidRunPage(test_story_set.stories[1])

    results.WillRunPage(test_story_set.stories[2])
    self._fake_timer.SetTime(0.015)
    results.AddValue(failure.FailureValue(test_story_set.stories[2], exc_info))
    results.DidRunPage(test_story_set.stories[2])

    results.WillRunPage(test_story_set.stories[3])
    self._fake_timer.SetTime(0.020)
    results.DidRunPage(test_story_set.stories[3])

    results.WillRunPage(test_story_set.stories[4])
    self._fake_timer.SetTime(0.025)
    results.DidRunPage(test_story_set.stories[4])

    results.WillRunPage(test_story_set.stories[5])
    self._fake_timer.SetTime(0.030)
    results.AddValue(failure.FailureValue(test_story_set.stories[5], exc_info))
    results.DidRunPage(test_story_set.stories[5])

    results.PrintSummary()
    exception_trace = ''.join(traceback.format_exception(*exc_info))
    expected = ("[ RUN      ] http://www.foo.com/\n"
                "[       OK ] http://www.foo.com/ (7 ms)\n"
                "[ RUN      ] http://www.bar.com/\n"
                "%s\n"
                "[  FAILED  ] http://www.bar.com/ (2 ms)\n"
                "[ RUN      ] http://www.baz.com/\n"
                "%s\n"
                "[  FAILED  ] http://www.baz.com/ (6 ms)\n"
                "[ RUN      ] http://www.roz.com/\n"
                "[       OK ] http://www.roz.com/ (5 ms)\n"
                "[ RUN      ] http://www.fus.com/@{'1': '2'}\n"
                "[       OK ] http://www.fus.com/@{'1': '2'} (5 ms)\n"
                "[ RUN      ] http://www.ro.com/@{'1': '2'}\n"
                "%s\n"
                "[  FAILED  ] http://www.ro.com/@{'1': '2'} (5 ms)\n"
                "[  PASSED  ] 3 tests.\n"
                "[  FAILED  ] 3 tests, listed below:\n"
                "[  FAILED  ]  http://www.bar.com/\n"
                "[  FAILED  ]  http://www.baz.com/\n"
                "[  FAILED  ]  http://www.ro.com/@{'1': '2'}\n\n"
                "3 FAILED TESTS\n\n"
                % (exception_trace, exception_trace, exception_trace))
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

  def testStreamingResults(self):
    test_story_set = _MakeStorySet()
    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    exc_info = self.CreateException()

    results.WillRunPage(test_story_set.stories[0])
    self._fake_timer.SetTime(0.007)
    results.DidRunPage(test_story_set.stories[0])
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '[       OK ] http://www.foo.com/ (7 ms)\n')
    self.assertEquals(expected, ''.join(self._output_stream.output_data))

    results.WillRunPage(test_story_set.stories[1])
    self._fake_timer.SetTime(0.009)
    exception_trace = ''.join(traceback.format_exception(*exc_info))
    results.AddValue(failure.FailureValue(test_story_set.stories[1], exc_info))
    results.DidRunPage(test_story_set.stories[1])
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '[       OK ] http://www.foo.com/ (7 ms)\n'
                '[ RUN      ] http://www.bar.com/\n'
                '%s\n'
                '[  FAILED  ] http://www.bar.com/ (2 ms)\n' % exception_trace)

  def testOutputSkipInformation(self):
    test_story_set = _MakeStorySet()
    self._reporter = gtest_progress_reporter.GTestProgressReporter(
        self._output_stream, output_skipped_tests_summary=True)
    results = page_test_results.PageTestResults(
        progress_reporter=self._reporter)
    results.WillRunPage(test_story_set.stories[0])
    self._fake_timer.SetTime(0.007)
    results.AddValue(skip.SkipValue(test_story_set.stories[0],
        'Page skipped for testing reason'))
    results.DidRunPage(test_story_set.stories[0])

    results.PrintSummary()
    expected = ('[ RUN      ] http://www.foo.com/\n'
                '===== SKIPPING TEST http://www.foo.com/:'
                ' Page skipped for testing reason =====\n'
                '[       OK ] http://www.foo.com/ (7 ms)\n'
                '[  PASSED  ] 1 test.\n'
                '\n'
                'Skipped pages:\n'
                'http://www.foo.com/\n'
                '\n')
    self.assertEquals(expected, ''.join(self._output_stream.output_data))


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::EnsEMBL::CoordSystem

=head1 SYNOPSIS

  my $db = Bio::EnsEMBL::DBSQL::DBAdaptor->new(...);

  my $csa = $db->get_CoordSystemAdaptor();

  #
  # Get all coord systems in the database:
  #
  foreach my $cs ( @{ $csa->fetch_all() } ) {
    my $str = join ':', $cs->name(), $cs->version(), $cs->dbID();
    print "$str\n";
  }

=head1 DESCRIPTION

This is a simple object which contains a few coordinate system attributes:
name, internal identifier, version.  A coordinate system is uniquely defined
by its name and version.  A version of a coordinate system applies to all
sequences within a coordinate system.  This should not be confused with
individual sequence versions.

Take for example the Human assembly.  The version 'NCBI33' applies to
to all chromosomes in the NCBI33 assembly (that is the entire 'chromosome'
coordinate system).  The 'clone' coordinate system in the same database would
have no version however.  Although the clone sequences have their own sequence
versions, there is no version which applies to the entire set of clones.

Coordinate system objects are immutable. Their name and version, and other
attributes may not be altered after they are created.

=head1 METHODS

=cut

use strict;
use warnings;

package Bio::EnsEMBL::CoordSystem;

use Bio::EnsEMBL::Storable;

use Bio::EnsEMBL::Utils::Argument  qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw);

use vars qw(@ISA);

@ISA = qw(Bio::EnsEMBL::Storable);

=head2 new

  Arg [..]   : List of named arguments:
               -NAME      - The name of the coordinate system
               -VERSION   - (optional) The version of the coordinate system.
                            Note that if the version passed in is undefined,
                            it will be set to the empty string in the
                            resulting CoordSystem object.
               -RANK      - The rank of the coordinate system. The highest
                            level coordinate system should have rank 1, the
                            second highest rank 2 and so on.  An example of
                            a high level coordinate system is 'chromosome' an
                            example of a lower level coordinate system is
                            'clone'.
               -TOP_LEVEL - (optional) Sets whether this is a top-level coord
                            system. Default = 0. This should only be set to
                            true if you are creating an artificial toplevel
                            coordsystem by the name of 'toplevel'
               -SEQUENCE_LEVEL - (optional) Sets whether this is a sequence
                            level coordinate system. Default = 0
               -DEFAULT   - (optional)
                            Whether this is the default version of the
                            coordinate systems of this name. Default = 0
               -DBID      - (optional) The internal identifier of this
                             coordinate system
               -ADAPTOR   - (optional) The adaptor which provides database
                            interaction for this object
               -ALIAS_TO  - (optional) Sets an alias for a coordsystem. If set
                            it should only be set to 'chromosome'
  Example    : $cs = Bio::EnsEMBL::CoordSystem->new(-NAME    => 'chromosome',
                                                    -VERSION => 'NCBI33',
                                                    -RANK    => 1,
                                                    -DBID    => 1,
                                                    -ADAPTOR => adaptor,
                                                    -DEFAULT => 1,
                                                    -SEQUENCE_LEVEL => 0);
  Description: Creates a new CoordSystem object representing a coordinate
               system.
  Returntype : Bio::EnsEMBL::CoordSystem
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub new {
  my $caller = shift;
  my $class = ref($caller) || $caller;

  my $self = $class->SUPER::new(@_);

  my ( $name, $version, $top_level, $sequence_level, $default, $rank, $alias_to ) =
    rearrange( [ 'NAME',      'VERSION',
                 'TOP_LEVEL', 'SEQUENCE_LEVEL',
                 'DEFAULT',   'RANK',
                 'ALIAS_TO' ],
               @_ );

  $top_level      = ($top_level)      ? 1 : 0;
  $sequence_level = ($sequence_level) ? 1 : 0;
  $default        = ($default)        ? 1 : 0;
  $rank ||= 0;

  if ( $top_level == 1 ) {
    if ( $rank != 0 ) {
      throw('RANK argument must be 0 if TOP_LEVEL is 1');
    }

    if ( defined($name) ) {
      if ( $name ne 'toplevel' ) {
        throw('The NAME argument must be "toplevel" if TOP_LEVEL is 1');
      }
    } else {
      $name = 'toplevel';
    }

    if ( $sequence_level == 1 ) {
      throw("SEQUENCE_LEVEL argument must be 0 if TOP_LEVEL is 1");
    }

    $default = 0;

  } else {

    if ( $rank == 0 ) {
      throw("RANK argument must be non-zero unless TOP_LEVEL is 1");
    }

    if ( !defined($name) ) {
      throw('The NAME argument is required');
    } elsif ( $name eq 'toplevel' ) {
      throw(   "Cannot name coord system 'toplevel' "
             . "unless TOP_LEVEL is 1" );
    }

  }

  if ( $rank !~ /^\d+$/ ) {
    throw('The RANK argument must be a positive integer');
  }

  if ( defined($alias_to) ) {
    throw("The ALIAS_TO argument can only be defined as 'chromosome'") unless $alias_to eq "chromosome";
  }

  $self->{'version'}        = $version;
  $self->{'name'}           = $name;
  $self->{'top_level'}      = $top_level;
  $self->{'sequence_level'} = $sequence_level;
  $self->{'default'}        = $default;
  $self->{'rank'}           = $rank;
  $self->{'alias_to'}       = $alias_to;

  return $self;
} ## end sub new

=head2 name

  Arg [1]    : (optional) string $name
  Example    : print $coord_system->name();
  Description: Getter for the name of this coordinate system
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub name {
  my $self = shift;
  return $self->{'name'};
}

=head2 version

  Arg [1]    : none
  Example    : print $coord->version();
  Description: Getter for the version of this coordinate system.  This
               will return an empty string if no version is defined for this
               coordinate system.
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub version {
  my $self = shift;

  return '' unless defined $self->{'version'};
  return $self->{'version'};
}

=head2 species

  Arg [1]    : none
  Example    : print $coord->species();
  Description: Shortcut method to get the species this CoordSystem refers to.
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub species {
  my $self = shift;
  return $self->adaptor->db->species;
}

=head2 equals

  Arg [1]    : Bio::EnsEMBL::CoordSystem $cs
               The coord system to compare to for equality.
  Example    : if($coord_sys->equals($other_coord_sys)) { ... }
  Description: Compares 2 coordinate systems and returns true if they are
               equivalent.  The definition of equivalent is sharing the same
               name and version.
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub equals {
  my $self = shift;
  my $cs = shift;

  if(!$cs || !ref($cs) || !$cs->isa('Bio::EnsEMBL::CoordSystem')) {
    if ($cs->isa('Bio::EnsEMBL::ExternalData::DAS::CoordSystem')) {
      return $cs->equals($self);
    }
    throw('Argument must be a CoordSystem');
  }

  if($self->version() eq $cs->version() && $self->{'name'} eq $cs->name()) {
    return 1;
  }

  return 0;
}

=head2 is_top_level

  Arg [1]    : none
  Example    : if($coord_sys->is_top_level()) { ... }
  Description: Returns true if this is the toplevel pseudo coordinate system.
               The toplevel coordinate system is not a real coordinate system
               which is stored in the database, but it is a placeholder that
               can be used to request transformations or retrievals to/from
               the highest defined coordinate system in a given region.
  Returntype : 1 or 0
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub is_top_level {
  my $self = shift;
  return $self->{'top_level'};
}

=head2 is_sequence_level

  Arg [1]    : none
  Example    : if($coord_sys->is_sequence_level()) { ... }
  Description: Returns true if this is a sequence level coordinate system
  Returntype : 1 or 0
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub is_sequence_level {
  my $self = shift;
  return $self->{'sequence_level'};
}

=head2 is_default

  Arg [1]    : none
  Example    : if($coord_sys->is_default()) { ... }
  Description: Returns true if this coordinate system is the default
               version of the coordinate system of this name.
  Returntype : 1 or 0
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub is_default {
  my $self = shift;
  return $self->{'default'};
}

=head2 rank

  Arg [1]    : none
  Example    : if($cs1->rank() < $cs2->rank()) {
                 print $cs1->name(), " is a higher level coord system than",
                       $cs2->name(), "\n";
               }
  Description: Returns the rank of this coordinate system.  A lower number
               is a higher coordinate system.  The highest level coordinate
               system has a rank of 1 (e.g. 'chromosome').  The toplevel
               pseudo coordinate system has a rank of 0.
  Returntype : int
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub rank {
  my $self = shift;
  return $self->{'rank'};
}

=head2 alias_to

  Arg [1]    : string
  Example    : $coord->alias_to('chromosome');
  Description: Getter/Setter for the alias of this coordinate system.
  Returntype : Bio::EnsEMBL::CoordSystem
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub alias_to {
  my ($self, $alias_to) = @_;
  if (defined($alias_to)) {
    throw("The alias can only be set to 'chromosome'") unless $alias_to eq "chromosome";
  }
  $self->{'alias_to'} = $alias_to if defined $alias_to;
  return $self->{'alias_to'};
}

1;


text:
using Newtonsoft.Json;
using Simple.AspNetCore.Identity.DocumentDb.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Simple.AspNetCore.Identity.DocumentDb
{
    static class Extentions
    {

        /// <summary>
        /// Nots the null.
        /// </summary>
        /// <param name="thisObject">The this object.</param>
        /// <param name="paramName">Name of the parameter.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void NotNull(this object thisObject, string paramName)
        {
            if (thisObject == null) throw new ArgumentNullException(paramName);
        }

        /// <summary>
        /// Nots the null or empty.
        /// </summary>
        /// <param name="thisString">The this string.</param>
        /// <param name="paramName">Name of the parameter.</param>
        /// <param name="message">The message.</param>
        /// <exception cref="ArgumentException"></exception>
        public static void NotNullOrEmpty(this string thisString, string paramName, string message)
        {
            if (string.IsNullOrEmpty(thisString)) throw new ArgumentException(message, paramName);
        }

        /// <summary>
        /// Clones the specified this object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="thisObject">The this object.</param>
        /// <returns></returns>
        public static T Clone<T>(this T thisObject) where T: class
        {
            if (thisObject == null) return null;
            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(thisObject));
        }

        private static DateTime Date19700101 = new DateTime(1970, 1, 1);
        /// <summary>
        /// To the epoch.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <returns></returns>
        public static int ToEpoch(this DateTime date)
        {
            if (date < Date19700101)
                return int.MinValue;

            return (int)(date - Date19700101).TotalSeconds;
        }

        /// <summary>
        /// Converts the <see cref="IdentityUserClaim"/> to <see cref="Claim"/>
        /// </summary>
        /// <param name="thisClaim">The <see cref="IdentityUserClaim"/> to be converted</param>
        /// <returns>Returns the newly created <see cref="Claim"/></returns>
        public static Claim ToClaim(this IdentityUserClaim thisClaim)
        {
            return new Claim(thisClaim.Type, thisClaim.Value, thisClaim.ValueType, thisClaim.Issuer, thisClaim.OriginalIssuer);
        }

        /// <summary>
        /// Converts the <see cref="Claim"/> to <see cref="IdentityUserClaim"/>
        /// </summary>
        /// <param name="thisClaim">The <see cref="IdentityUserClaim"/> to be converted</param>
        /// <returns>Returns the newly created <see cref="IdentityUserClaim"/></returns>
        public static IdentityUserClaim ToClaim(this Claim thisClaim)
        {
            return new IdentityUserClaim
            {
                Type = thisClaim.Type,
                Value = thisClaim.Value,
                ValueType = thisClaim.ValueType,
                Issuer = thisClaim.Issuer,
                OriginalIssuer = thisClaim.OriginalIssuer
            };
        }
    }

}


text:
package monopoly.web.util;

import java.util.concurrent.LinkedBlockingQueue;

public class MQ<T> implements IMQ<T> {

	private final LinkedBlockingQueue<T> q = new LinkedBlockingQueue<T>();

	@Override
	public T getNextRequest() {
		try {
			return q.take();
		} catch (InterruptedException e) {
			return null;
		}
	}

	@Override
	public void submitRequest(T req) {
		q.add(req);
	}

}


text:
<?php
namespace Bun\Form\Config;

use Bun\Core\Config\AbstractConfig;

/**
 * Class ContainerConfig
 *
 * @package Bun\Form\Config
 */
class ContainerConfig extends AbstractConfig
{
    protected $name = 'container';

    protected $config = array(
        'bun.form.builder' => array(
            'class' => 'Bun\\Form\\FormBuilder'
        )
    );
}


text:
<?php

namespace Phoenix\Core;

/**
 * Root configurator object.
 *
 * @version 1.3
 * @author MPI
 *
 */
abstract class Configurator {

    /**
     * Configurator constructor.
     *
     * @return void
     */
    public function __construct() {
    }

    /**
     * Run all required operations in Configurator to setup App.
     *
     * @return void
     */
    public function run() {
        $this->registerConfiguration();
        $this->registerRoutes();
        $this->registerNoticeExceptions();
        $this->registerWarningExceptions();
        $this->registerFailureExceptions();
        $this->disableRegistrations();
    }

    /**
     * Disable registration in all required objects (Config, Router,
     * Notice+Warning+Failure Exceptions).
     * Will be executed after all
     * register methods in this class.
     *
     * @return void
     */
    protected abstract function disableRegistrations();

    /**
     * Register App Configuration into Config object.
     *
     * @return void
     */
    protected abstract function registerConfiguration();

    /**
     * Register Routes into Router object.
     *
     * @return void
     */
    protected abstract function registerRoutes();

    /**
     * Register NoticeExceptions defined in App into NoticeException object.
     *
     * @return void
     */
    protected abstract function registerNoticeExceptions();

    /**
     * Register WarningExceptions defined in App into WarningException object.
     *
     * @return void
     */
    protected abstract function registerWarningExceptions();

    /**
     * Register FailureExceptions defined in App into FailureException object.
     *
     * @return void
     */
    protected abstract function registerFailureExceptions();
}
?>


text: require 'graphql/relay/range_add'


text:
promise_test(async t => {
  let imgElement = document.createElement('img');
  let loadPromise = new Promise(r => imgElement.onload = r);
  imgElement.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
  await loadPromise;
  verifyTimestampRequiredToConstructFrame(imgElement);
}, 'Test that timestamp is required when constructing VideoFrame from HTMLImageElement');

promise_test(async t => {
    let svgImageElement = document.createElementNS('http://www.w3.org/2000/svg','image');
    let loadPromise = new Promise(r => svgImageElement.onload = r);
    svgImageElement.setAttributeNS('http://www.w3.org/1999/xlink','href','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
    await loadPromise;
    verifyTimestampRequiredToConstructFrame(svgImageElement);
}, 'Test that timestamp is required when constructing VideoFrame from SVGImageElement');

promise_test(async t => {
  verifyTimestampRequiredToConstructFrame(document.createElement('canvas'))
}, 'Test that timeamp is required when constructing VideoFrame from HTMLCanvasElement');


text:
namespace InControl
{
	// D-Pad doesn't work.
	//
	// @cond nodoc
	[AutoDiscover]
	public class NykoPlayPadProAmazonProfile : UnityInputDeviceProfile
	{
		public NykoPlayPadProAmazonProfile()
		{
			Name = "Nyko PlayPad Pro";
			Meta = "Nyko PlayPad Pro on Amazon Fire TV";

			DeviceClass = InputDeviceClass.Controller;

			IncludePlatforms = new[] {
				"Amazon AFT"
			};

			JoystickNames = new[] {
				"NYKO PLAYPAD PRO",
			};

			ButtonMappings = new[] {
				new InputControlMapping {
					Handle = "A",
					Target = InputControlType.Action1,
					Source = Button0
				},
				new InputControlMapping {
					Handle = "B",
					Target = InputControlType.Action2,
					Source = Button1
				},
				new InputControlMapping {
					Handle = "X",
					Target = InputControlType.Action3,
					Source = Button2
				},
				new InputControlMapping {
					Handle = "Y",
					Target = InputControlType.Action4,
					Source = Button3
				},
				new InputControlMapping {
					Handle = "Left Bumper",
					Target = InputControlType.LeftBumper,
					Source = Button4
				},
				new InputControlMapping {
					Handle = "Right Bumper",
					Target = InputControlType.RightBumper,
					Source = Button5
				},
				new InputControlMapping {
					Handle = "Left Stick Button",
					Target = InputControlType.LeftStickButton,
					Source = Button8
				},
				new InputControlMapping {
					Handle = "Right Stick Button",
					Target = InputControlType.RightStickButton,
					Source = Button9
				},
				new InputControlMapping {
					Handle = "Back",
					Target = InputControlType.Back,
					Source = EscapeKey
				},
				new InputControlMapping {
					Handle = "Menu",
					Target = InputControlType.Menu,
					Source = Button10
				}
			};

			AnalogMappings = new[] {
				LeftStickLeftMapping( Analog0 ),
				LeftStickRightMapping( Analog0 ),
				LeftStickUpMapping( Analog1 ),
				LeftStickDownMapping( Analog1 ),

				RightStickLeftMapping( Analog2 ),
				RightStickRightMapping( Analog2 ),
				RightStickUpMapping( Analog3 ),
				RightStickDownMapping( Analog3 ),

				// DPadLeftMapping( Analog4 ),
				// DPadRightMapping( Analog4 ),
				// DPadUpMapping( Analog5 ),
				// DPadDownMapping( Analog5 ),

				new InputControlMapping {
					Handle = "Left Trigger",
					Target = InputControlType.LeftTrigger,
					Source = Analog12,
				},
				new InputControlMapping {
					Handle = "Right Trigger",
					Target = InputControlType.RightTrigger,
					Source = Analog11,
				}
			};
		}
	}
	// @endcond
}


text:
using namespace Rcpp;

// rcpp_partition
Rcpp::NumericVector rcpp_partition(const arma::mat& neighbors, const Rcpp::NumericVector& centers);
RcppExport SEXP _gbdcd_rcpp_partition(SEXP neighborsSEXP, SEXP centersSEXP) {
BEGIN_RCPP
    Rcpp::RObject rcpp_result_gen;
    Rcpp::RNGScope rcpp_rngScope_gen;
    Rcpp::traits::input_parameter< const arma::mat& >::type neighbors(neighborsSEXP);
    Rcpp::traits::input_parameter< const Rcpp::NumericVector& >::type centers(centersSEXP);
    rcpp_result_gen = Rcpp::wrap(rcpp_partition(neighbors, centers));
    return rcpp_result_gen;
END_RCPP
}
// rcpp_freqmatrix
Rcpp::NumericMatrix rcpp_freqmatrix(const Rcpp::NumericVector& partitions);
RcppExport SEXP _gbdcd_rcpp_freqmatrix(SEXP partitionsSEXP) {
BEGIN_RCPP
    Rcpp::RObject rcpp_result_gen;
    Rcpp::RNGScope rcpp_rngScope_gen;
    Rcpp::traits::input_parameter< const Rcpp::NumericVector& >::type partitions(partitionsSEXP);
    rcpp_result_gen = Rcpp::wrap(rcpp_freqmatrix(partitions));
    return rcpp_result_gen;
END_RCPP
}

static const R_CallMethodDef CallEntries[] = {
    {"_gbdcd_rcpp_partition", (DL_FUNC) &_gbdcd_rcpp_partition, 2},
    {"_gbdcd_rcpp_freqmatrix", (DL_FUNC) &_gbdcd_rcpp_freqmatrix, 1},
    {NULL, NULL, 0}
};

RcppExport void R_init_gbdcd(DllInfo *dll) {
    R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
}


text:
{-# OPTIONS_GHC -XKindSignatures #-}

{-|
The 'Knot3' instrument is used for knot tying across passes. Knot
tying is a technique sometimes used in lazy functional programming, in
which the definition of a variable depends on its own value. The lazy
programming technique depends on an implicit two-pass ordering of the
computation. For example, the classic repmin program produces a pair
of outputs - a tree and an integer - and there is an implicit two-pass
ordering where the integer is computed during the first pass and the
tree during the second. The 'Knot3' instrument allows the same
technique to be applied, but the ordering of the passes is managed
explicitly by the "Control.Monad.MultiPass" library, rather than
implicitly by lazy evalution.
-}

module Control.Monad.MultiPass.Instrument.Knot3
  ( Knot3
  , knot3
  )
where

import Control.Monad ( void )
import Control.Monad.ST2
import Control.Monad.MultiPass
import Control.Monad.MultiPass.ThreadContext.CounterTC

-- | Abstract datatype for the instrument.
data Knot3 (a :: *) r w (p1 :: * -> *) p2 p3 tc
  = Knot3
      { knot3Internal :: !(forall b.
          (p3 a -> MultiPass r w tc (p2 a, b)) -> MultiPass r w tc b)
      }

-- | Tie the knot for the supplied function.
knot3
  :: (Monad p1, Monad p2, Monad p3)
  => Knot3 a r w p1 p2 p3 tc
  -> (p3 a -> MultiPass r w tc (p2 a, b))
  -> MultiPass r w tc b
knot3 =
  knot3Internal

newtype Buffer r w a
  = Buffer (ST2Array r w Int a)  -- Storage array

instance Instrument tc () () (Knot3 a r w Off Off Off tc) where
  createInstrument _ _ () =
    wrapInstrument $ Knot3 $ \f ->
    do (Off, x) <- f Off
       return x

-- Pass 1 of the Knot3 instrument. This pass counts the number of
-- times knot3 is used, so that an array can be allocated to store the
-- values during the second pass.
instance Instrument tc (CounterTC1 Int r) ()
                    (Knot3 a r w On Off Off tc) where
  createInstrument _ updateCtx () =
    wrapInstrument $ Knot3 $ \f ->
    do void $ mkMultiPass $ updateCtx incrCounterTC1
       (Off, x) <- f Off
       return x

instance Instrument tc (CounterTC2 Int r) (Buffer r w a)
                    (Knot3 a r w On On Off tc) where
  createInstrument st2ToMP updateCtx (Buffer xs) =
    wrapInstrument $ Knot3 $ \f ->
    do counter <- mkMultiPass $ updateCtx incrCounterTC2
       let k = counterVal2 counter
       (On v, x) <- f Off
       mkMultiPass $ st2ToMP $ writeST2Array xs k v
       return x

instance Instrument tc (CounterTC2 Int r) (Buffer r w a)
                    (Knot3 a r w On On On tc) where
  createInstrument st2ToMP updateCtx (Buffer xs) =
    wrapInstrument $ Knot3 $ \f ->
    do counter <- mkMultiPass $ updateCtx incrCounterTC2
       let k = counterVal2 counter
       v <- mkMultiPass $ st2ToMP $ readST2Array xs k
       (_,x) <- f (On v)
       return x

-- This instrument never needs to back-track.
instance BackTrack r w tc (Buffer r w a)

instance NextGlobalContext r w (CounterTC1 Int r)
                           () (Buffer r w a) where
  nextGlobalContext _ _ counter () =
    let n = counterVal1 counter in
    do xs <- newST2Array_ (0, n-1)
       return (Buffer xs)

instance NextGlobalContext r w tc (Buffer r w a)
                           (Buffer r w a) where
  nextGlobalContext _ _ _ (Buffer xs) = return (Buffer xs)


text:
curl --data @Kwafer.avsc 'http://localhost:8080/putschema/kwafer/?fullname=com.wandoujia.kwaf.schema.Kwafer'
# OK
printf "\n"

curl 'http://localhost:8080/kwafer/get/1'
#
printf "\n"

curl --data-binary @Kwafer.update 'http://localhost:8080/kwafer/put/1'
# OK
printf "\n"

curl 'http://localhost:8080/kwafer/get/1'
#
printf "\n"

curl --data '.accountRecords[0].action.type' 'http://localhost:8080/kwafer/select/1'
#
printf "\n"


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;

namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
    /// <summary>
    /// Contains navigate-to specific operations that depend on the version of the
    /// host they're running under.
    /// </summary>
    internal interface INavigateToHostVersionService
    {
        bool GetSearchCurrentDocument(INavigateToOptions options);
        INavigateToItemDisplayFactory CreateDisplayFactory();
    }
}


text:
//
//  ListViewController.m
//  Foodcolors
//
//  Created by kamyFCMacBook on 10/26/16.
//  Copyright © 2016 kamyFCMacBook. All rights reserved.
//

#import "ListViewController.h"
#import "Constants.h"

@interface ListViewController ()
@property (nonatomic, strong) NSMutableArray *arrayOfSettings;
@end

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.listTableView.rowHeight = UITableViewAutomaticDimension;
    self.listTableView.estimatedRowHeight = 81.0;
    self.listTableView.backgroundColor = [UIColor clearColor];

    NSString *string = @"";
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];
    [items addObject:[string stringByAppendingString:@"Home"]];
    [items addObject:[string stringByAppendingString:@"Preferences"]];
    [items addObject:[string stringByAppendingString:@"Notifications"]];
    [items addObject:[string stringByAppendingString:@"Login"]];

    self.arrayOfSettings = items;

    [self.listTableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.listTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

    self.listTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.listTableView.contentInset = UIEdgeInsetsMake(22.f, 0.f, 44.f, 0.f);
    self.listTableView.showsVerticalScrollIndicator = NO;

    [self.listTableView deselectRowAtIndexPath:indexPath animated:YES];

    [self setTabScroller];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

#pragma mark -  Methods
- (void) setTabScroller
{
    MenuViewController *menuVC = kMenuViewController;
    UINavigationController *navVC = (UINavigationController *) menuVC.rootViewController;
    MainViewController *mainVC = (MainViewController *) navVC.topViewController;

    ScrollingNavigationController *scrollNaVC = (ScrollingNavigationController *)mainVC.navigationController;
    if ([scrollNaVC isKindOfClass:[UINavigationController class]])
    {
        [scrollNaVC followScrollView:self.listTableView delay:50];
    }
}

#pragma mark -
#pragma mark UITableView Datasource/Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [self.arrayOfSettings count];
    }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return 46;
    }

-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
    {
        return 20.0;
    }

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
    {
        return 20.0;
    }

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
    {
        return [[UIView alloc] initWithFrame:CGRectZero];
    }

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
    {
        return [[UIView alloc] initWithFrame:CGRectZero];
    }

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        return @"Functions";
    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        ProfileCell *cell = (ProfileCell *) [tableView dequeueReusableCellWithIdentifier:@"TestCell"];
        cell.backgroundColor = [UIColor clearColor];

        cell.preservesSuperviewLayoutMargins = NO;
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.tintColor = [UIColor whiteColor];

        // Set up the cell...
        NSUInteger row = [indexPath row];

        if ([self.arrayOfSettings count] > 0)
        {
            NSString *item = nil;
            item = [self.arrayOfSettings objectAtIndex:row];

            cell.profileLabelText = item;

            [cell render];
        }

        return cell;
    }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        //NSUInteger row = [indexPath row];

        /*if (row == 0)
         {
         }
         else if (row == 1)
         {
         [self performSegueWithIdentifier:@"SegueToUpdate" sender:nil];
         }
         else if (row == 2)
         {
         [self performSegueWithIdentifier:@"SegueToAddStation" sender:nil];
         }
         else if ((row == 3) || (row == 4) || (row == 7) || (row == 8))
         {
         [self performSegueWithIdentifier:@"SegueToAbout" sender:indexPath];
         }
         else if (row == 5)
         {
         [self performSegueWithIdentifier:@"SegueToTour" sender:nil];
         }
         if (row == 6)
         {

         }*/
    }

@end