text:
package ua.com.fielden.platform.domaintree.centre.analyses.impl;

import java.util.Set;

import ua.com.fielden.platform.domaintree.centre.analyses.ISentinelDomainTreeRepresentation;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.reflection.AnnotationReflector;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.Pair;

/**
 * A domain tree representation for sentinel analyses.
 *
 * @author TG Team
 *
 */
public class SentinelDomainTreeRepresentation extends AnalysisDomainTreeRepresentation implements ISentinelDomainTreeRepresentation {
    public static final String COUNT_OF_SELF_DASHBOARD = "countOfSelfDashboard";
    public static final String RED = "RED";
    public static final String YELLOW = "YELLOW";
    public static final String GREEN = "GREEN";

    /**
     * A representation constructor for the first time instantiation.
     *
     * @param entityFactory
     * @param rootTypes
     */
    public SentinelDomainTreeRepresentation(final EntityFactory entityFactory, final Set<Class<?>> rootTypes) {
        this(entityFactory, rootTypes, createSet(), new SentinelAddToDistributionTickRepresentation(), new SentinelAddToAggregationTickRepresentation());
    }

    /**
     * A representation constructor. Initialises also children references on itself.
     */
    protected SentinelDomainTreeRepresentation(final EntityFactory entityFactory, final Set<Class<?>> rootTypes, final Set<Pair<Class<?>, String>> excludedProperties, final SentinelAddToDistributionTickRepresentation firstTick, final SentinelAddToAggregationTickRepresentation secondTick) {
        super(entityFactory, rootTypes, excludedProperties, firstTick, secondTick);
    }

    @Override
    public ISentinelAddToDistributionTickRepresentation getFirstTick() {
        return (ISentinelAddToDistributionTickRepresentation) super.getFirstTick();
    }

    @Override
    public ISentinelAddToAggregationTickRepresentation getSecondTick() {
        return (ISentinelAddToAggregationTickRepresentation) super.getSecondTick();
    }

    /**
     * Makes CountOfSelfDashboard property disabled for both ticks.
     */
    public void provideMetaStateForCountOfSelfDashboardProperty() {
        for (final Class<?> rootType : rootTypes()) {
            if (!isExcludedImmutably(rootType, SentinelDomainTreeRepresentation.COUNT_OF_SELF_DASHBOARD)) {
                getFirstTick().disableImmutably(rootType, SentinelDomainTreeRepresentation.COUNT_OF_SELF_DASHBOARD);
                getSecondTick().disableImmutably(rootType, SentinelDomainTreeRepresentation.COUNT_OF_SELF_DASHBOARD);
            }
        }
    }

    @Override
    public boolean isExcludedImmutably(final Class<?> root, final String property) {
        // inject an enhanced type into method implementation
        final Class<?> managedType = managedType(root);

        final boolean isEntityItself = "".equals(property); // empty property means "entity itself"
        return (super.isExcludedImmutably(managedType, property)) || // base TG analysis domain representation usage
                !(isSentinel(managedType, property) || isEntityItself || COUNT_OF_SELF_DASHBOARD.equals(property)); // exclude all properties except "sentinels" and special "countOfSelf" property
    }

    /**
     * Indicates whether the property represents so called "sentinel", which is by a contract a case-insensitive implementation of "case/when" string calculated property with
     * return values "GREEN" or "RED".
     *
     * @param managedType
     * @param property
     * @return
     */
    private boolean isSentinel(final Class<?> managedType, final String property) {
        final boolean isEntityItself = "".equals(property); // empty property means "entity itself"
        final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, property);
        final Calculated calculatedAnnotation = isEntityItself ? null : AnnotationReflector.getPropertyAnnotation(Calculated.class, managedType, property);
        final String upperCasedAndTrimmedExpr = calculatedAnnotation != null ? calculatedAnnotation.value().trim().toUpperCase() : null;
        return calculatedAnnotation != null && EntityUtils.isString(propertyType) && //
                upperCasedAndTrimmedExpr.startsWith("CASE WHEN ") && upperCasedAndTrimmedExpr.endsWith(" END") && //
                upperCasedAndTrimmedExpr.contains(" \"" + GREEN + "\" ") && upperCasedAndTrimmedExpr.contains(" \"" + RED + "\" ");
    }

    public static class SentinelAddToDistributionTickRepresentation extends AnalysisAddToDistributionTickRepresentation implements ISentinelAddToDistributionTickRepresentation {
        /**
         * Used for serialisation and for normal initialisation. IMPORTANT : To use this tick it should be passed into representation constructor, which should initialise "dtr"
         * field.
         */
        public SentinelAddToDistributionTickRepresentation() {
        }
    }

    public static class SentinelAddToAggregationTickRepresentation extends AnalysisAddToAggregationTickRepresentation implements ISentinelAddToAggregationTickRepresentation {
        /**
         * Used for serialisation and for normal initialisation. IMPORTANT : To use this tick it should be passed into representation constructor, which should initialise "dtr"
         * field.
         */
        public SentinelAddToAggregationTickRepresentation() {
        }
    }

}


text:
class IOSChromeUnitTestSuite : public web::WebTestSuite {
 public:
  IOSChromeUnitTestSuite(int argc, char** argv);

  IOSChromeUnitTestSuite(const IOSChromeUnitTestSuite&) = delete;
  IOSChromeUnitTestSuite& operator=(const IOSChromeUnitTestSuite&) = delete;

  ~IOSChromeUnitTestSuite() override;

  // web::WebTestSuite overrides:
  void Initialize() override;

 private:
  scoped_refptr<base::SingleThreadTaskRunner> action_task_runner_;
};

#endif  // IOS_CHROME_TEST_IOS_CHROME_UNIT_TEST_SUITE_H_

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="@drawable/jc_dialog_progress_bg"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="222dp"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="2dp">

        <ImageView
            android:id="@+id/volume_image_tip"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:scaleType="fitCenter"
            android:src="@drawable/jc_brightness_video" />

        <ProgressBar
            android:id="@+id/brightness_progressbar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="0dp"
            android:layout_height="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:layout_weight="1"
            android:progressDrawable="@drawable/jc_dialog_progress" />

        <TextView
            android:id="@+id/tv_brightness"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="0"
            android:textColor="#ffffffff"
            android:textSize="16sp" />
    </LinearLayout>
</LinearLayout>


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

<title>SlideEvent</title>
<meta name="date" content="2016-05-31">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

model

Class SlideEvent

java.lang.Object

model.Slide

model.SlideEvent

public class SlideEvent
extends Slide

Created by Mikkel on 02/05/2016.

Constructor Summary

Constructors

Constructor and Description

SlideEvent()

SlideEvent(java.lang.String slideType,
          java.lang.String date,
          java.time.LocalDate localDate,
          java.lang.String startTime,
          java.lang.String header,
          java.lang.String text,
          java.lang.String imagePath)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getDate()

java.lang.String
getHeader()

java.lang.String
getImagePath()

java.time.LocalDate
getLocalDate()

java.lang.String
getStartTime()

java.lang.String
getText()

void
setDate(java.lang.String date)

void
setHeader(java.lang.String header)

void
setImagePath(java.lang.String imagePath)

void
setLocalDate(java.time.LocalDate localDate)

void
setStartTime(java.lang.String startTime)

void
setText(java.lang.String text)

Methods inherited from class model.Slide

getSlideType, setSlideType

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SlideEvent

public SlideEvent()

SlideEvent

public SlideEvent(java.lang.String slideType,
                  java.lang.String date,
                  java.time.LocalDate localDate,
                  java.lang.String startTime,
                  java.lang.String header,
                  java.lang.String text,
                  java.lang.String imagePath)

Method Detail

getDate

public java.lang.String getDate()

setDate

public void setDate(java.lang.String date)

getLocalDate

public java.time.LocalDate getLocalDate()

setLocalDate

public void setLocalDate(java.time.LocalDate localDate)

getStartTime

public java.lang.String getStartTime()

setStartTime

public void setStartTime(java.lang.String startTime)

getHeader

public java.lang.String getHeader()

setHeader

public void setHeader(java.lang.String header)

getText

public java.lang.String getText()

setText

public void setText(java.lang.String text)

getImagePath

public java.lang.String getImagePath()

Overrides:

getImagePath in class Slide

setImagePath

public void setImagePath(java.lang.String imagePath)

Overrides:

setImagePath in class Slide

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
.. _community:

=========
Community
=========

Schematics was created in Brooklyn, NY by `James Dennis <http://j2labs.io>`_.
Since then, the code has been worked on by folks from around the world.  If you
have ideas, we encourage you to share them!

Special thanks to `Hacker School <http://hackerschool.com>`_, `Plain Vanilla
<http://www.plainvanilla.is/>`_, `Quantopian <http://quantopian.com>`_, `Apple
<http://apple.com>`_, `Johns Hopkins University <http://jhu.edu>`_, and
everyone who has contributed to Schematics.

Bugs & Features
===============

