text:
package com.google.android.exoplayer.testutil;

import android.util.SparseBooleanArray;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.extractor.ExtractorInput;
import com.google.android.exoplayer.upstream.DataSource;

import junit.framework.Assert;

import java.io.EOFException;
import java.io.IOException;

/**
 * A fake {@link ExtractorInput} capable of simulating various scenarios.
 *

 * Read, skip and peek errors can be simulated using {@link Builder#setSimulateIOErrors}. When
 * enabled each read and skip will throw a {@link SimulatedIOException} unless one has already been
 * thrown from the current position. Each peek will throw {@link SimulatedIOException} unless one
 * has already been thrown from the current peek position. When a {@link SimulatedIOException} is
 * thrown the read position is left unchanged and the peek position is reset back to the read
 * position.
 *

 * Partial reads and skips can be simulated using {@link Builder#setSimulatePartialReads}. When
 * enabled, {@link #read(byte[], int, int)} and {@link #skip(int)} calls will only read or skip a
 * single byte unless a partial read or skip has already been performed that had the same target
 * position. For example, a first read request for 10 bytes will be partially satisfied by reading
 * a single byte and advancing the position to 1. If the following read request attempts to read 9
 * bytes then it will be fully satisfied, since it has the same target position of 10.
 *

 * Unknown data length can be simulated using {@link Builder#setSimulateUnknownLength}. When enabled
 * {@link #getLength()} will return {@link C#LENGTH_UNBOUNDED} rather than the length of the data.
 */
public final class FakeExtractorInput implements ExtractorInput {

  /**
   * Thrown when simulating an {@link IOException}.
   */
  public static final class SimulatedIOException extends IOException {

    public SimulatedIOException(String message) {
      super(message);
    }

  }

  private final byte[] data;
  private final boolean simulateUnknownLength;
  private final boolean simulatePartialReads;
  private final boolean simulateIOErrors;

  private int readPosition;
  private int peekPosition;

  private final SparseBooleanArray partiallySatisfiedTargetPositions;
  private final SparseBooleanArray failedReadPositions;
  private final SparseBooleanArray failedPeekPositions;

  private FakeExtractorInput(byte[] data, boolean simulateUnknownLength,
      boolean simulatePartialReads, boolean simulateIOErrors) {
    this.data = data;
    this.simulateUnknownLength = simulateUnknownLength;
    this.simulatePartialReads = simulatePartialReads;
    this.simulateIOErrors = simulateIOErrors;
    partiallySatisfiedTargetPositions = new SparseBooleanArray();
    failedReadPositions = new SparseBooleanArray();
    failedPeekPositions = new SparseBooleanArray();
  }

  /**
   * Sets the read and peek positions.
   *
   * @param position The position to set.
   */
  public void setPosition(int position) {
    Assert.assertTrue(0 <= position && position < data.length);
    readPosition = position;
    peekPosition = position;
  }

  @Override
  public int read(byte[] target, int offset, int length) throws IOException {
    length = getReadLength(length);
    if (readFully(target, offset, length, true)) {
      return length;
    }
    return C.RESULT_END_OF_INPUT;
  }

  @Override
  public boolean readFully(byte[] target, int offset, int length, boolean allowEndOfInput)
      throws IOException {
    if (!checkXFully(allowEndOfInput, readPosition, length, failedReadPositions)) {
      return false;
    }
    System.arraycopy(data, readPosition, target, offset, length);
    readPosition += length;
    peekPosition = readPosition;
    return true;
  }

  @Override
  public void readFully(byte[] target, int offset, int length) throws IOException {
    readFully(target, offset, length, false);
  }

  @Override
  public int skip(int length) throws IOException {
    length = getReadLength(length);
    if (skipFully(length, true)) {
      return length;
    }
    return C.RESULT_END_OF_INPUT;
  }

  @Override
  public boolean skipFully(int length, boolean allowEndOfInput) throws IOException {
    if (!checkXFully(allowEndOfInput, readPosition, length, failedReadPositions)) {
      return false;
    }
    readPosition += length;
    peekPosition = readPosition;
    return true;
  }

  @Override
  public void skipFully(int length) throws IOException {
    skipFully(length, false);
  }

  @Override
  public boolean peekFully(byte[] target, int offset, int length, boolean allowEndOfInput)
      throws IOException {
    if (!checkXFully(allowEndOfInput, peekPosition, length, failedPeekPositions)) {
      return false;
    }
    System.arraycopy(data, peekPosition, target, offset, length);
    peekPosition += length;
    return true;
  }

  @Override
  public void peekFully(byte[] target, int offset, int length) throws IOException {
    peekFully(target, offset, length, false);
  }

  @Override
  public boolean advancePeekPosition(int length, boolean allowEndOfInput) throws IOException {
    if (!checkXFully(allowEndOfInput, peekPosition, length, failedPeekPositions)) {
      return false;
    }
    peekPosition += length;
    return true;
  }

  @Override
  public void advancePeekPosition(int length) throws IOException {
    advancePeekPosition(length, false);
  }

  @Override
  public void resetPeekPosition() {
    peekPosition = readPosition;
  }

  @Override
  public long getPeekPosition() {
    return peekPosition;
  }

  @Override
  public long getPosition() {
    return readPosition;
  }

  @Override
  public long getLength() {
    return simulateUnknownLength ? C.LENGTH_UNBOUNDED : data.length;
  }

  @Override
  public DataSource getDataSource() {
    return null;
  }

  private boolean checkXFully(boolean allowEndOfInput, int position, int length,
                              SparseBooleanArray failedPositions) throws IOException {
    if (simulateIOErrors && !failedPositions.get(position)) {
      failedPositions.put(position, true);
      peekPosition = readPosition;
      throw new SimulatedIOException("Simulated IO error at position: " + position);
    }
    if (isEof()) {
      if (allowEndOfInput) {
        return false;
      }
      throw new EOFException();
    }
    if (position + length > data.length) {
      throw new IOException("Attempted to move past end of data: (" + position + " + "
          + length + ") > " + data.length);
    }
    return true;
  }

  private int getReadLength(int requestedLength) {
    int targetPosition = readPosition + requestedLength;
    if (simulatePartialReads && requestedLength > 1
        && !partiallySatisfiedTargetPositions.get(targetPosition)) {
      partiallySatisfiedTargetPositions.put(targetPosition, true);
      return 1;
    }
    return Math.min(requestedLength, data.length - readPosition);
  }

  private boolean isEof() {
    return readPosition == data.length;
  }

  /**
   * Builder of {@link FakeExtractorInput} instances.
   */
  public static final class Builder {

    private byte[] data;
    private boolean simulateUnknownLength;
    private boolean simulatePartialReads;
    private boolean simulateIOErrors;

    public Builder() {
      data = new byte[0];
    }

    public Builder setData(byte[] data) {
      this.data = data;
      return this;
    }

    public Builder setSimulateUnknownLength(boolean simulateUnknownLength) {
      this.simulateUnknownLength = simulateUnknownLength;
      return this;
    }

    public Builder setSimulatePartialReads(boolean simulatePartialReads) {
      this.simulatePartialReads = simulatePartialReads;
      return this;
    }

    public Builder setSimulateIOErrors(boolean simulateIOErrors) {
      this.simulateIOErrors = simulateIOErrors;
      return this;
    }

    public FakeExtractorInput build() {
      return new FakeExtractorInput(data, simulateUnknownLength, simulatePartialReads,
          simulateIOErrors);
    }

  }

}


text:
$(document).ready(function () {
  $("#fbLogin").on('click', function () {
    chrome.extension.sendRequest({ msg: "fbLogin" });
  });
});

redpajama_set_name: RedPajamaGithub


text: Test Data and Modules


text:
package org.apache.geode.test.junit.rules;

import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS;
import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER;
import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT;
import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
import static org.apache.geode.distributed.ConfigurationProperties.MAX_WAIT_TIME_RECONNECT;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.distributed.ConfigurationProperties.NAME;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.apache.geode.management.internal.ManagementConstants.OBJECTNAME__CLIENTSERVICE_MXBEAN;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import javax.management.ObjectName;

import org.apache.commons.lang.ArrayUtils;
import org.assertj.core.api.Assertions;
import org.awaitility.core.ConditionTimeoutException;
import org.junit.rules.TemporaryFolder;

import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.membership.gms.MembershipManagerHelper;
import org.apache.geode.internal.UniquePortSupplier;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
import org.apache.geode.internal.net.SocketCreatorFactory;
import org.apache.geode.management.CacheServerMXBean;
import org.apache.geode.management.DistributedRegionMXBean;
import org.apache.geode.management.DistributedSystemMXBean;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.internal.MBeanJMXAdapter;
import org.apache.geode.management.internal.SystemManagementService;
import org.apache.geode.management.internal.cli.CliUtil;
import org.apache.geode.security.SecurityManager;
import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;

/**
 * the abstract class that's used by LocatorStarterRule and ServerStarterRule to avoid code
 * duplication.
 */
public abstract class MemberStarterRule<T> extends SerializableExternalResource implements Member {

  protected String oldUserDir;

  protected transient TemporaryFolder temporaryFolder;
  protected File workingDir;
  protected int memberPort = 0;
  protected int jmxPort = -1;
  protected int httpPort = -1;

  protected String name;
  protected boolean logFile = false;
  protected Properties properties = new Properties();

  protected boolean autoStart = false;
  private final transient UniquePortSupplier portSupplier;

  public static void setWaitUntilTimeout(int waitUntilTimeout) {
    WAIT_UNTIL_TIMEOUT = waitUntilTimeout;
  }

  private static int WAIT_UNTIL_TIMEOUT = 30;

  public MemberStarterRule() {
    this(new UniquePortSupplier());
  }

  public MemberStarterRule(UniquePortSupplier portSupplier) {
    this.portSupplier = portSupplier;
    oldUserDir = System.getProperty("user.dir");

    // initial values
    properties.setProperty(MCAST_PORT, "0");
    properties.setProperty(LOCATORS, "");
    // set the reconnect wait time to 5 seconds in case some tests needs to reconnect in a timely
    // manner.
    properties.setProperty(MAX_WAIT_TIME_RECONNECT, "5000");
  }

  @Override
  public void before() {
    normalizeProperties();
    if (httpPort < 0) {
      // at this point, httpPort is not being configured by api, we assume they do not
      // want to start the http service.
      // use putIfAbsent if it was configured using withProperty
      properties.putIfAbsent(HTTP_SERVICE_PORT, "0");
    }
  }

  @Override
  public void after() {
    // invoke stop() first and then ds.disconnect
    stopMember();

    // this will clean up the SocketCreators created in this VM so that it won't contaminate
    // future tests
    SocketCreatorFactory.close();
    disconnectDSIfAny();

    if (temporaryFolder != null) {
      temporaryFolder.delete();
    }

    if (oldUserDir == null) {
      System.clearProperty("user.dir");
    } else {
      System.setProperty("user.dir", oldUserDir);
    }
  }

  public T withPort(int memberPort) {
    this.memberPort = memberPort;
    return (T) this;
  }

  public T withWorkingDir(File workingDir) {
    this.workingDir = workingDir;
    if (workingDir != null) {
      System.setProperty("user.dir", workingDir.toString());
    }
    return (T) this;
  }

