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 org.flowable.ldap;

import java.text.MessageFormat;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Rdn;

import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class with overridable methods that are called when doing the calls to the ldap system. You can extend this class and plug it into the {@link LDAPConfiguration} if the default queries are inadequate
 * for your use case.
 *
 * @author Joram Barrez
 */
public class LDAPQueryBuilder {

    protected static final Logger LOGGER = LoggerFactory.getLogger(LDAPQueryBuilder.class);

    public String buildQueryByUserId(LDAPConfiguration ldapConfigurator, String userId) {
        String searchExpression = null;
        if (ldapConfigurator.getQueryUserByUserId() != null) {
            searchExpression = MessageFormat.format(ldapConfigurator.getQueryUserByUserId(), userId);
        } else {
            searchExpression = userId;
        }
        return searchExpression;
    }

    public String buildQueryGroupsForUser(final LDAPConfiguration ldapConfigurator, final String userId) {
        String searchExpression = null;
        if (ldapConfigurator.getQueryGroupsForUser() != null) {

            // Fetch the dn of the user
            LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
            String userDn = ldapTemplate.execute(new LDAPCallBack<String>() {

                @Override
                public String executeInContext(InitialDirContext initialDirContext) {

                    String userDnSearch = buildQueryByUserId(ldapConfigurator, userId);
                    try {
                        String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
                        NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, userDnSearch, createSearchControls(ldapConfigurator));
                        while (namingEnum.hasMore()) { // Should be only one
                            SearchResult result = (SearchResult) namingEnum.next();
                            return result.getNameInNamespace();
                        }
                        namingEnum.close();
                    } catch (NamingException e) {
                        LOGGER.debug("Could not find user dn : {}", e.getMessage(), e);
                    }
                    return null;
                }

            });

            searchExpression = MessageFormat.format(ldapConfigurator.getQueryGroupsForUser(), Rdn.escapeValue(userDn));

        } else {
            searchExpression = userId;
        }
        return searchExpression;
    }

    public String buildQueryByFullNameLike(final LDAPConfiguration ldapConfigurator, String searchText) {
        String searchExpression = null;
        if (ldapConfigurator.getQueryUserByFullNameLike() != null) {
            searchExpression = MessageFormat.format(ldapConfigurator.getQueryUserByFullNameLike(), ldapConfigurator.getUserFirstNameAttribute(), searchText, ldapConfigurator.getUserLastNameAttribute(),
                    searchText);
        } else {
            throw new FlowableIllegalArgumentException("No 'queryUserByFullNameLike' configured");
        }
        return searchExpression;
    }

    protected SearchControls createSearchControls(LDAPConfiguration ldapConfigurator) {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
        return searchControls;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package se.ericthelin.fractions;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GreatestCommonDivisorTest {

	@Test
	public void returnsFirstWhenSecondIsZero() {
		assertThat(GreatestCommonDivisor.of(6, 0), is(6));
	}

	@Test
	public void returnsSecondWhenFirstIsZero() {
		assertThat(GreatestCommonDivisor.of(0, 4), is(4));
	}

	@Test
	public void returnsGreatestCommonDivisorOfFirstAndSecond() {
		assertThat(GreatestCommonDivisor.of(6, 4), is(2));
	}

	@Test
	public void acceptsArgumentsInReverseOrder() {
		assertThat(GreatestCommonDivisor.of(4, 6), is(2));
	}

	@Test
	public void acceptsNegativeFirstArgument() {
		assertThat(GreatestCommonDivisor.of(-6, 4), is(-2));
	}

	@Test
	public void acceptsNegativeSecondArgument() {
		assertThat(GreatestCommonDivisor.of(6, -4), is(2));
	}

	@Test
	public void acceptsBothArgumentsNegative() {
		assertThat(GreatestCommonDivisor.of(-6, -4), is(-2));
	}

	@Test
	public void canComputeGreatestCommonDivisorOfLargeArguments() {
		assertThat(GreatestCommonDivisor.of(1071, 462), is(21));
	}
}


text:
.StationDetails {
  display: flex;
  flex-direction: column;
  margin: 16px 16px 0;
}


text:
.. _config_thrift_filters_router:

Router
======

The router filter implements Thrift forwarding. It will be used in almost all Thrift proxying
scenarios. The filter's main job is to follow the instructions specified in the configured
:ref:`route table <envoy_api_msg_config.filter.network.thrift_proxy.v2alpha1.RouteConfiguration>`.

* :ref:`v2 API reference <envoy_api_msg_config.filter.thrift.router.v2alpha1.Router>`
* This filter should be configured with the name *envoy.filters.thrift.router*.


text:
package seedu.address.storage;

import java.io.IOException;
import java.util.Optional;

import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.model.UserPrefs;

/**
 * Represents a storage for {@link seedu.address.model.UserPrefs}.
 */
public interface UserPrefsStorage {

    /**
     * Returns the file path of the UserPrefs data file.
     */
    String getUserPrefsFilePath();

    /**
     * Returns UserPrefs data from storage.
     *   Returns {@code Optional.empty()} if storage file is not found.
     * @throws DataConversionException if the data in storage is not in the expected format.
     * @throws IOException if there was any problem when reading from the storage.
     */
    Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException;

    /**
     * Saves the given {@link seedu.address.model.UserPrefs} to the storage.
     * @param userPrefs cannot be null.
     * @throws IOException if there was any problem writing to the file.
     */
    void saveUserPrefs(UserPrefs userPrefs) throws IOException;

}


text:
package R2;

// Author: Ian Taylor

import R2.Trans.Commands.BuyEquityCommand;
import R2.Trans.Commands.SellEquityCommand;
import R2.Trans.Transaction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class Portfolio {

    private String name = "";
    private Date dateCreated = new Date();
    private ArrayList<Equity> equities = new ArrayList<Equity>();
    private ArrayList<Account> accounts = new ArrayList<Account>();
    private int id = IdGenorator.getInstance().getNewId();
    private Transaction history;
    private User user;

    public Portfolio(User user, String name) {
	this.name = name;
	this.user = user;
    }

    public int getId() { return this.id; }
    public User getUser() { return this.user; }
    public Transaction getTransaction() { return this.history; }
    public Date getDate() { return this.dateCreated;  }
    public ArrayList<Equity> getEquities() { return this.equities; }
    public ArrayList<Account> getAccounts() { return this.accounts; }

    // this might be in the wrong place...
    public boolean validatePassword(String entered_password) {
	if (entered_password == getUser().getPassword())
	    return true;
	else
	    return false;
    }

    // (for both below) returns empty string iff the transaction was undone successfully.
    public String undoTransaction() {
	return "";
    }
    public String performTransaction() {
	return "";
    }

    // Searches for the equity by ticker symbol. Then removes it from watched by either setting it to false
    // and/or removing it from the list of equities completely.
    public boolean removeWatchedEquity(String ticker) {
	for(Equity equity : this.equities) {
	    if(equity.getTicker() == ticker && equity.isWatched == true) {
		equity.isWatched = false;
		if(equity.getOwned() == 0) {
		    this.equities.remove(equity);
		}
		return true;
	    }
	}
	return false;
    }

    // sets a new equity's isWatched to true and creates it if necessary.
    public boolean addWatchedEquity(String ticker) throws IOException {
	for(Equity equity : this.equities) {
	    if(equity.getTicker() == ticker) {
		equity.isWatched = true;
		return true;
	    }
	}
        if(Woolie.getInfoByTicker(ticker) != null) {
	    Equity newEquity = new Equity(ticker, 0, 0); // NEED TO FIGURE OUT HOW and when to update the numbers...
	    // should update by itself though...
	    equities.add(newEquity);
	    newEquity.isWatched = true;
	    return true;
	}
	return false;
    }

    public boolean buyEquity(Equity equity, int number, Account account) {
	try {
	    BuyEquityCommand buy = new BuyEquityCommand(account, equity, number, this.history);
	    buy.execute();
	    this.equities.add(equity);
	} catch (Exception e) {
	    return false;
	}
	return true;
    }
    public boolean sellEquity(Equity equity, int number, Account account) {
	try {
	    SellEquityCommand sell = new SellEquityCommand(account, equity, number, this.history);
	    sell.execute();
	    if(!equity.isWatched) {
		this.equities.remove(equity);
	    }
	} catch(Exception e) {
	    return false;
	}
	return true;
    }

    // Deposits money in a specified account.
    public boolean depositInAccount(String name, double amount) {
	for(Account account : this.accounts) {
	    if(account.getName() == name) {
		account.deposit(amount);
		return true;
	    }
	}
	return false;
    }
    // Withdraws money from a specified account.
    public boolean withdrawFromAccount(String name, double amount) {
	for(Account account : this.accounts) {
	    if(account.getName() == name) {
		double check = account.withdraw(amount);
		if(check == -1)
		    return false;
		else
		    return true;
	    }
	}
	return false;
    }

	/*
    public ArrayList<Equity> simulateMarket(int choice) {
	if(choice == 1) {
	    return simulated;
	} else if(choice == 2) {
	    return simulated;
	} else if(choice == 3) {
	    return simulated;
	}
	return null;
    }
	*/

    // These are done dead last.
    public Portfolio importPortfolio() {return null;}
    public String exportPortfolio() {return null;}

    // Adds an account to accounts.
    public void addAccount(String name, double balance) {
	this.accounts.add(new Account(name, balance));
    }
    public boolean removeAccount(String name) {
	for(Account account : this.accounts) {
	    if(account.getName() == name) {
		accounts.remove(account);
		return true;
	    }
	}
	return false;
    }

}


text:
package org.missinglink.ant.task.http.server;

import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;

import org.missinglink.ant.task.http.AbstractTest;
import org.missinglink.http.encoding.Base64;
import org.missinglink.tools.StreamUtils;

public abstract class AbstractHttpServerTest extends AbstractTest {

  protected static final String PING_CONTEXT = "/ping";
  protected static final String PING_RESPONSE = "pong?";

  protected static final String ECHO_CONTEXT = "/echo";
  protected static final String ECHO_TEXT = "text";

  protected static final String INTERNAL_SERER_ERROR_CONTEXT = "/500";
  protected static final String INTERNAL_SERER_ERROR_RESPONSE = "Internal Server Error";

  protected static final String SECURE_CONTEXT = "/secure";

  protected static final String USERNAME = "user";
  protected static final String PASSWORD = "password";

  protected static final String HW_ZIP_CONTEXT = "/hwzip";
  protected static final String HW_PNG_CONTEXT = "/hwpng";

  protected static final String HW_ZIP = "hw.zip";
  protected static final String HW_PNG = "hw.png";

  protected int httpServerPort = 10080;
  protected int httpsServerPort = 10443;

  protected HttpServer httpServer;
  protected HttpsServer httpsServer;

  protected AbstractHttpServerTest() {
    super();
  }

  protected void stopHttpServer() {
    httpServer.stop(0);
  }

  protected void stopHttpsServer() {
    httpsServer.stop(0);
  }

  protected void startHttpServer() throws IOException {
    final InetSocketAddress addr = new InetSocketAddress(httpServerPort);
    httpServer = HttpServer.create(addr, 0);
    httpServer.setExecutor(Executors.newCachedThreadPool());
    attachHttpHandlers(httpServer);
    httpServer.start();
  }

  protected void startHttpsServer() throws Exception {
    final InetSocketAddress addr = new InetSocketAddress(httpsServerPort);
    httpsServer = HttpsServer.create(addr, 0);
    httpsServer.setExecutor(Executors.newCachedThreadPool());
    attachHttpHandlers(httpsServer);

    final char[] passphrase = "password".toCharArray();
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(getClass().getResourceAsStream("/keystore.jks"), passphrase);

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, passphrase);

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    httpsServer.setHttpsConfigurator(new HttpsConfigurator(ssl) {
      @Override
      public void configure(final HttpsParameters params) {
        final SSLContext c = getSSLContext();
        final SSLParameters sslparams = c.getDefaultSSLParameters();
        params.setSSLParameters(sslparams);
      }
    });

    httpsServer.start();
  }

  protected void attachHttpHandlers(final HttpServer server) {

    // ping handler
    server.createContext(PING_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(200, PING_RESPONSE.getBytes().length);
        exchange.getResponseBody().write(PING_RESPONSE.getBytes());
        exchange.getResponseBody().close();
      }
    });

    // secure ping handler
    final HttpContext securePingContext = server.createContext(SECURE_CONTEXT + PING_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(200, PING_RESPONSE.getBytes().length);
        exchange.getResponseBody().write(PING_RESPONSE.getBytes());
        exchange.getResponseBody().close();
      }
    });
    securePingContext.setAuthenticator(getBasicAuthenticator());

    // echo handler
    server.createContext(ECHO_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        String responseEntity = "";
        if ("POST".equalsIgnoreCase(exchange.getRequestMethod()) || "PUT".equalsIgnoreCase(exchange.getRequestMethod())) {
          responseEntity = StreamUtils.inputStreamToString(exchange.getRequestBody());
        } else if ("GET".equalsIgnoreCase(exchange.getRequestMethod())) {
          responseEntity = getQueryParams(exchange.getRequestURI()).get(ECHO_TEXT);
        }
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(200, responseEntity.getBytes().length);
        writeEntity(exchange, responseEntity);
        exchange.close();
      }

      protected void writeEntity(final HttpExchange httpExchange, final String entity) throws IOException {
        httpExchange.getResponseBody().write(entity.getBytes());
      }
    });

    // secure echo handler
    final HttpContext secureEchoContext = server.createContext(SECURE_CONTEXT + ECHO_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        String responseEntity = "";
        if ("POST".equalsIgnoreCase(exchange.getRequestMethod()) || "PUT".equalsIgnoreCase(exchange.getRequestMethod())) {
          responseEntity = StreamUtils.inputStreamToString(exchange.getRequestBody());
        } else if ("GET".equalsIgnoreCase(exchange.getRequestMethod())) {
          responseEntity = getQueryParams(exchange.getRequestURI()).get(ECHO_TEXT);
        }
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(200, responseEntity.getBytes().length);
        writeEntity(exchange, responseEntity);
        exchange.close();
      }

      protected void writeEntity(final HttpExchange httpExchange, final String entity) throws IOException {
        httpExchange.getResponseBody().write(entity.getBytes());
      }
    });
    secureEchoContext.setAuthenticator(getBasicAuthenticator());

    // 500 handler
    server.createContext(INTERNAL_SERER_ERROR_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(500, INTERNAL_SERER_ERROR_RESPONSE.getBytes().length);
        exchange.getResponseBody().write(INTERNAL_SERER_ERROR_RESPONSE.getBytes());
        exchange.getResponseBody().close();
      }
    });

    // secure 500 handler
    final HttpContext secure500Context = server.createContext(SECURE_CONTEXT + INTERNAL_SERER_ERROR_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(500, INTERNAL_SERER_ERROR_RESPONSE.getBytes().length);
        exchange.getResponseBody().write(INTERNAL_SERER_ERROR_RESPONSE.getBytes());
        exchange.getResponseBody().close();
      }
    });
    secure500Context.setAuthenticator(getBasicAuthenticator());

    // hw zip handler
    server.createContext(HW_ZIP_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        final InputStream is = getClass().getResourceAsStream(HW_ZIP);
        final byte[] bytes = StreamUtils.inputStreamToByteArray(is);
        exchange.getResponseHeaders().set("Content-Type", "application/zip");
        exchange.sendResponseHeaders(200, bytes.length);
        exchange.getResponseBody().write(bytes);
        exchange.getResponseBody().close();
      }
    });

    // secure hw zip handler
    final HttpContext hwZipContext = server.createContext(SECURE_CONTEXT + HW_ZIP_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        final InputStream is = getClass().getResourceAsStream(HW_ZIP);
        final byte[] bytes = StreamUtils.inputStreamToByteArray(is);
        exchange.getResponseHeaders().set("Content-Type", "application/zip");
        exchange.sendResponseHeaders(200, bytes.length);
        exchange.getResponseBody().write(bytes);
        exchange.getResponseBody().close();
      }
    });
    hwZipContext.setAuthenticator(getBasicAuthenticator());

    // hw png handler
    server.createContext(HW_PNG_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        final InputStream is = getClass().getResourceAsStream(HW_PNG);
        final byte[] bytes = StreamUtils.inputStreamToByteArray(is);
        exchange.getResponseHeaders().set("Content-Type", "image/png");
        exchange.sendResponseHeaders(200, bytes.length);
        exchange.getResponseBody().write(bytes);
        exchange.getResponseBody().close();
      }
    });

    // secure hw png handler
    final HttpContext hwPngContext = server.createContext(SECURE_CONTEXT + HW_PNG_CONTEXT, new HttpHandler() {
      @Override
      public void handle(final HttpExchange exchange) throws IOException {
        final InputStream is = getClass().getResourceAsStream(HW_PNG);
        final byte[] bytes = StreamUtils.inputStreamToByteArray(is);
        exchange.getResponseHeaders().set("Content-Type", "image/png");
        exchange.sendResponseHeaders(200, bytes.length);
        exchange.getResponseBody().write(bytes);
        exchange.getResponseBody().close();
      }
    });
    hwPngContext.setAuthenticator(getBasicAuthenticator());
  }

  protected Map<String, String> getQueryParams(final URI uri) throws UnsupportedEncodingException {
    final Map<String, String> map = new HashMap<String, String>();
    if (null != uri.getQuery() && uri.getQuery().length() > 0) {
      final String[] params = uri.getQuery().split("&");
      for (final String param : params) {
        final String[] pair = param.split("=");
        map.put(pair[0], pair.length > 1 ? URLDecoder.decode(pair[1], "UTF-8") : null);
      }
    }
    return map;
  }

  protected String getHttpServerUri() {
    return "http://localhost:" + httpServerPort;
  }

  protected String getHttpsServerUri() {
    return "https://localhost:" + httpsServerPort;
  }

  // protected String readHttpURL(final URL url) throws IOException {
  // final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  // return StreamUtils.inputStreamToString(conn.getInputStream());
  // }

  protected void attachSSLSocketFactory(final HttpsURLConnection conn) throws Exception {

    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(getClass().getResourceAsStream("/keystore.jks"), "password".toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(null, tmf.getTrustManagers(), null);

    conn.setSSLSocketFactory(ssl.getSocketFactory());
  }

  protected BasicAuthenticator getBasicAuthenticator() {
    return new BasicAuthenticator("Test Realm") {
      @Override
      public boolean checkCredentials(final String username, final String password) {
        if (USERNAME.equals(username) && PASSWORD.equals(password)) {
          return true;
        }
        return false;
      }
    };
  }

  protected void addAuthenticationHeader(final HttpURLConnection con) {
    final String userpass = USERNAME + ":" + PASSWORD;
    final String basicAuth = "Basic " + new String(Base64.encodeBytes(userpass.getBytes()));
    con.setRequestProperty("Authorization", basicAuth);
  }

  protected HttpURLConnection createAndWriteToHttpURLConnection(final String method, final String path, final String entity, final boolean auth) throws IOException {
    final URL url = new URL(path);

    final HttpURLConnection con = (HttpURLConnection) url.openConnection();

    if (auth) {
      addAuthenticationHeader(con);
    }

    con.setRequestMethod(method);
    con.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    out.write(entity);
    out.close();
    return con;
  }

  protected HttpsURLConnection createAndWriteToHttpsURLConnection(final String method, final String path, final String entity, final boolean auth) throws Exception {
    final URL url = new URL(path);

    final HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

    if (auth) {
      addAuthenticationHeader(con);
    }

    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(getClass().getResourceAsStream("/keystore.jks"), "password".toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(null, tmf.getTrustManagers(), null);

    con.setSSLSocketFactory(ssl.getSocketFactory());

    con.setRequestMethod(method);
    con.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    out.write(entity);
    out.close();
    return con;
  }
}


text:
import numpy as np
from .dtype import img_as_float

__all__ = ['random_noise']

def random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs):
    """
    Function to add random noise of various types to a floating-point image.

    Parameters
    ----------
    image : ndarray
        Input image data. Will be converted to float.
    mode : str
        One of the following strings, selecting the type of noise to add:

        - 'gaussian'  Gaussian-distributed additive noise.
        - 'localvar'  Gaussian-distributed additive noise, with specified
                      local variance at each point of `image`
        - 'poisson'   Poisson-distributed noise generated from the data.
        - 'salt'      Replaces random pixels with 1.
        - 'pepper'    Replaces random pixels with 0 (for unsigned images) or
                      -1 (for signed images).
        - 's&p'       Replaces random pixels with either 1 or `low_val`, where
                      `low_val` is 0 for unsigned images or -1 for signed
                      images.
        - 'speckle'   Multiplicative noise using out = image + n*image, where
                      n is uniform noise with specified mean & variance.
    seed : int
        If provided, this will set the random seed before generating noise,
        for valid pseudo-random comparisons.
    clip : bool
        If True (default), the output will be clipped after noise applied
        for modes `'speckle'`, `'poisson'`, and `'gaussian'`. This is
        needed to maintain the proper image data range. If False, clipping
        is not applied, and the output may extend beyond the range [-1, 1].
    mean : float
        Mean of random distribution. Used in 'gaussian' and 'speckle'.
        Default : 0.
    var : float
        Variance of random distribution. Used in 'gaussian' and 'speckle'.
        Note: variance = (standard deviation) ** 2. Default : 0.01
    local_vars : ndarray
        Array of positive floats, same shape as `image`, defining the local
        variance at every image point. Used in 'localvar'.
    amount : float
        Proportion of image pixels to replace with noise on range [0, 1].
        Used in 'salt', 'pepper', and 'salt & pepper'. Default : 0.05
    salt_vs_pepper : float
        Proportion of salt vs. pepper noise for 's&p' on range [0, 1].
        Higher values represent more salt. Default : 0.5 (equal amounts)

    Returns
    -------
    out : ndarray
        Output floating-point image data on range [0, 1] or [-1, 1] if the
        input `image` was unsigned or signed, respectively.

    Notes
    -----
    Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside
    the valid image range. The default is to clip (not alias) these values,
    but they may be preserved by setting `clip=False`. Note that in this case
    the output may contain values outside the ranges [0, 1] or [-1, 1].
    Use this option with care.

    Because of the prevalence of exclusively positive floating-point images in
    intermediate calculations, it is not possible to intuit if an input is
    signed based on dtype alone. Instead, negative values are explicity
    searched for. Only if found does this function assume signed input.
    Unexpected results only occur in rare, poorly exposes cases (e.g. if all
    values are above 50 percent gray in a signed `image`). In this event,
    manually scaling the input to the positive domain will solve the problem.

    The Poisson distribution is only defined for positive integers. To apply
    this noise type, the number of unique values in the image is found and
    the next round power of two is used to scale up the floating-point result,
    after which it is scaled back down to the floating-point image range.

    To generate Poisson noise against a signed image, the signed image is
    temporarily converted to an unsigned image in the floating point domain,
    Poisson noise is generated, then it is returned to the original range.

    """
    mode = mode.lower()

    # Detect if a signed image was input
    if image.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.

    image = img_as_float(image)
    if seed is not None:
        np.random.seed(seed=seed)

    allowedtypes = {
        'gaussian': 'gaussian_values',
        'localvar': 'localvar_values',
        'poisson': 'poisson_values',
        'salt': 'sp_values',
        'pepper': 'sp_values',
        's&p': 's&p_values',
        'speckle': 'gaussian_values'}

    kwdefaults = {
        'mean': 0.,
        'var': 0.01,
        'amount': 0.05,
        'salt_vs_pepper': 0.5,
        'local_vars': np.zeros_like(image) + 0.01}

    allowedkwargs = {
        'gaussian_values': ['mean', 'var'],
        'localvar_values': ['local_vars'],
        'sp_values': ['amount'],
        's&p_values': ['amount', 'salt_vs_pepper'],
        'poisson_values': []}

    for key in kwargs:
        if key not in allowedkwargs[allowedtypes[mode]]:
            raise ValueError('%s keyword not in allowed keywords %s' %
                             (key, allowedkwargs[allowedtypes[mode]]))

    # Set kwarg defaults
    for kw in allowedkwargs[allowedtypes[mode]]:
        kwargs.setdefault(kw, kwdefaults[kw])

    if mode == 'gaussian':
        noise = np.random.normal(kwargs['mean'], kwargs['var'] ** 0.5,
                                 image.shape)
        out = image + noise

    elif mode == 'localvar':
        # Ensure local variance input is correct
        if (kwargs['local_vars'] <= 0).any():
            raise ValueError('All values of `local_vars` must be > 0.')

        # Safe shortcut usage broadcasts kwargs['local_vars'] as a ufunc
        out = image + np.random.normal(0, kwargs['local_vars'] ** 0.5)

    elif mode == 'poisson':
        # Determine unique values in image & calculate the next power of two
        vals = len(np.unique(image))
        vals = 2 ** np.ceil(np.log2(vals))

        # Ensure image is exclusively positive
        if low_clip == -1.:
            old_max = image.max()
            image = (image + 1.) / (old_max + 1.)

        # Generating noise for each unique value in image.
        out = np.random.poisson(image * vals) / float(vals)

        # Return image to original range if input was signed
        if low_clip == -1.:
            out = out * (old_max + 1.) - 1.

    elif mode == 'salt':
        # Re-call function with mode='s&p' and p=1 (all salt noise)
        out = random_noise(image, mode='s&p', seed=seed,
                           amount=kwargs['amount'], salt_vs_pepper=1.)

    elif mode == 'pepper':
        # Re-call function with mode='s&p' and p=1 (all pepper noise)
        out = random_noise(image, mode='s&p', seed=seed,
                           amount=kwargs['amount'], salt_vs_pepper=0.)

    elif mode == 's&p':
        out = image.copy()
        p = kwargs['amount']
        q = kwargs['salt_vs_pepper']
        flipped = np.random.choice([True, False], size=image.shape,
                                   p=[p, 1 - p])
        salted = np.random.choice([True, False], size=image.shape,
                                  p=[q, 1 - q])
        peppered = ~salted
        out[flipped & salted] = 1
        out[flipped & peppered] = low_clip

    elif mode == 'speckle':
        noise = np.random.normal(kwargs['mean'], kwargs['var'] ** 0.5,
                                 image.shape)
        out = image + image * noise

    # Clip back to original range, if necessary
    if clip:
        out = np.clip(out, low_clip, 1.0)

    return out