We track bugs, feature requests, and documentation requests with `Github Issues
<https://github.com/schematics/schematics/issues>`_.

Mailing list
============

We discuss the future of Schematics and upcoming changes in detail on
`schematics-dev <http://groups.google.com/group/schematics-dev>`_.

If you've read the documentation and still haven't found the answer you're
looking for, you should reach out to us here too.

Contributing
============

If you're interested in contributing code or documentation to Schematics,
please visit the :doc:`development` for instructions.


text:
package com.beligum.core.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.security.spec.KeySpec;
import java.text.Normalizer;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.codec.binary.Hex;
import org.codehaus.jackson.JsonNode;
import org.w3c.dom.Document;

import play.libs.Json;
import play.libs.WS;
import play.libs.WS.WSRequestHolder;

public class Toolkit
{
    // -----CONSTANTS-----
    private static final String VALID_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";

    // -----VARIABLES-----

    // -----CONSTRUCTORS-----
    public Toolkit()
    {
    }

    // -----PUBLIC FUNCTIONS-----
    public static String readWebpage(String url, boolean addNewlines) throws Exception
    {
	BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
	String line = reader.readLine();
	String retVal = line;
	while (line != null) {
	    line = reader.readLine();
	    if (line != null) {
		if (addNewlines) {
		    retVal += Toolkit.getNewline() + line;
		} else {
		    retVal += line;
		}
	    }
	}

	reader.close();

	return retVal;
    }
    public static String getNewline()
    {
	return System.getProperty("line.separator");
    }

    public static String urlize(String input)
    {
	String t = normalizeString(input).trim().toLowerCase().replaceAll(" ", "-").replaceAll("[^a-z0-9]", "-").replaceAll("-+", "-")
					 .replaceAll("-$", "");
	if (t.length() > 59)
	    return t.substring(0, 58);
	else
	    return t;
    }

    public static String normalizeString(String input)
    {
	return Normalizer.normalize(input, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
    }

    public static String xmlToString(Document document, boolean indent) throws Exception
    {
	if (document == null) {
	    return null;
	} else {
	    try {
		StringWriter sw = new StringWriter();
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

		transformer.transform(new DOMSource(document), new StreamResult(sw));
		return sw.toString();
	    } catch (Exception e) {
		throw new Exception("Error converting XML to String", e);
	    }
	}
    }
    /*
     * Watch out: this is the same code as in cindi.Toolkit.js, so make sure you
     * change both if you change anything
     */
    public static String searchMetadataWithContextName(JsonNode metadataObject, String contextKey)
    {
	String retVal = null;

	if (metadataObject.get("class").asText().equals("metadata.list") || metadataObject.get("class").asText().equals("metadata.map")) {
	    Iterator<JsonNode> metaNodes = metadataObject.get("value").getElements();
	    while (metaNodes.hasNext()) {
		JsonNode childCollection = metaNodes.next();
		retVal = Toolkit.searchMetadataWithContextName(childCollection, contextKey);
		// break loop if contextName is found
		if (retVal != null)
		    break;
	    }
	} else if (metadataObject.has("context") &&
		   metadataObject.get("context").has("key") && metadataObject.get("context").get("key").asText().equals(contextKey)) {
	    if (!metadataObject.get("class").asText().equals("metadata.null")) {
		retVal = metadataObject.get("value").asText();
	    }
	}

	return retVal;
    }

    private static String cachedAllStatusesJS = null;

    public static String getJsonContentType()
    {
	return play.api.http.ContentTypeOf.contentTypeOf_JsValue(play.api.mvc.Codec.utf_8()).mimeType().get();
    }
    public static String getXmlContentType()
    {
	return play.api.http.ContentTypeOf.contentTypeOf_Xml(play.api.mvc.Codec.utf_8()).mimeType().get();
    }
    public static WSRequestHolder buildBackendUrl(String actionConfigKey)
    {
	return WS.url(Toolkit.buildBackendUrlString(actionConfigKey));
    }
    public static WSRequestHolder buildAcceptJsonBackendUrl(String actionConfigKey)
    {
	return WS.url(Toolkit.buildBackendUrlString(actionConfigKey)).setHeader("Accept", Toolkit.getJsonContentType());
    }
    public static WSRequestHolder buildAcceptXmlBackendUrl(String actionConfigKey)
    {
	return WS.url(Toolkit.buildBackendUrlString(actionConfigKey)).setHeader("Accept", Toolkit.getXmlContentType());
    }
    public static String buildBackendUrlString(String actionConfigKey)
    {
	StringBuilder url = new StringBuilder();
	url.append(play.Play.application().configuration().getString("cindi.fileServer"));

	String actionUrl = play.Play.application().configuration().getString(actionConfigKey);
	if (actionUrl.charAt(0) != '/' && url.charAt(url.length() - 1) != '/') {
	    url.append("/");
	}
	url.append(actionUrl);

	return url.toString();
    }
    public static String createRandomString(Integer length)
    {
	Random random = new Random();
	String name = "";
	for (int i = 0; i < length; i++) {
	    int pos = random.nextInt(VALID_CHARACTERS.length());
	    name += VALID_CHARACTERS.substring(pos, pos + 1);
	}
	return name;
    }
    public static String hash(String password, String salt)
    {
	KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 2048, 160);
	try {
	    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	    byte[] hash = f.generateSecret(spec).getEncoded();
	    return new String(Hex.encodeHex(hash));
	} catch (Exception e) {
	    return null;
	}

    }
    public static Boolean isEmpty(String string)
    {
	if (string == null || string.equals("") || string.trim().equals("")) {
	    return true;
	} else {
	    return false;
	}
    }
    public static String getNiceSize(long fileSize)
    {
	String retVal = "";

	double fileSizeD = fileSize;
	String fileSizeS;
	String fileSizeEx;

	if (fileSize < 1024) {
	    fileSizeS = fileSizeD + "";
	    fileSizeEx = "B";
	} else if (fileSize < (1024 * 1024)) {
	    fileSizeS = fileSizeD / 1024.0 + "";
	    fileSizeEx = "KB";
	} else if (fileSize < (1024 * 1024 * 1024)) {
	    fileSizeS = fileSizeD / (1024.0 * 1024.0) + "";
	    fileSizeEx = "MB";
	} else if (fileSize < Math.pow(1024, 4)) {
	    fileSizeS = fileSizeD / (1024.0 * 1024.0 * 1024.0) + "";
	    fileSizeEx = "GB";
	} else if (fileSize < Math.pow(1024, 5)) {
	    fileSizeS = fileSizeD / (1024.0 * 1024.0 * 1024.0 * 1024.0) + "";
	    fileSizeEx = "TB";
	} else if (fileSize < Math.pow(1024, 6)) {
	    fileSizeS = fileSizeD / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0) + "";
	    fileSizeEx = "PB";
	} else {
	    return "HUGE!";
	}

	int dotPos = fileSizeS.indexOf('.');
	String fileSizeS2 = dotPos == -1 ? fileSizeS : fileSizeS.substring(0, dotPos + 2);
	return fileSizeS2 + " " + fileSizeEx;
    }

    // -----PROTECTED FUNCTIONS-----

    // -----PRIVATE FUNCTIONS-----
}


text:
package org.ice4j.ice.harvest;

import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;

/**
 * A harvester implementation which binds to a single <tt>DatagramSocket</tt>
 * and provides local candidates of type "host". It runs a thread
 * ({@link #thread}) which perpetually reads from the socket.
 *
 * When {@link #harvest(org.ice4j.ice.Component)} is called, this harvester
 * creates and adds to the component a
 * {@link org.ice4j.ice.harvest.SinglePortUdpHarvester.MyCandidate} instance,
 * and associates the component's local username fragment (ufrag) with this
 * candidate.
 *
 * When a datagram from an unknown source is received, it is parsed as a STUN
 * Binding Request, and if it has a USERNAME attribute, its ufrag is extracted.
 * If this ufrag is associated with a candidate of this harvester, a new socket
 * is created and added to the candidate, and the remote address of the datagram
 * is associated with this socket. This mapping is then used to de-multiplex
 * received datagrams based on their remote address.
 *
 * @author Boris Grozev
 */