  /**
   * create a working dir using temporaryFolder. Use with caution, this sets "user.dir" system
   * property that not approved by JDK
   */
  public T withWorkingDir() {
    temporaryFolder = new TemporaryFolder();
    try {
      temporaryFolder.create();
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    withWorkingDir(temporaryFolder.getRoot().getAbsoluteFile());
    return (T) this;
  }

  /**
   * All the logs are written in the logfile instead on the console. this is usually used with
   * withWorkingDir so that logs are accessible and will be cleaned up afterwards.
   */
  public T withLogFile() {
    this.logFile = true;
    return (T) this;
  }

  public static void disconnectDSIfAny() {
    DistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
    if (ds != null) {
      ds.disconnect();
    }
  }

  public T withProperty(String key, String value) {
    properties.setProperty(key, value);
    return (T) this;
  }

  public T withProperties(Properties props) {
    if (props != null) {
      this.properties.putAll(props);
    }
    return (T) this;
  }

  public T withSecurityManager(Class<? extends SecurityManager> securityManager) {
    properties.setProperty(SECURITY_MANAGER, securityManager.getName());
    return (T) this;
  }

  public T withAutoStart() {
    this.autoStart = true;
    return (T) this;
  }

  public T withName(String name) {
    // only if name is not defined yet
    if (!properties.containsKey(NAME)) {
      this.name = name;
      properties.putIfAbsent(NAME, name);
    }
    return (T) this;
  }

  public T withConnectionToLocator(int... locatorPorts) {
    if (locatorPorts.length == 0) {
      return (T) this;
    }
    String locators = Arrays.stream(locatorPorts).mapToObj(i -> "localhost[" + i + "]")
        .collect(Collectors.joining(","));
    properties.setProperty(LOCATORS, locators);
    return (T) this;
  }

  /**
   * be able to start JMX manager and admin rest on default ports
   */
  public T withJMXManager(boolean useProductDefaultPorts) {
    if (!useProductDefaultPorts) {
      // do no override these properties if already exists
      properties.putIfAbsent(JMX_MANAGER_PORT,
          portSupplier.getAvailablePort() + "");
      this.jmxPort = Integer.parseInt(properties.getProperty(JMX_MANAGER_PORT));
    } else {
      // the real port numbers will be set after we started the server/locator.
      this.jmxPort = 0;
    }
    properties.putIfAbsent(JMX_MANAGER, "true");
    properties.putIfAbsent(JMX_MANAGER_START, "true");
    return (T) this;
  }

  public T withHttpService(boolean useDefaultPort) {
    properties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost");
    if (!useDefaultPort) {
      properties.putIfAbsent(HTTP_SERVICE_PORT,
          portSupplier.getAvailablePort() + "");
      this.httpPort = Integer.parseInt(properties.getProperty(HTTP_SERVICE_PORT));
    } else {
      // indicate start http service but with default port
      // (different from Gemfire properties, 0 means do not start http service)
      httpPort = 0;
    }
    return (T) this;
  }

  /**
   * start the jmx manager and admin rest on a random ports
   */
  public T withJMXManager() {
    return withJMXManager(false);
  }

  public T withHttpService() {
    return withHttpService(false);
  }

  protected void normalizeProperties() {
    // if name is set via property, not with API
    if (name == null) {
      if (properties.containsKey(NAME)) {
        name = properties.getProperty(NAME);
      } else {
        if (this instanceof ServerStarterRule) {
          name = "server";
        } else {
          name = "locator";
        }
      }
      withName(name);
    }

    // if jmxPort is set via property, not with API
    if (jmxPort < 0 && properties.containsKey(JMX_MANAGER_PORT)) {
      // this will make sure we have all the missing properties, but it won't override
      // the existing properties
      withJMXManager(false);
    }

    // if caller wants the logs being put into a file instead of in console output
    // do it here since only here, we can guarantee the name is present
    if (logFile) {
      properties.putIfAbsent(LOG_FILE, new File(name + ".log").getAbsolutePath());
    }
  }

  public DistributedRegionMXBean getRegionMBean(String regionName) {
    return getManagementService().getDistributedRegionMXBean(regionName);
  }

  public ManagementService getManagementService() {
    ManagementService managementService =
        ManagementService.getExistingManagementService(getCache());
    if (managementService == null) {
      throw new IllegalStateException("Management service is not available on this member");
    }
    return managementService;
  }

  public abstract InternalCache getCache();

  public void waitUntilRegionIsReadyOnExactlyThisManyServers(String regionName,
      int exactServerCount) throws Exception {
    if (exactServerCount == 0) {
      waitUntilEqual(
          () -> getRegionMBean(regionName),
          Objects::isNull,
          true,
          String.format("Expecting to not find an mbean for region '%s'", regionName),
          WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);
      return;
    }
    // First wait until the region mbean is not null...
    waitUntilEqual(
        () -> getRegionMBean(regionName),
        Objects::nonNull,
        true,
        String.format("Expecting to find an mbean for region '%s'", regionName),
        WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);

    // Now actually wait for the members to receive the region
    String assertionConditionDescription = String.format(
        "Expecting region '%s' to be found on exactly %d servers", regionName, exactServerCount);
    waitUntilSatisfied(
        () -> Arrays.asList(getRegionMBean(regionName).getMembers()),
        Function.identity(),
        members -> Assertions.assertThat(members).isNotNull().hasSize(exactServerCount),
        assertionConditionDescription,
        WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);
  }

  public void waitTillClientsAreReadyOnServer(String serverName, int serverPort, int clientCount) {
    waitTillCacheServerIsReady(serverName, serverPort);
    CacheServerMXBean bean = getCacheServerMXBean(serverName, serverPort);
    await().atMost(1, TimeUnit.MINUTES).until(() -> bean.getClientIds().length == clientCount);
  }

  /**
   * Invoked in serverVM
   */
  public void waitTillCacheClientProxyHasBeenPaused() {
    await().until(() -> {
      CacheClientNotifier clientNotifier = CacheClientNotifier.getInstance();
      Collection<CacheClientProxy> clientProxies = clientNotifier.getClientProxies();

      for (CacheClientProxy clientProxy : clientProxies) {
        if (clientProxy.isPaused()) {
          return true;
        }
      }
      return false;
    });
  }

  public void waitTillCacheServerIsReady(String serverName, int serverPort) {
    await().atMost(1, TimeUnit.MINUTES)
        .until(() -> getCacheServerMXBean(serverName, serverPort) != null);
  }

  public CacheServerMXBean getCacheServerMXBean(String serverName, int serverPort) {
    SystemManagementService managementService = (SystemManagementService) getManagementService();
    String objectName = MessageFormat.format(OBJECTNAME__CLIENTSERVICE_MXBEAN,
        String.valueOf(serverPort), serverName);
    ObjectName cacheServerMBeanName = MBeanJMXAdapter.getObjectName(objectName);
    return managementService.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
  }

  public void waitUntilGatewaySendersAreReadyOnExactlyThisManyServers(int exactGatewaySenderCount)
      throws Exception {
    DistributedSystemMXBean dsMXBean = getManagementService().getDistributedSystemMXBean();
    String predicateDescription = String.format(
        "Expecting to find exactly %d gateway sender beans.", exactGatewaySenderCount);

    waitUntilEqual(() -> dsMXBean.listGatewaySenderObjectNames(),
        array -> array.length, exactGatewaySenderCount, predicateDescription, WAIT_UNTIL_TIMEOUT,
        TimeUnit.SECONDS);
  }

  public void waitUntilDiskStoreIsReadyOnExactlyThisManyServers(String diskStoreName,
      int exactServerCount) throws Exception {
    final Supplier<DistributedSystemMXBean> distributedSystemMXBeanSupplier =
        () -> getManagementService().getDistributedSystemMXBean();

    waitUntilSatisfied(distributedSystemMXBeanSupplier,
        Function.identity(),
        bean -> assertThat(bean, notNullValue()),
        "Distributed System MXBean should not be null",
        WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);

    DistributedSystemMXBean dsMXBean = distributedSystemMXBeanSupplier.get();

    String predicateDescription = String.format(
        "Expecting exactly %d servers to present mbeans for a disk store with name %s.",
        exactServerCount, diskStoreName);
    Supplier<List<String[]>> diskStoreSupplier = () -> dsMXBean.listMemberDiskstore()
        .values().stream().filter(x1 -> ArrayUtils.contains(x1, diskStoreName))
        .collect(Collectors.toList());

    waitUntilEqual(diskStoreSupplier,
        x -> x.size(),
        exactServerCount,
        predicateDescription,
        WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);
  }

  public void waitUntilAsyncEventQueuesAreReadyOnExactlyThisManyServers(String queueId,
      int exactServerCount)
      throws Exception {
    String examinerDescription = String.format(
        "Expecting exactly %d servers to have an AEQ with id '%s'.", exactServerCount, queueId);
    waitUntilEqual(
        () -> CliUtil.getMembersWithAsyncEventQueue(getCache(), queueId),
        membersWithAEQ -> membersWithAEQ.size(),
        exactServerCount,
        examinerDescription,
        WAIT_UNTIL_TIMEOUT, TimeUnit.SECONDS);
  }

  /**
   * This method wraps an {@link org.awaitility.Awaitility#await} call for more meaningful error
   * reporting.
   *
   * @param supplier Method to retrieve the result to be tested, e.g.,
   *        get a list of visible region mbeans
   * @param examiner Method to evaluate the result provided by {@code provider}, e.g.,
   *        get the length of the provided list.
   *        Use {@link java.util.function.Function#identity()} if {@code assertionConsumer}
   *        directly tests the value provided by {@code supplier}.
   * @param assertionConsumer assertThat styled condition on the output of {@code examiner} against
   *        which
   *        the {@code await().untilAsserted(...)} will be called. E.g.,
   *        {@code beanCount -> assertThat(beanCount, is(5))}
   * @param assertionConsumerDescription A description of the {@code assertionConsumer} method,
   *        for additional failure information should this call time out.
   *        E.g., "Visible region mbean count should be 5"
   * @param timeout With {@code unit}, the maximum time to wait before raising an exception.
   * @param unit With {@code timeout}, the maximum time to wait before raising an exception.
   * @throws org.awaitility.core.ConditionTimeoutException The timeout has been reached
   * @throws Exception Any exception produced by {@code provider.call()}
   */
  public <K, J> void waitUntilSatisfied(Supplier<K> supplier, Function<K, J> examiner,
      Consumer<J> assertionConsumer, String assertionConsumerDescription, long timeout,
      TimeUnit unit)
      throws Exception {
    try {
      await(assertionConsumerDescription)
          .atMost(timeout, unit)
          .untilAsserted(() -> assertionConsumer.accept(examiner.apply(supplier.get())));
    } catch (ConditionTimeoutException e) {
      // There is a very slight race condition here, where the above could conceivably time out,
      // and become satisfied before the next supplier.get()
      throw new ConditionTimeoutException(
          "The observed result '" + String.valueOf(supplier.get())
              + "' does not satisfy the provided assertionConsumer. \n" + e.getMessage());
    }
  }

  /**
   * Convenience alias for {@link #waitUntilSatisfied},
   * requiring equality rather than a generic assertion.
   */
  public <K, J> void waitUntilEqual(Supplier<K> provider,
      Function<K, J> examiner,
      J expectation,
      String expectationDesription,
      long timeout, TimeUnit unit)
      throws Exception {
    Consumer<J> assertionConsumer = examined -> assertThat(examined, is(expectation));
    waitUntilSatisfied(provider, examiner, assertionConsumer, expectationDesription, timeout, unit);
  }

  abstract void stopMember();

  public void forceDisconnectMember() {
    MembershipManagerHelper
        .crashDistributedSystem(InternalDistributedSystem.getConnectedInstance());
  }

  @Override
  public File getWorkingDir() {
    return workingDir;
  }

  @Override
  public int getPort() {
    return memberPort;
  }

  @Override
  public int getJmxPort() {
    return jmxPort;
  }

  @Override
  public int getHttpPort() {
    return httpPort;
  }

  @Override
  public String getName() {
    return name;
  }
}


text:
package org.cocos2d.protocols;

import org.cocos2d.opengl.CCTexture2D;

/** CCNode objects that uses a Texture2D to render the images.
 The texture can have a blending function.
 If the texture has alpha premultiplied the default blending function is:
    src=GL_ONE dst= GL_ONE_MINUS_SRC_ALPHA
 else
	src=GL_SRC_ALPHA dst= GL_ONE_MINUS_SRC_ALPHA
 But you can change the blending funtion at any time.
 @since v0.8.0
 */

public interface CCTextureProtocol extends CCBlendProtocol {
    /** returns the used texture */
    public CCTexture2D getTexture();

