text:
<!doctype html>

<meta charset="utf-8">
<title>Quantum Computing – Maths & Physics Club</title>
<meta name="description" content="The following article was written for and published by the annual newsletter of Dept. of Physics, IIT Bombay in collaboration with Insight, the student media body of IITB, in the Autumn semester of my freshmen year (2015). It is aimed at providing a brief info to the latest advancements in the field of quantum computing and what lies ahead.

">
<meta name="keywords" content="Quantum Physics">

<meta name="twitter:title" content="Quantum Computing">
<meta name="twitter:description" content="The following article was written for and published by the annual newsletter of Dept. of Physics, IIT Bombay in collaboration with Insight, the student media body of IITB, in the Autumn semester of my freshmen year (2015). It is aimed at providing a brief info to the latest advancements in the field of quantum computing and what lies ahead.

">

<meta name="twitter:creator" content="@toshi_physics">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://mnp-club.github.io/images/site-logo.png">

<meta property="og:locale" content="India">
<meta property="og:type" content="article">
<meta property="og:title" content="Quantum Computing">
<meta property="og:description" content="The following article was written for and published by the annual newsletter of Dept. of Physics, IIT Bombay in collaboration with Insight, the student media body of IITB, in the Autumn semester of my freshmen year (2015). It is aimed at providing a brief info to the latest advancements in the field of quantum computing and what lies ahead.

">
<meta property="og:url" content="http://mnp-club.github.io/blog/quantum-computation/">
<meta property="og:site_name" content="Maths & Physics Club">

<link rel="canonical" href="http://mnp-club.github.io/blog/quantum-computation/">
<link href="http://mnp-club.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="Maths & Physics Club Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://mnp-club.github.io/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://mnp-club.github.io/favicon.ico">

<link rel="shortcut icon" href="http://mnp-club.github.io/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://mnp-club.github.io/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://mnp-club.github.io/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://mnp-club.github.io/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://mnp-club.github.io/images/apple-touch-icon-144x144-precomposed.png">

About

Blog

Projects

Events

Maths & Physics Club

Where Knowledge is Free...

Quantum Physics

Quantum Computing

        By Toshi Parmar
        <time datetime="2017-01-09T15:49:07+05:30"> January 09, 2017</time>

         Comment

The following article was written for and published by the annual newsletter of Dept. of Physics, IIT Bombay in collaboration with Insight, the student media body of IITB, in the Autumn semester of my freshmen year (2015). It is aimed at providing a brief info to the latest advancements in the field of quantum computing and what lies ahead.

A New Hope

Our story begins with a team of researchers at The University of New South Wales(UNSW), Australia, led by Andrew Dzurak who have successfully
accomplished the making of a two qubit logic gate in silicon, which is a crucial hurdle overcome in making quantum computers
a reality. "What we have is a game changer," says team leader Prof. Dzurak.

"We've demonstrated a two qubit logic gate the central building block of a quantum computer and, significantly, done it in silicon.
Because we use essentially the same device technology as existing computer chips, we believe it will be much easier to manufacture
a fullscale processor chip than for any of the leading designs, which rely on more exotic technologies."
The key idea behind the working of the UNSW team has been the morphing of normal transistors, into defining quantum bits or 'qubits',
by ensuring that each transistor has a single electron associated with it, and representing the binary equivalent of numbers 0 and 1
by spin of the electron.

The sentence makes sense quite ephemerally, so let's deconstruct the concept in lyman's language and restore freedom to our bound curiosity…

The Very Begining

Essentially the concept of quantum computing involves use of quantum bits or 'qubits' instead of conventional bits in boolean algebra,
that can be coupled in a scalable manner to make up one and two qubit logic gates.
The numerous physical realisations of qubits, single photons, trapped ions, silicon and semiconductor quantum dots,
single defects or atoms in diamond etc. have to be sufficiently fault tolerant and conserved under time evolution,
with discrete and spaced eigenvalues that can be mapped onto an effective spin 1/2 system.

The ideation for representing qubits as the spin of an electron was primarily proposed in 1968,
and sparked up with eminent physicist Richard Feynman proposing the possibility of a quantum computer in 1982.

That which makes all the difference

The edge that a quantum system has over the conventional is the property of entanglement and superposition of states,
i.e. a qubit's existence is governed by superposition of the two basis states that denote conventional bits 0 and 1,
mathematically, a linear combination.

The bloch sphere shown in the article, is a representation of a qubit with associated probability amplitudes,
with the two basis states represented in standard Dirac notation (The braket notation).
Thus considering two interacting qubits, four possible combinations yield, each weighed by a coefficient
that denotes the probability of existence of the system in that state.
To specify a combination of two conventional bits, two information are coded, the value of both the bits,
while for the quantum system four information, the four coefficients.
Thus the information represented by an 'n' qubit system is exponentially large in comparison with its classical counterpart,
the former is essentially two raised to the latter.

But the world is not all cupcakes and rainbows

The state of superposition cascades down to one of its basis states on observation,
termed as the collapse of the governing Schrodinger wave function, essentially leading to us losing our data that boasted
of exponentially large capacities to normal bit sized information.
Thus, here lies the spinner, specific algorithms have to be applied to extract specific information out of a quantum system.
Many such brilliant minds have risen to the occasion, among them, notably and famed are Peter Shor (Shor's Algorithm, 1994),
Daniel Simon (Simon's Algorithm, 1994) and Lov K. Grover (Grover's Algorithm, 1996).

Let's take a look at what specific information can be extracted out -

Shor's algorithm is a quantum algorithm that addresses the problem of discrete logarithms and integer factorisation,
a problem so intricate that our public key cryptography schemes like the RSA rely on the computational intractability
in factoring large numbers for the most advanced classical computers.

Simon's algorithm deals with the computational analysis of decision tree complexity and solves the problem exponentially
faster than any known classical algorithm.

Grover's algorithm addresses database search, i.e. given a unique output produced by a black box function
(A function with unknown formulation but known mapping) it figures out the input with high probability,
addressing the problem in quadratically fewer queries than classical.

Many more such algorithms exist, attacking with brute force, the issues that lie beyond the scope of classical computers.
Another problem is that many of the quantum algorithms give probabilistic solutions, solutions with probability very close to one,
and which can be improved upon by repeated iterations but nevertheless its probabilistic.
Many others however, are fully deterministic and hence efficacious.

The quantum computers can only respond to specific algorithms and tasks exponentially efficiently than classical, thus,
they are not the substitute for them, but an aid, for more technological and advanced sector.
Not every task that a normal personal computer does can be effectively performed with them.
So wish the genie to show you a movie, and quantum computer would be useless trash. Wish to crack security codes for all online credit
transfers, ye ol' quantum computer would watch the world burn as it decrypts transactions.

Further, not-so-farther difficulties ahead

A big hurdle now is to remove decoherence from the system, isolating the system from the
surroundings, cutting down its interactions that make the system decohere, and to do so
economically and feasibly. Decoherence is irreversible and nonunitary and thus must be
controlled if not eradicated. Currently superconducting qubits can be configured to remove
setting in of significant decoherence in physically avoidable time lag, which typically ranges
between the order of nanoseconds to seconds at low temperatures, by cooling the qubit to 20milli kelvin or lower temperatures.

Another problem that is now faced is to scale this system up to vast numbers of stable qubit registers or "q-registers",
quantum mechanical analogues of classical processor registers.

Unless a very efficient way is developed, optimum working is an impossibility.
In this direction, Prof. Dzurak notes that the team has "recently patented a design for full scale
quantum computer chip that would allow for millions of our qubits, all doing the same kind of calculations
we've just experimentally demonstrated."

The UNSW team's research breakthrough has attacked three of the major requirements -

1) qubits that can be initialised to arbitrary values,
2) qubits with successful readout fidelities,
3) a universal CNOT quantum gate, faster than the decoherence time of the system,
with the fabrication process compatible with standard Complementary Metal Oxide Semiconductor (CMOS) technology that already exists
 for manufacturing classical Si based semiconductor chips.
Future experiments by this team will include improvements to facilitate full two qubit tomography.
Improvement by lowering the sensitivity to electrical noise is also targeted.
Though the two qubit system represents the smallest scalable system so far, it is consistent with current transistor sizes, offering the prospect of realizing a largescale
quantum processor using the same silicon manufacturing technologies that have enabled the current information age.

And lastly, on a more tender note,
"Computers are physical objects, and computations are physical processes.
What computers can or cannot compute is determined by the laws of physics alone."
– David Deutsch

So we mustn't lose faith. More breakthroughs are yet to arrive!

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

© 2017 Maths And Physics Club. Powered by Jekyll


text:
package com.facebook.thrift.server.example;

import com.facebook.thrift.TException;
import com.facebook.thrift.TProcessor;
import com.facebook.thrift.TProcessorFactory;
import com.facebook.thrift.protocol.TProtocol;
import com.facebook.thrift.protocol.TProtocolFactory;
import com.facebook.thrift.protocol.TBinaryProtocol;
import com.facebook.thrift.protocol.THeaderProtocol;
import com.facebook.thrift.server.TServer;
import com.facebook.thrift.server.TRpcConnectionContext;
import com.facebook.thrift.server.TThreadFactoryImpl;
import com.facebook.thrift.transport.TServerTransport;
import com.facebook.thrift.transport.TTransport;
import com.facebook.thrift.transport.TTransportException;
import com.facebook.thrift.transport.TTransportFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @deprecated "Please use Netty server instead.
 * See https://github.com/facebook/nifty for details."
 *
 * Server which uses Java's built in ThreadPool management to spawn off
 * a worker pool that
 *
 */
@Deprecated
public class TThreadPoolServer extends TServer {

  private static final Logger LOGGER = LoggerFactory.getLogger(TThreadPoolServer.class.getName());

  // Executor service for handling client connections
  private ExecutorService executorService_;

  // Flag for stopping the server
  private volatile boolean stopped_;

  // Server options
  private Options options_;

  // Customizable server options
  public static class Options {
    public int minWorkerThreads = 5;
    public int maxWorkerThreads = Integer.MAX_VALUE;
    public int stopTimeoutVal = 60;
    public TimeUnit stopTimeoutUnit = TimeUnit.SECONDS;
    public BlockingQueue<Runnable> executorQueue = null;
    public RejectedExecutionHandler rejectedExecutionHandler = null;
    public ExecutorService executorService = null;
  }