public class SinglePortUdpHarvester
        extends CandidateHarvester
{
    /**
     * Our class logger.
     */
    private static final Logger logger
            = Logger.getLogger(SinglePortUdpHarvester.class.getName());

    /**
     * The size for newly allocated <tt>Buffer</tt> instances. This limits the
     * maximum size of datagrams we can receive.
     *
     * XXX should we increase this in case of other MTUs, or set it dynamically
     * according to the available network interfaces?
     */
    private static final int BUFFER_SIZE
        = /* assumed MTU */ 1500 - /* IPv4 header */ 20 - /* UDP header */ 8;

    /**
     * The number of <tt>Buffer</tt> instances to keep in {@link #pool}.
     */
    private static final int POOL_SIZE = 256;

    /**
     * Creates a new <tt>SinglePortUdpHarvester</tt> instance for each allowed
     * IP address found on each allowed network interface, with the given port.
     *
     * @param port the UDP port number to use.
     * @return the list of created <tt>SinglePortUdpHarvester</tt>s.
     */
    public static List<SinglePortUdpHarvester>
        createHarvesters(int port)
    {
        List<SinglePortUdpHarvester> harvesters
           = new LinkedList<SinglePortUdpHarvester>();

        List<TransportAddress> addresses = new LinkedList<TransportAddress>();
        boolean isIPv6Disabled = StackProperties.getBoolean(
                StackProperties.DISABLE_IPv6,
                false);
        boolean isIPv6LinkLocalDisabled = StackProperties.getBoolean(
                StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
                false);

        try
        {
            for (NetworkInterface iface
                    : Collections.list(NetworkInterface.getNetworkInterfaces()))
            {
                if (NetworkUtils.isInterfaceLoopback(iface)
                        || !NetworkUtils.isInterfaceUp(iface)
                        || !HostCandidateHarvester.isInterfaceAllowed(iface))
                {
                    continue;
                }

                Enumeration<InetAddress> ifaceAddresses
                        = iface.getInetAddresses();
                while (ifaceAddresses.hasMoreElements())
                {
                    InetAddress address = ifaceAddresses.nextElement();

                    if (!HostCandidateHarvester.isAddressAllowed(address))
                        continue;

                    if (isIPv6Disabled && address instanceof Inet6Address)
                        continue;
                    if (isIPv6LinkLocalDisabled
                            && address instanceof Inet6Address
                            && address.isLinkLocalAddress())
                        continue;

                    addresses.add(
                        new TransportAddress(address, port, Transport.UDP));
                }
            }
        }
        catch (SocketException se)
        {
            logger.info("Failed to get network interfaces: " + se);
        }

        return harvesters;
    }

    /**
     * The map which keeps the known remote addresses and their associated
     * candidateSockets.
     * {@link #thread} is the only thread which adds new entries, while
     * other threads remove entries when candidates are freed.
     */
    private final Map<SocketAddress, MySocket> sockets
            = new ConcurrentHashMap<SocketAddress, MySocket>();

    /**
     * The map which keeps all currently active <tt>Candidate</tt>s created by
     * this harvester. The keys are the local username fragments (ufrags) of
     * the components for which the candidates are harvested.
     */
    private final Map<String, MyCandidate> candidates
            = new ConcurrentHashMap<String, MyCandidate>();

    /**
     * A pool of <tt>Buffer</tt> instances used to avoid creating of new java
     * objects.
     */
    private final ArrayBlockingQueue<Buffer> pool
        = new ArrayBlockingQueue<Buffer>(POOL_SIZE);

    /**
     * The local address that this harvester is bound to.
     */
    private final TransportAddress localAddress;

    /**
     * The "main" socket that this harvester reads from.
     */
    private final DatagramSocket socket;

    /**
     * The thread reading from {@link #socket}.
     */
    private final Thread thread;

    /**
     * Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to
     * bind on the specified local address.
     * @param localAddress the address to bind to.
     * @throws IOException if initialization fails.
     */
    public SinglePortUdpHarvester(TransportAddress localAddress)
        throws IOException
    {
        this.localAddress = localAddress;
        this.socket = new DatagramSocket(localAddress);
        logger.info("Initialized SinglePortUdpHarvester with address "
                            + localAddress);

        thread = new Thread()
        {
            @Override
            public void run()
            {
                SinglePortUdpHarvester.this.runInHarvesterThread();
            }
        };

        thread.setName(SinglePortUdpHarvester.class.getName() + " thread");
        thread.setDaemon(true);
        thread.start();
    }

    /**
     * Perpetually reads datagrams from {@link #socket} and handles them
     * accordingly.
     *
     * It is important that this blocks are little as possible (except on
     * socket.receive(), of course),  because it could potentially delay the
     * reception of both ICE and media packets for the whole application.
     */
    private void runInHarvesterThread()
    {
        Buffer buf;
        DatagramPacket pkt = null;
        Component component;
        MyCandidate candidate;
        MySocket destinationSocket;
        InetSocketAddress remoteAddress;

        while (true)
        {
            // TODO: implement stopping the thread with a switch?

            buf = getFreeBuffer();

            if (pkt == null)
                pkt = new DatagramPacket(buf.buffer, 0, buf.buffer.length);
            else
                pkt.setData(buf.buffer, 0, buf.buffer.length);

            try
            {
                socket.receive(pkt);
            }
            catch (IOException ioe)
            {
                logger.severe("Failed to receive from socket: " + ioe);
                break;
            }
            buf.len = pkt.getLength();

            remoteAddress = (InetSocketAddress) pkt.getSocketAddress();
            destinationSocket = sockets.get(remoteAddress);
            if (destinationSocket != null)
            {
                //make 'pkt' available for reading through destinationSocket
                destinationSocket.addBuffer(buf);
            }
            else
            {
                // Packet from an unknown source. Is it a STUN Binding Request?
                String ufrag = getUfrag(buf.buffer, 0, buf.len);
                if (ufrag == null)
                {
                    // Not a STUN Binding Request or doesn't have a valid
                    // USERNAME attribute. Drop it.
                    continue;
                }

                candidate = candidates.get(ufrag);
                component
                    = candidate == null ? null : candidate.getParentComponent();
                if (component != null)
                {
                    // This is a STUN Binding Request destined for this
                    // specific Candidate/Component/Agent.

                    try
                    {
                        // 1. Create a socket for this remote address
                        MySocket newSocket = new MySocket(remoteAddress);

                        // 2. Set-up de-multiplexing for future datagrams
                        // with this address to this socket.
                        sockets.put(remoteAddress, newSocket);

                        // 3. Let the candidate and its STUN stack no about the
                        // new socket.
                        candidate.addSocket(newSocket, remoteAddress);

                        // 4. Add the original datagram to the new socket.
                        newSocket.addBuffer(buf);
                    }
                    catch (SocketException se)
                    {
                        logger.info("Could not create a socket: " + se);
                        continue;
                    }
                    catch (IOException ioe)
                    {
                        logger.info("Failed to handle new socket: " + ioe);
                        continue;
                    }
                }
                else
                {
                    // A STUN Binding Request with an unknown USERNAME. Drop it.
                    continue;
                }
            }
        }

        // TODO we are all done, clean up.
    }

    /**
     * Gets an unused <tt>Buffer</tt> instance, creating it if necessary.
     * @return  an unused <tt>Buffer</tt> instance, creating it if necessary.
     */
    private Buffer getFreeBuffer()
    {
        Buffer buf = pool.poll();
        if (buf == null)
        {
            buf = new Buffer(new byte[BUFFER_SIZE], 0);
        }

        return buf;
    }

    /**
     * Tries to parse the bytes in <tt>buf</tt> at offset <tt>off</tt> (and
     * length <tt>len</tt>) and a STUN Binding Request message. If successful,
     * looks for a USERNAME attribute and returns the local username fragment
     * part (see RFC5245 Section 7.1.2.3).
     * In case of any failure returns <tt>null</tt>.
     *
     * @param buf the bytes.
     * @param off the offset.
     * @param len the length.
     * @return the local ufrag from the USERNAME attribute of the STUN message
     * contained in <tt>buf</tt>, or <tt>null</tt>.
     */
    private String getUfrag(byte[] buf, int off, int len)
    {
        try
        {
            Message stunMessage
                    = Message.decode(buf,
                                     (char) off,
                                     (char) len);

            if (stunMessage.getMessageType()
                    != Message.BINDING_REQUEST)
            {
                return null;
            }

            UsernameAttribute usernameAttribute
                    = (UsernameAttribute)
                    stunMessage.getAttribute(Attribute.USERNAME);
            if (usernameAttribute == null)
                return null;

            String usernameString
                    = new String(usernameAttribute.getUsername());
            return usernameString.split(":")[0];
        }
        catch (Exception e)
        {
            // Catch everything. We are going to log, and then drop the packet
            // anyway.
            logger.info("Failed to extract local ufrag: " + e);
        }

        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<LocalCandidate> harvest(Component component)
    {
        IceMediaStream stream = component.getParentStream();
        Agent agent = stream.getParentAgent();
        String ufrag = agent.getLocalUfrag();

        if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1)
        {
            /*
             * SinglePortUdpHarvester only works with streams with a
             * single component, and agents with a single stream. This is
             * because we use the local "ufrag" from an incoming STUN packet
             * to setup de-multiplexing based on remote transport address.
             */
            logger.info(
                    "More than one Component for an Agent, cannot harvest.");
            return new LinkedList<LocalCandidate>();
        }

        MyCandidate candidate = new MyCandidate(component, ufrag);

        candidates.put(ufrag, candidate);
        component.addLocalCandidate(candidate);

        return new ArrayList<LocalCandidate>(Arrays.asList(candidate));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isHostHarvester()
    {
        return true;
    }

    /**
     * Implements a <tt>DatagramSocket</tt> for the purposes of a specific
     * <tt>MyCandidate</tt>.
     *
     * It is not bound to a specific port, but shares the same local address
     * as the bound socket held by the harvester.
     */
    private class MySocket
            extends DatagramSocket
    {
        /**
         * The size of {@link #queue}.
         */
        private static final int QUEUE_SIZE = 64;

        /**
         * The FIFO which acts as a buffer for this socket.
         */
        private final ArrayBlockingQueue<Buffer> queue
            = new ArrayBlockingQueue<Buffer>(QUEUE_SIZE);

        /**
         * The remote address that is associated with this socket.
         */
        private SocketAddress remoteAddress;

        /**
         * The flag which indicates that this <tt>DatagramSocket</tt> has been
         * closed.
         */
        private boolean closed = false;

        /**
         * Initializes a new <tt>MySocket</tt> instance with the given
         * remote address.
         * @param remoteAddress the remote address to be associated with the
         * new instance.
         * @throws SocketException
         */
        public MySocket(SocketAddress remoteAddress)
            throws SocketException
        {
            // unbound
            super((SocketAddress)null);

            this.remoteAddress = remoteAddress;
        }

        /**
         * Adds pkt to this socket. If the queue is full, drops a packet. Does
         * not block.
         */
        private void addBuffer(Buffer buf)
        {
            synchronized (queue)
            {
                // Drop the first rather than the current packet, so that
                // receivers can notice the loss earlier.
                if (queue.size() == QUEUE_SIZE)
                {
                    logger.info("Dropping a packet because the queue is full.");
                    queue.poll();
                }
                queue.offer(buf);

                queue.notifyAll();
            }
        }

        /**
         * {@inheritDoc}
         *
         * Delegates to the actual socket of the harvester.
         */
        @Override
        public InetAddress getLocalAddress()
        {
            return localAddress.getAddress();
        }

        /**
         * {@inheritDoc}
         *
         * Delegates to the actual socket of the harvester.
         */
        @Override
        public int getLocalPort()
        {
            return localAddress.getPort();
        }

        /**
         * {@inheritDoc}
         *
         * Delegates to the actual socket of the harvester.
         */
        @Override
        public SocketAddress getLocalSocketAddress()
        {
            return localAddress;
        }

        /**
         * {@inheritDoc}
         *
         * Removes the association of the remote address with this socket from
         * the harvester's map.
         */
        @Override
        public void close()
        {
            closed = true;

            synchronized (queue)
            {
                // Wake up any threads still in receive()
                queue.notifyAll();
            }

            // We could be called by the super-class constructor, in which
            // case this.removeAddress is not initialized yet.
            if (remoteAddress != null)
                SinglePortUdpHarvester.this.sockets.remove(remoteAddress);

            super.close();
        }

        /**
         * Reads the data from the first element of {@link #queue} into
         * <tt>p</tt>. Blocks until {@link #queue} has an element.
         * @param p
         * @throws IOException
         */
        @Override
        public void receive(DatagramPacket p)
           throws IOException
        {
            Buffer buf = null;

            while (buf == null)
            {
                if (closed)
                    throw new SocketException("Socket closed");

                synchronized (queue)
                {
                    if (queue.isEmpty())
                    {
                        try
                        {
                            queue.wait();
                        }
                        catch (InterruptedException ie)
                        {}
                    }

                    buf = queue.poll();
                }
            }

            byte[] pData = p.getData();

            // XXX Should we use p.setData() here with a buffer of our own?
            if (pData == null || pData.length < buf.len)
                throw new IOException("packet buffer not available");

            System.arraycopy(buf.buffer, 0, pData, 0, buf.len);
            p.setLength(buf.len);
            p.setSocketAddress(remoteAddress);

            pool.offer(buf);
        }

        /**
         * {@inheritDoc}
         *
         * Delegates to the actual socket of the harvester.
         */
        @Override
        public void send(DatagramPacket p)
            throws IOException
        {
            socket.send(p);
        }
    }

    /**
     * Represents a buffer for the purposes of <tt>SinglePortUdpHarvester</tt>.
     * Wraps a byte[] and adds a length field specifying the number of elements
     * actually used.
     */
    private class Buffer
    {
        /**
         * The actual data.
         */
        byte[] buffer;

        /**
         * The number of elements of {@link #buffer} actually used.
         */
        int len;

        /**
         * Initializes a new <tt>Buffer</tt> instance.
         * @param buffer the data.
         * @param len the length.
         */
        private Buffer(byte[] buffer, int len)
        {
            this.buffer = buffer;
            this.len = len;
        }
    }

    /**
     * Implements a <tt>Candidate</tt> for the purposes of this
     * <tt>SinglePortUdpHarvester</tt>.
     */
    private class MyCandidate
        extends HostCandidate
    {
        /**
         * The local username fragment associated with this candidate.
         */
        private final String ufrag;

        /**
         * The flag which indicates that this <tt>MyCandidate</tt> has been
         * freed.
         */
        private boolean freed = false;

        /**
         * The collection of <tt>IceSocketWrapper</tt>s that can potentially
         * be used by the ice4j user to read/write from/to this candidate.
         * The keys are the remote addresses for each socket.
         *
         * There are wrappers over <tt>MultiplexedDatagramSocket</tt>s over
         * a corresponding socket in {@link #sockets}.
         */
        private final Map<SocketAddress, IceSocketWrapper> candidateSockets
                = new HashMap<SocketAddress, IceSocketWrapper>();

        /**
         * The collection of <tt>DatagramSocket</tt>s added to this candidate.
         * The keys are the remote addresses for each socket.
         *
         * These are the "raw" sockets, before any wrappers are added for
         * the STUN stack or the user of ice4j.
         */
        private final Map<SocketAddress, DatagramSocket> sockets
                = new HashMap<SocketAddress, DatagramSocket>();

        /**
         * Initializes a new <tt>MyCandidate</tt> instance with the given
         * <tt>Component</tt> and the given local username fragment.
         * @param component the <tt>Component</tt> for which this candidate will
         * serve.
         * @param ufrag the local ICE username fragment for this candidate (and
         * its <tt>Component</tt> and <tt>Agent</tt>).
         */
        private MyCandidate(Component component, String ufrag)
        {
            super(localAddress, component);
            this.ufrag = ufrag;
        }

        /**
         * {@inheritDoc}
         *
         * Closes all sockets in use by this <tt>LocalCandidate</tt>.
         */
        @Override
        public void free()
        {
            synchronized (this)
            {
                if (freed)
                    return;
                freed = true;
            }

            candidates.remove(ufrag);

            synchronized (sockets)
            {
                StunStack stunStack = getStunStack();

                for (Map.Entry<SocketAddress, DatagramSocket> e
                        : sockets.entrySet())
                {
                    DatagramSocket socket = e.getValue();

                    if (stunStack != null)
                    {
                        TransportAddress localAddress
                                = new TransportAddress(socket.getLocalAddress(),
                                                       socket.getLocalPort(),
                                                       Transport.UDP);
                        TransportAddress remoteAddress
                                = new TransportAddress((InetSocketAddress) e.getKey(),

                                                       Transport.UDP);

                        stunStack.removeSocket(localAddress, remoteAddress);
                    }

                    socket.close();
                }

                sockets.clear();
            }

            synchronized (candidateSockets)
            {
                candidateSockets.clear();
            }

            super.free();
        }

        /**
         * Adds a new <tt>Socket</tt> to this candidate, which is associated
         * with a particular remote address.
         * @param socket the socket to add.
         * @param remoteAddress the remote address for the socket.
         */
        private synchronized void addSocket(DatagramSocket socket,
                               InetSocketAddress remoteAddress)
            throws IOException
        {
            if (freed)
            {
                throw new IOException("Candidate freed");
            }

            Component component = getParentComponent();
            if (component == null)
            {
                throw new IOException("No parent component");
            }

            IceProcessingState state
                    = component.getParentStream().getParentAgent().getState();
            if (!IceProcessingState.WAITING.equals(state)
                    && !IceProcessingState.RUNNING.equals(state))
            {
                throw new IOException(
                        "Agent state is " + state + ". Cannot add socket.");
            }

            MultiplexingDatagramSocket multiplexing
                    = new MultiplexingDatagramSocket(socket);

            // Socket to add to the candidate
            IceSocketWrapper candidateSocket
                = new IceUdpSocketWrapper(multiplexing);

            // STUN-only filtered socket to add to the StunStack
            IceSocketWrapper stunSocket
                = new IceUdpSocketWrapper(
                    multiplexing.getSocket(new StunDatagramPacketFilter()));

            component.getParentStream().getParentAgent().getStunStack()
                    .addSocket(
                            stunSocket,
                            new TransportAddress(remoteAddress, Transport.UDP));

            // XXX is this necessary?
            synchronized (candidateSockets)
            {
                candidateSockets.put(remoteAddress, candidateSocket);
            }

            // XXX is this necessary?
            synchronized (sockets)
            {
                sockets.put(remoteAddress, socket);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
        {
            return candidateSockets.get(remoteAddress);
        }
    }
}


text:
===========
JDBC driver
===========

The Trino `JDBC driver <https://en.wikipedia.org/wiki/JDBC_driver>`_ allows
users to access Trino using Java-based applications, and other non-Java
applications running in a JVM. Both desktop and server-side applications, such
as those used for reporting and database development, use the JDBC driver.

Requirements
------------

The Trino JDBC driver has the following requirements:

* Java version 8 or higher.
* All users that connect to Trino with the JDBC driver must be granted access to
  query tables in the ``system.jdbc`` schema.

Installing
----------

Download :maven_download:`jdbc` and add it to the classpath of your Java application.

The driver is also available from Maven Central:

.. parsed-literal::

    <dependency>
        <groupId>io.trino</groupId>
        <artifactId>trino-jdbc</artifactId>
        <version>\ |version|\ </version>
    </dependency>

We recommend using the latest version of the JDBC driver. A list of all
available versions can be found in the `Maven Central Repository
<https://repo1.maven.org/maven2/io/trino/trino-jdbc/>`_. Navigate to the
directory for the desired version, and select the ``trino-jdbc-xxx.jar`` file
to download, where ``xxx`` is the version number.

Once downloaded, you must add the JAR file to a directory in the classpath
of users on systems where they will access Trino.

After you have downloaded the JDBC driver and added it to your
classpath, you'll typically need to restart your application in order to
recognize the new driver. Then, depending on your application, you
may need to manually register and configure the driver.

The CLI uses the HTTP protocol and the
:doc:`Trino client REST API </develop/client-protocol>` to communicate
with Trino.

Registering and configuring the driver
--------------------------------------

Drivers are commonly loaded automatically by applications once they are added to
its classpath. If your application does not, such as is the case for some
GUI-based SQL editors, read this section. The steps to register the JDBC driver
in a UI or on the command line depend upon the specific application you are
using. Please check your application's documentation.

Once registered, you must also configure the connection information as described
in the following section.

Connecting
----------

When your driver is loaded, registered and configured, you are ready to connect
to Trino from your application. The following JDBC URL formats are supported:

.. code-block:: text

    jdbc:trino://host:port
    jdbc:trino://host:port/catalog
    jdbc:trino://host:port/catalog/schema

The following is an example of a JDBC URL used to create a connection:

.. code-block:: text

    jdbc:trino://example.net:8080/hive/sales

This example JDBC URL locates a Trino instance running on port ``8080`` on
``example.net``, with the catalog ``hive`` and the schema ``sales`` defined.

.. note::

  Typically, the JDBC driver classname is configured automatically by your
  client. If it is not, use ``io.trino.jdbc.TrinoDriver`` wherever a driver
  classname is required.

.. _jdbc-java-connection:

Connection parameters
---------------------

The driver supports various parameters that may be set as URL parameters,
or as properties passed to ``DriverManager``. Both of the following
examples are equivalent:

.. code-block:: java

    // properties
    String url = "jdbc:trino://example.net:8080/hive/sales";
    Properties properties = new Properties();
    properties.setProperty("user", "test");
    properties.setProperty("password", "secret");
    properties.setProperty("SSL", "true");
    Connection connection = DriverManager.getConnection(url, properties);

    // URL parameters
    String url = "jdbc:trino://example.net:8443/hive/sales?user=test&password=secret&SSL=true";
    Connection connection = DriverManager.getConnection(url);

These methods may be mixed; some parameters may be specified in the URL,
while others are specified using properties. However, the same parameter
may not be specified using both methods.

.. _jdbc-parameter-reference:

Parameter reference
-------------------

================================================================= =======================================================================
Name                                                              Description
================================================================= =======================================================================
``user``                                                          Username to use for authentication and authorization.
``password``                                                      Password to use for LDAP authentication.
``sessionUser``                                                   Session username override, used for impersonation.
``socksProxy``                                                    SOCKS proxy host and port. Example: ``localhost:1080``
``httpProxy``                                                     HTTP proxy host and port. Example: ``localhost:8888``
``clientInfo``                                                    Extra information about the client.
``clientTags``                                                    Client tags for selecting resource groups. Example: ``abc,xyz``
``traceToken``                                                    Trace token for correlating requests across systems.
``source``                                                        Source name for the Trino query. This parameter should be used in
                                                                  preference to ``ApplicationName``. Thus, it takes precedence
                                                                  over ``ApplicationName`` and/or ``applicationNamePrefix``.
``applicationNamePrefix``                                         Prefix to append to any specified ``ApplicationName`` client info
                                                                  property, which is used to set the source name for the Trino query
                                                                  if the ``source`` parameter has not been set. If neither this
                                                                  property nor ``ApplicationName`` or ``source`` are set, the source
                                                                  name for the query is ``trino-jdbc``.
``accessToken``                                                   :doc:`JWT </security/jwt>` access token for token based authentication.
``SSL``                                                           Set ``true`` to specify using TLS/HTTPS for connections.
``SSLVerification``                                               The method of TLS verification. There are three modes: ``FULL``
                                                                  (default), ``CA`` and ``NONE``. For ``FULL``, the normal TLS
                                                                  verification is performed. For ``CA``, only the CA is verified but
                                                                  hostname mismatch is allowed. For ``NONE``, there is no verification.
``SSLKeyStorePath``                                               Use only when connecting to a Trino cluster that has :doc:`certificate
                                                                  authentication </security/certificate>` enabled.
                                                                  Specifies the path to a :doc:`PEM </security/inspect-pem>` or :doc:`JKS
                                                                  </security/inspect-jks>` file, which must contain a certificate that
                                                                  is trusted by the Trino cluster you connect to.
``SSLKeyStorePassword``                                           The password for the KeyStore, if any.
``SSLKeyStoreType``                                               The type of the KeyStore. The default type is provided by the Java
                                                                  ``keystore.type`` security property or ``jks`` if none exists.
``SSLTrustStorePath``                                             The location of the Java TrustStore file to use.
                                                                  to validate HTTPS server certificates.
``SSLTrustStorePassword``                                         The password for the TrustStore.
``SSLTrustStoreType``                                             The type of the TrustStore. The default type is provided by the Java
                                                                  ``keystore.type`` security property or ``jks`` if none exists.
``SSLUseSystemTrustStore``                                        Set ``true`` to automatically use the system TrustStore based on the operating system.
                                                                  The supported OSes are Windows and macOS. For Windows, the ``Windows-ROOT``
                                                                  TrustStore is selected. For macOS, the ``KeychainStore`` TrustStore is selected.
                                                                  For other OSes, the default Java TrustStore is loaded.
                                                                  The TrustStore specification can be overridden using ``SSLTrustStoreType``.
``KerberosRemoteServiceName``                                     Trino coordinator Kerberos service name. This parameter is
                                                                  required for Kerberos authentication.
``KerberosPrincipal``                                             The principal to use when authenticating to the Trino coordinator.
``KerberosUseCanonicalHostname``                                  Use the canonical hostname of the Trino coordinator for the Kerberos
                                                                  service principal by first resolving the hostname to an IP address
                                                                  and then doing a reverse DNS lookup for that IP address.
                                                                  This is enabled by default.
``KerberosServicePrincipalPattern``                               Trino coordinator Kerberos service principal pattern. The default is
                                                                  ``${SERVICE}@${HOST}``. ``${SERVICE}`` is replaced with the value of
                                                                  ``KerberosRemoteServiceName`` and ``${HOST}`` is replaced with the
                                                                  hostname of the coordinator (after canonicalization if enabled).
``KerberosConfigPath``                                            Kerberos configuration file.
``KerberosKeytabPath``                                            Kerberos keytab file.
``KerberosCredentialCachePath``                                   Kerberos credential cache.
``KerberosDelegation``                                            Set to ``true`` to use the token from an existing Kerberos context.
                                                                  This allows client to use Kerberos authentication without passing
                                                                  the Keytab or credential cache. Defaults to ``false``.
``extraCredentials``                                              Extra credentials for connecting to external services,
                                                                  specified as a list of key-value pairs. For example,
                                                                  ``foo:bar;abc:xyz`` creates the credential named ``abc``
                                                                  with value ``xyz`` and the credential named ``foo`` with value ``bar``.
``roles``                                                         Authorization roles to use for catalogs, specified as a list of
                                                                  key-value pairs for the catalog and role. For example,
                                                                  ``catalog1:roleA;catalog2:roleB`` sets ``roleA``
                                                                  for ``catalog1`` and ``roleB`` for ``catalog2``.
``sessionProperties``                                             Session properties to set for the system and for catalogs,
                                                                  specified as a list of key-value pairs.
                                                                  For example, ``abc:xyz;example.foo:bar`` sets the system property
                                                                  ``abc`` to the value ``xyz`` and the ``foo`` property for
                                                                  catalog ``example`` to the value ``bar``.
``externalAuthentication``                                        Set to true if you want to use external authentication via
                                                                  :doc:`/security/oauth2`. Use a local web browser to authenticate with an
                                                                  identity provider (IdP) that has been configured for the Trino coordinator.
``externalAuthenticationTokenCache``                              Allows the sharing of external authentication tokens between different
                                                                  connections for the same authenticated user until the cache is
                                                                  invalidated, such as when a client is restarted or when the classloader
                                                                  reloads the JDBC driver. This is disabled by default, with a value of
                                                                  ``NONE``. To enable, set the value to ``MEMORY``. If the JDBC driver is used
                                                                  in a shared mode by different users, the first registered token is stored
                                                                  and authenticates all users.
``disableCompression``                                            Whether compression should be enabled.
``assumeLiteralUnderscoreInMetadataCallsForNonConformingClients`` When enabled, the name patterns passed to ``DatabaseMetaData`` methods
                                                                  are treated as underscores. You can use this as a workaround for
                                                                  applications that do not escape schema or table names when passing them
                                                                  to ``DatabaseMetaData`` methods as schema or table name patterns.
================================================================= =======================================================================


text:
import os
from os import path as op
import shutil
import glob
import warnings
from nose.tools import assert_true, assert_raises

from mne.commands import (mne_browse_raw, mne_bti2fiff, mne_clean_eog_ecg,
                          mne_compute_proj_ecg, mne_compute_proj_eog,
                          mne_coreg, mne_flash_bem_model, mne_kit2fiff,
                          mne_make_scalp_surfaces, mne_maxfilter,
                          mne_report, mne_surf2bem)
from mne.utils import (run_tests_if_main, _TempDir, requires_mne, requires_PIL,
                       requires_mayavi, requires_tvtk, ArgvSetter, slow_test)
from mne.io import Raw
from mne.datasets import testing

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')

subjects_dir = op.join(testing.data_path(download=False), 'subjects')

warnings.simplefilter('always')

def check_usage(module, force_help=False):
    """Helper to ensure we print usage"""
    args = ('--help',) if force_help else ()
    with ArgvSetter(args) as out:
        try:
            module.run()
        except SystemExit:
            pass
        assert_true('Usage: ' in out.stdout.getvalue())

@slow_test
def test_browse_raw():
    """Test mne browse_raw"""
    check_usage(mne_browse_raw)

def test_bti2fiff():
    """Test mne bti2fiff"""
    check_usage(mne_bti2fiff)

@requires_mne
def test_clean_eog_ecg():
    """Test mne clean_eog_ecg"""
    check_usage(mne_clean_eog_ecg)
    tempdir = _TempDir()
    raw = Raw([raw_fname, raw_fname, raw_fname])
    raw.info['bads'] = ['MEG 2443']
    use_fname = op.join(tempdir, op.basename(raw_fname))
    raw.save(use_fname)
    with ArgvSetter(('-i', use_fname, '--quiet')):
        mne_clean_eog_ecg.run()
    fnames = glob.glob(op.join(tempdir, '*proj.fif'))
    assert_true(len(fnames) == 2)  # two projs
    fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
    assert_true(len(fnames) == 3)  # raw plus two projs

@slow_test
def test_compute_proj_ecg_eog():
    """Test mne compute_proj_ecg/eog"""
    for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
        check_usage(fun)
        tempdir = _TempDir()
        use_fname = op.join(tempdir, op.basename(raw_fname))
        bad_fname = op.join(tempdir, 'bads.txt')
        with open(bad_fname, 'w') as fid:
            fid.write('MEG 2443\n')
        shutil.copyfile(raw_fname, use_fname)
        with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
                         '--rej-eeg', '150')):
            fun.run()
        fnames = glob.glob(op.join(tempdir, '*proj.fif'))
        assert_true(len(fnames) == 1)
        fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
        assert_true(len(fnames) == 1)

def test_coreg():
    """Test mne coreg"""
    assert_true(hasattr(mne_coreg, 'run'))

def test_flash_bem_model():
    """Test mne flash_bem_model"""
    assert_true(hasattr(mne_flash_bem_model, 'run'))
    check_usage(mne_flash_bem_model)

def test_kit2fiff():
    """Test mne kit2fiff"""
    # Can't check
    check_usage(mne_kit2fiff, force_help=True)

@requires_tvtk
@requires_mne
@testing.requires_testing_data
def test_make_scalp_surfaces():
    """Test mne make_scalp_surfaces"""
    check_usage(mne_make_scalp_surfaces)
    # Copy necessary files to avoid FreeSurfer call
    tempdir = _TempDir()
    surf_path = op.join(subjects_dir, 'sample', 'surf')
    surf_path_new = op.join(tempdir, 'sample', 'surf')
    os.mkdir(op.join(tempdir, 'sample'))
    os.mkdir(surf_path_new)
    os.mkdir(op.join(tempdir, 'sample', 'bem'))
    shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)

    orig_fs = os.getenv('FREESURFER_HOME', None)
    orig_mne = os.getenv('MNE_ROOT')
    if orig_fs is not None:
        del os.environ['FREESURFER_HOME']
    cmd = ('-s', 'sample', '--subjects-dir', tempdir)
    os.environ['_MNE_TESTING_SCALP'] = 'true'
    try:
        with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
            assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
            os.environ['FREESURFER_HOME'] = tempdir  # don't need it
            del os.environ['MNE_ROOT']
            assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
            os.environ['MNE_ROOT'] = orig_mne
            mne_make_scalp_surfaces.run()
            assert_raises(IOError, mne_make_scalp_surfaces.run)  # no overwrite
    finally:
        if orig_fs is not None:
            os.environ['FREESURFER_HOME'] = orig_fs
        os.environ['MNE_ROOT'] = orig_mne
        del os.environ['_MNE_TESTING_SCALP']