    /** sets a new texture. it will be retained */
    public void setTexture(CCTexture2D texture);

}


text:
@charset "UTF-8";

@import "default.ultimate.css";

ul.dropdown {
 width: 760px;
 background: url(images/grad2.png) 0 100% repeat-x;
 border-bottom: solid 1px #ccc;
}

	ul.dropdown li,
	ul.dropdown li a {
	 border: none;
	 background: url(images/grad2.png) 0 100% repeat-x;
	}

	ul.dropdown li.hover,
	ul.dropdown li:hover {
	 background: #f6f6f6;
	 color: #000;
	}

	ul.dropdown li a:active {
	 background: none;
	}

	ul.dropdown ul {
	 width: 760px;
	 margin-top: -1px;
	 border-top: solid 1px #ccc;
	 background-color: #f6f6f6;
	}

		ul.dropdown ul li,
		ul.dropdown ul li a,
		ul.dropdown ul *.dir {
		 background: transparent;
		}

		ul.dropdown ul li.hover {
		 margin: 0;
		 border: none;
		}

		ul.dropdown ul li a:hover {
		 background-color: #f6f6f6;
		}

ul.dropdown *.dir {
 border: none;
}

	ul.dropdown ul *.dir {
	 padding-right: 7px;
	 background: none;
	}

ul.dropdown li.hover *.open {
 position: relative;
 z-index: 600;
 float: left;
 margin: -1px -1px 0;
 border-width: 1px;
 border-color: #ffa500 #ccc #f6f6f6;
 background-color: #f6f6f6;
}

ul.dropdown ul li.hover *.open {
 position: static;
 margin: 0;
 padding-left: 8px;
 border: none;
 background-color: transparent;
}

	/* CSS 2 Clone */

	ul.dropdown li:hover > *.dir {
	 position: relative;
	 z-index: 600;
	 float: left;
	 margin: -1px -1px 0;
	 border-width: 1px;
	 border-color: #ffa500 #ccc #f6f6f6;
	 background-color: #f6f6f6;
	}

	ul.dropdown ul li:hover > *.dir {
	 position: static;
	 margin: 0;
	 padding-left: 8px;
	 border: none;
	 background-color: transparent;
	}


text:
package net.minecraft.entity.ai;

import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.player.Player;

public class EntityAILookAtTradePlayer extends EntityAIWatchClosest
{
    private final EntityVillager theMerchant;

    public EntityAILookAtTradePlayer(EntityVillager theMerchantIn)
    {
        super(theMerchantIn, Player.class, 8.0F);
        this.theMerchant = theMerchantIn;
    }

    /**
     * Returns whether the EntityAIBase should begin execution.
     */
    public boolean shouldExecute()
    {
        if (this.theMerchant.isTrading())
        {
            this.closestEntity = this.theMerchant.getCustomer();
            return true;
        }
        else
        {
            return false;
        }
    }
}


text:
// snippet-start:[sqs.go.get_queue_url]
package main

// snippet-start:[sqs.go.get_queue_url.imports]
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
// snippet-end:[sqs.go.get_queue_url.imports]

// GetQueueURL gets the URL of an Amazon SQS queue
// Inputs:
//     sess is the current session, which provides configuration for the SDK's service clients
//     queueName is the name of the queue
// Output:
//     If success, the URL of the queue and nil
//     Otherwise, an empty string and an error from the call to
func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) {
    // Create an SQS service client
    // snippet-start:[sqs.go.get_queue_url.call]
    svc := sqs.New(sess)

    result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
        QueueName: queue,
    })
    // snippet-end:[sqs.go.get_queue_url.call]
    if err != nil {
        return nil, err
    }

    return result, nil
}

func main() {
    // snippet-start:[sqs.go.get_queue_url.args]
    queue := flag.String("q", "", "The name of the queue")
    flag.Parse()

    if *queue == "" {
        fmt.Println("You must supply a queue name (-q QUEUE")
        return
    }
    // snippet-end:[sqs.go.get_queue_url.args]

    // Create a session that gets credential values from ~/.aws/credentials
    // and the default region from ~/.aws/config
    // snippet-start:[sqs.go.get_queue_url.sess]
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))
    // snippet-end:[sqs.go.get_queue_url.sess]

    result, err := GetQueueURL(sess, queue)
    if err != nil {
        fmt.Println("Got an error getting the queue URL:")
        fmt.Println(err)
        return
    }

    // snippet-start:[sqs.go.get_queue_url.print]
    fmt.Println("URL: " + *result.QueueUrl)
    // snippet-end:[sqs.go.get_queue_url.print]
}
// snippet-end:[sqs.go.get_queue_url]


text:
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'HBW'
end


text:
package com.fernandocejas.android10.sample.domain.interactor;

import com.fernandocejas.android10.sample.domain.User;
import com.fernandocejas.android10.sample.domain.executor.PostExecutionThread;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import com.fernandocejas.android10.sample.domain.repository.UserRepository;
import javax.inject.Inject;
import rx.Observable;

/**
 * This class is an implementation of {@link UseCase} that represents a use case for
 * retrieving data related to an specific {@link User}.
 */
public class GetUserDetails extends UseCase {

  private final int userId;
  private final UserRepository userRepository;

  @Inject
  public GetUserDetails(int userId, UserRepository userRepository,
      ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
    super(threadExecutor, postExecutionThread);
    this.userId = userId;
    this.userRepository = userRepository;
  }

  @Override protected Observable buildUseCaseObservable() {
    return this.userRepository.user(this.userId);
  }
}


text:
import test from 'tape-catch';
import vtkContourTriangulator from 'vtk.js/Sources/Filters/General/ContourTriangulator';
import { reverseElements } from '../helper';

test('Test vtkContourTriangulator instance', (t) => {
  t.ok(vtkContourTriangulator, 'Make sure the class definition exists');
  const instance = vtkContourTriangulator.newInstance();
  t.ok(instance);
  t.end();
});

test('Test reverseElements', (t) => {
  const originalArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  const arr1 = [...originalArr];
  const arr2 = [...originalArr];

  reverseElements(arr1, 2, 7);
  t.deepEqual(arr1, [0, 1, 7, 6, 5, 4, 3, 2, 8, 9], 'reverse elements 2 to 7');

  reverseElements(arr1, 2, 7);
  t.deepEqual(arr1, originalArr, 'reversing again gives original array');

  reverseElements(arr1);
  arr2.reverse();

  t.deepEqual(arr1, arr2, 'without arguments does the same as .reverse');
  t.end();
});


text:
package org.dbsteward.maven;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

/**
 * Difference the specified DBSteward definition files, outputting the SQL
 * statements to upgrade old to new
 *
 * @author nicholas.kiraly
 */
@Mojo(name = "sql-diff", defaultPhase = LifecyclePhase.COMPILE)
public class SQLDiffMojo extends DBStewardAbstractMojo {

  /**
   * Relative or absolute path to old (previous) database definition XML file
   */
  @Parameter(property = "oldDefinitionFile", required = true)
  protected File oldDefinitionFile;

  /**
   * Relative or absolute path to new (current) database definition XML file
   */
  @Parameter(property = "newDefinitionFile", required = true)
  protected File newDefinitionFile;

  /**
   * Compile upgrade SQL files specified in plugin config
   *
   * @throws MojoExecutionException
   */
  @Override
  public void execute() throws MojoExecutionException {
    // do common setup from DBStewardAbstractMojo
    super.execute();

    getLog().info("Diffing DBSteward definitions");
    getLog().info("  Old: " + oldDefinitionFile.getPath());
    getLog().info("  New: " + newDefinitionFile.getPath());

    String[] args = {
      "--oldxml=" + oldDefinitionFile.getPath(),
      "--newxml=" + newDefinitionFile.getPath()
    };
    runDbsteward(args);

    // confirm output before returning
    // calculate upgrade files path
    String upgradeSqlFilePrefix = FilenameUtils.getBaseName(newDefinitionFile.getPath());
    upgradeSqlFilePrefix = upgradeSqlFilePrefix + "_upgrade";

    // look for files matching prefix in outputDir
    FilenameFilter fileFilter = (FilenameFilter) new WildcardFileFilter(upgradeSqlFilePrefix + "*.sql");
    File[] upgradeSqlFiles = outputDir.listFiles(fileFilter);
    Arrays.sort(upgradeSqlFiles);

    if (upgradeSqlFiles.length == 0) {
      throw new MojoExecutionException("DBSteward outputDir " + outputDir + " not found to contain any upgrade files. Check DBSteward execution output.");
    }

    // store in upgradeSqlFileNameCSL for reference by build chain
    String upgradeSqlFileNameCSL = StringUtils.join(upgradeSqlFiles, ",");
    proj.getProperties().setProperty("project.dbsteward.output.upgradeSqlFileNameCSL", upgradeSqlFileNameCSL);
  }

}


text:
<?php
namespace Chamilo\Libraries\Storage\DataManager\Doctrine\Condition;

/**
 *
 * @package Chamilo\Libraries\Storage\DataManager\Doctrine\Condition
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 * @deprecated Replaced by the ConditionPartTranslators and related service and factory
 */
class AggregateConditionTranslator extends ConditionTranslator
{

    /**
     *
     * @see \Chamilo\Libraries\Storage\Query\Condition\ConditionTranslator::translate()
     */
    public function translate()
    {
        $string = '';

        $condition_translations = array();
        $count = 0;

        foreach ($this->get_condition()->get_conditions() as $key => $condition)
        {
            $count ++;
            $translation = ConditionTranslator::render($condition);

            if (! empty($translation))
            {
                $condition_translations[] = $translation;
            }
        }

        if (count($condition_translations) > 0)
        {
            $string = '(' . implode($this->get_condition()->get_operator(), $condition_translations) . ')';
        }

        return $string;
    }
}


text:
<?php

namespace Google\AdsApi\Dfp\v201705;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class PackageStatus
{
    const IN_PROGRESS = 'IN_PROGRESS';
    const COMPLETED = 'COMPLETED';
    const UNKNOWN = 'UNKNOWN';

}


