text:
package org.ihtsdo.sct.drugmatch.verification.service.healthterm.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.ihtsdo.sct.drugmatch.exception.DrugMatchConfigurationException;
import org.ihtsdo.sct.drugmatch.properties.DrugMatchProperties;
import org.ihtsdo.sct.drugmatch.verification.service.VerificationService;
import org.ihtsdo.sct.drugmatch.verification.service.healthterm.model.ConceptDescriptor;
import org.ihtsdo.sct.drugmatch.verification.service.healthterm.model.ConceptSearchResultDescriptor;
import org.ihtsdo.sct.drugmatch.verification.service.healthterm.model.LogEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * HealthTerm implementation of {@link VerificationService}.
 * @author dev-team@carecom.dk
 */
public class VerificationServiceImpl implements VerificationService {

	private static final Logger log = LoggerFactory.getLogger(VerificationServiceImpl.class);

	private static final TypeReference<List<ConceptDescriptor>> CONCEPT_DESCRIPTOR_TYPE_REFERENCE = new TypeReference<List<ConceptDescriptor>>() {
		// empty on purpose.
	};

	private static final TypeReference<List<ConceptSearchResultDescriptor>> CONCEPT_SEARCH_RESULT_DESCRIPTOR_TYPE_REFERENCE = new TypeReference<List<ConceptSearchResultDescriptor>>() {
		// empty on purpose.
	};

	private static final TypeReference<List<LogEntry>> LOG_ENTRY_TYPE_REFERENCE = new TypeReference<List<LogEntry>>() {
		// empty on purpose.
	};

	/**
	 * Empty, cause: unable to filter on namespace as the SNOMED CT international release now contains 1+ namespace.
	 */
	private static final Set<String> SNOMED_CT_NAMESPACE_IDS = Collections.<String>emptySet();

	private final CredentialsProvider credentialsProvider;

	private SSLConnectionSocketFactory customSslSocketFactory = null;

	private final Set<String> englishLocaleCodes = new TreeSet<>(Arrays.asList(new String[] {"en", "en-GB", "en-US"}));

	/**
	 * @throws DrugMatchConfigurationException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	public VerificationServiceImpl() throws DrugMatchConfigurationException, KeyManagementException, NoSuchAlgorithmException, IOException {
		String serviceUrl = DrugMatchProperties.getVerificationService();
		if (serviceUrl == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.VERIFICATION_SERVICE + "' isn't set!");
		}
		UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"}, UrlValidator.ALLOW_LOCAL_URLS);
		if (!urlValidator.isValid(serviceUrl.toLowerCase(Locale.ENGLISH))) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.VERIFICATION_SERVICE + "' isn't a valid HTTP/HTTPS URL!");
		}
		String login = DrugMatchProperties.getVerificationLogin();
		if (login == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.VERIFICATION_LOGIN + "' isn't set!");
		}
		String password = DrugMatchProperties.getVerificationPassword();
		if (password == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.VERIFICATION_PASSWORD + "' isn't set!");
		}
		URL url = new URL(serviceUrl);
		int port;
		if (url.getPort() > 0) {
			port = url.getPort();
		} else {
			port = ("https".equals(url.getProtocol().toLowerCase(Locale.ENGLISH))) ? 443 : 80;
		}
		this.credentialsProvider = new BasicCredentialsProvider();
		this.credentialsProvider.setCredentials(
				new AuthScope(url.getHost(), port),
				new UsernamePasswordCredentials(login, password));
		// test if CA root is present in JRE, otherwise invoke SSL workaround
		try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
			HttpGet httpget = new HttpGet(url.getProtocol() + "://" + url.getHost() + ":" + port);
			log.debug("Executing request: {}", httpget.getRequestLine());
			try (CloseableHttpResponse response = httpclient.execute(httpget);) {
				log.debug("Executed request: {} status: {}", httpget.getRequestLine(), response.getStatusLine());
				EntityUtils.consume(response.getEntity());
			} catch (SSLHandshakeException e) {
				if ("sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target".equals(e.getMessage())) {
					log.debug("Unable to establish certificate trust chain, most likely cause: root certificate unavailable from JRE keystore. Proceeding with disabled TrustManager.");
					this.customSslSocketFactory = new SSLConnectionSocketFactory(initializeCerts());
				} else {
					throw e;
				}
			}
		}
	}

	/**
	 *  Workaround for ex. StartCom CA root certificate is not included in the JRE's default keystore.
	 * @return {@link SSLContext}
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 */
	private static SSLContext initializeCerts() throws KeyManagementException, NoSuchAlgorithmException {

		TrustManager[] trustAllCerts = new TrustManager[] {
			new X509TrustManager() {
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}

				@Override
				public void checkClientTrusted(final X509Certificate[] certs,
						final String authType) {
					// empty on purpose
				}

				@Override
				public void checkServerTrusted(final X509Certificate[] certs,
						final String authType) {
					// empty on purpose
				}
			}};