def test_maxfilter():
    """Test mne maxfilter"""
    check_usage(mne_maxfilter)
    with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
                     '--trans', raw_fname)) as out:
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            os.environ['_MNE_MAXFILTER_TEST'] = 'true'
            try:
                mne_maxfilter.run()
            finally:
                del os.environ['_MNE_MAXFILTER_TEST']
        assert_true(len(w) == 1)
        for check in ('maxfilter', '-trans', '-movecomp'):
            assert_true(check in out.stdout.getvalue(), check)

@slow_test
@requires_mayavi
@requires_PIL
@testing.requires_testing_data
def test_report():
    """Test mne report"""
    check_usage(mne_report)
    tempdir = _TempDir()
    use_fname = op.join(tempdir, op.basename(raw_fname))
    shutil.copyfile(raw_fname, use_fname)
    with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir,
                     '-s', 'sample', '--no-browser', '-m', '30')):
        mne_report.run()
    fnames = glob.glob(op.join(tempdir, '*.html'))
    assert_true(len(fnames) == 1)

def test_surf2bem():
    """Test mne surf2bem"""
    check_usage(mne_surf2bem)

run_tests_if_main()


text:
package org.parboiled.matchers;

import org.parboiled.MatcherContext;
import org.parboiled.matchervisitors.MatcherVisitor;