text:
<?php

namespace Torann\GeoIP;

use Illuminate\Cache\CacheManager;

class Cache
{
    /**
     * Instance of cache manager.
     *
     * @var \Illuminate\Cache\CacheManager
     */
    protected $cache;

    /**
     * Lifetime of the cache.
     *
     * @var int
     */
    protected $expires;

    /**
     * Create a new cache instance.
     *
     * @param CacheManager $cache
     * @param array        $tags
     * @param int          $expires
     */
    public function __construct(CacheManager $cache, $tags, $expires = 30)
    {
        $this->cache = $tags ? $cache->tags($tags) : $cache;
        $this->expires = $expires;
    }

    /**
     * Get an item from the cache.
     *
     * @param string $name
     *
     * @return Location|null
     */
    public function get($name)
    {
        $value = $this->cache->get($name);

        return is_array($value)
            ? new Location($value)
            : null;
    }

    /**
     * Store an item in cache.
     *
     * @param string   $name
     * @param Location $location
     *
     * @return bool
     */
    public function set($name, Location $location)
    {
        return $this->cache->put($name, $location->toArray(), $this->expires);
    }

    /**
     * Flush cache for tags.
     *
     * @return bool
     */
    public function flush()
    {
        return $this->cache->flush();
    }
}


text:
#include <QMenu>
#include <QAction>
#include <QToolButton>
#include <QScopedPointer>
#include <QPainter>
#include <QStringList>
#include <QDesktopServices>
#include <QMouseEvent>
#include <QUrl>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QUrlQuery>
#endif

#include "account.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "login-dialog.h"
#include "settings-mgr.h"
#ifdef HAVE_SHIBBOLETH_SUPPORT
#include "shib/shib-login-dialog.h"
#endif // HAVE_SHIBBOLETH_SUPPORT
#include "account-settings-dialog.h"
#include "rpc/rpc-client.h"
#include "rpc/local-repo.h"
#include "main-window.h"
#include "init-vdrive-dialog.h"
#include "auto-login-service.h"
#include "avatar-service.h"
#include "utils/paint-utils.h"
#include "filebrowser/file-browser-manager.h"
#include "api/api-error.h"
#include "api/requests.h"

#include "account-view.h"
namespace {

QStringList collectSyncedReposForAccount(const Account& account)
{
    std::vector<LocalRepo> repos;
    SeafileRpcClient *rpc = seafApplet->rpcClient();
    rpc->listLocalRepos(&repos);
    QStringList repo_ids;
    for (size_t i = 0; i < repos.size(); i++) {
        LocalRepo repo = repos[i];
        QString repo_server_url;
        if (rpc->getRepoProperty(repo.id, "server-url", &repo_server_url) < 0) {
            continue;
        }
        if (QUrl(repo_server_url).host() != account.serverUrl.host()) {
            continue;
        }
        QString token;
        if (rpc->getRepoProperty(repo.id, "token", &token) < 0 || token.isEmpty()) {
            repo_ids.append(repo.id);
        }
    }

    return repo_ids;
}

}

AccountView::AccountView(QWidget *parent)
    : QWidget(parent)
{
    setupUi(this);

    // Init account drop down menu
    account_menu_ = new QMenu;
    mAccountBtn->setMenu(account_menu_);
    mAccountBtn->setPopupMode(QToolButton::InstantPopup);
    mAccountBtn->setFixedSize(QSize(AvatarService::kAvatarSize, AvatarService::kAvatarSize));

    onAccountChanged();

    connect(AvatarService::instance(), SIGNAL(avatarUpdated(const QString&, const QImage&)),
            this, SLOT(updateAvatar()));

    mAccountBtn->setCursor(Qt::PointingHandCursor);
    mAccountBtn->installEventFilter(this);
    account_menu_->installEventFilter(this);

    connect(seafApplet->accountManager(), SIGNAL(accountRequireRelogin(const Account&)),
            this, SLOT(reloginAccount(const Account &)));
    connect(seafApplet->accountManager(), SIGNAL(requireAddAccount()),
            this, SLOT(showAddAccountDialog()));
    connect(mServerAddr, SIGNAL(linkActivated(const QString&)),
            this, SLOT(visitServerInBrowser(const QString&)));
}

void AccountView::showAddAccountDialog()
{
    LoginDialog dialog(this);
    // Show InitVirtualDriveDialog for the first account added
    AccountManager *account_mgr = seafApplet->accountManager();
    if (dialog.exec() == QDialog::Accepted
        && account_mgr->accounts().size() == 1) {

        InitVirtualDriveDialog dialog(account_mgr->currentAccount(), seafApplet->mainWindow());
#if defined(Q_OS_WIN32)
        dialog.exec();
#endif
    }
}

void AccountView::deleteAccount()
{
    QAction *action = qobject_cast<QAction*>(sender());
    if (!action)
        return;
    Account account = qvariant_cast<Account>(action->data());

    QString question = tr("Are you sure to remove account from \"%1\"?
"
                          "Warning: All libraries of this account would be unsynced!").arg(account.serverUrl.toString());

    if (seafApplet->yesOrNoBox(question, this, false)) {
        FileBrowserManager::getInstance()->closeAllDialogByAccount(account);
        QString error, server_addr = account.serverUrl.host();
        if (seafApplet->rpcClient()->unsyncReposByAccount(server_addr,
                                                          account.username,
                                                          &error) < 0) {

            seafApplet->warningBox(
                tr("Failed to unsync libraries of this account: %1").arg(error),
                this);
        }

        seafApplet->accountManager()->removeAccount(account);
    }
}

void AccountView::editAccountSettings()
{
    QAction *action = qobject_cast<QAction*>(sender());
    if (!action)
        return;
    Account account = qvariant_cast<Account>(action->data());

    AccountSettingsDialog dialog(account, this);

    dialog.exec();
}

void AccountView::updateAccountInfoDisplay()
{
    if (seafApplet->accountManager()->hasAccount()) {
        const Account account = seafApplet->accountManager()->currentAccount();
        mEmail->setText(account.username);
        // mServerAddr->setOpenExternalLinks(true);
        mServerAddr->setToolTip(tr("click to open the website"));

        QString host = account.serverUrl.host();
        QString href = account.serverUrl.toString();
        QString text = QString("%2").arg(href).arg(host);

        mServerAddr->setText(account.isPro() ? QString("%1 %2").arg(text).arg(tr("pro version")) : text);
    } else {
        mEmail->setText(tr("No account"));
        mServerAddr->setText(QString());
    }

    updateAvatar();
}

/**
 * Update the account menu when accounts changed
 */
void AccountView::onAccountChanged()
{
    const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();

    // Remove all menu items
    account_menu_->clear();

    if (!accounts.empty()) {
        for (size_t i = 0, n = accounts.size(); i < n; i++) {
            const Account &account = accounts[i];
            QString text = account.username + "(" + account.serverUrl.host() + ")";
            if (!account.isValid()) {
                text += ", " + tr("not logged in");
            }
            QMenu *submenu = new QMenu(text, account_menu_);
            if (i == 0) {
                submenu->setIcon(QIcon(":/images/account-checked.png"));
            } else {
                submenu->setIcon(QIcon(":/images/account-else.png"));
            }

            QAction *submenu_action = submenu->menuAction();
            submenu_action->setData(QVariant::fromValue(account));
            connect(submenu_action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked()));

            QAction *action = new QAction(tr("Choose"), submenu);
            action->setIcon(QIcon(":/images/account-checked.png"));
            action->setIconVisibleInMenu(true);
            action->setData(QVariant::fromValue(account));
            connect(action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked()));

            submenu->addAction(action);
            submenu->setDefaultAction(action);

            QAction *account_settings_action = new QAction(tr("Account settings"), this);
            account_settings_action->setIcon(QIcon(":/images/account-settings.png"));
            account_settings_action->setIconVisibleInMenu(true);
            account_settings_action->setData(QVariant::fromValue(account));
            connect(account_settings_action, SIGNAL(triggered()), this, SLOT(editAccountSettings()));
            submenu->addAction(account_settings_action);

            QAction *toggle_action = new QAction(this);
            toggle_action->setIcon(QIcon(":/images/logout.png"));
            toggle_action->setIconVisibleInMenu(true);
            toggle_action->setData(QVariant::fromValue(account));
            connect(toggle_action, SIGNAL(triggered()), this, SLOT(toggleAccount()));
            if (account.isValid())
                toggle_action->setText(tr("Logout"));
            else
                toggle_action->setText(tr("Login"));
            submenu->addAction(toggle_action);

            QAction *delete_account_action = new QAction(tr("Delete"), this);
            delete_account_action->setIcon(QIcon(":/images/delete-account.png"));
            delete_account_action->setIconVisibleInMenu(true);
            delete_account_action->setData(QVariant::fromValue(account));
            connect(delete_account_action, SIGNAL(triggered()), this, SLOT(deleteAccount()));
            submenu->addAction(delete_account_action);

            account_menu_->addMenu(submenu);
        }

        account_menu_->addSeparator();
    }

    add_account_action_ = new QAction(tr("Add an account"), this);
    add_account_action_->setIcon(QIcon(":/images/add-account.png"));
    add_account_action_->setIconVisibleInMenu(true);
    connect(add_account_action_, SIGNAL(triggered()), this, SLOT(showAddAccountDialog()));
    account_menu_->addAction(add_account_action_);

    updateAccountInfoDisplay();
}

QAction* AccountView::makeAccountAction(const Account& account)
{
    QString text = account.username + "(" + account.serverUrl.host() + ")";
    if (!account.isValid()) {
        text += ", " + tr("not logged in");
    }
    QAction *action = new QAction(text, account_menu_);
    action->setData(QVariant::fromValue(account));
    // action->setCheckable(true);
    // QMenu won't display tooltip for menu item
    // action->setToolTip(account.serverUrl.host());

    connect(action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked()));

    return action;
}

// Switch to the clicked account in the account menu
void AccountView::onAccountItemClicked()
{
    QAction *action = (QAction *)(sender());
    Account account = qvariant_cast<Account>(action->data());

    if (!account.isValid()) {
        reloginAccount(account);
    } else {
        seafApplet->accountManager()->setCurrentAccount(account);
    }
}

void AccountView::getRepoTokenWhenRelogin(const Account& account)
{
    QStringList repo_ids = collectSyncedReposForAccount(account);
    if (repo_ids.empty()) {
        return;
    }

    /* old account object don't contains the new token */
    QString host = account.serverUrl.host();
    QString username = account.username;
    Account new_account = seafApplet->accountManager()->getAccountByHostAndUsername(host, username);
    if (!new_account.isValid())
        return;

    GetRepoTokensRequest *req = new GetRepoTokensRequest(
        new_account, repo_ids);

    connect(req, SIGNAL(success()),
            this, SLOT(onGetRepoTokensSuccess()));
    connect(req, SIGNAL(failed(const ApiError&)),
            this, SLOT(onGetRepoTokensFailed(const ApiError&)));
    req->send();
}

