text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.worker;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.sandbox.SandboxHelpers;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxOutputs;
import com.google.devtools.build.lib.shell.Subprocess;
import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.shell.SubprocessFactory;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import javax.annotation.Nullable;

/**
 * An intermediate worker that sends requests and receives responses from the worker processes.
 * There is at most one of these per {@code WorkerKey}, corresponding to one worker process. {@code
 * WorkerMultiplexer} objects run in separate long-lived threads. {@code WorkerProxy} objects call
 * into them to send requests. When a worker process returns a {@code WorkResponse}, {@code
 * WorkerMultiplexer} wakes up the relevant {@code WorkerProxy} to retrieve the response.
 */
public class WorkerMultiplexer {
  /**
   * A queue of {@link WorkRequest} instances that need to be sent to the worker. {@link
   * WorkerProxy} instances add to this queue, while the requestSender subthread remove requests and
   * send them to the worker. This prevents dynamic execution interrupts from corrupting the {@code
   * stdin} of the worker process.
   */
  @VisibleForTesting final BlockingQueue<WorkRequest> pendingRequests = new LinkedBlockingQueue<>();
  /**
   * A map of {@code WorkResponse}s received from the worker process. They are stored in this map
   * keyed by the request id until the corresponding {@code WorkerProxy} picks them up.
   */
  private final ConcurrentMap<Integer, WorkResponse> workerProcessResponse =
      new ConcurrentHashMap<>();
  /**
   * A map of semaphores corresponding to {@code WorkRequest}s. After sending the {@code
   * WorkRequest}, {@code WorkerProxy} will wait on a semaphore to be released. {@code
   * WorkerMultiplexer} is responsible for releasing the corresponding semaphore in order to signal
   * {@code WorkerProxy} that the {@code WorkerResponse} has been received.
   */
  private final ConcurrentMap<Integer, Semaphore> responseChecker = new ConcurrentHashMap<>();
  /**
   * The worker process that this WorkerMultiplexer should be talking to. This should only be set
   * once, when creating a new process. If the process dies or its stdio streams get corrupted, the
   * {@code WorkerMultiplexer} gets discarded as well and a new one gets created as needed.
   */
  @VisibleForTesting Subprocess process;
  /** The implementation of the worker protocol (JSON or Proto). */
  private WorkerProtocolImpl workerProtocol;
  /** InputStream from the worker process. */
  private RecordingInputStream recordingStream;
  /** True if this multiplexer was explicitly destroyed. */
  private boolean wasDestroyed;
  /**
   * The log file of the actual running worker process. It is shared between all WorkerProxy
   * instances for this multiplexer.
   */
  private final Path logFile;

  /** The worker key that this multiplexer is for. */
  private final WorkerKey workerKey;

  /** For testing only, allow a way to fake subprocesses. */
  private SubprocessFactory subprocessFactory;

  /** A separate thread that sends requests. */
  private Thread requestSender;

  /** A separate thread that receives responses. */
  private Thread responseReceiver;

  /**
   * The active Reporter object, non-null if {@code --worker_verbose} is set. This must be cleared
   * at the end of a command execution.
   */
  private EventHandler reporter;

  /**
   * Shutdown hook to make sure we wait for the process to finish on JVM shutdown, to avoid creating
   * zombie processes. Unfortunately, shutdown hooks are not guaranteed to be called, but this is
   * the best we can do. This must be set when a process is created.
   */
  private Thread shutdownHook;

  WorkerMultiplexer(Path logFile, WorkerKey workerKey) {
    this.logFile = logFile;
    this.workerKey = workerKey;
  }

  /** Sets or clears the reporter for outputting verbose info. */
  synchronized void setReporter(@Nullable EventHandler reporter) {
    this.reporter = reporter;
  }

  /** Reports a string to the user if reporting is enabled. */
  private synchronized void report(@Nullable String s) {
    if (this.reporter != null && s != null) {
      this.reporter.handle(Event.info(s));
    }
  }

  /**
   * Creates a worker process corresponding to this {@code WorkerMultiplexer}, if it doesn't already
   * exist. Also starts up the subthreads handling reading and writing requests and responses, and
   * sets up the sandbox root dir with the required worker files.
   */
  public synchronized void createSandboxedProcess(
      Path workDir, Set<PathFragment> workerFiles, SandboxInputs inputFiles) throws IOException {
    // TODO: Make blaze clean remove the workdir.
    if (this.process == null) {
      // This should be a once-only operation.
      workDir.createDirectoryAndParents();
      workDir.deleteTreesBelow();
      LinkedHashSet<PathFragment> dirsToCreate = new LinkedHashSet<>();
      Set<PathFragment> inputsToCreate = new HashSet<>();
      SandboxHelpers.populateInputsAndDirsToCreate(
          ImmutableSet.of(),
          inputsToCreate,
          dirsToCreate,
          workerFiles,
          SandboxOutputs.getEmptyInstance().files(),
          SandboxOutputs.getEmptyInstance().dirs());
      SandboxHelpers.cleanExisting(
          workDir.getParentDirectory(), inputFiles, inputsToCreate, dirsToCreate, workDir);
      SandboxHelpers.createDirectories(dirsToCreate, workDir, /* strict=*/ false);
      WorkerExecRoot.createInputs(inputsToCreate, inputFiles.limitedCopy(workerFiles), workDir);
      createProcess(workDir);
    }
  }

  /**
   * Creates a worker process corresponding to this {@code WorkerMultiplexer}, if it doesn't already
   * exist. Also starts up the subthreads handling reading and writing requests and responses.
   */
  public synchronized void createProcess(Path workDir) throws IOException {
    if (this.process == null) {
      if (this.wasDestroyed) {
        throw new IOException("Multiplexer destroyed before created process");
      }
      this.shutdownHook =
          new Thread(
              () -> {
                this.shutdownHook = null;
                this.destroyMultiplexer();
              });
      Runtime.getRuntime().addShutdownHook(shutdownHook);
      ImmutableList<String> args = workerKey.getArgs();
      File executable = new File(args.get(0));
      if (!executable.isAbsolute() && executable.getParent() != null) {
        List<String> newArgs = new ArrayList<>(args);
        newArgs.set(0, new File(workDir.getPathFile(), newArgs.get(0)).getAbsolutePath());
        args = ImmutableList.copyOf(newArgs);
      }
      SubprocessBuilder processBuilder =
          subprocessFactory != null
              ? new SubprocessBuilder(subprocessFactory)
              : new SubprocessBuilder();
      processBuilder.setArgv(args);
      processBuilder.setWorkingDirectory(workDir.getPathFile());
      processBuilder.setStderr(logFile.getPathFile());
      processBuilder.setEnv(workerKey.getEnv());
      this.process = processBuilder.start();
      recordingStream = new RecordingInputStream(process.getInputStream());
      recordingStream.startRecording(4096);
      if (workerProtocol == null) {
        switch (workerKey.getProtocolFormat()) {
          case JSON:
            workerProtocol = new JsonWorkerProtocol(process.getOutputStream(), recordingStream);
            break;
          case PROTO:
            workerProtocol = new ProtoWorkerProtocol(process.getOutputStream(), recordingStream);
            break;
        }
      }
      String id = workerKey.getMnemonic() + "-" + workerKey.hashCode();
      // TODO(larsrc): Consider moving sender/receiver threads into separate classes.
      this.requestSender =
          new Thread(
              () -> {
                while (process.isAlive() && sendRequest()) {}
              });
      this.requestSender.setName("multiplexer-request-sender-" + id);
      this.requestSender.start();
      this.responseReceiver =
          new Thread(
              () -> {
                while (process.isAlive() && readResponse()) {}
              });
      this.responseReceiver.setName("multiplexer-response-receiver-" + id);
      this.responseReceiver.start();
    } else if (!this.process.isAlive()) {
      throw new IOException("Process is dead");
    }
  }

  /**
   * Returns the path of the log file shared by all multiplex workers using this process. May be
   * null if the process has not started yet.
   */
  public Path getLogFile() {
    return logFile;
  }

  /**
   * Signals this object to destroy itself, including the worker process. The object might not be
   * fully destroyed at the end of this call, but will terminate soon. This is considered a
   * deliberate destruction.
   */
  public synchronized void destroyMultiplexer() {
    if (this.process != null) {
      destroyProcess();
    }
    wasDestroyed = true;
  }

  /**
   * Destroys the worker subprocess. This might block forever if the subprocess refuses to die. It
   * is safe to call this multiple times.
   */
  private synchronized void destroyProcess() {
    boolean wasInterrupted = false;
    try {
      this.process.destroy();
      while (true) {
        try {
          this.process.waitFor();
          return;
        } catch (InterruptedException ie) {
          wasInterrupted = true;
        }
      }
    } finally {
      if (shutdownHook != null) {
        Runtime.getRuntime().removeShutdownHook(shutdownHook);
        shutdownHook = null;
      }
      // Stop the subthreads only when the process is dead, or their loops will go on.
      if (this.requestSender != null) {
        this.requestSender.interrupt();
      }
      if (this.responseReceiver != null) {
        this.responseReceiver.interrupt();
      }
      // Might as well release any waiting workers
      for (Semaphore semaphore : responseChecker.values()) {
        semaphore.release();
      }
      // Read this for detailed explanation: http://www.ibm.com/developerworks/library/j-jtp05236/
      if (wasInterrupted) {
        Thread.currentThread().interrupt(); // preserve interrupted status
      }
    }
  }

  /**
   * Sends the WorkRequest to worker process. This method is called on the thread of a {@code
   * WorkerProxy}, and so is subject to interrupts by dynamic execution.
   */
  public synchronized void putRequest(WorkRequest request) throws IOException {
    if (!process.isAlive()) {
      throw new IOException(
          "Attempting to send request " + request.getRequestId() + " to dead process");
    }
    responseChecker.put(request.getRequestId(), new Semaphore(0));
    pendingRequests.add(request);
  }

  /**
   * Waits on a semaphore for the {@code WorkResponse} returned from worker process. This method is
   * called on the thread of a {@code WorkerProxy}, and so is subject to interrupts by dynamic
   * execution.
   */
  public WorkResponse getResponse(Integer requestId) throws InterruptedException {
    try {
      if (!process.isAlive()) {
        // If the process has died, all we can do is return what may already have been returned.
        return workerProcessResponse.get(requestId);
      }

      Semaphore waitForResponse = responseChecker.get(requestId);

      if (waitForResponse == null) {
        report("Null response semaphore for " + requestId);
        // If there is no semaphore for this request, it probably failed to send, so we just return
        // what we got, probably nothing.
        return workerProcessResponse.get(requestId);
      }

      // Wait for the multiplexer to get our response and release this semaphore. The semaphore will
      // throw {@code InterruptedException} when the multiplexer is terminated.
      waitForResponse.acquire();

      return workerProcessResponse.get(requestId);
    } finally {
      responseChecker.remove(requestId);
      workerProcessResponse.remove(requestId);
    }
  }

