text:
#include <cstdint>
#include <cstdio>
#include <signal.h>
#include <util/CommandOptionParser.h>
#include <thread>
#include "Configuration.h"
#include <Aeron.h>

using namespace aeron::util;
using namespace aeron;

std::atomic<bool> running (true);

void sigIntHandler (int param)
{
    running = false;
}

static const char optHelp     = 'h';
static const char optPrefix   = 'p';
static const char optChannel  = 'c';
static const char optStreamId = 's';

static const std::chrono::duration<long, std::milli> IDLE_SLEEP_MS(1);
static const int FRAGMENTS_LIMIT = 10;

struct Settings
{
    std::string dirPrefix = "";
    std::string channel = samples::configuration::DEFAULT_CHANNEL;
    std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
};

Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
    cp.parse(argc, argv);
    if (cp.getOption(optHelp).isPresent())
    {
        cp.displayOptionsHelp(std::cout);
        exit(0);
    }

    Settings s;

    s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
    s.channel = cp.getOption(optChannel).getParam(0, s.channel);
    s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);

    return s;
}

fragment_handler_t printStringMessage()
{
    return [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header)
    {
        std::cout << "Message to stream " << header.streamId() << " from session " << header.sessionId();
        std::cout << "(" << length << "@" << offset << ") <<";
        std::cout << std::string((char *)buffer.buffer() + offset, (unsigned long)length) << ">>" << std::endl;
    };
}

int main(int argc, char** argv)
{
    CommandOptionParser cp;
    cp.addOption(CommandOption (optHelp,     0, 0, "                Displays help information."));
    cp.addOption(CommandOption (optPrefix,   1, 1, "dir             Prefix directory for aeron driver."));
    cp.addOption(CommandOption (optChannel,  1, 1, "channel         Channel."));
    cp.addOption(CommandOption (optStreamId, 1, 1, "streamId        Stream ID."));

    signal (SIGINT, sigIntHandler);

    try
    {
        Settings settings = parseCmdLine(cp, argc, argv);

        std::cout << "Subscribing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl;

        aeron::Context context;

        if (settings.dirPrefix != "")
        {
            context.aeronDir(settings.dirPrefix);
        }

        context.newSubscriptionHandler(
            [](const std::string& channel, std::int32_t streamId, std::int64_t correlationId)
            {
                std::cout << "Subscription: " << channel << " " << correlationId << ":" << streamId << std::endl;
            });

        context.newImageHandler([](
            Image& image,
            const std::string &channel,
            std::int32_t streamId,
            std::int32_t sessionId,
            std::int64_t joiningPosition,
            const std::string &sourceIdentity)
        {
            std::cout << "New image on " << channel << " streamId=" << streamId << " sessionId=" << sessionId;
            std::cout << " at position=" << joiningPosition << " from " << sourceIdentity << std::endl;
        });

        context.inactiveImageHandler(
            [](Image& image, const std::string &channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t position)
            {
                std::cout << "Inactive image on " << channel << "streamId=" << streamId << " sessionId=" << sessionId;
                std::cout << " at position=" << position << std::endl;
            });

        std::shared_ptr<Aeron> aeron = Aeron::connect(context);

        // add the subscription to start the process
        std::int64_t id = aeron->addSubscription(settings.channel, settings.streamId);

        std::shared_ptr<Subscription> subscription = aeron->findSubscription(id);
        // wait for the subscription to be valid
        while (!subscription)
        {
            std::this_thread::yield();
            subscription = aeron->findSubscription(id);
        }

        fragment_handler_t handler = printStringMessage();
        SleepingIdleStrategy idleStrategy(IDLE_SLEEP_MS);

        while (running)
        {
            const int fragmentsRead = subscription->poll(handler, FRAGMENTS_LIMIT);

            idleStrategy.idle(fragmentsRead);
        }

    }
    catch (CommandOptionException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        cp.displayOptionsHelp(std::cerr);
        return -1;
    }
    catch (SourcedException& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
        return -1;
    }
    catch (std::exception& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << std::endl;
        return -1;
    }

    return 0;
}


text:
class Blog::Admin::PostsController < Blog::Admin::BaseController
  respond_to :html
  before_filter :load_post, only: [:edit, :update]

  def index
    @posts = Blog::Post.default
  end

  def new
    @post = Blog::Post.new
  end

  ## Preview a post without saving.
  def preview
    # mockup our models for preview.
    @post = Blog::Post.new post_params
    @post.user_id = current_user.id
    @post.published_at = Time.zone.now
    # render it exactly as it would display when live.
    render "/blog/posts/show", layout: Blog::Config.layout || "/layouts/blog/application"
  end

  def create
    @post = Blog::Post.new post_params
    @post.user_id = current_user.id
    if @post.save
      prepare_flash_and_redirect_to_edit()
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      prepare_flash_and_redirect_to_edit()
    else
      render :edit
    end
  end

  def destroy
    post = Blog::Post.find(params[:id])
    if post.destroy
      redirect_to admin_posts_path, notice:  I18n.t("blog.admin.posts.delete.removed")
    else
      redirect_to admin_posts_path, alert: I18n.t("blog.admin.posts.delete.failed")
    end
  end

private
  def load_post
    @post = Blog::Post.find(params[:id])
  end

  def prepare_flash_and_redirect_to_edit
    if @post.published_in_future? && ActionController::Base.perform_caching
      flash[:warning] = I18n.t("blog.admin.posts.#{params[:action]}.saved_with_future_date_and_cache")
    else
      flash[:notice] =  I18n.t("blog.admin.posts.#{params[:action]}.saved")
    end
    redirect_to edit_admin_post_path(@post)
  end

  def post_params
    params.require(:post).permit(:published, :tag_list, :title, :content, :url, :image, :published_at)
  end
end

redpajama_set_name: RedPajamaGithub