void AccountView::updateAvatar()
{
    mAccountBtn->setIconSize(QSize(AvatarService::kAvatarSize, AvatarService::kAvatarSize));
    const Account account = seafApplet->accountManager()->currentAccount();
    if (!account.isValid())  {
        mAccountBtn->setIcon(QIcon(":/images/account.png"));
        return;
    }

    AvatarService *service = AvatarService::instance();

    if (service->avatarFileExists(account.username)) {
        QString icon_path = AvatarService::instance()->getAvatarFilePath(account.username);
        mAccountBtn->setIcon(QIcon(icon_path));
        return;
    }

    mAccountBtn->setIcon(QIcon(":/images/account.png"));
    // will trigger a GetAvatarRequest
    service->getAvatar(account.username);
}

bool AccountView::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == account_menu_ && event->type() == QEvent::MouseButtonRelease) {
        QMouseEvent *ev = (QMouseEvent*)event;
        QAction *action = account_menu_->actionAt(ev->pos());
        if (action) {
            action->trigger();
        }
    }
    if (obj == mAccountBtn && event->type() == QEvent::Paint) {
        QRect rect(0, 0, AvatarService::kAvatarSize, AvatarService::kAvatarSize);
        QPainter painter(mAccountBtn);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::HighQualityAntialiasing);

        // get the device pixel radio from current painter device
        int scale_factor = 1;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        scale_factor = painter.device()->devicePixelRatio();
#endif // QT5

        QPixmap image(mAccountBtn->icon().pixmap(rect.size()).scaled(scale_factor * rect.size()));
        QRect actualRect(QPoint(0, 0), image.size());

        QImage masked_image(actualRect.size(), QImage::Format_ARGB32_Premultiplied);
        masked_image.fill(Qt::transparent);
        QPainter mask_painter;
        mask_painter.begin(&masked_image);
        mask_painter.setRenderHint(QPainter::Antialiasing);
        mask_painter.setRenderHint(QPainter::HighQualityAntialiasing);
        mask_painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
        mask_painter.setPen(Qt::NoPen);
        mask_painter.setBrush(Qt::white);
        mask_painter.drawEllipse(actualRect);
        mask_painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        mask_painter.drawPixmap(actualRect, image);
        mask_painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
        mask_painter.fillRect(actualRect, Qt::transparent);
        mask_painter.end();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        masked_image.setDevicePixelRatio(scale_factor);
#endif // QT5

        painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
        painter.drawImage(QPoint(0,0), masked_image);
        return true;
    }
    return QObject::eventFilter(obj, event);
}

/**
 * Only remove the api token of the account. The accout would still be shown
 * in the account list.
 */
void AccountView::toggleAccount()
{
    QAction *action = qobject_cast<QAction*>(sender());
    if (!action)
        return;
    Account account = qvariant_cast<Account>(action->data());
    if (!account.isValid()) {
        reloginAccount(account);
        return;
    }

    // logout Account
    FileBrowserManager::getInstance()->closeAllDialogByAccount(account);
    LogoutDeviceRequest *req = new LogoutDeviceRequest(account);
    connect(req, SIGNAL(success()),
            this, SLOT(onLogoutDeviceRequestSuccess()));
    connect(req, SIGNAL(failed(const ApiError&)),
            this, SLOT(onLogoutDeviceRequestFailed(const ApiError&)));
    req->send();
}

void AccountView::reloginAccount(const Account &account)
{
    bool accepted;
    do {
#ifdef HAVE_SHIBBOLETH_SUPPORT
        if (account.isShibboleth) {
            ShibLoginDialog shib_dialog(account.serverUrl, seafApplet->settingsManager()->getComputerName(), this);
            accepted = shib_dialog.exec() == QDialog::Accepted;
            break;
        }
#endif
        LoginDialog dialog(this);
        dialog.initFromAccount(account);
        accepted = dialog.exec() == QDialog::Accepted;
    } while (0);

    if (accepted) {
        getRepoTokenWhenRelogin(account);
    }
}

void AccountView::onLogoutDeviceRequestSuccess()
{
    LogoutDeviceRequest *req = (LogoutDeviceRequest *)QObject::sender();
    const Account& account = req->account();
    QString error;
    if (seafApplet->rpcClient()->removeSyncTokensByAccount(account.serverUrl.host(),
                                                           account.username,
                                                           &error)  < 0) {
        seafApplet->warningBox(
            tr("Failed to remove local repos sync token: %1").arg(error),
            this);
        return;
    }
    seafApplet->accountManager()->clearAccountToken(account);
    req->deleteLater();
}

void AccountView::onLogoutDeviceRequestFailed(const ApiError& error)
{
    LogoutDeviceRequest *req = (LogoutDeviceRequest *)QObject::sender();
    req->deleteLater();
    QString msg;
    if (error.httpErrorCode() == 404) {
        msg = tr("Logging out is not supported on your server (version too low).");
    } else {
        msg = tr("Failed to remove information on server: %1").arg(error.toString());
    }
    seafApplet->warningBox(msg, this);
}

void AccountView::onGetRepoTokensSuccess()
{
    GetRepoTokensRequest *req = (GetRepoTokensRequest *)(sender());
    foreach (const QString& repo_id, req->repoTokens().keys()) {
        seafApplet->rpcClient()->setRepoToken(
            repo_id, req->repoTokens().value(repo_id));
    }
    req->deleteLater();
}

void AccountView::onGetRepoTokensFailed(const ApiError& error)
{
    GetRepoTokensRequest *req = (GetRepoTokensRequest *)QObject::sender();
    req->deleteLater();
    seafApplet->warningBox(
        tr("Failed to get repo sync information from server: %1").arg(error.toString()), this);
}

void AccountView::visitServerInBrowser(const QString& link)
{
    AutoLoginService::instance()->startAutoLogin("/");
}


text:
title: Buscar enlaces simbólicos
date: 2014-10-01T14:53:14+00:00
categories:
  - Linux
  - Terminal
format: aside

---
Comando para buscar enlaces simbólicos desde consola.

find . -type l -exec ls -lad {} \;


text:
require 'spec_helper'
describe Sqlite2Mysql do
  it 'does a thing' do
    Sqlite2Mysql.run(['spec/fixtures/test.db'])
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea subcrustulata Vain.

### Remarks
null


text:
toml config file, app config reader

### 查找顺序
- /tmp/config.toml

```go
import "github.com/wiloon/pingd-config"

config.GetString("group0.key0", "")
```


text:
import errorParser from "../error-parser"

describe(`query-error-parser`, () => {
  it.each([
    [
      `specific one`,
      `Variable "Foo" of required type "Bar" was not provided.`,
      `85920`,
    ],
    [`totally vague one`, `foo bar`, `85901`],
    [
      `real error`,
      `this error should show a trace`,
      `85901`,
      new Error(`this error should show a trace`),
    ],
  ])(`%s`, (_name, message, expectedId, error = undefined) => {
    const structured = errorParser({
      message,
      filePath: `test.js`,
      location: { start: { line: 5, column: 10 } },
      error: error instanceof Error ? error : undefined,
    })
    expect(structured).toMatchSnapshot()
    expect(structured.id).toEqual(expectedId)
  })
})


text:
const { assert, expect } = require('chai'),
  co = require('co'),
  request = require('request'),
  jsdom = require('jsdom');

describe('Simple tests', () => {
  it('Should pass', () => {
    assert(1 == '1');
  });

  it('Should do an async test using callbacks', (done) => {
    request.get('https://nodejs.org/dist/', (error, response, body) => {
      expect(response.statusCode).to.equal(200);
      jsdom.env(body, (error, window) => {
        const links = window.document.querySelectorAll('a');
        expect(links.length).to.equal(256);
        done();
      });
    });
  });

  const dom = html => new Promise((resolve, reject) => {
    return jsdom.env(html, (error, window) => error ? reject(error) : resolve(window))
  });

  const [ get, post ] = ['get', 'post'].map(verb => {
    return options => new Promise((resolve, reject) => {
      return request[verb](options, (error, response) => {
        return error ? reject(error) : resolve(response);
      });
    });
  });

  const test = generator => done => co(generator).then(done, done);

  it('Should run async test with promises and generators', test(function* () {
    const { statusCode, body: html } = yield get('https://nodejs.org/dist/');
    expect(statusCode).to.equal(200);
    const window = yield dom(html);
    const links = window.document.querySelectorAll('a');
    expect(links.length).to.equal(256);
    // const [ gr, yr ] = yield [get('https://google.com'), get('http://ya.ru')];
  }));
});


text:
export default class UserError extends Error {
  constructor(message: string) {
    super(message);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, UserError);
    }

    this.name = 'UserError';
  }
}


text:
var express = require('express');
var router = express.Router();
var async = require('async');
var request = require('request');
var fs = require('fs');

var validateObj = function(template, result) {
  var isValid = true;
  Object.keys(template).forEach(function(key) {
    if(!(key in result)) {
      isValid = false;
    }
  });
  return isValid;
}

var validateUrlForCitizenType = function(input, callback) {
  fs.readFile(__dirname + "/citizen-types/" + input.citizenType + '.json',
    'utf8', function (err, data) {
      if (err) {
        callback(null, null);
      } else {
        template = JSON.parse(data);
        async.map(template.endpoints, function(endpoint, callback) {
            if(endpoint.requestType == "get") {
              var url = input.url + endpoint.relativeUri;
              request.get(url,
                function(err, httpResponse, body) {
                  if(httpResponse.statusCode !== 200 || err) {callback(null, false);}
                  else {
                    var result = JSON.parse(body);
                    var isValid = validateObj(endpoint.responseTemplate, result);
                    callback(null, isValid);
                  }
                })
            }
        }, function(err, results) {
              var hasInvalidEndpoints = false;
              results.forEach(function(result) {
                  if(!result) {
                    hasInvalidEndpoints = true;
                  }
              });

              if(hasInvalidEndpoints) {
                callback(null, null)
              } else {
                callback(null, input)
              }
        })
      }
  });
}

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to the regulation api!' });
});

router.get('/enforce/all', function (req, res) {
  request.get('http://localhost:3000/government/citizenship/all',
    function(err, httpResponse, body) {
      var citizens = JSON.parse(body).citizens;
      inputs = [];
      validCitizens = [];
      citizens.forEach(function(citizen) {
          inputs.push({url: citizen.url, citizenType: citizen.citizenType});
      });
      async.map(inputs, validateUrlForCitizenType,
          function(err, results) {
              results.forEach(function(result) {
                      if(result) {
                        validCitizens.push(result);
                      }
                    });
          res.json({success: true, validCitizens: validCitizens});
        });
      })
});

router.post('/enforce/url', function (req, res) {
  var response;
  if(req.body.url && req.body.citizenTypes) {
    validCitizenTypes = [];
    inputs = [];
    req.body.citizenTypes.forEach(function(citizenType, i, arr) {
      inputs.push({citizenType: citizenType, url: req.body.url})
    })
    async.map(inputs, validateUrlForCitizenType,
        function(err, results) {
            results.forEach(function(result) {
                    if(result) {
                      validCitizenTypes.push(result.citizenType);
                    }
                  });
        res.json({success: true, validCitizenTypes: validCitizenTypes});
      });
}});

module.exports = {router: router};


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.common.engine.api.delegate.event;

/**
 * Describes a class that listens for {@link FlowableEvent}s dispatched by the engine.
 *
 * @author Frederik Heremans
 * @author Joram Barrez
 */
public interface FlowableEventListener {

    /**
     * Called when an event has been fired
     *
     * @param event the event
     */
    void onEvent(FlowableEvent event);