  /**
   * Sends a single pending request, if there are any. Blocks until a request is available.
   *
   *
This is only called by the {@code requestSender} thread and so cannot be interrupted by
   * dynamic execution cancellation, but only by a call to {@link #destroyProcess()}.
   */
  private boolean sendRequest() {
    WorkRequest request;
    try {
      request = pendingRequests.take();
    } catch (InterruptedException e) {
      return false;
    }
    try {
      workerProtocol.putRequest(request);
    } catch (IOException e) {
      // We can't know how much of the request was sent, so we have to assume the worker's input
      // now contains garbage, and this request is lost.
      // TODO(b/177637516): Signal that this action failed for presumably transient reasons.
      report("Failed to send request " + request.getRequestId());
      Semaphore s = responseChecker.remove(request.getRequestId());
      if (s != null) {
        s.release();
      }
      // TODO(b/177637516): Leave process in a moribound state so pending responses can be returned.
      destroyProcess();
      return false;
    }
    return true;
  }

  /**
   * Reads a {@code WorkResponse} from worker process, puts that {@code WorkResponse} in {@code
   * workerProcessResponse}, and releases the semaphore for the {@code WorkerProxy}.
   *
   *
This is only called on the readResponses subthread and so cannot be interrupted by dynamic
   * execution cancellation, but only by a call to {@link #destroyProcess()}.
   *
   * @return True if the worker is still in a consistent state.
   */
  private boolean readResponse() {
    WorkResponse parsedResponse;
    try {
      parsedResponse = workerProtocol.getResponse();
    } catch (IOException e) {
      if (!(e instanceof InterruptedIOException)) {
        report(
            String.format(
                "Error while reading response from multiplexer process for %s: %s",
                workerKey.getMnemonic(), e));
      }
      // We can't know how much of the response was read, so we have to assume the worker's output
      // now contains garbage, and we can't reliably read any further responses.
      destroyProcess();
      return false;
    }

    // A null parsedResponse can only happen if the input stream is closed, in which case we
    // drop everything.
    if (parsedResponse == null) {
      report(
          String.format(
              "Multiplexer process for %s has closed its output stream", workerKey.getMnemonic()));
      destroyProcess();
      return false;
    }

    int requestId = parsedResponse.getRequestId();
    workerProcessResponse.put(requestId, parsedResponse);

    // TODO(b/151767359): When allowing cancellation, just remove responses that have no matching
    // entry in responseChecker.
    Semaphore semaphore = responseChecker.get(requestId);
    if (semaphore != null) {
      // This wakes up the WorkerProxy that should receive this response.
      semaphore.release();
    } else {
      report(String.format("Multiplexer for %s found no semaphore", workerKey.getMnemonic()));
      workerProcessResponse.remove(requestId);
    }
    return true;
  }

  String getRecordingStreamMessage() {
    // Unlike SingleplexWorker, we don't want to read the remaining bytes, as those could contain
    // many other responses. We just return what we actually read.
    return recordingStream.getRecordedDataAsString();
  }

  /** Returns true if this process has died for other reasons than a call to {@code #destroy()}. */
  boolean diedUnexpectedly() {
    return this.process != null && !this.process.isAlive() && !wasDestroyed;
  }

  /** Returns the exit value of multiplexer's process, if it has exited. */
  Optional<Integer> getExitValue() {
    return this.process != null && !this.process.isAlive()
        ? Optional.of(this.process.exitValue())
        : Optional.empty();
  }

  /** For testing only, to verify that maps are cleared after responses are reaped. */
  @VisibleForTesting
  boolean noOutstandingRequests() {
    return responseChecker.isEmpty() && workerProcessResponse.isEmpty();
  }

  @VisibleForTesting
  void setProcessFactory(SubprocessFactory factory) {
    subprocessFactory = factory;
  }

  public long getProcessId() {
    if (process == null) {
      return -1;
    }
    return process.getProcessId();
  }

  // TODO: Check if this can be removed
  @VisibleForTesting
  Subprocess getProcess() {
    return process;
  }
}


text:
/*the ajax loading icon*/
.mloading {width:100%;height:20px;background:rgba(255, 255, 255, 0.8) url('ajax_loader.gif') no-repeat 50% 50%;}
/*the form div*/
#awpqsf_id{border:1px solid #ccc;}
/*Form title*/
.form_title{font-weight:bold!important;text-align:center;margin:auto 0 auto 0}
.awpqsf_class{width:100%;margin-bottom:5px;}
/*label for each field*/
.awpqsf_class > label[class*='tax-label-'], .awpqsf_class > label[class*='tcmf-label-']{padding:5px;font-weight:bold !important;}
/*dropdown*/
.awpqsf_class select {width:98%;margin-left:1%;margin-right:1%}
/*Checkbox label field*/
label.taxchklabel, label.cmfchklabel{float:left;width:100%;}
/*radio label field*/
label.taxrdlabel, label.cmfrdlabel{float:left;width:100%;}
/*search button*/
.awpqsf_submit{text-align:center;margin-bottom:15px;}
/*keyword search label*/
.awpqsf_class-keyword{padding:5px;font-weight:bold !important;}
/*text input for keyword*/
input#awpqsf_id_key{width:97%;margin-left:1%;margin-right:1%}

/*Pagination*/
.ajaxsfpagi{text-align:center;margin-top:15px;margin-bottom:15px;clear:both;width:100%}

a.pagievent{padding-left: 12px; padding-right: 12px; height: 25px; line-height: 25px; display: inline-block;
	text-align: center;
	}
span.pagicurrent{padding-left: 12px; padding-right: 12px; height: 25px; line-height: 25px; display: inline-block;
	text-align: center;color:#000}

redpajama_set_name: RedPajamaGithub


text:
#ifndef NodeRenderStyle_h
#define NodeRenderStyle_h

#include "RenderObject.h"
#include "RenderStyle.h"
#include "Node.h"

namespace WebCore {

inline RenderStyle* Node::renderStyle() const
{
    // Using a ternary here confuses the Solaris Studio 12/12.1/12.2 compilers:
    // Bug is CR 6569194, "Problem with question operator binding in inline function"
    if (RenderObject* renderer = this->renderer())
        return renderer->style();
    return nonRendererStyle();
}

}
#endif


text:
body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    /*font-family: Tahoma;*/
    font-size: 14px;
}
.appHeader {
    background: #8ca448 repeat-x scroll left top;
    height: 70px;
    margin: 0;
    padding: 0;
    width: 100%;
}
.appHeader .headerLogo {
    float: left;
    left: 30px;
    position: relative;
    top: 8px;
}
.appHeader .headerTitle {
    color: #FFFFFF;
    float: left;
    font-size: 16pt;
    font-weight: bold;
    left: 60px;
    top: 15px;
    position: relative;
}
.appHeader .subHeaderTitle {
    color: #CFCFCF;
    font-size: small;
    padding-left: 20px;
}
.appHeader .search {
    float: left;
    left: 80px;
    position: relative;
    top: 18px;
}
.appHeader .headerLinks {
    float: right;
    color: #FFFFFF;
    position: relative;
    top: 27px;
    right: 10px;
    text-align: right;
}
.appHeader .headerLinks a {
    color: #FFFFFF;
}
#borderContainerOuter {
    position: absolute;
    top: 70px;
    bottom: 0;
    left: 0;
    right: 0;
    border: none;
    padding: 0;
    background-color: #FFFFFF
}
#sidebarLeft {
    width: 334px;
    padding: 4px;
    margin: 0;
    overflow: auto;
    overflow-x: hidden;
    border-right: 1px solid #B5BCC7;
}
#sidebarRight {
    width: 300px;
    padding: 4px;
    margin: 0;
    overflow: auto;
    overflow-x: hidden;
    border-left: 1px solid #B5BCC7;
}
#sidebarBottom {
    height: 100px;
    padding: 4px;
    margin: 0;
    overflow: auto;
    overflow-x: hidden;
    border-top: 1px solid #B5BCC7;
}
#sidebarTop {
    height: 50px;
    padding: 4px;
    margin: 0;
    overflow: auto;
    overflow-x: hidden;
    border-bottom: 1px solid #B5BCC7;
}
#mapCenter {
    padding: 0;
    overflow: hidden;
    background: url("../images/noisy_grid.png") #fff;
}
.panetop {
    border-top: 1px solid #B5BCC7;
}
.panebottom {
    border-bottom: 1px solid #B5BCC7;
}
.paneleft {
    border-left: 1px solid #B5BCC7;
}
.paneright {
    border-right: 1px solid #B5BCC7;
}
.HomeButton, .LocateButton {
    margin-bottom: 10px;
}
.titlePaneBottomFix {
    margin-bottom: -1px;
}
.titlePaneRightFix {
    margin-right: -1px;
}
.sidebarCollapseButton {
    position: absolute;
    z-index: 40;
    background-color: white;
    cursor: pointer;
    color: #666666;
    font-size: 1.3em;
    font-family: FontAwesome;
}
.sidebarCollapseButtonHorz {
    width: 16px;
    height: 25px;
    top: 48%;
    top: -webkit-calc(50% - 12px);
    top: -moz-calc(50% - 12px);
    top: -o-calc(50% - 12px);
    top: calc(50% - 12px);
    border-bottom: 1px solid #B5BCC7;
    border-top: 1px solid #B5BCC7;
}
.sidebarCollapseButtonVert {
    width: 25px;
    height: 18px;
    left: 48%;
    left: -webkit-calc(50% - 12px);
    left: -moz-calc(50% - 12px);
    left: -o-calc(50% - 12px);
    left: calc(50% - 12px);
    border-left: 1px solid #B5BCC7;
    border-right: 1px solid #B5BCC7;
}
.sidebarleftCollapseButton {
    left: -1px;
    border-radius: 0 5px 5px 0;
    border-right: 1px solid #B5BCC7;
}
.sidebarrightCollapseButton {
    right: -1px;
    border-radius: 5px 0 0 5px;
    border-left: 1px solid #B5BCC7;
}
.sidebarbottomCollapseButton {
    bottom: -1px;
    border-radius: 5px 5px 0 0;
    border-top: 1px solid #B5BCC7;
}
.sidebartopCollapseButton {
    top: -1px;
    border-radius: 0 0 5px 5px;
    border-bottom: 1px solid #B5BCC7;
}
.sidebarCollapseButtonHorz .button {
    padding-top: 4px;
    padding-left: 2px;
}
.sidebarCollapseButtonVert .button {
    padding-left: 4px;
    margin-top: -2px;
}
.sidebarleftCollapseButton .open:before {
    content: "\f054";
}
.sidebarleftCollapseButton .close:before {
    content: "\f053";
}
.sidebarrightCollapseButton .open:before {
    content: "\f053";
}
.sidebarrightCollapseButton .close:before {
    content: "\f054";
}
.sidebarbottomCollapseButton .open:before {
    content: "\f077";
}
.sidebarbottomCollapseButton .close:before {
    content: "\f078";
}
.sidebartopCollapseButton .open:before {
    content: "\f078";
}
.sidebartopCollapseButton .close:before {
    content: "\f077";
}
.floatingWidget_underlay {
    display: none
}
#help_parent_underlay {
    display: block;
}