text:
Write-Output "Loading Shaun Luttin's Profile"

# https://ss64.com/ps/syntax-functions.html

$FILE_STORAGE_ROOT = 'C:/dev/shaunluttin/happiness/';

function prompt {
  $currentDir = Split-Path -leaf -path (Get-Location)
  "$currentDir$ "
}

function Use-MediaValetSettings {
  # Import MediaValet specific modules.
  C:\dev\mediaValet\MediaValet.Learning\entropy\DamShell\Import-MvDamShell.ps1

  # Stop KillerController, because it breaks git remote communication.
  Get-Process -name Killer* | Stop-Process -Force
}

function Convert-MarkdownToOdt {
    param([string]$absoluteFilePath)

    if(-not (Test-Path $absoluteFilePath)) {
        Write-Output "$($absoluteFilePath) does not exist."
        return
    }

    $destination = [io.path]::ChangeExtension($absoluteFilePath, "odt")

    pandoc $absoluteFilePath -f markdown -t odt -o $destination
}

function Prepend-Content {
    param([string]$Content, [string]$Path, [Switch]$Open)

    # The following machinery lets us *prepend* an item effeciently to a file.
    $tempFile = "$FILE_STORAGE_ROOT/temp.txt";

    $line | Set-Content $tempFile;

    if(Test-Path $Path) {
      Get-Content $Path | Add-Content $tempFile;
      Remove-Item $Path;
    }

    Rename-Item $tempFile $Path;

    if($Open)
    {
      vim $Path;
    } else
    {
      Write-Output $Path;
      Write-Output $line;
    }
}