    /**
     * @return whether or not the current operation should fail when this listeners execution throws an exception.
     */
    boolean isFailOnException();

    /**
     * @return Returns whether this event listener fires immediately when the event occurs or
     *         on a transaction lifecycle event (before/after commit or rollback).
     */
    boolean isFireOnTransactionLifecycleEvent();

    /**
     * @return if non-null, indicates the point in the lifecycle of the current transaction when the event should be fired.
     */
    String getOnTransaction();

}


text:
        <rule-list (detailedRule)="changeDetailedRule($event)" class="mb-5"></rule-list>
        <button *ngIf="!hasIdToken" class="btn btn-primary" (click)="createUser()">Grant Offline Access</button>
        <button *ngIf="hasIdToken" type="button" (click)="toCreateView()" class="mt-3 btn btn-success">Create Rule</button>

    <rule-creator></rule-creator>
    <button type="button" (click)="toListView()" class="btn btn-secondary">Back</button>

    <rule-detail [rule]="detailedRule"></rule-detail>
    <button type="button" (click)="toListView()" class="btn btn-secondary">Back</button>


text:
This guide is to show you how to use grammars with IBM Voice Gateway. With the IBM Speech-To-Text service one can uses grammars to specify how to form valid strings from the language's alphabet. When you use a custom language model and a grammar for speech recognition, the service can return a valid phrase from the grammar or an empty result. Grammars are useful when you need to recognize specific words or phrases, such as **yes** or **no**, individual letters, numbers as well as alphanumerical combinations.

For more information on grammars with IBM Speech-To-Text service https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-grammars#grammars

First you'll need to create a custom language model as well as a grammar to use, you can follow the steps defined in: [Adding a grammar to a custom language model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-grammarAdd#grammarAdd)