  public TThreadPoolServer(TProcessor processor,
                           TServerTransport serverTransport) {
    this(processor, serverTransport,
         new TTransportFactory(), new TTransportFactory(),
         new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory());
  }

  public TThreadPoolServer(TProcessorFactory processorFactory,
                           TServerTransport serverTransport) {
    this(processorFactory, serverTransport,
         new TTransportFactory(), new TTransportFactory(),
         new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory());
  }

  public TThreadPoolServer(TProcessor processor,
                           TServerTransport serverTransport,
                           TProtocolFactory protocolFactory) {
    this(processor, serverTransport,
         new TTransportFactory(), new TTransportFactory(),
         protocolFactory, protocolFactory);
  }

  public TThreadPoolServer(TProcessor processor,
                           TServerTransport serverTransport,
                           TTransportFactory transportFactory,
                           TProtocolFactory protocolFactory) {
    this(processor, serverTransport,
         transportFactory, transportFactory,
         protocolFactory, protocolFactory);
  }

  public TThreadPoolServer(TProcessorFactory processorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory transportFactory,
                           TProtocolFactory protocolFactory) {
    this(processorFactory, serverTransport,
         transportFactory, transportFactory,
         protocolFactory, protocolFactory);
  }

  public TThreadPoolServer(TProcessor processor,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory) {
    this(new TProcessorFactory(processor), serverTransport,
         inputTransportFactory, outputTransportFactory,
         inputProtocolFactory, outputProtocolFactory);
  }

  public TThreadPoolServer(TProcessorFactory processorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory) {
    super(processorFactory, serverTransport,
          inputTransportFactory, outputTransportFactory,
          inputProtocolFactory, outputProtocolFactory);
    options_ = new Options();
    executorService_ = Executors.newCachedThreadPool(
        new TThreadFactoryImpl("thrift")
    );
  }

  public TThreadPoolServer(TProcessor processor,
          TServerTransport serverTransport,
          TTransportFactory inputTransportFactory,
          TTransportFactory outputTransportFactory,
          TProtocolFactory inputProtocolFactory,
          TProtocolFactory outputProtocolFactory,
          Options options) {
    this(new TProcessorFactory(processor), serverTransport,
         inputTransportFactory, outputTransportFactory,
         inputProtocolFactory, outputProtocolFactory,
         options);
  }

  public TThreadPoolServer(TProcessorFactory processorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory,
                           Options options) {
    super(processorFactory, serverTransport,
          inputTransportFactory, outputTransportFactory,
          inputProtocolFactory, outputProtocolFactory);

    if (options.executorService != null) {
      executorService_ = options.executorService;
    } else {
      RejectedExecutionHandler rejectedExecutionHandler = null;
      if (options.rejectedExecutionHandler != null) {
        rejectedExecutionHandler = options.rejectedExecutionHandler;
      } else {
        rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
      }

      BlockingQueue<Runnable> executorQueue = null;
      if (options.executorQueue != null) {
        executorQueue = options.executorQueue;
      } else {
        executorQueue = new SynchronousQueue<Runnable>();
      }
      executorService_ = new ThreadPoolExecutor(options.minWorkerThreads,
                                                options.maxWorkerThreads,
                                                60,
                                                TimeUnit.SECONDS,
                                                executorQueue,
                                                new TThreadFactoryImpl("thrift"),
                                                rejectedExecutionHandler);
    }

    options_ = options;
  }

  public void serve() {
    try {
      serverTransport_.listen();
    } catch (TTransportException ttx) {
      LOGGER.error("Error occurred during listening.", ttx);
      return;
    }

    stopped_ = false;
    while (!stopped_) {
      try {
        TTransport client = serverTransport_.accept();
        WorkerProcess wp = new WorkerProcess(client);
        try {
          executorService_.execute(wp);
        } catch (RejectedExecutionException ree) {
          LOGGER.warn("Client request was rejected by executor", ree);
          // close the connection, we don't need it anymore
          // if clause should always be true, but just to be on the safe side
          if (client != null && client.isOpen()) {
            client.close();
          }
        }
      } catch (TTransportException ttx) {
        if (!stopped_) {
          LOGGER.warn("Transport error occurred during acceptance of message.", ttx);
        }
      }
    }

    executorService_.shutdown();

    // Loop until awaitTermination finally does return without a interrupted
    // exception. If we don't do this, then we'll shut down prematurely. We want
    // to let the executorService clear it's task queue, closing client sockets
    // appropriately.
    long timeoutMS = options_.stopTimeoutUnit.toMillis(options_.stopTimeoutVal);
    long now = System.currentTimeMillis();
    while (timeoutMS >= 0) {
      try {
        executorService_.awaitTermination(timeoutMS, TimeUnit.MILLISECONDS);
        break;
      } catch (InterruptedException ix) {
        long newnow = System.currentTimeMillis();
        timeoutMS -= (newnow - now);
        now = newnow;
      }
    }
  }

  public void stop() {
    stopped_ = true;
    serverTransport_.interrupt();
  }

  private class WorkerProcess implements Runnable {

    /**
     * Client that this services.
     */
    private TTransport client_;

    /**
     * Default constructor.
     *
     * @param client Transport to process
     */
    private WorkerProcess(TTransport client) {
      client_ = client;
    }