text:
BASE_URLS = [
"www.biomedcentral.com",
"www.actaneurocomms.org",
"www.actavetscand.com",
"www.ascpjournal.org",
"www.agricultureandfoodsecurity.com",
"www.aidsrestherapy.com",
"www.almob.org",
"www.aacijournal.com",
"alzres.com",
"www.amb-express.com",
"www.animalbiotelemetry.com",
"www.ann-clinmicrob.com",
"www.annals-general-psychiatry.com",
"www.annalsofintensivecare.com",
"www.asir-journal.com",
"www.aricjournal.com",
"www.aquaticbiosystems.org",
"www.archpublichealth.com",
"arthritis-research.com",
"www.apfmj.com",
"www.bacandrology.com",
"www.behavioralandbrainfunctions.com",
"www.biodatamining.org",
"www.biointerphases.com",
"www.biologicalproceduresonline.com",
"www.biology-direct.com",
"www.biolmoodanxietydisord.com",
"www.bsd-journal.com",
"www.biomarkerres.org",
"www.biomedical-engineering-online.com",
"www.bpsmedicine.com",
"www.biotechnologyforbiofuels.com",
"www.biomedcentral.com/bmcanesthesiol",
"www.biomedcentral.com/bmcbiochem",
"www.biomedcentral.com/bmcbioinformatics",
"www.biomedcentral.com/bmcbiol",
"www.biomedcentral.com/bmcbiophys",
"www.biomedcentral.com/bmcbiotechnol",
"www.biomedcentral.com/bmcblooddisord",
"www.biomedcentral.com/bmccancer",
"www.biomedcentral.com/bmccardiovascdisord",
"www.biomedcentral.com/bmccellbiol",
"www.biomedcentral.com/bmcchembiol",
"www.biomedcentral.com/bmcclinpathol",
"www.biomedcentral.com/bmccomplementalternmed",
"www.biomedcentral.com/bmcdermatol",
"www.biomedcentral.com/bmcdevbiol",
"www.biomedcentral.com/bmcearnosethroatdisord",
"www.biomedcentral.com/bmcecol",
"www.biomedcentral.com/bmcemergmed",
"www.biomedcentral.com/bmcendocrdisord",
"www.biomedcentral.com/bmcevolbiol",
"www.biomedcentral.com/bmcfampract",
"www.biomedcentral.com/bmcgastroenterol",
"www.biomedcentral.com/bmcgenet",
"www.biomedcentral.com/bmcgenomics",
"www.biomedcentral.com/bmcgeriatr",
"www.biomedcentral.com/bmchealthservres",
"www.biomedcentral.com/bmcimmunol",
"www.biomedcentral.com/bmcinfectdis",
"www.biomedcentral.com/bmcinthealthhumrights",
"www.biomedcentral.com/bmcmededuc",
"www.biomedcentral.com/bmcmedethics",
"www.biomedcentral.com/bmcmedgenet",
"www.biomedcentral.com/bmcmedgenomics",
"www.biomedcentral.com/bmcmedimaging",
"www.biomedcentral.com/bmcmedinformdecismak",
"www.biomedcentral.com/bmcmedphys",
"www.biomedcentral.com/bmcmedresmethodol",
"www.biomedcentral.com/bmcmed",
"www.biomedcentral.com/bmcmicrobiol",
"www.biomedcentral.com/bmcmolbiol",
"www.biomedcentral.com/bmcmusculoskeletdisord",
"www.biomedcentral.com/bmcnephrol",
"www.biomedcentral.com/bmcneurol",
"www.biomedcentral.com/bmcneurosci",
"www.biomedcentral.com/bmcnurs",
"www.biomedcentral.com/bmcophthalmol",
"www.biomedcentral.com/bmcoralhealth",
"www.biomedcentral.com/bmcpalliatcare",
"www.biomedcentral.com/bmcpediatr",
"www.biomedcentral.com/bmcpharmacoltoxicol",
"www.biomedcentral.com/bmcphysiol",
"www.biomedcentral.com/bmcplantbiol",
"www.biomedcentral.com/bmcpregnancychildbirth",
"www.biomedcentral.com/bmcproc",
"www.biomedcentral.com/bmcpsychiatry",
"www.biomedcentral.com/bmcpsychol",
"www.biomedcentral.com/bmcpublichealth",
"www.biomedcentral.com/bmcpulmmed",
"www.biomedcentral.com/bmcresnotes",
"www.biomedcentral.com/bmcstructbiol",
"www.biomedcentral.com/bmcsurg",
"www.biomedcentral.com/bmcsystbiol",
"www.biomedcentral.com/bmcurol",
"www.biomedcentral.com/bmcvetres",
"www.biomedcentral.com/bmcwomenshealth",
"www.bpded.com",
"breast-cancer-research.com",
"www.cancerandmetabolism.com",
"www.cancerci.com",
"www.cbmjournal.com",
"www.cardiab.com",
"www.cardiovascularultrasound.com",
"www.cellandbioscience.com",
"www.biosignaling.com",
"www.celldiv.com",
"www.cellregenerationjournal.com",
"journal.chemistrycentral.com",
"www.capmh.com",
"www.cmjournal.org",
"www.chiromt.com",
"www.ciliajournal.com",
"www.clinicalmolecularallergy.com",
"www.ctajournal.com",
"www.clintransmed.com",
"www.clinicalepigeneticsjournal.com",
"www.clinicalproteomicsjournal.com",
"www.clinicalsarcomaresearch.com",
"www.comparative-hepatology.com",
"www.conflictandhealth.com",
"www.resource-allocation.com",
"www.coughjournal.com",
"ccforum.com",
"www.criticalultrasoundjournal.com",
"www.darujps.com",
"www.dmsjournal.com",
"www.diagnosticpathology.org",
"www.ejnmmires.com",
"www.ete-online.com",
"www.environmentalevidencejournal.org",
"www.ehjournal.net",
"www.enveurope.com",
"www.epigeneticsandchromatin.com",
"www.epmajournal.com",
"bsb.eurasipjournals.com",
"www.eurjmedres.com",
"www.evodevojournal.com",
"www.evolution-outreach.com",
"www.etsmjournal.com",
"www.ehoonline.org",
"www.extremephysiolmed.com",
"www.fibrogenesis.com",
"www.flavourjournal.com",
"www.fluidsbarrierscns.com",
"www.frontiersinzoology.com",
"www.gsejournal.org",
"genomebiology.com",
"www.genomeintegrity.com",
"genomemedicine.com",
"www.geochemicaltransactions.com",
"www.gigasciencejournal.com",
"www.globalizationandhealth.com",
"www.gutpathogens.com",
"www.harmreductionjournal.com",
"www.head-face-med.com",
"www.hqlo.com",
"www.hissjournal.com",
"www.health-policy-systems.com",
"www.hccpjournal.com",
"www.heritagesciencejournal.com",
"www.herpesviridae.org",
"www.thehugojournal.com",
"www.humgenomics.com",
"www.human-resources-health.com",
"www.immunityageing.com",
"www.implementationscience.com",
"www.in-silico-pharmacology.com",
"www.infectagentscancer.com",
"www.idpjournal.com",
"www.intaquares.com",
"www.intarchmed.com",
"www.internationalbreastfeedingjournal.com",
"www.equityhealthj.com",
"www.ijbnpa.org",
"www.journalbipolardisorders.com",
"www.intjem.com",
"www.ij-healthgeographics.com",
"www.ijmhs.com",
"www.ijpeonline.com",
"www.investigativegenetics.com",
"www.ijehse.com",
"www.irishvetjournal.org",
"www.ijhpr.org",
"www.ijponline.net",
"www.immunotherapyofcancer.org",
"www.jasbsci.com",
"www.jbioleng.org",
"www.jbiomedsci.com",
"www.jbiomedsem.com",
"www.jbppni.com",
"www.cardiothoracicsurgery.org",
"jcmr-online.com",
"www.jcheminf.com",
"www.jcircadianrhythms.com",
"www.jclinbioinformatics.com",
"www.jdmdonline.com",
"www.jeatdisord.com",
"www.ethnobiomed.com",
"www.jeccr.com",
"www.jfootankleres.com",
"www.thejournalofheadacheandpain.com",
"www.jhoonline.org",
"www.journal-inflammation.com",
"www.mathematical-neuroscience.com",
"www.jmedicalcasereports.com",
"www.jmolecularpsychiatry.com",
"www.jmolecularsignaling.com",
"www.jnanobiotechnology.com",
"www.jnrbm.com",
"www.jneurodevdisorders.com",
"www.jneuroengrehab.com",
"www.jneuroinflammation.com",
"www.occup-med.com",
"www.joii-journal.com",
"www.josr-online.com",
"www.journalotohns.com",
"www.ovarianresearch.com",
"www.jphysiolanthropol.com",
"www.jsystchem.com",
"www.jissn.com",
"www.jtultrasound.com",
"www.translational-medicine.com",
"www.traumamanagement.org",
"www.juaa-journal.com",
"www.jvat.org",
"www.lipidworld.com",
"www.longevityandhealthspan.com",
"www.malariajournal.com",
"www.medicalgasresearch.com",
"www.microbialcellfactories.com",
"www.microbialinformaticsj.com",
"www.microbiomejournal.com",
"www.mobilednajournal.com",
"www.molecularautism.com",
"www.molecularbrain.com",
"www.molecular-cancer.com",
"www.molecularcytogenetics.org",
"www.molecularneurodegeneration.com",
"www.molecularpain.com",
"www.movementecologyjournal.com",
"www.mrmjournal.com",
"www.neuraldevelopment.com",
"www.neurogliajournal.com",
"www.nzjforestryscience.com",
"www.nutritionandmetabolism.com",
"www.nutritionj.com",
"www.optnano.com",
"www.ojrd.com",
"www.parasitesandvectors.com",
"www.particleandfibretoxicology.com",
"www.pssjournal.com",
"www.ped-rheum.com",
"www.perioperativemedicinejournal.com",
"www.peh-med.com",
"www.plantmethods.com",
"www.pophealthmetrics.com",
"www.progressbiomaterials.com",
"www.proteomesci.com",
"www.ro-journal.com",
"www.regenmedres.com",
"www.rbej.com",
"www.reproductive-health-journal.com",
"respiratory-research.com",
"www.retrovirology.com",
"www.thericejournal.com",
"www.sjtrem.com",
"www.scoliosisjournal.com",
"www.silencejournal.com",
"www.skeletalmusclejournal.com",
"www.scfbm.org",
"www.smarttjournal.com",
"www.springerplus.com",
"stemcellres.com",
"www.substanceabusepolicy.com",
"www.sustainablechemicalprocesses.com",
"www.systematicreviewsjournal.com",
"www.tbiomed.com",
"www.thrombosisjournal.com",
"www.thyroidresearchjournal.com",
"www.tobaccoinduceddiseases.com",
"www.translationalneurodegeneration.com",
"www.transrespmed.com",
"www.transplantationresearch.com",
"www.trialsjournal.com",
"www.vascularcell.com",
"www.veterinaryresearch.org",
"www.vjoes.org",
"www.virologyj.com",
"www.waojournal.org",
"www.wjes.org",
"www.wjso.com",
"www.anzhealthpolicy.com",
"www.aejournal.net",
"archive.biomedcentral.com/1860-5397",
"www.biomagres.com",
"www.bio-diglib.com",
"www.biomedcentral.com/bmcpharmacol/",
"www.casesjournal.com",
"www.cellandchromosome.com",
"www.cpementalhealth.com",
"archive.biomedcentral.com/1742-6413",
"www.dynamic-med.com",
"archive.biomedcentral.com/1476-3591",
"archive.biomedcentral.com/1742-5573",
"www.filariajournal.com",
"www.gvt-journal.com",
"www.headandneckoncology.org",
"www.immunome-research.com",
"www.integrativeomics.org",
"www.issoonline.com",
"www.jautoimdis.com",
"jbiol.com/",
"www.j-biomed-discovery.com",
"www.jbioscimed.com",
"archive.biomedcentral.com/1477-3163",
"archive.biomedcentral.com/1743-1050",
"www.jibtherapies.com",
"archive.biomedcentral.com/1758-2652",
"www.kinetoplastids.com",
"www.medimmunol.com",
"www.neuralsystemsandcircuits.com",
"www.nonlinearbiomedphys.com",
"www.nuclear-receptor.com",
"www.opennetworkbiology.com",
"www.openresearchcomputation.com",
"www.om-pc.com",
"www.pathogeneticsjournal.com",
"www.sustainablehealthcarejournal.com"]


text:
package ro.pub.cs.systems.pdsd.practicaltest02var05;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

class Value{
	public String value;
	public String time;
}

public class CommunicationThread extends Thread{

	private static final String WEB_SERVICE_ADDRESS = "http://www.timeapi.org/utc/now";
	private ServerThread serverThread;
	private Socket       socket;

	public CommunicationThread(ServerThread serverThread, Socket socket) {
		this.serverThread = serverThread;
		this.socket       = socket;

	}

	@Override
	public void run() {
		if (socket != null) {
			try {
				BufferedReader bufferedReader = Utilities.getReader(socket);
				PrintWriter    printWriter    = Utilities.getWriter(socket);
				if (bufferedReader != null && printWriter != null) {
					String[] text = bufferedReader.readLine().split(",");
					String result = "aici";

					if(text[0].equals("put")){
						if(serverThread.tabel.containsKey(text[1])){

							HttpClient httpClient = new DefaultHttpClient();
							HttpGet httpGet = new HttpGet(WEB_SERVICE_ADDRESS);
							ResponseHandler<String> responseHandler = new BasicResponseHandler();
							String pageSourceCode = httpClient.execute(httpGet, responseHandler);

							String[] t = pageSourceCode.split("[-T:+]");

							DateTime d = new DateTime(Integer.parseInt(t[0]),Integer.parseInt(t[1]),
									Integer.parseInt(t[2]),Integer.parseInt(t[3]),Integer.parseInt(t[4]),Integer.parseInt(t[5]));

							String[] t2 = serverThread.tabel.get(text[1]).time.split("[-T:+]");

							DateTime d2= new DateTime(Integer.parseInt(t2[0]),Integer.parseInt(t2[1]),
									Integer.parseInt(t2[2]),Integer.parseInt(t2[3]),Integer.parseInt(t2[4]),Integer.parseInt(t2[5]));

							if(d.toLong() - d2.toLong() > 60){
								Value v = new Value();
								v.value = text[2];
								v.time = pageSourceCode;

								serverThread.tabel.put(text[1], v);
								result = "modified";
							}
							else{
								result = "";
							}
						}
						else{
							result = "inserted";

							HttpClient httpClient = new DefaultHttpClient();
							HttpGet httpGet = new HttpGet(WEB_SERVICE_ADDRESS);
							ResponseHandler<String> responseHandler = new BasicResponseHandler();
							String pageSourceCode = httpClient.execute(httpGet, responseHandler);

							Value v = new Value();
							v.value = text[2];
							v.time = pageSourceCode;

							serverThread.tabel.put(text[1], v);
						}
					}

					if(text[0].equals("get")){
						if(serverThread.tabel.containsKey(text[1])){
							result = serverThread.tabel.get(text[1]).value;
						}
						else{
							result = "none";
						}
					}

					printWriter.write(result + "\n");
					printWriter.flush();
				}
			} catch (Exception e) {
				Log.e("Exeption", e.toString());
			}
		}
	}
}


text:
<?php

namespace Liuggio\Fastest\Queue\Infrastructure;

use Liuggio\Fastest\Queue\QueueInterface;
use Liuggio\Fastest\Queue\TestsQueue;
use Liuggio\Fastest\Queue\TestSuite;

class InMemoryQueue implements QueueInterface
{
    /**
     * @var array<int, TestSuite>
     */
    private $queue;

    public function __construct()
    {
        $this->queue = [];
    }

    public function pop(): ?TestSuite
    {
        return array_pop($this->queue);
    }

    public function shift(): ?TestSuite
    {
        return array_shift($this->queue);
    }

    public function push(TestsQueue $testSuite): bool
    {
        $this->queue = array_merge($this->queue, $testSuite->toArray());

        return count($this->queue) > 0;
    }

    public function getNumberOfPushedMessage(): int
    {
        return count($this->queue);
    }

    public function close(): void
    {
        $this->queue = [];
    }

    public function count(): int
    {
        if (null !== $this->queue) {
            return count($this->queue);
        }

        return 0;
    }

    public function isEmpty(): bool
    {
        return 0 == $this->count();
    }
}


text:
require 'set'

module Launchy
  #
  # Use by either
  #
  #   class Foo
  #     extend DescendantTracker
  #   end
  #
  # or
  #
  #   class Foo
  #     class << self
  #       include DescendantTracker
  #     end
  #   end
  #
  # It will track all the classes that inherit from the extended class and keep
  # them in a Set that is available via the 'children' method.
  #
  module DescendantTracker
    def inherited( klass )
      return unless klass.instance_of?( Class )
      self.children << klass
    end

    #
    # The list of children that are registered
    #
    def children
      unless defined? @children
        @children = Array.new
      end
      return @children
    end

    #
    # Find one of the child classes by calling the given method
    # and passing all the rest of the parameters to that method in
    # each child
    def find_child( method, *args )
      children.find do |child|
        Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
        child.send( method, *args )
      end
    end
  end
