text:
module.exports.run = async (client, message, args) => {
	const Discord = require('discord.js');
	try {
	let embed = new Discord.RichEmbed()
		.setAuthor(client.user.username + " Uptime", client.user.avatarURL)
		var time;
		var uptime = parseInt(client.uptime);
		uptime = Math.floor(uptime / 1000);
        var uptimeMinutes = Math.floor(uptime / 60);
        var minutes = uptime % 60;
        var hours = 0;
        while (uptimeMinutes >= 60) {
            hours++;
            uptimeMinutes = uptimeMinutes - 60;
        }
		var uptimeSeconds = minutes % 60;
		var days = Math.floor(hours / 24);
            embed.setDescription("Precipitation has been online for " + days + " days, " + hours + " hours, " + uptimeMinutes + " minutes, and " + uptimeSeconds + " seconds.")
            embed.setColor("GREEN")
            embed.setTimestamp()
        message.channel.send({ embed })
	} catch(err) {
		message.channel.send(err)
	}
}

module.exports.help = {
    name: "uptime",
    args: " ",
    notes: "Shows the uptime for Precipitation."
}


text:
const options = {
    use: true
};
export default options;

redpajama_set_name: RedPajamaGithub


text:
Installing Hasura on GKE
========================

This section describes:

1. How to setup a Hasura cluster on GKE
2. How to add that Hasura cluster to a Hasura project

Set up a GKE cluster
--------------------

Your GKE cluster needs to have a few things set up before the Hasura platform can be installed on it. The following are the necessary pieces to be set up and configured:

Navigate to your **Google Cloud Console**

1. From the **Kubernetes Engine** section, create a new Kubernetes Cluster in whichever region you prefer. We'll select the region ``asia-east1-a`` and name the cluster as ``myco-hasura``.

2. From the **Compute Engine > Disks** section, create 3 disks:

   1. ``myco-hasura-postgres``
   2. ``myco-hasura-redis``
   3. ``myco-hasura-filestore``

   Make sure that they are large enough to hold your data (min 10 GB each), located in the same region as your Kubernetes cluster, the ``Source type`` option is set to ``None (blank disk)`` and preferably are SSDs.

3. From the **VPC Network > External IP Addresses** section, reserve a static IP address in the same region as the Kubernetes cluster (no need to attach to any particular pool).

4. Map your domain (let's call it ``myco-hasura.my-domain.com``) to this IP from your DNS provider's dashboard by creating an A record.

Get the credentials for the GKE cluster
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Set up the kube context using the ``gcloud container clusters get-credentials ...`` command from the Kubernetes Engine console.

Note the context set by this command since we'll be needing it later. Use ``kubectl config current-context`` (or ``get-contexts``) and note the context.

Installing the Hasura platform
------------------------------

Create ``cluster-data.yaml``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Create a file named ``cluster-data.yaml`` with the content as shown below. This file defines a cluster.

.. literalinclude:: clusters.yaml
   :language: yaml
   :caption: cluster-data.yaml
   :linenos:
   :emphasize-lines: 1,2,4,10,33,38,43

We're now ready to install the Hasura platform on the ``myco-hasura`` cluster!

Install the Hasura platform
^^^^^^^^^^^^^^^^^^^^^^^^^^^

To install the Hasura platform, run:

.. code-block:: console

   $ hasura cluster install --file cluster-data.yaml --domain myco-hasura.my-domain.com

Wait for some time for all the components of the cluster to come up. You may use ``kubectl get pods -n hasura`` to see if all the pods are up.

Setup a local project
^^^^^^^^^^^^^^^^^^^^^

If you have an existing Hasura project, skip to the cluster add part.

Clone the base repo from Hasura Hub into a local directory:

.. code-block:: console

   $ hasura clone hasura/base

Add the cluster
^^^^^^^^^^^^^^^

To add this cluster to the project,

.. code-block:: console

   $ cd [project-directory]
   $ hasura cluster add --file=/path/to/cluster-data.yaml

This will add the cluster defined in ``cluster-data.yaml`` to the current project, sets up required remotes, hooks and ssh keys.

Deploy project to the cluster
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Finally push your project to the newly created cluster:

.. code-block:: console

   $ git push myco-hasura master

Tearing down
------------

You can delete all the resources Hasura created by executing the following
commands:

.. code-block:: bash

   kubectl delete namespace hasura
   kubectl delete configmap hasura-conf hasura-status ssh-authorized-keys
   kubectl delete secret hasura-secrets
   kubectl delete clusterrolebinding hasura-cluster-admin-binding

   # Next, delete all the infrastructure components like disks, ip address etc.

.. note::

    The Hasura Kubernetes Platform is available under these `Terms of Service <https://hasura.io/legal/platform-terms-of-service/>`_.


text:
package com.google.api.ads.dfp.jaxws.v201311;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for LabelEntityAssociationError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="LabelEntityAssociationError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="INVALID_COMPANY_TYPE"/>
 *     <enumeration value="DUPLICATE_ASSOCIATION"/>
 *     <enumeration value="INVALID_ASSOCIATION"/>
 *     <enumeration value="DUPLICATE_ASSOCIATION_WITH_NEGATION"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "LabelEntityAssociationError.Reason")
@XmlEnum
public enum LabelEntityAssociationErrorReason {

    /**
     *
     *                 Labels can only be associated with {@link Company.Type#HOUSE_ADVERTISER},
     *                 {@link Company.Type#ADVERTISER} and {@link Company.Type#AD_NETWORK} type
     *                 of companies.
     *
     *
     */
    INVALID_COMPANY_TYPE,

    /**
     *
     *                 The label has already been attached to the entity.
     *
     *
     */
    DUPLICATE_ASSOCIATION,

    /**
     *
     *                 A label is being applied to an entity that does not support that entity
     *                 type.
     *
     *
     */
    INVALID_ASSOCIATION,

    /**
     *
     *                 The same label is being applied and negated to the same entity.
     *
     *
     */
    DUPLICATE_ASSOCIATION_WITH_NEGATION,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static LabelEntityAssociationErrorReason fromValue(String v) {
        return valueOf(v);
    }

}


text:
<?php

namespace NilPortugues\SchemaOrg\Properties;

use NilPortugues\SchemaOrg\SchemaProperty;

/**
 * The tangible thing generated by the service, e.g. a passport, permit, etc.
 */
class ProducesProperty extends SchemaProperty
{
    const SCHEMA_URL = 'http://schema.org/produces';
    const PROPERTY_NAME = 'produces';

    /**
     * A list of schemas allowed to use this property.
     *
     * @var array
     */
    protected static $allowedSchemas = [
        'http://schema.org/Service',
    ];
}


text:
package org.apache.carbondata.core.scan.expression.logical;

import mockit.Mock;
import mockit.MockUp;

import org.apache.carbondata.core.metadata.datatype.DataTypes;
import org.apache.carbondata.core.scan.expression.ColumnExpression;
import org.apache.carbondata.core.scan.expression.ExpressionResult;
import org.apache.carbondata.core.scan.expression.exception.FilterIllegalMemberException;
import org.apache.carbondata.core.scan.expression.exception.FilterUnsupportedException;
import org.apache.carbondata.core.scan.filter.intf.RowImpl;
import org.apache.carbondata.core.scan.filter.intf.RowIntf;

import org.junit.Before;
import org.junit.Test;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;

public class RangeExpressionTest {
  private RangeExpression rangeExpression;

  @Before public void setUp() {
    ColumnExpression leftExpression = new ColumnExpression("IMEI", DataTypes.BOOLEAN);
    ColumnExpression rightExpression = new ColumnExpression("IMEI", DataTypes.BOOLEAN);
    rangeExpression = new RangeExpression(leftExpression, rightExpression);
  }

  @Test public void testGetString() {
    String actualValue = rangeExpression.getString();
    String expectedValue = "Range(ColumnExpression(IMEI),ColumnExpression(IMEI))";
    assertEquals(expectedValue, actualValue);
  }

  @Test public void testEvaluate() throws FilterIllegalMemberException, FilterUnsupportedException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { false });
    final ExpressionResult expressionResult = new ExpressionResult(DataTypes.BOOLEAN, "test");
    new MockUp<ColumnExpression>() {
      @Mock public ExpressionResult evaluate(RowIntf value) {
        return expressionResult;
      }
    };

    assertTrue(rangeExpression.evaluate(rowImpl) instanceof ExpressionResult);
  }

  @Test public void testEvaluate1()
      throws FilterIllegalMemberException, FilterUnsupportedException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { false });
    final ExpressionResult expressionResult = new ExpressionResult(DataTypes.BOOLEAN, "true");
    new MockUp<ColumnExpression>() {
      @Mock public ExpressionResult evaluate(RowIntf value) {
        return expressionResult;
      }
    };

    assertTrue(rangeExpression.evaluate(rowImpl) instanceof ExpressionResult);
  }

  @Test public void testEvaluate2()
      throws FilterIllegalMemberException, FilterUnsupportedException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { false });
    final ExpressionResult expressionResultRight = new ExpressionResult(DataTypes.BOOLEAN, "false");
    final ExpressionResult expressionResultLeft = new ExpressionResult(DataTypes.BOOLEAN, "true");
    new MockUp<ColumnExpression>() {
      boolean isLeft = true;

      @Mock public ExpressionResult evaluate(RowIntf value) {
        if (isLeft) {
          isLeft = false;
          return expressionResultLeft;
        }
        return expressionResultRight;
      }
    };

    assertTrue(rangeExpression.evaluate(rowImpl) instanceof ExpressionResult);
  }

  @Test public void testEvaluate3()
      throws FilterIllegalMemberException, FilterUnsupportedException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { false });
    final ExpressionResult expressionResultRight = new ExpressionResult(DataTypes.BOOLEAN, "false");
    final ExpressionResult expressionResultLeft = new ExpressionResult(DataTypes.BOOLEAN, "false");
    new MockUp<ColumnExpression>() {
      boolean isLeft = true;

      @Mock public ExpressionResult evaluate(RowIntf value) {
        if (isLeft) {
          isLeft = false;
          return expressionResultLeft;
        }
        return expressionResultRight;
      }
    };

    assertTrue(rangeExpression.evaluate(rowImpl) instanceof ExpressionResult);
  }

  @Test public void testEvaluate4()
      throws FilterIllegalMemberException, FilterUnsupportedException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { false });
    final ExpressionResult expressionResult = new ExpressionResult(DataTypes.BOOLEAN, "false");
    new MockUp<ColumnExpression>() {
      @Mock public ExpressionResult evaluate(RowIntf value) {
        return expressionResult;
      }
    };

    assertTrue(rangeExpression.evaluate(rowImpl) instanceof ExpressionResult);
  }

  @Test(expected = Exception.class) public void testEvaluateForDefault()
      throws FilterUnsupportedException, FilterIllegalMemberException {
    RowImpl rowImpl = new RowImpl();
    rowImpl.setValues(new Boolean[] { true });
    final ExpressionResult expressionResult = new ExpressionResult(DataTypes.STRING, "test");
    new MockUp<ColumnExpression>() {
      @Mock public ExpressionResult evaluate(RowIntf value)
          throws FilterUnsupportedException, FilterIllegalMemberException {
        return expressionResult;
      }
    };
    rangeExpression.evaluate(rowImpl);
  }
}


text:
<?php

namespace gries\Pokemath\Numbers;

use gries\Pokemath\PokeNumber;

class Mothim extends PokeNumber
{
    public function __construct()
    {
        parent::__construct('mothim');
    }
}


text:
package hudson.plugins.groovy;

import groovy.lang.GroovySystem;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.JDK;
import hudson.model.Result;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.slaves.DumbSlave;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.steps.StepConfigTester;
import org.jenkinsci.test.acceptance.docker.DockerRule;
import org.jenkinsci.test.acceptance.docker.fixtures.JavaContainer;
import static org.junit.Assume.assumeFalse;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.Rule;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.JenkinsRule;

public class WithGroovyStepTest {

    @ClassRule
    public static BuildWatcher buildWatcher = new BuildWatcher();

    @Rule
    public JenkinsRule r = new JenkinsRule();

    @Rule
    public DockerRule<JavaContainer> javaContainerRule = new DockerRule<>(JavaContainer.class);

    @Rule
    public DockerRule<JavaContainerWith9> java9ContainerRule = new DockerRule<>(JavaContainerWith9.class);