    /**
     * Loops on processing a client forever
     */
    public void run() {
      TProcessor processor = null;
      TTransport inputTransport = null;
      TTransport outputTransport = null;
      TProtocol inputProtocol = null;
      TProtocol outputProtocol = null;
      try {
        processor = processorFactory_.getProcessor(client_);
        inputTransport = inputTransportFactory_.getTransport(client_);
        inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
        // THeaderProtocol must be the same instance for both input and output
        if (inputProtocol instanceof THeaderProtocol) {
          outputProtocol = inputProtocol;
        } else {
          outputTransport = outputTransportFactory_.getTransport(client_);
          outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
        }
        // we check stopped_ first to make sure we're not supposed to be shutting
        // down. this is necessary for graceful shutdown.
        TRpcConnectionContext server_ctx = new TRpcConnectionContext(client_,
                                                                     inputProtocol,
                                                                     outputProtocol);
        while (!stopped_ && processor.process(inputProtocol, outputProtocol, server_ctx)) {}
      } catch (TTransportException ttx) {
        // Assume the client died and continue silently
      } catch (TException tx) {
        LOGGER.error("Thrift error occurred during processing of message.", tx);
      } catch (Exception x) {
        LOGGER.error("Error occurred during processing of message.", x);
      }

      if (inputTransport != null) {
        inputTransport.close();
      }

      if (outputTransport != null) {
        outputTransport.close();
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
require 'fileutils'
require 'rubygems'

##
# The documentation manager generates RDoc and RI for RubyGems.

class Gem::DocManager

  include Gem::UserInteraction

  @configured_args = []

  def self.configured_args
    @configured_args ||= []
  end

  def self.configured_args=(args)
    case args
    when Array
      @configured_args = args
    when String
      @configured_args = args.split
    end
  end

  ##
  # Load RDoc from a gem if it is available, otherwise from Ruby's stdlib

  def self.load_rdoc
    begin
      gem 'rdoc'
    rescue Gem::LoadError
      # use built-in RDoc
    end

    begin
      require 'rdoc/rdoc'

      @rdoc_version = if defined? RDoc::VERSION then
                        Gem::Version.new RDoc::VERSION
                      else
                        Gem::Version.new '1.0.1' # HACK parsing is hard
                      end

    rescue LoadError => e
      raise Gem::DocumentError,
          "ERROR: RDoc documentation generator not installed: #{e}"
    end
  end

  def self.rdoc_version
    @rdoc_version
  end

  ##
  # Updates the RI cache for RDoc 2 if it is installed

  def self.update_ri_cache
    load_rdoc rescue return

    return unless defined? RDoc::VERSION # RDoc 1 does not have VERSION

    require 'rdoc/ri/driver'

    options = {
      :use_cache => true,
      :use_system => true,
      :use_site => true,
      :use_home => true,
      :use_gems => true,
      :formatter => RDoc::RI::Formatter,
    }

    driver = RDoc::RI::Driver.new(options).class_cache
  end

  ##
  # Create a document manager for +spec+. +rdoc_args+ contains arguments for
  # RDoc (template etc.) as a String.

  def initialize(spec, rdoc_args="")
    @spec = spec
    @doc_dir = File.join(spec.installation_path, "doc", spec.full_name)
    @rdoc_args = rdoc_args.nil? ? [] : rdoc_args.split
  end

  ##
  # Is the RDoc documentation installed?

  def rdoc_installed?
    File.exist?(File.join(@doc_dir, "rdoc"))
  end

  ##
  # Is the RI documentation installed?

  def ri_installed?
    File.exist?(File.join(@doc_dir, "ri"))
  end

  ##
  # Generate the RI documents for this gem spec.
  #
  # Note that if both RI and RDoc documents are generated from the same
  # process, the RI docs should be done first (a likely bug in RDoc will cause
  # RI docs generation to fail if run after RDoc).

  def generate_ri
    setup_rdoc
    install_ri # RDoc bug, ri goes first

    FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
  end

  ##
  # Generate the RDoc documents for this gem spec.
  #
  # Note that if both RI and RDoc documents are generated from the same
  # process, the RI docs should be done first (a likely bug in RDoc will cause
  # RI docs generation to fail if run after RDoc).

  def generate_rdoc
    setup_rdoc
    install_rdoc

    FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
  end

  ##
  # Generate and install RDoc into the documentation directory

  def install_rdoc
    rdoc_dir = File.join @doc_dir, 'rdoc'

    FileUtils.rm_rf rdoc_dir

    say "Installing RDoc documentation for #{@spec.full_name}..."
    run_rdoc '--op', rdoc_dir
  end

  ##
  # Generate and install RI into the documentation directory

  def install_ri
    ri_dir = File.join @doc_dir, 'ri'

    FileUtils.rm_rf ri_dir

    say "Installing ri documentation for #{@spec.full_name}..."
    run_rdoc '--ri', '--op', ri_dir
  end

  ##
  # Run RDoc with +args+, which is an ARGV style argument list

  def run_rdoc(*args)
    args << @spec.rdoc_options
    args << self.class.configured_args
    args << '--quiet'
    args << @spec.require_paths.clone
    args << @spec.extra_rdoc_files
    args << '--title' << "#{@spec.full_name} Documentation"
    args = args.flatten.map do |arg| arg.to_s end

    if self.class.rdoc_version >= Gem::Version.new('2.4.0') then
      args.delete '--inline-source'
      args.delete '--promiscuous'
      args.delete '-p'
      args.delete '--one-file'
      # HACK more
    end

    r = RDoc::RDoc.new

    old_pwd = Dir.pwd
    Dir.chdir @spec.full_gem_path

    say "rdoc #{args.join ' '}" if Gem.configuration.really_verbose

    begin
      r.document args
    rescue Errno::EACCES => e
      dirname = File.dirname e.message.split("-")[1].strip
      raise Gem::FilePermissionError.new(dirname)
    rescue RuntimeError => ex
      alert_error "While generating documentation for #{@spec.full_name}"
      ui.errs.puts "... MESSAGE:   #{ex}"
      ui.errs.puts "... RDOC args: #{args.join(' ')}"
      ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if
      Gem.configuration.backtrace
      ui.errs.puts "(continuing with the rest of the installation)"
    ensure
      Dir.chdir old_pwd
    end
  end

  def setup_rdoc
    if File.exist?(@doc_dir) && !File.writable?(@doc_dir) then
      raise Gem::FilePermissionError.new(@doc_dir)
    end

    FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)

    self.class.load_rdoc
  end

  ##
  # Remove RDoc and RI documentation

  def uninstall_doc
    raise Gem::FilePermissionError.new(@spec.installation_path) unless
    File.writable? @spec.installation_path

    original_name = [
      @spec.name, @spec.version, @spec.original_platform].join '-'

    doc_dir = File.join @spec.installation_path, 'doc', @spec.full_name
    unless File.directory? doc_dir then
      doc_dir = File.join @spec.installation_path, 'doc', original_name
    end

    FileUtils.rm_rf doc_dir

    ri_dir = File.join @spec.installation_path, 'ri', @spec.full_name

    unless File.directory? ri_dir then
      ri_dir = File.join @spec.installation_path, 'ri', original_name
    end

    FileUtils.rm_rf ri_dir
  end

end


text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Copyright (c) 2000 World Wide Web Consortium,
 * (Massachusetts Institute of Technology, Institut National de
 * Recherche en Informatique et en Automatique, Keio University). All
 * Rights Reserved. This program is distributed under the W3C's Software
 * Intellectual Property License. This program is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more
 * details.
 */

package org.w3c.dom.html;

/**
 *  Regroups the COL and COLGROUP elements. See the
 * COL element definition in HTML 4.0.
 *
See also the Document Object Model (DOM) Level 2 Specification.
 */
public interface HTMLTableColElement extends HTMLElement {
    /**
     *  Horizontal alignment of cell data in column. See the  align attribute
     * definition in HTML 4.0.
     */
    public String getAlign();
    public void setAlign(String align);

    /**
     *  Alignment character for cells in a column. See the  char attribute
     * definition in HTML 4.0.
     */
    public String getCh();
    public void setCh(String ch);

    /**
     *  Offset of alignment character. See the  charoff attribute definition
     * in HTML 4.0.
     */
    public String getChOff();
    public void setChOff(String chOff);

    /**
     *  Indicates the number of columns in a group or affected by a grouping.
     * See the  span attribute definition in HTML 4.0.
     */
    public int getSpan();
    public void setSpan(int span);

    /**
     *  Vertical alignment of cell data in column. See the  valign attribute
     * definition in HTML 4.0.
     */
    public String getVAlign();
    public void setVAlign(String vAlign);

    /**
     *  Default column width. See the  width attribute definition in HTML 4.0.
     */
    public String getWidth();
    public void setWidth(String width);

}


text:
<?php

use frontend\assets\AppAsset;

AppAsset::addScript($this, 'public/js/showBox.js');
AppAsset::addScript($this, 'public/js/push_ms.js');
?>

第三方实时推送


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<resources>
    <string name="app_name">Bar</string>
    <string name="weight_converter">Convertisseur de Poids</string>
    <string name="size_converter">Convertisseur de Distance</string>
    <string name="volume_converter">Convertisseur de Volume</string>
    <string name="temperature_converter">Convertisseur de Température</string>
    <string name="history">Historique</string>
   	<string name="from">De:</string>
   	<string name="to">Vers:</string>
   	<string name="select_unit">Sélectionner une unité</string>
</resources>


text:
require "spec_helper"

describe Protobuf::ActiveRecord::Columns do
  describe "._protobuf_map_columns" do
    context "when the class has a table" do
      let(:expected_column_names) {
        User.columns.inject({}) do |hash, column|
          hash[column.name.to_sym] = column
          hash
        end
      }

      let(:expected_column_types) {
        User.columns.inject({}) do |hash, column|
          hash[column.type.to_sym] ||= ::Set.new
          hash[column.type.to_sym] << column.name.to_sym
          hash
        end
      }

      it "maps columns by name" do
        expect(User._protobuf_columns).to eq expected_column_names
      end

      it "maps column names by column type" do
        expected_column_types.each do |expected_column_type, value|
          expect(User._protobuf_column_types).to include expected_column_type => value
        end
      end
    end
  end

  context "column type predicates" do
    before { allow(User).to receive(:_protobuf_column_types).and_return({}) }

    describe "._protobuf_date_column?" do
      before { User._protobuf_column_types[:date] = [:foo_date] }

      context "when the column type is :date" do
        it "is true" do
          expect(User._protobuf_date_column?(:foo_date)).to be true
        end
      end

      context "when the column type is not :date" do
        it "is false" do
          expect(User._protobuf_date_column?(:bar_date)).to be false
        end
      end
    end

    describe "._protobuf_datetime_column?" do
      before { User._protobuf_column_types[:datetime] = [:foo_datetime] }

      context "when the column type is :datetime" do
        it "is true" do
          expect(User._protobuf_datetime_column?(:foo_datetime)).to be true
        end
      end

      context "when the column type is not :datetime" do
        it "is false" do
          expect(User._protobuf_datetime_column?(:bar_datetime)).to be false
        end
      end
    end

    describe "._protobuf_time_column?" do
      before { User._protobuf_column_types[:time] = [:foo_time] }

      context "when the column type is :time" do
        it "is true" do
          expect(User._protobuf_time_column?(:foo_time)).to be true
        end
      end

      context "when the column type is not :time" do
        it "is false" do
          expect(User._protobuf_time_column?(:bar_time)).to be false
        end
      end
    end

    describe "._protobuf_timestamp_column?" do
      before { User._protobuf_column_types[:timestamp] = [:foo_timestamp] }

      context "when the column type is :timestamp" do
        it "is true" do
          expect(User._protobuf_timestamp_column?(:foo_timestamp)).to be true
        end
      end

      context "when the column type is not :timestamp" do
        it "is false" do
          expect(User._protobuf_timestamp_column?(:bar_timestamp)).to be false
        end
      end
    end
  end
end


text:
require 'test_helper'

class AdminRakeTest < ActiveSupport::TestCase

  @@rake = nil

  setup do

    dump_database
    collection_fixtures 'providers'

    if (!@@rake)
      @@rake = Rake.application
      Rake.application = @@rake
      Rake.application.rake_require "../../lib/tasks/admin"
      Rake::Task.define_task(:environment)
    end
    Rake.application.tasks.each {|t| t.instance_eval{@already_invoked = false}}

  end

  teardown do

  end

  test "create an admin user" do
    assert User.where(:username => 'pophealth').blank?

    capture_stdout do
      @@rake["admin:create_admin_account"].invoke
    end

    @admin = User.where(:username => 'pophealth').first

    assert !@admin.blank?
    assert @admin.approved?, "the created user should be approved"
    assert @admin.admin?, "the created user should be an admin"
  end

  def capture_stdout(&block)
    original_stdout = $stdout
    $stdout = StringIO.new
    begin
      yield
    ensure
      $stdout = original_stdout
    end
  end

end


text:
package com.facebook.buck.jvm.java;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.jvm.core.JavaLibrary;

/**
 * The new Java Test runner rule for the test protocol.
 *
 * <p>This is used to specify the target that represents the test runner itself, which is a binary
 * that will have the test source compiled into it.
 */
public class JavaTestRunner extends NoopBuildRuleWithDeclaredAndExtraDeps {

  private final JavaLibrary compiledTestsLibrary;
  private final String mainClass;

  public JavaTestRunner(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      JavaLibrary compiledTestsLibrary,
      String mainClass) {
    super(buildTarget, projectFilesystem, params.copyAppendingExtraDeps(compiledTestsLibrary));
    this.compiledTestsLibrary = compiledTestsLibrary;
    this.mainClass = mainClass;
  }

  /** @return the underlying library that represents the runner */
  public JavaLibrary getCompiledTestsLibrary() {
    return compiledTestsLibrary;
  }

  /** @return the name of the main class for running */
  public String getMainClass() {
    return mainClass;
  }
}


text:
package com.android.utils.wificonnecter;

import java.util.Comparator;
import java.util.List;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.PairwiseCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

public class WiFi {

	// Constants used for different security types
	public static final String WPA2 = "WPA2";
	public static final String WPA = "WPA";
	public static final String WEP = "WEP";
	public static final String OPEN = "Open";
    // For EAP Enterprise fields
    public static final String WPA_EAP = "WPA-EAP";
    public static final String IEEE8021X = "IEEE8021X";

    public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" };

    public static final int WEP_PASSWORD_AUTO = 0;
    public static final int WEP_PASSWORD_ASCII = 1;
    public static final int WEP_PASSWORD_HEX = 2;

	private static final String TAG = "Wifi Connecter";

	/**
	 * Change the password of an existing configured network and connect to it
	 * @param wifiMgr
	 * @param config
	 * @param newPassword
	 * @return
	 */
	public static boolean changePasswordAndConnect( final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) {
		setupSecurity(config, getWifiConfigurationSecurity(config), newPassword);
		final int networkId = wifiMgr.updateNetwork(config);
		if(networkId == -1) {
			// Update failed.
			return false;
		}
        //确定
		return connectToConfiguredNetwork(wifiMgr, config, true);
	}

	/**
	 * Configure a network, and connect to it.
	 * @param wifiMgr
	 * @param scanResult
	 * @param password Password for secure network or is ignored.
	 * @return
	 */
	public static boolean connectToNewNetwork(final WifiManager wifiMgr, final ScanResult scanResult, final String password) {
        //1.获取wifi加密方式(WEP, WPA, WPA2, WPA_EAP, IEEE8021X)
		final String security = getScanResultSecurity(scanResult);

		if(security.equals(OPEN)) {
			final int numOpenNetworksKept = 10;
			checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept);
		}

		WifiConfiguration config = new WifiConfiguration();
		config.SSID = StringUtils.convertToQuotedString(scanResult.SSID);
		config.BSSID = scanResult.BSSID;
		setupSecurity(config, security, password);

		int id = wifiMgr.addNetwork(config);
		if(id == -1) {
			return false;
		}

		if(!wifiMgr.saveConfiguration()) {
			return false;
		}

		config = getWifiConfiguration(wifiMgr, config, security);
		if(config == null) {
			return false;
		}

		return connectToConfiguredNetwork(wifiMgr, config, true);
	}

	/**
	 * Connect to a configured network.
	 * @param wifiManager
	 * @param config
	 * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT
	 * @return
	 */
	public static boolean connectToConfiguredNetwork( final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
		final String security = getWifiConfigurationSecurity(config);

		int oldPri = config.priority;
		// Make it the highest priority.
		int newPri = getMaxPriority(wifiMgr) + 1;
		if(newPri > MAX_PRIORITY) {
			newPri = shiftPriorityAndSave(wifiMgr);
			config = getWifiConfiguration(wifiMgr, config, security);
			if(config == null) {
				return false;
			}
		}

		// Set highest priority to this configured network
		config.priority = newPri;
		int networkId = wifiMgr.updateNetwork(config);
		if(networkId == -1) {
			return false;
		}

		// Do not disable others
		if(!wifiMgr.enableNetwork(networkId, false)) {
			config.priority = oldPri;
			return false;
		}

		if(!wifiMgr.saveConfiguration()) {
			config.priority = oldPri;
			return false;
		}

		// We have to retrieve the WifiConfiguration after save.
		config = getWifiConfiguration(wifiMgr, config, security);
		if(config == null) {
			return false;
		}

		// Disable others, but do not save.
		// Just to force the WifiManager to connect to it.
		if(!wifiMgr.enableNetwork(config.networkId, true)) {
			return false;
		}

		final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
		if(!connect) {
			return false;
		}

		return true;
	}

	private static void sortByPriority(final List<WifiConfiguration> configurations) {
		java.util.Collections.sort(configurations, new Comparator<WifiConfiguration>() {

			@Override
			public int compare(WifiConfiguration object1,
					WifiConfiguration object2) {
				return object1.priority - object2.priority;
			}
		});
	}

	/**
	 * Ensure no more than numOpenNetworksKept open networks in configuration list.
	 * @param wifiMgr
	 * @param numOpenNetworksKept
	 * @return Operation succeed or not.
	 */
	private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) {
		final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
		sortByPriority(configurations);

		boolean modified = false;
		int tempCount = 0;
		for(int i = configurations.size() - 1; i >= 0; i--) {
			final WifiConfiguration config = configurations.get(i);
			if(getWifiConfigurationSecurity(config).equals(OPEN)) {
				tempCount++;
				if(tempCount >= numOpenNetworksKept) {
					modified = true;
					wifiMgr.removeNetwork(config.networkId);
				}
			}
		}
		if(modified) {
			return wifiMgr.saveConfiguration();
		}

		return true;
	}