function Add-Distraction {
    param([string]$Description, [Switch]$Open)

    # Text to add
    $moment = Get-Date -format "MMM yyyy";
    $line = "* [ ] ($moment) $Description";

    Prepend-Content `
        -Content $line `
        -Path "$FILE_STORAGE_ROOT/distractions.md" `
        -Open:$Open
}

function Start-Pompo {
    param([string]$Description, [Switch]$Open)

    # Text to add
    $moment = Get-Date -format "MMM yyyy @ hh:mm";
    $line = "Start: ($moment) $Description";

    Prepend-Content `
      -Content $line `
      -Path "$FILE_STORAGE_ROOT/pompos.md" `
      -Open:$Open
}

function Stop-Pompo {
    param([Switch]$Open)

    $lastPompo = Get-Content -Path "$FILE_STORAGE_ROOT/pompos.md" -TotalCount 1;

    $now = Get-Date;
    $timestamp = $now.ToString("MMM yyyy @ hh:mm");

    $duration;
    if($lastPompo -match "\(.*\)") {
        $lastTimestamp = [datetime]::ParseExact($matches[0], "(MMM yyyy @ hh:mm)", $null);
        $duration = $now - $lastTimestamp;
    }

    $line = "Stop: ($timestamp) $duration";

    Prepend-Content `
      -Content $line `
      -Path "$FILE_STORAGE_ROOT/pompos.md" `
      -Open:$Open
}

# Chocolatey profile
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
  Import-Module "$ChocolateyProfile"
}

Use-MediaValetSettings;

Import-Module Posh-Git;


text:
% Macros for The TeXbook

\catcode`@=11 % borrow the private macros of PLAIN (with care)

\font\tentex=cmtex10

\font\inchhigh=cminch
\font\titlefont=cmssdc10 at 40pt

\font\ninerm=cmr9
\font\eightrm=cmr8
\font\sixrm=cmr6

\font\ninei=cmmi9
\font\eighti=cmmi8
\font\sixi=cmmi6
\skewchar\ninei='177 \skewchar\eighti='177 \skewchar\sixi='177

\font\ninesy=cmsy9
\font\eightsy=cmsy8
\font\sixsy=cmsy6
\skewchar\ninesy='60 \skewchar\eightsy='60 \skewchar\sixsy='60

\font\eightss=cmssq8

\font\eightssi=cmssqi8

\font\ninebf=cmbx9
\font\eightbf=cmbx8
\font\sixbf=cmbx6

\font\ninett=cmtt9
\font\eighttt=cmtt8

\hyphenchar\tentt=-1 % inhibit hyphenation in typewriter type
\hyphenchar\ninett=-1
\hyphenchar\eighttt=-1

\font\ninesl=cmsl9
\font\eightsl=cmsl8

\font\nineit=cmti9
\font\eightit=cmti8

\font\tenu=cmu10 % unslanted text italic
\font\magnifiedfiverm=cmr5 at 10pt
\font\manual=manfnt % font used for the METAFONT logo, etc.
\font\cmman=cmman % font used for miscellaneous Computer Modern variations

\newskip\ttglue
\def\tenpoint{\def\rm{\fam0\tenrm}%
  \textfont0=\tenrm \scriptfont0=\sevenrm \scriptscriptfont0=\fiverm
  \textfont1=\teni \scriptfont1=\seveni \scriptscriptfont1=\fivei
  \textfont2=\tensy \scriptfont2=\sevensy \scriptscriptfont2=\fivesy
  \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex
  \def\it{\fam\itfam\tenit}%
  \textfont\itfam=\tenit
  \def\sl{\fam\slfam\tensl}%
  \textfont\slfam=\tensl
  \def\bf{\fam\bffam\tenbf}%
  \textfont\bffam=\tenbf \scriptfont\bffam=\sevenbf
   \scriptscriptfont\bffam=\fivebf
  \def\tt{\fam\ttfam\tentt}%
  \textfont\ttfam=\tentt
  \tt \ttglue=.5em plus.25em minus.15em
  \normalbaselineskip=12pt
  \def\MF{{\manual META}\-{\manual FONT}}%
  \let\sc=\eightrm
  \let\big=\tenbig
  \setbox\strutbox=\hbox{\vrule height8.5pt depth3.5pt width\z@}%
  \normalbaselines\rm}

\def\ninepoint{\def\rm{\fam0\ninerm}%
  \textfont0=\ninerm \scriptfont0=\sixrm \scriptscriptfont0=\fiverm
  \textfont1=\ninei \scriptfont1=\sixi \scriptscriptfont1=\fivei
  \textfont2=\ninesy \scriptfont2=\sixsy \scriptscriptfont2=\fivesy
  \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex
  \def\it{\fam\itfam\nineit}%
  \textfont\itfam=\nineit
  \def\sl{\fam\slfam\ninesl}%
  \textfont\slfam=\ninesl
  \def\bf{\fam\bffam\ninebf}%
  \textfont\bffam=\ninebf \scriptfont\bffam=\sixbf
   \scriptscriptfont\bffam=\fivebf
  \def\tt{\fam\ttfam\ninett}%
  \textfont\ttfam=\ninett
  \tt \ttglue=.5em plus.25em minus.15em
  \normalbaselineskip=11pt
  \def\MF{{\manual hijk}\-{\manual lmnj}}%
  \let\sc=\sevenrm
  \let\big=\ninebig
  \setbox\strutbox=\hbox{\vrule height8pt depth3pt width\z@}%
  \normalbaselines\rm}

\def\eightpoint{\def\rm{\fam0\eightrm}%
  \textfont0=\eightrm \scriptfont0=\sixrm \scriptscriptfont0=\fiverm
  \textfont1=\eighti \scriptfont1=\sixi \scriptscriptfont1=\fivei
  \textfont2=\eightsy \scriptfont2=\sixsy \scriptscriptfont2=\fivesy
  \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex
  \def\it{\fam\itfam\eightit}%
  \textfont\itfam=\eightit
  \def\sl{\fam\slfam\eightsl}%
  \textfont\slfam=\eightsl
  \def\bf{\fam\bffam\eightbf}%
  \textfont\bffam=\eightbf \scriptfont\bffam=\sixbf
   \scriptscriptfont\bffam=\fivebf
  \def\tt{\fam\ttfam\eighttt}%
  \textfont\ttfam=\eighttt
  \tt \ttglue=.5em plus.25em minus.15em
  \normalbaselineskip=9pt
  \def\MF{{\manual opqr}\-{\manual stuq}}%
  \let\sc=\sixrm
  \let\big=\eightbig
  \setbox\strutbox=\hbox{\vrule height7pt depth2pt width\z@}%
  \normalbaselines\rm}

\def\tenmath{\tenpoint\fam-1 } % use after $ in ninepoint sections
\def\tenbig#1{{\hbox{$\left#1\vbox to8.5pt{}\right.\n@space$}}}
\def\ninebig#1{{\hbox{$\textfont0=\tenrm\textfont2=\tensy
  \left#1\vbox to7.25pt{}\right.\n@space$}}}
\def\eightbig#1{{\hbox{$\textfont0=\ninerm\textfont2=\ninesy
  \left#1\vbox to6.5pt{}\right.\n@space$}}}

% Page layout
\newdimen\pagewidth \newdimen\pageheight \newdimen\ruleht
\hsize=29pc  \vsize=44pc  \maxdepth=2.2pt  \parindent=3pc
\pagewidth=\hsize \pageheight=\vsize \ruleht=.5pt
\abovedisplayskip=6pt plus 3pt minus 1pt
\belowdisplayskip=6pt plus 3pt minus 1pt
\abovedisplayshortskip=0pt plus 3pt
\belowdisplayshortskip=4pt plus 3pt

%\newinsert\footins
\def\footnote#1{\edef\@sf{\spacefactor\the\spacefactor}#1\@sf
      \insert\footins\bgroup\eightpoint
      \interlinepenalty100 \let\par=\endgraf
        \leftskip=\z@skip \rightskip=\z@skip
        \splittopskip=10pt plus 1pt minus 1pt \floatingpenalty=20000
        \smallskip\item{#1}\bgroup\strut\aftergroup\@foot\let\next}
\skip\footins=12pt plus 2pt minus 4pt % space added when footnote is present
%\count\footins=1000 % footnote magnification factor (1 to 1)
\dimen\footins=30pc % maximum footnotes per page

\newinsert\margin
\dimen\margin=\maxdimen
%\count\margin=0 \skip\margin=0pt % marginal inserts take up no space

\newif\iftitle
\def\titlepage{\global\titletrue} % for pages without headlines
\def\rhead{} % \rhead contains the running headline

\def\leftheadline{\hbox to \pagewidth{\spaceskip=0pt
    \vbox to 10pt{}% strut to position the baseline
    \llap{\tenbf\folio\kern1pc}% folio to left of text
    \tenit\rhead\hfil% running head flush left
    }}
\def\rightheadline{\hbox to \pagewidth{\spaceskip=0pt
    \vbox to 10pt{}% strut to position the baseline
    \hfil\tenit\rhead\/% running head flush right
    \rlap{\kern1pc\tenbf\folio}% folio to right of text
    }}

\def\onepageout#1{\shipout\vbox{ % here we define one page of output
    \offinterlineskip % butt the boxes together
    \vbox to 3pc{ % this part goes on top of the 44pc pages
      \iftitle % the next is used for title pages
        \global\titlefalse % reset the titlepage switch
        \setcornerrules % for camera alignment
      \else\ifodd\pageno \rightheadline\else\leftheadline\fi\fi
      \vfill} % this completes the \vbox to 3pc
    \vbox to \pageheight{
      \ifvoid\margin\else % marginal info is present
        \rlap{\kern31pc\vbox to\z@{\kern4pt\box\margin \vss}}\fi
      #1 % now insert the main information
      \ifvoid\footins\else % footnote info is present
        \vskip\skip\footins \kern-3pt
        \hrule height\ruleht width\pagewidth \kern-\ruleht \kern3pt
        \unvbox\footins\fi
      \boxmaxdepth=\maxdepth
      } % this completes the \vbox to \pageheight
    }
  \advancepageno}