Here are a some options of using grammars with IBM Voice Gateway:- [Using Grammars for Speech Recognition](#using-grammars-for-speech-recognition)

- [Setting a grammar from Watson Assistant](#setting-a-grammar-from-watson-assistant)
- [Advanced JSON Configuration](#advanced-json-configuration)

### Setting a grammar from Watson Assistant

Generally, you may want to use a grammar to recognize some kind of an expected phrase, for example matching an alpha numerical combination. By using the `vgwActSetSTTConfig` action from a Watson Assistant Dialog node you can modify the Speech recognition configuration to use grammar for just an input from the user or you can set it for the rest of the conversation.

For example, in your Watson Assistant Dialog node, specify the `vgwActSetSTTConfig`, as the action `vgwAction` to use, it would use the following structure:

```json

{
  "output": {
    "text": {
      "values": [
        "Hey, testing a grammar input!"
      ],
      "selection_policy": "sequential"
    },
    "vgwAction": {
      "command": "vgwActSetSTTConfig",
      "parameters": {
        "updateMethod": "mergeOnce",
        "config": {
          "grammar_name": "{your_grammar_name}",
          "language_customization_id": "{your_language_customization_id}"
        }
      }
    }
}
```

As you can see, `updateMethod` set to `mergeOnce` specifies that the grammar will be merged and used once on the user input. If it is set to `merge`, the grammar will be merged to the existing speech recognition configuration for the rest of the conversation.

For more information on the `vgwActSetSTTConfig` action, see [Dynamically configuring the Speech to Text service](https://www.ibm.com/support/knowledgecenter/SS4U29/dynamicstt.html) for more information.

### Advanced JSON Configuration

You can specify it through the [Advanced JSON Configuration](https://www.ibm.com/support/knowledgecenter/SS4U29/json_config_props.html). This configuration will be used for all recognition requests by the IBM Voice Gateway. You can modify the configuration using the `vgwActSetSTTConfig` action from a Watson Assistant Dialog node, see [Dynamically configuring the Speech to Text service](https://www.ibm.com/support/knowledgecenter/SS4U29/dynamicstt.html) for more information.

```javascript
{
  "tenants": [{
    "tenantURI": "2345556789",
    "description": "Voice Gateway Demo",
    "conversation": {
        ...
    },
    "stt": {
      "credentials": {
        "url": "https://stream.watsonplatform.net/speech-to-text/api",
        "username": "9h7f54cb-f28f-4a64-91e1-a0657e1dd3f4",
        "password": "password"
      },
      "config": {
        "model": "en-US_NarrowbandModel",
        "language_customization_id": "{your_customization_id}",
        "grammar_name": "{your_grammar_name}"
        "profanity_filter": true,
        "smart_formatting": true
      }
    },
    "tts": {
        ...
    }
  }]
}
```


text:
module IdentityCache
  class ExpiryHook
    def initialize(cached_association)
      @cached_association = cached_association
    end

    def install
      cached_association.validate
      entry = [parent_class, only_on_foreign_key_change?]
      child_class.parent_expiration_entries[inverse_name] << entry
    end

    private

    attr_reader :cached_association

    def only_on_foreign_key_change?
      cached_association.embedded_by_reference? && !cached_association.reflection.has_scope?
    end

    def inverse_name
      cached_association.inverse_name
    end

    def parent_class
      cached_association.reflection.active_record
    end

    def child_class
      cached_association.reflection.klass
    end
  end

  private_constant :ExpiryHook
end


text:
errmsg: __unset() must take exactly 1 argument
--FILE--
<?php

class test {
	function __unset() {
	}
}

echo "Done\n";
?>
--EXPECTF--
Fatal error: Method test::__unset() must take exactly 1 argument in %s on line %d


text:
package org.sagebionetworks.web.client.resources;

import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface ResourceLoader {

	/**
	 * Require certain web resources
	 *
	 * @param resources
	 * @param loadedCallback
	 */
	void requires(WebResource resource, AsyncCallback<Void> loadedCallback);

	/**
	 * Require certain web resources
	 *
	 * @param resources
	 * @param loadedCallback
	 */
	void requires(List<WebResource> resources, AsyncCallback<Void> loadedCallback);

	boolean isLoaded(WebResource resource);
}


text:
'use strict';

describe('Directive: markdowntf', function () {

    // load the directive's module
    beforeEach(module('yeoMeanApp'));

    var element,
        scope;

    beforeEach(inject(function ($rootScope) {
        scope = $rootScope.$new();
    }));
    //Please excuse the horrible worthless test, I'll hopefully make it do something someday
    it('should pass', inject(function ($compile) {
        element = angular.element('');
        element = $compile(element)(scope);
        expect(element.text()).toBe('');
    }));
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Catalog Entries for Indexes</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.10 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Index Access Method Interface Definition"
HREF="indexam.html"><LINK
REL="PREVIOUS"
TITLE="Index Access Method Interface Definition"
HREF="indexam.html"><LINK
REL="NEXT"
TITLE="Index Access Method Functions"
HREF="index-functions.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2012-09-19T22:08:45">

PostgreSQL 9.0.10 Documentation

Prev	Up	Chapter 51. Index Access Method Interface Definition	Next

51.1. Catalog Entries for Indexes

   Each index access method is described by a row in the
   <TT
CLASS="STRUCTNAME"
>pg_am</TT
> system catalog (see
   Section 45.3).  The principal contents of a
   <TT
CLASS="STRUCTNAME"
>pg_am</TT
> row are references to
   <TT
CLASS="STRUCTNAME"
>pg_proc</TT
>
   entries that identify the index access
   functions supplied by the access method.  The APIs for these functions
   are defined later in this chapter.  In addition, the
   <TT
CLASS="STRUCTNAME"
>pg_am</TT
> row specifies a few fixed properties of
   the access method, such as whether it can support multicolumn indexes.
   There is not currently any special support
   for creating or deleting <TT
CLASS="STRUCTNAME"
>pg_am</TT
> entries;
   anyone able to write a new access method is expected to be competent
   to insert an appropriate row for themselves.

   To be useful, an index access method must also have one or more
   operator families and
   operator classes defined in
   <TT
CLASS="STRUCTNAME"
>pg_opfamily</TT
>,
   <TT
CLASS="STRUCTNAME"
>pg_opclass</TT
>,
   <TT
CLASS="STRUCTNAME"
>pg_amop</TT
>, and
   <TT
CLASS="STRUCTNAME"
>pg_amproc</TT
>.
   These entries allow the planner
   to determine what kinds of query qualifications can be used with
   indexes of this access method.  Operator families and classes are described
   in Section 35.14, which is prerequisite material for reading
   this chapter.

   An individual index is defined by a
   <TT
CLASS="STRUCTNAME"
>pg_class</TT
>
   entry that describes it as a physical relation, plus a
   <TT
CLASS="STRUCTNAME"
>pg_index</TT
>
   entry that shows the logical content of the index — that is, the set
   of index columns it has and the semantics of those columns, as captured by
   the associated operator classes.  The index columns (key values) can be
   either simple columns of the underlying table or expressions over the table
   rows.  The index access method normally has no interest in where the index
   key values come from (it is always handed precomputed key values) but it
   will be very interested in the operator class information in
   <TT
CLASS="STRUCTNAME"
>pg_index</TT
>.  Both of these catalog entries can be
   accessed as part of the <TT
CLASS="STRUCTNAME"
>Relation</TT
> data structure that is
   passed to all operations on the index.

   Some of the flag columns of <TT
CLASS="STRUCTNAME"
>pg_am</TT
> have nonobvious
   implications.  The requirements of <TT
CLASS="STRUCTFIELD"
>amcanunique</TT
>
   are discussed in Section 51.5.
   The <TT
CLASS="STRUCTFIELD"
>amcanmulticol</TT
> flag asserts that the
   access method supports multicolumn indexes, while
   <TT
CLASS="STRUCTFIELD"
>amoptionalkey</TT
> asserts that it allows scans
   where no indexable restriction clause is given for the first index column.
   When <TT
CLASS="STRUCTFIELD"
>amcanmulticol</TT
> is false,
   <TT
CLASS="STRUCTFIELD"
>amoptionalkey</TT
> essentially says whether the
   access method allows full-index scans without any restriction clause.
   Access methods that support multiple index columns must
   support scans that omit restrictions on any or all of the columns after
   the first; however they are permitted to require some restriction to
   appear for the first index column, and this is signaled by setting
   <TT
CLASS="STRUCTFIELD"
>amoptionalkey</TT
> false.
   <TT
CLASS="STRUCTFIELD"
>amindexnulls</TT
> asserts that index entries are
   created for NULL key values.  Since most indexable operators are
   strict and hence cannot return TRUE for NULL inputs,
   it is at first sight attractive to not store index entries for null values:
   they could never be returned by an index scan anyway.  However, this
   argument fails when an index scan has no restriction clause for a given
   index column.  In practice this means that
   indexes that have <TT
CLASS="STRUCTFIELD"
>amoptionalkey</TT
> true must
   index nulls, since the planner might decide to use such an index
   with no scan keys at all.  A related restriction is that an index
   access method that supports multiple index columns must
   support indexing null values in columns after the first, because the planner
   will assume the index can be used for queries that do not restrict
   these columns.  For example, consider an index on (a,b) and a query with
   <TT
CLASS="LITERAL"
>WHERE a = 4</TT
>.  The system will assume the index can be
   used to scan for rows with <TT
CLASS="LITERAL"
>a = 4</TT
>, which is wrong if the
   index omits rows where <TT
CLASS="LITERAL"
>b</TT
> is null.
   It is, however, OK to omit rows where the first indexed column is null.
   Thus, <TT
CLASS="STRUCTFIELD"
>amindexnulls</TT
> should be set true only if the
   index access method indexes all rows, including arbitrary combinations of
   null values.  An index access method that sets
   <TT
CLASS="STRUCTFIELD"
>amindexnulls</TT
> may also set
   <TT
CLASS="STRUCTFIELD"
>amsearchnulls</TT
>, indicating that it supports
   <TT
CLASS="LITERAL"
>IS NULL</TT
> and <TT
CLASS="LITERAL"
>IS NOT NULL</TT
> clauses as search
   conditions.

Prev	Home	Next

Index Access Method Interface Definition	Up	Index Access Method Functions


text:
<?php
require("functions/logincheck.php");
require("functions/cmum.php");

if(isset($_POST["user"]) && $_POST["user"]<>"") {
	if(!isset($_POST["profiles"])) {
		$profiles="";
	} else {
		$profiles=$_POST["profiles"];
	}
	$status=adduser($_POST["user"],$_POST["password"],$_POST["displayname"],$_POST["email"],$_POST["ipmask"],$_POST["maxconn"],$_POST["ecmrate"],$_POST["customvalues"],$_POST["usrgroup"],$_POST["admin"],$_POST["enabled"],$_POST["mapexclude"],$_POST["debug"],$_POST["startdate"],$_POST["expiredate"],$profiles,$_POST["boxtype"],$_POST["macaddress"],$_POST["serialnumber"],$_POST["comment"]);
		if($status=="0") {
			$notice="toastr.success('User successfully created');";
		} elseif($status=="1") {
			$notice="toastr.error('You must enter a username and a password');";
		} elseif($status=="2") {
			$notice="toastr.error('Username already exists');";
		}
}

$mysqli=new mysqli($dbhost,$dbuser,$dbpass,$dbname);
if(mysqli_connect_errno()) {
	errorpage("MYSQL DATABASE ERROR",mysqli_connect_error(),$charset,CMUM_TITLE,$_SERVER["REQUEST_URI"],CMUM_VERSION,CMUM_BUILD,CMUM_MOD);
	exit;
}
	if($_SESSION[$secretkey."admlvl"]=="0" ||  $_SESSION[$secretkey."admlvl"]=="1") {
		$grpsql=$mysqli->query("SELECT id,name FROM groups ORDER BY name ASC");
	} elseif($_SESSION[$secretkey."admlvl"]=="2" && $_SESSION[$secretkey."admgrp"]<>"0") {
		$grpsql=$mysqli->query("SELECT id,name FROM groups WHERE id='".$mysqli->real_escape_string($_SESSION[$secretkey."admgrp"])."' ORDER BY name ASC");
	} else {
		$grpsql="";
	}
	$profsql=$mysqli->query("SELECT id,name FROM profiles ORDER BY name ASC");
	$defprofsql=$mysqli->query("SELECT id,name FROM profiles ORDER BY name ASC");
	$setsql=$mysqli->query("SELECT rndstring,rndstringlength,def_autoload,def_ipmask,def_profiles,def_maxconn,def_admin,def_enabled,def_mapexc,def_debug,def_custcspval,def_ecmrate FROM settings WHERE id='1'");
		$setres=$setsql->fetch_array();
mysqli_close($mysqli);

$counters=explode(";",counter());
?>
<!DOCTYPE html>

		<meta charset="<?php print($charset); ?>">
		<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
		<meta name="robots" content="NOODP, NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET">
		<title><?php print(CMUM_TITLE); ?></title>
		<link rel="stylesheet" href="css/bootstrap.min.css">
		<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
		<link rel="stylesheet" href="css/styles.css">
		<link rel="stylesheet" href="css/datepicker.css">
		<link rel="stylesheet" href="css/toastr.min.css">
		<link rel="shortcut icon" href="favicon.ico">
		<link rel="apple-touch-icon" href="favicon.png">

	<body onload="<?php if(isset($notice)) { print($notice); } if($setres["def_autoload"]=="1") { print(" loaddef();"); }?> ">
		<?php
			require("includes/header.php");
		?>

<?php if($_SESSION[$secretkey."fetchcsp"]=="1") { print(dashcheckcspconn($cspconnstatus)); } ?>
Dashboard

<?php print($counters[0]); ?>
Users

								<?php
									if($_SESSION[$secretkey."admlvl"]=="0") {
										print("
".$counters[1]."
Groups
");
										print("
".$counters[2]."
Profiles
");
										print("
".$counters[3]."
Admins
");
										print("

Tools
");
										print("

Settings
");
									}
								?>

						<button class="btn pull-right" onclick="loaddef();">Load Defaults</button>
						<form name="newuser" id="newuser" action="newuser.php" method="post" class="form-horizontal">

User Info

										Username

											<input type="text" name="user" id="user" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" ondblclick="autouser('user');" maxlength="30" autofocus>

										Password

											<input type="text" name="password" id="password" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" ondblclick="autouser('password');" maxlength="30">

										Displayname

											<input type="text" name="displayname" id="displayname" maxlength="50">

										Email

											<input type="text" name="email" id="email" maxlength="254">

										IP mask

											<input type="text" name="ipmask" id="ipmask" maxlength="15">

										Max connections

											<input type="text" name="maxconn" id="maxconn" onkeypress="return onlynumbers(event);" maxlength="4">

										Ecm rate

											<input type="text" name="ecmrate" id="ecmrate" maxlength="4">

										Custom CSP values

											<input type="text" name="customvalues" id="customvalues" maxlength="255">

										Group

											<select name="usrgroup" id="usrgroup">
												<?php
													if($_SESSION[$secretkey."admlvl"]=="0" ||  $_SESSION[$secretkey."admlvl"]=="1") {
														print("<option value=\"\"></option>");
													}
													while($grpres=$grpsql->fetch_array()) {
														print("<option value=\"".$grpres["id"]."\">".$grpres["name"]."</option>");
													}
												?>
											</select>

											Admin

												<select name="admin" id="admin">
													<option value=""></option>
													<option value="1">True</option>
													<option value="0">False</option>
												</select>

										Enabled

											<select name="enabled" id="enabled">
												<option value=""></option>
												<option value="1">True</option>
												<option value="0">False</option>
											</select>

										Map exclude

											<select name="mapexclude" id="mapexclude">
												<option value=""></option>
												<option value="1">True</option>
												<option value="0">False</option>
											</select>

										Debug

											<select name="debug" id="debug">
												<option value=""></option>
												<option value="1">True</option>
												<option value="0">False</option>
											</select>

										Start date

											<input type="text" name="startdate" id="startdate" data-date-format="yyyy-mm-dd">

										Expire date

											<input type="text" name="expiredate" id="expiredate" data-date-format="yyyy-mm-dd">

Profiles

										Profile(s)

													<?php
														$numprof=$profsql->num_rows;
														$row=0;
															while($profres=$profsql->fetch_array()) {
																if($row==0) {
																	print("
");
																	print("<input type=\"checkbox\" name=\"profiles[]\" value=\"".$profres["id"]."\" id=\"".$profres["id"]."\"> ".$profres["name"]."	");
																}
																if($row==1) {
																	print("<input type=\"checkbox\" name=\"profiles[]\" value=\"".$profres["id"]."\" id=\"".$profres["id"]."\"> ".$profres["name"]."	");
																}
																if($row==2) {
																	print("<input type=\"checkbox\" name=\"profiles[]\" value=\"".$profres["id"]."\" id=\"".$profres["id"]."\"> ".$profres["name"]."	");
																	print("
");
																}
															$row++;
																if($row==3) {
																	$row=0;
																}
															}
													?>

												<?php
													if($numprof==0) {
														print("No profiles added!");
													} else {
														print("<input type=\"checkbox\" name=\"allprof\" onclick=\"checkedallprof('newuser')\"> All profiles</all>");
													}
												?>

Extra Info

										Boxtype

											<input type="text" name="boxtype" id="boxtype" maxlength="30">

										MAC address

											<input type="text" name="macaddress" id="macaddress" maxlength="23">

										Serialnumber

											<input type="text" name="serialnumber" id="serialnumber" maxlength="128">

										Comment

											<textarea name="comment" id="comment" rows="4" style="resize: none;" maxlength="255"></textarea>

						</form>
							<button class="btn" name="badd" value="Add User" onclick="checkusername(<?php echo checksetting("invalidcharcheck"); ?>);">Add User</button>

		<?php
			require("includes/modal-logout.php");
			require("includes/footer.php");
		?>


text: set UZ_HOME=C:/home/projects/uz-location/temp


text:
#include "Matrix.h"

namespace Kore {
	class Quaternion {
	public:
		Quaternion();
		Quaternion(float x, float y, float z, float w);
		Quaternion(const vec3& axis, float radians);
		Quaternion slerp(float t, const Quaternion& q) const;
		Quaternion rotated(const Quaternion& b) const;
		Quaternion scaled(float scale) const;
		float dot(const Quaternion& q) const;
		mat4 matrix() const;
		Quaternion operator+(const Quaternion& q) const;
		Quaternion operator+(const vec3& v) const;
		void operator+=(const vec3& v);
		Quaternion operator*(const Quaternion& r) const;
		Quaternion operator-(const Quaternion& q) const;
		bool operator==(const Quaternion& q) const;
		bool operator!=(const Quaternion& q) const;
		void normalize();
		void rotate(const Quaternion& q2);
		Quaternion conjugate() const;
		Quaternion invert() const;

		float x, y, z, w;
	};
}


text:
Coursera Get and Cleaning Data Project

# Project description

The project uses the "Human Activity Recognition Using Smartphones" data set available here:

http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones

Direct link to the data set:

https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip

The original experiment consisted in recording measurement data from the gyroscope and accelerometers of mobile phones carried by subjets on their waist; the recordings were then processed to provide various kind of data. During the experiment, subjects were requested to perform various activities, like sitting, walking, standing etc...

The Coursera project consists in consolidating, tidying and selecting a subset of the data from the original dataset, and perform some operations on it.

# Script

The script performing the required operations is called [run_analysis.R](run_analysis.R), and can be found in this repository. It was developped and tested using R Studio 0.98.1102 and R 3.1.2 for windows.

Usage:

1. Put the script ([run_analysis.R](run_analysis.R)) in your working directory
2. Unzip the original data set in the same working directory. The files will be located in a subdirectory called "UCI HAR Dataset\".
3. Make sure you have dplyr package installed in your environment. If not, use the following command:

		install.packages("dplyr")

4. Run the script
5. Two files will be generated:

   * [tidy_means_per_activity_and_subject.txt](tidy_means_per_activity_and_subject.txt): contains the generated data set
   * [column_names.txt](column_names.txt): column names, not required for the project, provided for convenience.

# Codebook

The codebook is in the file named [Codebook.md](Codebook.md) in the Github repository.


text:
This part of workshops will teach you how to create Cart Price Rules.
###1. Cart price rules
More info: http://docs.magento.com/m2/ce/user_guide/marketing/price-rules-cart.html

The best way to see a difference between catalog and cart price rules is the place where your client see a discount. If we create catalog price rule we see a discount in category view, search view and product view. Rules created in cart price rules are visible olny in shopping cart. In mostly cases you activate discount by typing special coupon code.
  _Cart price rules is an easy way to create special coupon codes, for example for new user in welcome mail._
   * TASK:
    Create cart price rule that will discount all products in cart if cost of products is higher than 100$/zl
   * TASK:
    Create cart price rule with special code for -15% for new users.

###2. Types of actions in cart price rules
  * Percent of product price discount
  * Fixed amount discount
  * Fixed amount discount for whole cart
  * Buy X get Y free - Defines a quantity that the customer must purchase to receive a quantity for free. (The Discount Amount is Y.)


text:
/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

global
{
	content-background-color: #202020;
}


text:
#import "XCUIElement+FBTap.h"

#import "FBRunLoopSpinner.h"
#import "FBLogger.h"
#import "FBMathUtils.h"
#import "XCUIElement+FBUtilities.h"
#import "XCElementSnapshot-Hitpoint.h"
#import "XCEventGenerator.h"
#import "XCSynthesizedEventRecord.h"

@implementation XCUIElement (FBTap)

- (BOOL)fb_tapWithError:(NSError **)error
{
  [self fb_waitUntilFrameIsStable];
  __block BOOL didSucceed;
  [FBRunLoopSpinner spinUntilCompletion:^(void(^completion)()){
    NSValue *hitpointValue = self.lastSnapshot.suggestedHitpoints.firstObject;
    CGPoint hitPoint = hitpointValue ? hitpointValue.CGPointValue : [self coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)].screenPoint;
    hitPoint = FBInvertPointForApplication(hitPoint, self.application.frame.size, self.application.interfaceOrientation);
    XCEventGeneratorHandler handlerBlock = ^(XCSynthesizedEventRecord *record, NSError *commandError) {
      if (commandError) {
        [FBLogger logFmt:@"Failed to perform tap: %@", commandError];
      }
      if (error) {
        *error = commandError;
      }
      didSucceed = (commandError == nil);
      completion();
    };
    XCEventGenerator *eventGenerator = [XCEventGenerator sharedGenerator];
    if ([eventGenerator respondsToSelector:@selector(tapAtTouchLocations:numberOfTaps:orientation:handler:)]) {
      [eventGenerator tapAtTouchLocations:@[[NSValue valueWithCGPoint:hitPoint]] numberOfTaps:1 orientation:self.interfaceOrientation handler:handlerBlock];
    }
    else {
      [eventGenerator tapAtPoint:hitPoint orientation:self.interfaceOrientation handler:handlerBlock];
    }
  }];
  return didSucceed;
}

@end


text:
package com.twofortyfouram.locale.sdk.host.model;

import android.os.Parcel;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import com.twofortyfouram.locale.sdk.host.test.fixture.PluginInstanceDataFixture;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

@RunWith(AndroidJUnit4.class)
public final class PluginInstanceDataTest {

    @SmallTest
    @Test
    public void getType() {
        final PluginInstanceData data = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertThat(data.getType(), is(PluginInstanceDataFixture.DEFAULT_TYPE));
    }

    @SmallTest
    @Test
    public void getRegistryName() {
        final PluginInstanceData data = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertThat(data.getRegistryName(), is(PluginInstanceDataFixture.DEFAULT_REGISTRY_NAME));
    }

    @SmallTest
    @Test
    public void testGetBlurb() {
        final PluginInstanceData data = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertThat(data.getBlurb(), is(PluginInstanceDataFixture.DEFAULT_BLURB));
    }

    @SmallTest
    @Test
    public void getSerializedBundle() {
        final PluginInstanceData data = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertArrayEquals(PluginInstanceDataFixture.getDefaultBundle(),
                data.getSerializedBundle());
    }

    @SmallTest
    @Test
    public void getSerializedBundle_copy() {
        final PluginInstanceData data = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertThat(data.getSerializedBundle(), not(sameInstance(data.getSerializedBundle())));
    }

    @SmallTest
    @Test
    public void equalsContract() {
        PluginInstanceData defaultData = PluginInstanceDataFixture.newDefaultPluginInstanceData();

        assertEquals(defaultData, defaultData);
        assertEquals(defaultData, PluginInstanceDataFixture
                .newDefaultPluginInstanceData());

        assertNotEquals(defaultData,
                new PluginInstanceData(PluginType.CONDITION,
                        PluginInstanceDataFixture.DEFAULT_REGISTRY_NAME,
                        PluginInstanceDataFixture.getDefaultBundle(),
                        PluginInstanceDataFixture.DEFAULT_BLURB)
        );

        assertNotEquals(defaultData,
                new PluginInstanceData(PluginInstanceDataFixture.DEFAULT_TYPE,
                        Plugin.generateRegistryName("bar", "foo"),
                        PluginInstanceDataFixture.getDefaultBundle(),
                        PluginInstanceDataFixture.DEFAULT_BLURB)
        );

        assertNotEquals(defaultData,
                new PluginInstanceData(PluginInstanceDataFixture.DEFAULT_TYPE,
                        PluginInstanceDataFixture.DEFAULT_REGISTRY_NAME, "bar".getBytes(),
                        PluginInstanceDataFixture.DEFAULT_BLURB)
        );

        assertNotEquals(defaultData,
                new PluginInstanceData(PluginInstanceDataFixture.DEFAULT_TYPE,
                        PluginInstanceDataFixture.DEFAULT_REGISTRY_NAME,
                        PluginInstanceDataFixture.getDefaultBundle(),
                        "bork")
        );
    }

    @SmallTest
    @Test
    public void toString_not_null() {
        final PluginInstanceData defaultData = PluginInstanceDataFixture
                .newDefaultPluginInstanceData();
        final String stringified = defaultData.toString();

        assertThat(stringified, notNullValue());
    }

    @SmallTest
    @Test
    public void toString_contains_type() {
        final PluginInstanceData defaultData = PluginInstanceDataFixture
                .newDefaultPluginInstanceData();
        final String stringified = defaultData.toString();
        assertThat(stringified, containsString(PluginInstanceDataFixture.DEFAULT_TYPE.name()));
    }

    @SmallTest
    @Test
    public void toString_contains_registry_name() {
        final PluginInstanceData defaultData = PluginInstanceDataFixture
                .newDefaultPluginInstanceData();
        final String stringified = defaultData.toString();
        assertThat(stringified, containsString(PluginInstanceDataFixture.DEFAULT_REGISTRY_NAME));
    }

    @SmallTest
    @Test
    public void toString_contains_blurb() {
        final PluginInstanceData defaultData = PluginInstanceDataFixture
                .newDefaultPluginInstanceData();
        final String stringified = defaultData.toString();
        assertThat(stringified, containsString(PluginInstanceDataFixture.DEFAULT_BLURB));
    }

    @SmallTest
    @Test
    public void parcelable() {
        final Parcel parcel = Parcel.obtain();
        try {
            final PluginInstanceData data = PluginInstanceDataFixture
                    .newDefaultPluginInstanceData();

            data.writeToParcel(parcel, 0);

            parcel.setDataPosition(0);
            final PluginInstanceData unparceled = PluginInstanceData.CREATOR
                    .createFromParcel(parcel);

            assertThat(unparceled, is(data));
        } finally {
            parcel.recycle();
        }
    }
}


text:
DEPENDS    = [ 'base', 'dialog', 'humans' ]

import politics

def get_data(k):

    politics.get_data(k)


text:
#pragma once

#include <string>
#include <atomic>
#include <future>
#include <optional>

#include <glm/glm.hpp>
#include <boost/lockfree/queue.hpp>

#include "input.h"

namespace Vingine {
	class InputManager;

	/*
		A pure virtual class that defines the interface for a window
		An implementation of a window is extremely _OS-specific,
		thus different implementations may work extremely different

		All implementations of the Window class have to guarantuee thread-safety,
		they should be implemented using a queue-based system
	*/
	class WindowBase {
	public:
		/*
			The base constructor only sets some trivial variables
		*/
		WindowBase() :
			mRunning(true),
			mInputManager(nullptr)
			{ /*Empty*/ }

		/*
			Another constructor also sets the InputManager
		*/
		WindowBase(InputManager * inputManager) :
			mRunning(true),
			mInputManager(inputManager)
			{ /*Empty*/ }

		/*
			Destructor, unfortunately it needs to have an implementation as per the standard
		*/
		virtual ~WindowBase() { /*Empty*/ };

		/*
			The main window loop might not be needed for some implementations
		*/
		virtual void Run() = 0;

		/*
			Exiting the main-loop forcefully
		*/
		virtual void Quit() = 0;

		/*
			Manual window manipulation
		*/
		virtual glm::uvec2 GetSize() const = 0;
		virtual glm::ivec2 GetPosition() const = 0;
		virtual void Resize(glm::uvec2 size) = 0;
		virtual void Reposition(glm::ivec2 position) = 0;
		virtual void Rearrange(glm::ivec2 position, glm::uvec2 size) = 0;

		/*
			Fullscreen is the usual option in which the full resolution of the screen is used
		*/
		virtual bool IsFullscreen() const = 0;
		virtual void ToggleFullscreen() = 0;

		/*
			Fullsize will keep the window in 'windowed' mode while using all non-system-occupied space
		*/
		virtual bool IsFullsize() const = 0;
		virtual void ToggleFullsize() = 0;

		/*
			A minimized window is not visible
		*/
		virtual bool IsMinimized() const = 0;
		virtual void ToggleMinimized() = 0;

		/*
			A focused window has more system resources
		*/
		virtual bool IsFocused() const = 0;

		/*
			A hidden cursor can't be seen, du'h
		*/
		virtual bool IsCursorHidden() const = 0;
		virtual void ToggleCursorHidden() = 0;

		/*
			A captured cursor will not kill the windows focus when it barely moves out of the window
		*/
		virtual bool IsCursorCapture() const = 0;
		virtual void ToggleCursorCaptured() = 0;

		/*
			Changing the cursor while inside the window
		*/
		enum class CursorType {
			Custom = -1,
			Default = 0,
			Loading = 1
		};
		virtual CursorType GetCursor() const = 0;
		virtual void SetCursor(CursorType cursor) = 0;
		virtual void SetCursor(const std::string & cursorFile,
							   const glm::ivec2 & size) = 0;

		/*
			Changing the icon of the window
		*/
		enum class IconType {
			Custom = -1,
			Default = 0
		};
		virtual IconType GetIcon() const = 0;
		virtual void SetIcon(IconType icon) = 0;
		virtual void SetIcon(const std::string & iconFile,
							 const std::optional<glm::ivec2> & smallSize,
							 const std::optional<glm::ivec2> & bigSize) = 0;

		/*
			A window can have no window to guarantuee correct client area size
		*/
		virtual bool HasBorder() const = 0;
		virtual void ToggleBorder() = 0;

		/*
			Changing the name of the window
		*/
		virtual std::string GetName() const = 0;
		virtual void SetName(const std::string & name) = 0;

		/*
			Changing the behaviour of the window
		*/
		virtual bool IsUserResizable() const = 0;
		virtual bool IsUserMovable() const = 0;
		virtual void SetUserResizable(bool userResizable) = 0;

	protected:
		/*
			State variable to check if the update loop is still runnning
		*/
		std::atomic<bool> mRunning;

		/*
			The InputManager to register key- and button-events to
		*/
		InputManager * mInputManager;

		/*
			Note that an implementation can decide how to keep track of it's state
			and thus may use no private members at all but instead query the state
			from the window manager when it is asked for it
		*/
	};
}