end


text:
#import "XMPPDateTimeProfiles.h"
#import "NSNumber+XMPP.h"

#if ! __has_feature(objc_arc)
#warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif

@interface XMPPDateTimeProfiles (PrivateAPI)
+ (NSDate *)parseDateTime:(NSString *)dateTimeStr withMandatoryTimeZone:(BOOL)mandatoryTZ;
@end

@implementation XMPPDateTimeProfiles

/**
 * The following acronyms and characters are used from XEP-0082 to represent time-related concepts:
 *
 * CCYY	four-digit year portion of Date
 * MM	two-digit month portion of Date
 * DD	two-digit day portion of Date
 * -	ISO 8601 separator among Date portions
 * T	ISO 8601 separator between Date and Time
 * hh	two-digit hour portion of Time (00 through 23)
 * mm	two-digit minutes portion of Time (00 through 59)
 * ss	two-digit seconds portion of Time (00 through 59)
 * :	ISO 8601 separator among Time portions
 * .	ISO 8601 separator between seconds and milliseconds
 * sss	fractional second addendum to Time (MAY contain any number of digits)
 * TZD	Time Zone Definition (either "Z" for UTC or "(+|-)hh:mm" for a specific time zone)
 *
**/

+ (NSDate *)parseDate:(NSString *)dateStr
{
	if ([dateStr length] < 10) return nil;

	// The Date profile defines a date without including the time of day.
	// The lexical representation is as follows:
	//
	// CCYY-MM-DD
	//
	// Example:
	//
	// 1776-07-04

	NSDateFormatter *df = [[NSDateFormatter alloc] init];
	[df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3)
	[df setDateFormat:@"yyyy-MM-dd"];

	NSDate *result = [df dateFromString:dateStr];

	return result;
}

+ (NSDate *)parseTime:(NSString *)timeStr
{
	// The Time profile is used to specify an instant of time that recurs (e.g., every day).
	// The lexical representation is as follows:
	//
	// hh:mm:ss[.sss][TZD]
	//
	// The Time Zone Definition is optional; if included, it MUST be either UTC (denoted by addition
	// of the character 'Z' to the end of the string) or some offset from UTC (denoted by addition
	// of '[+|-]' and 'hh:mm' to the end of the string).
	//
	// Examples:
	//
	// 16:00:00
	// 16:00:00Z
	// 16:00:00+07:00
	// 16:00:00.123
	// 16:00:00.123Z
	// 16:00:00.123+07:00

	// Extract the current day so the result can be on the current day.
	// Why do we bother doing this?
	//
	// First, it is rather intuitive.
	// Second, if we don't we risk being on a date with a conflicting DST (daylight saving time).
	//
	// For example, -0800 instead of the current -0700.
	// This can be rather confusing when printing the result.

	NSDateFormatter *df = [[NSDateFormatter alloc] init];
	[df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3)
	[df setDateFormat:@"yyyy-MM-dd"];

	NSString *today = [df stringFromDate:[NSDate date]];

	NSString *dateTimeStr = [NSString stringWithFormat:@"%@T%@", today, timeStr];

	return [self parseDateTime:dateTimeStr withMandatoryTimeZone:NO];
}

+ (NSDate *)parseDateTime:(NSString *)dateTimeStr
{
	// The DateTime profile is used to specify a non-recurring moment in time to an accuracy of seconds (or,
	// optionally, fractions of a second). The format is as follows:
	//
	// CCYY-MM-DDThh:mm:ss[.sss]TZD
	//
	// The Time Zone Definition is mandatory and MUST be either UTC (denoted by addition of the character 'Z'
	// to the end of the string) or some offset from UTC (denoted by addition of '[+|-]' and 'hh:mm' to the
	// end of the string).
	//
	// Examples:
	//
	// 1969-07-21T02:56:15Z
	// 1969-07-20T21:56:15-05:00
	// 1969-07-21T02:56:15.123Z
	// 1969-07-20T21:56:15.123-05:00

	return [self parseDateTime:dateTimeStr withMandatoryTimeZone:YES];
}