		// Install the all-trusting trust manager
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new SecureRandom());
		return sc;
	}

	private CloseableHttpClient getHttpClient() {
		if (this.customSslSocketFactory == null) {
			return HttpClients.custom().setDefaultCredentialsProvider(this.credentialsProvider).build();
		} // else
		return HttpClients.custom().setDefaultCredentialsProvider(this.credentialsProvider).setSSLSocketFactory(this.customSslSocketFactory).build();
	}

	private static HttpGet getHttpGetJSON(final String path) throws DrugMatchConfigurationException {
		StringBuilder url = new StringBuilder(DrugMatchProperties.getVerificationService());
		if (!path.startsWith("/")) {
			url.append('/');
		}
		url.append(path);
		HttpGet httpget = new HttpGet(url.toString());
		httpget.setHeader("Accept", "application/json");
		return httpget;
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getAttributeExactMatch(final Set<Long> attributeIds,
			final Set<Long> valueIds) throws DrugMatchConfigurationException, IOException {
		// construct path
		StringBuilder path = new StringBuilder("/webservice/restricted/v1.0/search/concept/attributeRelationExact?");
		// attribute (Relationship type ID)
		for (Long attributeId : attributeIds) {
			path.append("&attributeId=")
				.append(attributeId);
		}
		// value (conceptid2|target)
		for (Long valueId : valueIds) {
			path.append("&valueId=")
				.append(valueId);
		}
		// remove unneeded '&' for first parameter
		int i = path.indexOf("?&");
		if (i > -1) {
			path.deleteCharAt(i + 1);
		}
		// search
		return getConceptSearchResult(path.toString());
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptDescriptor> getConceptsByIds(final Set<Long> conceptIds) throws DrugMatchConfigurationException, IOException {
		try (CloseableHttpClient httpclient = getHttpClient();) {
			HttpGet httpget = getHttpGetConceptsByIds(conceptIds);
			try (CloseableHttpResponse response = httpclient.execute(httpget);) {
				log.debug("Executed request: {} status: {}", httpget.getRequestLine(), response.getStatusLine());
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					ObjectMapper mapper = new ObjectMapper();
					JsonNode results = mapper.readTree(response.getEntity().getContent()).get("record");
					List<ConceptDescriptor> result = mapper.readValue(results.traverse(), CONCEPT_DESCRIPTOR_TYPE_REFERENCE);
					EntityUtils.consume(response.getEntity());
					if (result.size() != conceptIds.size()) {
						log.debug("Request returned: {} expected: {} result(s)!",
								result.size(),
								conceptIds.size());
					}
					return result;
				} // else
				StringBuilder sb = new StringBuilder();
				try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
						CharEncoding.UTF_8));) {
					String line;
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					ObjectMapper mapper = new ObjectMapper();
					JsonNode logEntries = mapper.readTree(sb.toString()).get("logEntry");
					List<LogEntry> result = mapper.readValue(logEntries.traverse(), LOG_ENTRY_TYPE_REFERENCE);
					EntityUtils.consume(response.getEntity());
					if (result.isEmpty()) {
						throw new IOException("Unable to retrieve Concept by ID, cause: HTTP status code " + response.getStatusLine().getStatusCode());
					} // else
					throw new IOException(result.iterator().next().toString());
				} catch (JsonParseException e) {
					throw new IOException("Unable to retrieve Concept by ID, cause: HTTP status code " + response.getStatusLine().getStatusCode() +
							" response content: " + sb.toString());
				}
			}
		}
	}

	/**
	 * Common logic for generating a Concept ID GET.
	 * @param conceptIds
	 * @return {@link HttpGet}
	 * @throws DrugMatchConfigurationException
	 */
	private static HttpGet getHttpGetConceptsByIds(Set<Long> conceptIds) throws DrugMatchConfigurationException {
		// construct path
		StringBuilder path = new StringBuilder("/webservice/restricted/v1.0/lookup/concept/byId?");
		// attribute (Relationship type ID)
		for (Long conceptId : conceptIds) {
			path.append("&conceptId=")
				.append(conceptId);
		}
		// remove unneeded '&' for first parameter
		int i = path.indexOf("?&");
		if (i > -1) {
			path.deleteCharAt(i + 1);
		}
		return getHttpGetJSON(path.toString());
	}

	/**
	 * {@inheritDoc}
	 */
	public String getConceptsByIdsUrl(Set<Long> conceptIds) throws DrugMatchConfigurationException {
		return getHttpGetConceptsByIds(conceptIds).getURI().toString();
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getDoseFormExactEnglishTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		return getDoseFormExactTermMatch(
				SNOMED_CT_NAMESPACE_IDS,
				query,
				this.englishLocaleCodes);
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getDoseFormExactNationalTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		String nationalNamespaceId = DrugMatchProperties.getNationalNamespaceId();
		if (nationalNamespaceId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.EXTENSION_NAMESPACE_ID + "' isn't set!");
		} // else
		return getDoseFormExactTermMatch(
				Collections.singleton(nationalNamespaceId),
				query,
				Collections.<String>emptySet());
	}

	/**
	 * Common logic for dose form exact term match
	 * @param namespaceIds
	 * @param query
	 * @param localeCodes
	 * @return {@link List}({@link ConceptSearchResultDescriptor})
	 * @throws DrugMatchConfigurationException
	 * @throws IOException
	 */
	private List<ConceptSearchResultDescriptor> getDoseFormExactTermMatch(final Set<String> namespaceIds,
			final String query,
			final Set<String> localeCodes) throws DrugMatchConfigurationException, IOException {
		Long constraintId = DrugMatchProperties.getConstraintIdDoseForm();
		if (constraintId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.CONSTRAINT_ID_DOSE_FORM + "' isn't set!");
		} // else
		return getExactTermMatch(
				namespaceIds,
				Collections.singleton(constraintId),
				localeCodes,
				query);
	}

	/**
	 * Common logic for exact term match
	 * @param namespaceIds
	 * @param query
	 * @param localeCodes
	 * @return {@link List}({@link ConceptSearchResultDescriptor})
	 * @throws DrugMatchConfigurationException
	 * @throws IOException
	 */
	private List<ConceptSearchResultDescriptor> getExactTermMatch(final Set<String> namespaceIds,
			final Set<Long> constraintIds,
			final Set<String> localeCodes,
			final String query) throws DrugMatchConfigurationException, IOException {
		// construct path
		StringBuilder path = new StringBuilder("/webservice/restricted/v1.0/search/concept/exactSearch?query=");
		path.append(URLEncoder.encode(query, CharEncoding.UTF_8));
		// top point constraints
		for (Long constraintId : constraintIds) {
			path.append("&constraintId=")
				.append(constraintId);
		}
		// namespaces
		for (String namespaceId : namespaceIds) {
			path.append("&namespaceId=")
				.append(URLEncoder.encode(namespaceId, CharEncoding.UTF_8));
		}
		// locale codes
		for (String localeCode : localeCodes) {
			path.append("&contentLocaleCode=")
				.append(URLEncoder.encode(localeCode, CharEncoding.UTF_8));
		}
		// search
		return getConceptSearchResult(path.toString());
	}

	/**
	 * @param path
	 * @return {@link List}({@link ConceptSearchResultDescriptor}), for the given path.
	 * @throws DrugMatchConfigurationException
	 * @throws IOException
	 */
	private List<ConceptSearchResultDescriptor> getConceptSearchResult(final String path) throws DrugMatchConfigurationException, IOException {
		try (CloseableHttpClient httpclient = getHttpClient();) {
			HttpGet httpget = getHttpGetJSON(path);
			try (CloseableHttpResponse response = httpclient.execute(httpget);) {
				log.debug("Executed request: {} status: {}", httpget.getRequestLine(), response.getStatusLine());
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					ObjectMapper mapper = new ObjectMapper();
					JsonNode results = mapper.readTree(response.getEntity().getContent()).get("record");
					List<ConceptSearchResultDescriptor> result = mapper.readValue(results.traverse(), CONCEPT_SEARCH_RESULT_DESCRIPTOR_TYPE_REFERENCE);
					EntityUtils.consume(response.getEntity());
					log.debug("Request returned: {} result(s).",
							result.size());
					return result;
				} // else
				StringBuilder sb = new StringBuilder();
				try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
						CharEncoding.UTF_8));) {
					String line;
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					ObjectMapper mapper = new ObjectMapper();
					JsonNode logEntries = mapper.readTree(sb.toString()).get("logEntry");
					List<LogEntry> result = mapper.readValue(logEntries.traverse(), LOG_ENTRY_TYPE_REFERENCE);
					EntityUtils.consume(response.getEntity());
					if (result.isEmpty()) {
						throw new IOException("Unable to search for exact match, cause: HTTP status code " + response.getStatusLine().getStatusCode());
					} // else
					throw new IOException(result.iterator().next().toString());
				} catch (JsonParseException e) {
					throw new IOException("Unable to search for exact match, cause: HTTP status code " + response.getStatusLine().getStatusCode() +
							" response content: " + sb.toString());
				}
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getSubstanceExactEnglishTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		return getSubstanceExactTermMatch(
				SNOMED_CT_NAMESPACE_IDS,
				query,
				this.englishLocaleCodes);
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getSubstanceExactNationalTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		String nationalNamespaceId = DrugMatchProperties.getNationalNamespaceId();
		if (nationalNamespaceId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.EXTENSION_NAMESPACE_ID + "' isn't set!");
		} // else
		return getSubstanceExactTermMatch(
				Collections.singleton(nationalNamespaceId),
				query,
				Collections.<String>emptySet());
	}

	/**
	 * Common logic for substance exact term match
	 * @param namespaceIds
	 * @param query
	 * @param localeCodes
	 * @return {@link List}({@link ConceptSearchResultDescriptor})
	 * @throws DrugMatchConfigurationException
	 * @throws IOException
	 */
	private List<ConceptSearchResultDescriptor> getSubstanceExactTermMatch(final Set<String> namespaceIds,
			final String query,
			final Set<String> localeCodes) throws DrugMatchConfigurationException, IOException {
		Long constraintId = DrugMatchProperties.getConstraintIdSubstance();
		if (constraintId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.CONSTRAINT_ID_SUBSTANCE + "' isn't set!");
		} // else
		return getExactTermMatch(
				namespaceIds,
				Collections.singleton(constraintId),
				localeCodes,
				query);
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getUnitExactEnglishTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		return getUnitExactTermMatch(
				SNOMED_CT_NAMESPACE_IDS,
				query,
				this.englishLocaleCodes);
	}

	/**
	 * {@inheritDoc}
	 */
	public final List<ConceptSearchResultDescriptor> getUnitExactNationalTermMatch(final String query) throws DrugMatchConfigurationException, IOException {
		String nationalNamespaceId = DrugMatchProperties.getNationalNamespaceId();
		if (nationalNamespaceId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.EXTENSION_NAMESPACE_ID + "' isn't set!");
		} // else
		return getUnitExactTermMatch(
				Collections.singleton(nationalNamespaceId),
				query,
				Collections.<String>emptySet());
	}

	/**
	 * Common logic for unit exact term match
	 * @param namespaceIds
	 * @param query
	 * @param localeCodes
	 * @return {@link List}({@link ConceptSearchResultDescriptor})
	 * @throws DrugMatchConfigurationException
	 * @throws IOException
	 */
	private List<ConceptSearchResultDescriptor> getUnitExactTermMatch(final Set<String> namespaceIds,
			final String query,
			final Set<String> localeCodes) throws DrugMatchConfigurationException, IOException {
		Long constraintId = DrugMatchProperties.getConstraintIdUnit();
		if (constraintId == null) {
			throw new DrugMatchConfigurationException("Unable to proceed, cause: '" + DrugMatchProperties.CONSTRAINT_ID_UNIT + "' isn't set!");
		} // else
		return getExactTermMatch(
				namespaceIds,
				Collections.singleton(constraintId),
				localeCodes,
				query);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.metadata;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import io.airlift.discovery.client.ServiceDescriptor;
import io.airlift.discovery.client.ServiceSelector;
import io.airlift.discovery.client.ServiceType;
import io.airlift.http.client.HttpClient;
import io.airlift.log.Logger;
import io.airlift.node.NodeInfo;
import io.prestosql.client.NodeVersion;
import io.prestosql.connector.ConnectorId;
import io.prestosql.connector.system.GlobalSystemConnector;
import io.prestosql.failureDetector.FailureDetector;
import io.prestosql.server.InternalCommunicationConfig;
import io.prestosql.spi.Node;
import io.prestosql.spi.NodeState;
import org.weakref.jmx.Managed;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference;
import static io.airlift.concurrent.Threads.threadsNamed;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.prestosql.spi.NodeState.ACTIVE;
import static io.prestosql.spi.NodeState.INACTIVE;
import static io.prestosql.spi.NodeState.SHUTTING_DOWN;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;

@ThreadSafe
public final class DiscoveryNodeManager
        implements InternalNodeManager
{
    private static final Logger log = Logger.get(DiscoveryNodeManager.class);

    private static final Splitter CONNECTOR_ID_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
    private final ServiceSelector serviceSelector;
    private final FailureDetector failureDetector;
    private final NodeVersion expectedNodeVersion;
    private final ConcurrentHashMap<String, RemoteNodeState> nodeStates = new ConcurrentHashMap<>();
    private final HttpClient httpClient;
    private final ScheduledExecutorService nodeStateUpdateExecutor;
    private final ExecutorService nodeStateEventExecutor;
    private final boolean httpsRequired;
    private final PrestoNode currentNode;

    @GuardedBy("this")
    private SetMultimap<ConnectorId, Node> activeNodesByConnectorId;

    @GuardedBy("this")
    private AllNodes allNodes;

    @GuardedBy("this")
    private Set<Node> coordinators;

    @GuardedBy("this")
    private final List<Consumer<AllNodes>> listeners = new ArrayList<>();

    @Inject
    public DiscoveryNodeManager(
            @ServiceType("presto") ServiceSelector serviceSelector,
            NodeInfo nodeInfo,
            FailureDetector failureDetector,
            NodeVersion expectedNodeVersion,
            @ForNodeManager HttpClient httpClient,
            InternalCommunicationConfig internalCommunicationConfig)
    {
        this.serviceSelector = requireNonNull(serviceSelector, "serviceSelector is null");
        this.failureDetector = requireNonNull(failureDetector, "failureDetector is null");
        this.expectedNodeVersion = requireNonNull(expectedNodeVersion, "expectedNodeVersion is null");
        this.httpClient = requireNonNull(httpClient, "httpClient is null");
        this.nodeStateUpdateExecutor = newSingleThreadScheduledExecutor(threadsNamed("node-state-poller-%s"));
        this.nodeStateEventExecutor = newCachedThreadPool(threadsNamed("node-state-events-%s"));
        this.httpsRequired = internalCommunicationConfig.isHttpsRequired();

        this.currentNode = findCurrentNode(
                serviceSelector.selectAllServices(),
                requireNonNull(nodeInfo, "nodeInfo is null").getNodeId(),
                expectedNodeVersion,
                httpsRequired);

        refreshNodesInternal();
    }

    private static PrestoNode findCurrentNode(List<ServiceDescriptor> allServices, String currentNodeId, NodeVersion expectedNodeVersion, boolean httpsRequired)
    {
        for (ServiceDescriptor service : allServices) {
            URI uri = getHttpUri(service, httpsRequired);
            NodeVersion nodeVersion = getNodeVersion(service);
            if (uri != null && nodeVersion != null) {
                PrestoNode node = new PrestoNode(service.getNodeId(), uri, nodeVersion, isCoordinator(service));

                if (node.getNodeIdentifier().equals(currentNodeId)) {
                    checkState(
                            node.getNodeVersion().equals(expectedNodeVersion),
                            "INVARIANT: current node version (%s) should be equal to %s",
                            node.getNodeVersion(),
                            expectedNodeVersion);
                    return node;
                }
            }
        }
        throw new IllegalStateException("INVARIANT: current node not returned from service selector");
    }

    @PostConstruct
    public void startPollingNodeStates()
    {
        nodeStateUpdateExecutor.scheduleWithFixedDelay(() -> {
            try {
                pollWorkers();
            }
            catch (Exception e) {
                log.error(e, "Error polling state of nodes");
            }
        }, 5, 5, TimeUnit.SECONDS);
        pollWorkers();
    }

    private void pollWorkers()
    {
        AllNodes allNodes = getAllNodes();
        Set<Node> aliveNodes = ImmutableSet.<Node>builder()
                .addAll(allNodes.getActiveNodes())
                .addAll(allNodes.getShuttingDownNodes())
                .build();

        ImmutableSet<String> aliveNodeIds = aliveNodes.stream()
                .map(Node::getNodeIdentifier)
                .collect(toImmutableSet());

        // Remove nodes that don't exist anymore
        // Make a copy to materialize the set difference
        Set<String> deadNodes = difference(nodeStates.keySet(), aliveNodeIds).immutableCopy();
        nodeStates.keySet().removeAll(deadNodes);

        // Add new nodes
        for (Node node : aliveNodes) {
            nodeStates.putIfAbsent(node.getNodeIdentifier(),
                    new RemoteNodeState(httpClient, uriBuilderFrom(node.getHttpUri()).appendPath("/v1/info/state").build()));
        }

        // Schedule refresh
        nodeStates.values().forEach(RemoteNodeState::asyncRefresh);

        // update indexes
        refreshNodesInternal();
    }

    @PreDestroy
    public void stop()
    {
        nodeStateUpdateExecutor.shutdownNow();
    }

    @Override
    public void refreshNodes()
    {
        refreshNodesInternal();
    }

    private synchronized void refreshNodesInternal()
    {
        // This is currently a blacklist.
        // TODO: make it a whitelist (a failure-detecting service selector) and maybe build in support for injecting this in airlift
        Set<ServiceDescriptor> services = serviceSelector.selectAllServices().stream()
                .filter(service -> !failureDetector.getFailed().contains(service))
                .collect(toImmutableSet());

        ImmutableSet.Builder<Node> activeNodesBuilder = ImmutableSet.builder();
        ImmutableSet.Builder<Node> inactiveNodesBuilder = ImmutableSet.builder();
        ImmutableSet.Builder<Node> shuttingDownNodesBuilder = ImmutableSet.builder();
        ImmutableSet.Builder<Node> coordinatorsBuilder = ImmutableSet.builder();
        ImmutableSetMultimap.Builder<ConnectorId, Node> byConnectorIdBuilder = ImmutableSetMultimap.builder();

        for (ServiceDescriptor service : services) {
            URI uri = getHttpUri(service, httpsRequired);
            NodeVersion nodeVersion = getNodeVersion(service);
            boolean coordinator = isCoordinator(service);
            if (uri != null && nodeVersion != null) {
                PrestoNode node = new PrestoNode(service.getNodeId(), uri, nodeVersion, coordinator);
                NodeState nodeState = getNodeState(node);

                switch (nodeState) {
                    case ACTIVE:
                        activeNodesBuilder.add(node);
                        if (coordinator) {
                            coordinatorsBuilder.add(node);
                        }

                        // record available active nodes organized by connector id
                        String connectorIds = service.getProperties().get("connectorIds");
                        if (connectorIds != null) {
                            connectorIds = connectorIds.toLowerCase(ENGLISH);
                            for (String connectorId : CONNECTOR_ID_SPLITTER.split(connectorIds)) {
                                byConnectorIdBuilder.put(new ConnectorId(connectorId), node);
                            }
                        }

                        // always add system connector
                        byConnectorIdBuilder.put(new ConnectorId(GlobalSystemConnector.NAME), node);
                        break;
                    case INACTIVE:
                        inactiveNodesBuilder.add(node);
                        break;
                    case SHUTTING_DOWN:
                        shuttingDownNodesBuilder.add(node);
                        break;
                    default:
                        log.error("Unknown state %s for node %s", nodeState, node);
                }
            }
        }

        if (allNodes != null) {
            // log node that are no longer active (but not shutting down)
            SetView<Node> missingNodes = difference(allNodes.getActiveNodes(), Sets.union(activeNodesBuilder.build(), shuttingDownNodesBuilder.build()));
            for (Node missingNode : missingNodes) {
                log.info("Previously active node is missing: %s (last seen at %s)", missingNode.getNodeIdentifier(), missingNode.getHostAndPort());
            }
        }

        // nodes by connector id changes anytime a node adds or removes a connector (note: this is not part of the listener system)
        activeNodesByConnectorId = byConnectorIdBuilder.build();

        AllNodes allNodes = new AllNodes(activeNodesBuilder.build(), inactiveNodesBuilder.build(), shuttingDownNodesBuilder.build(), coordinatorsBuilder.build());
        // only update if all nodes actually changed (note: this does not include the connectors registered with the nodes)
        if (!allNodes.equals(this.allNodes)) {
            // assign allNodes to a local variable for use in the callback below
            this.allNodes = allNodes;
            coordinators = coordinatorsBuilder.build();

            // notify listeners
            List<Consumer<AllNodes>> listeners = ImmutableList.copyOf(this.listeners);
            nodeStateEventExecutor.submit(() -> listeners.forEach(listener -> listener.accept(allNodes)));
        }
    }

    private NodeState getNodeState(PrestoNode node)
    {
        if (expectedNodeVersion.equals(node.getNodeVersion())) {
            if (isNodeShuttingDown(node.getNodeIdentifier())) {
                return SHUTTING_DOWN;
            }
            else {
                return ACTIVE;
            }
        }
        else {
            return INACTIVE;
        }
    }

    private boolean isNodeShuttingDown(String nodeId)
    {
        Optional<NodeState> remoteNodeState = nodeStates.containsKey(nodeId)
                ? nodeStates.get(nodeId).getNodeState()
                : Optional.empty();
        return remoteNodeState.isPresent() && remoteNodeState.get() == SHUTTING_DOWN;
    }

    @Override
    public synchronized AllNodes getAllNodes()
    {
        return allNodes;
    }

    @Managed
    public int getActiveNodeCount()
    {
        return getAllNodes().getActiveNodes().size();
    }

    @Managed
    public int getInactiveNodeCount()
    {
        return getAllNodes().getInactiveNodes().size();
    }

    @Managed
    public int getShuttingDownNodeCount()
    {
        return getAllNodes().getShuttingDownNodes().size();
    }

    @Override
    public Set<Node> getNodes(NodeState state)
    {
        switch (state) {
            case ACTIVE:
                return getAllNodes().getActiveNodes();
            case INACTIVE:
                return getAllNodes().getInactiveNodes();
            case SHUTTING_DOWN:
                return getAllNodes().getShuttingDownNodes();
            default:
                throw new IllegalArgumentException("Unknown node state " + state);
        }
    }

    @Override
    public synchronized Set<Node> getActiveConnectorNodes(ConnectorId connectorId)
    {
        return activeNodesByConnectorId.get(connectorId);
    }

    @Override
    public Node getCurrentNode()
    {
        return currentNode;
    }

    @Override
    public synchronized Set<Node> getCoordinators()
    {
        return coordinators;
    }

    @Override
    public synchronized void addNodeChangeListener(Consumer<AllNodes> listener)
    {
        listeners.add(requireNonNull(listener, "listener is null"));
        AllNodes allNodes = this.allNodes;
        nodeStateEventExecutor.submit(() -> listener.accept(allNodes));
    }

    @Override
    public synchronized void removeNodeChangeListener(Consumer<AllNodes> listener)
    {
        listeners.remove(requireNonNull(listener, "listener is null"));
    }

    private static URI getHttpUri(ServiceDescriptor descriptor, boolean httpsRequired)
    {
        String url = descriptor.getProperties().get(httpsRequired ? "https" : "http");
        if (url != null) {
            try {
                return new URI(url);
            }
            catch (URISyntaxException ignored) {
            }
        }
        return null;
    }

    private static NodeVersion getNodeVersion(ServiceDescriptor descriptor)
    {
        String nodeVersion = descriptor.getProperties().get("node_version");
        return nodeVersion == null ? null : new NodeVersion(nodeVersion);
    }

    private static boolean isCoordinator(ServiceDescriptor service)
    {
        return Boolean.parseBoolean(service.getProperties().get("coordinator"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""wrapper module for Bibliopixel for use with lightshowpi

"""

import atexit
import importlib
import math
import numpy

import bibliopixel.colors as colors
import bibliopixel.image as image

from bibliopixel.led import *
from bibliopixel.drivers.driver_base import *
from lightshow_serial_driver import *
from bibliopixel import log
from PIL import Image, ImageSequence, ImageChops, ImageEnhance

from driver_sacn import DriverSACN

log.setLogLevel(log.WARNING)
# log.setLogLevel(log.DEBUG)

color_map = [list(colors.hue2rgb(c)) for c in range(256)]
scale = colors.color_scale
int_map = [colors.Green for g in range(0, 80)] + \
          [colors.Yellow for y in range(80, 160)] + \
          [colors.Red for r in range(160, 256)]

class Led(object):
    """wrapper module for Bibliopixel for use with lightshowpi"""

    def __init__(self, led_config):
        self.led_config = led_config
        self.driver = None
        self.drops = None
        self.images = None
        self.p_type = None
        self.write_all = None
        self.all_set_on = False
        self.test = False

        self.per_channel = self.led_config.per_channel
        self.pattern_color = self.led_config.pattern_color
        self.pattern_color_map = self.led_config.pattern_color_map

        self.channel_order = getattr(ChannelOrder, self.led_config.channel_order)
        self.last = self.led_config.led_count - 1
        self.rgb = list()
        for x in range(self.led_config.led_count):
            self.rgb.append(color_map[int((float(x) / (self.last + 1)) * 255)])
        self.skip = self.led_config.update_throttle
        self.update_skip = self.skip
        self.max_brightness = self.led_config.max_brightness / 100.0

        if self.led_config.led_configuration == "STRIP":
            self.led_count = self.led_config.led_count * self.led_config.per_channel
        elif self.led_config.led_configuration == "MATRIX":
            self.led_count = self.led_config.matrix_width * self.led_config.matrix_height

        if self.led_config.led_connection == "SPI":
            self.strip_setup()
        elif self.led_config.led_connection == "SERIAL":
            self.serial_setup()
        elif self.led_config.led_connection == "SACN":
            self.sacn_setup()

        if self.led_config.led_configuration == "STRIP":
            self.led = LEDStrip(self.driver)
            self.write_all = self.write_full
        elif self.led_config.led_configuration == "MATRIX":
            self.matrix_setup()
            self.write_all = self.write_matrix

        self.led.setMasterBrightness(int(self.max_brightness * 255))
        atexit.register(self.exit_function)

    def exit_function(self):
        if not self.all_set_on:
            self.all_leds_off()

    def strip_setup(self):
        main_driver = importlib.import_module("bibliopixel.drivers." + self.led_config.strip_type)
        driver = getattr(main_driver, "Driver" + self.led_config.strip_type)
        self.driver = driver(num=self.led_count,
                             c_order=self.channel_order,
                             use_py_spi=True)

    def serial_setup(self):
        strip_type = getattr(LEDTYPE, self.led_config.strip_type)
        self.driver = DriverSerial(type=strip_type,
                                   num=self.led_count,
                                   dev=self.led_config.device_address,
                                   c_order=self.channel_order,
                                   restart_timeout=5,
                                   deviceID=self.led_config.device_id,
                                   hardwareID=self.led_config.hardware_id,
                                   baud_rate=self.led_config.baud_rate)

    def sacn_setup(self):
        self.driver = DriverSACN(num=self.led_count,
                                 host=self.led_config.sacn_address,
                                 port=self.led_config.sacn_port,
                                 universe = self.led_config.universe_start,
                                 universe_boundary=self.led_config.universe_boundary,
                                 broadcast=self.led_config.sacn_broadcast)

    def matrix_setup(self):
        self.images = []
        self.p_type = self.led_config.matrix_pattern_type
        self.led = LEDMatrix(self.driver,
                             width=self.led_config.matrix_width,
                             height=self.led_config.matrix_height,
                             serpentine=True,
                             vert_flip=True,
                             threadedUpdate=False)

        image_path = self.led_config.image_path
        for frame in ImageSequence.Iterator(Image.open(image_path)):
            rgba = Image.new("RGBA", frame.size)
            rgba.paste(frame)
            self.images.append(rgba)

        self.drops = [[0 for _ in range(self.led_config.led_count)] for _ in range(self.led_config.matrix_height)]

    def all_leds_off(self):
        self.led.all_off()
        self.led.update()

    def all_leds_on(self):
        leds = numpy.array([1 for _ in range(self.led_config.led_count)])
        self.update_skip = 0
        self.write_all(leds)

    def write(self, pin, color):
        if self.led_config.led_configuration == "SERIALMATRIX":
            return

        self.led.set(pin, scale(color_map[color], color))

        if pin == self.last or self.test:
            self.led.update()

    def write_full(self, pin_list):
        if self.update_skip != 0:
            self.update_skip -= 1
            if self.update_skip >= 0:
                return

        self.led.all_off()

        brightnesses = pin_list * 255
        brightnesses = brightnesses.astype(int)
        half_channels = self.led_config.per_channel / 2
        midl = int(half_channels)
        pin = 0

        for level, brightness in zip(pin_list, brightnesses):
            sled = pin * self.per_channel

            if self.pattern_color_map == 'MONO':
                rgb = (int(level * self.pattern_color[0]),
                       int(level * self.pattern_color[1]),
                       int(level * self.pattern_color[2]))

            elif self.pattern_color_map == 'FREQ1':
                # rgb = color_map[int((float(pin) / (self.last + 1)) * 255)]
                rgb = self.rgb[pin]
                rgb = (int(rgb[0] * level), int(rgb[1] * level), int(rgb[2] * level))

            elif self.pattern_color_map == 'MAP1':
                rgb = scale(color_map[brightness], brightness)

            elif self.pattern_color_map == 'MAP2':
                rgb = scale(color_map[255 - brightness], brightness)

            else:
                rgb = (brightness, brightness, brightness)

            if self.led_config.pattern_type == 'CBARS':
                mlvl = int(level * midl)
                self.led.fill(rgb, sled + midl - mlvl, sled + midl + mlvl)

            elif self.led_config.pattern_type == 'FULL':
                self.led.fill(rgb, sled, sled + self.led_config.per_channel - 1)

            elif self.led_config.pattern_type == 'LBARS':
                midl = int(half_channels) + sled
                for gled in range(0, int((half_channels) * level)):
                    self.led.set(midl + gled, int_map[int((float(gled) / half_channels) * 255)])
                    self.led.set(midl - gled, int_map[int((float(gled) / half_channels) * 255)])

            pin += 1

        self.led.update()
        self.update_skip = self.skip

    def write_matrix(self, pin_list):
        if self.update_skip != 0:
            self.update_skip -= 1
            if self.update_skip >= 0:
                return

        self.led.all_off()

        if self.p_type == 'SBARS':
            for y in range(self.led_config.matrix_width):
                y_ind = int(((self.last + 1.0) / self.led_config.matrix_width) * y)
                for x_cord in range(int(pin_list[y_ind] * float(self.led_config.matrix_height))):
                    rgb = color_map[int( 255.0 * float(x_cord) / float(self.led_config.matrix_height) )]
                    self.led.set(x_cord, y_ind, rgb)
        if self.p_type == 'MBARS':
            norm_arr = [int(x * 255) for x in pin_list]
            self.drops.append(norm_arr)
            for y_cord in range(self.led_config.matrix_height):
                for x in range(self.led_config.matrix_width):
                    x_ind = int(((self.last + 1.0) / self.led_config.matrix_width) * x)
                    if self.drops[y_cord][x_ind] > 64:
                        rgb = scale(color_map[255 - self.drops[y_cord][x_ind]],
                                    int(self.drops[y_cord][x_ind] * 0.5))
                        self.led.set(x, y_cord, rgb)
            del self.drops[0]
        elif self.p_type == 'IMAGE':
            complete_image = Image.new("RGBA", self.images[0].size)
            for pin in xrange(len(pin_list)):
                if pin_list[pin] > 0.25:
                    complete_image = ImageChops.add_modulo(complete_image, ImageEnhance.Brightness(
                        self.images[pin]).enhance(pin_list[pin]))

            image.showImage(self.led, "",
                            ImageEnhance.Brightness(complete_image).enhance(self.max_brightness * 0.5))

        self.led.update()
        self.update_skip = self.skip


text:
.class final Lo/jH$if;
.super Ljava/lang/Exception;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lo/jH;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x18
    name = "if"
.end annotation

.annotation runtime Lo/jE;
.end annotation

# instance fields
.field private final ˊ:I

# direct methods
.method public constructor <init>(Ljava/lang/String;I)V
    .locals 0

    invoke-direct {p0, p1}, Ljava/lang/Exception;-><init>(Ljava/lang/String;)V

    iput p2, p0, Lo/jH$if;->ˊ:I

    return-void
.end method

# virtual methods
.method public ˊ()I
    .locals 1

    iget v0, p0, Lo/jH$if;->ˊ:I

    return v0
.end method


text:
/**
 * @author pschroen / https://ufo.ai/
 */

import { Group, Quaternion, Vector3 } from 'three';

import { WebAudio } from './WebAudio.js';
import { WebAudioParam } from './WebAudioParam.js';

import { clamp, guid, mapLinear } from '../Utils.js';

export class Sound3D extends Group {
    constructor(camera, id, buffer) {
        super();

        if (typeof id !== 'string') {
            buffer = id;
            id = camera;
            camera = null;
        }

        this.context = WebAudio.context;

        if (camera) {
            this.camera = camera;
            this.cameraWorldPosition = new Vector3();
            this.worldPosition = new Vector3();

            this.audioDistance = 0;
            this.audioNearDistance = camera.near;
            this.audioFarDistance = camera.far;

            this.output = this.context.createGain();
            this.output.connect(WebAudio.input);

            this.gain = new WebAudioParam(this, 'output', 'gain', 0);

            this.screenSpacePosition = new Vector3();

            this.stereo = this.context.createStereoPanner();
            this.stereo.connect(this.output);

            this.stereoPan = new WebAudioParam(this, 'stereo', 'pan', 0);

            this.input = this.output;
        } else {
            this.worldPosition = new Vector3();
            this.worldQuaternion = new Quaternion();
            this.worldScale = new Vector3();
            this.worldOrientation = new Vector3();

            this.panner = this.context.createPanner();
            this.panner.panningModel = 'HRTF';
            this.panner.connect(WebAudio.input);

            this.audioPositionX = new WebAudioParam(this, 'panner', 'positionX', 0);
            this.audioPositionY = new WebAudioParam(this, 'panner', 'positionY', 0);
            this.audioPositionZ = new WebAudioParam(this, 'panner', 'positionZ', 0);
            this.audioOrientationX = new WebAudioParam(this, 'panner', 'orientationX', 0);
            this.audioOrientationY = new WebAudioParam(this, 'panner', 'orientationY', 0);
            this.audioOrientationZ = new WebAudioParam(this, 'panner', 'orientationZ', 1);

            this.output = this.panner;
            this.input = this.output;
        }

        if (buffer) {
            this.sound = WebAudio.add(this, id, buffer, true);
        } else {
            this.sound = WebAudio.clone(this, id, guid(), true);
        }
    }

    updateMatrixWorld(force) {
        super.updateMatrixWorld(force);

        if (isNaN(this.matrixWorld.elements[0])) {
            return;
        }

        if (this.camera) {
            this.cameraWorldPosition.setFromMatrixPosition(this.camera.matrixWorld);
            this.worldPosition.setFromMatrixPosition(this.matrixWorld);

            this.gain.value = clamp(mapLinear(this.cameraWorldPosition.distanceTo(this.worldPosition) + this.audioDistance, this.audioNearDistance, this.audioFarDistance, 1, 0), 0, 1);

            this.screenSpacePosition.copy(this.worldPosition).project(this.camera);

            this.stereoPan.value = clamp(this.screenSpacePosition.x, -1, 1);
        } else {
            this.matrixWorld.decompose(this.worldPosition, this.worldQuaternion, this.worldScale);
            this.worldOrientation.set(0, 0, 1).applyQuaternion(this.worldQuaternion);

            this.audioPositionX.value = this.worldPosition.x;
            this.audioPositionY.value = this.worldPosition.y;
            this.audioPositionZ.value = this.worldPosition.z;
            this.audioOrientationX.value = this.worldOrientation.x;
            this.audioOrientationY.value = this.worldOrientation.y;
            this.audioOrientationZ.value = this.worldOrientation.z;
        }
    }

    destroy() {
        WebAudio.remove(this.sound.id);
    }
}


text: export const borderRadius = `8px`;


text:
using UnityEngine;
using System.Collections;

public class DoneLiftTrigger : MonoBehaviour
{
	public float timeToDoorsClose = 2f;					// Time since the player entered the lift before the doors close.
	public float timeToLiftStart = 3f;					// Time since the player entered the lift before it starts to move.
	public float timeToEndLevel = 6f;					// Time since the player entered the lift before the level ends.
	public float liftSpeed = 3f;						// The speed at which the lift moves.

	private GameObject player;							// Reference to the player.
	private Animator playerAnim;						// Reference to the players animator component.
	private DoneHashIDs hash;							// Reference to the HashIDs script.
	private DoneCameraMovement camMovement;				// Reference to the camera movement script.
	private DoneSceneFadeInOut sceneFadeInOut;			// Reference to the SceneFadeInOut script.
	private DoneLiftDoorsTracking liftDoorsTracking;	// Reference to LiftDoorsTracking script.
	private bool playerInLift;							// Whether the player is in the lift or not.
	private float timer;								// Timer to determine when the lift moves and when the level ends.

	void Awake ()
	{
		// Setting up references.
		player = GameObject.FindGameObjectWithTag(DoneTags.player);
		playerAnim = player.GetComponent<Animator>();
		hash = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneHashIDs>();
		camMovement = Camera.main.gameObject.GetComponent<DoneCameraMovement>();
		sceneFadeInOut = GameObject.FindGameObjectWithTag(DoneTags.fader).GetComponent<DoneSceneFadeInOut>();
		liftDoorsTracking = GetComponent<DoneLiftDoorsTracking>();
	}

	void OnTriggerEnter (Collider other)
	{
		// If the colliding gameobject is the player...
		if(other.gameObject == player)
			// ... the player is in the lift.
			playerInLift = true;
	}

	void OnTriggerExit (Collider other)
	{
		// If the player leaves the trigger area...
		if(other.gameObject == player)
		{
			// ... reset the timer, the player is no longer in the lift and unparent the player from the lift.
			playerInLift = false;
			timer = 0;
		}
	}

	void Update ()
	{
		// If the player is in the lift...
		if(playerInLift)
			// ... activate the lift.
			LiftActivation();

		// If the timer is less than the time before the doors close...
		if(timer < timeToDoorsClose)
			// ... the inner doors should follow the outer doors.
			liftDoorsTracking.DoorFollowing();
		else
			// Otherwise the doors should close.
			liftDoorsTracking.CloseDoors();
	}

	void LiftActivation ()
	{
		// Increment the timer by the amount of time since the last frame.
		timer += Time.deltaTime;

		// If the timer is greater than the amount of time before the lift should start...
		if(timer >= timeToLiftStart)
		{
			// ... stop the player and the camera moving and parent the player to the lift.
			playerAnim.SetFloat(hash.speedFloat,0f);
			camMovement.enabled = false;
			player.transform.parent = transform;

			// Move the lift upwards.
			transform.Translate(Vector3.up * liftSpeed * Time.deltaTime);

			// If the audio clip isn't playing...
			if(!audio.isPlaying)
				// ... play the clip.
				audio.Play();

			// If the timer is greater than the amount of time before the level should end...
			if(timer >= timeToEndLevel)
				// ... call the EndScene function.
				sceneFadeInOut.EndScene();
		}
	}
}


text:
/**
 * use `angular.isFunction` instead of `typeof` comparisons
 *
 * You should use the angular.isFunction method instead of the default JavaScript implementation (typeof function(){} ==="[object Function]").
 *
 * @version 0.1.0
 * @category angularWrapper
 * @sinceAngularVersion 1.x
 */
'use strict';

var utils = require('./utils/utils');

module.exports = {
    meta: {
        schema: []
    },
    create: function(context) {
        function recordError(node, origin) {
            if (node.type === 'Literal' && (node.value === 'function' || node.value === '[object Function]')) {
                context.report(origin, 'You should use the angular.isFunction method', {});
            }
        }

        return {

            BinaryExpression: function(node) {
                if (node.operator === '===' || node.operator === '!==') {
                    if (utils.isTypeOfStatement(node.left) || utils.isToStringStatement(node.left)) {
                        recordError(node.right, node);
                    } else if (utils.isTypeOfStatement(node.right) || utils.isToStringStatement(node.right)) {
                        recordError(node.left, node);
                    }
                }
            }
        };
    }
};


text:
//
//  TwoViewController.m
//  CoolSegmentVC
//
//  Created by ian on 2017/7/19.
//  Copyright © 2017年 RengFou.Inc. All rights reserved.
//

#import "TwoViewController.h"

@interface TwoViewController ()

@end

@implementation TwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0, 0, 60, 60);
    btn.center = self.view.center;
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitle:@"next" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];

    // Do any additional setup after loading the view.
}

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

- (void)Click:(id)sender
{
    if (self.goToAction) {
        self.goToAction();
    }
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
from functools import partial
from itertools import chain

from sqlalchemy.event import listen
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import Comparator, hybrid_property

from indico.core.db import db
from indico.core.db.sqlalchemy import PyIntEnum
from indico.util.decorators import strict_classproperty
from indico.util.enum import RichIntEnum
from indico.util.i18n import _

class LinkType(RichIntEnum):
    __titles__ = (None, _('Category'), _('Event'), _('Contribution'), _('Subcontribution'), _('Session'),
                  _('Session block'))

    category = 1
    event = 2
    contribution = 3
    subcontribution = 4
    session = 5
    session_block = 6

_all_columns = {'category_id', 'linked_event_id', 'contribution_id', 'subcontribution_id', 'session_id',
                'session_block_id'}
_columns_for_types = {
    LinkType.category: {'category_id'},
    LinkType.event: {'linked_event_id'},
    LinkType.contribution: {'contribution_id'},
    LinkType.subcontribution: {'subcontribution_id'},
    LinkType.session: {'session_id'},
    LinkType.session_block: {'session_block_id'},
}

def _make_checks(allowed_link_types):
    available_columns = set(chain.from_iterable(cols for type_, cols in _columns_for_types.items()
                                                if type_ in allowed_link_types))
    yield db.CheckConstraint(f'(event_id IS NULL) = (link_type = {LinkType.category})', 'valid_event_id')
    for link_type in allowed_link_types:
        required_cols = available_columns & _columns_for_types[link_type]
        forbidden_cols = available_columns - required_cols
        criteria = [f'{col} IS NULL' for col in sorted(forbidden_cols)]
        criteria += [f'{col} IS NOT NULL' for col in sorted(required_cols)]
        condition = 'link_type != {} OR ({})'.format(link_type, ' AND '.join(criteria))
        yield db.CheckConstraint(condition, f'valid_{link_type.name}_link')

def _make_uniques(allowed_link_types, extra_criteria=None):
    for link_type in allowed_link_types:
        where = [f'link_type = {link_type.value}']
        if extra_criteria is not None:
            where += list(extra_criteria)
        yield db.Index(None, *_columns_for_types[link_type], unique=True,
                       postgresql_where=db.text(' AND '.join(where)))

class LinkMixin:
    #: The link types that are supported.  Can be overridden in the
    #: model using the mixin.  Affects the table structure, so any
    #: changes to it should go along with a migration step!
    allowed_link_types = frozenset(LinkType)
    #: If only one link per object should be allowed.  This may also
    #: be a string containing an SQL string to specify the criterion
    #: for the unique index to be applied, e.g. ``'is_foo = true'``.
    unique_links = False
    #: The name of the backref that's added to the Event model to
    #: access *all* linked objects
    events_backref_name = None
    #: The name of the backref that's added to the linked objects
    link_backref_name = None
    #: The laziness of the backref that's added to the linked objects
    link_backref_lazy = True

    @strict_classproperty
    @classmethod
    def __auto_table_args(cls):
        args = tuple(_make_checks(cls.allowed_link_types))
        if cls.unique_links:
            extra_criteria = [cls.unique_links] if isinstance(cls.unique_links, str) else None
            args = args + tuple(_make_uniques(cls.allowed_link_types, extra_criteria))
        return args

    @classmethod
    def register_link_events(cls):
        """Register sqlalchemy events needed by this mixin.

        Call this method after the definition of a model which uses
        this mixin class.
        """
        event_mapping = {cls.session: lambda x: x.event,
                         cls.session_block: lambda x: x.event,
                         cls.contribution: lambda x: x.event,
                         cls.subcontribution: lambda x: x.contribution.event,
                         cls.linked_event: lambda x: x}

        type_mapping = {cls.category: LinkType.category,
                        cls.linked_event: LinkType.event,
                        cls.session: LinkType.session,
                        cls.session_block: LinkType.session_block,
                        cls.contribution: LinkType.contribution,
                        cls.subcontribution: LinkType.subcontribution}

        def _set_link_type(link_type, target, value, *unused):
            if value is not None:
                target.link_type = link_type

        def _set_event_obj(fn, target, value, *unused):
            if value is not None:
                event = fn(value)
                assert event is not None
                target.event = event

        for rel, fn in event_mapping.items():
            if rel is not None:
                listen(rel, 'set', partial(_set_event_obj, fn))

        for rel, link_type in type_mapping.items():
            if rel is not None:
                listen(rel, 'set', partial(_set_link_type, link_type))

    @declared_attr
    def link_type(cls):
        return db.Column(
            PyIntEnum(LinkType, exclude_values=set(LinkType) - cls.allowed_link_types),
            nullable=False
        )

    @declared_attr
    def category_id(cls):
        if LinkType.category in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('categories.categories.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def event_id(cls):
        return db.Column(
            db.Integer,
            db.ForeignKey('events.events.id'),
            nullable=True,
            index=True
        )

    @declared_attr
    def linked_event_id(cls):
        if LinkType.event in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('events.events.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def session_id(cls):
        if LinkType.session in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('events.sessions.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def session_block_id(cls):
        if LinkType.session_block in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('events.session_blocks.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def contribution_id(cls):
        if LinkType.contribution in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('events.contributions.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def subcontribution_id(cls):
        if LinkType.subcontribution in cls.allowed_link_types:
            return db.Column(
                db.Integer,
                db.ForeignKey('events.subcontributions.id'),
                nullable=True,
                index=True
            )

    @declared_attr
    def category(cls):
        if LinkType.category in cls.allowed_link_types:
            return db.relationship(
                'Category',
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @declared_attr
    def event(cls):
        return db.relationship(
            'Event',
            foreign_keys=cls.event_id,
            lazy=True,
            backref=db.backref(
                cls.events_backref_name,
                lazy='dynamic'
            )
        )

    @declared_attr
    def linked_event(cls):
        if LinkType.event in cls.allowed_link_types:
            return db.relationship(
                'Event',
                foreign_keys=cls.linked_event_id,
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @declared_attr
    def session(cls):
        if LinkType.session in cls.allowed_link_types:
            return db.relationship(
                'Session',
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @declared_attr
    def session_block(cls):
        if LinkType.session_block in cls.allowed_link_types:
            return db.relationship(
                'SessionBlock',
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @declared_attr
    def contribution(cls):
        if LinkType.contribution in cls.allowed_link_types:
            return db.relationship(
                'Contribution',
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @declared_attr
    def subcontribution(cls):
        if LinkType.subcontribution in cls.allowed_link_types:
            return db.relationship(
                'SubContribution',
                lazy=True,
                backref=db.backref(
                    cls.link_backref_name,
                    cascade='all, delete-orphan',
                    uselist=(cls.unique_links != True),  # noqa
                    lazy=cls.link_backref_lazy
                )
            )

    @hybrid_property
    def object(self):
        if self.link_type == LinkType.category:
            return self.category
        elif self.link_type == LinkType.event:
            return self.event
        elif self.link_type == LinkType.session:
            return self.session
        elif self.link_type == LinkType.session_block:
            return self.session_block
        elif self.link_type == LinkType.contribution:
            return self.contribution
        elif self.link_type == LinkType.subcontribution:
            return self.subcontribution

    @object.setter
    def object(self, obj):
        self.category = None
        self.linked_event = self.event = self.session = self.session_block = None
        self.contribution = self.subcontribution = None
        if isinstance(obj, db.m.Category):
            self.category = obj
        elif isinstance(obj, db.m.Event):
            self.linked_event = obj
        elif isinstance(obj, db.m.Session):
            self.session = obj
        elif isinstance(obj, db.m.SessionBlock):
            self.session_block = obj
        elif isinstance(obj, db.m.Contribution):
            self.contribution = obj
        elif isinstance(obj, db.m.SubContribution):
            self.subcontribution = obj
        else:
            raise TypeError(f'Unexpected object: {obj}')

    @object.comparator
    def object(cls):
        return LinkedObjectComparator(cls)

    @property
    def link_repr(self):
        """A kwargs-style string suitable for the object's repr."""
        info = [('link_type', self.link_type.name if self.link_type is not None else 'None')]
        info.extend((key, getattr(self, key)) for key in _all_columns if getattr(self, key) is not None)
        return ', '.join(f'{key}={value}' for key, value in info)

    @property
    def link_event_log_data(self):
        """
        Return a dict containing information about the linked object
        suitable for the event log.

        It does not return any information for an object linked to a
        category or the event itself.
        """
        data = {}
        if self.link_type == LinkType.session:
            data['Session'] = self.session.title
        if self.link_type == LinkType.session_block:
            data['Session Block'] = self.session_block.title
        elif self.link_type == LinkType.contribution:
            data['Contribution'] = self.contribution.title
        elif self.link_type == LinkType.subcontribution:
            data['Contribution'] = self.subcontribution.contribution.title
            data['Subcontribution'] = self.subcontribution.title
        return data

class LinkedObjectComparator(Comparator):
    def __init__(self, cls):
        self.cls = cls

    def __clause_element__(self):
        # just in case
        raise NotImplementedError

    def __eq__(self, other):
        if isinstance(other, db.m.Category):
            return db.and_(self.cls.link_type == LinkType.category,
                           self.cls.category_id == other.id)
        elif isinstance(other, db.m.Event):
            return db.and_(self.cls.link_type == LinkType.event,
                           self.cls.linked_event_id == other.id)
        elif isinstance(other, db.m.Session):
            return db.and_(self.cls.link_type == LinkType.session,
                           self.cls.session_id == other.id)
        elif isinstance(other, db.m.SessionBlock):
            return db.and_(self.cls.link_type == LinkType.session_block,
                           self.cls.session_block_id == other.id)
        elif isinstance(other, db.m.Contribution):
            return db.and_(self.cls.link_type == LinkType.contribution,
                           self.cls.contribution_id == other.id)
        elif isinstance(other, db.m.SubContribution):
            return db.and_(self.cls.link_type == LinkType.subcontribution,
                           self.cls.subcontribution_id == other.id)
        else:
            raise ValueError(f'Unexpected object type {type(other)}: {other}')


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth_model extends CI_Model {

	public $table = 'user';

	public function insert_registration($data) {
		$query = $this->db->insert($this->table, $data);
		return $query;
	}

	public function login_validation($data) {
		$limit = 1;
		$query = $this->db->get_where($this->table, $data);
		return ($query->num_rows() == 1) ? true : false;
	}

	public function read_user_information($email) {
		$query = $this->db->get_where($this->table, array('email'=>$email), 1);
		if($query->num_rows() == 1) {
			return $query;
		}
		return false;
	}

	public function insert_token($email) {
		$token = substr(sha1(rand()), 0, 30);
		$date = date('Y-m-d');

		$string = array(
			'token'					=> $token,
			'user_email'		=> $email,
			'date_created'	=> $date
		);

		$this->db->insert('tokens', $string);
		return $tokens . $email;
	}

	public function is_token_valid($token) {
		$tkn = substr($token, 0, 30);
		$uemail = substr($token, 30);

		$q = $this->db->get_where('tokens', array(
			'tokens.token'			=> $tkn,
			'tokens.user_email'	=> $uemail,
		), 1);

		if($this->db->affected_rows() > 0) {
			$row = $q->row();

			$created = $row->date_created;
			$today = date('Y-m-d');
			if(strtotime($created) != strtotime($today)){
				return false;
			}

			$user_info = $this->read_user_information($row->email);
			return $user_info;
		}
		return false;
	}

	public function update_password($email, $pass, $forgot = false ) {
		$query1 = $this->db->where('email', $email);
		$query1->update($this->table, array('password' => $pass));
		if($query1->affected_rows() > 0){
			if($forgot){
				$query2->where('email', $email);
				$query2->update('token', array('is_expired'=>true));
			}
			return true;
		}
		return false;
	}

	public function update_username($email, $new_username) {
		$this->db->where('email', $email);
		$this->db->update($this->table, array('username'=>$new_username));
		return $this->db->affected_rows();
	}

	public function get_old_password($email) {
		$this->db->select('password');
		$this->db->where('email', $email);
		return $this->db->get($this->table)->result_array()[0]['password'];
	}

	public function get_hash($email) {
		$this->db->select('hash');
		$this->db->where('email', $email);
		$result = $this->db->get($this->table)->result_array();
		return $result[0];
	}

	public function verify_user($email) {
		$data = array('is_verified' => 1);
		$this->db->where('email', $email);
		$this->db->update('user', $data);
		return ($this->db->affected_rows() > 0);
  }

  public function get_jalur($username) {
  	$this->db->select('jalur');
  	$this->db->where('username', $username);
  	$result = $this->db->get($this->table)->result_array();
  	return $result[0]['jalur'];
  }

  public function is_email_exist($email) {
  	$this->db->where('email', $email);
  	$this->db->get($this->table);
  	if($this->db->affected_rows() == 1){
  		return true;
  	} else {
  		return false;
  	}
  }

  public function delete_user($email) {
  	$this->db->where('email', $email);
  	$this->db->delete($this->table);
  	if($this->db->affected_rows() == 1){
  		return true;
  	} else {
  		return false;
  	}
  }

  public function is_admin($email) {
  	$this->db->where('email', $email);
  	$this->db->where('role', 3);
  	$this->db->get($this->table);
  	if($this->db->affected_rows() == 1) {
  		return true;
  	} else {
  		return false;
  	}
  }

}

?>


text:
<?php

/* AoceuVerbBundle:Tense:index.html.twig */
class __TwigTemplate_1e661b7feb9169481455b5c261aea006 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("AoceuSiteBundle::layout.html.twig");

        $this->blocks = array(
            'bodyContent' => array($this, 'block_bodyContent'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "AoceuSiteBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_bodyContent($context, array $blocks = array())
    {
        // line 4
        echo "
Tense list

            Id
            Tense
            Actions

    ";
        // line 15
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getContext($context, "entities"));
        foreach ($context['_seq'] as $context["_key"] => $context["entity"]) {
            // line 16
            echo "

            env, $this->env->getExtension('routing')->getPath("admin_tense_show", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "id"), "html", null, true);
            echo "
            ";
            // line 18
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "tense"), "html", null, true);
            echo "

                        env, $this->env->getExtension('routing')->getPath("admin_tense_show", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">show

                        env, $this->env->getExtension('routing')->getPath("admin_tense_edit", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">edit

    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['entity'], $context['_parent'], $context['loop']);
        $context = array_merge($_parent, array_intersect_key($context, $_parent));
        // line 31
        echo "

        env, $this->env->getExtension('routing')->getPath("admin_tense_new"), "html", null, true);
        echo "\">
            Create a new entry

";
    }

    public function getTemplateName()
    {
        return "AoceuVerbBundle:Tense:index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  87 => 36,  80 => 31,  68 => 25,  62 => 22,  55 => 18,  49 => 17,  46 => 16,  42 => 15,  29 => 4,  26 => 3,);
    }
}


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "C:/Program Files/glslang")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "Release")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/spirv-tools" TYPE FILE FILES
    "D:/Vulkan/1.0.65.1/glslang/External/spirv-tools/include/spirv-tools/libspirv.h"
    "D:/Vulkan/1.0.65.1/glslang/External/spirv-tools/include/spirv-tools/libspirv.hpp"
    "D:/Vulkan/1.0.65.1/glslang/External/spirv-tools/include/spirv-tools/optimizer.hpp"
    "D:/Vulkan/1.0.65.1/glslang/External/spirv-tools/include/spirv-tools/linker.hpp"
    )