    @Test
    public void smokes() throws Exception {
        DumbSlave s = r.createSlave("remote", null, null);
        r.waitOnline(s);
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        s.getWorkspaceFor(p).child("x.groovy").write("println(/got: ${111/3}/)", null);
        p.setDefinition(new CpsFlowDefinition("node('remote') {withGroovy {if (isUnix()) {sh 'env | fgrep PATH; groovy x.groovy'} else {bat 'groovy x.groovy'}}}", true));
        r.assertLogContains("got: 37", r.buildAndAssertSuccess(p));
        s.getWorkspaceFor(p).child("x.groovy").write("System.exit(23)", null);
        p.setDefinition(new CpsFlowDefinition("node('remote') {withGroovy {try {if (isUnix()) {sh 'groovy x.groovy'} else {bat 'groovy x.groovy'}} catch (e) {echo(/caught: $e/)}}}", true));
        r.assertLogContains("caught: ", r.buildAndAssertSuccess(p));
    }

    @Test
    public void configRoundtrip() throws Exception {
        StepConfigTester tester = new StepConfigTester(r);
        WithGroovyStep step = new WithGroovyStep();
        r.assertEqualDataBoundBeans(step, tester.configRoundTrip(step));
        r.jenkins.getDescriptorByType(GroovyInstallation.DescriptorImpl.class).setInstallations(new GroovyInstallation("groovy3", "/usr/share/groovy3", null));
        r.assertEqualDataBoundBeans(step, tester.configRoundTrip(step));
        step.setTool("groovy3");
        r.assertEqualDataBoundBeans(step, tester.configRoundTrip(step));
        r.jenkins.getDescriptorByType(JDK.DescriptorImpl.class).setInstallations(new JDK("jdk9", "/usr/share/jdk9"));
        step.setJdk("jdk9");
        r.assertEqualDataBoundBeans(step, tester.configRoundTrip(step));
    }

    @Test
    public void io() throws Exception {
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        r.jenkins.getWorkspaceFor(p).child("calc.groovy").write("Pipeline.output(Pipeline.input().collect {k, v -> k * v})", null);
        p.setDefinition(new CpsFlowDefinition("node {def r = withGroovy(input: [once: 1, twice: 2, thrice: 3]) {if (isUnix()) {sh 'env | fgrep PATH; groovy calc.groovy'} else {bat 'groovy calc.groovy'}}; echo r.join('/')}", true));
        r.assertLogContains("once/twicetwice/thricethricethrice", r.buildAndAssertSuccess(p));
    }

    @Test
    public void ioJep200() throws Exception {
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        r.jenkins.getWorkspaceFor(p).child("die.groovy").write("@Grab('com.google.guava:guava:11.0.1') import com.google.common.collect.LinkedListMultimap; Pipeline.output(LinkedListMultimap.create())", null);
        p.setDefinition(new CpsFlowDefinition("node {withGroovy(input: true) {if (isUnix()) {sh 'groovy die.groovy'} else {bat 'groovy die.groovy'}}}", true));
        r.assertLogContains("java.lang.SecurityException: Rejected: com.google.common.collect.LinkedListMultimap; see https://jenkins.io/redirect/class-filter/", r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0)));
    }

    @Test
    public void tool() throws Exception {
        assumeFalse("TODO fails on Windows CI: JAVA_HOME is set to an invalid directory: C:/tools/jdk-8", Functions.isWindows());
        FilePath home = r.jenkins.getRootPath();
        home.unzipFrom(WithGroovyStepTest.class.getResourceAsStream("/groovy-binary-2.4.13.zip"));
        r.jenkins.getDescriptorByType(GroovyInstallation.DescriptorImpl.class).setInstallations(new GroovyInstallation("2.4.x", home.child("groovy-2.4.13").getRemote(), null));
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        r.jenkins.getWorkspaceFor(p).child("x.groovy").write("println(/running $GroovySystem.version/)", null);
        p.setDefinition(new CpsFlowDefinition("node {withGroovy(tool: '2.4.x') {if (isUnix()) {sh 'env | fgrep PATH; groovy x.groovy'} else {bat 'groovy x.groovy'}}}", true));
        r.assertLogContains("running 2.4.13", r.buildAndAssertSuccess(p));
    }

    @Test
    public void builtInGroovy() throws Exception {
        assumeFalse("needs Linux Docker", Functions.isWindows());
        JavaContainer container = javaContainerRule.get();
        DumbSlave s = new DumbSlave("docker", "/home/test", new SSHLauncher(container.ipBound(22), container.port(22), "test", "test", "", ""));
        r.jenkins.addNode(s);
        r.waitOnline(s);
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        s.getWorkspaceFor(p).child("x.groovy").write("println(/running $GroovySystem.version/)", null);
        p.setDefinition(new CpsFlowDefinition("node('docker') {withGroovy {sh 'env | fgrep PATH; groovy x.groovy'}}", true));
        r.assertLogContains("running " + GroovySystem.getVersion(), r.buildAndAssertSuccess(p));
        s.getWorkspaceFor(p).child("x.groovy").write("System.exit(23)", null);
        p.setDefinition(new CpsFlowDefinition("node('docker') {withGroovy {sh 'groovy x.groovy'}}", true));
        r.assertLogContains("23", r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0)));
    }

    @Test
    public void builtInGroovyGrab() throws Exception {
        DumbSlave s = r.createOnlineSlave();
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        s.getWorkspaceFor(p).child("grape.groovy").write("@Grab('commons-primitives:commons-primitives:1.0') import org.apache.commons.collections.primitives.ArrayIntList; def ls = new ArrayIntList(); ls.add(1); ls.add(2); println(ls)", null);
        p.setDefinition(new CpsFlowDefinition("node('" + s.getNodeName() + "') {withGroovy {if (isUnix()) {sh 'env | fgrep PATH; groovy grape.groovy'} else {bat 'groovy grape.groovy'}}}", true));
        r.assertLogContains("[1, 2]", r.buildAndAssertSuccess(p));
    }

    @Test
    public void jdk() throws Exception {
        assumeFalse("needs Linux Docker", Functions.isWindows());
        JavaContainerWith9 container = java9ContainerRule.get();
        DumbSlave s = new DumbSlave("docker", "/home/test", new SSHLauncher(container.ipBound(22), container.port(22), "test", "test", "", ""));
        r.jenkins.addNode(s);
        r.waitOnline(s);
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        s.getWorkspaceFor(p).child("x.groovy").write("println(/running ${System.properties['java.version']}/)", null);
        p.setDefinition(new CpsFlowDefinition("node('docker') {withGroovy {sh 'env | fgrep PATH; groovy x.groovy'}}", true));
        r.assertLogContains("running 1.8.", r.buildAndAssertSuccess(p));
        r.jenkins.getDescriptorByType(JDK.DescriptorImpl.class).setInstallations(new JDK("jdk9", "/opt/jdk9"));
        p.setDefinition(new CpsFlowDefinition("node('docker') {withGroovy(jdk: 'jdk9') {sh 'env | fgrep PATH; groovy x.groovy'}}", true));
        r.assertLogContains("running 9.", r.buildAndAssertSuccess(p));
        FilePath home = s.getRootPath();
        home.unzipFrom(WithGroovyStepTest.class.getResourceAsStream("/groovy-binary-2.4.13.zip"));
        r.jenkins.getDescriptorByType(GroovyInstallation.DescriptorImpl.class).setInstallations(new GroovyInstallation("2.4.x", home.child("groovy-2.4.13").getRemote(), null));
        s.getWorkspaceFor(p).child("x.groovy").write("println(/running $GroovySystem.version on ${System.properties['java.version']}/)", null);
        p.setDefinition(new CpsFlowDefinition("node('docker') {withGroovy(tool: '2.4.x', jdk: 'jdk9') {sh 'env | fgrep PATH; groovy x.groovy'}}", true));
        r.assertLogContains("running 2.4.13 on 9.", r.buildAndAssertSuccess(p));
    }

}


text:
package org.apache.oodt.cas.filemgr.metadata.extractors;

//JDK imports

import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.Reference;
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.metadata.exceptions.MetExtractionException;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

//OODT imports

/**
 * @author mattmann
 * @version $Revision$
 *
 * <p>
 * An abstract base class providing functionality to any sub-classing
 * {@link FilemgrMetExtractor}s.
 * </p>.
 */