\def\setcornerrules{\hbox to \pagewidth{\vrule width 1pc height\ruleht
    \hfil \vrule width 1pc}
  \hbox to \pagewidth{\llap{\sevenrm(page \folio)\kern1pc}%
    \vrule height1pc width\ruleht depth\z@
    \hfil \vrule width\ruleht depth\z@}}

\output{\onepageout{\unvbox255}}

\newbox\partialpage
\def\begindoublecolumns{\begingroup
  \output={\global\setbox\partialpage=\vbox{\unvbox255\bigskip}}\eject
  \output={\doublecolumnout} \hsize=14pc \vsize=89pc}
\def\enddoublecolumns{\output={\balancecolumns}\eject
  \endgroup \pagegoal=\vsize}

\def\doublecolumnout{\splittopskip=\topskip \splitmaxdepth=\maxdepth
  \dimen@=44pc \advance\dimen@ by-\ht\partialpage
  \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
  \onepageout\pagesofar
  \unvbox255 \penalty\outputpenalty}
\def\pagesofar{\unvbox\partialpage
  \wd0=\hsize \wd2=\hsize \hbox to\pagewidth{\box0\hfil\box2}}
\def\balancecolumns{\setbox0=\vbox{\unvbox255} \dimen@=\ht0
  \advance\dimen@ by\topskip \advance\dimen@ by-\baselineskip
  \divide\dimen@ by2 \splittopskip=\topskip
  {\vbadness=10000 \loop \global\setbox3=\copy0
    \global\setbox1=\vsplit3 to\dimen@
    \ifdim\ht3>\dimen@ \global\advance\dimen@ by1pt \repeat}
  \setbox0=\vbox to\dimen@{\unvbox1}
  \setbox2=\vbox to\dimen@{\unvbox3}
  \pagesofar}