endif()

if(NOT CMAKE_INSTALL_LOCAL_ONLY)
  # Include the install script for each subdirectory.
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/spirv-tools/external/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/spirv-tools/source/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/spirv-tools/tools/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/spirv-tools/test/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/spirv-tools/examples/cmake_install.cmake")

endif()


text:
<?php

namespace jeus\QuickstrikeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * CartePartie
 *
 * @ORM\Table(name="quickstrike_cartepartie")
 * @ORM\Entity(repositoryClass="jeus\QuickstrikeBundle\Repository\CartePartieRepository")
 */
class CartePartie
{
    private $em;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="position", type="smallint", nullable=true)
     */
    private $position;

    /**
     * @var integer
     *
     * @ORM\Column(name="numeroJoueur", type="smallint")
     */
    private $numeroJoueur;

    /**
     * @var string
     *
     * @ORM\Column(name="emplacement", type="string", length=50)
     */
    protected $emplacement;

    /**
     * @ORM\ManyToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Partie", inversedBy="CarteParties", cascade={"persist","remove"})
     */
    protected $Partie;

    /**
     * @ORM\ManyToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte")
     */
    protected $Carte;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set position
     *
     * @param integer $position
     * @return CartePartie
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set numeroJoueur
     *
     * @param integer $numeroJoueur
     * @return CartePartie
     */
    public function setNumeroJoueur($numeroJoueur)
    {
        $this->numeroJoueur = $numeroJoueur;

        return $this;
    }

    /**
     * Get numeroJoueur
     *
     * @return integer
     */
    public function getNumeroJoueur()
    {
        return $this->numeroJoueur;
    }

    /**
     * Set emplacement
     *
     * @param string $emplacement
     * @return Partie
     */
    public function setEmplacement($emplacement)
    {
        $this->emplacement = $emplacement;

        return $this;
    }

    /**
     * Get emplacement
     *
     * @return string
     */
    public function getEmplacement()
    {
        return $this->emplacement;
    }

    /**
     * Set Partie
     *
     * @param \jeus\QuickstrikeBundle\Entity\Partie $Partie
     * @return Deck
     */
    public function setPartie(\jeus\QuickstrikeBundle\Entity\Partie $Partie)
    {
        $this->Partie = $Partie;

        return $this;
    }

    /**
     * Get Partie
     *
     * @return \jeus\QuickstrikeBundle\Entity\Partie
     */
    public function getPartie()
    {
        return $this->Partie;
    }

    /**
     * Set Carte
     *
     * @param \jeus\QuickstrikeBundle\Entity\Carte $Carte
     * @return CartePartie
     */
    public function setCarte(\jeus\QuickstrikeBundle\Entity\Carte $Carte)
    {
        $this->Carte = $Carte;

        return $this;
    }

    /**
     * Get Carte
     *
     * @return \jeus\QuickstrikeBundle\Entity\Carte
     */
    public function getCarte()
    {
        return $this->Carte;
    }

    public function getLien($parametres = null)
    {
        $chamberVisible = (isset($parametres['chamberVisible'.$this->numeroJoueur])) ? $parametres['chamberVisible'.$this->numeroJoueur] : false;
        $lien = '';
        if (
            (($this->emplacement == 'DECK') && ($parametres['deckVisible'.$this->numeroJoueur] == false))
            || ($this->emplacement == 'ENERGIE_VERTE')
            || ($this->emplacement == 'ENERGIE_JAUNE')
            || ($this->emplacement == 'ENERGIE_ROUGE')
            ) {
            $lien = 'back.png';
        } elseif ($this->emplacement == 'CHAMBER') {
            if ($chamberVisible==true) {
                $lien = $this->Carte->getImage();
            } else {
                if (strpos($this->Carte->getNumero(), 'v') === false)  {
                    $lien = 'recto-' . $this->Carte->getPersonnageChamber() . '.png';
                } else {
                    $lien = 'verso-' . $this->Carte->getPersonnageChamber() . '.png';
                }
            }
        } else
            $lien = $this->Carte->getImage();

        return $lien;
    }

    public function getLienAgrandi($parametres = null)
    {
        $adverse = (isset($parametres['adverse'])) ? $parametres['adverse'] : false;
        $lien = '';
        if ($this->Carte->getTypeCarte()->getTag() === 'CHAMBER') {
            if ($adverse) {
                $lien = $this->getLien($parametres);
            } else {
                $lien = $this->Carte->getImage();
            }
        } else if (
            (($this->emplacement == 'DECK') && ($parametres['deckVisible'.$this->numeroJoueur] == false))
            || ($this->emplacement == 'ENERGIE_VERTE')
            || ($this->emplacement == 'ENERGIE_JAUNE')
            || ($this->emplacement == 'ENERGIE_ROUGE')
            )  {
            $lien = 'back.png';
        } else{
            $lien = $this->Carte->getImage();
        }

        return $lien;
    }

    public function __construct($Carte,$Partie,$numeroJoueur,$emplacement = 'DECK') {
        $this->Carte = $Carte;
        $this->numeroJoueur = $numeroJoueur;
        $this->Partie = $Partie;
        $this->position = 0;
        if ($Carte->getTypeCarte()->getTag()=='CHAMBER') {
            $this->emplacement = 'CHAMBER';
        } else {
            $this->emplacement = $emplacement;
        }
    }
}