/* dbootstrap overrides*/

.dbootstrap .dijitToolbar .dijitButtonContents {
    padding: 1px !important;
}
.dbootstrap .dijitTitlePane {
    border: 1px solid #DDDDDD;
    margin-bottom: 2px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
}
.dbootstrap .dijitTitlePaneTitle {
    color: #666666 !important;
    border-bottom: none;
    padding: 8px 15px;
    background-color: #F5F5F5;
}
.dijitSliderBarContainerH {
    z-index: 0 !important;
}
.dbootstrap .dijitTitlePaneContentInner {
    background-color: #FFFFFF;
}
.dijitBorderContainerNoGutterPane {
    z-index: auto;
}
.dbootstrap :focus {
    outline: none !important;
}

/* end dbootstrap overrides*/

/* esri popup window overrides */

.esriPopup .sizer {
    width: 325px;
}

.esriPopup .esriPopupWrapper {
    background-color: #FFFFFF;
}
.esriPopup .attachmentsSection div {
    font-weight: bold;
}
.esriPopup .contentPane table.attrTable {
    width: 100%;
    border-collapse: collapse;
}
.esriPopup .contentPane table.attrTable td {
    padding: 2px;
}
.esriPopup .contentPane table.attrTable td.attrName {
    text-align: right;
    font-weight: bold;
    color: #333333;
    width: 40%;
    padding-right: 5px;
}
.esriPopup .contentPane table.attrTable td.attrValue {
    width: 60%;
}
.esriPopup .contentPane table.attrTable tr {
    vertical-align: top;
    border-bottom: 1px solid rgb(221, 221, 221);
}
.esriPopup .contentPane table.attrTable tr:nth-child(odd) {
    background-color: none;
}
.esriPopup .contentPane table.attrTable tr:nth-child(even) {
    background-color: rgb(238, 238, 238);
}

/* end esri popup window overrides */

/* esri mobile popup overrides */

.esriPopupMobile {
    z-index: 999;
}
.esriMobileNavigationBar {
    background-color: #666666;
    background: url("../images/linen.jpg") repeat-x scroll left top transparent;
    color: #FFFFFF;
}
.esriPopupMobile .titlePane {
    background-color: #666666;
    background: url("../images/linen.jpg") repeat-x scroll left top transparent;
    color: #FFFFFF;
}
.esriPopupMobile .pointer.bottom{
    background:url("../images/pointertop.png");
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    transform: rotate(180deg);
}
.esriPopupMobile .pointer.top {
    background:url("../images/pointertop.png");
}

/* end esri mobile popup overrides */

/*
    media queries bootstrap style
    http://getbootstrap.com/css/#grid-media-queries
*/

@media screen and (max-width: 991px) {
    /* adjust the l/r sidebars on small and extra-small devices. */
    #sidebarLeft {
        width: 204px;
        max-width: 95%;
    }

    #sidebarRight {
        max-width: 95%;
        display: none;
    }
}
@media screen and (max-width: 767px) {
    /* hide the sidebars by default on extra-small devices (phones) */
    #sidebarLeft, #sidebarBottom, #sidebarTop {
        display: none;
    }
    /* no search widget in app header */
    .appHeader .search {
        display: none;
    }
    /* no logo in app header */
    .appHeader .headerLogo {
        display: none;
    }
    /* move the title when no logo */
    .appHeader .headerTitle {
        left: 10px;
    }
}

/* end media queries bootstrap style */


text:
using System.Collections.Generic;
using System.Linq;

namespace UnityEngine.Purchasing
{
    /// <summary>
    /// Automatically initializes Unity IAP with the products defined in the IAP Catalog (if enabled in the UI).
    /// Manages IAPButtons and IAPListeners.
    /// </summary>
    public class CodelessIAPStoreListener : IStoreListener
    {
        private static CodelessIAPStoreListener instance;
        private List<IAPButton> activeButtons = new List<IAPButton>();
        private List<IAPListener> activeListeners = new List<IAPListener> ();
        private static bool unityPurchasingInitialized;

        protected IStoreController controller;
        protected IExtensionProvider extensions;
        protected ProductCatalog catalog;

        // Allows outside sources to know whether the full initialization has taken place.
        public static bool initializationComplete;

        [RuntimeInitializeOnLoadMethod]
        static void InitializeCodelessPurchasingOnLoad() {
            ProductCatalog catalog = ProductCatalog.LoadDefaultCatalog();
            if (catalog.enableCodelessAutoInitialization && !catalog.IsEmpty() && instance == null)
            {
                CreateCodelessIAPStoreListenerInstance();
            }
        }

        private static void InitializePurchasing()
        {
            StandardPurchasingModule module = StandardPurchasingModule.Instance();
            module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

            ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);

            IAPConfigurationHelper.PopulateConfigurationBuilder(ref builder, instance.catalog);

            UnityPurchasing.Initialize(instance, builder);

            unityPurchasingInitialized = true;
        }

        private CodelessIAPStoreListener()
        {
            catalog = ProductCatalog.LoadDefaultCatalog();
        }

        public static CodelessIAPStoreListener Instance
        {
            get
            {
                if (instance == null)
                {
                    CreateCodelessIAPStoreListenerInstance();
                }
                return instance;
            }
        }

        /// <summary>
        /// Creates the static instance of CodelessIAPStoreListener and initializes purchasing
        /// </summary>
        private static void CreateCodelessIAPStoreListenerInstance()
        {
            instance = new CodelessIAPStoreListener();
            if (!unityPurchasingInitialized)
            {
                Debug.Log("Initializing UnityPurchasing via Codeless IAP");
                InitializePurchasing();
            }
        }

        public IStoreController StoreController
        {
            get { return controller; }
        }

        public IExtensionProvider ExtensionProvider
        {
            get { return extensions; }
        }

        public bool HasProductInCatalog(string productID)
        {
            foreach (var product in catalog.allProducts)
            {
                if (product.id == productID)
                {
                    return true;
                }
            }
            return false;
        }

        public Product GetProduct(string productID)
        {
            if (controller != null && controller.products != null && !string.IsNullOrEmpty(productID))
            {
                return controller.products.WithID(productID);
            }
            Debug.LogError("CodelessIAPStoreListener attempted to get unknown product " + productID);
            return null;
        }

        public void AddButton(IAPButton button)
        {
            activeButtons.Add(button);
        }

        public void RemoveButton(IAPButton button)
        {
            activeButtons.Remove(button);
        }

        public void AddListener(IAPListener listener)
        {
            activeListeners.Add (listener);
        }

        public void RemoveListener(IAPListener listener)
        {
            activeListeners.Remove (listener);
        }

        public void InitiatePurchase(string productID)
        {
            if (controller == null)
            {
                Debug.LogError("Purchase failed because Purchasing was not initialized correctly");

                foreach (var button in activeButtons)
                {
                    if (button.productId == productID)
                    {
                        button.OnPurchaseFailed(null, Purchasing.PurchaseFailureReason.PurchasingUnavailable);
                    }
                }
                return;
            }

            controller.InitiatePurchase(productID);
        }

        public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
        {
            initializationComplete = true;
            this.controller = controller;
            this.extensions = extensions;

            foreach (var button in activeButtons)
            {
                button.UpdateText();
            }
        }

        public void OnInitializeFailed(InitializationFailureReason error)
        {
            Debug.LogError(string.Format("Purchasing failed to initialize. Reason: {0}", error.ToString()));
        }

        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            PurchaseProcessingResult result;

            // if any receiver consumed this purchase we return the status
            bool consumePurchase = false;
            bool resultProcessed = false;

            foreach (IAPButton button in activeButtons)
            {
                if (button.productId == e.purchasedProduct.definition.id)
                {
                    result = button.ProcessPurchase(e);

                    if (result == PurchaseProcessingResult.Complete) {

                        consumePurchase = true;
                    }

                    resultProcessed = true;
                }
            }

            foreach (IAPListener listener in activeListeners)
            {
                result = listener.ProcessPurchase(e);

                if (result == PurchaseProcessingResult.Complete) {

                    consumePurchase = true;
                }

                resultProcessed = true;
            }

            // we expect at least one receiver to get this message
            if (!resultProcessed) {

                Debug.LogError("Purchase not correctly processed for product \"" +
                                 e.purchasedProduct.definition.id +
                                 "\". Add an active IAPButton to process this purchase, or add an IAPListener to receive any unhandled purchase events.");

            }

            return (consumePurchase) ? PurchaseProcessingResult.Complete : PurchaseProcessingResult.Pending;
        }

        public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
        {
            bool resultProcessed = false;

            foreach (IAPButton button in activeButtons)
            {
                if (button.productId == product.definition.id)
                {
                    button.OnPurchaseFailed(product, reason);

                    resultProcessed = true;
                }
            }

            foreach (IAPListener listener in activeListeners)
            {
                listener.OnPurchaseFailed(product, reason);

                resultProcessed = true;
            }

            // we expect at least one receiver to get this message
            if (!resultProcessed) {

                Debug.LogError("Failed purchase not correctly handled for product \"" + product.definition.id +
                                  "\". Add an active IAPButton to handle this failure, or add an IAPListener to receive any unhandled purchase failures.");
            }

            return;
        }
    }
}

#endif


text:
ScalaJS.impls.scala_parallel_Future$mcD$sp$class__$init$__Lscala_parallel_Future$mcD$sp__V = (function($$this) {
  /*<skip>*/
});
//@ sourceMappingURL=Future$mcD$sp$class.js.map


text:
package org.laboys.better.spring.autoconfigure.web;