	private static final int MAX_PRIORITY = 99999;

	private static int shiftPriorityAndSave(final WifiManager wifiMgr) {
		final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
		sortByPriority(configurations);
		final int size = configurations.size();
		for(int i = 0; i < size; i++) {
			final WifiConfiguration config = configurations.get(i);
			config.priority = i;
			wifiMgr.updateNetwork(config);
		}
		wifiMgr.saveConfiguration();
		return size;
	}

	private static int getMaxPriority(final WifiManager wifiManager) {
		final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
		int pri = 0;
		for(final WifiConfiguration config : configurations) {
			if(config.priority > pri) {
				pri = config.priority;
			}
		}
		return pri;
	}

	public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr,
                                                         final ScanResult hotsopt, String hotspotSecurity) {
		final String ssid = StringUtils.convertToQuotedString(hotsopt.SSID);
		if(ssid.length() == 0) {
			return null;
		}

		final String bssid = hotsopt.BSSID;
		if(bssid == null) {
			return null;
		}

		if(hotspotSecurity == null) {
			hotspotSecurity = getScanResultSecurity(hotsopt);
		}

		final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();

		for(final WifiConfiguration config : configurations) {
			if(config.SSID == null || !ssid.equals(config.SSID)) {
				continue;
			}
			if(config.BSSID == null || bssid.equals(config.BSSID)) {
				final String configSecurity = getWifiConfigurationSecurity(config);
				if(hotspotSecurity.equals(configSecurity)) {
					return config;
				}
			}
		}
		return null;
	}

	public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr,
                                                         final WifiConfiguration configToFind, String security) {
		final String ssid = configToFind.SSID;
		if(ssid.length() == 0) {
			return null;
		}

		final String bssid = configToFind.BSSID;

		if(security == null) {
			security = getWifiConfigurationSecurity(configToFind);
		}

		final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();

		for(final WifiConfiguration config : configurations) {
			if(config.SSID == null || !ssid.equals(config.SSID)) {
				continue;
			}
			if(config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) {
				final String configSecurity = getWifiConfigurationSecurity(config);
				if(security.equals(configSecurity)) {
					return config;
				}
			}
		}
		return null;
	}

	/**
     * @return The security of a given {@link WifiConfiguration}.
     */
    static public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {

        if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) {
            // If we never set group ciphers, wpa_supplicant puts all of them.
            // For open, we don't set group ciphers.
            // For WEP, we specifically only set WEP40 and WEP104, so CCMP
            // and TKIP should not be there.
            if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP)
                    && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40)
                            || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) {
                return WEP;
            } else {
                return OPEN;
            }
        } else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) {
            return WPA2;
        } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
            return WPA_EAP;
        } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
            return IEEE8021X;
        } else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) {
            return WPA;
        } else {
            Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open.");
            return OPEN;
        }
    }

    /**
     * Fill in the security fields of WifiConfiguration config.
     * @param config The object to fill.
     * @param security If is OPEN, password is ignored.
     * @param password Password of the network if security is not OPEN.
     */
	static private void setupSecurity(WifiConfiguration config, String security, final String password) {
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        if (TextUtils.isEmpty(security)) {
            security = OPEN;
            Log.w(TAG, "Empty security, assuming open");
        }

        if (security.equals(WEP)) {
        	 int wepPasswordType = WEP_PASSWORD_AUTO;
            // If password is empty, it should be left untouched
            if (!TextUtils.isEmpty(password)) {
				if (wepPasswordType == WEP_PASSWORD_AUTO) {
                    if (isHexWepKey(password)) {
                        config.wepKeys[0] = password;
                    } else {
                        config.wepKeys[0] = StringUtils.convertToQuotedString(password);
                    }
                } else {
                    config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII
                            ? StringUtils.convertToQuotedString(password)
                            : password;
                }
            }

            config.wepTxKeyIndex = 0;

            config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);

            config.allowedKeyManagement.set(KeyMgmt.NONE);

            config.allowedGroupCiphers.set(GroupCipher.WEP40);
            config.allowedGroupCiphers.set(GroupCipher.WEP104);

        } else if (security.equals(WPA) || security.equals(WPA2)){
            config.allowedGroupCiphers.set(GroupCipher.TKIP);
            config.allowedGroupCiphers.set(GroupCipher.CCMP);

            config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);

            config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA);

            // If password is empty, it should be left untouched
            if (!TextUtils.isEmpty(password)) {
                if (password.length() == 64 && isHex(password)) {
                    // Goes unquoted as hex
                    config.preSharedKey = password;
                } else {
                    // Goes quoted as ASCII
                    config.preSharedKey = StringUtils.convertToQuotedString(password);
                }
            }

        } else if (security.equals(OPEN)) {
            config.allowedKeyManagement.set(KeyMgmt.NONE);
        } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) {
            config.allowedGroupCiphers.set(GroupCipher.TKIP);
            config.allowedGroupCiphers.set(GroupCipher.CCMP);
            if (security.equals(WPA_EAP)) {
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
            } else {
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
            }
            if (!TextUtils.isEmpty(password)) {
                config.preSharedKey = StringUtils.convertToQuotedString(password);
            }
        }
    }

	private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
                return false;
            }
        }

        return true;
    }

    static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X };

	/**
     * @return The security of a given {@link ScanResult}.
     */
    public static String getScanResultSecurity(ScanResult scanResult) {
        final String cap = scanResult.capabilities;
        for (int i = SECURITY_MODES.length - 1; i >= 0; i--) {
            if (cap.contains(SECURITY_MODES[i])) {
                return SECURITY_MODES[i];
            }
        }

        return OPEN;
    }
}


text:
package org.unitime.timetable.model.base;

import java.util.List;

import org.unitime.timetable.model.PitCourseOffering;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.model.dao.PitCourseOfferingDAO;

/**
 * Do not change this class. It has been automatically generated using ant create-model.
 * @see org.unitime.commons.ant.CreateBaseModelFromXml
 */
public abstract class BasePitCourseOfferingDAO extends _RootDAO<PitCourseOffering,Long> {

	private static PitCourseOfferingDAO sInstance;

	public static PitCourseOfferingDAO getInstance() {
		if (sInstance == null) sInstance = new PitCourseOfferingDAO();
		return sInstance;
	}

	public Class<PitCourseOffering> getReferenceClass() {
		return PitCourseOffering.class;
	}

	@SuppressWarnings("unchecked")
	public List<PitCourseOffering> findBySubjectArea(org.hibernate.Session hibSession, Long subjectAreaId) {
		return hibSession.createQuery("from PitCourseOffering x where x.subjectArea.uniqueId = :subjectAreaId").setLong("subjectAreaId", subjectAreaId).list();
	}

	@SuppressWarnings("unchecked")
	public List<PitCourseOffering> findByCourseOffering(org.hibernate.Session hibSession, Long courseOfferingId) {
		return hibSession.createQuery("from PitCourseOffering x where x.courseOffering.uniqueId = :courseOfferingId").setLong("courseOfferingId", courseOfferingId).list();
	}

	@SuppressWarnings("unchecked")
	public List<PitCourseOffering> findByPitInstructionalOffering(org.hibernate.Session hibSession, Long pitInstructionalOfferingId) {
		return hibSession.createQuery("from PitCourseOffering x where x.pitInstructionalOffering.uniqueId = :pitInstructionalOfferingId").setLong("pitInstructionalOfferingId", pitInstructionalOfferingId).list();
	}