public abstract class AbstractFilemgrMetExtractor implements
        FilemgrMetExtractor {
  private static Logger LOG = Logger.getLogger(AbstractFilemgrMetExtractor.class.getName());
    protected Properties configuration;

    /*
     * (non-Javadoc)
     *
     * @see org.apache.oodt.cas.filemgr.metadata.extractors.
     *      FilemgrMetExtractor#extractMetadata(org.apache.oodt.cas.filemgr.structs.Product,
     *      org.apache.oodt.cas.metadata.Metadata)
     */
    public Metadata extractMetadata(Product product, Metadata met)
            throws MetExtractionException {
        validateProduct(product, met);
        return doExtract(product, met);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.oodt.cas.filemgr.metadata.extractors.FilemgrMetExtractor#configure(java.util.Properties)
     */
    public void configure(Properties props) {
        this.configuration = props;
        doConfigure();
    }

    public abstract Metadata doExtract(Product product, Metadata met)
            throws MetExtractionException;

    public abstract void doConfigure();

    protected void validateProduct(Product product, Metadata met)
            throws MetExtractionException {
        if (product.getProductType() == null || ((product
                                                      .getProductType().getName() == null || (product
                                                                                .getProductType()
                                                                                .getName()
                                                                                .equals(""))))) {
            throw new MetExtractionException("Product Type undefined");
        }

        if (product.getProductReferences() == null || (product
                                                           .getProductReferences().size() == 0)) {
            throw new MetExtractionException("Product references undefined");
        }

    }

    protected void addMetadataIfUndefined(Metadata origMet, Metadata destMet,
            String key, String val) {
        if (!origMet.containsKey(key)) {
            destMet.addMetadata(key, val);
        }
    }

    protected void merge(Metadata src, Metadata dest) {
        dest.addMetadata(src.getMap());
    }

    protected File getProductFile(Product product)
            throws MetExtractionException {
        File prodFile;

        if (product.getProductStructure()
                .equals(Product.STRUCTURE_HIERARCHICAL)) {
            try {
                prodFile = new File(getRootRefPath(product
                        .getProductReferences(), product.getProductType()
                        .getProductRepositoryPath()));
            } catch (Exception e) {
                LOG.log(Level.SEVERE, e.getMessage());
                throw new MetExtractionException("URI exception parsing: ["
                        + product.getRootRef().getOrigReference() + "]");
            }
        } else {
            try {
                prodFile = new File(new URI(((Reference) product
                        .getProductReferences().get(0)).getOrigReference()));
            } catch (Exception e) {
                throw new MetExtractionException("URI exception parsing: ["
                        + ((Reference) product.getProductReferences().get(0))
                                .getOrigReference() + "]");

            }
        }

        return prodFile;
    }

    protected String getRootRefPath(List<Reference> refs,
            String productTypeRepoPath) throws URISyntaxException {
        return new File(new URI(refs.get(0)
                .getOrigReference())).getAbsolutePath();
    }

}


text:
using namespace IECore;
using namespace IECoreHoudini;

IE_CORE_DEFINERUNTIMETYPED( FromHoudiniPolygonsConverter );

FromHoudiniGeometryConverter::Description<FromHoudiniPolygonsConverter> FromHoudiniPolygonsConverter::m_description( MeshPrimitiveTypeId );

FromHoudiniPolygonsConverter::FromHoudiniPolygonsConverter( const GU_DetailHandle &handle ) :
	FromHoudiniGeometryConverter( handle, "Converts a Houdini GU_Detail to an IECore::MeshPrimitive." )
{
}

FromHoudiniPolygonsConverter::FromHoudiniPolygonsConverter( const SOP_Node *sop ) :
	FromHoudiniGeometryConverter( sop, "Converts a Houdini GU_Detail to an IECore::MeshPrimitive." )
{
}

FromHoudiniPolygonsConverter::~FromHoudiniPolygonsConverter()
{
}

FromHoudiniGeometryConverter::Convertability FromHoudiniPolygonsConverter::canConvert( const GU_Detail *geo )
{
	const GA_PrimitiveList &primitives = geo->getPrimitiveList();

	for ( GA_Iterator it=geo->getPrimitiveRange().begin(); !it.atEnd(); ++it )
	{
		const GA_Primitive *prim = primitives.get( it.getOffset() );
		if ( prim->getTypeId() != GEO_PRIMPOLY )
		{
			return Inapplicable;
		}
	}

	// is there a single named shape?
	GA_ROAttributeRef attrRef = geo->findPrimitiveAttribute( "name" );
	if ( attrRef.isValid() && attrRef.isString() )
	{
		const GA_Attribute *nameAttr = attrRef.getAttribute();
		const GA_AIFSharedStringTuple *tuple = nameAttr->getAIFSharedStringTuple();
		if ( tuple->getTableEntries( nameAttr ) < 2 )
		{
			return Ideal;
		}
	}

	return Suitable;
}

ObjectPtr FromHoudiniPolygonsConverter::doDetailConversion( const GU_Detail *geo, const CompoundObject *operands ) const
{
	const GA_PrimitiveList &primitives = geo->getPrimitiveList();

	MeshPrimitivePtr result = new MeshPrimitive();

	GA_Iterator firstPrim = geo->getPrimitiveRange().begin();
	for ( GA_Iterator it=firstPrim; !it.atEnd(); ++it )
	{
		const GA_Primitive *prim = primitives.get( it.getOffset() );
		if ( prim->getTypeId() != GEO_PRIMPOLY )
		{
			throw std::runtime_error( "FromHoudiniPolygonsConverter: Geometry contains non-polygon primitives" );
		}
	}

	// loop over primitives gathering mesh data
	std::vector<int> vertIds;
	std::vector<int> vertsPerFace;
	for ( GA_Iterator it=firstPrim; !it.atEnd(); ++it )
	{
		const GA_Primitive *prim = primitives.get( it.getOffset() );
		size_t numPrimVerts = prim->getVertexCount();
		vertsPerFace.push_back( numPrimVerts );
		std::vector<int> ids( numPrimVerts );
		for ( size_t j=0; j < numPrimVerts; j++ )
		{
			vertIds.push_back( geo->pointIndex( prim->getPointOffset( numPrimVerts - 1 - j ) ) );
		}
	}

	// try to get the interpolation type from the geo
	CompoundObjectPtr modifiedOperands = 0;
	std::string interpolation = "linear";
	const GA_ROAttributeRef attrRef = geo->findStringTuple( GA_ATTRIB_PRIMITIVE, GA_SCOPE_PUBLIC, "ieMeshInterpolation" );
	if ( attrRef.isValid() )
	{
		modifiedOperands = operands->copy();
		std::string &attributeFilter = modifiedOperands->member<StringData>( "attributeFilter" )->writable();
		attributeFilter += " ^ieMeshInterpolation";

		GA_Range primRange = geo->getPrimitiveRange();
		for ( GA_Iterator it=primRange.begin(); !it.atEnd(); ++it )
		{
			const char *value = attrRef.getString( it.getOffset() );
			if ( value )
			{
				if ( !strcmp( value, "subdiv" ) )
				{
					interpolation = "catmullClark";
					// subdivision meshes should not have normals. we assume this occurred because the geo contained
					// both subdiv and linear meshes, inadvertantly extending the normals attribute to both.
					attributeFilter += " ^N";
					break;
				}
				else if ( !strcmp( value, "poly" ) )
				{
					interpolation = "linear";
					break;
				}
			}
		}
	}

	result->setTopology( new IntVectorData( vertsPerFace ), new IntVectorData( vertIds ), interpolation );

	if ( geo->getNumVertices() )
	{
		transferAttribs( geo, result, modifiedOperands ? modifiedOperands : operands );
	}

	return result;
}


text:
title: Documentation
---

In this resource center you can find documentation, tutorials, videos and more information about Kotlin

Reference. Syntax reference and information on basic constructs with Kotlin

Tutorials. Walk-through tutorials providing step-by-step guidance on how to accomplish different tasks

Videos. Short (and longer) videos showing different aspects of Kotlin

More Resources. Links and information to some community resources


text:
<?php
	//register.class.php

	include_once 'traits/password.trait.php';
	/*
		it is class used for the registration of user

		public $uid;		// user id
		public $usn;		// user usn
		public $fname;		// user first name
		public $lname;		// user last name
		public $gender;		// user gender
		public $dob;		// user data-of-birth
		public $pos;		// user position
		public $level; 		// user level
	*/
	class register extends user
	{

		private $password;

		// including password trait methods
		use password;

		function __construct($password1)
		{
			$this->password=$password1;
			unset($password1);
		}

		public function add()			// function to add data to database without password
		{
			include 'dbms/dbms_imp.php';

			$insert_query="INSERT INTO `userdetail` (`uniqueid`, `usn`, `password`, `firstname`, `surname`, `gender`, `dob`, `pos`)
				VALUES ('','$this->usn','','$this->fname','$this->lname','$this->gender','$this->dob','')";

			$mysql_query_run=$connection->query($insert_query);

			mysqli_close($connection);

			if(!$mysql_query_run)
			{
				// error occurs
				echo "
Error writing data".mysqli_error($connection);
			}
			else
			{
				$this->get_userid();
				$this->add_password();
			}

		}

		public function get_userid()	// function to get userid back
		{
			include 'dbms/dbms_imp.php';

			$sql= "SELECT `uniqueid` FROM `userdetail` WHERE `usn`='$this->usn';";

			$mysql_query_run=$connection->query($sql);

			if(!$mysql_query_run)
			{
				// error occurs
				echo "
Error getting data".mysqli_error($connection);
			}
			else
			{
				$rows=$mysql_query_run->fetch_array();
				$this->uid=$rows[0];
			}
		}

		public function add_password()	// function to add the password to corresponding userid
		{
			$this->password=$this->password_hash_gen($this->usn,$this->password,$this->uid);

			include 'dbms/dbms_imp.php';

			$sql = "UPDATE `userdetail` SET `password` = '$this->password' WHERE `uniqueid` = '$this->uid'";

			$mysql_query_run=$connection->query($sql);

			if(!$mysql_query_run)
			{
				// error occurs
				echo "
Error writing data".mysqli_error($connection);
			}
		}

	}
?>


text:
  Matton-et-Clémency est
       un village
       localisé dans le département des Ardennes en Champagne-Ardenne. Elle totalisait 462 habitants en 2008.

Le nombre d'habitations, à Matton-et-Clémency, se décomposait en 2011 en douze appartements et 231 maisons soit
 un marché plutôt équilibré.

Si vous pensez emmenager à Matton-et-Clémency, vous pourrez aisément trouver une maison à acheter.

À coté de Matton-et-Clémency sont situées les villes de
Sachy localisée à 4 km, 156 habitants,
Tremblois-lès-Carignan à 3 km, 113 habitants,
Messincourt située à 3 km, 581 habitants,
Carignan à 4 km, 3 188 habitants,
Pure située à 2 km, 620 habitants,
Tétaigne située à 5 km, 80 habitants,
 entre autres. De plus, Matton-et-Clémency est située à seulement 18 km de Sedan.


text:
#include "opParsers.h"

using namespace nvinfer1;

namespace nvcaffeparser1
{
template <typename T>
inline bool bnConvertWrap(float scaleFactor, const Weights& variance, const Weights& mean,
                          const Weights& scaleBlob, const Weights& biasBlob,
                          Weights& shift, Weights& scale, float eps,
                          bool nvCaffe, CaffeWeightFactory& weightFactory)
{

    assert(shift.count == scale.count);
    if (nvCaffe)
    {
        if (scaleBlob.values == nullptr)
        {
            return false;
        }
        if (biasBlob.values == nullptr)
        {
            return false;
        }
    }
    T* shiftv = reinterpret_cast<T*>(malloc(sizeof(T) * shift.count));
    if (!shiftv)
    {
        return false;
    }

    T* scalev = reinterpret_cast<T*>(malloc(sizeof(T) * scale.count));
    if (!scalev)
    {
        free(shiftv);
        return false;
    }
    shift.values = shiftv;
    scale.values = scalev;
    weightFactory.getTmpAllocs().push_back(shiftv);
    weightFactory.getTmpAllocs().push_back(scalev);

    const T* m = reinterpret_cast<const T*>(mean.values);
    const T* v = reinterpret_cast<const T*>(variance.values);
    for (int i = 0; i < shift.count; i++)
    {
        scalev[i] = T(1.0f / std::sqrt(float(v[i]) * scaleFactor + eps));
        shiftv[i] = T(-(float(m[i]) * scaleFactor * float(scalev[i])));
    }

    if (nvCaffe)
    {
        const T* s = reinterpret_cast<const T*>(scaleBlob.values);
        const T* b = reinterpret_cast<const T*>(biasBlob.values);
        for (int i = 0; i < shift.count; i++)
        {
            scalev[i] = T(float(scalev[i]) * s[i]);
            shiftv[i] = T(float(shiftv[i]) * s[i]) + b[i];
        }
    }
    return true;
}

ILayer* parseBatchNormalization(INetworkDefinition& network, const trtcaffe::LayerParameter& msg, CaffeWeightFactory& weightFactory, BlobNameToTensor& tensors)
{
    if (!checkBlobs(msg, 1, 1))
    {
        return nullptr;
    }

    const trtcaffe::BatchNormParameter& p = msg.batch_norm_param();
    bool nvCaffe = weightFactory.getBlobsSize(msg.name()) == 5;

    int C = parserutils::getC(tensors[msg.bottom(0)]->getDimensions());

    Weights mean{DataType::kFLOAT, nullptr, 0},
        variance{DataType::kFLOAT, nullptr, 0},
        scaleBlob{DataType::kFLOAT, nullptr, 0},
        biasBlob{DataType::kFLOAT, nullptr, 0},
        movingAverage{DataType::kFLOAT, nullptr, 0};

    // Because of the incompatible nature of the batch normalizations
    // between BLVC Caffe and nvCaffe, two different paths have to be
    // used.
    if (nvCaffe)
    {
        if (weightFactory.isInitialized())
        {
            mean = weightFactory(msg.name(), WeightType::kNVMEAN);
            variance = weightFactory(msg.name(), WeightType::kNVVARIANCE);
            scaleBlob = weightFactory(msg.name(), WeightType::kNVSCALE);
            biasBlob = weightFactory(msg.name(), WeightType::kNVBIAS);
        }
        else
        {
            mean = weightFactory.allocateWeights(C);
            variance = weightFactory.allocateWeights(C, std::uniform_real_distribution<float>(0.9F, 1.1F));
            scaleBlob = weightFactory.allocateWeights(C, std::uniform_real_distribution<float>(0.9F, 1.1F));
            biasBlob = weightFactory.allocateWeights(C);
        }
    }
    else
    {
        if (weightFactory.isInitialized())
        {
            mean = weightFactory(msg.name(), WeightType::kMEAN);
            variance = weightFactory(msg.name(), WeightType::kVARIANCE);
            movingAverage = weightFactory(msg.name(), WeightType::kMOVING_AVERAGE);
        }
        else
        {
            mean = weightFactory.allocateWeights(C);
            variance = weightFactory.allocateWeights(C, std::uniform_real_distribution<float>(0.9F, 1.1F));
            movingAverage = weightFactory.allocateWeights(1, std::uniform_real_distribution<float>(0.99F, 1.01F));
        }
        assert(mean.count == variance.count && movingAverage.count == 1);
    }

    Weights shift{mean.type, nullptr, mean.count};
    Weights scale{mean.type, nullptr, mean.count};
    Weights power{mean.type, nullptr, 0};
    bool success{false};
    float scaleFactor{1.0f};
    if (!nvCaffe)
    {
        float average{0.0f};
        // Inside weightFactory, the weights are generated based off the type.
        if (mean.type == DataType::kFLOAT)
        {
            average = *(static_cast<const float*>(movingAverage.values));
        }
        else
        {
            average = *(static_cast<const float16*>(movingAverage.values));
        }
        if (average == 0.0f)
        {
            std::cout << "Batch normalization moving average is zero" << std::endl;
            return nullptr;
        }
        scaleFactor /= average;
    }
    if (mean.type == DataType::kFLOAT)
    {
        success = bnConvertWrap<float>(scaleFactor, variance, mean, scaleBlob, biasBlob, shift, scale, p.eps(), nvCaffe, weightFactory);
    }
    else
    {
        success = bnConvertWrap<float16>(scaleFactor, variance, mean, scaleBlob, biasBlob, shift, scale, p.eps(), nvCaffe, weightFactory);
    }

    if (!success)
    {
        return nullptr;
    }

    weightFactory.convert(shift);
    weightFactory.convert(scale);
    weightFactory.convert(power);
    return network.addScale(*tensors[msg.bottom(0)], ScaleMode::kCHANNEL, shift, scale, power);
}
} //namespace nvcaffeparser1


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>The Swift Programming Language: About the Language Reference</title>
    <link rel="stylesheet" type="text/css" href="resource/style-1.1.15.css">
  <meta charset="utf-8">

      The Swift Programming Language

Welcome to Swift

              	About Swift

              	A Swift Tour

Language Guide

              	The Basics

              	Basic Operators

              	Strings and Characters

              	Collection Types

              	Control Flow

              	Functions

              	Closures

              	Enumerations

              	Classes and Structures

              	Properties

              	Methods

              	Subscripts

              	Inheritance

              	Initialization

              	Deinitialization

              	Automatic Reference Counting

              	Optional Chaining

              	Type Casting

              	Nested Types

              	Extensions

              	Protocols

              	Generics

              	Advanced Operators

Language Reference

              	About the Language Reference

              	Lexical Structure

              	Types

              	Expressions

              	Statements

              	Declarations

              	Attributes

              	Patterns

              	Generic Parameters and Arguments

              	Summary of the Grammar

About the Language Reference

  This part of the book describes the formal grammar of the Swift programming language. The grammar described here is intended to help you understand the language in more detail, rather than to allow you to directly implement a parser or compiler.

  The Swift language is relatively small, because many common types, functions, and operators that appear virtually everywhere in Swift code are actually defined in the Swift standard library. Although these types, functions, and operators are not part of the Swift language itself, they are used extensively in the discussions and code examples in this part of the book.

How to Read the Grammar

  The notation used to describe the formal grammar of the Swift programming language follows a few conventions:

  An arrow (→) is used to mark grammar productions and can be read as "can consist of."

  Syntactic categories are indicated by italic text and appear on both sides of a grammar production rule.

  Literal words and punctuation are indicated by boldface constant width text and appear only on the right-hand side of a grammar production rule.

  Alternative grammar productions are separated by vertical bars (|). When alternative productions are too long to read easily, they are broken into multiple grammar production rules on new lines.

  In a few cases, regular font text is used to describe the right-hand side of a grammar production rule.

  Optional syntactic categories and literals are marked by a trailing subscript, opt.

  As an example, the grammar of a getter-setter block is defined as follows:

  Grammar of a getter-setter block

  getter-setter-block

  →

  {getter-clausesetter-clauseopt}

  {setter-clausegetter-clause}

  This definition indicates that a getter-setter block can consist of a getter clause followed by an optional setter clause, enclosed in braces, or a setter clause followed by a getter clause, enclosed in braces. The grammar production above is equivalent to the following two productions, where the alternatives are spelled out explicitly:

  Grammar of a getter setter block

  getter-setter-block

  →
{getter-clausesetter-clauseopt}

  getter-setter-block

  →
{setter-clausegetter-clause}

Advanced Operators

Lexical Structure

Copyright © 2014 Apple Inc. All rights reserved. Terms of Use   |  Privacy Policy  |  Updated: 2014-06-02


text:
package de.webshop.util.persistence;

import static javax.persistence.TemporalType.TIMESTAMP;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.xml.bind.annotation.XmlTransient;

@MappedSuperclass
public abstract class AbstractAuditable implements Serializable {

	private static final long	serialVersionUID	= -6888875114036861068L;

	@Temporal(TIMESTAMP)
	@Basic(optional = false)
	@XmlTransient
	private Date erzeugt;

	@Temporal(TIMESTAMP)
	@Basic(optional = false)
	@XmlTransient
	private Date aktualisiert;

	@PrePersist
	protected void prePersist() {
		erzeugt = new Date();
		aktualisiert = new Date();
	}

	@PreUpdate
	protected void preUpdate() {
		aktualisiert = new Date();
	}

	public Date getErzeugt() {
		return erzeugt == null ? null : (Date) erzeugt.clone();
	}

	public void setErzeugt(Date erzeugt) {
		this.erzeugt = erzeugt == null ? null : (Date) erzeugt.clone();
	}

	public Date getAktualisiert() {
		return aktualisiert == null ? null : (Date) aktualisiert.clone();
	}

	public void setAktualisiert(Date aktualisiert) {
		this.aktualisiert = aktualisiert == null ? null : (Date) aktualisiert.clone();
	}

	@Override
	public String toString() {
		return "[Erzeugt: " + erzeugt + ", aktualisiert: " + aktualisiert + "]";
	}
}


text:
package messages.OmissionDefense;

import messages.Message;
import experiment.frameworks.NodeAddress;

public class DefendMessage extends Message {
  private static final long serialVersionUID = -8094804515751404671L;
  public NodeAddress nodeToCheck;

  public DefendMessage(final String tag, final NodeAddress sourceId, final NodeAddress destID,
      final NodeAddress nodeToCheck) {
    super(tag, sourceId, destID);
    this.nodeToCheck = nodeToCheck;
  }

  @Override protected String getContents() {
    return nodeToCheck.toString();
  }

  @Override public boolean isOverheadMessage() {
    return true;
  }

  @Override public long getSimulatedSize() {
    return super.getSimulatedSize() + NodeAddress.SIZE;
  }
}


text:
class WatchableList {
  constructor(ObjectHelper, WatcherFactory, list) {
    this.ObjectHelper = ObjectHelper;
    this.WatcherFactory = WatcherFactory;

    this.list = list;
    this.watchers = [];
  }

  get(path) {
    return this.ObjectHelper.get(this.list, path);
  }

  getAll() {
    return this.list;
  }

  getSubset(paths) {
    return _.zipObject(paths, _.map(paths, this.get.bind(this)));
  }

  set(path, value) {
    this.ObjectHelper.set(this.list, path, value);
    this._notifyWatchers(path, value);
  }

  unset(paths) {
    if (!(paths instanceof Array)) {
      paths = [paths];
    }

    _(paths).each((path) => {
      this.ObjectHelper.unset(this.list, path);
      this._notifyWatchers(path, undefined);
    });
  }

  watch(paths, handler) {
    if (!(paths instanceof Array)) {
      paths = [paths];
    }

    _(paths).each((path) => {
      this.watchers.push(this.WatcherFactory.create(path, handler, this.get(path)));
    });
  }

  removeWatcher(watcher) {
    if (this.watchers.length === 0) {
      return;
    }
    const newWatchers = [];

    _.each(this.watchers, thisWatcher => {
      if (thisWatcher.handler !== watcher) {
        newWatchers.push(thisWatcher);
      }
    });

    return this.watchers = newWatchers;
  }

  _notifyWatchers(changedPath, newValue) {
    _.each(this.watchers, watcher => {
      if (watcher.shouldNotify(changedPath, newValue)) {
        const newValueAtWatchedPath = this.ObjectHelper.get(this.list, watcher.watchPath);
        watcher.notify(changedPath, newValueAtWatchedPath);
      }
    });
  }
}

class WatchableListFactory {
  constructor(ObjectHelper, WatcherFactory) {
    this.ObjectHelper = ObjectHelper;
    this.WatcherFactory = WatcherFactory;
  }

  create(list = {}) {
    return new WatchableList(this.ObjectHelper, this.WatcherFactory, list);
  }
}

angular.module('bicker_router').factory('WatchableListFactory', (ObjectHelper, WatcherFactory) => {
  'ngInject';
  return new WatchableListFactory(ObjectHelper, WatcherFactory);
});


text:
require "google/cloud/gke_backup/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::GkeBackup::V1::BackupForGKE::Client#get_volume_backup
#
def get_volume_backup
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::GkeBackup::V1::BackupForGKE::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::GkeBackup::V1::GetVolumeBackupRequest.new

  # Call the get_volume_backup method.
  result = client.get_volume_backup request

  # The returned object is of type Google::Cloud::GkeBackup::V1::VolumeBackup.
  p result
end
# [END gkebackup_v1_generated_BackupForGKE_GetVolumeBackup_sync]


text:
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
 *
 *  (C) 2014 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * This test attempts communication between 2 running processes
 * after another process has failed. The communication should complete
 * successfully.
 */
int main(int argc, char **argv)
{
    int rank, size, err;
    char buf[10];
    MPI_Request request;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    if (size < 4) {
        fprintf( stderr, "Must run with at least 4 processes\n" );
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    if (rank == 1) {
        exit(EXIT_FAILURE);
    }

    if (rank == 0) {
        err =  MPI_Issend("No Errors", 10, MPI_CHAR, 3, 0, MPI_COMM_WORLD, &request);
        err += MPI_Wait(&request, MPI_STATUS_IGNORE);
        if (err) {
            fprintf(stderr, "An error occurred during the send operation\n");
        }
    }

    if (rank == 3) {
        err =  MPI_Irecv(buf, 10, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request);
        err += MPI_Wait(&request, MPI_STATUS_IGNORE);
        if (err) {
            fprintf(stderr, "An error occurred during the recv operation\n");
        }
    }

    if (rank == 3) {
        exit(EXIT_FAILURE);
    }

    if (rank == 0) {
        err =  MPI_Issend("No Errors", 10, MPI_CHAR, 2, 0, MPI_COMM_WORLD, &request);
        err += MPI_Wait(&request, MPI_STATUS_IGNORE);
        if (err) {
            fprintf(stderr, "An error occurred during the send operation\n");
        }
    }

    if (rank == 2) {
        err =  MPI_Irecv(buf, 10, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request);
        err += MPI_Wait(&request, MPI_STATUS_IGNORE);
        if (err) {
            fprintf(stderr, "An error occurred during the recv operation\n");
        } else {
            printf(" %s\n", buf);
            fflush(stdout);
        }
    }

    if (rank == 2) {
        exit(EXIT_FAILURE);
    }

    MPI_Finalize();

    return 0;
}


text:
package debrepo.teamcity.service;

import java.util.List;
import java.util.Set;
import java.util.UUID;

import debrepo.teamcity.DebPackage;
import debrepo.teamcity.entity.DebPackageNotFoundInStoreException;
import debrepo.teamcity.entity.DebPackageStore;
import debrepo.teamcity.entity.DebRepositoryConfiguration;
import debrepo.teamcity.entity.DebRepositoryStatistics;
import lombok.Value;

public interface DebRepositoryManager {

	DebPackageStore getPackageStore(String storeName) throws NonExistantRepositoryException;
	public DebPackageStore initialisePackageStore(DebRepositoryConfiguration conf);
	public List<DebPackageStore> getPackageStoresForBuildType(String buildTypeid) throws NonExistantRepositoryException;
	public boolean persist(UUID uuid);
	public DebRepositoryStatistics getRepositoryStatistics(String uuid, String repoUrl);
	public DebRepositoryStatistics getRepositoryStatistics(DebRepositoryConfiguration projectConfig, String repoUrl);
	public void addBuildPackage(DebRepositoryConfiguration config, DebPackage newEntity);
	public Set<String> findUniqueArchByDistAndComponent(String repoName, String distName, String component) throws NonExistantRepositoryException;
	public Set<String> findUniqueComponentByDist(String repoName, String distName) throws NonExistantRepositoryException;
	public Set<String> findUniqueDist(String repoName) throws NonExistantRepositoryException;
	public Set<String> findUniqueComponent(String repoName) throws NonExistantRepositoryException;
	public Set<String> findUniquePackageNameByComponent(String repoName, String component) throws NonExistantRepositoryException;
	public List<? extends DebPackage> findAllByDistComponentArch(String repoName, String distName, String component, String archName) throws NonExistantRepositoryException;
	public List<? extends DebPackage> findAllByDistComponentArchIncludingAll(String repoName, String distName, String component, String archName) throws NonExistantRepositoryException;
	public List<? extends DebPackage> getUniquePackagesByComponentAndPackageName(String repoName, String component, String packageName) throws NonExistantRepositoryException;
	public DebPackage findByUri(String repoName, String uri) throws NonExistantRepositoryException, DebPackageNotFoundInStoreException;
	public boolean isExistingRepository(String repoName);
	public boolean isExistingRepository(UUID uuid);
	public void removeRepository(UUID uuid);
	public boolean isRestrictedRepository(String repoName) throws NonExistantRepositoryException;

	void addBuildPackages(DebRepositoryConfiguration debRepositoryConfiguration, List<DebPackage> newPackages) throws NonExistantRepositoryException;
	public void removeBuildPackages(DebPackageRemovalBean packageRemovalBean);

	@Value
	public static class DebPackageRemovalBean {
		private DebRepositoryConfiguration debRepositoryConfiguration;
		private String buildTypeId;
		private Long buildId;
		private List<DebPackage> packagesToKeep;
	}

}


text:
local NUMBER_OF_SLOTS_TO_LEAVE_FOR_JOINERS_DURING_NON_CAPTAINS_GAMES = 1
local actionslog = { }
local clientsWhoAreConnectedEnoughToBeConsideredBumpable = {}
local MESSAGE_PREFIX = "SLOTS"
table.insert(actionslog, "COMMUNITY SLOTS DEBUG: ")
local victimBumpCounts = {}
local rejectBumpCounts = {}
local commandStructureLastOccupancies = {}
local lastSetReservedSlotAmount
local inReadyRoomSinceTimes = {}
--local fullSpecDataRepository
--local fullSpecSteamIds
local canNotifyAboutOtherServerSlots = true
local blacklistedClients = {}
local lastAnnouncedRemainingPublicSlotsCount
local trySlotEnabled = {}

local COMMANDER_PROTECTION_DURATION_IN_SECONDS = 60
local clientConnectTimesInSeconds = {}

-- local otherServerStaticInfo = {}
-- otherServerStaticInfo["Taunt"] = { address = "tgns2.tacticalgamer.com", simpleName = "Chuckle" }
-- otherServerStaticInfo["Chuckle"] = { address = "tgns.tacticalgamer.com", simpleName = "Taunt" }

local tgnsMd = TGNSMessageDisplayer.Create("TGNS")
local slotsDebugMd = TGNSMessageDisplayer.Create("SLOTSDEBUG")

local function getCommunitySlotsCount()
    local result = Server.GetMaxPlayers() - Shine.Plugins.communityslots.Config.PublicSlots
    return result
end

local function getMaximumSpectatorsCount()
    local result = getCommunitySlotsCount() - NUMBER_OF_SLOTS_TO_LEAVE_FOR_JOINERS_DURING_NON_CAPTAINS_GAMES
    return result
end

local function IsClientAmongLongestPlayed(clients, client, limit)
    TGNS.SortDescending(clients, TGNSConnectedTimesTracker.GetPlayedTimeInSeconds)
    local result = TGNS.ElementIsFoundBeforeIndex(clients, client, limit)
    return result
end

local function IsTargetProtectedStranger(targetClient, playerList)
    local strangersClients = TGNS.GetStrangersClients(playerList)
    local strangersClientsWithFewerThanTenGames = TGNS.Where(strangersClients, function(c) return Balance.GetTotalGamesPlayed(c) < TGNS.PRIMER_GAMES_THRESHOLD end)
    local result = IsClientAmongLongestPlayed(strangersClientsWithFewerThanTenGames, targetClient, Shine.Plugins.communityslots.Config.MinimumStrangers)
    return result
end

local function clientSatisfiesBkaRequirement(client)
    local result = client == nil or Shine.Plugins.betterknownas:IsPlayingWithBkaName(client)
    return result
end

local function IsTargetProtectedPrimerOnly(targetClient, playerList)
    local candidateClients = TGNS.Where(TGNS.GetPrimerOnlyClients(playerList), function(c) return clientSatisfiesBkaRequirement(c) end)
    local result = IsClientAmongLongestPlayed(candidateClients, targetClient, Shine.Plugins.communityslots.Config.MinimumPrimerOnlys)
    return result
end

local function IsTargetProtectedCommander(targetClient)
    local result = false
    local timeAtWhichTargetClientWasLastACommander = commandStructureLastOccupancies[targetClient]
    if timeAtWhichTargetClientWasLastACommander ~= nil then
        if Shared.GetTime() - timeAtWhichTargetClientWasLastACommander <= COMMANDER_PROTECTION_DURATION_IN_SECONDS then
            result = true
        end
    end
    return result
end

local function IsPrimerOnlyTargetProtectedDueToUnprotectedStrangers(targetClient, playerList)
    local result = TGNS.IsPrimerOnlyClient(targetClient) and clientSatisfiesBkaRequirement(targetClient) and TGNS.Any(TGNS.GetStrangersClients(playerList), function(c) return not (IsTargetProtectedStranger(c, playerList) or IsTargetProtectedCommander(c)) end)
    return result
end

local function TargetAndJoiningArePrimerOnly(targetClient, joiningSteamId)
    local result = (TGNS.IsPrimerOnlyClient(targetClient) and clientSatisfiesBkaRequirement(targetClient)) and (TGNS.IsSteamIdPrimerOnly(joiningSteamId) and clientSatisfiesBkaRequirement(TGNS.GetClientByNs2Id(joiningSteamId)))
    return result
end

local function GetRemainingPublicSlots(playingPlayers)
    local result = Shine.Plugins.communityslots.Config.PublicSlots - #playingPlayers
    result = result > 0 and result or 0
    return result
end

local function ServerIsFull(playerList)
    local result = GetRemainingPublicSlots(playerList) == 0
    return result
end

local function Log(message)
    table.insert(actionslog, message)
    -- TGNS.Log(message)
end

local function FindVictimClient(joiningSteamId, playerList, passingTheBumpKarmaDelta)
    local result = nil
    local clientsGivenImmunityViaKarma = {}
    local joiningClient = TGNS.GetClientByNs2Id(joiningSteamId)
    if not joiningClient or trySlotEnabled[joiningClient] then
        local bumpableClients = TGNS.GetMatchingClients(playerList, function(c,p) return Shine.Plugins.communityslots:IsTargetBumpable(c, playerList, joiningSteamId) end)
        if #bumpableClients > 0 then
            TGNS.SortDescending(bumpableClients, Balance.GetTotalGamesPlayed)

            local potentiallyImmuneClients = {}
            if type(passingTheBumpKarmaDelta) == "number" then
                TGNS.DoFor(bumpableClients, function(c)
                    if TGNS.Karma(c) >= math.abs(passingTheBumpKarmaDelta) then
                        table.insert(potentiallyImmuneClients, c)
                    else
                        -- slotsDebugMd:ToAdminConsole(string.format("%s (%s Karma) - not enough Karma for slots immunity.", TGNS.GetClientName(c), TGNS.Karma(c)))
                        return true
                    end
                end)
            end
            if #potentiallyImmuneClients > 0 and #potentiallyImmuneClients < #bumpableClients then
                TGNS.DoForReverse(bumpableClients, function(c, i)
                    if TGNS.Has(potentiallyImmuneClients, c) then
                        table.insert(clientsGivenImmunityViaKarma, c)
                        table.remove(bumpableClients, i)
                    end
                end)
            end

            result = TGNS.GetFirst(bumpableClients)
        end
    else
        if not TGNS.IsSteamIdStranger(joiningSteamId) then
            tgnsMd:ToPlayerNotifyInfo(TGNS.GetPlayer(joiningClient), "Use sh_slot to activate whatever reserved slot you have.")
        end
    end
    return result, clientsGivenImmunityViaKarma
end

local function GetKickDetails(targetClient, joiningClient, playerList)
    local result = {}
    result.targetIsSM = TGNS.IsClientSM(targetClient) and "Y" or "N"
    result.targetHasSignedPrimer = TGNS.HasClientSignedPrimerWithGames(targetClient) and "Y" or "N"
    result.joinerIsSM = TGNS.IsClientSM(joiningClient) and "Y" or "N"
    result.joinerHasSignedPrimer = TGNS.IsClientSM(joiningClient) and "Y" or "N"
    result.strangerCount = #TGNS.GetStrangersClients(playerList)
    result.primerOnlyCount = #TGNS.GetPrimerOnlyClients(playerList)
    result.smCount = #TGNS.GetSmClients(playerList)
    result.shortReport = string.format("T: %s%s J:%s%s ?:%s P:%s S:%s Total:%s", result.targetIsSM, result.targetHasSignedPrimer, result.joinerIsSM, result.joinerHasSignedPrimer, result.strangerCount, result.primerOnlyCount, result.smCount, #playerList)
    return result
end

local function IncrementBumpCount(targetClient, bumpCounts)
    if TGNS.HasClientSignedPrimerWithGames(targetClient) then
        bumpCounts.primerOnly = TGNS.GetNumericValueOrZero(bumpCounts.primerOnly) + 1
    elseif TGNS.IsClientStranger(targetClient) then
        bumpCounts.stranger = TGNS.GetNumericValueOrZero(bumpCounts.stranger) + 1
    end
end

local function AnnounceClientBumpToStrangers(playerName)
    local strangerClients = TGNS.GetMatchingClients(TGNS.GetPlayerList(), function(c,p) return TGNS.IsClientStranger(c) end)
    local strangerPlayers = TGNS.GetPlayers(strangerClients)
    TGNS.DoFor(strangerPlayers, function(p) tgnsMd:ToPlayerNotifyInfo(p, Shine.Plugins.communityslots:GetBumpMessage(playerName)) end)
end

-- local function AnnounceOtherServerOptionsToBumpedClient(client)
--     local otherServerStaticInfo = otherServerStaticInfo[TGNS.GetSimpleServerName()]
--     if otherServerStaticInfo then
--         TGNSServerInfoGetter.GetInfoBySimpleServerName(otherServerStaticInfo.simpleName, function(getResponse)
--             if getResponse.success then
--                 local otherServerDynamicInfo = getResponse.value
--                 if otherServerDynamicInfo.HasRecentData then
--                     local otherServerRemainingPublicSlots = otherServerDynamicInfo.GetPublicSlotsRemaining()
--                     if otherServerRemainingPublicSlots >= 4 then
--                         local message = string.format("~%s slots open on %s! Console: connect %s", otherServerRemainingPublicSlots, otherServerStaticInfo.simpleName, otherServerStaticInfo.address)
--                         tgnsMd:ToPlayerNotifyInfo(TGNS.GetPlayer(client), message)
--                         tgnsMd:ToClientConsole(client, message)
--                         tgnsMd:ToAdminConsole(message)
--                     end
--                 end
--             end
--         end)
--     end
-- end

local function onPreVictimKick(targetClient, targetPlayer, joiningClient, playerList)
    Log(string.format("%s: Victim: %s Joining: %s", GetKickDetails(targetClient, joiningClient, playerList).shortReport, TGNS.GetClientNameSteamIdCombo(targetClient), TGNS.GetClientNameSteamIdCombo(joiningClient)))
    IncrementBumpCount(targetClient, victimBumpCounts)
end

local function onPreJoinerKick(targetClient, targetPlayer, playerList)
    Log(string.format("%s: Reject: %s", GetKickDetails(targetClient, targetClient, playerList).shortReport, TGNS.GetClientNameSteamIdCombo(targetClient)))
    IncrementBumpCount(targetClient, rejectBumpCounts)
end

local function GetPlayingPlayers(clientToExclude)
    local allPlayingPlayers = TGNS.Where(TGNS.GetPlayerList(), function(p)
        local playerIsOnPlayingTeam = TGNS.PlayerIsOnPlayingTeam(p)
        local clientIsVirtual = TGNS.ClientAction(p, TGNS.GetIsClientVirtual)
        return playerIsOnPlayingTeam and not clientIsVirtual
    end)
    local result = {}
    TGNS.DoFor(allPlayingPlayers, function(p)
        local client = TGNS.GetClient(p)
        if client ~= clientToExclude and TGNS.Has(clientsWhoAreConnectedEnoughToBeConsideredBumpable, client) then
            table.insert(result, p)
        end
    end)
    return result
end

local function RemoveTag(partialName)
    local Tags = {}

    Server.GetTags( Tags )

    TGNS.DoFor(Tags, function(Tag)
        if Tag and Tag:find(partialName) then
            Server.RemoveTag(Tag)
        end
    end)
end

local function UpdateReservedSlotsTag(reservedSlotCount)
    RemoveTag("R_S")
    Server.AddTag("R_S"..reservedSlotCount)
end

local function UpdateIgnorePlayNowTag(shouldExist)
    local tagName = "ignore_playnow"
    RemoveTag(tagName)
    if shouldExist then
        Server.AddTag(tagName)
    end
end

local function UpdateReservedSlotAmount()
    local countNonPlayingPlayersConservatively = (TGNS.GetAbbreviatedDayOfWeek() == "Friday" and TGNS.GetCurrentHour() >= 19) or (TGNS.GetAbbreviatedDayOfWeek() == "Sat" and TGNS.GetCurrentHour() < 6)
    local afkNonPlayingThresholdInSeconds = countNonPlayingPlayersConservatively and 300 or 120
    local clientJoinedAfkAndStillIs = function(c) return Shine:IsValidClient(c) and not TGNS.Has(clientsWhoAreConnectedEnoughToBeConsideredBumpable, c) and (TGNS.GetSecondsSinceMapLoaded() - (clientConnectTimesInSeconds[c] or 0) > afkNonPlayingThresholdInSeconds) end
    local playerIsLikelyGone = function(p) return ((TGNS.GetPlayerAfkDurationInSeconds(p) >= afkNonPlayingThresholdInSeconds) or clientJoinedAfkAndStillIs(TGNS.GetClient(p))) and TGNS.IsPlayerReadyRoom(p) end
    local nonPlayingPlayersCount = #TGNS.Where(TGNS.GetPlayerList(), function(p) return (TGNS.IsPlayerSpectator(p) or playerIsLikelyGone(p)) and not TGNS.ClientAction(p, TGNS.GetIsClientVirtual) end)
    if not countNonPlayingPlayersConservatively then
        nonPlayingPlayersCount = nonPlayingPlayersCount + TGNS.GetNumberOfConnectingPlayers()
    end
    local usableNonPlayablePlayersCount = (Server.GetNumPlayersTotal() >= Shine.Plugins.communityslots.Config.PublicSlots) and nonPlayingPlayersCount or 0
    local reservedSlotCount = getCommunitySlotsCount() - usableNonPlayablePlayersCount
    reservedSlotCount = reservedSlotCount > 0 and reservedSlotCount or 0
    if lastSetReservedSlotAmount ~= reservedSlotCount then
        UpdateReservedSlotsTag(reservedSlotCount)
        local ignorePlayNowTagShouldExist = ServerIsFull(GetPlayingPlayers())
        UpdateIgnorePlayNowTag(ignorePlayNowTagShouldExist)
        lastSetReservedSlotAmount = reservedSlotCount
    end
end

local function AnnounceRemainingPublicSlots()
    local playingPlayers = GetPlayingPlayers()
    local remainingPublicSlotsCount = GetRemainingPublicSlots(playingPlayers)
    if lastAnnouncedRemainingPublicSlotsCount == nil or lastAnnouncedRemainingPublicSlotsCount ~= remainingPublicSlotsCount then
        TGNS.ExecuteEventHooks("PublicSlotsRemainingChanged", TGNS.GetSimpleServerName(), remainingPublicSlotsCount, #playingPlayers)
        lastAnnouncedRemainingPublicSlotsCount = remainingPublicSlotsCount
    end
    UpdateReservedSlotAmount()
end

local function GetBumpSummary(playerList, bumpingClient, bumpedClient, joinerOrVictim)
    local supportingMembersCount = #TGNS.GetSmClients(playerList)
    local primerOnlysCount = #TGNS.GetPrimerOnlyClients(playerList)
    local strangersCount = #TGNS.GetStrangersClients(playerList)
    local aliensCount = #TGNS.GetAlienClients(playerList)
    local marinesCount = #TGNS.GetMarineClients(playerList)
    local bumpingClientName = TGNS.GetClientName(bumpingClient)
    local bumpedClientName = TGNS.GetClientName(bumpedClient)
    local bumpingClientCommunityDesignationCharacter = TGNS.GetClientCommunityDesignationCharacter(bumpingClient)
    local bumpedClientCommunityDesignationCharacter = TGNS.GetClientCommunityDesignationCharacter(bumpedClient)
    local bumpedClientPlayedTimeInSeconds = TGNSConnectedTimesTracker.GetPlayedTimeInSeconds(bumpedClient) or 0
    local bumpedClientPlayedDurationClock = TGNS.SecondsToClock(bumpedClientPlayedTimeInSeconds)
    local result = string.format("%s>%s K%s bumping %s %s>%s K%s G%s after %s with S:%s P:%s ?:%s A:%s M:%s", bumpingClientCommunityDesignationCharacter, bumpingClientName, TGNS.Karma(bumpingClient), joinerOrVictim, bumpedClientCommunityDesignationCharacter, bumpedClientName, TGNS.Karma(bumpedClient), Balance.GetTotalGamesPlayed(bumpedClient), bumpedClientPlayedDurationClock, supportingMembersCount, primerOnlysCount, strangersCount, aliensCount, marinesCount)
    return result
end

local function showSlotRevocationAdvisory(client)
    tgnsMd:ToPlayerNotifyInfo(TGNS.GetPlayer(client), "Your reserved slot is presently revoked. See console for details.")
    tgnsMd:ToClientConsole(client, "Your reserved slot privilege is presently revoked.")
    tgnsMd:ToClientConsole(client, "Do not on the server complain or inquire about revoked privileges.")
    tgnsMd:ToClientConsole(client, "Rather, use the CAA forum: http://rr.tacticalgamer.com/Community")
end

local function IsClientBumped(joiningClient)
    local result = false
    local victimTeamNumber = nil
    if not TGNS.GetIsClientVirtual(joiningClient) then
        local playerList = GetPlayingPlayers(joiningClient)
        if ServerIsFull(playerList) then
            local joiningSteamId = TGNS.GetClientSteamId(joiningClient)
            local victimClient, clientsGivenImmunityViaKarma
            if not blacklistedClients[joiningClient] then
                victimClient, clientsGivenImmunityViaKarma = FindVictimClient(joiningSteamId, playerList, Shine.Plugins.karma.Config.Deltas["PassingTheBump"])
            end
            local joiningName = TGNS.GetClientName(joiningClient)
            local blacklistAdvisoryClient
            if victimClient ~= nil then
                local victimPlayer = TGNS.GetPlayer(victimClient)
                victimTeamNumber = TGNS.GetPlayerTeamNumber(victimPlayer)
                local victimName = TGNS.GetClientName(victimClient)
                tgnsMd:ToPlayerNotifyInfo(victimPlayer, Shine.Plugins.communityslots:GetBumpMessage(victimName))
                onPreVictimKick(victimClient,victimPlayer,joiningClient,playerList)
                TGNS.ExecuteClientCommand(victimClient, "readyroom")
                slotsDebugMd:ToAdminConsole(GetBumpSummary(playerList, joiningClient, victimClient, "VICTIM"))
                TGNS.Karma(joiningClient, "Bumping")
                TGNS.DoFor(clientsGivenImmunityViaKarma, function(c)
                    -- slotsDebugMd:ToAdminConsole(string.format("%s (%s Karma) - enough Karma for slots immunity.", TGNS.GetClientName(c), TGNS.Karma(c)))
                    TGNS.Karma(c, "PassingTheBump")
                end)
                TGNS.RemoveAllMatching(clientsWhoAreConnectedEnoughToBeConsideredBumpable, victimClient)
                tgnsMd:ToPlayerNotifyInfo(victimPlayer, "You got bumped by reserved slots. You might be able to Spectate.")
                tgnsMd:ToClientConsole(victimClient, string.format("%s %s protected by good Karma. Learn more in the Required Reading's \"Reserved Slots (Advanced Logic)\" section.", Pluralize(#clientsGivenImmunityViaKarma, "player"), #clientsGivenImmunityViaKarma == 1 and "was" or "were"))
                if blacklistedClients[victimClient] then
                    blacklistAdvisoryClient = victimClient
                end
            else
                local joiningPlayer = TGNS.GetPlayer(joiningClient)
                tgnsMd:ToPlayerNotifyInfo(joiningPlayer, Shine.Plugins.communityslots:GetBumpMessage(joiningName))
                slotsDebugMd:ToAdminConsole(GetBumpSummary(playerList, joiningClient, joiningClient, "JOINER"))
                onPreJoinerKick(joiningClient,joiningPlayer,playerList)
                TGNS.ExecuteClientCommand(joiningClient, "readyroom")
                result = true
                if blacklistedClients[joiningClient] then
                    blacklistAdvisoryClient = joiningClient
                end
            end
            if blacklistAdvisoryClient then
                showSlotRevocationAdvisory(blacklistAdvisoryClient)
            end
        end
    end
    return result, victimTeamNumber
end

local function GetBumpCounts()
    local result = {}
    result.primerOnlyVictims = TGNS.GetNumericValueOrZero(victimBumpCounts.primerOnly)
    result.strangerVictims = TGNS.GetNumericValueOrZero(victimBumpCounts.stranger)
    result.primerOnlyRejects = TGNS.GetNumericValueOrZero(rejectBumpCounts.primerOnly)
    result.strangerRejects = TGNS.GetNumericValueOrZero(rejectBumpCounts.stranger)
    result.totalVictims = result.primerOnlyVictims + result.strangerVictims
    result.totalRejects = result.primerOnlyRejects + result.strangerRejects
    return result
end

local function PrintBumpCountsReport(client)
    local bumpCounts = GetBumpCounts()
    tgnsMd:ToClientConsole(client, string.format("BUMP TOTALS SO FAR THIS MAP (%s):", bumpCounts.totalVictims + bumpCounts.totalRejects))
    tgnsMd:ToClientConsole(client, string.format("Victims: %s (%s Primer Only; %s Stranger)", bumpCounts.totalVictims, bumpCounts.primerOnlyVictims, bumpCounts.strangerVictims))
    tgnsMd:ToClientConsole(client, string.format("Rejects: %s (%s Primer Only; %s Stranger)", bumpCounts.totalRejects, bumpCounts.primerOnlyRejects, bumpCounts.strangerRejects))
end

local Plugin = {}
Plugin.HasConfig = true
Plugin.ConfigName = "communityslots.json"

function Plugin:IsClientRecentCommander(client)
    return IsTargetProtectedCommander(client)
end

function Plugin:GetPlayersForNewGame()
    local prioritizedPlayers = {}
    local addToPrioritizedPlayers = function(p) table.insert(prioritizedPlayers, p) end
    local getPlayerPlayedTime = function(p) return TGNSConnectedTimesTracker.GetPlayedTimeInSeconds(TGNS.GetClient(p)) end

    local playerList = TGNS.Where(TGNS.GetPlayerList(), function(p) return TGNS.IsPlayerReadyRoom(p) and not TGNS.IsPlayerAFK(p) and not TGNS.GetIsClientVirtual(TGNS.GetClient(p)) and not Shine.Plugins.betterknownas:PlayerFailsBkaPrerequisite(p) and not Shine.Plugins.newcomms:ClientIsGated(TGNS.GetClient(p)) end)
    local supportingMemberPlayers = TGNS.Where(playerList, TGNS.IsPlayerSM)

    local primerOnlyPlayers = TGNS.Where(playerList, TGNS.IsPrimerOnlyPlayer)
    local protectedPrimerOnlyPlayers = TGNS.Where(primerOnlyPlayers, function(p) return IsTargetProtectedPrimerOnly(TGNS.GetClient(p), primerOnlyPlayers) end)
    local otherPrimerOnlyPlayers = TGNS.Where(primerOnlyPlayers, function(p) return not TGNS.Has(protectedPrimerOnlyPlayers, p) end)

    local strangerPlayers = TGNS.Where(playerList, TGNS.IsPlayerStranger)
    local protectedStrangerPlayers = TGNS.Where(strangerPlayers, function(p) return IsTargetProtectedStranger(TGNS.GetClient(p), strangerPlayers) end)
    local otherStrangerPlayers = TGNS.Where(strangerPlayers, function(p) return not TGNS.Has(protectedStrangerPlayers, p) end)

    TGNS.SortDescending(protectedStrangerPlayers, getPlayerPlayedTime)
    TGNS.SortDescending(protectedPrimerOnlyPlayers, getPlayerPlayedTime)
    TGNS.SortAscending(supportingMemberPlayers, getPlayerPlayedTime)
    TGNS.SortAscending(otherPrimerOnlyPlayers, getPlayerPlayedTime)
    TGNS.SortAscending(otherStrangerPlayers, getPlayerPlayedTime)

    TGNS.DoFor(protectedStrangerPlayers, addToPrioritizedPlayers)
    TGNS.DoFor(protectedPrimerOnlyPlayers, addToPrioritizedPlayers)
    TGNS.DoFor(supportingMemberPlayers, addToPrioritizedPlayers)
    TGNS.DoFor(otherPrimerOnlyPlayers, addToPrioritizedPlayers)
    TGNS.DoFor(otherStrangerPlayers, addToPrioritizedPlayers)

    local result = TGNS.Take(prioritizedPlayers, Shine.Plugins.communityslots.Config.PublicSlots)
    return result
end

function Plugin:GetBumpMessage(targetName)
    local result = string.format(Shine.Plugins.communityslots.Config.BumpReason, targetName, Shine.Plugins.communityslots.Config.PublicSlots, Shine.Plugins.communityslots.Config.PublicSlots)
    if Shine.Plugins.captains and Shine.Plugins.captains:IsCaptainsModeEnabled() then
        result = result .. " Captains Game in play!"
    end
    return result
end

local function isNonSmDuringGameAndLacksBumpKarma(joiningSteamId)
    local result = TGNS.IsSteamIdPrimerOnly(joiningSteamId) and (TGNS.IsGameInCountdown() or TGNS.IsGameInProgress()) and TGNS.Karma(joiningSteamId) < Shine.Plugins.communityslots.Config.MidGameNonSmBumpKarmaMinimum
    return result
end

function Plugin:IsTargetBumpable(targetClient, playerList, joiningSteamId)
    local result = not TGNS.GetIsClientVirtual(targetClient)
    if result then
        local targetClientHasSlotsPrivilege = not blacklistedClients[targetClient]
        local joinerIsStranger = TGNS.IsSteamIdStranger(joiningSteamId)
        local joinerIsPrimerSignerWhoIsNotPlayingWithBka = TGNS.IsSteamIdPrimerOnly(joiningSteamId) and not clientSatisfiesBkaRequirement(joiningClient)
        local joinerIsNonSmDuringGameAndLacksBumpKarma = isNonSmDuringGameAndLacksBumpKarma(joiningSteamId)
        local targetIsSM = TGNS.IsClientSM(targetClient) and targetClientHasSlotsPrivilege
        local targetIsProtectedCommander = IsTargetProtectedCommander(targetClient)
        local targetIsProtectedStranger = IsTargetProtectedStranger(targetClient, playerList) and targetClientHasSlotsPrivilege
        local targetIsProtectedPrimerOnly = IsTargetProtectedPrimerOnly(targetClient, playerList) and targetClientHasSlotsPrivilege
        local targetAndJoiningArePrimerOnly = TargetAndJoiningArePrimerOnly(targetClient, joiningSteamId) and targetClientHasSlotsPrivilege
        local targetIsPrimerOnlyWhoIsProtectedDueToUnprotectedStrangers = IsPrimerOnlyTargetProtectedDueToUnprotectedStrangers(targetClient, playerList) and targetClientHasSlotsPrivilege
        local targetIsNotYetConnectedEnoughToBeConsideredBumpable = not TGNS.Has(clientsWhoAreConnectedEnoughToBeConsideredBumpable, targetClient)
        local captainsModeIsEnabled = Shine.Plugins.captains and Shine.Plugins.captains:IsCaptainsModeEnabled() and targetClientHasSlotsPrivilege

        if joinerIsStranger or joinerIsPrimerSignerWhoIsNotPlayingWithBka or joinerIsNonSmDuringGameAndLacksBumpKarma or targetIsSM or targetIsProtectedCommander or targetIsProtectedStranger or targetIsProtectedPrimerOnly or targetAndJoiningArePrimerOnly or targetIsPrimerOnlyWhoIsProtectedDueToUnprotectedStrangers or targetIsNotYetConnectedEnoughToBeConsideredBumpable or captainsModeIsEnabled
        then
            result = false
        end
    end
    return result
end

function Plugin:ClientConnect(joiningClient)
    if TGNS.GetIsClientVirtual(joiningClient) then
        TGNS.ScheduleAction(3, function()
            if Shine:IsValidClient(joiningClient) then
                self:ClientConfirmConnect(joiningClient)
            end
        end)
    else
        local pbr = TGNSPlayerBlacklistRepository.Create("communityslots")
        pbr:IsClientBlacklisted(joiningClient, function(isBlacklisted)
            blacklistedClients[joiningClient] = isBlacklisted
        end)
    end
    clientConnectTimesInSeconds[joiningClient] = TGNS.GetSecondsSinceMapLoaded()
end

function Plugin:ClientConfirmConnect(client)
    local chatMessage
    if TGNS.IsClientSM(client) then
        chatMessage = "Supporting Member! Thank you! Your help makes TG's servers possible!"
    elseif TGNS.HasClientSignedPrimerWithGames(client) then
        chatMessage = string.format("TGNS Primer signer! Join the full server when >%s strangers are playing!", Shine.Plugins.communityslots.Config.MinimumStrangers)
    else
        chatMessage = "Press 'm' for menu. Visit http://rr.tacticalgamer.com/Community to say hello!"
    end
    if not TGNS.GetIsClientVirtual(client) then
        TGNS.ScheduleAction(2, function()
            if Shine:IsValidClient(client) then
                tgnsMd:ToClientConsole(client, chatMessage)
            end
        end)
    end
    -- local steamId = TGNS.GetClientSteamId(client)
    -- if ServerIsFull(GetPlayingPlayers()) and TGNS.Has(fullSpecSteamIds, steamId) then
    --     TGNS.ScheduleAction(1, function()
    --         if Shine:IsValidClient(client) then
    --             tgnsMd:ToClientConsole(client, "Your sh_fullspec is enabled. Help: M > Info > sh_fullspec")
    --         end
    --     end)
    -- end
end

TGNS.RegisterEventHook("OnSlotTaken", function(client)
    UpdateReservedSlotAmount()
end)

function Plugin:EndGame(gamerules, winningTeam)
    TGNS.ScheduleAction(TGNS.ENDGAME_TIME_TO_READYROOM, function()
        -- local bumpCounts = GetBumpCounts()
        -- TGNS.DoFor(TGNS.GetMatchingClients(TGNS.GetPlayerList(), TGNS.IsClientAdmin), function(c)
        --     PrintBumpCountsReport(c)
        -- end)
        commandStructureLastOccupancies = {}
    end)
end

-- local function refreshFullSpecData()
--     if fullSpecDataRepository then
--         fullSpecDataRepository.Load(nil, function(loadResponse)
--             if loadResponse.success then
--                 local fullSpecData = loadResponse.value
--                 fullSpecSteamIds = fullSpecData.enrolled
--             else
--                 TGNS.DebugPrint("communityslots ERROR: unable to load fullSpecSteamIds", true)
--             end
--         end)
--     end
-- end

function Plugin:CreateCommands()
    local logCommand = self:BindCommand( "sh_cslog", "cslog", function(client)
        TGNS.DoFor(actionslog, function(logline, index)
            tgnsMd:ToClientConsole(client, logline)
            if #actionslog - index <= 5 then
                tgnsMd:ToPlayerNotifyInfo(TGNS.GetPlayer(client), logline)
            end
        end)
        PrintBumpCountsReport(client)
    end)
    logCommand:Help("View the Community Slots log.")

    local trySlotCommand = self:BindCommand("sh_slot", "slot", function(client)
        local player = TGNS.GetPlayer(client)
        if blacklistedClients[client] then
            showSlotRevocationAdvisory(client)
        else
            trySlotEnabled[client] = true
            tgnsMd:ToPlayerNotifyInfo(player, "Reserved slots logic enabled for your client until the end of the map.")
        end
    end, true)
    trySlotCommand:Help("Enable whatever reserved slot you might have.")

    local showTimesCommand = self:BindCommand( "sh_showtimes", "showtimes", TGNSConnectedTimesTracker.PrintConnectedDurations)
    showTimesCommand:Help("View connected time of each client.")
    -- local fullSpecCommand = self:BindCommand( "sh_fullspec", "fs", function(client)
    --     fullSpecDataRepository.Load(nil, function(loadResponse)
    --         if loadResponse.success then
    --             fullSpecData = loadResponse.value
    --             local steamId = TGNS.GetClientSteamId(client)
    --             if TGNS.Has(fullSpecData.enrolled, steamId) then
    --                 TGNS.RemoveAllMatching(fullSpecData.enrolled, steamId)
    --             else
    --                 table.insert(fullSpecData.enrolled, steamId)
    --             end
    --             fullSpecSteamIds = fullSpecData.enrolled
    --             fullSpecDataRepository.Save(fullSpecData, nil, function(saveResponse)
    --                 if saveResponse.success then
    --                     tgnsMd:ToClientConsole(client, string.format("Your sh_fullspec is %s.", TGNS.Has(fullSpecSteamIds, steamId) and "Enabled" or "Disabled"))
    --                     tgnsMd:ToClientConsole(client, "Execute the command again to toggle. Help: M > Info > sh_fullspec")
    --                 else
    --                     tgnsMd:ToPlayerNotifyError("Unable to save sh_fullspec data.")
    --                 end
    --             end)
    --         else
    --             tgnsMd:ToPlayerNotifyError("Unable to access sh_fullspec data.")
    --         end
    --     end)
    -- end, true)
    -- fullSpecCommand:Help("Toggle your sh_fullspec. Help: http://rr.tacticalgamer.com/FullSpec/Manage")

    -- local fullSpecRefreshCommand = self:BindCommand( "sh_fullspec_datarefresh", nil, function(client)
    --     refreshFullSpecData()
    -- end)
    -- fullSpecRefreshCommand:Help("Used by the TGNS Portal to sync fullspec opt-in changes.")
end

--local function PrintPlayerSlotsStatuses(client)
--    local playerList = TGNS.GetPlayerList()
--    local smClients = TGNS.GetSmClients(playerList)
--    local primerOnlyClients = TGNS.GetPrimerOnlyClients(playerList)
--    local strangerClients = TGNS.GetStrangersClients(playerList)
--    TGNS.DoFor(smClients, function(c) TGNS.ConsolePrint(client, string.format("Supporting Member: %s %s", TGNS.GetClientName(c), TGNS.HasClientSignedPrimerWithGames(c) and "(signed TGNS Primer)" or ""), MESSAGE_PREFIX) end)
--    TGNS.DoFor(primerOnlyClients, function(c) TGNS.ConsolePrint(client, string.format("Primer Only: %s", TGNS.GetClientName(c)), MESSAGE_PREFIX) end)
--    TGNS.DoFor(strangerClients, function(c) TGNS.ConsolePrint(client, string.format("Say Hello To: %s", TGNS.GetClientName(c)), MESSAGE_PREFIX) end)
--    TGNS.ConsolePrint(client, string.format("S: %s | P: %s | ?: %s", #smClients, #primerOnlyClients, #strangerClients), MESSAGE_PREFIX)
--    PrintBumpCountsReport(client)
--end
--TGNS.RegisterCommandHook("Console_sv_csinfo", PrintPlayerSlotsStatuses, "Print Community Slots bump counts and player statuses.", true)

function Plugin:GetMaximumEffectiveSpectatorCount()
    -- local captainsModeIsEnabled = Shine.Plugins.captains and Shine.Plugins.captains:IsCaptainsModeEnabled()
    -- local result = captainsModeIsEnabled and getCommunitySlotsCount() or getMaximumSpectatorsCount()
    -- return result
    return Server.GetMaxSpectators();
end

function Plugin:JoinTeam(gamerules, player, newTeamNumber, force, shineForce)
    local cancel = false
    local victimTeamNumber = nil
    local joiningClient = TGNS.GetClient(player)
    TGNS.ScheduleAction(2, UpdateReservedSlotAmount)
    local publicSlotsPerTeam = Shine.Plugins.communityslots.Config.PublicSlots / 2
    local fullGameDescriptor = string.format("%sv%s", publicSlotsPerTeam, publicSlotsPerTeam)
    local playerList = TGNS.GetPlayerList()
    if TGNS.IsGameplayTeamNumber(newTeamNumber) then
        if not (force or shineForce) then
            cancel, victimTeamNumber = IsClientBumped(joiningClient)
        end
        if cancel then
            if isNonSmDuringGameAndLacksBumpKarma(TGNS.GetClientSteamId(joiningClient)) then
                tgnsMd:ToPlayerNotifyError(player, string.format("Non-SM Primer signers must have %s+ Karma to bump mid-game. View yours: M > TGNS Portal > Karma", Shine.Plugins.communityslots.Config.MidGameNonSmBumpKarmaMinimum))
            end
            tgnsMd:ToPlayerNotifyError(player, string.format("Teams are full (%s). You might be able to join Spectate.", fullGameDescriptor))
            TGNS.RemoveAllMatching(clientsWhoAreConnectedEnoughToBeConsideredBumpable, joiningClient)
        else
            if not (force or shineForce) and not TGNS.GetIsClientVirtual(joiningClient) then
                if victimTeamNumber ~= nil and newTeamNumber ~= victimTeamNumber then
                    tgnsMd:ToPlayerNotifyInfo(player, string.format("You were placed on %s to preserve %s.", TGNS.GetTeamName(victimTeamNumber), fullGameDescriptor))
                    if Shine.Plugins.teamres and Shine.Plugins.teamres.Enabled then
                        Shine.Plugins.teamres:JoinTeam(gamesrules, player, victimTeamNumber, force, shineForce)
                    end
                    return true, victimTeamNumber
                end
            end
        end
    elseif newTeamNumber == kSpectatorIndex then
        if not (force or shineForce) then
            local spectateIsFull = #TGNS.GetSpectatorClients(playerList) >= self:GetMaximumEffectiveSpectatorCount()
            local isCaptainsModeEnabled = Shine.Plugins.captains and Shine.Plugins.captains.Enabled and Shine.Plugins.captains.IsCaptainsModeEnabled and Shine.Plugins.captains.IsCaptainsModeEnabled()
            if TGNS.IsGameInProgress() and not ServerIsFull(GetPlayingPlayers()) and not (TGNS.IsClientAdmin(joiningClient) or TGNS.IsClientSM(joiningClient)) and not isCaptainsModeEnabled and Shine.Plugins.bots:GetTotalNumberOfBots() == 0 and not TGNS.PlayerIsRookie(player) then
                if Shine.GetGamemode() == "ns2" then
                    tgnsMd:ToPlayerNotifyError(player, string.format("Mid-game spectate is available only when teams are %s.", fullGameDescriptor))
                    cancel = true
                end
            end
            if not cancel then
                if spectateIsFull and not TGNS.IsClientAdmin(joiningClient) then
                    cancel = true
                    tgnsMd:ToPlayerNotifyError(player, "Sorry. Spectate is full.")
                    tgnsMd:ToAdminConsole(string.format("%s was not allowed to Spectate.", TGNS.GetPlayerName(player)))
                end
            end
        end
    end
    -- if not cancel and TGNS.IsPlayerReadyRoom(player) and Shine.GetGamemode() == "Infested" and ((#TGNS.GetMarineClients(playerList) + #TGNS.GetSpectatorClients(playerList)) >= Server.GetMaxPlayers() - 1) then
    --     cancel = true
    --     local teamName = TGNS.GetTeamName(newTeamNumber)
    --     tgnsMd:ToPlayerNotifyError(player, string.format("Sorry. %s is full.", teamName))
    --     tgnsMd:ToAdminConsole(string.format("%s was not allowed to join %s.", TGNS.GetPlayerName(player), teamName))
    -- end

    if cancel then
        return false
    end
end

function Plugin:PostJoinTeam(gamerules, player, oldTeamNumber, newTeamNumber, force, shineForce)
    local client = TGNS.GetClient(player)
    if client then
        inReadyRoomSinceTimes[client] = TGNS.IsPlayerReadyRoom(player) and TGNS.GetSecondsSinceMapLoaded() or nil
        if TGNS.IsGameplayTeamNumber(newTeamNumber) then
            if not TGNS.Has(clientsWhoAreConnectedEnoughToBeConsideredBumpable, client) then
                table.insert(clientsWhoAreConnectedEnoughToBeConsideredBumpable, client)
                TGNS.ExecuteEventHooks("OnSlotTaken", client)
            end
        elseif newTeamNumber == kSpectatorIndex then
            TGNS.RemoveAllMatching(clientsWhoAreConnectedEnoughToBeConsideredBumpable, client)
        end
    end
end

-- local function sweep()
--     if Server.GetNumPlayersTotal() >= Server.GetMaxPlayers()-0 then
--         TGNS.DoFor(TGNS.GetReadyRoomClients(TGNS.Where(TGNS.GetPlayerList(), function(p) return not (Shine.Plugins.sidebar and Shine.Plugins.sidebar:PlayerIsInSidebar(p)) end)), function(c)
--             if TGNS.IsGameInProgress() then
--                 local lastTeamChangeTime = inReadyRoomSinceTimes[c]
--                 if lastTeamChangeTime then
--                     local secondsRemaining = TGNS.RoundPositiveNumberDown(lastTeamChangeTime + 180 - TGNS.GetSecondsSinceMapLoaded())
--                     if secondsRemaining > 0 then
--                         if secondsRemaining < 40 then
--                             local p = TGNS.GetPlayer(c)
--                             tgnsMd:ToPlayerNotifyError(p, string.format("Play or Spectate within %s seconds to stay on the server.", secondsRemaining))
--                             Shine.Plugins.scoreboard:AlertApplicationIconForPlayer(p)
--                         end
--                     else
--                         TGNSClientKicker.Kick(c, "Too long spent in the Ready Room.", nil, AnnounceClientBumpToStrangers)
--                         tgnsMd:ToAdminNotifyInfo(string.format("%s kicked for being in the Ready Room too long.", TGNS.GetClientName(c)))
--                     end
--                 else
--                     inReadyRoomSinceTimes[c] = TGNS.GetSecondsSinceMapLoaded()
--                 end
--             else
--                 inReadyRoomSinceTimes[c] = TGNS.GetSecondsSinceMapLoaded()
--             end
--         end)
--     end
-- end

function Plugin:ClientDisconnect(client)
    UpdateReservedSlotAmount()
end

TGNS.RegisterEventHook("CheckConnectionAllowed", function(joiningSteamId)
    local result = true
    if not TGNS.IsSteamIdAdmin(joiningSteamId) then
        local playingPlayers = GetPlayingPlayers()
        local nonSpectatorPlayers = TGNS.Where(TGNS.GetPlayerList(), function(p) return not TGNS.IsPlayerSpectator(p) and not TGNS.GetIsClientVirtual(TGNS.GetClient(p)) end)
        if ServerIsFull(nonSpectatorPlayers) then
            local bumpableClient = FindVictimClient(joiningSteamId, playingPlayers)
            -- local joinerWillingToSpectate = TGNS.Has(fullSpecSteamIds, joiningSteamId) or TGNS.HasSteamIdSignedPrimer(joiningSteamId)
            local joinerWillingToSpectate = TGNS.HasSteamIdSignedPrimer(joiningSteamId)
            result = bumpableClient ~= nil or (joinerWillingToSpectate and #TGNS.GetSpectatorClients(TGNS.GetPlayerList()) < Shine.Plugins.communityslots:GetMaximumEffectiveSpectatorCount())
        end
    end
    return result
end)

function Plugin:Think()
    TGNS.DoFor(TGNS.GetMatchingClients(TGNS.GetPlayerList(), TGNS.IsClientCommander), function(client)
        commandStructureLastOccupancies[client] = Shared.GetTime()
    end)
end

function Plugin:PlayerSay(client, networkMessage)
    local cancel = false
    local teamOnly = networkMessage.teamOnly
    local message = StringTrim(networkMessage.message)
    if not teamOnly then
        TGNS.PlayerAction(client, function(p)
            if p then
                if TGNS.IsPlayerSpectator(p) and not (Shine.Plugins.chatchannels and Shine.Plugins.chatchannels.DoesChatStartWithChatChannelTriggerCharacter and Shine.Plugins.chatchannels:DoesChatStartWithChatChannelTriggerCharacter(message)) then
                    TGNS.SendChatMessage(p, TGNS.GetSpectatorPlayers(TGNS.GetPlayerList()), true, message)
                    cancel = true
                else
                    if TGNS.IsPlayerReadyRoom(p) and TGNS.IsGameInProgress() and not TGNS.HasClientSignedPrimerWithGames(client) then
                        if ServerIsFull(GetPlayingPlayers()) and not TGNS.Has(clientsWhoAreConnectedEnoughToBeConsideredBumpable, client) then
                            tgnsMd:ToPlayerNotifyError(p, "You must read and agree to our rules")
                            tgnsMd:ToPlayerNotifyError(p, "to chat to a full game from the Ready Room.")
                            tgnsMd:ToPlayerNotifyError(p, "Team chat starting with '@' goes to all admins.")
                            cancel = true
                        end
                    end
                end
            end
        end)
    end
    if cancel then
        return ""
    end
end

function Plugin:Initialise()
    self.Enabled = true
    self:CreateCommands()
    -- TGNS.ScheduleActionInterval(10, sweep)
    TGNS.ScheduleActionInterval(10, AnnounceRemainingPublicSlots)
    -- fullSpecDataRepository = TGNSDataRepository.Create("fullspec", function(data)
    --     data.enrolled = data.enrolled or {}
    --     return data
    -- end)
    -- TGNS.ScheduleAction(2, refreshFullSpecData)
    -- TGNS.ScheduleActionInterval(15, function()
    --     if canNotifyAboutOtherServerSlots then
    --         local humansCount = #TGNS.Where(TGNS.GetClientList(), function(c) return not TGNS.GetIsClientVirtual(c) end)
    --         if humansCount > 0 and humansCount < 10 then
    --             local otherServerStaticInfo = otherServerStaticInfo[TGNS.GetSimpleServerName()]
    --             if otherServerStaticInfo then
    --                 TGNSServerInfoGetter.GetInfoBySimpleServerName(otherServerStaticInfo.simpleName, function(otherServerDynamicInfo)
    --                     if otherServerDynamicInfo.HasRecentData then
    --                         local otherServerPlayingPlayersCount = otherServerDynamicInfo.GetPlayingPlayersCount()
    --                         local otherServerPublicSlotsRemaining = otherServerDynamicInfo.GetPublicSlotsRemaining()
    --                         if otherServerPlayingPlayersCount > humansCount and otherServerPublicSlotsRemaining >= humansCount then
    --                             tgnsMd:ToAllNotifyInfo(string.format("%s players and %s open slots on %s (%s ago).", otherServerPlayingPlayersCount, otherServerPublicSlotsRemaining, otherServerStaticInfo.simpleName, otherServerDynamicInfo.GetTimeElapsedSinceLastUpdate()))
    --                             tgnsMd:ToAllNotifyInfo(string.format("To join %s from your console: connect %s", otherServerStaticInfo.simpleName, otherServerStaticInfo.address))
    --                             canNotifyAboutOtherServerSlots = false
    --                             TGNS.ScheduleAction(180, function() canNotifyAboutOtherServerSlots = true end)
    --                         end
    --                     end
    --                 end)
    --             end
    --         end
    --     end
    -- end)

    return true
end

function Plugin:Cleanup()
    --Cleanup your extra stuff like timers, data etc.
    self.BaseClass.Cleanup( self )
end

Shine:RegisterExtension("communityslots", Plugin)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>geologger.saints.com.geologger.map クラス階層</title>
<meta name="date" content="2015-03-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

ブラウザのJavaScriptが無効になっています。

概要

パッケージ

クラス

階層ツリー

非推奨

索引

ヘルプ

前

次

フレーム

フレームなし

すべてのクラス

パッケージgeologger.saints.com.geologger.mapの階層

パッケージ階層:

すべてのパッケージ

クラス階層

java.lang.Object

geologger.saints.com.geologger.map.BaseMapWorker

geologger.saints.com.geologger.map.BaseMapWorker_

geologger.saints.com.geologger.map.MapWorker

geologger.saints.com.geologger.map.MapWorker_

geologger.saints.com.geologger.map.CheckinInfoWindowAdapter (implements com.google.android.gms.maps.GoogleMap.InfoWindowAdapter)

概要

パッケージ

クラス

階層ツリー

非推奨

索引

ヘルプ

前

次

フレーム

フレームなし

すべてのクラス


text:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';

// Like https://github.com/brunobertolini/styled-by
const styledBy = (property, mapping) => props => mapping[props[property]];

const StyledButton = withStyles({
  root: {
    background: styledBy('color', {
      default: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
      blue: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
    }),
    borderRadius: 3,
    border: 0,
    color: 'white',
    height: 48,
    padding: '0 30px',
    boxShadow: styledBy('color', {
      default: '0 3px 5px 2px rgba(255, 105, 135, .3)',
      blue: '0 3px 5px 2px rgba(33, 203, 243, .3)',
    }),
  },
})(({ classes, color, ...other }) => <Button className={classes.root} {...other} />);

class DynamicCSS extends React.Component {
  state = {
    color: 'default',
  };

  handleChange = event => {
    this.setState({ color: event.target.checked ? 'blue' : 'default' });
  };

  render() {
    return (
      <React.Fragment>
        <FormControlLabel
          control={
            <Switch
              checked={this.state.color === 'blue'}
              onChange={this.handleChange}
              color="primary"
              value="dynamic-class-name"
            />
          }
          label="Blue"
        />
        <StyledButton color={this.state.color}>Dynamic CSS</StyledButton>
      </React.Fragment>
    );
  }
}

export default DynamicCSS;


text:
package com.narvis.dataaccess.models.conf;

import com.narvis.dataaccess.interfaces.dataproviders.IConfDataProvider;
import java.util.HashMap;
import java.util.Map;
import org.simpleframework.xml.*;

/**
 *
 * @author Yoann LE MOUËL & Alban BONNET & Charles COQUE & Raphaël BLIN
 */
@Root(name = "ModuleConf")
public class ModuleConf implements IConfDataProvider {

    @Element(name = "ModuleClassPath")
    private String moduleClassPath;

    @ElementMap(entry = "entry", key = "key", attribute = true, inline = true, required = false)
    @SuppressWarnings("FieldMayBeFinal")
    private Map<String, String> entries;

    public static String MODULE_CLASS_PATH_KEYWORD = "ModuleClassPath";

    public ModuleConf() {
        this.entries = new HashMap<>();
    }

    public String getModuleClassPath() {
        return this.moduleClassPath;
    }

    public void setModuleClassPath(String val) {
        this.moduleClassPath = val;
    }

    public Map<String, String> getEntries() {
        return this.entries;
    }

    @Override
    public String getData(String... keywords) {
        if (keywords[0].equals(MODULE_CLASS_PATH_KEYWORD)) {
            return this.moduleClassPath;
        }
        return this.entries.get(keywords[0]);
    }
    //Todo

    @Override
    public void setData(String... keywords) {
        if (keywords[0].equals(MODULE_CLASS_PATH_KEYWORD)) {
            this.moduleClassPath = keywords[1];
        }
        this.entries.put(keywords[0], keywords[1]);
    }

}


text:
<?php

/*
 * (c) Kévin Dunglas <dunglas@gmail.com>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\HTML5FormBundle\Form;

use Symfony\Component\Form\TextField;

/**
 * SearchField.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class SearchField extends TextField {
}