import org.laboys.better.spring.core.web.RestExceptionAdvice;
import org.laboys.better.spring.core.web.RestResultAdvice;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@ConditionalOnWebApplication
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(WebProperties.class)
@Import({WebExceptionAutoConfiguration.class, WebMvcAutoConfiguration.class})
public class WebAutoConfiguration {

    @Configuration
    @ConditionalOnProperty(prefix = WebProperties.PREFIX, name = "decoration.enabled", havingValue = "true", matchIfMissing = true)
    public static class DecorationConfiguration {
        @Bean
        @ConditionalOnProperty(prefix = WebProperties.PREFIX, name = "decoration.on-success", havingValue = "true", matchIfMissing = true)
        public RestResultAdvice restResultAdvice(ApplicationContext context) {
            return new RestResultAdvice(context);
        }

        @Bean
        @ConditionalOnProperty(prefix = WebProperties.PREFIX, name = "decoration.on-failure", havingValue = "true", matchIfMissing = true)
        public RestExceptionAdvice restExceptionAdvice(ApplicationContext context) {
            return new RestExceptionAdvice(context);
        }
    }

}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Prepare extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * @access public
	 * @param string
	 * @return string
	 */

	function __construct()
	{
		parent::__construct();
		$this->load->driver('session');
	}

	public function index()
	{
		$this->load->view('prepare_view');
	}

	public function login()
	{
		if(isset($_POST['prepare_str'])){
			if($_POST['prepare_str'] == 'poiwelcome123'){
				$this->session->set_userdata('isloggedIn',TRUE);
				redirect('/');
			}
			else{
				$data['info'] = 'password error,please type again.';
				$this->load->view('prepare_view',$data);
			}
		}
		else{
			$this->load->view('prepare_view');
		}
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */


text:
module Shell
  module Commands
    class IsEnabled < Command
      def help
        return <<-EOF
Is named table enabled?: e.g. "hbase> is_enabled 't1'"
EOF
      end

      def command(table)
        format_simple_command do
          formatter.row([
            admin.enabled?(table)? "true" : "false"
          ])
        end
      end
    end
  end
end


text:
Thank you!

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat


text: react + redux small kit


text:
"""Provides the web interface for reporting a graph of traces."""

__author__ = 'sullivan@google.com (Annie Sullivan)'

import json
import os

from dashboard import chart_handler
from dashboard import update_test_suites

class ReportHandler(chart_handler.ChartHandler):

  def get(self):
    """Renders the UI for selecting graphs."""
    dev_version = ('Development' in os.environ['SERVER_SOFTWARE'] or
                   self.request.host == 'chrome-perf.googleplex.com')
    self.RenderHtml('report.html', {
        'dev_version': dev_version,
        'test_suites': json.dumps(update_test_suites.FetchCachedTestSuites()),
    })


text: @page toc{color:black;}


text:
angular.module('won.settings', [])

  .controller('SettingsCtrl', function (settings, $scope, $ionicLoading) {
    $scope.scale = settings.scale;
    $scope.precision = settings.precision;

    $scope.scales = [
     {symbol: 'F', name: 'Fahrenheit'},
     {symbol: 'C', name: 'Celcuis'},
     {symbol: 'K', name: 'Kelvin'},
     {symbol: 'Ra', name: 'Rankine'},
     {symbol: 'D', name: 'Delisle'},
     {symbol: 'N', name: 'Newton'},
     {symbol: 'Ré', name: 'Réaumur'},
     {symbol: 'Rø', name: 'Rømer'},
     {symbol: 'X', name: 'Random'}
    ];

    $scope.$watch('precision', function () {
      settings.precision = $scope.precision;
    });

    $scope.$watch('scale', function () {
      if ($scope.scale === 'X') {
        $ionicLoading.show({
          // template: '<img src="img/whatshappening.gif">',
          // duration: 5000
        });
      }

      settings.scale = $scope.scale;
    });

  })

  .factory('settings', function () {
    return {
      get scale() {
        return localStorage.getItem('scale') || 'K';
      },
      get precision() {
        return localStorage.getItem('precision') || '2';
      },
      set scale(s) {
        localStorage.setItem('scale', s);
      },
      set precision(p) {
        localStorage.setItem('precision', p);
      }
    };
  })

  .factory('location', function () {
    var defaultFavorites = [{
        city: 'Cupertino, CA',
        lat: '37.3190',
        long: '-122.0293'
      },{
        city: 'Mountain View, CA',
        lat: '37.3897',
        long: '-122.0816'
      },{
        city: 'Redmond, WA',
        lat: '47.6786',
        long: '-122.1310'
      },{
        city: 'Nashville, TN',
        lat: '36.1658',
        long: '-86.7777'
      }];

    if (!localStorage.favorites) {
      localStorage.favorites = JSON.stringify(defaultFavorites);
    }

    return {
      get favorites() {
        var json = localStorage.getItem('favorites');
        return JSON.parse(json);
      },
      set favorites(f) {
        var json = JSON.stringify(f);
        localStorage.setItem('favorites', json);
      },
      addFavorite: function (f) {
        this.favorites = this.favorites.concat(f);
      },
      removeFavorite: function (cityName) {
        this.favorites = this.favorites.filter(function (fav) {
          return fav.city !== cityName;
        });
      }
    };
  });


text:
package org.elasolutions.utils.test.performance;

import java.util.ArrayList;
import java.util.List;

public class TestResults {

    public static TestResults newResults(final String name,
            final int numberOfThreads, final int maxIterationsPerThread,
            final long maxRunTime) {
        return new TestResults(name, numberOfThreads, maxIterationsPerThread, maxRunTime);
    }

    public void addTestThread(final TestThread thread) {
        getTestList().add(thread);
    }

    /**
     *

     * getAverageThreadTime.
     *

     *
     * @return a long.
     */
    public long getAverageThreadTime() {
        return m_averageThreadTimes;
    }

    public long getEndTime() {
        return m_endTime;
    }

    public int getMaxIterationsPerThread() {
        return m_maxIterationsPerThread;
    }

    public long getMaxRunTime() {
        return m_maxRunTime;
    }

    public String getName() {
        return m_name;
    }

    public int getNumberOfThreads() {
        return m_numberOfThreads;
    }

    public long getStartTime() {
        return m_startTime;
    }

    public long getTestDuration() {
        return m_endTime - m_startTime;
    }

    /**
     *

     * getTestList.
     *

     *
     * @return a {@link java.util.List} object.
     */
    public List<TestThread> getTestList() {
        if (m_testsList == null) {
            m_testsList = new ArrayList<>();
        }
        return m_testsList;
    }

    public void setAverageThreadTime(final long averageThreadTimes) {
        m_averageThreadTimes = averageThreadTimes;

    }

    public void setEndTime(final long end) {
        m_endTime = end;
    }

    public void setStartTime(final long start) {
        m_startTime = start;
    }

    private TestResults(final String name, final int numberOfThreads,
            final int maxIterationsPerThread, final long maxRunTime) {
        m_name = name;
        m_numberOfThreads = numberOfThreads;
        m_maxIterationsPerThread = maxIterationsPerThread;
        m_maxRunTime = maxRunTime;
    }

    private final String m_name;

    private final int m_numberOfThreads;

    private final int m_maxIterationsPerThread;

    private final long m_maxRunTime;

    private long m_startTime;

    private long m_endTime;

    long m_averageThreadTimes;

    private List<TestThread> m_testsList;
}


text:
> a JS library for building UIs

* desing simple views for each state in app, React will update and render right component on data changes

* create encapuslated components in JS managing their own state, composed to create complex UIs

* can also render on server using Node, power mobile apps using React Native

---

* [tutorialspoint.com/reactjs](./tutorialspoint.com/README.md)

---
---


text:
package org.springframework.context.event;

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

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.TestListener;
import org.springframework.context.event.test.TestEvent;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

/**
 * @author Dmitriy Kopylenko
 * @author Juergen Hoeller
 * @author Rick Evans
 */
public class EventPublicationInterceptorTests {

	private ApplicationEventPublisher publisher;

	@Before
	public void setUp() {
		this.publisher = mock(ApplicationEventPublisher.class);
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWithNoApplicationEventClassSupplied() throws Exception {
		EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
		interceptor.setApplicationEventPublisher(this.publisher);
		interceptor.afterPropertiesSet();
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWithNonApplicationEventClassSupplied() throws Exception {
		EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
		interceptor.setApplicationEventPublisher(this.publisher);
		interceptor.setApplicationEventClass(getClass());
		interceptor.afterPropertiesSet();
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWithAbstractStraightApplicationEventClassSupplied() throws Exception {
		EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
		interceptor.setApplicationEventPublisher(this.publisher);
		interceptor.setApplicationEventClass(ApplicationEvent.class);
		interceptor.afterPropertiesSet();
	}

	@Test(expected=IllegalArgumentException.class)
	public void testWithApplicationEventClassThatDoesntExposeAValidCtor() throws Exception {
		EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
		interceptor.setApplicationEventPublisher(this.publisher);
		interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class);
		interceptor.afterPropertiesSet();
	}

	@Test
	public void testExpectedBehavior() throws Exception {
		TestBean target = new TestBean();
		final TestListener listener = new TestListener();

		class TestContext extends StaticApplicationContext {
			@Override
			protected void onRefresh() throws BeansException {
				addApplicationListener(listener);
			}
		}

		StaticApplicationContext ctx = new TestContext();
		MutablePropertyValues pvs = new MutablePropertyValues();
		pvs.add("applicationEventClass", TestEvent.class.getName());
		// should automatically receive applicationEventPublisher reference
		ctx.registerSingleton("publisher", EventPublicationInterceptor.class, pvs);
		ctx.registerSingleton("otherListener", FactoryBeanTestListener.class);
		ctx.refresh();

		EventPublicationInterceptor interceptor =
				(EventPublicationInterceptor) ctx.getBean("publisher");
		ProxyFactory factory = new ProxyFactory(target);
		factory.addAdvice(0, interceptor);

		ITestBean testBean = (ITestBean) factory.getProxy();

		// invoke any method on the advised proxy to see if the interceptor has been invoked
		testBean.getAge();

		// two events: ContextRefreshedEvent and TestEvent
		assertTrue("Interceptor must have published 2 events", listener.getEventCount() == 2);
		TestListener otherListener = (TestListener) ctx.getBean("&otherListener");
		assertTrue("Interceptor must have published 2 events", otherListener.getEventCount() == 2);
	}

	@SuppressWarnings("serial")
	public static final class TestEventWithNoValidOneArgObjectCtor extends ApplicationEvent {

		public TestEventWithNoValidOneArgObjectCtor() {
			super("");
		}
	}

	public static class FactoryBeanTestListener extends TestListener implements FactoryBean<Object> {

		@Override
		public Object getObject() throws Exception {
			return "test";
		}

		@Override
		public Class<String> getObjectType() {
			return String.class;
		}

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

}


text:
local sample02= (function()
require('core').import('core')
local _var1
_C[hash("if1")]=function (block, stream, condition, action, otherwise)
local _var0
local _var1
do
local fn=eval(list({symbol("lambda"),list({symbol("condition"),symbol("action"),symbol("otherwise")}),list({symbol("quasiquote"),list({symbol("cond"),condition,action,otherwise})})}))
_var1=compile(block, stream, fn(condition, action, otherwise))
end
return _var1
end
_var1=_C[hash("if1")]
function sum(l)
local _var0
local _var1
if
l
then
_var1
=
((l[1]) + sum((l[2])))
else
_var1
=
0
end
return _var1
end
return _var1
end)()


text:
namespace QuantConnect.Data.Auxiliary
{
    /// <summary>
    /// Unique definition key for a collection of auxiliary data for a Market and SecurityType
    /// </summary>
    public class AuxiliaryDataKey
    {
        /// <summary>
        /// USA equities market corporate actions key definition
        /// </summary>
        public static AuxiliaryDataKey EquityUsa { get; } = new (QuantConnect.Market.USA, SecurityType.Equity);

        /// <summary>
        /// The market associated with these corporate actions
        /// </summary>
        public string Market { get; }

        /// <summary>
        /// The associated security type
        /// </summary>
        public SecurityType SecurityType { get; }

        /// <summary>
        /// Creates a new instance
        /// </summary>
        public AuxiliaryDataKey(string market, SecurityType securityType)
        {
            Market = market;
            SecurityType = securityType;
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = Market.GetHashCode();
                return (hashCode*397) ^ SecurityType.GetHashCode();
            }
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// true if the specified object  is equal to the current object; otherwise, false.
        /// </returns>
        /// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority>
        public override bool Equals(object? obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (obj.GetType() != GetType()) return false;

            var other = (AuxiliaryDataKey)obj;

            return other.Market == Market
                && other.SecurityType == SecurityType;
        }

        public override string ToString()
        {
            return $"{Market}:{SecurityType}";
        }

        /// <summary>
        /// Helper method to create a new instance from a Symbol
        /// </summary>
        public static AuxiliaryDataKey Create(Symbol symbol) => Create(symbol.HasUnderlying ? symbol.Underlying.ID : symbol.ID);

        /// <summary>
        /// Helper method to create a new instance from a SecurityIdentifier
        /// </summary>
        public static AuxiliaryDataKey Create(SecurityIdentifier securityIdentifier)
        {
            securityIdentifier = securityIdentifier.HasUnderlying ? securityIdentifier.Underlying : securityIdentifier;
            return new AuxiliaryDataKey(securityIdentifier.Market, securityIdentifier.SecurityType);
        }
    }
}


text:
namespace Assets { class DependencyValidation; }

namespace RenderCore { namespace Metal_DX11
{

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class VertexShader
    {
    public:
            //
            //          Resource interface
            //
        explicit VertexShader(const ::Assets::ResChar initializer[]);
        explicit VertexShader(const CompiledShaderByteCode& byteCode);
        VertexShader();
        ~VertexShader();

        typedef ID3D::VertexShader* UnderlyingType;
        UnderlyingType  GetUnderlying() const { return _underlying.get(); }
        ID3D::ClassLinkage* GetClassLinkage() const { return _classLinkage.get(); }

    private:
        intrusive_ptr<ID3D::VertexShader>   _underlying;
        intrusive_ptr<ID3D::ClassLinkage>   _classLinkage;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class PixelShader
    {
    public:
            //
            //          Resource interface
            //
        explicit PixelShader(const ::Assets::ResChar initializer[]);
        explicit PixelShader(const CompiledShaderByteCode& byteCode);
        PixelShader();
        ~PixelShader();

        typedef ID3D::PixelShader*  UnderlyingType;
        UnderlyingType      GetUnderlying() const { return _underlying.get(); }
        ID3D::ClassLinkage* GetClassLinkage() const { return _classLinkage.get(); }

    private:
        intrusive_ptr<ID3D::PixelShader>    _underlying;
        intrusive_ptr<ID3D::ClassLinkage>   _classLinkage;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class InputElementDesc;

    class GeometryShader
    {
    public:
        class StreamOutputInitializers
        {
        public:
            const InputElementDesc* _outputElements;
            unsigned _outputElementCount;
            const unsigned* _outputBufferStrides;
            unsigned _outputBufferCount;

            StreamOutputInitializers(
                const InputElementDesc outputElements[], unsigned outputElementCount,
                const unsigned outputBufferStrides[], unsigned outputBufferCount)
                : _outputElements(outputElements), _outputElementCount(outputElementCount)
                , _outputBufferStrides(outputBufferStrides), _outputBufferCount(outputBufferCount)
            {}
            StreamOutputInitializers()
                : _outputElements(nullptr), _outputElementCount(0)
                , _outputBufferStrides(nullptr), _outputBufferCount(0)
            {}
        };

            //
            //          Resource interface
            //
        GeometryShader(const ::Assets::ResChar initializer[], const StreamOutputInitializers& soInitializers = GetDefaultStreamOutputInitializers());
        explicit GeometryShader(const CompiledShaderByteCode& byteCode, const StreamOutputInitializers& soInitializers = GetDefaultStreamOutputInitializers());
        GeometryShader();
        ~GeometryShader();
        GeometryShader(GeometryShader&& moveFrom);
        GeometryShader& operator=(GeometryShader&& moveFrom);

        static void SetDefaultStreamOutputInitializers(const StreamOutputInitializers&);
        static const StreamOutputInitializers& GetDefaultStreamOutputInitializers();

        typedef ID3D::GeometryShader*       UnderlyingType;
        UnderlyingType                      GetUnderlying() const { return _underlying.get(); }

    private:
        intrusive_ptr<ID3D::GeometryShader>     _underlying;
        static StreamOutputInitializers         _hackInitializers;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class HullShader
    {
    public:
        explicit HullShader(const ::Assets::ResChar initializer[], const ::Assets::ResChar definesTable[]=nullptr);
        explicit HullShader(const CompiledShaderByteCode& byteCode);
        ~HullShader();

        typedef ID3D::HullShader*       UnderlyingType;
        UnderlyingType                  GetUnderlying() const { return _underlying.get(); }

        const std::shared_ptr<::Assets::DependencyValidation>& GetDependencyValidation() const     { return _validationCallback; }

    private:
        intrusive_ptr<ID3D::HullShader>            _underlying;
        std::shared_ptr<::Assets::DependencyValidation>   _validationCallback;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class DomainShader
    {
    public:
        explicit DomainShader(const ::Assets::ResChar initializer[], const ::Assets::ResChar definesTable[]=nullptr);
        explicit DomainShader(const CompiledShaderByteCode& byteCode);
        ~DomainShader();

        typedef ID3D::DomainShader*     UnderlyingType;
        UnderlyingType                  GetUnderlying() const { return _underlying.get(); }

        const std::shared_ptr<::Assets::DependencyValidation>& GetDependencyValidation() const     { return _validationCallback; }

    private:
        intrusive_ptr<ID3D::DomainShader>          _underlying;
        std::shared_ptr<::Assets::DependencyValidation>   _validationCallback;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    class ComputeShader
    {
    public:
        explicit ComputeShader(const ::Assets::ResChar initializer[], const ::Assets::ResChar definesTable[]=nullptr);
        explicit ComputeShader(const CompiledShaderByteCode& byteCode);
        ~ComputeShader();

        typedef ID3D::ComputeShader*    UnderlyingType;
        UnderlyingType                  GetUnderlying() const { return _underlying.get(); }

        const std::shared_ptr<::Assets::DependencyValidation>& GetDependencyValidation() const     { return _validationCallback; }

    private:
        intrusive_ptr<ID3D::ComputeShader>         _underlying;
        std::shared_ptr<::Assets::DependencyValidation>   _validationCallback;
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    ///
    /// A set of shaders for each stage of the shader pipeline
    ///
    /// A ShaderProgram contains a set of shaders, each of which will be bound to the pipeline
    /// at the same time. Most of the time, it will contain just a vertex shader and a pixel shader.
    ///
    /// In DirectX, it's easy to manage shaders for different stages of the pipeline separately. But
    /// OpenGL prefers to combine all of the shaders together into one shader program object.
    ///
    ///     The DirectX11 shader pipeline looks like this:
    ///         <list>
    ///             <item>Vertex Shader</item>
    ///             <item>Hull Shader</item>
    ///             <item>(fixed function tessellator)</item>
    ///             <item>Domain shader</item>
    ///             <item>Geometry shader</item>
    ///             <item>Pixel Shader</item>
    ///         </list>
    ///
    /// Normally ShaderProgram objects are created and managed using the "Assets::GetAsset" or "Assets::GetAssetDep"
    /// functions.
    /// For example:
    /// \code
    ///     auto& shader = Assets::GetAssetDep<ShaderProgram>("shaders/basic.vsh:main:vs_*", "shaders/basic.psh:main:ps_*");
    /// \endcode
    ///
    /// But it's also possible to construct a ShaderProgram as a basic object.
    /// \code
    ///     ShaderProgram myShaderProgram("shaders/basic.vsh:main:vs_*", "shaders/basic.psh:main:ps_*");
    /// \endcode
    ///
    /// Note that the parameters ":main:vs_*" specify the entry point and shader compilation model.
    ///     <list>
    ///         <item>":main" -- this is the entry point function. That is, there is a function in
    ///                 the shader file called "main." It will take the shader input parameters and
    ///                 return the shader output values.</item>
    ///         <item>":vs_*" -- this is the compilation model. "vs" means vertex shader. The "_*"
    ///                 means to use the default compilation model for the current device. But it can
    ///                 be replaced with an appropriate compilation model
    ///                     (eg, vs_5_0, vs_4_0_level_9_1, ps_3_0, etc)
    ///                 Normally it's best to use the default compilation model.</item>
    ///     </list>
    ///
    class ShaderProgram : noncopyable
    {
    public:
        ShaderProgram(  const ::Assets::ResChar vertexShaderInitializer[],
                        const ::Assets::ResChar fragmentShaderInitializer[]);

        ShaderProgram(  const ::Assets::ResChar vertexShaderInitializer[],
                        const ::Assets::ResChar fragmentShaderInitializer[],
                        const ::Assets::ResChar definesTable[]);

        ShaderProgram(  const ::Assets::ResChar vertexShaderInitializer[],
                        const ::Assets::ResChar geometryShaderInitializer[],
                        const ::Assets::ResChar fragmentShaderInitializer[],
                        const ::Assets::ResChar definesTable[]);

        ShaderProgram(  const CompiledShaderByteCode& compiledVertexShader,
                        const CompiledShaderByteCode& compiledFragmentShader);

		ShaderProgram();
        ~ShaderProgram();

        const VertexShader&                 GetVertexShader() const             { return _vertexShader; }
        const GeometryShader&               GetGeometryShader() const           { return _geometryShader; }
        const PixelShader&                  GetPixelShader() const              { return _pixelShader; }
        const CompiledShaderByteCode&       GetCompiledVertexShader() const     { return *_compiledVertexShader; }
        const CompiledShaderByteCode&       GetCompiledPixelShader() const      { return *_compiledPixelShader; }
        const CompiledShaderByteCode*       GetCompiledGeometryShader() const   { return _compiledGeometryShader; }
        const std::shared_ptr<::Assets::DependencyValidation>& GetDependencyValidation() const     { return _validationCallback; }

        bool DynamicLinkingEnabled() const;

		ShaderProgram(ShaderProgram&&) never_throws;
        ShaderProgram& operator=(ShaderProgram&&) never_throws;

    protected:
        const CompiledShaderByteCode*           _compiledVertexShader;
        const CompiledShaderByteCode*           _compiledPixelShader;
        const CompiledShaderByteCode*           _compiledGeometryShader;
        VertexShader                            _vertexShader;
        PixelShader                             _pixelShader;
        GeometryShader                          _geometryShader;
        std::shared_ptr<::Assets::DependencyValidation>   _validationCallback;

        ShaderProgram(const ShaderProgram&) = delete;
        ShaderProgram& operator=(const ShaderProgram&) = delete;
    };

    ///
    /// A shader program with tessellation support
    ///
    /// A DeepShaderProgram is the same as ShaderProgram, but with tessellation support. Most
    /// ShaderPrograms don't need tessellation shaders, so for simplicity they are excluded
    /// from the default ShaderProgram object.
    ///
    class DeepShaderProgram : public ShaderProgram
    {
    public:
        DeepShaderProgram(  const ::Assets::ResChar vertexShaderInitializer[],
                            const ::Assets::ResChar geometryShaderInitializer[],
                            const ::Assets::ResChar fragmentShaderInitializer[],
                            const ::Assets::ResChar hullShaderInitializer[],
                            const ::Assets::ResChar domainShaderInitializer[],
                            const ::Assets::ResChar definesTable[]);
        ~DeepShaderProgram();

        const HullShader&                   GetHullShader() const               { return _hullShader; }
        const DomainShader&                 GetDomainShader() const             { return _domainShader; }
        const CompiledShaderByteCode&       GetCompiledHullShader() const       { return _compiledHullShader; }
        const CompiledShaderByteCode&       GetCompiledDomainShader() const     { return _compiledDomainShader; }

    private:
        const CompiledShaderByteCode&   _compiledHullShader;
        const CompiledShaderByteCode&   _compiledDomainShader;
        HullShader                      _hullShader;
        DomainShader                    _domainShader;

        DeepShaderProgram(const DeepShaderProgram&);
        DeepShaderProgram& operator=(const DeepShaderProgram&);
    };

        ////////////////////////////////////////////////////////////////////////////////////////////////

    std::shared_ptr<ShaderService::ILowLevelCompiler> CreateLowLevelShaderCompiler();

    intrusive_ptr<ID3D::ShaderReflection>  CreateReflection(const CompiledShaderByteCode& shaderCode);

    extern template intrusive_ptr<ID3D::ShaderReflection>;

}}


text:
function letters = randomletter(size)
% Return an array of random 'letters'. Returns an array of integers {1,2,3}
%%%%%%%%%%%%%%%%%
% Inputs:
%	** size: number of length of the array of output
%%%%%%%%%%%%%%%%%
% Outputs:
%	** letters: Returns an array of integers {1,2,3}
%%%%%%%%%%%%%%%%%
% Author: 'Toño G. Quintela' tgq.spm@gmail.com

%letters=zeros(1,size);
%support = rand(1,size);

letters = randi([1,3],1,size);
%letters = (support<1/3) + 2*(support >= 1/3 & support<2/3) + 3*(support >=2/3);

end


text:
#ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_SEQUENCE
#define BOOST_SPIRIT_INCLUDE_CLASSIC_SEQUENCE
#include <boost/spirit/home/classic/core/composite/sequence.hpp>
#endif


text:
from tincan.serializable_base import SerializableBase

"""
.. module:: languagemap
   :synopsis: A simple wrapper for a map containing language mappings

"""

class LanguageMap(dict, SerializableBase):
    def __init__(self, *args, **kwargs):
        """Initializes a LanguageMap with the given mapping

        This constructor will first check the arguments for flatness
        to avoid nested languagemaps (which are invalid) and then
        call the base dict constructor

        """
        check_args = dict(*args, **kwargs)
        list(map(lambda k_v: (k_v[0], self._check_basestring(k_v[1])), iter(check_args.items())))
        super(LanguageMap, self).__init__(check_args)

    def __setitem__(self, prop, value):
        """Allows bracket notation for setting values with hyphenated keys

        :param prop: The property to set
        :type prop: str
        :param value: The value to set
        :type value: obj

        :raises: NameError, LanguageMapTypeError

        """
        self._check_basestring(value)
        super(LanguageMap, self).__setitem__(prop, value)

    @staticmethod
    def _check_basestring(value):
        """Ensures that value is an instance of basestring

        :param value: the value to check
        :type value: any

        """
        if not isinstance(value, str):
            raise TypeError("Value must be a stringstring_types")


text:
The pelican-hyde is a [Pelican](https://github.com/getpelican) theme inspired on the beautiful [Hyde](http://hyde.getpoole.com/) Jekyll theme

You can see a live demo [here](http://jvanz.github.io/)

![Screenshot](screenshot.png)


text:
from __future__ import unicode_literals

from django.conf.urls import url, include

import spirit.comment.bookmark.urls
import spirit.comment.flag.urls
import spirit.comment.history.urls
import spirit.comment.like.urls
from . import views

urlpatterns = [
    url(r'^(?P<topic_id>\d+)/publish/$', views.publish, name='publish'),
    url(r'^(?P<topic_id>\d+)/publish/(?P<pk>\d+)/quote/$', views.publish, name='publish'),

    url(r'^(?P<pk>\d+)/update/$', views.update, name='update'),
    url(r'^(?P<pk>\d+)/find/$', views.find, name='find'),
    url(r'^(?P<topic_id>\d+)/move/$', views.move, name='move'),

    url(r'^(?P<pk>\d+)/delete/$', views.delete, name='delete'),
    url(r'^(?P<pk>\d+)/undelete/$', views.delete, kwargs={'remove': False, }, name='undelete'),

    url(r'^upload/$', views.image_upload_ajax, name='image-upload-ajax'),

    url(r'^bookmark/', include(spirit.comment.bookmark.urls, namespace='bookmark')),
    url(r'^flag/', include(spirit.comment.flag.urls, namespace='flag')),
    url(r'^history/', include(spirit.comment.history.urls, namespace='history')),
    url(r'^like/', include(spirit.comment.like.urls, namespace='like')),
]


text:
import { Code } from "./code";
import { TransportEquipment } from "./transport-equipment";

export class TransportMeans {
    constructor(public transportMeansTypeCode: Code = new Code(),
        public transportEquipment: TransportEquipment[] = [new TransportEquipment()]) {
    }
}


text:
<?php
/**
 * *
 *  * please don't remove this comment block
 *  *
 *  * @author phptricks Team - Mohammad Anzawi
 *  * @author_uri https://phptricks.org
 *  * @uri https://github.com/anzawi/php-database-class
 *  * @version 5.0.0
 *  * @licence MIT -> https://opensource.org/licenses/MIT
 *  * @package PHPtricks\Orm
 *
 */

namespace PHPtricks\Orm\Relation;

use PHPtricks\Orm\Collection\Collection;
use PHPtricks\Orm\Model;

/**
 * Trait RelationProvider
 * @since Version 5.0.0
 *
 * @package PHPtricks\Orm\Relation
 */
trait RelationProvider
{

    /**
     * @var
     */
    private $_relationModel;
    /**
     * @var
     */
    private $_relationWithModel;

    /**
     * @var
     */
    private $_joinType = '';

    /**
     * @var
     */
    private $_allowedTyps = ['LEFT', 'RIGHT'];

    /**
     * @param  Model  $model
     *
     * @return $this
     */
    protected function make(Model $model)
    {
        $this->_relationModel = $model;

        return $this;
    }

    /**
     * @param  string  $model
     *
     * @return $this
     */
    protected function relatedWith(string $model) : RelationProvider
    {
        // create new object from model
        $this->_relationWithModel = new $model();

        return $this;
    }

    protected function join(string $type = '') : RelationProvider
    {
        // empty $type main cross join
        $this->_joinType = strtoupper($type);
        if( !in_array($type, $this->_allowedTyps) ) {
            $this->_joinType = "";
        }

        return $this;
    }

    protected function outer()
    {
        $this->_joinType .= ' OUTER';
    }

    /**
     * @param  string  $foreignId
     * @param  string|null  $id
     *
     * @return PHPtricks\Orm\Collection\Collection
     */
    protected function on(string $foreignId, string $id = null) : Collection
    {
        if ($id === null) {
            $id = $this->_relationModel->id();
        }

        $stmt = "SELECT * FROM {$this->_relationWithModel->table()} as main
                    {$this->_joinType} JOIN {$this->_relationModel->table()} as other
                    ON(main.{$id} = other.{$foreignId}){$this->getQueryAdditions()}";

        return $this->collection([
            'results' => $this->query($stmt)->results(),
            'table'   => null,
            'id'      => null,
        ]);
    }

    protected function fullOuterJoinOn(string $foreignId, string $id = null) : Collection
    {
        if ($id === null) {
            $id = $this->_relationModel->id();
        }

        $stmt = "SELECT * FROM {$this->_relationWithModel->table()} as main
                    LEFT OUTER JOIN {$this->_relationModel->table()} as other
                    ON(main.{$id} = other.{$foreignId}){$this->getQueryAdditions()}

                    UNION

                    SELECT * FROM {$this->_relationWithModel->table()} as main
                    RIGHT OUTER JOIN {$this->_relationModel->table()} as other
                    ON(main.{$id} = other.{$foreignId}){$this->getQueryAdditions()}
                    ";

        return $this->collection([
            'results' => $this->query($stmt)->results(),
            'table'   => null,
            'id'      => null,
        ]);
    }

}


text:
class OilTemplateDefinition;
class OilFunctionParameterList;
class OilFunctionParameter;
class OilMethodParameterList;

typedef struct FlatNameList_Struct
{

	inline FlatNameList_Struct ():
		Names ( NULL ),
		Count ( 0 )
	{
	}

	std :: u32string * Names;
	uint32_t Count;

} FlatNameList;

typedef struct FunctionParamList_Struct
{

	inline FunctionParamList_Struct ():
		Params ( NULL ),
		Count ( 0 )
	{
	}

	OilFunctionParameter ** Params;
	uint32_t Count;

} FunctionParamList;

void MakeNameList_TemplateDefinition ( OilTemplateDefinition & Template, FlatNameList & NameList, FlatNameList * BaseList = NULL );
void MakeNameList_FunctionParameters ( OilFunctionParameterList & ParamList, FunctionParamList & List, bool & NotEmpty );
void MakeNameList_MethodParameters ( OilMethodParameterList & ParamList, FunctionParamList & List, bool & NotEmpty );

void DestroyFlatNameList ( FlatNameList & NameList );
void DestroyFunctionParamList ( FunctionParamList & List );

#endif


text:
class CreateImage < ActiveRecord::Migration
  def change
    create_table :images do |t|
      t.text :image_meta_data

      t.timestamps null: false
    end
  end
end


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from amaasutils.logging_utils import DEFAULT_LOGGING
from decimal import Decimal
import unittest

from amaascore.assets.interface import AssetsInterface
from amaascore.books.interface import BooksInterface
from amaascore.transactions.children import Charge
from amaascore.transactions.interface import TransactionsInterface
from amaascore.tools.generate_asset import generate_asset
from amaascore.tools.generate_book import generate_book
from amaascore.tools.generate_transaction import generate_transaction
from tests.unit.config import STAGE

import logging.config
logging.config.dictConfig(DEFAULT_LOGGING)

class AllocationTest(unittest.TestCase):

    def setUp(self):
        self.longMessage = True  # Print complete error message on failure
        self.maxDiff = None  # View the complete diff when there is a mismatch in a test
        self.transactions_interface = TransactionsInterface(environment=STAGE)
        self.assets_interface = AssetsInterface(environment=STAGE)
        self.books_interface = BooksInterface(environment=STAGE)
        self.asset_manager_id = 1
        self.asset = generate_asset(asset_manager_id=self.asset_manager_id)
        self.asset_book = generate_book(asset_manager_id=self.asset_manager_id)
        self.counterparty_book = generate_book(asset_manager_id=self.asset_manager_id)
        self.transaction = generate_transaction(asset_manager_id=self.asset_manager_id, asset_id=self.asset.asset_id,
                                                asset_book_id=self.asset_book.book_id,
                                                counterparty_book_id=self.counterparty_book.book_id)
        self.transaction_id = self.transaction.transaction_id
        self.setup_cache()

    def tearDown(self):
        pass

    def create_transaction_asset(self):
        self.assets_interface.upsert(asset)

    def setup_cache(self):
        self.create_transaction_asset()
        self.create_transaction_book(self.asset_book)
        self.create_transaction_book(self.counterparty_book)

    def create_transaction_book(self, book):
        self.books_interface.new(book)

    def test_Allocations(self):
        transaction = generate_transaction(asset_manager_id=self.asset_manager_id, asset_id=self.asset.asset_id,
                                           asset_book_id=self.asset_book.book_id,
                                           counterparty_book_id=self.counterparty_book.book_id,
                                           quantity=Decimal('100'))
        transaction.charges['TEST'] = Charge(charge_value=Decimal('10'), currency='SGD')
        self.transactions_interface.new(transaction)
        allocation_dicts = [{'book_id': 'ABC', 'quantity': Decimal('40')},
                            {'book_id': 'XYZ', 'quantity': Decimal('60')}]
        abc_book = generate_book(asset_manager_id=self.asset_manager_id, book_id='ABC')
        xyz_book = generate_book(asset_manager_id=self.asset_manager_id, book_id='XYZ')
        self.create_transaction_book(abc_book)
        self.create_transaction_book(xyz_book)
        allocations = self.transactions_interface.allocate_transaction(asset_manager_id=self.asset_manager_id,
                                                                       transaction_id=transaction.transaction_id,
                                                                       allocation_type='asset_manager',
                                                                       allocation_dicts=allocation_dicts)
        self.assertEqual(len(allocations), 2)
        book_ids = sorted([allocation.asset_book_id for allocation in allocations])
        self.assertEqual(book_ids, ['ABC', 'XYZ'])
        quantities = sorted([allocation.quantity for allocation in allocations])
        self.assertEqual(quantities, [Decimal('40'), Decimal('60')])
        charges = sorted([allocation.charges.get('TEST').charge_value for allocation in allocations])
        self.assertEqual(charges, [Decimal('4'), Decimal('6')])

    def test_AllocationWithExplictID(self):
        transaction = generate_transaction(asset_manager_id=self.asset_manager_id, asset_id=self.asset.asset_id,
                                           asset_book_id=self.asset_book.book_id,
                                           counterparty_book_id=self.counterparty_book.book_id,
                                           quantity=Decimal('100'))
        self.transactions_interface.new(transaction)
        partial_tran_id = transaction.transaction_id[:10]
        allocation_dicts = [{'book_id': 'ABC', 'quantity': Decimal('60'), 'transaction_id': partial_tran_id + '_ABC'},
                            {'book_id': 'XYZ', 'quantity': Decimal('40'), 'transaction_id': partial_tran_id + '_XYZ'}]
        abc_book = generate_book(asset_manager_id=self.asset_manager_id, book_id='ABC')
        xyz_book = generate_book(asset_manager_id=self.asset_manager_id, book_id='XYZ')
        self.create_transaction_book(abc_book)
        self.create_transaction_book(xyz_book)
        allocations = self.transactions_interface.allocate_transaction(asset_manager_id=self.asset_manager_id,
                                                                       transaction_id=transaction.transaction_id,
                                                                       allocation_type='counterparty',
                                                                       allocation_dicts=allocation_dicts)
        self.assertEqual(len(allocations), 2)
        book_ids = sorted([allocation.counterparty_book_id for allocation in allocations])
        self.assertEqual(book_ids, ['ABC', 'XYZ'])
        quantities = sorted([allocation.quantity for allocation in allocations])
        self.assertEqual(quantities, [Decimal('40'), Decimal('60')])
        transaction_ids = sorted([allocation.transaction_id for allocation in allocations])
        self.assertEqual(transaction_ids, [partial_tran_id + '_ABC', partial_tran_id + '_XYZ'])

    def test_RetrieveTransactionAllocations(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
@extends('layouts.admin')
@section('content')

            @include('admin.include.button-add')

          @include('admin.include.search')

              {{trans('admin.fieldname_item_id')}}
              {{trans('admin.fieldname_item_classid')}}
              {{trans('admin.fieldname_item_type')}}
              {{trans('admin.fieldname_item_title')}}
              {{trans('admin.fieldname_item_attachment')}}
              {{trans('admin.fieldname_item_fraction')}}
              @if ($website['type'] == 3)
              {{trans('admin.fieldname_item_is_answer')}}
              @endif
              {{trans('admin.fieldname_item_status')}}
              {{trans('admin.fieldname_item_option')}}

              @include('admin.include.fieldvalue.v-for')
                @{{ item.id }}
                @{{ item.classname }}
                  {{trans('admin.define_model_question1')}}
                  {{trans('admin.define_model_question2')}}
                  {{trans('admin.define_model_question3')}}
                @{{ item.title}}
                @include('admin.include.fieldvalue.attachment')
                @{{ item.score }}
                @if ($website['type'] == 3)

                @endif
                @include('admin.include.fieldvalue.status')

                    @if ($website['type'] != 3)
                    <button type="button" @click="questionoption_action(item.id)" class="btn btn-primary" >  {{trans('admin.website_navigation_question_option')}}</button>
                    @endif
                    @include('admin.include.fieldvalue.option')

        @include('admin.include.pages')

@endsection


text:
namespace _03.Detail_Printer
{
    public class Program
    {
        public static void Main()
        {
        }
    }
}


text:
package org.kie.workbench.common.services.datamodeller.core;

public interface HasSuperClass {

    String getSuperClassName();

    void setSuperClassName(String superClassName);

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Nvelope.Reflection;

namespace Nvelope.Tests.Reflection
{
    [TestFixture]
    public class ReflectionExtensionTests
    {
        [Test]
        public void GetMembers()
        {
            DataTable dt = null;
            Assert.IsFalse(dt._GetMembers().Any());

            var dh = new DollHouse();
            var members = dh._GetMembers();
            Assert.AreEqual(4, members.Count());

            var attr = members.FilterAttributeType<DummyAttribute>();
            Assert.AreEqual(1, attr.Count());

            var ro = members.RemoveReadOnly();
            Assert.IsFalse(ro.Names().Contains("Size"));
            Assert.IsTrue(ro.Names().Contains("Rooms"));
            Assert.IsTrue(ro.Names().Contains("Paint"));
        }

        [Test]
        public void Declarations()
        {
            var dh = new DollHouse();
            var members = dh._GetMembers();
            var declare = members.FieldDeclarations();
            Assert.AreEqual(typeof(Color), declare["Paint"]);
            var allmembers = dh._GetMembers(MemberTypes.All);
            var fields = allmembers.FieldDeclarations();
            Assert.AreEqual("([Paint,System.Drawing.Color],[Rooms,System.String[]],[Size,System.Int32],[Spam,System.String])",
                fields.Print());
        }

        [Test]
        public void FieldTypes()
        {
            var dh = new DollHouse();
            var ft = dh._FieldTypes();
            Assert.AreEqual("([Paint,System.Drawing.Color],[Rooms,System.String[]],[Size,System.Int32],[Spam,System.String])",
                ft.Print());
        }

        [Test]
        public void GetNonGenericType()
        {
            Type i = typeof(int);
            Type inull = typeof(int?);
            Assert.AreEqual(inull.GetNonGenericType(), i);
        }

        [Test]
        public void PlayWithDollHouse()
        {
            var dh = new DollHouse();
            Assert.AreEqual(2, dh.Size);
            Assert.AreEqual("Eggs", dh.Spam);
            Assert.AreEqual(Color.White, dh.Paint);
            dh.Paint = Color.Black;
            Assert.AreEqual(Color.Black, dh.Paint);

        }

        [Test]
        public void _Inspect()
        {
            var data = new { IntField = 1, StrField = "a" };
            Assert.AreEqual("([IntField,1],[StrField,a])", data._Inspect());
        }

        [Test]
        public void _AsDictionary()
        {
            var data = new { IntField = 1, StrField = "a" }._AsDictionary();
            Assert.True(data.ContainsKey("IntField"));
            Assert.True(data.ContainsKey("StrField"));
            Assert.AreEqual(data["IntField"], 1);
            Assert.AreEqual(data["StrField"], "a");
        }

        [Test]
        public void _AsDictionary_KeepsAsDictionary()
        {
            var data = new Dictionary<string, object>();
            data.Add("IntField", 1);
            data.Add("StrField", "a");
            var res = data._AsDictionary();
            // Make sure the compiler doesn't screw around with us and change this on us
            Assert.AreEqual(typeof(Dictionary<string, object>), res.GetType());
            Assert.AreEqual("([IntField,1],[StrField,a])", res.Print());
        }

        [Test]
        public void _AsDictionary_WithFields_KeepsAsDictionary()
        {
            var data = new Dictionary<string, object>();
            data.Add("IntField", 1);
            data.Add("StrField", "a");
            var res = data._AsDictionary("IntField".And("StrField"));
            // Make sure the compiler doesn't screw around with us and change this on us
            Assert.AreEqual(typeof(Dictionary<string, object>), res.GetType());
            Assert.AreEqual("([IntField,1],[StrField,a])", res.Print());
        }

        [Test]
        public void _AsDictionary_KeepsAsDictionaryPolymorphically()
        {
            var data = new Dictionary<string, object>();
            data.Add("IntField", 1);
            data.Add("StrField", "a");
            // If we assign the dictionary to an object, it should still call the
            // right version of _AsDictionary internally, even though the compiler
            // will call the object version instead of the Dictionary<> version
            object obj = data;
            var res = obj._AsDictionary();
            Assert.AreEqual("([IntField,1],[StrField,a])", res.Print());
            // If the above has Comparer... etc in it, that means that instead of
            // evaluating the thing as a Dictionary and passing it back, the _AsDictionary
            // function got the properties of the Dictionary instead
        }

        [Test]
        public void _AsDictionary_WithFields_KeepsAsDictionaryPolymorphically()
        {
            var data = new Dictionary<string, object>();
            data.Add("IntField", 1);
            data.Add("StrField", "a");
            // If we assign the dictionary to an object, it should still call the
            // right version of _AsDictionary internally, even though the compiler
            // will call the object version instead of the Dictionary<> version
            object obj = data;
            var res = obj._AsDictionary("IntField".And("StrField"));
            Assert.AreEqual("([IntField,1],[StrField,a])", res.Print());
            // If the above has Comparer... etc in it, that means that instead of
            // evaluating the thing as a Dictionary and passing it back, the _AsDictionary
            // function got the properties of the Dictionary instead
        }

        [Test]
        public void _AsDictionary_WithDictionaryReturnsCopy()
        {
            var data = new Dictionary<string, object>();
            data.Add("IntField", 1);
            data.Add("StrField", "a");
            var res = data._AsDictionary();
            Assert.False(data == res, "The two dictionaries shouldn't have been the same object");
        }

        [Test]
        public void _Diff()
        {
            var a = new { A = 1, B = 2, C = 3 };
            var b = new { A = 1, B = -2, C = 3 };

            var diff = a._Diff(b);
            Assert.AreEqual("([B,(2, -2)])", diff.Print());

            diff = a._Diff(b, "A", "B");
            Assert.AreEqual("([B,(2, -2)])", diff.Print());

            diff = a._Diff(b, "A", "C");
            Assert.AreEqual("()", diff.Print());

            var copyA = new { A = 1, B = 2, C = 3 };
            diff = a._Diff(copyA);
            Assert.AreEqual("()", diff.Print());
        }

        [Test]
        public void _Diff_MissingFields()
        {
            var a = new { A = 1 };
            var b = new { B = 2 };

            var diff = a._Diff(b);
            Assert.AreEqual("([A,(1, )],[B,(, 2)])", diff.Print());
        }

        [Test]
        public void _AsType()
        {
            object o = typeof(int);
            Assert.AreEqual(typeof(int), o._AsType());
            o = 1;
            Assert.AreEqual(typeof(int), o._AsType());
        }

        [Test]
        public void Implements()
        {
            Assert.True(typeof(Dictionary<string, object>).Implements<IDictionary>());
            Assert.False(typeof(int).Implements<IDictionary>());
        }
    }

    public class DollHouse
    {
        public string[] Rooms = new string[] {
            "Dinning Room",
            "Kitchen"
        };

        public int Size
        {
            get
            {
                return Rooms.Count();
            }
        }
        /// <summary>
        /// This is here to test FilterAttributeType
        /// </summary>
        [DummyAttribute]
        public string Spam
        {
            get
            {
                return "Eggs";
            }
        }

        private Color? _paint;

        public Color Paint
        {
            get {
                return this._paint ?? Color.White;
            }
            set {
                this._paint = value;
            }
        }
    }
    [AttributeUsage(AttributeTargets.All)]
    public class DummyAttribute : System.Attribute
    {
        public DummyAttribute() { }
    }
}


text:
typedef enum BootRequest_Options
{
    BootRequest_Invalid = 0,
    BootRequest_NanoBooter = 1,
    BootRequest_ProprietaryBootloader = 2,
} BootRequest_Options;

typedef enum BootExecution_Options
{
    BootExecution_Unknown = 0,
    BootExecution_OK = 1,
    BootRequest_Error = 2,
} BootExecution_Options;

// This struct holds the information to be passed to and from nanoCLR and nanoBooter
// It's placed at a known fixed RAM address so both apps know where to look for it.
typedef struct __nfpack BootClipboard
{
    // to be hold the magic marker value
    uint32_t StartMarker;

    BootRequest_Options BootRequest;
    uint32_t BootParameters;
    BootExecution_Options BootExecution;
    uint32_t ErrorCode;

    VersionInfo BooterVersion;
    VersionInfo CLRVersion;

    // padding to keep the struct aligned
    // and keep space available for future expansion
    uint8_t padding[14];

    // to be hold the magic marker value
    uint32_t EndMarker;
} BootClipboard;

extern BootClipboard g_BootClipboard;

#ifdef __cplusplus
extern "C"
{
#endif

    void InitBootClipboard();

    // Launches the proprietary bootloader of the platform.
    // Returns false in case it's not supported (which is considered the default).
    // In case of a successfull call it won't return.
    // Implemented as "weak" to allow it to be replaced with "hard" implementation at platform level.
    bool LaunchProprietaryBootloader();

    // Returns true if the there is a request to remain in nanoBooter
    bool IsToRemainInBooter();

    // Request to launch nanoBooter
    // Returns false in case it's not supported (which is considered the default).
    bool RequestToLaunchNanoBooter();

    // Request to launch proprietary bootloader
    // Returns false in case it's not supported (which is considered the default).
    bool RequestToLaunchProprietaryBootloader();

    // Report successfull nanoBooter execution
    void ReportSuccessfullNanoBooter();

#ifdef __cplusplus
}
#endif

#endif // NANOHAL_BOOT_H


text:
layout: portfolio
title: Mapping Federal Firearms Licensces
date: 2014-06-22 20:51:57.000000000 +05:30
categories: []
tags: []
status: publish
type: portfolio
published: true
meta:
  _edit_last: '1'
  _wpas_done_all: '1'
  _thumbnail_id: '3903'
  _jetpack_related_posts_cache: a:0:{}
  dsq_thread_id: '3641947555'
author:
  login: cvlewis
  email: carl@carlvlewis.net
  display_name: Carl V. Lewis
  first_name: Carl V.
  last_name: Lewis
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---

This map, originally published on savannahnow.com, shows all 32 businesses that have a federal firearms license in Chatham County, Ga.


text:
package org.elasticsearch.script;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class ScriptStats implements Writeable, ToXContentFragment {
    private final List<ScriptContextStats> contextStats;
    private final long compilations;
    private final long cacheEvictions;
    private final long compilationLimitTriggered;

    public ScriptStats(List<ScriptContextStats> contextStats) {
        this.contextStats = contextStats.stream().sorted().collect(Collectors.toUnmodifiableList());
        long compilations = 0;
        long cacheEvictions = 0;
        long compilationLimitTriggered = 0;
        for (ScriptContextStats stats: contextStats) {
            compilations += stats.getCompilations();
            cacheEvictions += stats.getCacheEvictions();
            compilationLimitTriggered += stats.getCompilationLimitTriggered();
        }
        this.compilations = compilations;
        this.cacheEvictions = cacheEvictions;
        this.compilationLimitTriggered = compilationLimitTriggered;
    }

    public ScriptStats(StreamInput in) throws IOException {
        compilations = in.readVLong();
        cacheEvictions = in.readVLong();
        compilationLimitTriggered = in.readVLong();
        contextStats = in.readList(ScriptContextStats::new);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVLong(compilations);
        out.writeVLong(cacheEvictions);
        out.writeVLong(compilationLimitTriggered);
        out.writeList(contextStats);
    }

    public List<ScriptContextStats> getContextStats() {
        return contextStats;
    }

    public long getCompilations() {
        return compilations;
    }

    public long getCacheEvictions() {
        return cacheEvictions;
    }

    public long getCompilationLimitTriggered() {
        return compilationLimitTriggered;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(Fields.SCRIPT_STATS);
        builder.field(Fields.COMPILATIONS, compilations);
        builder.field(Fields.CACHE_EVICTIONS, cacheEvictions);
        builder.field(Fields.COMPILATION_LIMIT_TRIGGERED, compilationLimitTriggered);
        builder.startArray(Fields.CONTEXTS);
        for (ScriptContextStats contextStats: contextStats) {
            contextStats.toXContent(builder, params);
        }
        builder.endArray();
        builder.endObject();
        return builder;
    }

    static final class Fields {
        static final String SCRIPT_STATS = "script";
        static final String CONTEXTS = "contexts";
        static final String COMPILATIONS = "compilations";
        static final String CACHE_EVICTIONS = "cache_evictions";
        static final String COMPILATION_LIMIT_TRIGGERED = "compilation_limit_triggered";
    }
}