	@SuppressWarnings("unchecked")
	public List<PitCourseOffering> findByCourseType(org.hibernate.Session hibSession, Long courseTypeId) {
		return hibSession.createQuery("from PitCourseOffering x where x.courseType.uniqueId = :courseTypeId").setLong("courseTypeId", courseTypeId).list();
	}
}


text:
import { render, screen } from "@testing-library/react";
import { GridFilter } from ".";

test("", () => {
  render(<GridFilter>foo</GridFilter>);

  const text = screen.getByText("foo");
  expect(text).toBeInTheDocument();
});

test("empty", () => {
  const {
    container: { firstChild },
  } = render(<GridFilter />);

  expect(firstChild).toBeEmptyDOMElement();
});


text:
require 'sensu-plugin/utils'
require 'sensu-plugin/check/cli'
require 'tiny_redis'
require 'socket'
require 'json'
require 'net/http'

class SensuFleetCheck < Sensu::Plugin::Check::CLI

  include Sensu::Plugin::Utils

  attr_accessor :trigger_list, :resolve_list, :extra_msgs

  def run
    begin
      do_run
    rescue => e
      ok "Exception: msg='#{e.message}' backtrace=#{e.backtrace}"
    end
  end

  def do_run
    fleet_check_init if respond_to?(:fleet_check_init)
    raise("event_name bad or missing") if event_name.nil? || event_name.empty?

    @extra_msgs = []
    @trigger_list = [ ]
    @resolve_list = [ ]
    build_event_lists
    auto_resolve_old_alerts

    trigger_list.uniq!
    resolve_list.uniq!
    trigger_list.each { |event| trigger(event) }
    resolve_list.each { |sensu_client| resolve(sensu_client) }

    msgs = []
    msgs << "triggered: #{trigger_list.map {|t| t[:sensu_client_name] }.join(',')}" if
            trigger_list.any?
    msgs << "resolved: #{resolve_list.join(',')}" if resolve_list.any?
    msgs << 'no action taken, both trigger_list and resolve_list are empty' if
            trigger_list.empty? && resolve_list.empty?
    msgs += extra_msgs if extra_msgs.any?
    ok msgs.join(' ')
  end

  def event_name
    config[:event_name] || @event_name || raise('event name is not set')
  end

  # override build_event_lists OR
  # override build_trigger_list and built_resolve_list
  def build_event_lists
    build_trigger_list
    build_resolve_list
  end

  def build_trigger_list
    warn 'Probably want to override build_trigger_list'
  end

  def build_resolve_list
    warn 'Probably want to override build_resolve_list'
  end

  def trigger(event)
    # here is the dependency on server side check
    check = settings['checks']["server_side_placeholder_for_#{event_name}"]
    new_event = { 'source' => event[:sensu_client_name],
                  'name' => event_name,
                  'status' => event[:status],
                  'output' => event[:output],
                  'handlers' => check['actual_handlers'],
                  'command' => check['actual_command'] }
    [ :dependencies, :interval, :alert_after, :realert_every,
      :runbook, :sla, :team, :irc_channels, :slack_channels, :notification_email,
      :ticket, :page, :tip, :habitat, :tags, :timeout, :standalone,
    ].each do |k|
      new_event[k.to_s] = check[k.to_s]
    end

    # take irc_channels from team data
    new_event.delete('irc_channels') if check['with_team_data_irc_channels']

    # take slack_channels from team data
    new_event.delete('slack_channels') if check['with_team_data_slack_channels']

    if check['with_keepalive_team']
      team_override = get_client_keepalive_team(event[:sensu_client_name])
      new_event['team'] = team_override if team_override
    end

    begin
      sock = TCPSocket.new('127.0.0.1', 3030)
      sock.puts(new_event.to_json)
      sock.close

      redis.rpush(redis_key, event[:sensu_client_name]) unless
        event_already_triggered?(event[:sensu_client_name])
    rescue => e
      @extra_msgs << "trigger_fail(#{event[:sensu_client_name]}): #{e.message}"
      return
    end
  end

  def resolve(sensu_client)
    # sensu docs say they will return HTTP 202 Accepted on success.
    # if client is still in sensu, resolve the event through API;
    # remove client from our key in this case only if API request was successful
    api_response = nil
    if redis.sismember('clients', sensu_client) == 1
      api_response = api_request(:Delete, "/events/#{sensu_client}/#{event_name}")
    end
    if api_response.nil? || api_response.code =~ /^20/ || api_response.code == '404'
      redis.lrem(redis_key, 1, sensu_client)
    end
  end

  def clients_with_triggered_event
    # FIXME - when we run for the first time, redis_key will not be in redis
    # and this value will end up []. An improvement over this would be
    # to go over existing "result:*:#{event_key}" keys in redis and build a list
    # of sensu clients with this event. Maybe not worth implementing this
    # for just a first run though
    @clients_with_triggered_event ||= redis.lrange(redis_key, 0, -1) || []
  end

  def event_already_triggered?(sensu_client_name)
    clients_with_triggered_event.include? sensu_client_name
  end

  def redis
    @redis ||= TinyRedis::Client.new(
      host=settings['redis']['host'],
      port=settings['redis']['port']) rescue unknown('Failed to connect to redis')
  end

  def redis_key
    "fleet_check:#{event_name}"
  end

  # based on api_request method in sensu-handler.rb but with
  # better timeout handling (see also do_api_request method)
  def api_request(method, path)
    begin
      do_api_request(method, path)
    rescue Timeout::Error
      @extra_msgs << "api_timeout(#{method},#{path})"
      nil
    end
  end

  def do_api_request(method, path)
    raise "api.json settings not found." unless settings.has_key?('api')
    open_timeout = settings['api'].fetch('open_timeout', 10),
    read_timeout = settings['api'].fetch('read_timeout', 10)
    Net::HTTP.start(settings['api']['host'], settings['api']['port'],
                    :read_timeout => read_timeout) do |http|
      http.open_timeout = open_timeout
      req = Net::HTTP.const_get(method).new(path)
      if settings['api']['user'] && settings['api']['password']
        req.basic_auth(settings['api']['user'], settings['api']['password'])
      end
      req = yield(req) if block_given?
      http.request(req)
    end
  end

  def get_client_keepalive_team(client_name)
    begin
      client_data = JSON.parse(redis.get("client:#{client_name}"))
      client_data['keepalive']['team']
    rescue
      nil
    end
  end

  # any client that appears in clients_with_triggered_event but does
  # not appear in latest trigger_list either has been shut down or
  # its event cleared; resolve events for such clients automatically
  def auto_resolve_old_alerts
    return if clients_with_triggered_event.empty?
    trigger_client_names = trigger_list.map { |e| e[:sensu_client_name] }
    clients_with_triggered_event.each do |client_name|
      resolve_list << client_name unless trigger_client_names.include?(client_name)
    end
  end

end


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>MessageHandler | justcore | API</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					justcore | API Documentation

			Interface MessageHandler

A function that subscribes for given message.

Callable

__call(message: Message): void

A function that subscribes for given message.

Parameters

message: Message

Returns void

						Core

						Core<wbr>Class

						Extension

						Func

						Hook<wbr>Props

						Message

						Message<wbr>Handler

						Module

						Module<wbr>Factory

						Module<wbr>Start<wbr>Options

						Plugins<wbr>Map

						Sandbox

						Sandbox<wbr>Class

						Unsubscribe

						Hook<wbr>Type


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <label><!-- Enrollment Status --></label>
    <name>Enrollment_Status__c</name>
    <picklistValues>
        <masterLabel>Full-time</masterLabel>
        <translation><!-- Full-time --></translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Half-time</masterLabel>
        <translation><!-- Half-time --></translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Less than half-time</masterLabel>
        <translation><!-- Less than half-time --></translation>
    </picklistValues>
</CustomFieldTranslation>


text:
module Stripe
  # StripeError is the base error from which all other more specific Stripe
  # errors derive.
  class StripeError < StandardError
    attr_reader :message

    # Response contains a StripeResponse object that has some basic information
    # about the response that conveyed the error.
    attr_accessor :response

    attr_reader :code
    attr_reader :error
    attr_reader :http_body
    attr_reader :http_headers
    attr_reader :http_status
    attr_reader :json_body # equivalent to #data
    attr_reader :request_id

    # Initializes a StripeError.
    def initialize(message = nil, http_status: nil, http_body: nil,
                   json_body: nil, http_headers: nil, code: nil)
      @message = message
      @http_status = http_status
      @http_body = http_body
      @http_headers = http_headers || {}
      @idempotent_replayed = @http_headers["idempotent-replayed"] == "true"
      @json_body = json_body
      @code = code
      @request_id = @http_headers["request-id"]
      @error = construct_error_object
    end

    def construct_error_object
      return nil if @json_body.nil? || !@json_body.key?(:error)

      ErrorObject.construct_from(@json_body[:error])
    end

    # Whether the error was the result of an idempotent replay, meaning that it
    # originally occurred on a previous request and is being replayed back
    # because the user sent the same idempotency key for this one.
    def idempotent_replayed?
      @idempotent_replayed
    end

    def to_s
      status_string = @http_status.nil? ? "" : "(Status #{@http_status}) "
      id_string = @request_id.nil? ? "" : "(Request #{@request_id}) "
      "#{status_string}#{id_string}#{@message}"
    end
  end

  # AuthenticationError is raised when invalid credentials are used to connect
  # to Stripe's servers.
  class AuthenticationError < StripeError
  end

  # APIConnectionError is raised in the event that the SDK can't connect to
  # Stripe's servers. That can be for a variety of different reasons from a
  # downed network to a bad TLS certificate.
  class APIConnectionError < StripeError
  end

  # APIError is a generic error that may be raised in cases where none of the
  # other named errors cover the problem. It could also be raised in the case
  # that a new error has been introduced in the API, but this version of the
  # Ruby SDK doesn't know how to handle it.
  class APIError < StripeError
  end

  # CardError is raised when a user enters a card that can't be charged for
  # some reason.
  class CardError < StripeError
    attr_reader :param

    def initialize(message, param, code: nil, http_status: nil, http_body: nil,
                   json_body: nil, http_headers: nil)
      super(message, http_status: http_status, http_body: http_body,
                     json_body: json_body, http_headers: http_headers,
                     code: code)
      @param = param
    end
  end

  # IdempotencyError is raised in cases where an idempotency key was used
  # improperly.
  class IdempotencyError < StripeError
  end

  # InvalidRequestError is raised when a request is initiated with invalid
  # parameters.
  class InvalidRequestError < StripeError
    attr_accessor :param

    def initialize(message, param, http_status: nil, http_body: nil,
                   json_body: nil, http_headers: nil, code: nil)
      super(message, http_status: http_status, http_body: http_body,
                     json_body: json_body, http_headers: http_headers,
                     code: code)
      @param = param
    end
  end

  # PermissionError is raised in cases where access was attempted on a resource
  # that wasn't allowed.
  class PermissionError < StripeError
  end

  # RateLimitError is raised in cases where an account is putting too much load
  # on Stripe's API servers (usually by performing too many requests). Please
  # back off on request rate.
  class RateLimitError < StripeError
  end

  # SignatureVerificationError is raised when the signature verification for a
  # webhook fails
  class SignatureVerificationError < StripeError
    attr_accessor :sig_header

    def initialize(message, sig_header, http_body: nil)
      super(message, http_body: http_body)
      @sig_header = sig_header
    end
  end

  module OAuth
    # OAuthError is raised when the OAuth API returns an error.
    class OAuthError < StripeError
      def initialize(code, description, http_status: nil, http_body: nil,
                     json_body: nil, http_headers: nil)
        super(description, http_status: http_status, http_body: http_body,
                           json_body: json_body, http_headers: http_headers,
                           code: code)
      end

      def construct_error_object
        return nil if @json_body.nil?

        OAuthErrorObject.construct_from(@json_body)
      end
    end

    # InvalidClientError is raised when the client doesn't belong to you, or
    # the API key mode (live or test) doesn't match the client mode. Or the
    # stripe_user_id doesn't exist or isn't connected to your application.
    class InvalidClientError < OAuthError
    end

    # InvalidGrantError is raised when a specified code doesn't exist, is
    # expired, has been used, or doesn't belong to you; a refresh token doesn't
    # exist, or doesn't belong to you; or if an API key's mode (live or test)
    # doesn't match the mode of a code or refresh token.
    class InvalidGrantError < OAuthError
    end

    # InvalidRequestError is raised when a code, refresh token, or grant type
    # parameter is not provided, but was required.
    class InvalidRequestError < OAuthError
    end

    # InvalidScopeError is raised when an invalid scope parameter is provided.
    class InvalidScopeError < OAuthError
    end

    # UnsupportedGrantTypeError is raised when an unuspported grant type
    # parameter is specified.
    class UnsupportedGrantTypeError < OAuthError
    end

    # UnsupportedResponseTypeError is raised when an unsupported response type
    # parameter is specified.
    class UnsupportedResponseTypeError < OAuthError
    end
  end