import static org.parboiled.common.Preconditions.checkArgNotNull;

/**
 * A {@link org.parboiled.matchers.Matcher} that never matches anything.
 */
public class NothingMatcher extends AbstractMatcher {

    public NothingMatcher() {
        super("NOTHING");
    }

    public boolean match(MatcherContext context) {
        return false;
    }

    public <R> R accept(MatcherVisitor<R> visitor) {
        checkArgNotNull(visitor, "visitor");
        return visitor.visit(this);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<info:toolkitInfoModel xmlns:common="http://www.ibm.com/xmlns/prod/streams/spl/common" xmlns:info="http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo">
  <info:identity>
    <info:name>com.ibm.streamsx.iot</info:name>
    <info:description>IoT integration including connectivity with IBM Watson IoT Platform.

This toolkit provides a model around IoT devices where devices produce events (for example, sensor data) and subscribe to commands (for example, control instructions, such as reduce maximum rpm for an engine).

Streams applications can use this toolkit to provide real time analytics against all the events from potentially thousands of devices, including sending commands to specific devices based upon the analytics.

As well as the general IoT device model, integration with IBM Watson IoT
Platform is provided allowing ease of connecting IBM Streams to
a IoT Platform service (including IBM Cloud).

See [namespace:com.ibm.streamsx.iot] for more details.

This toolkit depends on these toolkits:
* `com.ibm.streamsx.mqtt`
* `com.ibm.streamsx.json`
* `com.ibm.streamsx.datetime`
* `com.ibm.streamsx.topology`

</info:description>
    <info:version>1.3.0</info:version>
    <info:requiredProductVersion>4.3.0</info:requiredProductVersion>
  </info:identity>
  <info:dependencies>
    <info:toolkit>
      <common:name>com.ibm.streamsx.mqtt</common:name>
      <common:version>[1.0.0,99.0.0)</common:version>
    </info:toolkit>
    <info:toolkit>
      <common:name>com.ibm.streamsx.json</common:name>
      <common:version>[1.1.1,99.0.0)</common:version>
    </info:toolkit>
    <info:toolkit>
      <common:name>com.ibm.streamsx.datetime</common:name>
      <common:version>[1.1.1,99.0.0)</common:version>
    </info:toolkit>
    <info:toolkit>
      <common:name>com.ibm.streamsx.topology</common:name>
      <common:version>[1.3.0,99.0.0)</common:version>
    </info:toolkit>
  </info:dependencies>

  <info:resources>
    <info:messageSet name="IoTResource">
      <info:lang default="true">en_US/IoTResource.xlf</info:lang>
      <info:lang>de_DE/IoTResource.xlf</info:lang>
      <info:lang>es_ES/IoTResource.xlf</info:lang>
      <info:lang>fr_FR/IoTResource.xlf</info:lang>
      <info:lang>it_IT/IoTResource.xlf</info:lang>
      <info:lang>ja_JP/IoTResource.xlf</info:lang>
      <info:lang>ko_KR/IoTResource.xlf</info:lang>
      <info:lang>pt_BR/IoTResource.xlf</info:lang>
      <info:lang>ru_RU/IoTResource.xlf</info:lang>
      <info:lang>zh_CN/IoTResource.xlf</info:lang>
      <info:lang>zh_TW/IoTResource.xlf</info:lang>
    </info:messageSet>
  </info:resources>

</info:toolkitInfoModel>


text:
  Sugères est
       un village
       situé dans le département de Puy-de-Dôme en Auvergne. On dénombrait 551 habitants en 2008.

À Sugères, le prix moyen à l'achat d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 392 € du m². À la location la valorisation moyenne se situe à 0 € du m² par mois.

Le nombre d'habitations, à Sugères, se décomposait en 2011 en cinq appartements et 380 maisons soit
 un marché relativement équilibré.

À coté de Sugères sont situées les communes de
Auzelles à 8 km, 336 habitants,
Les Pradeaux localisée à 6 km, 324 habitants,
Brousse à 3 km, 358 habitants,
Manglieu située à 4 km, 431 habitants,
Saint-Quentin-sur-Sauxillanges située à 5 km, 109 habitants,
Sauxillanges localisée à 6 km, 1 122 habitants,
 entre autres. De plus, Sugères est située à seulement 22 km de Cournon-d'Auvergne.

Si vous pensez emmenager à Sugères, vous pourrez facilement trouver une maison à acheter.

La ville propose quelques  équipements sportifs, elle propose entre autres un terrain de sport et une boucle de randonnée.


text:
require 'dyio/input'

module Bowler
  module IO
    module Peripherals

      # Represents a UART peripherial attached to the dyio
      class UART
        # @!attribute [r] receiver
        #   @return [UARTRx] the receiver input associated with this UART
        attr_reader :receiver

        # @!attribute [r] transmitter
        #   @return [UARTTx] the transmitter peripheral object associated with this UART
        attr_reader :transmitter

        # Represents a UART receiver channel
        class UARTRx < Input
          # Create a new UART receiver input channel
          # @param [DyIO] dyio the {DyIO} representing the device to which the peripheral is connected
          # @param [Fixnum] channel the dyio channel to which the peripheral is connected
          # @param [true,false] async whether to operate this device in asynchronous mode (NOT CURRENTLY SUPPORTED)
          def initialize(dyio, channel, async=false)
            super(dyio, channel, :usart_rx, async)
          end

          private
          def process_data(data)

          end
        end

        # Represents a UART transmitter channel
        class UARTTx < IO::Channel
          # Create a new UART transmitter channel
          # @param [DyIO] dyio the {DyIO} representing the device to which the peripheral is connected
          # @param [Fixnum] channel the dyio channel to which the peripheral is connected
          def initialize(dyio, channel)
            super(dyio, channel, :usart_tx, false)
          end
        end

        # Create a new UART object representing a UART peripherial connected to the
        # given DyIO at the given input and output channels.
        # @param [DyIO] dyio the {DyIO} representing the device to which the peripheral is connected
        # @param [Fixnum] in_channel the dyio channel to which the UARTRx is connected
        # @param [Fixnum] out_channel the dyio channel to which the UARTTx is connected
        # @param [true,false] async whether to operate this device in asynchronous mode (NOT CURRENTLY SUPPORTED)
        def initialize(dyio, in_channel = 17, out_channel = 16, async = false)
          @receiver = UARTRx.new(dyio, in_channel)
          @transmitter = UARTTx.new(dyio, out_channel)
        end

        # Transmits a sequences of bytes to the peripheral
        # @param [Array<Fixnum>] bytes the bytes to transmit
        def transmit(bytes)
          @transmitter.value = bytes
        end

        # Receives a sequence of bytes from the peripheral
        # @return [String] the bytes returned by the receiver
        def receive
          @transmitter.value
        end
      end
    end
  end
end


text:
<?xml version="1.0" standalone="yes"?>
<library-reference id="temperature_base_units_reference"><title>Temperature Base Units Reference</title><header name="boost/units/base_units/temperature/celsius.hpp">
<namespace name="boost">
<namespace name="units">
<namespace name="temperature">
<struct name="celsius_base_unit"><inherit access="public">base_unit< celsius_base_unit, temperature_dimension,-1008 ></inherit><method-group name="public static functions">
<method name="name" specifiers="static"><type>std::string</type></method>
<method name="symbol" specifiers="static"><type>std::string</type></method>
</method-group>
</struct></namespace>
</namespace>
</namespace>
</header>
<header name="boost/units/base_units/temperature/fahrenheit.hpp">
<namespace name="boost">
<namespace name="units">
<namespace name="temperature">
<struct name="fahrenheit_base_unit"><inherit access="public">base_unit< fahrenheit_base_unit, temperature_dimension,-1007 ></inherit><method-group name="public static functions">
<method name="name" specifiers="static"><type>std::string</type></method>
<method name="symbol" specifiers="static"><type>std::string</type></method>
</method-group>
</struct></namespace>
</namespace>
</namespace>
</header>
</library-reference>


text:
TOOL.Category = "Construction"
TOOL.Name = "#tool.hoverball.name"

TOOL.ClientConVar[ "keyup" ] = "46"
TOOL.ClientConVar[ "keydn" ] = "43"
TOOL.ClientConVar[ "speed" ] = "1"
TOOL.ClientConVar[ "resistance" ] = "0"
TOOL.ClientConVar[ "strength" ] = "1"
TOOL.ClientConVar[ "model" ] = "models/dav0r/hoverball.mdl"

TOOL.Information = { { name = "left" } }

cleanup.Register( "hoverballs" )

local function IsValidHoverballModel( model )
	for mdl, _ in pairs( list.Get( "HoverballModels" ) ) do
		if ( mdl:lower() == model:lower() ) then return true end
	end
	return false
end

function TOOL:LeftClick( trace )

	if ( trace.Entity && trace.Entity:IsPlayer() ) then return false end

	-- If there's no physics object then we can't constraint it!
	if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	if ( CLIENT ) then return true end

	local ply = self:GetOwner()

	local model = self:GetClientInfo( "model" )
	local key_d = self:GetClientNumber( "keydn" )
	local key_u = self:GetClientNumber( "keyup" )
	local speed = self:GetClientNumber( "speed" )
	local strength = math.Clamp( self:GetClientNumber( "strength" ), 0.1, 20 )
	local resistance = math.Clamp( self:GetClientNumber( "resistance" ), 0, 20 )

	-- We shot an existing hoverball - just change its values
	if ( IsValid( trace.Entity ) && trace.Entity:GetClass() == "gmod_hoverball" && trace.Entity:GetPlayer() == ply ) then

		trace.Entity:SetSpeed( speed )
		trace.Entity:SetAirResistance( resistance )
		trace.Entity:SetStrength( strength )

		numpad.Remove( trace.Entity.NumDown )
		numpad.Remove( trace.Entity.NumUp )
		numpad.Remove( trace.Entity.NumBackDown )
		numpad.Remove( trace.Entity.NumBackUp )

		trace.Entity.NumDown = numpad.OnDown( ply, key_u, "Hoverball_Up", trace.Entity, true )
		trace.Entity.NumUp = numpad.OnUp( ply, key_u, "Hoverball_Up", trace.Entity, false )

		trace.Entity.NumBackDown = numpad.OnDown( ply, key_d, "Hoverball_Down", trace.Entity, true )
		trace.Entity.NumBackUp = numpad.OnUp( ply, key_d, "Hoverball_Down", trace.Entity, false )

		trace.Entity.key_u = key_u
		trace.Entity.key_d = key_d
		trace.Entity.speed = speed
		trace.Entity.strength = strength
		trace.Entity.resistance = resistance

		return true

	end

	if ( !util.IsValidModel( model ) || !util.IsValidProp( model ) || !IsValidHoverballModel( model ) ) then return false end
	if ( !self:GetSWEP():CheckLimit( "hoverballs" ) ) then return false end

	local ball = MakeHoverBall( ply, trace.HitPos, key_d, key_u, speed, resistance, strength, model )

	local CurPos = ball:GetPos()
	local NearestPoint = ball:NearestPoint( CurPos - ( trace.HitNormal * 512 ) )
	local Offset = CurPos - NearestPoint

	ball:SetPos( trace.HitPos + Offset )

	local const

	-- Don't weld to world
	if ( trace.Entity != NULL && !trace.Entity:IsWorld() ) then

		const = constraint.Weld( ball, trace.Entity, 0, trace.PhysicsBone, 0, 0, true )

		if ( IsValid( ball:GetPhysicsObject() ) ) then ball:GetPhysicsObject():EnableCollisions( false ) end
		ball.nocollide = true

		ply:AddCleanup( "hoverballs", const )

	end

	undo.Create( "HoverBall" )
		undo.AddEntity( ball )
		undo.AddEntity( const )
		undo.SetPlayer( ply )
	undo.Finish()

	return true

end

if ( SERVER ) then

	function MakeHoverBall( ply, Pos, key_d, key_u, speed, resistance, strength, model, Vel, aVel, frozen, nocollide )

		if ( IsValid( ply ) && !ply:CheckLimit( "hoverballs" ) ) then return false end
		if ( !IsValidHoverballModel( model ) ) then return false end

		local ball = ents.Create( "gmod_hoverball" )
		if ( !IsValid( ball ) ) then return false end

		ball:SetPos( Pos )
		ball:SetModel( Model( model ) )
		ball:Spawn()
		ball:SetSpeed( speed )
		ball:SetAirResistance( resistance )
		ball:SetStrength( strength )

		if ( IsValid( ply ) ) then
			ball:SetPlayer( ply )
		end

		ball.NumDown = numpad.OnDown( ply, key_u, "Hoverball_Up", ball, true )
		ball.NumUp = numpad.OnUp( ply, key_u, "Hoverball_Up", ball, false )

		ball.NumBackDown = numpad.OnDown( ply, key_d, "Hoverball_Down", ball, true )
		ball.NumBackUp = numpad.OnUp( ply, key_d, "Hoverball_Down", ball, false )

		if ( nocollide == true && IsValid( ball:GetPhysicsObject() ) ) then ball:GetPhysicsObject():EnableCollisions( false ) end

		local ttable = {
			key_d = key_d,
			key_u = key_u,
			pl = ply,
			nocollide = nocollide,
			speed = speed,
			strength = strength,
			resistance = resistance,
			model = model
		}

		table.Merge( ball:GetTable(), ttable )

		if ( IsValid( ply ) ) then
			ply:AddCount( "hoverballs", ball )
			ply:AddCleanup( "hoverballs", ball )
		end

		DoPropSpawnedEffect( ball )

		return ball

	end
	duplicator.RegisterEntityClass( "gmod_hoverball", MakeHoverBall, "Pos", "key_d", "key_u", "speed", "resistance", "strength", "model", "Vel", "aVel", "frozen", "nocollide" )

end

function TOOL:UpdateGhostHoverball( ent, ply )

	if ( !IsValid( ent ) ) then return end

	local trace = ply:GetEyeTrace()
	if ( !trace.Hit || trace.Entity && ( trace.Entity:GetClass() == "gmod_hoverball" || trace.Entity:IsPlayer() ) ) then

		ent:SetNoDraw( true )
		return

	end

	local CurPos = ent:GetPos()
	local NearestPoint = ent:NearestPoint( CurPos - ( trace.HitNormal * 512 ) )
	local Offset = CurPos - NearestPoint

	ent:SetPos( trace.HitPos + Offset )

	ent:SetNoDraw( false )

end

function TOOL:Think()

	local mdl = self:GetClientInfo( "model" )
	if ( !IsValidHoverballModel( mdl ) ) then self:ReleaseGhostEntity() return end

	if ( !IsValid( self.GhostEntity ) || self.GhostEntity:GetModel() != mdl ) then
		self:MakeGhostEntity( mdl, Vector( 0, 0, 0 ), Angle( 0, 0, 0 ) )
	end

	self:UpdateGhostHoverball( self.GhostEntity, self:GetOwner() )

end

local ConVarsDefault = TOOL:BuildConVarList()

function TOOL.BuildCPanel( CPanel )

	CPanel:AddControl( "Header", { Description = "#tool.hoverball.help" } )

	CPanel:AddControl( "ComboBox", { MenuButton = 1, Folder = "hoverball", Options = { [ "#preset.default" ] = ConVarsDefault }, CVars = table.GetKeys( ConVarsDefault ) } )

	CPanel:AddControl( "Numpad", { Label = "#tool.hoverball.up", Command = "hoverball_keyup", Label2 = "#tool.hoverball.down", Command2 = "hoverball_keydn" } )
	CPanel:AddControl( "Slider", { Label = "#tool.hoverball.speed", Command = "hoverball_speed", Type = "Float", Min = 0, Max = 20, Help = true } )
	CPanel:AddControl( "Slider", { Label = "#tool.hoverball.resistance", Command = "hoverball_resistance", Type = "Float", Min = 0, Max = 10, Help = true } )
	CPanel:AddControl( "Slider", { Label = "#tool.hoverball.strength", Command = "hoverball_strength", Type = "Float", Min = 0.1, Max = 10, Help = true } )

	CPanel:AddControl( "PropSelect", { Label = "#tool.hoverball.model", ConVar = "hoverball_model", Models = list.Get( "HoverballModels" ), Height = 0 } )

end

list.Set( "HoverballModels", "models/dav0r/hoverball.mdl", {} )
list.Set( "HoverballModels", "models/maxofs2d/hover_basic.mdl", {} )
list.Set( "HoverballModels", "models/maxofs2d/hover_classic.mdl", {} )
list.Set( "HoverballModels", "models/maxofs2d/hover_plate.mdl", {} )
list.Set( "HoverballModels", "models/maxofs2d/hover_propeller.mdl", {} )
list.Set( "HoverballModels", "models/maxofs2d/hover_rings.mdl", {} )


text:
package com.packtpub.e4.clock.ui;

import java.time.ZoneId;
import java.time.ZonedDateTime;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;

public class ClockWidget extends Canvas {
	private final Color color;
	private ZoneId zone = ZoneId.systemDefault();

	public ClockWidget(Composite parent, int style, RGB rgb) {
		super(parent, style);
		this.color = new Color(parent.getDisplay(), rgb);
		addDisposeListener(e -> color.dispose());
		addPaintListener(this::drawClock);
		Runnable redraw = () -> {
			while (!this.isDisposed()) {
				this.getDisplay().asyncExec(() -> this.redraw());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					return;
				}

			}
		};
		new Thread(redraw, "TickTock").start();
	}

	private void drawClock(PaintEvent e) {
		e.gc.drawArc(e.x, e.y, e.width - 1, e.height - 1, 0, 360);
		ZonedDateTime now = ZonedDateTime.now(zone);
		int seconds = now.getSecond();
		int arc = (15 - seconds) * 6 % 360;
		if (handColor == null) {
			e.gc.setBackground(color);
		} else {
			e.gc.setBackground(handColor);
		}
		e.gc.fillArc(e.x, e.y, e.width - 1, e.height - 1, arc - 1, 2);
		e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_BLACK));
		int hours = now.getHour();
		arc = (3 - hours) * 30 % 360;
		e.gc.fillArc(e.x, e.y, e.width - 1, e.height - 1, arc - 5, 10);
	}

	@Override
	public Point computeSize(int w, int h, boolean changed) {
		int size;
		if (w == SWT.DEFAULT) {
			size = h;
		} else if (h == SWT.DEFAULT) {
			size = w;
		} else {
			size = Math.min(w, h);
		}
		if (size == SWT.DEFAULT) {
			size = 50;
		}
		return new Point(size, size);
	}

	public void setZone(ZoneId zone) {
		this.zone = zone;
	}

	// This does not work - add a dispose listener instead
	// @Override
	// public void dispose() {
	// if (color != null && !color.isDisposed())
	// color.dispose();
	// super.dispose();
	// }

	private Color handColor;

	public Color getHandColor() {
		if (handColor == null) {
			return color;
		} else {
			return handColor;
		}
	}

	public void setHandColor(Color color) {
		handColor = color;
	}
}


text:
import { IRemove } from "../../../../Interfaces/Options/Interactivity/Modes/IRemove";
import { RecursivePartial } from "../../../../Types/RecursivePartial";
export declare class Remove implements IRemove {
    /**
     *
     * @deprecated this property is obsolete, please use the new quantity
     */
    get particles_nb(): number;
    /**
     *
     * @deprecated this property is obsolete, please use the new quantity
     * @param value
     */
    set particles_nb(value: number);
    quantity: number;
    constructor();
    load(data?: RecursivePartial<IRemove>): void;
}