text:
package com.is2t.mwt.widgets.extended.renderers.util;

import com.is2t.mwt.widgets.extended.IExtendedStyle;
import com.is2t.mwt.widgets.renderers.util.ContentLook;

import ej.mwt.rendering.Look;

public class ContentStyleLook extends ContentLook {

	public ContentStyleLook(Look look, IExtendedStyle style, boolean isEnabled) {
		super(look, isEnabled);
		// FIXME apply enabled and pressed filters on chosen colors
		int styleBackgroundColor = style.getBackgroundColor();
		if (styleBackgroundColor != IExtendedStyle.DEFAULT_COLOR) {
			backgroundColor = styleBackgroundColor;
		}
		int styleForegroundColor = style.getForegroundColor();
		if (styleForegroundColor != IExtendedStyle.DEFAULT_COLOR) {
			foregroundColor = styleForegroundColor;
		}
	}

}


text:
package com.google.cloud.dlp.v2beta1;

import com.google.api.core.BetaApi;
import com.google.longrunning.Operation;
import com.google.privacy.dlp.v2beta1.AnalyzeDataSourceRiskRequest;
import com.google.privacy.dlp.v2beta1.CreateInspectOperationRequest;
import com.google.privacy.dlp.v2beta1.DeidentifyContentRequest;
import com.google.privacy.dlp.v2beta1.DeidentifyContentResponse;
import com.google.privacy.dlp.v2beta1.DlpServiceGrpc.DlpServiceImplBase;
import com.google.privacy.dlp.v2beta1.InspectContentRequest;
import com.google.privacy.dlp.v2beta1.InspectContentResponse;
import com.google.privacy.dlp.v2beta1.ListInfoTypesRequest;
import com.google.privacy.dlp.v2beta1.ListInfoTypesResponse;
import com.google.privacy.dlp.v2beta1.ListInspectFindingsRequest;
import com.google.privacy.dlp.v2beta1.ListInspectFindingsResponse;
import com.google.privacy.dlp.v2beta1.ListRootCategoriesRequest;
import com.google.privacy.dlp.v2beta1.ListRootCategoriesResponse;
import com.google.privacy.dlp.v2beta1.RedactContentRequest;
import com.google.privacy.dlp.v2beta1.RedactContentResponse;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockDlpServiceImpl extends DlpServiceImplBase {
  private ArrayList<GeneratedMessageV3> requests;
  private Queue<Object> responses;

  public MockDlpServiceImpl() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  public List<GeneratedMessageV3> getRequests() {
    return requests;
  }

  public void addResponse(GeneratedMessageV3 response) {
    responses.add(response);
  }

  public void setResponses(List<GeneratedMessageV3> responses) {
    this.responses = new LinkedList<Object>(responses);
  }

  public void addException(Exception exception) {
    responses.add(exception);
  }

  public void reset() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  @Override
  public void inspectContent(
      InspectContentRequest request, StreamObserver<InspectContentResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof InspectContentResponse) {
      requests.add(request);
      responseObserver.onNext((InspectContentResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void redactContent(
      RedactContentRequest request, StreamObserver<RedactContentResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof RedactContentResponse) {
      requests.add(request);
      responseObserver.onNext((RedactContentResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void deidentifyContent(
      DeidentifyContentRequest request,
      StreamObserver<DeidentifyContentResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof DeidentifyContentResponse) {
      requests.add(request);
      responseObserver.onNext((DeidentifyContentResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void createInspectOperation(
      CreateInspectOperationRequest request, StreamObserver<Operation> responseObserver) {
    Object response = responses.remove();
    if (response instanceof Operation) {
      requests.add(request);
      responseObserver.onNext((Operation) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void analyzeDataSourceRisk(
      AnalyzeDataSourceRiskRequest request, StreamObserver<Operation> responseObserver) {
    Object response = responses.remove();
    if (response instanceof Operation) {
      requests.add(request);
      responseObserver.onNext((Operation) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void listInspectFindings(
      ListInspectFindingsRequest request,
      StreamObserver<ListInspectFindingsResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof ListInspectFindingsResponse) {
      requests.add(request);
      responseObserver.onNext((ListInspectFindingsResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void listInfoTypes(
      ListInfoTypesRequest request, StreamObserver<ListInfoTypesResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof ListInfoTypesResponse) {
      requests.add(request);
      responseObserver.onNext((ListInfoTypesResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }

  @Override
  public void listRootCategories(
      ListRootCategoriesRequest request,
      StreamObserver<ListRootCategoriesResponse> responseObserver) {
    Object response = responses.remove();
    if (response instanceof ListRootCategoriesResponse) {
      requests.add(request);
      responseObserver.onNext((ListRootCategoriesResponse) response);
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError((Exception) response);
    } else {
      responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
    }
  }
}


text:
package org.nutz.mvc.init.errmodule;

import org.nutz.mvc.annotation.Modules;

@Modules(value = {SimpleErrorModule.class})
public class ErrorCatchMainModule {}


text:
using System;
using FluorineFx.Messaging.Api.Messaging;

namespace FluorineFx.Messaging.Rtmp.Stream
{
    /// <summary>
    /// Interface for providers that know if they contain video frames.
    /// </summary>
    [CLSCompliant(false)]
    public interface IStreamTypeAwareProvider : IProvider
    {
        /// <summary>
        /// Checks if the provider contains video tags.
        /// </summary>
        bool HasVideo();
    }
}