end


text:
{-# LANGUAGE OverloadedStrings #-}
module SiteJournal where

--------------------------------------------------------------------------------
import            Author
-- import            Page

import            Control.Applicative ((<$>), (<|>), empty)
import            Control.Monad       (forM_, liftM, liftM3)
import			  Data.Char
import            Data.Function       (on)
import            Data.List           (foldl', intersperse, intercalate, sortBy,
                                       elemIndex)
import            Data.List.HT        (chop, segmentBefore)
import            Data.Map            (keys, (!))
import            Data.Maybe
import            Data.Monoid         (mappend, (<>), mconcat)
import            Data.Ord            (comparing)
import            Data.String         (fromString)
import            Hakyll
import            Paper
import qualified  Text.BibTeX.Entry   as BibTex
import            Text.Pandoc
import            Text.Regex
import            System.FilePath
import qualified Text.Regex.XMLSchema.String as RE

-- Base URI for the W&CP site
baseURI = "http://jmlr.org/proceedings/papers/"

--------------------------------------------------------------------------------
realMain :: String -> IO ()
realMain regex = hakyllWith config $ do
  let onlyVols = fromRegex regex

  -- Papers are in, e.g., @db/v26/reid12b.bib
  match ("db-scraped/*/*.bib" .&&. onlyVols) $ do
    route $
      gsubRoute "db-scraped/" (const "") `composeRoutes`
      setExtension "meta"

    compile $ do
      entryCompiler
        >>= saveSnapshot "test"
        >>= loadAndApplyTemplate "templates/scholar/paper-journal.html" entryContext
        -- >>= relativizeUrls

  -- Templates
  match "templates/scholar/*" $
    compile templateCompiler

--------------------------------------------------------------------------------
config :: Configuration
config = defaultConfiguration
  { destinationDirectory = "/tmp/jmlr/",
    storeDirectory       = "/tmp/hakyll_cache/jmlr/",
	deployCommand =
      "rsync --checksum -avz --no-group /tmp/jmlr/* "
        ++ "mreid@login.csail.mit.edu:"
        ++ "/afs/csail.mit.edu/group/jmlr/docroot/proceedings/papers/"
  }

-- Define a context for template fields using a given entry.
-- This context will look for a matching field in the Entry's BibTeX fields
-- if it is one of "title", "author", "abstract", or "pages".
-- If it is not one of these it will look up the associated conference entry
-- and look for the BibTeX field there.
entryContext :: Context Entry
entryContext =
  constField "baseURI" baseURI     -- Base URI
  <> constField "booktitle" "Journal of Machine Learning Research"
  <> listField' "authors" authorContext (return . entryNames "author")
  <> field "journalvolume" (maybe empty return . entryVolumeIssue "volume")
  <> field "journalissue" (maybe empty return . entryVolumeIssue "issue")
  <> entryContext'      -- Fields from BibTeX entry

entryVolumeIssue :: String -> Item Entry -> Maybe String
entryVolumeIssue key entry = do
  volField <- getField "volume" entry
  lookup key $ RE.matchSubex volIssueRE volField

volIssueRE = "({volume}\\d+)\\(({issue}.+)\\)"

entryNames :: String -> Item Entry -> [Item Author]
entryNames key = map (Item "") . maybe [] toAuthors . getField key

entryContext' :: Context Entry
entryContext' = Context $
  \key item -> liftM StringField (maybeGetField key item)

-- Return a Compiler String for a looked-up value or the empty Compiler
-- If the key search for is a default key then log a warning and return a
-- placeholder value if it is missing
maybeGetField :: String -> Item Entry -> Compiler String
maybeGetField key
 | key `elem` defaultKeys = maybe (defaultKeyWarning key) return . getField key
 | otherwise              = maybe empty return . getField key
  where
    defaultKeys = ["abstract", "title", "author", "pages", "year", "volume"]
    defaultKeyWarning key =
      debugCompiler ("WARNING: Could not find " ++ key)
      >> return ("[Not found: " ++ key ++ "]")

-- Compile an entry by parsing its associated BibTeX file
entryCompiler :: Compiler (Item Entry)
entryCompiler = getResourceString >>= makeItem . parseEntry . itemBody

-- Save a snapshot of the paper with snapshot name equal to its conference ID
saveEntryCompiler :: Item Entry -> Compiler (Item Entry)
saveEntryCompiler entry = saveSnapshot (entryConfPath entry) entry

-- Compute the path for the conference BibTeX file given the path for a paper
-- e.g., this takes "db/ICML/2012/reid12a.bib" to "db/ICML/2012.bib"
confPath :: FilePath -> FilePath
confPath path = takeDirectory path ++ ".bib"

entryConfPath :: Item Entry -> FilePath
entryConfPath = confPath . toFilePath . itemIdentifier

--------------------------------------------------------------------------------
-- Miscellaneous functions
-- listField' should really be part of the Hakyll library.
listField' :: String -> Context a -> (Item b -> Compiler [Item a]) -> Context b
listField' key c value = field' key $ fmap (ListField c) . value

field' :: String -> (Item a -> Compiler ContextField) -> Context a
field' key value = Context $ \k i -> if k == key then value i else empty


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Filter\Fixtures;

use Doctrine\ORM\Mapping as ORM;

use Oro\Bundle\EntityExtendBundle\Entity\AbstractEnumValue;

/**
 * @ORM\Entity()
 */
class TestEnumValue extends AbstractEnumValue
{
}


text:
'use strict';

var React = require('react');
var classnames = require('classnames');

var MainButton = React.createClass({
  getDefaultProps: function(){
    return {
      href: '#',
      onClick: function(){},
      iconResting: '',
      iconActive: '',
      label: null
    };
  },
  render: function(){
    var iconResting = classnames('mfb-component__main-icon--resting', this.props.iconResting);
    var iconActive = classnames('mfb-component__main-icon--active', this.props.iconActive);
    var mainClass = classnames('mfb-component__button--main', this.props.className);
    var children = this.props.children || [
          ,

        ];

    if(this.props.label){
      return (

          {children}

      );
    } else {
      return (

          {children}

      );
    }
  }
});

module.exports = MainButton;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item type="id" name="expandable_text"/>
    <item type="id" name="expand_collapse"/>

</resources>


text:
layout: category
section-type: category
title: content
---
## Category


text:
<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root (#PCDATA)>
<!ELEMENT a ANY>
<!--* Missing white space after 'ATTLIST' *-->
<!ATTLISTa attr1 ID #REQUIRED >
]>
<root>Any content</root>


text:
extern "C" {
#include "ring.h"
}
#include "gcolordialog.h"

GColorDialog::GColorDialog(QWidget *parent,VM *pVM)  : QColorDialog(parent)
{
	this->pVM = pVM;
	this->pParaList = ring_list_new(0);
	strcpy(this->ccolorSelectedEvent,"");
	strcpy(this->ccurrentColorChangedEvent,"");

	QObject::connect(this, SIGNAL(colorSelected(const QColor)),this, SLOT(colorSelectedSlot()));
	QObject::connect(this, SIGNAL(currentColorChanged(const QColor)),this, SLOT(currentColorChangedSlot()));

}

GColorDialog::~GColorDialog()
{
	ring_list_delete(this->pParaList);
}

void GColorDialog::geteventparameters(void)
{
	void *pPointer;
	pPointer = this->pVM;
	RING_API_RETLIST(this->pParaList);
}

void GColorDialog::setcolorSelectedEvent(const char *cStr)
{
	if ( strlen(cStr) < RINGQT_EVENT_SIZE )
		strcpy(this->ccolorSelectedEvent,cStr);
	else {
		printf("\nEvent Code: %s\n",cStr);
		ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
	}
}

void GColorDialog::setcurrentColorChangedEvent(const char *cStr)
{
	if ( strlen(cStr) < RINGQT_EVENT_SIZE )
		strcpy(this->ccurrentColorChangedEvent,cStr);
	else {
		printf("\nEvent Code: %s\n",cStr);
		ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
	}
}

const char *GColorDialog::getcolorSelectedEvent(void)
{
	return this->ccolorSelectedEvent;
}

const char *GColorDialog::getcurrentColorChangedEvent(void)
{
	return this->ccurrentColorChangedEvent;
}

void GColorDialog::colorSelectedSlot()
{
	if (strcmp(this->ccolorSelectedEvent,"")==0)
		return ;

	ring_vm_runcode(this->pVM,this->ccolorSelectedEvent);
}

void GColorDialog::currentColorChangedSlot()
{
	if (strcmp(this->ccurrentColorChangedEvent,"")==0)
		return ;

	ring_vm_runcode(this->pVM,this->ccurrentColorChangedEvent);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@android:string/yes" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@android:string/no" />

</LinearLayout>


text:
package qemu

import (
	"encoding/json"
	"fmt"
	"net"

	"github.com/google/syzkaller/pkg/log"
)

type qmpVersion struct {
	Package string
	QEMU    struct {
		Major int
		Micro int
		Minor int
	}
}

type qmpBanner struct {
	QMP struct {
		Version qmpVersion
	}
}

type qmpCommand struct {
	Execute   string      `json:"execute"`
	Arguments interface{} `json:"arguments,omitempty"`
}

type hmpCommand struct {
	Command string `json:"command-line"`
	CPU     int    `json:"cpu-index"`
}

type qmpResponse struct {
	Error struct {
		Class string
		Desc  string
	}
	Return interface{}

	Event     string
	Data      map[string]interface{}
	Timestamp struct {
		Seconds      int64
		Microseconds int64
	}
}

func (inst *instance) qmpConnCheck() error {
	if inst.mon != nil {
		return nil
	}

	addr := fmt.Sprintf("127.0.0.1:%v", inst.monport)
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		return err
	}

	monDec := json.NewDecoder(conn)
	monEnc := json.NewEncoder(conn)

	var banner qmpBanner
	if err := monDec.Decode(&banner); err != nil {
		return err
	}

	inst.monEnc = monEnc
	inst.monDec = monDec
	if _, err := inst.doQmp(&qmpCommand{Execute: "qmp_capabilities"}); err != nil {
		inst.monEnc = nil
		inst.monDec = nil
		return err
	}
	inst.mon = conn

	return nil
}

func (inst *instance) qmpRecv() (*qmpResponse, error) {
	for {
		qmp := new(qmpResponse)
		err := inst.monDec.Decode(qmp)
		if err != nil || qmp.Event == "" {
			return qmp, err
		}
		log.Logf(1, "event: %v", qmp)
	}
}

func (inst *instance) doQmp(cmd *qmpCommand) (*qmpResponse, error) {
	if err := inst.monEnc.Encode(cmd); err != nil {
		return nil, err
	}
	return inst.qmpRecv()
}

func (inst *instance) qmp(cmd *qmpCommand) (interface{}, error) {
	if err := inst.qmpConnCheck(); err != nil {
		return nil, err
	}
	resp, err := inst.doQmp(cmd)
	if err != nil {
		return nil, err
	}
	if resp.Error.Desc != "" {
		return nil, fmt.Errorf("error %v", resp.Error)
	}
	if resp.Return == nil {
		return nil, fmt.Errorf(`no "return" nor "error" in [%v]`, resp)
	}
	return resp.Return, nil
}

func (inst *instance) hmp(cmd string, cpu int) (string, error) {
	req := &qmpCommand{
		Execute: "human-monitor-command",
		Arguments: &hmpCommand{
			Command: cmd,
			CPU:     cpu,
		},
	}
	resp, err := inst.qmp(req)
	if err != nil {
		return "", err
	}
	return resp.(string), nil
}


text:
import React, { PropTypes } from 'react';

import StyledTime from './StyledTime';

import timestamp from '../../utilities/timestamp';

const Time = ({time, className}) => {
  const timeAgo = timestamp(time * 1000);

  return (
    <StyledTime className={className}>{timeAgo}</StyledTime>
  );
};

Time.propTypes = {
  time: PropTypes.number,
  className: PropTypes.string
};

export default Time;


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { clearRender, render, find, settled } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { get, set } from '@ember/object';
import { run } from '@ember/runloop';
import vega, { changeset } from 'vega';
import sinon from 'sinon';

function basicAttrTest(attr, value, template, method = attr) {
    test('expected to be set on the vega instance', async function(assert) {
        const spy = sinon.spy(vega.View.prototype, method);

        run(() => {
            set(this, attr, value);
        });

        await render(template);

        assert.ok(spy.calledWith(value), `Expected view.${method} to be executed with ${JSON.stringify(value)} param`);
    });
}

function basicChangeAttrTest(attr, oldValue, newValue, template, method = attr) {
    test('change expected to update the vega instance', async function(assert) {
        const spy = sinon.spy(vega.View.prototype, method);

        run(() => {
            set(this, attr, oldValue);
        });

        await render(template);

        assert.ok(spy.calledWith(oldValue), `Expected view.${method} to be executed with ${JSON.stringify(oldValue)} param`);

        run(() => {
            set(this, attr, newValue);
        });

        await settled();

        assert.ok(spy.calledWith(newValue), `Expected view.${method} to be executed with ${JSON.stringify(newValue)} param`);
    });
}

function basicEventTypeAttrTest(attr, value, template, method = attr) {
    test('expected to be set on the vega instance', async function(assert) {
        const spy = sinon.spy(vega.View.prototype, method);
        const keys = Object.keys(value);

        run(() => {
            set(this, attr, value);
        });

        await render(template);

        keys.forEach((key) => {
            assert.ok(spy.calledWith(key, value[key]), `Expected view.${method} invoked with event ${key} and respective handler`);
        });
    });
}

function basicEventTypeChangeAttrTest(attr, oldValue, newValue, template, addMethod, removeMethod) {
    test('change expected to update the vega instance', async function(assert) {
        const addSpy = sinon.spy(vega.View.prototype, addMethod);
        const removeSpy = sinon.spy(vega.View.prototype, removeMethod);
        const oldKeys = Object.keys(oldValue);
        const newKeys = Object.keys(newValue);

        run(() => {
            set(this, attr, oldValue);
        });

        await render(template);

        oldKeys.forEach((key) => {
            assert.ok(addSpy.calledWith(key, oldValue[key]), `Expected view.${addMethod} invoked with event ${key} and respective handler`);
        });

        run(() => {
            set(this, attr, newValue);
        });

        await settled();

        oldKeys.forEach((key) => {
            assert.ok(removeSpy.calledWith(key, oldValue[key]), `Expected view.${removeMethod} invoked with event ${key} and respective handler`);
        });

        newKeys.forEach((key) => {
            assert.ok(addSpy.calledWith(key, newValue[key]), `Expected view.${addMethod} invoked with new event ${key} and handler`);
        });
    });
}

module('Integration | Component | vega vis', function(hooks) {
    setupRenderingTest(hooks);

    set(this, 'spec', {});

    test('it renders', async function(assert) {
        await render(hbs`{{vega-vis spec=spec}}`);

        assert.equal(find('svg').textContent.trim(), '');
    });

    test('destroying nulls vis attr', async function(assert) {
        await render(hbs`{{vega-vis vis=vis spec=spec}}`);

        assert.ok(get(this, 'vis'), 'Expected vis attr to be set');

        await clearRender();

        assert.notOk(get(this, 'vis'), 'Expected vis attr to be null');
    });

    test('config attr', async function(assert) {
        const config = {
            events: {
                defaults: {
                    prevent: ['wheel']
                }
            }
        };
        set(this, 'config', config);

        await render(hbs`{{vega-vis config=config spec=spec vis=vis}}`);
        const vis = get(this, 'vis');

        assert.equal(vis._runtime.eventConfig.defaults.prevent.wheel, true, 'Expected `config` to be parsed and be merged with `spec.config`');
    });

    module('visContainer attr', function() {
        test('expected to be set on the vega instance', async function(assert) {
            const spy = sinon.spy(vega.View.prototype, 'initialize');

            await render(hbs`{{vega-vis spec=spec visContainer=element tagName=""}}`);

            const value = get(this, 'element');

            assert.ok(spy.calledWith(value), `Expected view.initialize to be executed with element passed as visContainer attribute`);
        });
    });

    module('height attr', function() {
        const template = hbs`{{vega-vis spec=spec height=height}}`;

        basicAttrTest('height', 100, template);
        basicChangeAttrTest('height', 100, 1, template);
    });

    module('width attr', function() {
        const template = hbs`{{vega-vis spec=spec width=width}}`;

        basicAttrTest('width', 100, template);
        basicChangeAttrTest('width', 100, 1, template);
    });

    module('padding attr', function() {
        const template = hbs`{{vega-vis spec=spec padding=padding}}`;

        basicAttrTest('padding', {top: 0, bottom: 0, left: 0, right: 0}, template);
        basicChangeAttrTest('padding', {top: 0, bottom: 0, left: 0, right: 0}, {top: 1, bottom: 1, left: 1, right: 1}, template);
    });

    module('background attr', function() {
        const template = hbs`{{vega-vis spec=spec background=background}}`;

        basicAttrTest('background', '#000', template);
        basicChangeAttrTest('background', '#001', '#000', template);
    });

    module('spec attr', function() {
        // test('throws when not passed to the component', async function(assert) {
        //     assert.rejects(render(hbs`{{vega-vis}}`), 'Expected to throw when `spec` is not passed to the component');
        // });
        test('expected to be set on the vega instance', async function(assert) {
            const spec = { signals: [ { name: 'foo', value: 'bar' } ]};
            run(() => {
                set(this, 'spec', spec);
            });

            await render(hbs`{{vega-vis spec=spec vis=vis}}`);
            const vis = get(this, 'vis');

            assert.equal(vis._runtime.signals.foo.value, 'bar', 'Expected `spec` to be parsed');
        });

        test('change expected to update the vega instance', async function(assert) {
            const oldSpec = {width: 1};
            const spec = {width: 2};
            let vis;
            run(() => {
                set(this, 'spec', oldSpec);
            });

            await render(hbs`{{vega-vis vis=vis spec=spec}}`);
            vis = get(this, 'vis');

            assert.equal(vis._runtime.signals.width.value, 1, 'Expect `oldSpec` to be parsed on initial render');

            run(() => {
                set(this, 'spec', spec);
            });

            await settled();
            const newVis = get(this, 'vis');

            assert.equal(newVis._runtime.signals.width.value, 2, 'Expect new `spec` to be parsed when `spec` changes');
            assert.notEqual(vis, newVis, 'Expected a new vega instance to be created');
        });
    });

    module('enableHover attr', function() {
        test('by default expected to trigger vega instance hover method', async function(assert) {
            const spy = sinon.spy(vega.View.prototype, 'hover');

            await render(hbs`{{vega-vis spec=spec}}`);

            assert.ok(spy.calledOnce, 'Expected view.hover to be called once');
        });

        test('when false expected to not trigger vega instance hover method', async function(assert) {
            const spy = sinon.spy(vega.View.prototype, 'hover');

            await render(hbs`{{vega-vis spec=spec enableHover=false}}`);

            assert.ok(spy.notCalled, 'Expected view.hover to not be called');
        });
    });

    module('rendererType attr', function() {
        const template = hbs`{{vega-vis spec=spec rendererType=rendererType}}`;

        basicAttrTest('rendererType', 'svg', template, 'renderer');
        basicChangeAttrTest('rendererType', 'svg', 'canvas', template, 'renderer');
    });

    module('logLevel attr', function() {
        const template = hbs`{{vega-vis spec=spec logLevel=logLevel}}`;

        test('expected to lookup log level and set on vega instance', async function(assert) {
            const spy = sinon.spy(vega.View.prototype, 'logLevel');

            run(() => {
                set(this, 'logLevel', 'Warn');
            });

            await render(template);

            assert.ok(spy.calledWith(vega.Warn), 'Expected view.logLevel to be executed with vega.Warn param');
        });

        test('change expected to update the vega instance with looked up log level', async function(assert) {
            const spy = sinon.spy(vega.View.prototype, 'logLevel');

            run(() => {
                set(this, 'logLevel', 'Warn');
            });

            await render(template);

            assert.ok(spy.calledWith(vega.Warn), 'Expected view.logLevel to be executed with vega.Warn param');

            run(() => {
                set(this, 'logLevel', 'None');
            });

            await settled();

            assert.ok(spy.calledWith(vega.None), 'Expected view.logLevel to be executed with vega.None param');
        });
    });

    module('events attr', function() {
        const template = hbs`{{vega-vis spec=spec events=events}}`;

        basicEventTypeAttrTest('events', {
            foo() {}
        }, template, 'addEventListener');

        basicEventTypeChangeAttrTest('events', {
            foo() {}
        }, {
            baz() {}
        }, template, 'addEventListener', 'removeEventListener');
    });

    module('signalEvents attr', function() {
        const template = hbs`{{vega-vis spec=spec signalEvents=signalEvents}}`;

        // Signals are required for signal events, otherwise a parse error will be thrown
        run(() => {
            set(this, 'spec', {
                signals: [
                    { name: 'foo', value: 0 },
                    { name: 'baz', value: 0 }
                ]
            });
        });

        basicEventTypeAttrTest('signalEvents', {
            foo() {}
        }, template, 'addSignalListener');

        basicEventTypeChangeAttrTest('signalEvents', {
            foo() {}
        }, {
            baz() {}
        }, template, 'addSignalListener', 'removeSignalListener');
    });

    module('data attr', function() {
        test('expected to be set on the vega instance', async function(assert) {
            const spy = sinon.spy();
            const changeSpy = sinon.spy(vega.View.prototype, 'change');
            const data = {
                foo: [1],
                bar: spy,
                baz: changeset().insert([2])
            };
            const matchChangeset = sinon.match.has('constructor', changeset);
            let vis;

            run(() => {
                set(this, 'spec', {
                    data: [
                        { name: 'foo' },
                        { name: 'bar' },
                        { name: 'baz' }
                    ]
                });

                set(this, 'data', data);
            });

            await render(hbs`{{vega-vis vis=vis spec=spec data=data}}`);

            vis = get(this, 'vis');

            assert.equal(vis.data('foo')[0].data, 1, 'Expected array data to be found in vega instance');
            assert.equal(vis.data('baz')[0].data, 2, 'Expected data from vega changeset to be found in vega instance');
            assert.ok(changeSpy.calledWithExactly('foo', matchChangeset), 'Expected view.change to be invoked with foo and changeset');
            assert.ok(changeSpy.calledWithExactly('baz', data.baz), 'Expected view.change to be invoked with baz and respective changeset ');
            assert.ok(spy.calledOnceWith(vis, null), 'Expected data.bar function to be invoked with vega instance and value from view.data("bar"), which is expected to be null since there is no data');
        });

        test('change expected to update the vega instance', async function(assert) {
            set(this, 'spec', {
                data: [
                    { name: 'foo', values: [1] },
                    { name: 'bar', values: [2] },
                    { name: 'baz', values: [3] }
                ]
            });
            let vis;

            await render(hbs`{{vega-vis vis=vis spec=spec data=data}}`);

            vis = get(this, 'vis');

            let fooData = vis.data('foo');
            let barData = vis.data('bar');
            let bazData = vis.data('baz');

            assert.equal(fooData.length, 1, 'Expected foo data to contain one item');
            assert.equal(fooData[0].data, 1, 'Expected foo data to match');
            assert.equal(barData.length, 1, 'Expected bar data to contain one item');
            assert.equal(barData[0].data, 2, 'Expected bar data to match');
            assert.equal(bazData.length, 1, 'Expected baz data to contain one item');
            assert.equal(bazData[0].data, 3, 'Expected baz data to match');

            run(() => {
                set(this, 'data', {
                    foo: [4],
                    bar(vis, data, change) {
                        vis.change('bar', change.remove(data));
                    },
                    baz: changeset().insert([5])
                });
            });

            await settled();

            // Updated/replaced data.
            fooData = vis.data('foo');
            barData = vis.data('bar');
            bazData = vis.data('baz');

            assert.equal(fooData.length, 1, 'Expected changed foo data to contain one item');
            assert.equal(fooData[0].data, 4, 'Expected first item in foo data to match');
            assert.equal(barData.length, 0, 'Expected changed bar data to contain zero items');
            assert.equal(bazData[0].data, 3, 'Expected first item in baz data to match');
            assert.equal(bazData[1].data, 5, 'Expected second item in baz data to match');
            assert.equal(bazData.length, 2, 'Expected changed baz data to contain two items');
        });

        test('support array of datasets', async function(assert) {
            const spec = {
                data: [
                    { name: 'foo' },
                    { name: 'bar' },
                    { name: 'baz' }
                ]
            };
            const data = [
                { name: 'foo', values: [1] },
                {
                    name: 'bar',
                    values(vis, data, change) {
                        change.insert([2]);
                        vis.change('bar', change);
                    }
                },
                { name: 'baz', values: changeset().insert([3])}
            ];

            set(this, 'spec', spec);
            set(this, 'data', data);

            await render(hbs`{{vega-vis vis=vis spec=spec data=data}}`);

            const vis = get(this, 'vis');
            const fooData = vis.data('foo');
            const barData = vis.data('bar');
            const bazData = vis.data('baz');

            assert.equal(fooData[0].data, 1, 'Expected foo array data to be set');
            assert.equal(barData[0].data, 2, 'Expected bar function to set data');
            assert.equal(bazData[0].data, 3, 'Expected baz changeset to set data');
        });
    });

    module('onNewVis method callback attr', function() {
        test('expected to be executed when a new vega instance is created', async function(assert) {
            const spy = sinon.spy();
            let vis;
            set(this, 'onNewVis', spy);

            await render(hbs`{{vega-vis vis=vis spec=spec onNewVis=onNewVis}}`);

            vis = get(this, 'vis');

            assert.ok(spy.calledOnceWith(vis), 'Expected onNewVis callback to be executed with new vega instance');
        });
    });

    module('onParseError method attr', function() {
        test('expected to be executed when there is a parse error during vega instance creation', async function(assert) {
            const spy = sinon.spy();

            set(this, 'onParseError', spy);

            await render(hbs`{{vega-vis spec=spec signalEvents=(hash foo=false) onParseError=onParseError}}`);

            assert.ok(spy.calledOnceWith(sinon.match.instanceOf(Error)), 'Expected onParseError callback to be executed with error object');
        });
    });

    // test('updateData method', async function(assert) {});
    // test('visRun method', async function(assert) {});
    // test('_invokeEventMethod method', async function(assert) {});
    // test('addEvents method', async function(assert) {});
    // test('removeEvents method', async function(assert) {});
    // test('addSignalEvents method', async function(assert) {});
    // test('removeSignalEvents method', async function(assert) {});
});


text:
<!DOCTYPE html>

{% include head.html %}

{% include nav.html %}

{{ page.title }}

{{ page.description }}

		{% include ad.html %}

Start Bootstrap

Templates

{{ page.title }}

 Live Preview

 Download

 View Source

			{% if page.alt-version %}

Alternate Versions:

				{% if page.wordpress %}

 WordPress Version

				{% endif %}
				{% if page.tumblr %}

 Tumblr Version

				{% endif %}
				{% if page.jekyll %}

 Jekyll Version

				{% endif %}

			{% endif %}
			{% if page.user-version %}

User Contributed Versions:

 For license details and support of user contributed versions, please contact the versions author.

				{% if page.user-wordpress %}

 WordPress Version

				{% endif %}
				{% if page.user-tumblr %}

 Tumblr Version

				{% endif %}
				{% if page.user-jekyll %}

 Jekyll Version

				{% endif %}
				{% if page.user-c %}

 C# Version

				{% endif %}

			{% endif %}

License & Author Details:

				{% if page.license %}{{ page.license }}{% else %}{{ site.license }}{% endif %} by {% if page.author %}{{ page.author }}{% else %}{{ site.author }}{% endif %}

				{% if page.author %} This is a user contributed theme and is not supported by Start Bootstrap.{% endif %}

Theme Comments:

			{% include disqus.html %}

			{{ content }}

Tags:

				{% for tags in page.tags %}

{{ tags }}

				{% endfor %}

Please visit our resources page for design ideas and our help page if you need assistance with this theme.

Special Hosting Offer:

Need hosting for your new website?  has plans starting at $3.95/month! Use the coupon code "bootstrap" to save 20%!

			 See Hosting Plans!

{% include footer.html %}

{% include javascript.html %}


text:
package org.example.wrapped.api;

import java.util.Iterator;

/**
 *
 * @author developer
 */
public interface DataBase {

    Iterator<Person> list();

    Iterator<Person> filterByLastName(String lastName);

    Iterator<Person> filterByFirstName(String firstName);

}