+ (NSDate *)parseDateTime:(NSString *)dateTimeStr withMandatoryTimeZone:(BOOL)mandatoryTZ
{
	if ([dateTimeStr length] < 19) return nil;

	// The DateTime profile is used to specify a non-recurring moment in time to an accuracy of seconds (or,
	// optionally, fractions of a second). The format is as follows:
	//
	// CCYY-MM-DDThh:mm:ss[.sss]{TZD}
	//
	// Examples:
	//
	// 1969-07-21T02:56:15
	// 1969-07-21T02:56:15Z
	// 1969-07-20T21:56:15-05:00
	// 1969-07-21T02:56:15.123
	// 1969-07-21T02:56:15.123Z
	// 1969-07-20T21:56:15.123-05:00

	BOOL hasMilliseconds = NO;
	BOOL hasTimeZoneInfo = NO;
	BOOL hasTimeZoneOffset = NO;
	NSInteger fractionalDigits = 0;

	if ([dateTimeStr length] > 19)
	{
		unichar c = [dateTimeStr characterAtIndex:19];

		// Check for optional milliseconds
		if (c == '.')
		{
			hasMilliseconds = YES;

			// At least one fractional digit?
			if ([dateTimeStr length] < 21) return nil;
		}

		// Check for optional time zone info, which is at the last char (Z), or the
		// char 6 chars from the end
		if ([dateTimeStr characterAtIndex:[dateTimeStr length] - 1] == 'Z')
		{
			hasTimeZoneInfo = YES;
			hasTimeZoneOffset = NO;
			if (hasMilliseconds)
			{
				// 1969-07-21T02:56:15.1234Z -> 25 - 1 - 20 = 4
				fractionalDigits = [dateTimeStr length] - 1 - 20;
			}
		}
		else
		{
			c = [dateTimeStr characterAtIndex:[dateTimeStr length] - 6];
			if (c == '+' || c == '-')
			{
				hasTimeZoneInfo = YES;
				hasTimeZoneOffset = YES;
				if (hasMilliseconds)
				{
					// 1969-07-21T02:56:15.1234+00:00 -> 30 - 6 - 20 = 4
					fractionalDigits = [dateTimeStr length] - 6 - 20;
				}
			}
			else if (hasMilliseconds)
			{
				// 1969-07-21T02:56:15.1234 -> 24 - 20 = 4
				fractionalDigits = [dateTimeStr length] - 20;
			}
		}
	}

	if (mandatoryTZ && !hasTimeZoneInfo) return nil;

	NSDateFormatter *df = [[NSDateFormatter alloc] init];
	[df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3)
	[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

	NSDate *result = nil;
	NSString *dateAndTime = [dateTimeStr substringToIndex:19];
	NSString *fraction = fractionalDigits != 0 ? [NSString stringWithFormat:@"0%@", [dateTimeStr substringWithRange:NSMakeRange(19, fractionalDigits + 1)]] : nil;

	if (hasTimeZoneInfo && !hasTimeZoneOffset)
	{
		[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
		result = [df dateFromString:dateAndTime];
	}
	else if (hasTimeZoneInfo && hasTimeZoneOffset)
	{
		NSString *timeZone = [dateTimeStr substringFromIndex:[dateTimeStr length] - 6];
		NSTimeZone *tz = [self parseTimeZoneOffset:timeZone];
		if (tz == nil)
		{
			result = nil;
		}
		else
		{
			[df setTimeZone:tz];
			result = [df dateFromString:dateAndTime];
		}
	}
	else
	{
		result = [df dateFromString:dateAndTime];
	}

	if (result && fraction)
	{
		static NSNumberFormatter *numberFormatter = nil;
		static dispatch_once_t onceToken;
		dispatch_once(&onceToken, ^{
			numberFormatter = [[NSNumberFormatter alloc] init];
			[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
			[numberFormatter setDecimalSeparator:@"."];
		});

		NSTimeInterval fractionInterval = [[numberFormatter numberFromString:fraction] doubleValue];
		NSTimeInterval current = [result timeIntervalSinceReferenceDate];
		result = [NSDate dateWithTimeIntervalSinceReferenceDate:floor(current) + fractionInterval];
	}

	return result;
}

+ (NSTimeZone *)parseTimeZoneOffset:(NSString *)tzo
{
	// The tzo value is supposed to start with '+' or '-'.
	// Spec says: (+-)hh:mm
	//
	// hh : two-digit hour portion (00 through 23)
	// mm : two-digit minutes portion (00 through 59)

	if ([tzo length] != 6)
	{
		return nil;
	}

	NSString *hoursStr   = [tzo substringWithRange:NSMakeRange(1, 2)];
	NSString *minutesStr = [tzo substringWithRange:NSMakeRange(4, 2)];

	NSUInteger hours;
	if (![NSNumber xmpp_parseString:hoursStr intoNSUInteger:&hours])
		return nil;

	NSUInteger minutes;
	if (![NSNumber xmpp_parseString:minutesStr intoNSUInteger:&minutes])
		return nil;

	if (hours > 23) return nil;
	if (minutes > 59) return nil;

	NSInteger secondsOffset = (NSInteger)((hours * 60 * 60) + (minutes * 60));

	if ([tzo hasPrefix:@"-"])
	{
		secondsOffset = -1 * secondsOffset;
	}
	else if (![tzo hasPrefix:@"+"])
	{
		return nil;
	}

	return [NSTimeZone timeZoneForSecondsFromGMT:secondsOffset];
}

@end


text:
using BepuPhysics;
using BepuPhysics.Collidables;
using BepuPhysics.CollisionDetection;
using BepuPhysics.Constraints;
using BepuUtilities;
using System.Numerics;
using System.Runtime.CompilerServices;

namespace HeadlessTests23;

public struct DemoPoseIntegratorCallbacks : IPoseIntegratorCallbacks
{
    /// <summary>
    /// Gravity to apply to dynamic bodies in the simulation.
    /// </summary>
    public Vector3 Gravity;
    /// <summary>
    /// Fraction of dynamic body linear velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.
    /// </summary>
    public float LinearDamping;
    /// <summary>
    /// Fraction of dynamic body angular velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.
    /// </summary>
    public float AngularDamping;

    /// <summary>
    /// Gets how the pose integrator should handle angular velocity integration.
    /// </summary>
    public readonly AngularIntegrationMode AngularIntegrationMode => AngularIntegrationMode.Nonconserving;

    public void Initialize(Simulation simulation)
    {
        //In this demo, we don't need to initialize anything.
        //If you had a simulation with per body gravity stored in a CollidableProperty<T> or something similar, having the simulation provided in a callback can be helpful.
    }

    /// <summary>
    /// Creates a new set of simple callbacks for the demos.
    /// </summary>
    /// <param name="gravity">Gravity to apply to dynamic bodies in the simulation.</param>
    /// <param name="linearDamping">Fraction of dynamic body linear velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.</param>
    /// <param name="angularDamping">Fraction of dynamic body angular velocity to remove per unit of time. Values range from 0 to 1. 0 is fully undamped, while values very close to 1 will remove most velocity.</param>
    public DemoPoseIntegratorCallbacks(Vector3 gravity, float linearDamping = .03f, float angularDamping = .03f) : this()
    {
        Gravity = gravity;
        LinearDamping = linearDamping;
        AngularDamping = angularDamping;
    }

    Vector3 gravityDt;
    float linearDampingDt;
    float angularDampingDt;

    /// <summary>
    /// Callback invoked ahead of dispatches that may call into <see cref="IntegrateVelocity"/>.
    /// It may be called more than once with different values over a frame. For example, when performing bounding box prediction, velocity is integrated with a full frame time step duration.
    /// During substepped solves, integration is split into substepCount steps, each with fullFrameDuration / substepCount duration.
    /// The final integration pass for unconstrained bodies may be either fullFrameDuration or fullFrameDuration / substepCount, depending on the value of AllowSubstepsForUnconstrainedBodies.
    /// </summary>
    /// <param name="dt">Current integration time step duration.</param>
    /// <remarks>This is typically used for precomputing anything expensive that will be used across velocity integration.</remarks>
    public void PrepareForIntegration(float dt)
    {
        //No reason to recalculate gravity * dt for every body; just cache it ahead of time.
        //Since these callbacks don't use per-body damping values, we can precalculate everything.
        linearDampingDt = MathF.Pow(MathHelper.Clamp(1 - LinearDamping, 0, 1), dt);
        angularDampingDt = MathF.Pow(MathHelper.Clamp(1 - AngularDamping, 0, 1), dt);
        gravityDt = Gravity * dt;
    }

    public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia localInertia, int workerIndex, ref BodyVelocity velocity)
    {
        if (localInertia.InverseMass != 0)
        {
            velocity.Linear = (velocity.Linear + gravityDt) * linearDampingDt;
            velocity.Angular = velocity.Angular * angularDampingDt;
        }
    }
}
public unsafe struct DemoNarrowPhaseCallbacks : INarrowPhaseCallbacks
{
    public SpringSettings ContactSpringiness;
    public float MaximumRecoveryVelocity;
    public float FrictionCoefficient;

    public DemoNarrowPhaseCallbacks(SpringSettings contactSpringiness, float maximumRecoveryVelocity = 2f, float frictionCoefficient = 1f)
    {
        ContactSpringiness = contactSpringiness;
        MaximumRecoveryVelocity = maximumRecoveryVelocity;
        FrictionCoefficient = frictionCoefficient;
    }

    public void Initialize(Simulation simulation)
    {
        //Use a default if the springiness value wasn't initialized... at least until struct field initializers are supported outside of previews.
        if (ContactSpringiness.AngularFrequency == 0 && ContactSpringiness.TwiceDampingRatio == 0)
        {
            ContactSpringiness = new(30, 1);
            MaximumRecoveryVelocity = 2f;
            FrictionCoefficient = 1f;
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public bool AllowContactGeneration(int workerIndex, CollidableReference a, CollidableReference b)
    {
        //While the engine won't even try creating pairs between statics at all, it will ask about kinematic-kinematic pairs.
        //Those pairs cannot emit constraints since both involved bodies have infinite inertia. Since most of the demos don't need
        //to collect information about kinematic-kinematic pairs, we'll require that at least one of the bodies needs to be dynamic.
        return a.Mobility == CollidableMobility.Dynamic || b.Mobility == CollidableMobility.Dynamic;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB)
    {
        return true;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public unsafe bool ConfigureContactManifold<TManifold>(int workerIndex, CollidablePair pair, ref TManifold manifold, out PairMaterialProperties pairMaterial) where TManifold : struct, IContactManifold<TManifold>
    {
        pairMaterial.FrictionCoefficient = FrictionCoefficient;
        pairMaterial.MaximumRecoveryVelocity = MaximumRecoveryVelocity;
        pairMaterial.SpringSettings = ContactSpringiness;
        return true;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public bool ConfigureContactManifold(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB, ref ConvexContactManifold manifold)
    {
        return true;
    }

    public void Dispose()
    {
    }
}


text:
var nav_visible;

function showMap() {
    swapMainWindow($('#map-container'));
    if (!($('#feed').hasClass('side-visible'))) {
        //refresh-feed();
        loadFeed();
    }
}

function loadFeed() {
    console.log('Loading FeedPosts');
    $.each(post_ids, function (index, post_id) {
        $(post_id).css('left', "-100%");
    });
    swapSideBar($('#feed'));
    $.each(post_ids, function (index, post_id) {
        $('#feed-post' + post_id).delay(200 * index + 500).animate({
            'left': "5%"
        })
    });
}

function showListMenu() {
    $('.visible').animate({'right': "0", 'width': "55%"});
    $('.side-visible').animate({'left': "20%", 'width': "25%"});
    $('#list-menu').animate({'left': "0"});
    nav_visible = true;
}

function hideListMenu() {
    $('.visible').animate({'right': "0", 'width': "75%"});
    $('.side-visible').animate({'left': "0", 'width': "25%"});
    $('#list-menu').animate({'left': "-20%"});
    nav_visible = false;
}

/**
 * swapMainWindow -
 * Swaps the current main window with the new window to display.
 * The main window is the detail/list section of the display occupying
 * the right 75% of the screen with site-nav hidden and 55% when visible.
 * @param id
 */
function swapMainWindow(id) {
    if (!(id.hasClass('visible'))) {
        $('.visible').animate({'right': "-100%"}).removeClass('visible');
        if (nav_visible) {
            id.animate({'margin-right': "0", 'width': "55%"});
        }
        else {
            id.animate({'margin-right': "0", 'width': "75%"});
        }
        id.show().animate({'right': "0"}).addClass('visible');
    }
}

/**
 * swapSideBar -
 * Swaps the current side bar div with the new sidebar div to display based
 * on user nav selection.
 * Always uses 25% of screen to left of main window div.
 * @param id
 */
function swapSideBar(id) {
    if (!(id.hasClass('side-visible'))) {
        $('.side-visible').animate({'bottom': "-100%"}).hide().removeClass('side-visible');
        if (nav_visible) {
            id.css({'left': "20%", 'width': "25%"});
        }
        else {
            id.css({'left': "0", 'width': "25%"});
        }
        id.show().animate({'bottom': "0"}).addClass('side-visible');
    }
}

function toggleListMenu() {

    var menu_icon = $('#menu-icon');
    if (menu_icon.hasClass('glyphicon-remove')) {
        hideListMenu();
    }
    else {
        showListMenu();
    }
    menu_icon.toggleClass("glyphicon-list glyphicon-remove");
}

$('#toggle-user-post').click(function () {
    var toggle = $('#toggle-post-icon');
    if (toggle.hasClass('glyphicon-menu-up')) {
        $('#feed-header').animate({height: 70});
        $('#user-post').hide().addClass('user-post-invis');
    }
    else {
        $('#feed-header').animate({'height': "260px"}, 'slow');
        $('#user-post').show().removeClass('user-post-invis');
    }

    toggle.toggleClass("glyphicon-menu-up glyphicon-menu-down");
});

$(document).ready(function () {
    nav_visible = false;
    showMap();

    $('.nav-tabs a').click(function () {
        $(this).tab('show');
    });

    $('.menu-option button').hover(function () {
        $(this).stop().animate({
            'opacity': 1,
            'font-size': "25px"
        }, 300);
    }, function () {
        $(this).stop().animate({
            'opacity': 0.6,
            "font-size": '20px'
        }, 100);
    });

    $('#status-button').click(function () {
        swapMainWindow($('#status'));
        if (!($('#feed').hasClass('side-visible'))) {
            loadFeed();
        }
    });
    $('#map-button').click(function () {
        showMap();
    });
    $('#home-select').click(function () {
        showMap();
        toggleListMenu();
    });

    $('#account-select').click(function () {
        swapMainWindow($('#account'));
        swapSideBar($('#account-options'));
        toggleListMenu();
    });

    $('#poll-select').click(function () {
        swapMainWindow($('#poll-main'));
        swapSideBar($('#poll-sidebar'));
        toggleListMenu();

    });

    $('#info-select').click(function () {
        swapMainWindow($('#info-main'));
        swapSideBar($('#info-sidebar'));
        toggleListMenu();
    });
    $('#event-select').click(function () {
        swapMainWindow($('#event-calendar'));
        swapSideBar($('#event-detail-sidebar'));
        toggleListMenu();
    });

    $('#announce-index').click(function () {
        //getAnnouncements();
        swapMainWindow($('#announcement-main'));
        swapSideBar($('#announcement-sidebar'));
        toggleListMenu();
    });

    $('#poll-header').click(function (e) {
        e.preventDefault();
        $('.visible').animate({
            'right': "-100%"
        }).removeClass('visible');

        $('.side-visible').animate({
            'bottom': "-100%"
        }).removeClass('side-visible');

        window.location = "http://localhost:8000/polls/8/";
    });

    $('#list-menu-button').click(function () {
        var menu_icon = $('#menu-icon');
        if (menu_icon.hasClass('glyphicon-remove')) {
            hideListMenu();
        }
        else {
            showListMenu();
        }
        menu_icon.toggleClass("glyphicon-list glyphicon-remove");
    });

    $('.info-section-pill').click(function () {
        if (!$(this).hasClass('info-active')) {
            $('.info-active').removeClass('info-active');
            $(this).addClass('info-active');
            //$(this).tab('show');
        }
    });

    $('.info-section-pill a').click(function () {
        if (!$(this).parent().hasClass('info-active')) {
            $(this).tab('show');
        }
    });

// When new poll is created we reload the home page and
// swap the page to the events section
    $('#new-poll-form').bind('ajax:complete', function () {
        swapMainWindow($('#poll-main'));
        swapSideBar($('#poll-sidebar'));
    });

    $('#datetimepicker1').datetimepicker({
        format: "YY-MM-DD HH:mm:ss",
        defaultDate: "2016-01-01 00:00:00",
    });
    $('#datetimepicker2').datetimepicker({
        useCurrent: false, //Important! See issue #1075
        format: "YY-MM-DD HH:mm:ss",
        defaultDate: "2016-01-02 00:00:00"
    });
    $("#datetimepicker1").on("dp.change", function (e) {
        $('#datetimepicker2').data("DateTimePicker").minDate(e.date);
    });
    $("#datetimepicker2").on("dp.change", function (e) {
        $('#datetimepicker1').data("DateTimePicker").maxDate(e.date);
    });
});


text:
copyright:
  years: 2017
lastupdated: "2017-05-16"

---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Déploiement de ressources dans vos environnements
{: #deploying}

Avec {{site.data.keyword.bplong}}, vous pouvez déployer vos dernières modifications de code directement depuis votre code source. Lorsque vous déployez votre environnement, vous déployez les ressources qui sont définies par vos fichiers de configuration. Ensuite, vous pouvez gérer la mise à disposition, les orchestrations et le cycle de vie de l'environnement depuis {{site.data.keyword.bpshort}}.
{:shortdesc}

## Déploiement dans vos environnements à l'aide de l'interface graphique
{: #gui}

Si vous préférez une vue graphique pour déployer votre environnement, vous pouvez utiliser le tableau de bord {{site.data.keyword.bpshort}}.
{:shortdesc}

### Configuration requise
{: #gui-prereq}

* Stockez une configuration Terraform dans le contrôle des sources. Les configurations peuvent être écrites avec une syntaxe HCL (HashiCorp Configuration Language) ou JSON. Voir la documentation relative à la configuration de Terraform  pour des informations sur la syntaxe HCL et des instructions relatives à l'écriture de configurations. Voir le fournisseur de cloud {{site.data.keyword.IBM_notm}}  pour les ressources disponibles.

Après avoir stocké votre configuration :

1. Dans le tableau de bord **{{site.data.keyword.bpshort}}**, sélectionnez **Environments**.

2. Cliquez sur **Create Environment** pour ajouter un environnement ou sélectionnez la ligne d'un environnement existant à déployer.

3. Cliquez sur **Plan** pour prévisualiser les ressources qui seront mises à disposition lorsque vous déploierez votre environnement. Lorsque vous exécutez un plan, {{site.data.keyword.bpshort}} extrait les variables qui figurent dans les détails de votre environnement et la dernière version de votre configuration depuis le contrôle des sources. La sortie du plan compare la configuration aux éléments déployés en fonction de votre fichier d'état Terraform. Votre environnement est verrouillé et ne peut plus être modifié jusqu'à ce que le plan lui soit appliqué ou soit annulé.

4. Affichez le journal dans la section **Recent Activity** afin d'examiner la sortie du plan. Celle-ci indique si des erreurs existent et quelles sont les ressources que le service prévoit de créer, de changer ou de détruire.

5. Lorsque vous êtes prêt à lancer votre plan, cliquez sur **Apply**. Vous pouvez surveiller le journal d'activité pour vous assurer que l'application du plan a abouti au cours de la dernière exécution.

## Déploiement dans vos environnements à l'aide de l'interface de ligne de commande
{: #cli}

Vous pouvez utiliser le plug-in {{site.data.keyword.bpshort}} pour l'interface de ligne de commande de {{site.data.keyword.Bluemix_notm}} afin de déployer des mises à jour dans votre environnement.
{:shortdesc}

### Configuration requise
{: #cli-prereq}

* Stockez une configuration Terraform dans le contrôle des sources.
* Si vous ne l'avez pas déjà fait, installez l'interface de ligne de commande de {{site.data.keyword.Bluemix_notm}} pour votre système d'exploitation depuis le [référentiel d'interface de ligne de commande {{site.data.keyword.Bluemix_notm}}](http://clis.ng.bluemix.net/ui/home.html).

Après vous être connecté à l'interface de ligne de commande de {{site.data.keyword.Bluemix_notm}} :

1. Installez le plug-in d'interface de ligne de commande de {{site.data.keyword.bpshort}} en exécutant la commande suivante :

  ```
  bx plugin install schematics -r Bluemix
  ```
  {: codeblock}

  Le plug-in {{site.data.keyword.bpshort}} apparaît sous `bx plugin list` si l'installation aboutit.

2. Créez un environnement à partir de votre configuration. Lorsque vous créez votre environnement, vous faites pointer le service vers votre contrôle des sources pour qu'il puisse extraire le code le plus récent.

  ```
  bx schematics environment create --file NOM_FICHIER
  ```
  {: codeblock}

Tableau 1. Description de la commande environment create.

  Commande
  Action

  --file NOM_FICHIER
  Fichier JSON dans lequel sont stockés les détails de votre environnement.

Exemple de fichier JSON :

{
      "description": "(Optional) Description of the environment",
      "frozen": false,
      "name": "Name of the environment",
      "sourceurl": "The GitHub URL that points to the Terraform configuration",
      "tags": ["(Optional) metadata_tag_1", "(Optional) metadata_tag_2"],
      "terraformversion": "0.9",
      "variablestore": [{
          "name": "(Optional) variable_1",
          "secure": false,
          "value": "Visible value"
      },
      {
          "name": "(Optional) variable_2_secret",
          "secure": true,
          "value": "Secured value"
      }]
  }

  Notez la valeur `ID` qui est renvoyée. `ID` est un identificateur unique qui est affecté à votre environnement et utilisé dans les commandes qui suivent.

3. Exécutez la commande `plan` pour un aperçu des changements qui seront appliqués à votre environnement. La commande plan affiche les ressources qui changeront ainsi que leur nombre comparé aux éléments déployés, mais les changements ne sont pas appliqués tant que vous n'exécutez pas la commande `apply`.

  ```
  bx schematics action plan --id ID_ENVIRONNEMENT
```
  {: codeblock}

Tableau 2. Description de la commande plan.

  Commande
  Action

  --id ID_ENVIRONNEMENT
  Environnement spécifique pour lequel lancer un plan d'exécution. Vous pouvez exécuter bx schematics list si vous devez extraire la valeur de l'ID d'environnement.

  Un ID d'activité `ID_ACTIVITE` est affecté au plan et enregistré dans le journal d'activité.

4. Procédez à l'extraction du journal d'activité pour afficher la sortie du plan Terraform.

  ```
  bx schematics activity log --id ID_ACTIVITE
  ```
  {: codeblock}

Tableau 3. Description de la commande log.

  Commande
  Action

  --id ID_ACTIVITE
  Activité spécifique pour laquelle afficher le journal. Vous pouvez exécuter bx schematics activity list --id ID_ENVIRONNEMENT si vous devez extraire la valeur de l'ID d'activité.

5. Exécutez la commande `apply` pour déployer des ressources dans votre environnement.

  ```
  bx schematics action apply --id ID_ENVIRONNEMENT
  ```
  {: codeblock}

Tableau 4. Description de la commande apply.

  Commande
  Action

  --id ID_ENVIRONNEMENT
  Environnement spécifique dans lequel déployer des mises à jour. Vous pouvez exécuter bx schematics list si vous devez extraire la valeur de l'ID d'environnement.

6. Surveillez la sortie d'application pour vérifier que le déploiement a abouti.

  ```
  bx schematics activity log --id ID_ACTIVITE
  ```
  {: codeblock}

  Si le déploiement a réussi, la ligne suivante apparâit vers la fin de la sortie :

  ```
  Apply complete! Resources: N added, N changed, N destroyed.
  ```
  {: screen}

## Déploiement dans vos environnements à l'aide de l'API
{: #api}

Vous pouvez déployer votre environnement à l'aide d'un programme avec l'API {{site.data.keyword.bpshort}}.
{:shortdesc}

Les appels de l'API {{site.data.keyword.bpshort}}  pointent vers le noeud final de base suivant :

```
https://us-south.schematics.bluemix.net
```
{: codeblock}

### Configuration requise
{: #api-prereq}

* Stockez une configuration Terraform dans le contrôle des sources.

Procédez comme suit pour déployer des ressources dans votre environnement :

1. Générez un jeton OAuth IAM à utiliser dans votre en-tête d'authentification. La commande génère un jeton UAA et un jeton IAM.

  ```
  bx iam oauth-tokens
  ```
  {: codeblock}

  Exemple de sortie :
  ```
  IAM token:  Bearer eyJraWQ...
  ```
  {: screen}

  La sortie `Bearer eyJraWQ...` est un exemple tronqué du jeton IAM. Incluez le jeton complet dans l'en-tête de vos appels d'API.

2. Créez un environnement en exécutant un appel `POST v1/environments`.

  ```
  curl -X POST \
    https://us-south.schematics.bluemix.net/v1/environments \
    -H 'accept: text/plain' \
    -H 'authorization: bearer <jeton_IAM>' \
    -H 'content-type: application/json' \
    -d '{
    "description": "(Optional) Description of the environment",
    "frozen": false,
    "name": "Name of the environment",
    "sourceurl": "The GitHub URL that points to the Terraform configuration",
    "tags": [
      "(Optional) metadata_tag_1",
      "(Optional) metadata_tag_2"
    ],
    "terraformversion": "0.9",
    "variablestore": [{
        "name": "(Optional) variable_1",
        "secure": false,
        "value": "Visible value"
    },
    {
        "name": "(Optional) variable_2_secret",
        "secure": true,
        "value": "Secured value"
    }]
  }'
  ```
  {: codeblock}

  La sortie suivante dénote la réussite de l'opération :
  ```
  {
    "id": "Environment ID",
    "name": "Environment name",
    "description": "Description of the environment",
    "account": "{{site.data.keyword.Bluemix_notm}} account GUID",
    "owner": "The IBMid of the user who created the environment",
    "creationtime": "YYYY-MM-DDTHH:MM:SSZ",
    "status": "CREATED",
    "frozen": false,
    "sourceurl": "The GitHub URL that points to the configuration",
    "statefile": "The reference to the Terraform state file",
    "terraformversion": "0.9",
    "tags": [
      "metadata_tag_1",
      "metadata_tag_2"
    ],
    "variablestore": [
      {
        "name": "(Optional) variable_1",
        "value": "Visible value"
      }
    ]
  }
  ```
  {: screen}

  Notez la valeur `id` qui est renvoyée. `id` est un identificateur unique qui est affecté à votre environnement et utilisé dans les appels qui suivent.

3. Exécutez l'appel `POST v1/environments/<ID_environnement>/plan` pour un aperçu des ressources qui seront déployées dans votre environnement lorsque vous appliquerez votre configuration. Les plans extraient les configurations d'environnement dans la branche maître de votre référentiel.

  ```
  curl -X POST \
    https://us-south.schematics.bluemix.net/v1/environments/<ID_environnement>/plan \
    -H 'accept: application/json' \
    -H 'authorization: bearer <jeton_IAM>' \
    -H 'content-type: application/json'
  ```
  {: codeblock}

  Une réponse dénotant la réussite de l'opération renvoie un élément `activityid`. La valeur de l'ID d'activité est nécessaire pour afficher les journaux, comme la sortie du plan et de l'application.
  ```
  {
    "activityid": "<ID_activité>"
  }
  ```
  {: screen}

4. Exécutez l'appel `GET v1/environments/<ID_environnement>/activities/<ID_activité>/log` pour afficher la sortie du plan.

  ```
  curl -X GET \
    https://us-south.schematics.bluemix.net/v1/environments/<ID_environnement>/activities/<ID_activité>/log \
    -H 'accept: text/html' \
    -H 'authorization: bearer <jeton_IAM>'
  ```
  {: codeblock}

5. Déployez votre environnement en exécutant l'appel `PUT v1/environments/<ID_environnement>/apply/`.

  ```
  curl -X PUT \
    https://us-south.schematics.bluemix.net/v1/environments/<ID_environnement>/apply \
    -H 'accept: application/json' \
    -H 'authorization: bearer <jeton_IAM>' \
    -H 'content-type: application/json'
  ```
  {: codeblock}

6. Surveillez le déploiement en exécutant l'appel `GET v1/environments/<ID_environnement>/activities/<ID_activité>/log` pour afficher la sortie de l'application.

  ```
  curl -X GET \
    https://us-south.schematics.bluemix.net/v1/environments/<ID_environnement>/activities/<ID_activité>/log \
    -H 'accept: text/html' \
    -H 'authorization: bearer <jeton_IAM>'
  ```
  {: codeblock}

  Si le déploiement a réussi, la ligne suivante apparaît vers la fin de la sortie :

  ```
  Apply complete! Resources: N added, N changed, N destroyed.
  ```
  {: screen}


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

namespace Moq
{
	// @mbrit - 2012-05-31 - special exception to stand-in for the MissingMethodException
	// that's not in WinRT.
	public class SpecialMissingMethodException : Exception
	{
		public SpecialMissingMethodException(string message)
			: base(message)
		{
		}
	}
}


text:
import unittest

from pads.integer_partitions import mckay
from pads.integer_partitions import fixed_length_partitions
from pads.integer_partitions import partitions
from pads.integer_partitions import conjugate
from pads.integer_partitions import binary_partitions
from pads.integer_partitions import lex_partitions
from pads.integer_partitions import revlex_partitions

class PartitionTest(unittest.TestCase):
    counts = [1,1,2,3,5,7,11,15,22,30,42,56,77,101,135]

    def testCounts(self):
        """Check that each generator has the right number of outputs."""
        for n in range(len(self.counts)):
            self.assertEqual(self.counts[n],len(list(mckay(n))))
            self.assertEqual(self.counts[n],len(list(lex_partitions(n))))
            self.assertEqual(self.counts[n],len(list(revlex_partitions(n))))

    def testSums(self):
        """Check that all outputs are partitions of the input."""
        for n in range(len(self.counts)):
            for p in mckay(n):
                self.assertEqual(n,sum(p))
            for p in revlex_partitions(n):
                self.assertEqual(n,sum(p))
            for p in lex_partitions(n):
                self.assertEqual(n,sum(p))

    def testRevLex(self):
        """Check that the revlex generators' outputs are in revlex order."""
        for n in range(len(self.counts)):
            last = [n+1]
            for p in mckay(n):
                self.assertGreater(last, p)
                last = list(p)  # make less-mutable copy
            last = [n+1]
            for p in revlex_partitions(n):
                self.assertGreater(last, p)
                last = list(p)  # make less-mutable copy

    def testLex(self):
        """Check that the lex generator's outputs are in lex order."""
        for n in range(1,len(self.counts)):
            last = []
            for p in lex_partitions(n):
                self.assertLess(last, p)
                last = list(p)  # make less-mutable copy

    def testRange(self):
        """Check that all numbers in output partitions are in range."""
        for n in range(len(self.counts)):
            for p in mckay(n):
                for x in p:
                    self.assertLess(0, x)
                    self.assertLessEqual(x, n)
            for p in lex_partitions(n):
                for x in p:
                    self.assertLess(0, x)
                    self.assertLessEqual(x, n)
            for p in revlex_partitions(n):
                for x in p:
                    self.assertLess(0, x)
                    self.assertLessEqual(x, n)

    def testFixedLength(self):
        """Check that the fixed length partition outputs are correct."""
        for n in range(len(self.counts)):
            pn = [list(p) for p in revlex_partitions(n)]
            pn.sort()
            np = 0
            for L in range(n+1):
                pnL = [list(p) for p in fixed_length_partitions(n,L)]
                pnL.sort()
                np += len(pnL)
                self.assertEqual(pnL,[p for p in pn if len(p) == L])
            self.assertEqual(np,len(pn))

    def testConjugatePartition(self):
        """Check that conjugating a partition forms another partition."""
        for n in range(len(self.counts)):
            for p in partitions(n):
                c = conjugate(p)
                for x in c:
                    self.assertLess(0, x)
                    self.assertLessEqual(x, n)
                self.assertEqual(sum(c),n)

    def testConjugateInvolution(self):
        """Check that double conjugation returns the same partition."""
        for n in range(len(self.counts)):
            for p in partitions(n):
                self.assertEqual(p,conjugate(conjugate(p)))

    def testConjugateMaxLen(self):
        """Check the max-length reversing property of conjugation."""
        for n in range(1,len(self.counts)):
            for p in partitions(n):
                self.assertEqual(len(p),max(conjugate(p)))

    def testBinary(self):
        """Test that the binary partitions are generated correctly."""
        for n in range(len(self.counts)):
            binaries = []
            for p in partitions(n):
                for x in p:
                    if x & (x - 1):
                        break
                else:
                    binaries.append(list(p))
            self.assertEqual(binaries,[list(p) for p in binary_partitions(n)])


text:
package test.guice;

import org.testng.TestNG;
import org.testng.annotations.Test;

import test.SimpleBaseTest;
import junit.framework.Assert;

public class GuiceTest extends SimpleBaseTest {

  @Test
  public void guiceTest() {
    TestNG tng = create(new Class[] { Guice1Test.class, Guice2Test.class});
    Guice1Test.m_object = null;
    Guice2Test.m_object = null;
    tng.run();

    Assert.assertNotNull(Guice1Test.m_object);
    Assert.assertNotNull(Guice2Test.m_object);
    Assert.assertEquals(Guice1Test.m_object, Guice2Test.m_object);
  }

  @Test
  public void guiceWithNoModules() {
    TestNG tng = create(new Class[] { GuiceNoModuleTest.class });
    tng.run();
  }
}


text:
package de.haw_hamburg.vs_ws2015.spahl_haug.frontend.common.windows;

public interface ILoginActions extends IWindowActions{
	public void onLogin(final String userName) throws RepositoryException;
}


text:
<?php

namespace Behat\Behat\Formatter;

use Behat\Behat\Event\EventInterface,
    Behat\Behat\Event\FeatureEvent,
    Behat\Behat\Event\ScenarioEvent,
    Behat\Behat\Event\OutlineExampleEvent,
    Behat\Behat\Event\StepEvent;

use Behat\Gherkin\Node\FeatureNode,
    Behat\Gherkin\Node\ScenarioNode,
    Behat\Gherkin\Node\StepNode,
    Behat\Behat\Exception\FormatterException;

/**
 * Progress formatter.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class JUnitFormatter extends ConsoleFormatter
{
    /**
     * Current XML filename.
     *
     * @var string
     */
    protected $filename;
    /**
     * Test cases.
     *
     * @var array
     */
    protected $testcases = array();
    /**
     * Total steps count.
     *
     * @var integer
     */
    protected $stepsCount = 0;
    /**
     * Total exceptions count.
     *
     * @var integer
     */
    protected $exceptionsCount = 0;
    /**
     * Step exceptions.
     *
     * @var array
     */
    protected $exceptions = array();
    /**
     * Feature start time.
     *
     * @var float
     */
    protected $featureStartTime;
    /**
     * Scenario start time.
     *
     * @var float
     */
    protected $scenarioStartTime;

    /**
     * {@inheritdoc}
     */
    protected function getDefaultParameters()
    {
        return array();
    }

    /**
     * Returns an array of event names this subscriber wants to listen to.
     *
     * The array keys are event names and the value can be:
     *
     *  * The method name to call (priority defaults to 0)
     *  * An array composed of the method name to call and the priority
     *  * An array of arrays composed of the method names to call and respective
     *    priorities, or 0 if unset
     *
     * For instance:
     *
     *  * array('eventName' => 'methodName')
     *  * array('eventName' => array('methodName', $priority))
     *  * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
     *
     * @return array The event names to listen to
     */
    public static function getSubscribedEvents()
    {
        $events = array(
            'beforeFeature', 'afterFeature', 'beforeScenario', 'afterScenario',
            'beforeOutlineExample', 'afterOutlineExample', 'afterStep'
        );

        return array_combine($events, $events);
    }

    /**
     * Listens to "feature.before" event.
     *
     * @param FeatureEvent $event
     *
     * @uses printTestSuiteHeader()
     */
    public function beforeFeature(FeatureEvent $event)
    {
        $feature = $event->getFeature();
        $this->filename = 'TEST-' . basename($feature->getFile(), '.feature') . '.xml';

        $this->printTestSuiteHeader($feature);

        $this->stepsCount       = 0;
        $this->testcases        = array();
        $this->exceptionsCount  = 0;
        $this->featureStartTime = microtime(true);
    }

    /**
     * Listens to "feature.after" event.
     *
     * @param FeatureEvent $event
     *
     * @uses printTestSuiteFooter()
     * @uses flushOutputConsole()
     */
    public function afterFeature(FeatureEvent $event)
    {
        $this->printTestSuiteFooter($event->getFeature(), microtime(true) - $this->featureStartTime);
        $this->flushOutputConsole();
    }

    /**
     * Listens to "scenario.before" event.
     *
     * @param ScenarioEvent $event
     */
    public function beforeScenario(ScenarioEvent $event)
    {
        $this->scenarioStartTime = microtime(true);
    }

    /**
     * Listens to "scenario.after" event.
     *
     * @param ScenarioEvent $event
     *
     * @uses printTestCase()
     */
    public function afterScenario(ScenarioEvent $event)
    {
        $this->printTestCase($event->getScenario(), microtime(true) - $this->scenarioStartTime, $event);
    }

    /**
     * Listens to "outline.example.before" event.
     *
     * @param OutlineExampleEvent $event
     */
    public function beforeOutlineExample(OutlineExampleEvent $event)
    {
        $this->scenarioStartTime = microtime(true);
    }

    /**
     * Listens to "outline.example.after" event.
     *
     * @param OutlineExampleEvent $event
     *
     * @uses printTestCase()
     */
    public function afterOutlineExample(OutlineExampleEvent $event)
    {
        $this->printTestCase($event->getOutline(), microtime(true) - $this->scenarioStartTime, $event);
    }

    /**
     * Listens to "step.after" event.
     *
     * @param StepEvent $event
     */
    public function afterStep(StepEvent $event)
    {
        if ($event->hasException()) {
            $this->exceptions[] = $event->getException();
            $this->exceptionsCount++;
        }

        ++$this->stepsCount;
    }

    /**
     * Prints testsuite header.
     *
     * @param FeatureNode $feature
     */
    protected function printTestSuiteHeader(FeatureNode $feature)
    {
        $this->writeln('<?xml version="1.0" encoding="UTF-8"?>');
    }

    /**
     * Prints testsuite footer.
     *
     * @param FeatureNode $feature
     * @param float       $time
     */
    protected function printTestSuiteFooter(FeatureNode $feature, $time)
    {
        $suiteStats = sprintf('classname="behat.features" errors="0" failures="%d" name="%s" file="%s" tests="%d" time="%F"',
            $this->exceptionsCount,
            htmlspecialchars($feature->getTitle()),
            htmlspecialchars($feature->getFile()),
            $this->stepsCount,
            $time
        );

        $this->writeln("<testsuite $suiteStats>");
        $this->writeln(implode("\n", $this->testcases));
        $this->writeln('</testsuite>');
    }

    /**
     * Prints testcase.
     *
     * @param ScenarioNode   $scenario
     * @param float          $time
     * @param EventInterface $event
     */
    protected function printTestCase(ScenarioNode $scenario, $time, EventInterface $event)
    {
        $className  = $scenario->getFeature()->getTitle();
        $name       = $scenario->getTitle();
        $name      .= $event instanceof OutlineExampleEvent
                    ? ', Ex #' . ($event->getIteration() + 1)
                    : '';
        $caseStats  = sprintf('classname="%s" name="%s" time="%F"',
            htmlspecialchars($className),
            htmlspecialchars($name),
            $time
        );

        $xml  = "    <testcase $caseStats>\n";

        foreach ($this->exceptions as $exception) {
            $error = $this->exceptionToString($exception);
            $xml .= sprintf(
                '        <failure message="%s" type="%s">',
                htmlspecialchars($error),
                $this->getResultColorCode($event->getResult())
            );
            $exception = str_replace(array('<![CDATA[', ']]>'), '', (string) $exception);
            $xml .= "<![CDATA[\n$exception\n]]></failure>\n";
        }
        $this->exceptions = array();

        $xml .= "    </testcase>";

        $this->testcases[] = $xml;
    }

    /**
     * {@inheritdoc}
     */
    protected function createOutputStream()
    {
        $outputPath = $this->parameters->get('output_path');

        if (null === $outputPath) {
            throw new FormatterException(sprintf(
                'You should specify "output_path" parameter for %s', get_class($this)
            ));
        } elseif (is_file($outputPath)) {
            throw new FormatterException(sprintf(
                'Directory path expected as "output_path" parameter of %s, but got: %s',
                get_class($this),
                $outputPath
            ));
        }

        if (!is_dir($outputPath)) {
            mkdir($outputPath, 0777, true);
        }

        return fopen($outputPath . DIRECTORY_SEPARATOR . $this->filename, 'w');
    }
}


text:
/**
 * Imports
 */
import React from 'react';

/**
 * Component
 */
class ServerError extends React.Component {

    //*** Page Title and Snippets ***//

    static pageTitleAndSnippets = function (context) {
        return {
            title: 'Server Error'
        }
    };

    //*** Template ***//

    render() {
        return
Server Error
;
    }
}

/**
 * Exports
 */
export default ServerError;


text:
package org.apache.hadoop.hive.ql.io;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.txn.ValidCompactorTxnList;
import org.apache.hadoop.hive.common.ValidReadTxnList;
import org.apache.hadoop.hive.ql.io.orc.TestInputOutputFormat;
import org.apache.hadoop.hive.ql.io.orc.TestInputOutputFormat.MockFile;
import org.apache.hadoop.hive.ql.io.orc.TestInputOutputFormat.MockFileSystem;
import org.apache.hadoop.hive.ql.io.orc.TestInputOutputFormat.MockPath;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class TestAcidUtils {

  @Test
  public void testCreateFilename() throws Exception {
    Path p = new Path("/tmp");
    Configuration conf = new Configuration();
    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf)
        .setOldStyle(true).bucket(1);
    assertEquals("/tmp/00001_0",
        AcidUtils.createFilename(p, options).toString());
    options.bucket(123);
    assertEquals("/tmp/00123_0",
        AcidUtils.createFilename(p, options).toString());
    options.bucket(23)
        .minimumTransactionId(100)
        .maximumTransactionId(200)
        .writingBase(true)
        .setOldStyle(false);
    assertEquals("/tmp/base_0000200/bucket_00023",
        AcidUtils.createFilename(p, options).toString());
    options.writingBase(false);
    assertEquals("/tmp/delta_0000100_0000200/bucket_00023",
        AcidUtils.createFilename(p, options).toString());
  }

  @Test
  public void testParsing() throws Exception {
    assertEquals(123, AcidUtils.parseBase(new Path("/tmp/base_000123")));
    Path dir = new Path("/tmp/tbl");
    Configuration conf = new Configuration();
    AcidOutputFormat.Options opts =
        AcidUtils.parseBaseBucketFilename(new Path(dir, "base_567/bucket_123"),
            conf);
    assertEquals(false, opts.getOldStyle());
    assertEquals(true, opts.isWritingBase());
    assertEquals(567, opts.getMaximumTransactionId());
    assertEquals(0, opts.getMinimumTransactionId());
    assertEquals(123, opts.getBucket());
    opts = AcidUtils.parseBaseBucketFilename(new Path(dir, "000123_0"), conf);
    assertEquals(true, opts.getOldStyle());
    assertEquals(true, opts.isWritingBase());
    assertEquals(123, opts.getBucket());
    assertEquals(0, opts.getMinimumTransactionId());
    assertEquals(0, opts.getMaximumTransactionId());
  }

  @Test
  public void testOriginal() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/000000_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000001_1", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000002_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/random", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/_done", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/subdir/000000_0", 0, new byte[0]));
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(new MockPath(fs, "/tbl/part1"), conf,
            new ValidReadTxnList("100:"));
    assertEquals(null, dir.getBaseDirectory());
    assertEquals(0, dir.getCurrentDirectories().size());
    assertEquals(0, dir.getObsolete().size());
    List<FileStatus> result = dir.getOriginalFiles();
    assertEquals(5, result.size());
    assertEquals("mock:/tbl/part1/000000_0", result.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/000001_1", result.get(1).getPath().toString());
    assertEquals("mock:/tbl/part1/000002_0", result.get(2).getPath().toString());
    assertEquals("mock:/tbl/part1/random", result.get(3).getPath().toString());
    assertEquals("mock:/tbl/part1/subdir/000000_0", result.get(4).getPath().toString());
  }

  @Test
  public void testOriginalDeltas() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/000000_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000001_1", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000002_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/random", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/_done", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/subdir/000000_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_025_025/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_029_029/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_025_030/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_050_100/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_101_101/bucket_0", 0, new byte[0]));
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(new TestInputOutputFormat.MockPath(fs,
            "mock:/tbl/part1"), conf, new ValidReadTxnList("100:"));
    assertEquals(null, dir.getBaseDirectory());
    List<FileStatus> obsolete = dir.getObsolete();
    assertEquals(2, obsolete.size());
    assertEquals("mock:/tbl/part1/delta_025_025",
        obsolete.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_029_029",
        obsolete.get(1).getPath().toString());
    List<FileStatus> result = dir.getOriginalFiles();
    assertEquals(5, result.size());
    assertEquals("mock:/tbl/part1/000000_0", result.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/000001_1", result.get(1).getPath().toString());
    assertEquals("mock:/tbl/part1/000002_0", result.get(2).getPath().toString());
    assertEquals("mock:/tbl/part1/random", result.get(3).getPath().toString());
    assertEquals("mock:/tbl/part1/subdir/000000_0", result.get(4).getPath().toString());
    List<AcidUtils.ParsedDelta> deltas = dir.getCurrentDirectories();
    assertEquals(2, deltas.size());
    AcidUtils.ParsedDelta delt = deltas.get(0);
    assertEquals("mock:/tbl/part1/delta_025_030", delt.getPath().toString());
    assertEquals(25, delt.getMinTransaction());
    assertEquals(30, delt.getMaxTransaction());
    delt = deltas.get(1);
    assertEquals("mock:/tbl/part1/delta_050_100", delt.getPath().toString());
    assertEquals(50, delt.getMinTransaction());
    assertEquals(100, delt.getMaxTransaction());
  }

  @Test
  public void testBaseDeltas() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/base_5/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_10/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_49/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_025_025/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_029_029/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_025_030/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_050_105/bucket_0", 0, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_90_120/bucket_0", 0, new byte[0]));
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(new TestInputOutputFormat.MockPath(fs,
            "mock:/tbl/part1"), conf, new ValidReadTxnList("100:"));
    assertEquals("mock:/tbl/part1/base_49", dir.getBaseDirectory().toString());
    List<FileStatus> obsolete = dir.getObsolete();
    assertEquals(5, obsolete.size());
    assertEquals("mock:/tbl/part1/base_10", obsolete.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/base_5", obsolete.get(1).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_025_030", obsolete.get(2).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_025_025", obsolete.get(3).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_029_029", obsolete.get(4).getPath().toString());
    assertEquals(0, dir.getOriginalFiles().size());
    List<AcidUtils.ParsedDelta> deltas = dir.getCurrentDirectories();
    assertEquals(1, deltas.size());
    AcidUtils.ParsedDelta delt = deltas.get(0);
    assertEquals("mock:/tbl/part1/delta_050_105", delt.getPath().toString());
    assertEquals(50, delt.getMinTransaction());
    assertEquals(105, delt.getMaxTransaction());
  }

  @Test
  public void testBestBase() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/base_5/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_10/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_25/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_100/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_200/bucket_0", 500, new byte[0]));
    Path part = new MockPath(fs, "/tbl/part1");
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(part, conf, new ValidReadTxnList("150:"));
    assertEquals("mock:/tbl/part1/base_200", dir.getBaseDirectory().toString());
    List<FileStatus> obsoletes = dir.getObsolete();
    assertEquals(4, obsoletes.size());
    assertEquals("mock:/tbl/part1/base_10", obsoletes.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/base_100", obsoletes.get(1).getPath().toString());
    assertEquals("mock:/tbl/part1/base_25", obsoletes.get(2).getPath().toString());
    assertEquals("mock:/tbl/part1/base_5", obsoletes.get(3).getPath().toString());
    assertEquals(0, dir.getOriginalFiles().size());
    assertEquals(0, dir.getCurrentDirectories().size());
    // we should always get the latest base
    dir = AcidUtils.getAcidState(part, conf, new ValidReadTxnList("10:"));
    assertEquals("mock:/tbl/part1/base_200", dir.getBaseDirectory().toString());
  }

  @Test
  public void testObsoleteOriginals() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/base_10/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_5/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000000_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/000001_1", 500, new byte[0]));
    Path part = new MockPath(fs, "/tbl/part1");
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(part, conf, new ValidReadTxnList("150:"));
    // The two original buckets won't be in the obsolete list because we don't look at those
    // until we have determined there is no base.
    List<FileStatus> obsolete = dir.getObsolete();
    assertEquals(1, obsolete.size());
    assertEquals("mock:/tbl/part1/base_5", obsolete.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/base_10", dir.getBaseDirectory().toString());
  }

  @Test
  public void testOverlapingDelta() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/delta_0000063_63/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_000062_62/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_00061_61/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_40_60/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_0060_60/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_052_55/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_40_60/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/base_50/bucket_0", 500, new byte[0]));
    Path part = new MockPath(fs, "mock:/tbl/part1");
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(part, conf, new ValidReadTxnList("100:"));
    assertEquals("mock:/tbl/part1/base_50", dir.getBaseDirectory().toString());
    List<FileStatus> obsolete = dir.getObsolete();
    assertEquals(2, obsolete.size());
    assertEquals("mock:/tbl/part1/delta_052_55", obsolete.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_0060_60", obsolete.get(1).getPath().toString());
    List<AcidUtils.ParsedDelta> delts = dir.getCurrentDirectories();
    assertEquals(4, delts.size());
    assertEquals("mock:/tbl/part1/delta_40_60", delts.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_00061_61", delts.get(1).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_000062_62", delts.get(2).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_0000063_63", delts.get(3).getPath().toString());
  }

  @Test
  public void deltasWithOpenTxnInRead() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/delta_1_1/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_2_5/bucket_0", 500, new byte[0]));
    Path part = new MockPath(fs, "mock:/tbl/part1");
    AcidUtils.Directory dir = AcidUtils.getAcidState(part, conf, new ValidReadTxnList("100:4"));
    List<AcidUtils.ParsedDelta> delts = dir.getCurrentDirectories();
    assertEquals(2, delts.size());
    assertEquals("mock:/tbl/part1/delta_1_1", delts.get(0).getPath().toString());
    assertEquals("mock:/tbl/part1/delta_2_5", delts.get(1).getPath().toString());
  }

  @Test
  public void deltasWithOpenTxnsNotInCompact() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/delta_1_1/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_2_5/bucket_0", 500, new byte[0]));
    Path part = new MockPath(fs, "mock:/tbl/part1");
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(part, conf, new ValidCompactorTxnList("100:4"));
    List<AcidUtils.ParsedDelta> delts = dir.getCurrentDirectories();
    assertEquals(1, delts.size());
    assertEquals("mock:/tbl/part1/delta_1_1", delts.get(0).getPath().toString());
  }

  @Test
  public void deltasWithOpenTxnsNotInCompact2() throws Exception {
    Configuration conf = new Configuration();
    MockFileSystem fs = new MockFileSystem(conf,
        new MockFile("mock:/tbl/part1/delta_1_1/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_2_5/bucket_0", 500, new byte[0]),
        new MockFile("mock:/tbl/part1/delta_2_5/bucket_0" + AcidUtils.DELTA_SIDE_FILE_SUFFIX, 500,
            new byte[0]),
        new MockFile("mock:/tbl/part1/delta_6_10/bucket_0", 500, new byte[0]));
    Path part = new MockPath(fs, "mock:/tbl/part1");
    AcidUtils.Directory dir =
        AcidUtils.getAcidState(part, conf, new ValidCompactorTxnList("100:4"));
    List<AcidUtils.ParsedDelta> delts = dir.getCurrentDirectories();
    assertEquals(1, delts.size());
    assertEquals("mock:/tbl/part1/delta_1_1", delts.get(0).getPath().toString());
  }

}


text:
namespace content {

class ServiceWorkerDevToolsAgentHost : public WorkerDevToolsAgentHost {
 public:
  using List = std::vector<scoped_refptr<ServiceWorkerDevToolsAgentHost>>;
  using Map = std::map<std::string,
                       scoped_refptr<ServiceWorkerDevToolsAgentHost>>;
  using ServiceWorkerIdentifier =
      ServiceWorkerDevToolsManager::ServiceWorkerIdentifier;

  ServiceWorkerDevToolsAgentHost(WorkerId worker_id,
                                 const ServiceWorkerIdentifier& service_worker,
                                 bool is_installed_version);

  void UnregisterWorker();

  // DevToolsAgentHost overrides.
  Type GetType() override;
  std::string GetTitle() override;
  GURL GetURL() override;
  bool Activate() override;
  bool Close() override;

  // WorkerDevToolsAgentHost overrides.
  void OnAttachedStateChanged(bool attached) override;

  void WorkerVersionInstalled();
  void WorkerVersionDoomed();

  int64_t service_worker_version_id() const;
  GURL scope() const;

  // If the ServiceWorker has been installed before the worker instance started,
  // it returns the time when the instance started. Otherwise returns the time
  // when the ServiceWorker was installed.
  base::Time version_installed_time() const { return version_installed_time_; }

  // Returns the time when the ServiceWorker was doomed.
  base::Time version_doomed_time() const { return version_doomed_time_; }

  bool Matches(const ServiceWorkerIdentifier& other);

 private:
  ~ServiceWorkerDevToolsAgentHost() override;
  std::unique_ptr<ServiceWorkerIdentifier> service_worker_;
  std::unique_ptr<devtools::network::NetworkHandler> network_handler_;
  base::Time version_installed_time_;
  base::Time version_doomed_time_;

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerDevToolsAgentHost);
};

}  // namespace content

#endif  // CONTENT_BROWSER_DEVTOOLS_SERVICE_WORKER_DEVTOOLS_AGENT_HOST_H_


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.javadoc/1">
    <module_version install_time="1370465845279" last="true" origin="installer" specification_version="1.44.1">
        <file crc="2725695938" name="config/Modules/org-netbeans-modules-javadoc.xml"/>
        <file crc="1567654442" name="modules/locale/org-netbeans-modules-javadoc_ja.jar"/>
        <file crc="2763266306" name="modules/locale/org-netbeans-modules-javadoc_pt_BR.jar"/>
        <file crc="3794088866" name="modules/locale/org-netbeans-modules-javadoc_ru.jar"/>
        <file crc="1704436411" name="modules/locale/org-netbeans-modules-javadoc_zh_CN.jar"/>
        <file crc="3346695658" name="modules/org-netbeans-modules-javadoc.jar"/>
    </module_version>
</module>


text:
import cssifyFontFace from '../cssifyFontFace'

describe('Cssifying font faces', () => {
  it('should generate a valid CSS string', () => {
    expect(
      cssifyFontFace({
        fontFamily: '"Bar"',
        fontWeight: 300,
        src: 'url(foo/bar.ttf) format(ttf)',
      })
    ).toEqual(
      '@font-face{font-family:"Bar";font-weight:300;src:url(foo/bar.ttf) format(ttf)}'
    )
  })
})


text:
FROM java:8
MAINTAINER Luis Arias <luis@balsamiq.com>

RUN \
  apt-get update && \
  apt-get -y upgrade && apt-get -y install curl wget supervisor cron

# Install elasticsearch

WORKDIR /opt
RUN wget --no-check-certificate -O- https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.4.4.tar.gz | tar xvfz -
RUN mv elasticsearch-1.4.4 elasticsearch

# Install elasticsearch cloud aws plugin
RUN cd elasticsearch && bin/plugin -install elasticsearch/elasticsearch-cloud-aws/2.4.1

ENV ES_CLUSTER_NAME elasticsearch
ENV ES_AWS_REGION us-east-1

EXPOSE 9200 9300

ADD es_rotate /opt/es_rotate
RUN chmod +x /opt/es_rotate

ADD es.crontab /opt/es.crontab
RUN crontab /opt/es.crontab

ADD supervisord.conf /etc/supervisor/conf.d/elasticsearch.conf

ADD run ./run
RUN chmod +x ./run
CMD ./run


text:
title: A (attach) icon button for use in mBlazonry components
---

This is a (attach) icon button for multipurpose use with mblazonry components. Use unicode "f0c6" to call attachment icon


text:
cask "pragli" do
  version "22.5.4"
  sha256 :no_check

  url "https://storage.googleapis.com/always-on-cdf01.appspot.com/dist/Pesto%20(Pragli).dmg",
      verified: "storage.googleapis.com/always-on-cdf01.appspot.com/"
  name "Pragli"
  desc "Virtual office for remote teams"
  homepage "https://pragli.com/"

  livecheck do
    url "https://storage.googleapis.com/always-on-cdf01.appspot.com/dist/latest-mac.yml"
    strategy :electron_builder
  end

  app "Pesto (Pragli).app"

  zap trash: [
    "~/Library/Application Support/Pragli",
    "~/Library/Logs/Pragli",
    "~/Library/Preferences/pragli.com.plist",
    "~/Library/Saved Application State/pragli.com.savedState",
  ]
end


text:
import { coordAll, featureEach } from '@turf/meta';
import { getCoords } from '@turf/invariant';
import { featureCollection, isObject, isNumber } from '@turf/helpers';
import centerMean from '@turf/center-mean';
import pointsWithinPolygon from '@turf/points-within-polygon';
import ellipse from '@turf/ellipse';

/**
 * Takes a {@link FeatureCollection} and returns a standard deviational ellipse,
 * also known as a "directional distribution." The standard deviational ellipse
 * aims to show the direction and the distribution of a dataset by drawing
 * an ellipse that contains about one standard deviation's worth (~ 70%) of the
 * data.
 *
 * This module mirrors the functionality of [Directional Distribution](http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-statistics-toolbox/directional-distribution.htm)
 * in ArcGIS and the [QGIS Standard Deviational Ellipse Plugin](http://arken.nmbu.no/~havatv/gis/qgisplugins/SDEllipse/)
 *
 * **Bibliography**
 *
 * • Robert S. Yuill, "The Standard Deviational Ellipse; An Updated Tool for
 * Spatial Description," _Geografiska Annaler_ 53, no. 1 (1971): 28–39,
 * doi:{@link https://doi.org/10.2307/490885|10.2307/490885}.
 *
 * • Paul Hanly Furfey, "A Note on Lefever's "Standard Deviational Ellipse,"
 * _American Journal of Sociology_ 33, no. 1 (1927): 94—98,
 * doi:{@link https://doi.org/10.1086/214336|10.1086/214336}.
 *
 *
 * @name standardDeviationalEllipse
 * @param {FeatureCollection<Point>} points GeoJSON points
 * @param {Object} [options={}] Optional parameters
 * @param {string} [options.weight] the property name used to weight the center
 * @param {number} [options.steps=64] number of steps for the polygon
 * @param {Object} [options.properties={}] properties to pass to the resulting ellipse
 * @returns {Feature<Polygon>} an elliptical Polygon that includes approximately 1 SD of the dataset within it.
 * @example
 *
 * var bbox = [-74, 40.72, -73.98, 40.74];
 * var points = turf.randomPoint(400, {bbox: bbox});
 * var sdEllipse = turf.standardDeviationalEllipse(points);
 *
 * //addToMap
 * var addToMap = [points, sdEllipse];
 *
 */
function standardDeviationalEllipse(points, options) {
    // Optional params
    options = options || {};
    if (!isObject(options)) throw new Error('options is invalid');
    var steps = options.steps || 64;
    var weightTerm = options.weight;
    var properties = options.properties || {};

    // Validation:
    if (!isNumber(steps)) throw new Error('steps must be a number');
    if (!isObject(properties)) throw new Error('properties must be a number');

    // Calculate mean center & number of features:
    var numberOfFeatures = coordAll(points).length;
    var meanCenter = centerMean(points, {weight: weightTerm});

    // Calculate angle of rotation:
    // [X, Y] = mean center of all [x, y].
    // theta = arctan( (A + B) / C )
    // A = sum((x - X)^2) - sum((y - Y)^2)
    // B = sqrt(A^2 + 4(sum((x - X)(y - Y))^2))
    // C = 2(sum((x - X)(y - Y)))

    var xDeviationSquaredSum = 0;
    var yDeviationSquaredSum = 0;
    var xyDeviationSum = 0;

    featureEach(points, function (point) {
        var weight = point.properties[weightTerm] || 1;
        var deviation = getDeviations(getCoords(point), getCoords(meanCenter));
        xDeviationSquaredSum += Math.pow(deviation.x, 2) * weight;
        yDeviationSquaredSum += Math.pow(deviation.y, 2) * weight;
        xyDeviationSum += deviation.x * deviation.y * weight;
    });

    var bigA = xDeviationSquaredSum - yDeviationSquaredSum;
    var bigB = Math.sqrt(Math.pow(bigA, 2) + 4 * Math.pow(xyDeviationSum, 2));
    var bigC = 2 * xyDeviationSum;
    var theta = Math.atan((bigA + bigB) / bigC);
    var thetaDeg = theta * 180 / Math.PI;

    // Calculate axes:
    // sigmaX = sqrt((1 / n - 2) * sum((((x - X) * cos(theta)) - ((y - Y) * sin(theta)))^2))
    // sigmaY = sqrt((1 / n - 2) * sum((((x - X) * sin(theta)) - ((y - Y) * cos(theta)))^2))
    var sigmaXsum = 0;
    var sigmaYsum = 0;
    var weightsum = 0;
    featureEach(points, function (point) {
        var weight = point.properties[weightTerm] || 1;
        var deviation = getDeviations(getCoords(point), getCoords(meanCenter));
        sigmaXsum += Math.pow((deviation.x * Math.cos(theta)) - (deviation.y * Math.sin(theta)), 2) * weight;
        sigmaYsum += Math.pow((deviation.x * Math.sin(theta)) + (deviation.y * Math.cos(theta)), 2) * weight;
        weightsum += weight;
    });

    var sigmaX = Math.sqrt(2 * sigmaXsum / weightsum);
    var sigmaY = Math.sqrt(2 * sigmaYsum / weightsum);

    var theEllipse = ellipse(meanCenter, sigmaX, sigmaY, {units: 'degrees', angle: thetaDeg, steps: steps, properties: properties});
    var pointsWithinEllipse = pointsWithinPolygon(points, featureCollection([theEllipse]));
    var standardDeviationalEllipseProperties = {
        meanCenterCoordinates: getCoords(meanCenter),
        semiMajorAxis: sigmaX,
        semiMinorAxis: sigmaY,
        numberOfFeatures: numberOfFeatures,
        angle: thetaDeg,
        percentageWithinEllipse: 100 * coordAll(pointsWithinEllipse).length / numberOfFeatures
    };
    theEllipse.properties.standardDeviationalEllipse = standardDeviationalEllipseProperties;

    return theEllipse;
}

/**
 * Get x_i - X and y_i - Y
 *
 * @private
 * @param {Array} coordinates Array of [x_i, y_i]
 * @param {Array} center Array of [X, Y]
 * @returns {Object} { x: n, y: m }
 */
function getDeviations(coordinates, center) {
    return {
        x: coordinates[0] - center[0],
        y: coordinates[1] - center[1]
    };
}

export default standardDeviationalEllipse;