% To produce only a subset of pages, put the page numbers on separate
% lines in a file called pages.tex
\let\Shipout=\shipout
\newread\pages \newcount\nextpage \openin\pages=pages
\def\getnextpage{\ifeof\pages\else
 {\endlinechar=-1\read\pages to\next
  \ifx\next\empty % in this case we should have eof now
  \else\global\nextpage=\next\fi}\fi}
\ifeof\pages\else\message{OK, I'll ship only the requested pages!}
 \getnextpage\fi
\def\shipout{\ifeof\pages\let\next=\Shipout
 \else\ifnum\pageno=\nextpage\getnextpage\let\next=\Shipout
  \else\let\next=\Tosspage\fi\fi \next}
\newbox\garbage \def\Tosspage{\deadcycles=0\setbox\garbage=}

% Chapter formatting
% The preface and table of contents are formatted in place, not here

\newcount\exno % for the number of exercises in the current chapter
\newcount\subsecno % for the number of subsections in the current chapter

\def\beginchapter#1 #2#3. #4\par{\global\exno=0
  \subsecno=0
  \def\chapno{#2#3}
  \ifodd\pageno
    \errmessage{You had too much text on that last page; I'm backing up}
    \advance\pageno by-1 \fi
  \titlepage
  \def\\{ } % \\'s in the title will be treated as spaces
  \message{#1 #2#3:} % show the chapter title on the terminal
  \def\MF{{\manual 89:;<=>:}} % slant the logo
  \xdef\rhead{#1 #2#3: #4\unskip}
  {\def\TeX{T\kern-.2em\lower.5ex\hbox{E}\kern-.06em X}
    \def\MF{{\vbox to30pt{}\manual ()*+,-.*}}
    \def\\{#3} \advance\hsize by -18mm
    \ifx\empty\\ \rightline{\inchhigh #2\kern-.04em}
    \else\rightline{\inchhigh #2\kern-.06em#3\kern-.04em}\fi
    \vskip 1.75pc
    \baselineskip 36pt \lineskiplimit \titlelsl \lineskip 12pt
    \let\\=\cr % now the \\'s are line dividers
    \halign{\line{\titlefont\hss##}\\#4\unskip\\}
    \vfill\eject} % output the chapter title page
  \tenpoint
  \noindent\ignorespaces} % the first paragraph of a chapter is not indented
\newdimen\titlelsl \titlelsl=1pt

\outer\def\endchapter{\ifodd\pageno \else\vfill\eject\null\fi
  \begingroup\bigskip\vfill % beginning of the quotes
  \def\eject{\endgroup\eject}
  \def\par{\ifhmode\/\endgraf\fi}\obeylines
  \def\TeX{T\kern-.2em\lower.5ex\hbox{E}\kern-.000em X}
  \def\MF{{\manual opqr}\-{\manual stuq}}
  \eightpoint \let\tt=\ninett
  \baselineskip 10pt
  \parfillskip \z@
  \interlinepenalty 10000
  \leftskip \z@ plus 40pc minus \parindent
  \let\rm=\eightss \let\sl=\eightssi
  \everypar{\sl}}
\def\author#1(#2){\smallskip\noindent\rm--- #1\unskip\enspace(#2)}

\def\dbend{{\manual\char127}} % dangerous bend sign
\def\d@nger{\medbreak\begingroup\clubpenalty=10000
  \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  \hbox to0pt{\hskip-\hangindent\dbend\hfill}\ninepoint}
\outer\def\danger{\d@nger}
\def\dd@nger{\medbreak\begingroup\clubpenalty=10000
  \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  \hbox to0pt{\hskip-\hangindent\dbend\kern1pt\dbend\hfill}\ninepoint}
\outer\def\ddanger{\dd@nger}
\def\enddanger{\endgraf\endgroup} % omits the \medbreak

\outer\def\subsection#1. {\medbreak\advance\subsecno by 1
  \noindent{\it \the\subsecno.\enspace#1.\enspace}}
\def\ansno#1.#2:{\medbreak\noindent
  \hbox to\parindent{\bf\hss#1.#2.\enspace}\ignorespaces}

% Composition macros
\hyphenation{man-u-script man-u-scripts ap-pen-dix xscaled}

\def\AmSTeX{$\cal A\kern-.1667em\lower.5ex\hbox{$\cal M$}\kern-.075em
  S$-\TeX}
\def\bull{\vrule height .9ex width .8ex depth -.1ex } % square bullet
\def\SS{{\it SS}} % scriptscript style
\def\|{\leavevmode\hbox{\tt\char`\|}} % vertical line
\def\dn{\leavevmode\hbox{\tt\char'14}} % downward arrow
\def\up{\leavevmode\hbox{\tt\char'13}} % upward arrow
\def\]{\leavevmode\hbox{\tt\char`\ }} % visible space

\def\pt{\,{\rm pt}} % units of points, in math formulas
\def\em{\,{\rm em}} % units of ems, in math formulas
\def\<#1>{\leavevmode\hbox{$\langle$#1\/$\rangle$}} % syntactic quantity
\def\oct#1{\hbox{\rm\'{}\kern-.2em\it#1\/\kern.05em}} % octal constant
\def\hex#1{\hbox{\rm\H{}\tt#1}} % hexadecimal constant
\def\cstok#1{\leavevmode\thinspace\hbox{\vrule\vtop{\vbox{\hrule\kern1pt
        \hbox{\vphantom{\tt/}\thinspace{\tt#1}\thinspace}}
      \kern1pt\hrule}\vrule}\thinspace} % control sequence token

{\obeyspaces\gdef {\ }}
\def\parbreak{\hfil\break\indent\strut}
\def\stretch{\nobreak\hskip0pt plus2pt\relax}

% macros for non-centered displays
\outer\def\begindisplay{\obeylines\startdisplay}
{\obeylines\gdef\startdisplay#1
  {\catcode`\^^M=5$$#1\halign\bgroup\indent##\hfil&&\qquad##\hfil\cr}}
\outer\def\enddisplay{\crcr\egroup$$}

% (the following \begin...\end-type macros do not appear in Appendix E)
% macros for demonstrating math constructions
\outer\def\beginmathdemo{$$\advance\baselineskip by2pt
  \halign\bgroup\indent\hbox to 160pt{##\hfil}&$##$\hfil\cr\noalign{\vskip-2pt}}
\outer\def\begindisplaymathdemo {$$\advance\baselineskip by15pt
  \halign\bgroup\indent\hbox to 160pt{##\hfil}&$\displaystyle{##}$\hfil\cr
  \noalign{\vskip-15pt}}
\outer\def\beginlongmathdemo{$$\advance\baselineskip by2pt
  \halign\bgroup\indent\hbox to 210pt{##\hfil}&$##$\hfil\cr\noalign{\vskip-2pt}}
\outer\def\beginlongdisplaymathdemo {$$\advance\baselineskip by15pt
  \halign\bgroup\indent\hbox to 210pt{##\hfil}&$\displaystyle{##}$\hfil\cr
  \noalign{\vskip-15pt}}
\outer\def\endmathdemo{\egroup$$}

% macros for font tables
\def\oddline#1{\cr
  \noalign{\nointerlineskip}
  \multispan{19}\hrulefill&
  \setbox0=\hbox{\lower 2.3pt\hbox{\hex{#1x}}}\smash{\box0}\cr
  \noalign{\nointerlineskip}}
\def\evenline{\cr\noalign{\hrule}}
\def\chartstrut{\lower4.5pt\vbox to14pt{}}
\def\beginchart#1{$$\postdisplaypenalty=-10000 \global\count@=0 #1
  \halign to\hsize\bgroup
    \chartstrut##\tabskip0pt plus10pt&
    &\hfil##\hfil&\vrule##\cr
    \lower6.5pt\null
    &&&\oct0&&\oct1&&\oct2&&\oct3&&\oct4&&\oct5&&\oct6&&\oct7&\evenline}
\def\endchart{\raise11.5pt\null&&&\hex 8&&\hex 9&&\hex A&&\hex B&
  &\hex C&&\hex D&&\hex E&&\hex F&\cr\egroup$$}
\def\:{\setbox0=\hbox{\char\count@}%
  \ifdim\ht0>7.5pt\reposition
  \else\ifdim\dp0>2.5pt\reposition\fi\fi
  \box0\global\advance\count@ by1 }
\def\reposition{\setbox0=\hbox{$\vcenter{\kern2pt\box0\kern2pt}$}}
\def\normalchart{%
  &\oct{00x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline0
  &\oct{01x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{02x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline1
  &\oct{03x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{04x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline2
  &\oct{05x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{06x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline3
  &\oct{07x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{10x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline4
  &\oct{11x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{12x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline5
  &\oct{13x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{14x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline6
  &\oct{15x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline
  &\oct{16x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\oddline7
  &\oct{17x}&&\:&&\:&&\:&&\:&&\:&&\:&&\:&&\:&\evenline}

% (now Appendix E resumes again)
% macros for verbatim scanning
\chardef\other=12
\def\ttverbatim{\begingroup
  \catcode`\\=\other
  \catcode`\{=\other
  \catcode`\}=\other
  \catcode`\$=\other
  \catcode`\&=\other
  \catcode`\#=\other
  \catcode`\%=\other
  \catcode`\~=\other
  \catcode`\_=\other
  \catcode`\^=\other
  \obeyspaces \obeylines \tt}

\outer\def\begintt{$$\let\par=\endgraf \ttverbatim \parskip=\z@
  \catcode`\|=0 \rightskip-5pc \ttfinish}
{\catcode`\|=0 |catcode`|\=\other % | is temporary escape character
  |obeylines % end of line is active
  |gdef|ttfinish#1^^M#2\endtt{#1|vbox{#2}|endgroup$$}}

\catcode`\|=\active
{\obeylines \gdef|{\ttverbatim \spaceskip\ttglue \let^^M=\  \let|=\endgroup}}

% macros for syntax rules (again, not in Appendix E)
\def\[#1]{\silenttrue\xref|#1|\thinspace{\tt#1}\thinspace} % keyword in syntax
\def\beginsyntax{\endgraf\nobreak\medskip
  \begingroup \catcode`<=13 \catcode`[=13
  \let\par=\endsyntaxline \obeylines}
\def\endsyntaxline{\futurelet\next\syntaxswitch}
\def\syntaxswitch{\ifx\next\<\let\next=\syntaxrule
  \else\ifx\next\endsyntax\let\next=\endgroup
  \else\let\next=\continuerule\fi\fi \next}
\def\continuerule{\hfil\break\indent\qquad}
\def\endsyntax{\medbreak\noindent}
{\catcode`<=13 \catcode`[=13
  \global\let<=\< \global\let[=\[
  \gdef\syntaxrule<#1>{\endgraf\indent\silentfalse\xref\<#1>}}
\def\is{\ $\longrightarrow$ }
\def\alt{\ $\vert$ }

% macros to demarcate lines quoted from TeX source files
\def\beginlines{\par\begingroup\nobreak\medskip\parindent\z@ \obeylines
  \hrule\kern1pt\nobreak \everypar{\strut}}
\def\endlines{\kern1pt\hrule\endgroup\medbreak\noindent}
\def\weakendlines{\kern1pt\hrule\endgroup\medskip\noindent}
\def\finalendlines{\kern1pt\hrule\endgroup\medbreak}

\outer\def\exercise{\medbreak
  \global\advance\exno by 1
  \noindent\llap{\manual\char'170\rm\kern.15em}% triangle in margin
  {\ninebf EXERCISE \bf\chapno.\the\exno}\par\nobreak\noindent}
\def\dexercise{\global\advance\exno by 1
  \llap{\manual\char'170\rm\kern.15em}% triangle in indented space
  {\eightbf EXERCISE \bf\chapno.\the\exno}\hfil\break}
\outer\def\dangerexercise{\d@nger \dexercise}
\outer\def\ddangerexercise{\dd@nger \dexercise}

\newwrite\ans
\immediate\openout\ans=answers % file for answers to exercises
\outer\def\answer{\par\medbreak
  \immediate\write\ans{}
  \immediate\write\ans{\string\ansno\chapno.\the\exno:}
  \copytoblankline}
\def\copytoblankline{\begingroup\setupcopy\copyans}
\def\setupcopy{\def\do##1{\catcode`##1=\other}\dospecials
  \catcode`\|=\other \obeylines}
{\obeylines \gdef\copyans#1
  {\def\next{#1}%
  \ifx\next\empty\let\next=\endgroup %
  \else\immediate\write\ans{\next} \let\next=\copyans\fi\next}}

% Editorial notes: some things to watch for.

% f |\ and f ^|\ => insert \/  [e.g., if\/ |\hbox|...]
% appendi => check for \null  [e.g., Appendix~B\null.]
% ly- => the hyphen is probably omittable
% ''. and '', => transpose to .'' and ,''
% dgement => dgment
% in MFbook: f@' and \MF, and \MF.

% Macros for drawing figures (not in Appendix E)
\def\hidehrule#1#2{\kern-#1\hrule height#1 depth#2 \kern-#2 }
\def\hidevrule#1#2{\kern-#1{\dimen0=#1
    \advance\dimen0 by#2\vrule width\dimen0}\kern-#2 }
% \makeblankbox puts rules at the edges of a blank box
% whose dimensions are those of \box0 (assuming nonnegative wd,ht,dp)
% #1 is rule thickness outside, #2 is rule thickness inside
\def\makeblankbox#1#2{\hbox{\lower\dp0\vbox{\hidehrule{#1}{#2}%
    \kern-#1% overlap the rules at the corners
    \hbox to\wd0{\hidevrule{#1}{#2}%
      \raise\ht0\vbox to #1{}% set the vrule height
      \lower\dp0\vtop to #1{}% set the vrule depth
      \hfil\hidevrule{#2}{#1}}%
    \kern-#1\hidehrule{#2}{#1}}}}
\def\maketypebox{\makeblankbox{0pt}{1pt}}
\def\makelightbox{\makeblankbox{.2pt}{.2pt}}

% \box\bigdot is a null box with a bullet at its reference point
\newbox\bigdot \newbox\smalldot
\setbox0=\hbox{$\vcenter{}$} % \ht0 is the axis height
\setbox1=\hbox to\z@{$\hss\bullet\hss$} % bullet is centered on the axis
\setbox\bigdot=\vbox to\z@{\kern-\ht1 \kern\ht0 \box1 \vss}
\setbox1=\hbox to\z@{$\hss\cdot\hss$} % cdot is centered on the axis
\setbox\smalldot=\vbox to\z@{\kern-\ht1 \kern\ht0 \box1 \vss}

% \arrows makes things like <--- text --->
\def\arrows#1#2{% #1=width, #2=text
  {\setbox0=\hbox{$\mkern-2mu\mathord-\mkern-2mu$}
    \hbox to #1{\kern-.055556em$\leftarrow\mkern-6mu$%
      \cleaders\copy0\hfil
      \kern.4em #2\kern.4em
      \cleaders\copy0\hfil
      $\mkern-6mu\rightarrow$\kern-.055556em}}}

% \samplebox makes the outline of a box, with big dot at reference point
\def\samplebox#1#2#3#4{% #1=ht, #2=dp, #3=wd, #4=text
  {\setbox0=\vtop{\vbox to #1{\hbox to #3{}\vss}
      \nointerlineskip
      \vbox to #2{}}% now \box0 has the desired ht, dp, and wd
    \hbox{\copy\bigdot
      \vrule height.2pt depth.2pt width#3%
      \kern-#3%
      \makelightbox
      \kern-#3%
      \raise#1\vbox{\hbox to #3{\hss#4\hss}
        \kern 3pt}}}}

% \sampleglue makes glue between sample boxes
\newdimen\varunit
\varunit=\hsize \advance\varunit by-2\parindent
\divide\varunit by 58 % illustrations in Chapter 12
\def\sampleglue#1#2{% #1=width, #2=text
  \vtop{\hbox to #1{\xleaders\hbox to .5\varunit{\hss\copy\smalldot\hss}\hfil}
    \kern3pt
    \tabskip \z@ plus 1fil
    \halign to #1{\hfil##\cr#2\cr}}}

% Indexing macros
\newif\ifproofmode
\proofmodetrue % this should be false when making camera-ready copy
\newwrite\inx
\immediate\openout\inx=index % file for index reminders
\newif\ifsilent
\def\specialhat{\ifmmode\def\next{^}\else\let\next=\beginxref\fi\next}
\def\beginxref{\futurelet\next\beginxrefswitch}
\def\beginxrefswitch{\ifx\next\specialhat\let\next=\silentxref
  \else\silentfalse\let\next=\xref\fi \next}
\catcode`\^=\active \let ^=\specialhat
\def\silentxref^{\silenttrue\xref}

\def\marginstyle{\vrule height6pt depth2pt width\z@ \sevenrm}

\chardef\bslash=`\\
\def\xref{\futurelet\next\xrefswitch}
\def\xrefswitch{\begingroup
  \ifx\next|\aftergroup\vxref % case 1 or 2, |arg| or |\arg|
  \else\ifx\next\<\aftergroup\anglexref % case 3, "\<arg>" means angle brackets
    \else\aftergroup\normalxref \fi\fi\endgroup} % case 0, "{arg}"
\def\vxref|{\catcode`\\=\active \futurelet\next\vxrefswitch}
\def\vxrefswitch#1|{\catcode`\\=0
  \ifx\next\empty\def\xreftype{2}%
    \def\next{{\tt\bslash\text}}% type 2, |\arg|
  \else\def\xreftype{1}\def\next{{\tt\text}}\fi % type 1, |arg|
  \edef\text{#1}\makexref}
{\catcode`\|=0 \catcode`\\=\active |gdef\{}}
\def\anglexref\<#1>{\def\xreftype{3}\def\text{#1}%
  \def\next{\<\text>}\makexref}
\def\normalxref#1{\def\xreftype{0}\def\text{#1}\let\next=\text\makexref}
\def\makexref{\ifproofmode\insert\margin{\hbox{\marginstyle\text}}%
   \xdef\writeit{\write\inx{\text\space!\xreftype\space
     \noexpand\number\pageno.}}\writeit
   \else\ifhmode\kern\z@\fi\fi
  \ifsilent\ignorespaces\else\next\fi}
% the \insert (which is done in proofmode only) suppresses hyphenation,
% so the \kern\z@ is put in to give the same effect in non-proofmode.

% Internal cross references that may change
\def\sesame{61} % page number for Sesame Street quote
\def\bmiexno{20} % exercise number for bold math italic
\def\punishexno{1} % exercise number for `punishment'
\def\fracexno{6} % exercise number for `\frac'
\def\vshippage{31} % error message from `\vship'
\def\storypage{24} % listing of story.tex
\def\metaT{4} % exercise number for T of METAFONT
\def\xwhat{2} % exercise number for x3:=whatever
\def\Xwhat{2} % exercise number for whatever itself

\def\checkequals#1#2{\ifnum#1=#2\else
  \errmessage{Redefine \string#1 to be \the#2}\fi}

% Things for The METAFONTbook only
\ifx\MFmanual\!\else\endinput\fi

\def\!{\kern-.03em\relax}

\def\frac#1/#2{\leavevmode\kern.1em
  \raise.5ex\hbox{\the\scriptfont0 #1}\kern-.1em
  /\kern-.15em\lower.25ex\hbox{\the\scriptfont0 #2}}

\outer\def\displayfig #1 (#2){$$\advance\abovedisplayskip by 3pt
  \leftline{\indent\figbox{#1}{3in}{#2}\vbox}$$}
\def\rightfig #1 (#2 x #3) ^#4 {% #2 wide and #3 deep, raised #4
  \strut\vadjust{\setbox0=\vbox to 0pt{\vss
      \hbox to\pagewidth{\hfil
        \raise #4\figbox{#1}{#2}{#3}\vtop \quad}}
    \dp0=0pt \box0}}
\def\figbox#1#2#3#4{#4to#3{ % makes a box #2 wide and #3 deep
    \ifproofmode\kern0pt\hrule\vfill
    \hsize=#2 \baselineskip 6pt \fiverm\noindent\raggedright
    (Figure #1 will be inserted here; too bad you can't see it now.)
    \endgraf\vfill\hrule
    \else\vfill\hbox to#2{}\fi}}

\def\endsyntax{\begingroup\let\par=\endgraf\medbreak\endgroup\noindent}

\let\BEGINCHAPTER=\beginchapter
\def\beginchapter{\titlelsl=1pt \BEGINCHAPTER}
\def\beginChapter{\titlelsl=2pt \BEGINCHAPTER}

\def\decreasehsize #1 {\advance\hsize-#1}
\def\restorehsize{\hsize=\pagewidth}

\catcode`\@=\active
\catcode`\"=\active
\def\ttverbatim{\begingroup \catcode`\@=\other \catcode`\"=\other
  \catcode`\\=\other
  \catcode`\{=\other
  \catcode`\}=\other
  \catcode`\$=\other
  \catcode`\&=\other
  \catcode`\#=\other
  \catcode`\%=\other
  \catcode`\~=\other
  \catcode`\_=\other
  \catcode`\^=\other
  \obeyspaces \obeylines \tt}
\def\setupcopy{\def\do##1{\catcode`##1=\other}\dospecials
  \catcode`\|=\other \catcode`\@=\other \catcode`\"=\other \obeylines}
\def\_{\leavevmode \kern.06em \vbox{\hrule width.3em}}
\def@#1@{\begingroup\def\_{\kern.04em
    \vbox{\hrule width.3em height .6pt}\kern.08em}%
  \ifmmode\mathop{\bf#1}\else\hbox{\bf#1\/}\fi\endgroup}
\def"#1"{\hbox{\it#1\/\kern.05em}} % italic type for identifiers
\def\xrefswitch{\begingroup
  \ifx\next|\aftergroup\vxref % case 1, |arg| or |\arg|
  \else\ifx\next@\aftergroup\boldxref % case 2, "@arg@" means boldface
  \else\ifx\next"\aftergroup\italxref % case 4, ""arg"" means boldface
  \else\ifx\next\<\aftergroup\anglexref % case 3, "\<arg>" means angle brackets
    \else\aftergroup\normalxref \fi\fi\fi\fi\endgroup} % case 0, "{arg}"
\def\boldxref@#1@{\def\xreftype{2}\def\text{#1}%
  \def\next{@\text@}\makexref}
\def\italxref"#1"{\def\xreftype{4}\def\text{#1}%
  \def\next{"\text"}\makexref}

\def\pyth+{\mathbin{++}}
\def\0{\raise.7ex\hbox{$\scriptstyle\#$}}
\def\to{\mathrel{\ldotp\ldotp}}
\def\dashto{\mathrel{\hbox{-\thinspace-\kern-.05em}}}
\def\ddashto{\mathrel{\hbox{-\thinspace-\thinspace-\kern-.05em}}}
\def\round{\mathop{\rm round}}
\def\angle{\mathop{\rm angle}}
\def\rmsqrt{\mathop{\rm sqrt}}
\def\reverse{\mathop{\rm reverse}}
\def\curl{\mathop{\rm curl}}
\def\tension{\mathop{\rm tension}}
\def\atleast{\mathop{\rm atleast}}
\def\controls{\mathop{\rm controls}}
\def\and{\,{\rm and}\,}
\def\cycle{{\rm cycle}}
\def\pickup{@pickup@ \thinspace}
\def\penpos#1{\hbox{\it penpos}_{#1}}
\def\pentaper#1{\hbox{\it pentaper}_{#1}}

\chardef\hexa=1  % first hex
\chardef\hexb=2 % top and bot adjusted
\chardef\hexc=3 % same, bold
\chardef\hexd=4 % same, confined to box
\chardef\hexe=5 % penstroked hex
\chardef\Aa=6 % stick-figure A, golden ratio
\def\sevenAs{\char7\char8\char9\char10\char11\char12\char13} % same, variants
\chardef\Az=14 % same, with crooked bar
\chardef\Ab=15 % \Aa with rectilinear elliptical pen
\chardef\Ac=16 % same, with the ellipse tilted
\chardef\beana=17 % kidney bean, default pen
\chardef\beanb=18 % same, twice as bold
\chardef\beanc=19 % same, rectilinear elliptical pen
\chardef\beand=20 % same, with the ellipse tilted
\chardef\niba=21 % 10x rectilinear ellipse
\chardef\nibb=22 % same, with the ellipse tilted
\chardef\nibc=23 % same, 90 degrees titled
\chardef\IOT=24 % Ionian T
\chardef\IOS=25 % Ionian S
\chardef\IOO=26 % Ionian O
\chardef\IOI=27 % Ionian I
\chardef\cubea=28 % possible cube
\chardef\cubeb=29 % impossible cube
\chardef\bicentennial=30 % star with overlapping strokes
\chardef\oneu=31 % 1/4 of uuuu ornament
\chardef\circa=32 % quartercircle
\chardef\circb=33 % filled quartercircle
\chardef\circc=34 % rotated quartercircle
\chardef\circd=35 % cone
\chardef\circe=36 % concentric circles
\chardef\circf=37 % concentric diamonds
\chardef\fouru=38 % uuuu ornament
\chardef\fourc=39 % same, rotated
\chardef\seventh='140 % 1/7, to go with cmssqi8

\newdimen\apspix
\apspix=31448sp % 8 APS pixels = 52413.64sp, and I'm taking 60% of this
% to crude approximation, there are about 2\apspix per pt
\newdimen\blankpix \newdimen\Blankpix
\setbox0=\hbox{\manual P} \blankpix=\wd0 % approximately 1pt blank pixel
\setbox0=\hbox{\manual R} \Blankpix=\wd0 % approximately 3pt blank pixel

\def\leftheadline{\hbox to \pagewidth{%
    \vbox to 10pt{}% strut to position the baseline
    \llap{\tenbf\folio\kern1pc}% folio to left of text
    \def\MF{{\manual 89:;<=>:}}% slanted 10pt
    \tenit\rhead\hfil% running head flush left
    }}
\def\rightheadline{\hbox to \pagewidth{%
    \vbox to 10pt{}% strut to position the baseline
    \def\MF{{\manual 89:;<=>:}}% slanted 10pt
    \hfil\tenit\rhead\/% running head flush right
    \rlap{\kern1pc\tenbf\folio}% folio to right of text
    }}
\def\ttok#1{\leavevmode\thinspace\hbox{\vrule\vtop{\vbox{\hrule\kern1pt
        \hbox{\vphantom{\tt(j}\thinspace{\tt#1}\thinspace}}
      \kern1pt\hrule}\vrule}\thinspace} % token

\newdimen\tinypix \setbox0=\hbox{\sixrm0} \tinypix=5pt
\newdimen\pixcorr \pixcorr=\tinypix \advance\pixcorr by-\wd0
\def\pixpat#1#2#3#4{\vcenter{\sixrm\baselineskip=\tinypix
  \hbox{#1\kern\pixcorr#2}\hbox{#3\kern\pixcorr#4}}}

\font\rand=random


text:
APPD_EVENTS_SERVICE_DIR="/opt/AppDynamics/events-service"

validate() {
	if [ ! -d "$APPD_EVENTS_SERVICE_DIR" ]; then
		echo "ERROR: Unable to locate $APPD_EVENTS_SERVICE_DIR/. Correct the variable at the top of this script."
		exit 1
	fi
}

# Zookeeper
start-zookeeper() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Starting Zookeeper..."
	export set JAVA_OPTS="-Xmx1G -Xms1G"
	bin/events-service.sh start -y conf/events-service-zookeeper.yml -p conf/events-service-zookeeper.properties
	echo " "
}
stop-zookeeper() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Stopping Zookeeper..."
	bin/events-service.sh stop events-service-zookeeper.id
	echo " "
}
status-zookeeper() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Health of Zookeeper..."
	java -jar bin/tool/tool-healthcheck.jar -hp localhost:9051
	echo " "
}

# API-Store
start-api-store() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Starting API-Store..."
	export set JAVA_OPTS="-Xmx1G -Xms1G"
	bin/events-service.sh start -y conf/events-service-api-store.yml -p conf/events-service-api-store.properties
	echo " "
}
stop-api-store() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Stopping API-Store..."
	bin/events-service.sh stop events-service-api-store.id
	echo " "
}
status-api-store() {
	cd $APPD_EVENTS_SERVICE_DIR
	echo "Health of API-Store..."
	java -jar bin/tool/tool-healthcheck.jar -hp localhost:9081
	echo " "
}

main() {
	case "$1" in

	# Both components
	start)
		$0 start-zookeeper
		$0 start-api-store
		exit
		;;
	stop)
		$0 stop-zookeeper
		$0 stop-api-store
		exit
		;;
	restart)
		$0 stop
		$0 start
		exit
		;;
	status)
		status-zookeeper
		status-api-store
		exit
		;;

	# Zookeeper
	start-zookeeper)
		start-zookeeper
		exit
		;;
	stop-zookeeper)
		stop-zookeeper
		exit
		;;
	restart-zookeeper)
		stop-zookeeper
		start-zookeeper
		exit
		;;
	status-zookeeper)
		status-zookeeper
		exit
		;;

	# API-Store
	start-api-store)
		start-api-store
		exit
		;;
	stop-api-store)
		stop-api-store
		exit
		;;
	restart-api-store)
		stop-api-store
		start-api-store
		exit
		;;
	status-api-store)
		status-api-store
		exit
		;;

	*)
		echo "Usage: $0 {start|stop|restart|status}"
		echo " "
		echo "Optionally, manipulate individual components:"
		echo "  Zookeeper: $0 {start-zookeeper|stop-zookeeper|restart-zookeeper|status-zookeeper}"
		echo "  API-Store: $0 {start-api-store|stop-api-store|restart-api-store|status-api-store}"
		exit
	esac
}

validate
main "$@"


text: Loading...